Home | History | Annotate | Download | only in src
      1 /*
      2  *
      3  *  BlueZ - Bluetooth protocol stack for Linux
      4  *
      5  *  Copyright (C) 2006-2010  Nokia Corporation
      6  *  Copyright (C) 2004-2010  Marcel Holtmann <marcel (at) holtmann.org>
      7  *
      8  *
      9  *  This program is free software; you can redistribute it and/or modify
     10  *  it under the terms of the GNU General Public License as published by
     11  *  the Free Software Foundation; either version 2 of the License, or
     12  *  (at your option) any later version.
     13  *
     14  *  This program is distributed in the hope that it will be useful,
     15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
     16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     17  *  GNU General Public License for more details.
     18  *
     19  *  You should have received a copy of the GNU General Public License
     20  *  along with this program; if not, write to the Free Software
     21  *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
     22  *
     23  */
     24 
     25 #ifdef HAVE_CONFIG_H
     26 #include <config.h>
     27 #endif
     28 
     29 #define _GNU_SOURCE
     30 #include <stdio.h>
     31 #include <errno.h>
     32 #include <unistd.h>
     33 #include <stdlib.h>
     34 #include <sys/ioctl.h>
     35 
     36 #ifdef ANDROID_EXPAND_NAME
     37 #include <cutils/properties.h>
     38 #endif
     39 
     40 #include <bluetooth/bluetooth.h>
     41 #include <bluetooth/uuid.h>
     42 #include <bluetooth/sdp.h>
     43 #include <bluetooth/sdp_lib.h>
     44 
     45 #include <glib.h>
     46 #include <dbus/dbus.h>
     47 #include <gdbus.h>
     48 
     49 #include "log.h"
     50 #include "textfile.h"
     51 
     52 #include "hcid.h"
     53 #include "sdpd.h"
     54 #include "adapter.h"
     55 #include "manager.h"
     56 #include "device.h"
     57 #include "dbus-common.h"
     58 #include "event.h"
     59 #include "error.h"
     60 #include "glib-helper.h"
     61 #include "agent.h"
     62 #include "storage.h"
     63 #include "attrib-server.h"
     64 #include "att.h"
     65 #include "eir.h"
     66 
     67 /* Flags Descriptions */
     68 #define EIR_LIM_DISC                0x01 /* LE Limited Discoverable Mode */
     69 #define EIR_GEN_DISC                0x02 /* LE General Discoverable Mode */
     70 #define EIR_BREDR_UNSUP             0x04 /* BR/EDR Not Supported */
     71 #define EIR_SIM_CONTROLLER          0x08 /* Simultaneous LE and BR/EDR to Same
     72 					    Device Capable (Controller) */
     73 #define EIR_SIM_HOST                0x10 /* Simultaneous LE and BR/EDR to Same
     74 					    Device Capable (Host) */
     75 
     76 #define IO_CAPABILITY_DISPLAYONLY	0x00
     77 #define IO_CAPABILITY_DISPLAYYESNO	0x01
     78 #define IO_CAPABILITY_KEYBOARDONLY	0x02
     79 #define IO_CAPABILITY_NOINPUTNOOUTPUT	0x03
     80 #define IO_CAPABILITY_INVALID		0xFF
     81 
     82 #define check_address(address) bachk(address)
     83 
     84 static DBusConnection *connection = NULL;
     85 static GSList *adapter_drivers = NULL;
     86 
     87 static GSList *ops_candidates = NULL;
     88 
     89 const struct btd_adapter_ops *adapter_ops = NULL;
     90 
     91 struct session_req {
     92 	struct btd_adapter	*adapter;
     93 	DBusConnection		*conn;		/* Connection reference */
     94 	DBusMessage		*msg;		/* Unreplied message ref */
     95 	char			*owner;		/* Bus name of the owner */
     96 	guint			id;		/* Listener id */
     97 	uint8_t			mode;		/* Requested mode */
     98 	int			refcount;	/* Session refcount */
     99 	gboolean		got_reply;	/* Agent reply received */
    100 };
    101 
    102 struct service_auth {
    103 	service_auth_cb cb;
    104 	void *user_data;
    105 	struct btd_device *device;
    106 	struct btd_adapter *adapter;
    107 };
    108 
    109 struct btd_adapter {
    110 	uint16_t dev_id;
    111 	int up;
    112 	char *path;			/* adapter object path */
    113 	bdaddr_t bdaddr;		/* adapter Bluetooth Address */
    114 	uint32_t dev_class;		/* Class of Device */
    115 	char name[MAX_NAME_LENGTH + 1]; /* adapter name */
    116 	guint discov_timeout_id;	/* discoverable timeout id */
    117 	guint stop_discov_id;		/* stop inquiry/scanning id */
    118 	uint32_t discov_timeout;	/* discoverable time(sec) */
    119 	guint pairable_timeout_id;	/* pairable timeout id */
    120 	uint32_t pairable_timeout;	/* pairable time(sec) */
    121 	uint8_t scan_mode;		/* scan mode: SCAN_DISABLED, SCAN_PAGE,
    122 					 * SCAN_INQUIRY */
    123 	uint8_t mode;			/* off, connectable, discoverable,
    124 					 * limited */
    125 	uint8_t global_mode;		/* last valid global mode */
    126 	struct session_req *pending_mode;
    127 	int state;			/* standard inq, periodic inq, name
    128 					 * resolving, suspended discovery */
    129 	GSList *found_devices;
    130 	GSList *oor_devices;		/* out of range device list */
    131 	struct agent *agent;		/* For the new API */
    132 	guint auth_idle_id;		/* Ongoing authorization */
    133 	GSList *connections;		/* Connected devices */
    134 	GSList *devices;		/* Devices structure pointers */
    135 	GSList *mode_sessions;		/* Request Mode sessions */
    136 	GSList *disc_sessions;		/* Discovery sessions */
    137 	guint scheduler_id;		/* Scheduler handle */
    138 	sdp_list_t *services;		/* Services associated to adapter */
    139 
    140 	uint8_t  features[8];
    141 
    142 	gboolean pairable;		/* pairable state */
    143 	gboolean initialized;
    144 
    145 	gboolean off_requested;		/* DEVDOWN ioctl was called */
    146 
    147 	gint ref;
    148 
    149 	GSList *powered_callbacks;
    150 
    151 	gboolean name_stored;
    152 
    153 	GSList *loaded_drivers;
    154 };
    155 
    156 static void adapter_set_pairable_timeout(struct btd_adapter *adapter,
    157 					guint interval);
    158 static DBusMessage *set_discoverable(DBusConnection *conn, DBusMessage *msg,
    159 				gboolean discoverable, void *data);
    160 
    161 static int found_device_cmp(const struct remote_dev_info *d1,
    162 			const struct remote_dev_info *d2)
    163 {
    164 	int ret;
    165 
    166 	if (bacmp(&d2->bdaddr, BDADDR_ANY)) {
    167 		ret = bacmp(&d1->bdaddr, &d2->bdaddr);
    168 		if (ret)
    169 			return ret;
    170 	}
    171 
    172 	if (d2->name_status != NAME_ANY) {
    173 		ret = (d1->name_status - d2->name_status);
    174 		if (ret)
    175 			return ret;
    176 	}
    177 
    178 	return 0;
    179 }
    180 
    181 static void dev_info_free(struct remote_dev_info *dev)
    182 {
    183 	g_free(dev->name);
    184 	g_free(dev->alias);
    185 	g_slist_foreach(dev->services, (GFunc) g_free, NULL);
    186 	g_slist_free(dev->services);
    187 	g_strfreev(dev->uuids);
    188 	g_free(dev);
    189 }
    190 
    191 /*
    192  * Device name expansion
    193  *   %d - device id
    194  */
    195 static char *expand_name(char *dst, int size, char *str, int dev_id)
    196 {
    197 	register int sp, np, olen;
    198 	char *opt, buf[10];
    199 
    200 #ifdef ANDROID_EXPAND_NAME
    201 	char value[PROPERTY_VALUE_MAX];
    202 #endif
    203 
    204 	if (!str || !dst)
    205 		return NULL;
    206 
    207 	sp = np = 0;
    208 	while (np < size - 1 && str[sp]) {
    209 		switch (str[sp]) {
    210 		case '%':
    211 			opt = NULL;
    212 
    213 			switch (str[sp+1]) {
    214 			case 'd':
    215 				sprintf(buf, "%d", dev_id);
    216 				opt = buf;
    217 				break;
    218 
    219 			case 'h':
    220 				opt = main_opts.host_name;
    221 				break;
    222 
    223 #ifdef ANDROID_EXPAND_NAME
    224 			case 'b':
    225 				property_get("ro.product.brand", value, "");
    226 				opt = value;
    227 			break;
    228 
    229 			case 'm':
    230 				property_get("ro.product.model", value, "");
    231 				opt = value;
    232 			break;
    233 
    234 			case 'n':
    235 				property_get("ro.product.name", value, "");
    236 				opt = value;
    237 			break;
    238 #endif
    239 
    240 			case '%':
    241 				dst[np++] = str[sp++];
    242 				/* fall through */
    243 			default:
    244 				sp++;
    245 				continue;
    246 			}
    247 
    248 			if (opt) {
    249 				/* substitute */
    250 				olen = strlen(opt);
    251 				if (np + olen < size - 1)
    252 					memcpy(dst + np, opt, olen);
    253 				np += olen;
    254 			}
    255 			sp += 2;
    256 			continue;
    257 
    258 		case '\\':
    259 			sp++;
    260 			/* fall through */
    261 		default:
    262 			dst[np++] = str[sp++];
    263 			break;
    264 		}
    265 	}
    266 	dst[np] = '\0';
    267 	return dst;
    268 }
    269 
    270 int btd_adapter_set_class(struct btd_adapter *adapter, uint8_t major,
    271 								uint8_t minor)
    272 {
    273 	return adapter_ops->set_dev_class(adapter->dev_id, major, minor);
    274 }
    275 
    276 static int pending_remote_name_cancel(struct btd_adapter *adapter)
    277 {
    278 	struct remote_dev_info *dev, match;
    279 	int err;
    280 
    281 	/* find the pending remote name request */
    282 	memset(&match, 0, sizeof(struct remote_dev_info));
    283 	bacpy(&match.bdaddr, BDADDR_ANY);
    284 	match.name_status = NAME_REQUESTED;
    285 
    286 	dev = adapter_search_found_devices(adapter, &match);
    287 	if (!dev) /* no pending request */
    288 		return -ENODATA;
    289 
    290 	err = adapter_ops->cancel_resolve_name(adapter->dev_id, &dev->bdaddr);
    291 	if (err < 0)
    292 		error("Remote name cancel failed: %s(%d)",
    293 						strerror(errno), errno);
    294 
    295 	adapter_set_state(adapter, STATE_IDLE);
    296 
    297 	return err;
    298 }
    299 
    300 int adapter_resolve_names(struct btd_adapter *adapter)
    301 {
    302 	struct remote_dev_info *dev, match;
    303 	int err;
    304 
    305 	/* Do not attempt to resolve more names if on suspended state */
    306 	if (adapter->state == STATE_SUSPENDED)
    307 		return 0;
    308 
    309 	memset(&match, 0, sizeof(struct remote_dev_info));
    310 	bacpy(&match.bdaddr, BDADDR_ANY);
    311 	match.name_status = NAME_REQUIRED;
    312 
    313 	dev = adapter_search_found_devices(adapter, &match);
    314 	if (!dev)
    315 		return -ENODATA;
    316 
    317 	/* send at least one request or return failed if the list is empty */
    318 	do {
    319 		/* flag to indicate the current remote name requested */
    320 		dev->name_status = NAME_REQUESTED;
    321 
    322 		err = adapter_ops->resolve_name(adapter->dev_id, &dev->bdaddr);
    323 
    324 		if (!err)
    325 			break;
    326 
    327 		error("Unable to send HCI remote name req: %s (%d)",
    328 						strerror(errno), errno);
    329 
    330 		/* if failed, request the next element */
    331 		/* remove the element from the list */
    332 		adapter_remove_found_device(adapter, &dev->bdaddr);
    333 
    334 		/* get the next element */
    335 		dev = adapter_search_found_devices(adapter, &match);
    336 	} while (dev);
    337 
    338 	return err;
    339 }
    340 
    341 static const char *mode2str(uint8_t mode)
    342 {
    343 	switch(mode) {
    344 	case MODE_OFF:
    345 		return "off";
    346 	case MODE_CONNECTABLE:
    347 		return "connectable";
    348 	case MODE_DISCOVERABLE:
    349 		return "discoverable";
    350 	default:
    351 		return "unknown";
    352 	}
    353 }
    354 
    355 static uint8_t get_mode(const bdaddr_t *bdaddr, const char *mode)
    356 {
    357 	if (strcasecmp("off", mode) == 0)
    358 		return MODE_OFF;
    359 	else if (strcasecmp("connectable", mode) == 0)
    360 		return MODE_CONNECTABLE;
    361 	else if (strcasecmp("discoverable", mode) == 0)
    362 		return MODE_DISCOVERABLE;
    363 	else if (strcasecmp("on", mode) == 0) {
    364 		char onmode[14], srcaddr[18];
    365 
    366 		ba2str(bdaddr, srcaddr);
    367 		if (read_on_mode(srcaddr, onmode, sizeof(onmode)) < 0)
    368 			return MODE_CONNECTABLE;
    369 
    370 		return get_mode(bdaddr, onmode);
    371 	} else
    372 		return MODE_UNKNOWN;
    373 }
    374 
    375 static void adapter_set_limited_discoverable(struct btd_adapter *adapter,
    376 							gboolean limited)
    377 {
    378 	DBG("%s", limited ? "TRUE" : "FALSE");
    379 
    380 	adapter_ops->set_limited_discoverable(adapter->dev_id, limited);
    381 }
    382 
    383 static void adapter_remove_discov_timeout(struct btd_adapter *adapter)
    384 {
    385 	if (!adapter)
    386 		return;
    387 
    388 	if (adapter->discov_timeout_id == 0)
    389 		return;
    390 
    391 	g_source_remove(adapter->discov_timeout_id);
    392 	adapter->discov_timeout_id = 0;
    393 }
    394 
    395 static gboolean discov_timeout_handler(gpointer user_data)
    396 {
    397 	struct btd_adapter *adapter = user_data;
    398 
    399 	adapter->discov_timeout_id = 0;
    400 
    401 	set_discoverable(NULL, NULL, FALSE, user_data);
    402 
    403 	return FALSE;
    404 }
    405 
    406 static void adapter_set_discov_timeout(struct btd_adapter *adapter,
    407 					guint interval)
    408 {
    409 	if (adapter->discov_timeout_id) {
    410 		g_source_remove(adapter->discov_timeout_id);
    411 		adapter->discov_timeout_id = 0;
    412 	}
    413 
    414 	if (interval == 0) {
    415 		adapter_set_limited_discoverable(adapter, FALSE);
    416 		return;
    417 	}
    418 
    419 	/* Set limited discoverable if pairable and interval between 0 to 60
    420 	   sec */
    421 	if (adapter->pairable && interval <= 60)
    422 		adapter_set_limited_discoverable(adapter, TRUE);
    423 	else
    424 		adapter_set_limited_discoverable(adapter, FALSE);
    425 
    426 	adapter->discov_timeout_id = g_timeout_add_seconds(interval,
    427 							discov_timeout_handler,
    428 							adapter);
    429 }
    430 
    431 static struct session_req *session_ref(struct session_req *req)
    432 {
    433 	req->refcount++;
    434 
    435 	DBG("%p: ref=%d", req, req->refcount);
    436 
    437 	return req;
    438 }
    439 
    440 static struct session_req *create_session(struct btd_adapter *adapter,
    441 					DBusConnection *conn, DBusMessage *msg,
    442 					uint8_t mode, GDBusWatchFunction cb)
    443 {
    444 	const char *sender = dbus_message_get_sender(msg);
    445 	struct session_req *req;
    446 
    447 	req = g_new0(struct session_req, 1);
    448 	req->adapter = adapter;
    449 	req->conn = dbus_connection_ref(conn);
    450 	req->msg = dbus_message_ref(msg);
    451 	req->mode = mode;
    452 
    453 	if (cb == NULL)
    454 		return session_ref(req);
    455 
    456 	req->owner = g_strdup(sender);
    457 	req->id = g_dbus_add_disconnect_watch(conn, sender, cb, req, NULL);
    458 
    459 	info("%s session %p with %s activated",
    460 		req->mode ? "Mode" : "Discovery", req, sender);
    461 
    462 	return session_ref(req);
    463 }
    464 
    465 static int adapter_set_mode(struct btd_adapter *adapter, uint8_t mode)
    466 {
    467 	int err;
    468 
    469 	if (mode == MODE_CONNECTABLE)
    470 		err = adapter_ops->set_discoverable(adapter->dev_id, FALSE);
    471 	else
    472 		err = adapter_ops->set_discoverable(adapter->dev_id, TRUE);
    473 
    474 	if (err < 0)
    475 		return err;
    476 
    477 	if (mode == MODE_CONNECTABLE)
    478 		return 0;
    479 
    480 	adapter_remove_discov_timeout(adapter);
    481 
    482 	if (adapter->discov_timeout)
    483 		adapter_set_discov_timeout(adapter, adapter->discov_timeout);
    484 
    485 	return 0;
    486 }
    487 
    488 static struct session_req *find_session_by_msg(GSList *list, const DBusMessage *msg)
    489 {
    490 	for (; list; list = list->next) {
    491 		struct session_req *req = list->data;
    492 
    493 		if (req->msg == msg)
    494 			return req;
    495 	}
    496 
    497 	return NULL;
    498 }
    499 
    500 static int set_mode(struct btd_adapter *adapter, uint8_t new_mode,
    501 			DBusMessage *msg)
    502 {
    503 	int err;
    504 	const char *modestr;
    505 
    506 	if (adapter->pending_mode != NULL)
    507 		return -EALREADY;
    508 
    509 	if (!adapter->up && new_mode != MODE_OFF) {
    510 		err = adapter_ops->set_powered(adapter->dev_id, TRUE);
    511 		if (err < 0)
    512 			return err;
    513 
    514 		goto done;
    515 	}
    516 
    517 	if (adapter->up && new_mode == MODE_OFF) {
    518 		err = adapter_ops->set_powered(adapter->dev_id, FALSE);
    519 		if (err < 0)
    520 			return err;
    521 
    522 		adapter->off_requested = TRUE;
    523 
    524 		goto done;
    525 	}
    526 
    527 	if (new_mode == adapter->mode)
    528 		return 0;
    529 
    530 	err = adapter_set_mode(adapter, new_mode);
    531 
    532 	if (err < 0)
    533 		return err;
    534 
    535 done:
    536 	modestr = mode2str(new_mode);
    537 	write_device_mode(&adapter->bdaddr, modestr);
    538 
    539 	DBG("%s", modestr);
    540 
    541 	if (msg != NULL) {
    542 		struct session_req *req;
    543 
    544 		req = find_session_by_msg(adapter->mode_sessions, msg);
    545 		if (req) {
    546 			adapter->pending_mode = req;
    547 			session_ref(req);
    548 		} else
    549 			/* Wait for mode change to reply */
    550 			adapter->pending_mode = create_session(adapter,
    551 					connection, msg, new_mode, NULL);
    552 	} else
    553 		/* Nothing to reply just write the new mode */
    554 		adapter->mode = new_mode;
    555 
    556 	return 0;
    557 }
    558 
    559 static DBusMessage *set_discoverable(DBusConnection *conn, DBusMessage *msg,
    560 				gboolean discoverable, void *data)
    561 {
    562 	struct btd_adapter *adapter = data;
    563 	uint8_t mode;
    564 	int err;
    565 
    566 	mode = discoverable ? MODE_DISCOVERABLE : MODE_CONNECTABLE;
    567 
    568 	if (mode == adapter->mode) {
    569 		adapter->global_mode = mode;
    570 		return dbus_message_new_method_return(msg);
    571 	}
    572 
    573 	err = set_mode(adapter, mode, msg);
    574 	if (err < 0)
    575 		return btd_error_failed(msg, strerror(-err));
    576 
    577 	return NULL;
    578 }
    579 
    580 static DBusMessage *set_powered(DBusConnection *conn, DBusMessage *msg,
    581 				gboolean powered, void *data)
    582 {
    583 	struct btd_adapter *adapter = data;
    584 	uint8_t mode;
    585 	int err;
    586 
    587 	if (powered) {
    588 		mode = get_mode(&adapter->bdaddr, "on");
    589 		return set_discoverable(conn, msg, mode == MODE_DISCOVERABLE,
    590 									data);
    591 	}
    592 
    593 	mode = MODE_OFF;
    594 
    595 	if (mode == adapter->mode) {
    596 		adapter->global_mode = mode;
    597 		return dbus_message_new_method_return(msg);
    598 	}
    599 
    600 	err = set_mode(adapter, mode, msg);
    601 	if (err < 0)
    602 		return btd_error_failed(msg, strerror(-err));
    603 
    604 	return NULL;
    605 }
    606 
    607 void btd_adapter_pairable_changed(struct btd_adapter *adapter,
    608 							gboolean pairable)
    609 {
    610 	adapter->pairable = pairable;
    611 
    612 	write_device_pairable(&adapter->bdaddr, pairable);
    613 
    614 	emit_property_changed(connection, adapter->path,
    615 				ADAPTER_INTERFACE, "Pairable",
    616 				DBUS_TYPE_BOOLEAN, &pairable);
    617 
    618 	if (pairable && adapter->pairable_timeout)
    619 		adapter_set_pairable_timeout(adapter,
    620 						adapter->pairable_timeout);
    621 }
    622 
    623 static DBusMessage *set_pairable(DBusConnection *conn, DBusMessage *msg,
    624 				gboolean pairable, void *data)
    625 {
    626 	struct btd_adapter *adapter = data;
    627 	int err;
    628 
    629 	if (adapter->scan_mode == SCAN_DISABLED)
    630 		return btd_error_not_ready(msg);
    631 
    632 	if (pairable == adapter->pairable)
    633 		goto done;
    634 
    635 	if (!(adapter->scan_mode & SCAN_INQUIRY))
    636 		goto store;
    637 
    638 	err = set_mode(adapter, MODE_DISCOVERABLE, NULL);
    639 	if (err < 0 && msg)
    640 		return btd_error_failed(msg, strerror(-err));
    641 
    642 store:
    643 	adapter_ops->set_pairable(adapter->dev_id, pairable);
    644 
    645 done:
    646 	return msg ? dbus_message_new_method_return(msg) : NULL;
    647 }
    648 
    649 static gboolean pairable_timeout_handler(void *data)
    650 {
    651 	set_pairable(NULL, NULL, FALSE, data);
    652 
    653 	return FALSE;
    654 }
    655 
    656 static void adapter_set_pairable_timeout(struct btd_adapter *adapter,
    657 					guint interval)
    658 {
    659 	if (adapter->pairable_timeout_id) {
    660 		g_source_remove(adapter->pairable_timeout_id);
    661 		adapter->pairable_timeout_id = 0;
    662 	}
    663 
    664 	if (interval == 0)
    665 		return;
    666 
    667 	adapter->pairable_timeout_id = g_timeout_add_seconds(interval,
    668 						pairable_timeout_handler,
    669 						adapter);
    670 }
    671 
    672 static struct session_req *find_session(GSList *list, const char *sender)
    673 {
    674 	for (; list; list = list->next) {
    675 		struct session_req *req = list->data;
    676 
    677 		if (g_str_equal(req->owner, sender))
    678 			return req;
    679 	}
    680 
    681 	return NULL;
    682 }
    683 
    684 static uint8_t get_needed_mode(struct btd_adapter *adapter, uint8_t mode)
    685 {
    686 	GSList *l;
    687 
    688 	if (adapter->global_mode > mode)
    689 		mode = adapter->global_mode;
    690 
    691 	for (l = adapter->mode_sessions; l; l = l->next) {
    692 		struct session_req *req = l->data;
    693 
    694 		if (req->mode > mode)
    695 			mode = req->mode;
    696 	}
    697 
    698 	return mode;
    699 }
    700 
    701 static GSList *remove_bredr(GSList *all)
    702 {
    703 	GSList *l, *le;
    704 
    705 	for (l = all, le = NULL; l; l = l->next) {
    706 		struct remote_dev_info *dev = l->data;
    707 		if (dev->le == FALSE) {
    708 			dev_info_free(dev);
    709 			continue;
    710 		}
    711 
    712 		le = g_slist_append(le, dev);
    713 	}
    714 
    715 	g_slist_free(all);
    716 
    717 	return le;
    718 }
    719 
    720 static void stop_discovery(struct btd_adapter *adapter)
    721 {
    722 	pending_remote_name_cancel(adapter);
    723 
    724 	adapter->found_devices = remove_bredr(adapter->found_devices);
    725 
    726 	if (adapter->oor_devices) {
    727 		g_slist_free(adapter->oor_devices);
    728 		adapter->oor_devices = NULL;
    729 	}
    730 
    731 	/* Reset if suspended, otherwise remove timer (software scheduler)
    732 	   or request inquiry to stop */
    733 	if (adapter->state == STATE_SUSPENDED) {
    734 		adapter_set_state(adapter, STATE_IDLE);
    735 		return;
    736 	}
    737 
    738 	if (adapter->scheduler_id) {
    739 		g_source_remove(adapter->scheduler_id);
    740 		adapter->scheduler_id = 0;
    741 		return;
    742 	}
    743 
    744 	adapter_ops->stop_discovery(adapter->dev_id);
    745 }
    746 
    747 static void session_remove(struct session_req *req)
    748 {
    749 	struct btd_adapter *adapter = req->adapter;
    750 
    751 	/* Ignore set_mode session */
    752 	if (req->owner == NULL)
    753 		return;
    754 
    755 	DBG("%s session %p with %s deactivated",
    756 		req->mode ? "Mode" : "Discovery", req, req->owner);
    757 
    758 	if (req->mode) {
    759 		uint8_t mode;
    760 
    761 		adapter->mode_sessions = g_slist_remove(adapter->mode_sessions,
    762 							req);
    763 
    764 		mode = get_needed_mode(adapter, adapter->global_mode);
    765 
    766 		if (mode == adapter->mode)
    767 			return;
    768 
    769 		DBG("Switching to '%s' mode", mode2str(mode));
    770 
    771 		set_mode(adapter, mode, NULL);
    772 	} else {
    773 		adapter->disc_sessions = g_slist_remove(adapter->disc_sessions,
    774 							req);
    775 
    776 		if (adapter->disc_sessions)
    777 			return;
    778 
    779 		DBG("Stopping discovery");
    780 
    781 		stop_discovery(adapter);
    782 	}
    783 }
    784 
    785 static void session_free(struct session_req *req)
    786 {
    787 	if (req->id)
    788 		g_dbus_remove_watch(req->conn, req->id);
    789 
    790 	session_remove(req);
    791 
    792 	if (req->msg) {
    793 		dbus_message_unref(req->msg);
    794 		if (!req->got_reply && req->mode && req->adapter->agent)
    795 			agent_cancel(req->adapter->agent);
    796 	}
    797 
    798 	if (req->conn)
    799 		dbus_connection_unref(req->conn);
    800 	g_free(req->owner);
    801 	g_free(req);
    802 }
    803 
    804 static void session_owner_exit(DBusConnection *conn, void *user_data)
    805 {
    806 	struct session_req *req = user_data;
    807 
    808 	req->id = 0;
    809 
    810 	session_free(req);
    811 }
    812 
    813 static void session_unref(struct session_req *req)
    814 {
    815 	req->refcount--;
    816 
    817 	DBG("%p: ref=%d", req, req->refcount);
    818 
    819 	if (req->refcount)
    820 		return;
    821 
    822 	session_free(req);
    823 }
    824 
    825 static void confirm_mode_cb(struct agent *agent, DBusError *derr, void *data)
    826 {
    827 	struct session_req *req = data;
    828 	int err;
    829 	DBusMessage *reply;
    830 
    831 	req->got_reply = TRUE;
    832 
    833 	if (derr && dbus_error_is_set(derr)) {
    834 		reply = dbus_message_new_error(req->msg, derr->name,
    835 						derr->message);
    836 		g_dbus_send_message(req->conn, reply);
    837 		session_unref(req);
    838 		return;
    839 	}
    840 
    841 	err = set_mode(req->adapter, req->mode, req->msg);
    842 	if (err < 0)
    843 		reply = btd_error_failed(req->msg, strerror(-err));
    844 	else if (!req->adapter->pending_mode)
    845 		reply = dbus_message_new_method_return(req->msg);
    846 	else
    847 		reply = NULL;
    848 
    849 	if (reply) {
    850 		/*
    851 		 * Send reply immediately only if there was an error changing
    852 		 * mode, or change is not needed. Otherwise, reply is sent in
    853 		 * set_mode_complete.
    854 		 */
    855 		g_dbus_send_message(req->conn, reply);
    856 
    857 		dbus_message_unref(req->msg);
    858 		req->msg = NULL;
    859 	}
    860 
    861 	if (!find_session(req->adapter->mode_sessions, req->owner))
    862 		session_unref(req);
    863 }
    864 
    865 static DBusMessage *set_discoverable_timeout(DBusConnection *conn,
    866 							DBusMessage *msg,
    867 							uint32_t timeout,
    868 							void *data)
    869 {
    870 	struct btd_adapter *adapter = data;
    871 	const char *path;
    872 
    873 	if (adapter->discov_timeout == timeout && timeout == 0)
    874 		return dbus_message_new_method_return(msg);
    875 
    876 	if (adapter->scan_mode & SCAN_INQUIRY)
    877 		adapter_set_discov_timeout(adapter, timeout);
    878 
    879 	adapter->discov_timeout = timeout;
    880 
    881 	write_discoverable_timeout(&adapter->bdaddr, timeout);
    882 
    883 	path = dbus_message_get_path(msg);
    884 
    885 	emit_property_changed(conn, path,
    886 				ADAPTER_INTERFACE, "DiscoverableTimeout",
    887 				DBUS_TYPE_UINT32, &timeout);
    888 
    889 	return dbus_message_new_method_return(msg);
    890 }
    891 
    892 static DBusMessage *set_pairable_timeout(DBusConnection *conn,
    893 						DBusMessage *msg,
    894 						uint32_t timeout,
    895 						void *data)
    896 {
    897 	struct btd_adapter *adapter = data;
    898 	const char *path;
    899 
    900 	if (adapter->pairable_timeout == timeout && timeout == 0)
    901 		return dbus_message_new_method_return(msg);
    902 
    903 	if (adapter->pairable)
    904 		adapter_set_pairable_timeout(adapter, timeout);
    905 
    906 	adapter->pairable_timeout = timeout;
    907 
    908 	write_pairable_timeout(&adapter->bdaddr, timeout);
    909 
    910 	path = dbus_message_get_path(msg);
    911 
    912 	emit_property_changed(conn, path,
    913 				ADAPTER_INTERFACE, "PairableTimeout",
    914 				DBUS_TYPE_UINT32, &timeout);
    915 
    916 	return dbus_message_new_method_return(msg);
    917 }
    918 
    919 void btd_adapter_class_changed(struct btd_adapter *adapter, uint32_t new_class)
    920 {
    921 	uint8_t class[3];
    922 
    923 	class[2] = (new_class >> 16) & 0xff;
    924 	class[1] = (new_class >> 8) & 0xff;
    925 	class[0] = new_class & 0xff;
    926 
    927 	write_local_class(&adapter->bdaddr, class);
    928 
    929 	adapter->dev_class = new_class;
    930 
    931 	if (main_opts.attrib_server) {
    932 		/* Removes service class */
    933 		class[1] = class[1] & 0x1f;
    934 		attrib_gap_set(GATT_CHARAC_APPEARANCE, class, 2);
    935 	}
    936 
    937 	emit_property_changed(connection, adapter->path,
    938 				ADAPTER_INTERFACE, "Class",
    939 				DBUS_TYPE_UINT32, &new_class);
    940 }
    941 
    942 void adapter_update_local_name(struct btd_adapter *adapter, const char *name)
    943 {
    944 	if (strncmp(name, adapter->name, MAX_NAME_LENGTH) == 0)
    945 		return;
    946 
    947 	strncpy(adapter->name, name, MAX_NAME_LENGTH);
    948 
    949 	if (main_opts.attrib_server)
    950 		attrib_gap_set(GATT_CHARAC_DEVICE_NAME,
    951 			(const uint8_t *) adapter->name, strlen(adapter->name));
    952 
    953 	if (!adapter->name_stored) {
    954 		char *name_ptr = adapter->name;
    955 
    956 		write_local_name(&adapter->bdaddr, adapter->name);
    957 
    958 		if (connection)
    959 			emit_property_changed(connection, adapter->path,
    960 						ADAPTER_INTERFACE, "Name",
    961 						DBUS_TYPE_STRING, &name_ptr);
    962 	}
    963 
    964 	adapter->name_stored = FALSE;
    965 }
    966 
    967 static DBusMessage *set_name(DBusConnection *conn, DBusMessage *msg,
    968 					const char *name, void *data)
    969 {
    970 	struct btd_adapter *adapter = data;
    971 	char *name_ptr = adapter->name;
    972 
    973 	if (!g_utf8_validate(name, -1, NULL)) {
    974 		error("Name change failed: supplied name isn't valid UTF-8");
    975 		return btd_error_invalid_args(msg);
    976 	}
    977 
    978 	if (strncmp(name, adapter->name, MAX_NAME_LENGTH) == 0)
    979 		goto done;
    980 
    981 	strncpy(adapter->name, name, MAX_NAME_LENGTH);
    982 	write_local_name(&adapter->bdaddr, name);
    983 	emit_property_changed(connection, adapter->path,
    984 					ADAPTER_INTERFACE, "Name",
    985 					DBUS_TYPE_STRING, &name_ptr);
    986 
    987 	if (adapter->up) {
    988 		int err = adapter_ops->set_name(adapter->dev_id, name);
    989 		if (err < 0)
    990 			return btd_error_failed(msg, strerror(-err));
    991 
    992 		adapter->name_stored = TRUE;
    993 	}
    994 
    995 done:
    996 	return dbus_message_new_method_return(msg);
    997 }
    998 
    999 struct btd_device *adapter_find_device(struct btd_adapter *adapter,
   1000 							const char *dest)
   1001 {
   1002 	struct btd_device *device;
   1003 	GSList *l;
   1004 
   1005 	if (!adapter)
   1006 		return NULL;
   1007 
   1008 	l = g_slist_find_custom(adapter->devices, dest,
   1009 					(GCompareFunc) device_address_cmp);
   1010 	if (!l)
   1011 		return NULL;
   1012 
   1013 	device = l->data;
   1014 
   1015 	return device;
   1016 }
   1017 
   1018 static void adapter_update_devices(struct btd_adapter *adapter)
   1019 {
   1020 	char **devices;
   1021 	int i;
   1022 	GSList *l;
   1023 
   1024 	/* Devices */
   1025 	devices = g_new0(char *, g_slist_length(adapter->devices) + 1);
   1026 	for (i = 0, l = adapter->devices; l; l = l->next, i++) {
   1027 		struct btd_device *dev = l->data;
   1028 		devices[i] = (char *) device_get_path(dev);
   1029 	}
   1030 
   1031 	emit_array_property_changed(connection, adapter->path,
   1032 					ADAPTER_INTERFACE, "Devices",
   1033 					DBUS_TYPE_OBJECT_PATH, &devices, i);
   1034 	g_free(devices);
   1035 }
   1036 
   1037 static void adapter_emit_uuids_updated(struct btd_adapter *adapter)
   1038 {
   1039 	char **uuids;
   1040 	int i;
   1041 	sdp_list_t *list;
   1042 
   1043 	if (!adapter->initialized)
   1044 		return;
   1045 
   1046 	uuids = g_new0(char *, sdp_list_len(adapter->services) + 1);
   1047 
   1048 	for (i = 0, list = adapter->services; list; list = list->next) {
   1049 		char *uuid;
   1050 		sdp_record_t *rec = list->data;
   1051 
   1052 		uuid = bt_uuid2string(&rec->svclass);
   1053 		if (uuid)
   1054 			uuids[i++] = uuid;
   1055 	}
   1056 
   1057 	emit_array_property_changed(connection, adapter->path,
   1058 			ADAPTER_INTERFACE, "UUIDs", DBUS_TYPE_STRING, &uuids, i);
   1059 
   1060 	g_strfreev(uuids);
   1061 }
   1062 
   1063 static uint8_t get_uuid_mask(uuid_t *uuid)
   1064 {
   1065 	if (uuid->type != SDP_UUID16)
   1066 		return 0;
   1067 
   1068 	switch (uuid->value.uuid16) {
   1069 	case DIALUP_NET_SVCLASS_ID:
   1070 	case CIP_SVCLASS_ID:
   1071 		return 0x42;	/* Telephony & Networking */
   1072 	case IRMC_SYNC_SVCLASS_ID:
   1073 	case OBEX_OBJPUSH_SVCLASS_ID:
   1074 	case OBEX_FILETRANS_SVCLASS_ID:
   1075 	case IRMC_SYNC_CMD_SVCLASS_ID:
   1076 	case PBAP_PSE_SVCLASS_ID:
   1077 		return 0x10;	/* Object Transfer */
   1078 	case HEADSET_SVCLASS_ID:
   1079 	case HANDSFREE_SVCLASS_ID:
   1080 		return 0x20;	/* Audio */
   1081 	case CORDLESS_TELEPHONY_SVCLASS_ID:
   1082 	case INTERCOM_SVCLASS_ID:
   1083 	case FAX_SVCLASS_ID:
   1084 	case SAP_SVCLASS_ID:
   1085 	/*
   1086 	 * Setting the telephony bit for the handsfree audio gateway
   1087 	 * role is not required by the HFP specification, but the
   1088 	 * Nokia 616 carkit is just plain broken! It will refuse
   1089 	 * pairing without this bit set.
   1090 	 */
   1091 	case HANDSFREE_AGW_SVCLASS_ID:
   1092 		return 0x40;	/* Telephony */
   1093 	case AUDIO_SOURCE_SVCLASS_ID:
   1094 	case VIDEO_SOURCE_SVCLASS_ID:
   1095 		return 0x08;	/* Capturing */
   1096 	case AUDIO_SINK_SVCLASS_ID:
   1097 	case VIDEO_SINK_SVCLASS_ID:
   1098 		return 0x04;	/* Rendering */
   1099 	case PANU_SVCLASS_ID:
   1100 	case NAP_SVCLASS_ID:
   1101 	case GN_SVCLASS_ID:
   1102 		return 0x02;	/* Networking */
   1103 	default:
   1104 		return 0;
   1105 	}
   1106 }
   1107 
   1108 static int uuid_cmp(const void *a, const void *b)
   1109 {
   1110 	const sdp_record_t *rec = a;
   1111 	const uuid_t *uuid = b;
   1112 
   1113 	return sdp_uuid_cmp(&rec->svclass, uuid);
   1114 }
   1115 
   1116 void adapter_service_insert(struct btd_adapter *adapter, void *r)
   1117 {
   1118 	sdp_record_t *rec = r;
   1119 	gboolean new_uuid;
   1120 
   1121 	if (sdp_list_find(adapter->services, &rec->svclass, uuid_cmp) == NULL)
   1122 		new_uuid = TRUE;
   1123 	else
   1124 		new_uuid = FALSE;
   1125 
   1126 	adapter->services = sdp_list_insert_sorted(adapter->services, rec,
   1127 								record_sort);
   1128 
   1129 	if (new_uuid) {
   1130 		uint8_t svc_hint = get_uuid_mask(&rec->svclass);
   1131 		adapter_ops->add_uuid(adapter->dev_id, &rec->svclass, svc_hint);
   1132 	}
   1133 
   1134 	adapter_emit_uuids_updated(adapter);
   1135 }
   1136 
   1137 void adapter_service_remove(struct btd_adapter *adapter, void *r)
   1138 {
   1139 	sdp_record_t *rec = r;
   1140 
   1141 	adapter->services = sdp_list_remove(adapter->services, rec);
   1142 
   1143 	if (sdp_list_find(adapter->services, &rec->svclass, uuid_cmp) == NULL)
   1144 		adapter_ops->remove_uuid(adapter->dev_id, &rec->svclass);
   1145 
   1146 	adapter_emit_uuids_updated(adapter);
   1147 }
   1148 
   1149 static struct btd_device *adapter_create_device(DBusConnection *conn,
   1150 						struct btd_adapter *adapter,
   1151 						const char *address,
   1152 						device_type_t type)
   1153 {
   1154 	struct btd_device *device;
   1155 	const char *path;
   1156 
   1157 	DBG("%s", address);
   1158 
   1159 	device = device_create(conn, adapter, address, type);
   1160 	if (!device)
   1161 		return NULL;
   1162 
   1163 	device_set_temporary(device, TRUE);
   1164 
   1165 	adapter->devices = g_slist_append(adapter->devices, device);
   1166 
   1167 	path = device_get_path(device);
   1168 	g_dbus_emit_signal(conn, adapter->path,
   1169 			ADAPTER_INTERFACE, "DeviceCreated",
   1170 			DBUS_TYPE_OBJECT_PATH, &path,
   1171 			DBUS_TYPE_INVALID);
   1172 
   1173 	adapter_update_devices(adapter);
   1174 
   1175 	return device;
   1176 }
   1177 
   1178 void adapter_remove_device(DBusConnection *conn, struct btd_adapter *adapter,
   1179 						struct btd_device *device,
   1180 						gboolean remove_storage)
   1181 {
   1182 	const gchar *dev_path = device_get_path(device);
   1183 	struct agent *agent;
   1184 
   1185 	adapter->devices = g_slist_remove(adapter->devices, device);
   1186 	adapter->connections = g_slist_remove(adapter->connections, device);
   1187 
   1188 	adapter_update_devices(adapter);
   1189 
   1190 	g_dbus_emit_signal(conn, adapter->path,
   1191 			ADAPTER_INTERFACE, "DeviceRemoved",
   1192 			DBUS_TYPE_OBJECT_PATH, &dev_path,
   1193 			DBUS_TYPE_INVALID);
   1194 
   1195 	agent = device_get_agent(device);
   1196 
   1197 	if (agent && device_is_authorizing(device))
   1198 		agent_cancel(agent);
   1199 
   1200 	device_remove(device, remove_storage);
   1201 }
   1202 
   1203 struct btd_device *adapter_get_device(DBusConnection *conn,
   1204 						struct btd_adapter *adapter,
   1205 						const gchar *address)
   1206 {
   1207 	struct btd_device *device;
   1208 
   1209 	DBG("%s", address);
   1210 
   1211 	if (!adapter)
   1212 		return NULL;
   1213 
   1214 	device = adapter_find_device(adapter, address);
   1215 	if (device)
   1216 		return device;
   1217 
   1218 	return adapter_create_device(conn, adapter, address,
   1219 						DEVICE_TYPE_BREDR);
   1220 }
   1221 
   1222 static int start_discovery(struct btd_adapter *adapter)
   1223 {
   1224 	/* Do not start if suspended */
   1225 	if (adapter->state == STATE_SUSPENDED)
   1226 		return 0;
   1227 
   1228 	/* Postpone discovery if still resolving names */
   1229 	if (adapter->state == STATE_RESOLVNAME)
   1230 		return -EINPROGRESS;
   1231 
   1232 	pending_remote_name_cancel(adapter);
   1233 
   1234 	return adapter_ops->start_discovery(adapter->dev_id);
   1235 }
   1236 
   1237 static gboolean discovery_cb(gpointer user_data)
   1238 {
   1239 	struct btd_adapter *adapter = user_data;
   1240 	int err;
   1241 
   1242 	err = start_discovery(adapter);
   1243 	if (err == -EINPROGRESS)
   1244 		return TRUE;
   1245 	else if (err < 0)
   1246 		error("start_discovery: %s (%d)", strerror(-err), -err);
   1247 
   1248 	return FALSE;
   1249 }
   1250 
   1251 static DBusMessage *adapter_start_discovery(DBusConnection *conn,
   1252 						DBusMessage *msg, void *data)
   1253 {
   1254 	struct session_req *req;
   1255 	struct btd_adapter *adapter = data;
   1256 	const char *sender = dbus_message_get_sender(msg);
   1257 	int err;
   1258 
   1259 	if (!adapter->up)
   1260 		return btd_error_not_ready(msg);
   1261 
   1262 	req = find_session(adapter->disc_sessions, sender);
   1263 	if (req) {
   1264 		session_ref(req);
   1265 		return dbus_message_new_method_return(msg);
   1266 	}
   1267 
   1268 	if (adapter->disc_sessions)
   1269 		goto done;
   1270 
   1271 	g_slist_foreach(adapter->found_devices, (GFunc) dev_info_free, NULL);
   1272 	g_slist_free(adapter->found_devices);
   1273 	adapter->found_devices = NULL;
   1274 
   1275 	g_slist_free(adapter->oor_devices);
   1276 	adapter->oor_devices = NULL;
   1277 
   1278 	err = start_discovery(adapter);
   1279 	if (err < 0 && err != -EINPROGRESS)
   1280 		return btd_error_failed(msg, strerror(-err));
   1281 
   1282 done:
   1283 	req = create_session(adapter, conn, msg, 0,
   1284 				session_owner_exit);
   1285 
   1286 	adapter->disc_sessions = g_slist_append(adapter->disc_sessions, req);
   1287 
   1288 	return dbus_message_new_method_return(msg);
   1289 }
   1290 
   1291 static DBusMessage *adapter_stop_discovery(DBusConnection *conn,
   1292 						DBusMessage *msg, void *data)
   1293 {
   1294 	struct btd_adapter *adapter = data;
   1295 	struct session_req *req;
   1296 	const char *sender = dbus_message_get_sender(msg);
   1297 
   1298 	if (!adapter->up)
   1299 		return btd_error_not_ready(msg);
   1300 
   1301 	req = find_session(adapter->disc_sessions, sender);
   1302 	if (!req)
   1303 		return btd_error_failed(msg, "Invalid discovery session");
   1304 
   1305 	session_unref(req);
   1306 	info("Stopping discovery");
   1307 	return dbus_message_new_method_return(msg);
   1308 }
   1309 
   1310 static DBusMessage *get_properties(DBusConnection *conn,
   1311 					DBusMessage *msg, void *data)
   1312 {
   1313 	struct btd_adapter *adapter = data;
   1314 	const char *property;
   1315 	DBusMessage *reply;
   1316 	DBusMessageIter iter;
   1317 	DBusMessageIter dict;
   1318 	char str[MAX_NAME_LENGTH + 1], srcaddr[18];
   1319 	gboolean value;
   1320 	char **devices, **uuids;
   1321 	int i;
   1322 	GSList *l;
   1323 	sdp_list_t *list;
   1324 
   1325 	ba2str(&adapter->bdaddr, srcaddr);
   1326 
   1327 	if (check_address(srcaddr) < 0)
   1328 		return btd_error_invalid_args(msg);
   1329 
   1330 	reply = dbus_message_new_method_return(msg);
   1331 	if (!reply)
   1332 		return NULL;
   1333 
   1334 	dbus_message_iter_init_append(reply, &iter);
   1335 
   1336 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
   1337 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
   1338 			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
   1339 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
   1340 
   1341 	/* Address */
   1342 	property = srcaddr;
   1343 	dict_append_entry(&dict, "Address", DBUS_TYPE_STRING, &property);
   1344 
   1345 	/* Name */
   1346 	memset(str, 0, sizeof(str));
   1347 	strncpy(str, (char *) adapter->name, MAX_NAME_LENGTH);
   1348 	property = str;
   1349 
   1350 	dict_append_entry(&dict, "Name", DBUS_TYPE_STRING, &property);
   1351 
   1352 	/* Class */
   1353 	dict_append_entry(&dict, "Class",
   1354 				DBUS_TYPE_UINT32, &adapter->dev_class);
   1355 
   1356 	/* Powered */
   1357 	value = (adapter->up && !adapter->off_requested) ? TRUE : FALSE;
   1358 	dict_append_entry(&dict, "Powered", DBUS_TYPE_BOOLEAN, &value);
   1359 
   1360 	/* Discoverable */
   1361 	value = adapter->scan_mode & SCAN_INQUIRY ? TRUE : FALSE;
   1362 	dict_append_entry(&dict, "Discoverable", DBUS_TYPE_BOOLEAN, &value);
   1363 
   1364 	/* Pairable */
   1365 	dict_append_entry(&dict, "Pairable", DBUS_TYPE_BOOLEAN,
   1366 				&adapter->pairable);
   1367 
   1368 	/* DiscoverableTimeout */
   1369 	dict_append_entry(&dict, "DiscoverableTimeout",
   1370 				DBUS_TYPE_UINT32, &adapter->discov_timeout);
   1371 
   1372 	/* PairableTimeout */
   1373 	dict_append_entry(&dict, "PairableTimeout",
   1374 				DBUS_TYPE_UINT32, &adapter->pairable_timeout);
   1375 
   1376 
   1377 	if (adapter->state == STATE_DISCOV)
   1378 		value = TRUE;
   1379 	else
   1380 		value = FALSE;
   1381 
   1382 	/* Discovering */
   1383 	dict_append_entry(&dict, "Discovering", DBUS_TYPE_BOOLEAN, &value);
   1384 
   1385 	/* Devices */
   1386 	devices = g_new0(char *, g_slist_length(adapter->devices) + 1);
   1387 	for (i = 0, l = adapter->devices; l; l = l->next, i++) {
   1388 		struct btd_device *dev = l->data;
   1389 		devices[i] = (char *) device_get_path(dev);
   1390 	}
   1391 	dict_append_array(&dict, "Devices", DBUS_TYPE_OBJECT_PATH,
   1392 								&devices, i);
   1393 	g_free(devices);
   1394 
   1395 	/* UUIDs */
   1396 	uuids = g_new0(char *, sdp_list_len(adapter->services) + 1);
   1397 
   1398 	for (i = 0, list = adapter->services; list; list = list->next) {
   1399 		sdp_record_t *rec = list->data;
   1400 		char *uuid;
   1401 
   1402 		uuid = bt_uuid2string(&rec->svclass);
   1403 		if (uuid)
   1404 			uuids[i++] = uuid;
   1405 	}
   1406 
   1407 	dict_append_array(&dict, "UUIDs", DBUS_TYPE_STRING, &uuids, i);
   1408 
   1409 	g_strfreev(uuids);
   1410 
   1411 	dbus_message_iter_close_container(&iter, &dict);
   1412 
   1413 	return reply;
   1414 }
   1415 
   1416 static DBusMessage *set_property(DBusConnection *conn,
   1417 					DBusMessage *msg, void *data)
   1418 {
   1419 	struct btd_adapter *adapter = data;
   1420 	DBusMessageIter iter;
   1421 	DBusMessageIter sub;
   1422 	const char *property;
   1423 	char srcaddr[18];
   1424 
   1425 	ba2str(&adapter->bdaddr, srcaddr);
   1426 
   1427 	if (!dbus_message_iter_init(msg, &iter))
   1428 		return btd_error_invalid_args(msg);
   1429 
   1430 	if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
   1431 		return btd_error_invalid_args(msg);
   1432 
   1433 	dbus_message_iter_get_basic(&iter, &property);
   1434 	dbus_message_iter_next(&iter);
   1435 
   1436 	if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
   1437 		return btd_error_invalid_args(msg);
   1438 	dbus_message_iter_recurse(&iter, &sub);
   1439 
   1440 	if (g_str_equal("Name", property)) {
   1441 		const char *name;
   1442 
   1443 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)
   1444 			return btd_error_invalid_args(msg);
   1445 		dbus_message_iter_get_basic(&sub, &name);
   1446 
   1447 		return set_name(conn, msg, name, data);
   1448 	} else if (g_str_equal("Powered", property)) {
   1449 		gboolean powered;
   1450 
   1451 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
   1452 			return btd_error_invalid_args(msg);
   1453 
   1454 		dbus_message_iter_get_basic(&sub, &powered);
   1455 
   1456 		return set_powered(conn, msg, powered, data);
   1457 	} else if (g_str_equal("Discoverable", property)) {
   1458 		gboolean discoverable;
   1459 
   1460 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
   1461 			return btd_error_invalid_args(msg);
   1462 
   1463 		dbus_message_iter_get_basic(&sub, &discoverable);
   1464 
   1465 		return set_discoverable(conn, msg, discoverable, data);
   1466 	} else if (g_str_equal("DiscoverableTimeout", property)) {
   1467 		uint32_t timeout;
   1468 
   1469 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)
   1470 			return btd_error_invalid_args(msg);
   1471 
   1472 		dbus_message_iter_get_basic(&sub, &timeout);
   1473 
   1474 		return set_discoverable_timeout(conn, msg, timeout, data);
   1475 	} else if (g_str_equal("Pairable", property)) {
   1476 		gboolean pairable;
   1477 
   1478 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
   1479 			return btd_error_invalid_args(msg);
   1480 
   1481 		dbus_message_iter_get_basic(&sub, &pairable);
   1482 
   1483 		return set_pairable(conn, msg, pairable, data);
   1484 	} else if (g_str_equal("PairableTimeout", property)) {
   1485 		uint32_t timeout;
   1486 
   1487 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_UINT32)
   1488 			return btd_error_invalid_args(msg);
   1489 
   1490 		dbus_message_iter_get_basic(&sub, &timeout);
   1491 
   1492 		return set_pairable_timeout(conn, msg, timeout, data);
   1493 	}
   1494 
   1495 	return btd_error_invalid_args(msg);
   1496 }
   1497 
   1498 static DBusMessage *request_session(DBusConnection *conn,
   1499 					DBusMessage *msg, void *data)
   1500 {
   1501 	struct btd_adapter *adapter = data;
   1502 	struct session_req *req;
   1503 	const char *sender = dbus_message_get_sender(msg);
   1504 	uint8_t new_mode;
   1505 	int err;
   1506 
   1507 	if (!adapter->agent)
   1508 		return btd_error_agent_not_available(msg);
   1509 
   1510 	if (!adapter->mode_sessions)
   1511 		adapter->global_mode = adapter->mode;
   1512 
   1513 	new_mode = get_mode(&adapter->bdaddr, "on");
   1514 
   1515 	req = find_session(adapter->mode_sessions, sender);
   1516 	if (req) {
   1517 		session_ref(req);
   1518 		return dbus_message_new_method_return(msg);
   1519 	} else {
   1520 		req = create_session(adapter, conn, msg, new_mode,
   1521 					session_owner_exit);
   1522 		adapter->mode_sessions = g_slist_append(adapter->mode_sessions,
   1523 							req);
   1524 	}
   1525 
   1526 	/* No need to change mode */
   1527 	if (adapter->mode >= new_mode)
   1528 		return dbus_message_new_method_return(msg);
   1529 
   1530 	err = agent_confirm_mode_change(adapter->agent, mode2str(new_mode),
   1531 					confirm_mode_cb, req, NULL);
   1532 	if (err < 0) {
   1533 		session_unref(req);
   1534 		return btd_error_failed(msg, strerror(-err));
   1535 	}
   1536 
   1537 	return NULL;
   1538 }
   1539 
   1540 static DBusMessage *release_session(DBusConnection *conn,
   1541 					DBusMessage *msg, void *data)
   1542 {
   1543 	struct btd_adapter *adapter = data;
   1544 	struct session_req *req;
   1545 	const char *sender = dbus_message_get_sender(msg);
   1546 
   1547 	req = find_session(adapter->mode_sessions, sender);
   1548 	if (!req)
   1549 		return btd_error_failed(msg, "Invalid Session");
   1550 
   1551 	session_unref(req);
   1552 
   1553 	return dbus_message_new_method_return(msg);
   1554 }
   1555 
   1556 static DBusMessage *list_devices(DBusConnection *conn,
   1557 						DBusMessage *msg, void *data)
   1558 {
   1559 	struct btd_adapter *adapter = data;
   1560 	DBusMessage *reply;
   1561 	GSList *l;
   1562 	DBusMessageIter iter;
   1563 	DBusMessageIter array_iter;
   1564 	const gchar *dev_path;
   1565 
   1566 	if (!dbus_message_has_signature(msg, DBUS_TYPE_INVALID_AS_STRING))
   1567 		return btd_error_invalid_args(msg);
   1568 
   1569 	reply = dbus_message_new_method_return(msg);
   1570 	if (!reply)
   1571 		return NULL;
   1572 
   1573 	dbus_message_iter_init_append(reply, &iter);
   1574 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
   1575 				DBUS_TYPE_OBJECT_PATH_AS_STRING, &array_iter);
   1576 
   1577 	for (l = adapter->devices; l; l = l->next) {
   1578 		struct btd_device *device = l->data;
   1579 
   1580 		dev_path = device_get_path(device);
   1581 
   1582 		dbus_message_iter_append_basic(&array_iter,
   1583 				DBUS_TYPE_OBJECT_PATH, &dev_path);
   1584 	}
   1585 
   1586 	dbus_message_iter_close_container(&iter, &array_iter);
   1587 
   1588 	return reply;
   1589 }
   1590 
   1591 static DBusMessage *cancel_device_creation(DBusConnection *conn,
   1592 						DBusMessage *msg, void *data)
   1593 {
   1594 	struct btd_adapter *adapter = data;
   1595 	const gchar *address, *sender = dbus_message_get_sender(msg);
   1596 	struct btd_device *device;
   1597 
   1598 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &address,
   1599 						DBUS_TYPE_INVALID) == FALSE)
   1600 		return btd_error_invalid_args(msg);
   1601 
   1602 	if (check_address(address) < 0)
   1603 		return btd_error_invalid_args(msg);
   1604 
   1605 	device = adapter_find_device(adapter, address);
   1606 	if (!device || !device_is_creating(device, NULL))
   1607 		return btd_error_does_not_exist(msg);
   1608 
   1609 	if (!device_is_creating(device, sender))
   1610 		return btd_error_not_authorized(msg);
   1611 
   1612 	device_set_temporary(device, TRUE);
   1613 
   1614 	if (device_is_connected(device)) {
   1615 		device_request_disconnect(device, msg);
   1616 		return NULL;
   1617 	}
   1618 
   1619 	adapter_remove_device(conn, adapter, device, TRUE);
   1620 
   1621 	return dbus_message_new_method_return(msg);
   1622 }
   1623 
   1624 static struct btd_device *create_device_internal(DBusConnection *conn,
   1625 						struct btd_adapter *adapter,
   1626 						const gchar *address, int *err)
   1627 {
   1628 	struct remote_dev_info *dev, match;
   1629 	struct btd_device *device;
   1630 	device_type_t type;
   1631 
   1632 	memset(&match, 0, sizeof(struct remote_dev_info));
   1633 	str2ba(address, &match.bdaddr);
   1634 	match.name_status = NAME_ANY;
   1635 
   1636 	dev = adapter_search_found_devices(adapter, &match);
   1637 	if (dev && dev->le)
   1638 		type = DEVICE_TYPE_LE;
   1639 	else
   1640 		type = DEVICE_TYPE_BREDR;
   1641 
   1642 	device = adapter_create_device(conn, adapter, address, type);
   1643 	if (!device && err)
   1644 		*err = -ENOMEM;
   1645 
   1646 	return device;
   1647 }
   1648 
   1649 static DBusMessage *create_device(DBusConnection *conn,
   1650 					DBusMessage *msg, void *data)
   1651 {
   1652 	struct btd_adapter *adapter = data;
   1653 	struct btd_device *device;
   1654 	const gchar *address;
   1655 	DBusMessage *reply;
   1656 	int err;
   1657 
   1658 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &address,
   1659 						DBUS_TYPE_INVALID) == FALSE)
   1660 		return btd_error_invalid_args(msg);
   1661 
   1662 	if (check_address(address) < 0)
   1663 		return btd_error_invalid_args(msg);
   1664 
   1665 	if (!adapter->up)
   1666 		return btd_error_not_ready(msg);
   1667 
   1668 	if (adapter_find_device(adapter, address))
   1669 		return btd_error_already_exists(msg);
   1670 
   1671 	DBG("%s", address);
   1672 
   1673 	device = create_device_internal(conn, adapter, address, &err);
   1674 	if (!device)
   1675 		goto failed;
   1676 
   1677 	if (device_get_type(device) != DEVICE_TYPE_LE)
   1678 		err = device_browse_sdp(device, conn, msg, NULL, FALSE);
   1679 	else
   1680 		err = device_browse_primary(device, conn, msg, FALSE);
   1681 
   1682 	if (err < 0) {
   1683 		adapter_remove_device(conn, adapter, device, TRUE);
   1684 		return btd_error_failed(msg, strerror(-err));
   1685 	}
   1686 
   1687 	return NULL;
   1688 
   1689 failed:
   1690 	if (err == -ENOTCONN) {
   1691 		/* Device is not connectable */
   1692 		const char *path = device_get_path(device);
   1693 
   1694 		reply = dbus_message_new_method_return(msg);
   1695 
   1696 		dbus_message_append_args(reply,
   1697 				DBUS_TYPE_OBJECT_PATH, &path,
   1698 				DBUS_TYPE_INVALID);
   1699 	} else
   1700 		reply = btd_error_failed(msg, strerror(-err));
   1701 
   1702 	return reply;
   1703 }
   1704 
   1705 static uint8_t parse_io_capability(const char *capability)
   1706 {
   1707 	if (g_str_equal(capability, ""))
   1708 		return IO_CAPABILITY_DISPLAYYESNO;
   1709 	if (g_str_equal(capability, "DisplayOnly"))
   1710 		return IO_CAPABILITY_DISPLAYONLY;
   1711 	if (g_str_equal(capability, "DisplayYesNo"))
   1712 		return IO_CAPABILITY_DISPLAYYESNO;
   1713 	if (g_str_equal(capability, "KeyboardOnly"))
   1714 		return IO_CAPABILITY_KEYBOARDONLY;
   1715 	if (g_str_equal(capability, "NoInputNoOutput"))
   1716 		return IO_CAPABILITY_NOINPUTNOOUTPUT;
   1717 	return IO_CAPABILITY_INVALID;
   1718 }
   1719 
   1720 static DBusMessage *create_paired_device(DBusConnection *conn,
   1721 					DBusMessage *msg, void *data)
   1722 {
   1723 	struct btd_adapter *adapter = data;
   1724 	struct btd_device *device;
   1725 	const gchar *address, *agent_path, *capability, *sender;
   1726 	uint8_t cap;
   1727 	int err;
   1728 
   1729 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &address,
   1730 					DBUS_TYPE_OBJECT_PATH, &agent_path,
   1731 					DBUS_TYPE_STRING, &capability,
   1732 					DBUS_TYPE_INVALID) == FALSE)
   1733 		return btd_error_invalid_args(msg);
   1734 
   1735 	if (check_address(address) < 0)
   1736 		return btd_error_invalid_args(msg);
   1737 
   1738 	if (!adapter->up)
   1739 		return btd_error_not_ready(msg);
   1740 
   1741 	sender = dbus_message_get_sender(msg);
   1742 	if (adapter->agent &&
   1743 			agent_matches(adapter->agent, sender, agent_path)) {
   1744 		error("Refusing adapter agent usage as device specific one");
   1745 		return btd_error_invalid_args(msg);
   1746 	}
   1747 
   1748 	cap = parse_io_capability(capability);
   1749 	if (cap == IO_CAPABILITY_INVALID)
   1750 		return btd_error_invalid_args(msg);
   1751 
   1752 	device = adapter_find_device(adapter, address);
   1753 	if (!device) {
   1754 		device = create_device_internal(conn, adapter, address, &err);
   1755 		if (!device)
   1756 			return btd_error_failed(msg, strerror(-err));
   1757 	}
   1758 
   1759 	if (device_get_type(device) != DEVICE_TYPE_LE)
   1760 		return device_create_bonding(device, conn, msg,
   1761 							agent_path, cap);
   1762 
   1763 	err = device_browse_primary(device, conn, msg, TRUE);
   1764 	if (err < 0)
   1765 		return btd_error_failed(msg, strerror(-err));
   1766 
   1767 	return NULL;
   1768 }
   1769 
   1770 static gint device_path_cmp(struct btd_device *device, const gchar *path)
   1771 {
   1772 	const gchar *dev_path = device_get_path(device);
   1773 
   1774 	return strcasecmp(dev_path, path);
   1775 }
   1776 
   1777 static DBusMessage *remove_device(DBusConnection *conn, DBusMessage *msg,
   1778 								void *data)
   1779 {
   1780 	struct btd_adapter *adapter = data;
   1781 	struct btd_device *device;
   1782 	const char *path;
   1783 	GSList *l;
   1784 
   1785 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
   1786 						DBUS_TYPE_INVALID) == FALSE)
   1787 		return btd_error_invalid_args(msg);
   1788 
   1789 	l = g_slist_find_custom(adapter->devices,
   1790 			path, (GCompareFunc) device_path_cmp);
   1791 	if (!l)
   1792 		return btd_error_does_not_exist(msg);
   1793 
   1794 	device = l->data;
   1795 
   1796 	if (device_is_temporary(device) || device_is_busy(device))
   1797 		return g_dbus_create_error(msg,
   1798 				ERROR_INTERFACE ".DoesNotExist",
   1799 				"Device creation in progress");
   1800 
   1801 	device_set_temporary(device, TRUE);
   1802 
   1803 	if (!device_is_connected(device)) {
   1804 		adapter_remove_device(conn, adapter, device, TRUE);
   1805 		return dbus_message_new_method_return(msg);
   1806 	}
   1807 
   1808 	device_request_disconnect(device, msg);
   1809 	return NULL;
   1810 }
   1811 
   1812 static DBusMessage *find_device(DBusConnection *conn, DBusMessage *msg,
   1813 								void *data)
   1814 {
   1815 	struct btd_adapter *adapter = data;
   1816 	struct btd_device *device;
   1817 	DBusMessage *reply;
   1818 	const gchar *address;
   1819 	GSList *l;
   1820 	const gchar *dev_path;
   1821 
   1822 	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &address,
   1823 						DBUS_TYPE_INVALID))
   1824 		return btd_error_invalid_args(msg);
   1825 
   1826 	l = g_slist_find_custom(adapter->devices,
   1827 			address, (GCompareFunc) device_address_cmp);
   1828 	if (!l)
   1829 		return btd_error_does_not_exist(msg);
   1830 
   1831 	device = l->data;
   1832 
   1833 	reply = dbus_message_new_method_return(msg);
   1834 	if (!reply)
   1835 		return NULL;
   1836 
   1837 	dev_path = device_get_path(device);
   1838 
   1839 	dbus_message_append_args(reply,
   1840 				DBUS_TYPE_OBJECT_PATH, &dev_path,
   1841 				DBUS_TYPE_INVALID);
   1842 
   1843 	return reply;
   1844 }
   1845 
   1846 static void agent_removed(struct agent *agent, struct btd_adapter *adapter)
   1847 {
   1848 	adapter_ops->set_io_capability(adapter->dev_id,
   1849 					IO_CAPABILITY_NOINPUTNOOUTPUT);
   1850 
   1851 	adapter->agent = NULL;
   1852 }
   1853 
   1854 static DBusMessage *register_agent(DBusConnection *conn, DBusMessage *msg,
   1855 								void *data)
   1856 {
   1857 	const char *path, *name, *capability;
   1858 	struct agent *agent;
   1859 	struct btd_adapter *adapter = data;
   1860 	uint8_t cap;
   1861 
   1862 	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
   1863 			DBUS_TYPE_STRING, &capability, DBUS_TYPE_INVALID))
   1864 		return NULL;
   1865 
   1866 	if (adapter->agent)
   1867 		return btd_error_already_exists(msg);
   1868 
   1869 	cap = parse_io_capability(capability);
   1870 	if (cap == IO_CAPABILITY_INVALID)
   1871 		return btd_error_invalid_args(msg);
   1872 
   1873 	name = dbus_message_get_sender(msg);
   1874 
   1875 	agent = agent_create(adapter, name, path, cap,
   1876 				(agent_remove_cb) agent_removed, adapter);
   1877 	if (!agent)
   1878 		return btd_error_failed(msg, "Failed to create a new agent");
   1879 
   1880 	adapter->agent = agent;
   1881 
   1882 	DBG("Agent registered for hci%d at %s:%s", adapter->dev_id, name,
   1883 			path);
   1884 
   1885 	adapter_ops->set_io_capability(adapter->dev_id, cap);
   1886 
   1887 	return dbus_message_new_method_return(msg);
   1888 }
   1889 
   1890 static DBusMessage *unregister_agent(DBusConnection *conn, DBusMessage *msg,
   1891 								void *data)
   1892 {
   1893 	const char *path, *name;
   1894 	struct btd_adapter *adapter = data;
   1895 
   1896 	if (!dbus_message_get_args(msg, NULL, DBUS_TYPE_OBJECT_PATH, &path,
   1897 						DBUS_TYPE_INVALID))
   1898 		return NULL;
   1899 
   1900 	name = dbus_message_get_sender(msg);
   1901 
   1902 	if (!adapter->agent || !agent_matches(adapter->agent, name, path))
   1903 		return btd_error_does_not_exist(msg);
   1904 
   1905 	agent_free(adapter->agent);
   1906 	adapter->agent = NULL;
   1907 
   1908 	return dbus_message_new_method_return(msg);
   1909 }
   1910 
   1911 static sdp_record_t *create_rfcomm_record(struct btd_adapter *adapter,
   1912 					const char *name, uuid_t uuid, uint8_t channel)
   1913 {
   1914 	uuid_t root_uuid, l2cap_uuid, rfcomm_uuid;
   1915 	sdp_list_t *svclass, *root, *proto;
   1916 	sdp_record_t *record;
   1917 
   1918 	record = sdp_record_alloc();
   1919 	if (!record)
   1920 		return NULL;
   1921 
   1922 	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
   1923 	root = sdp_list_append(NULL, &root_uuid);
   1924 	sdp_set_browse_groups(record, root);
   1925 
   1926 	sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
   1927 	proto = sdp_list_append(NULL, sdp_list_append(NULL, &l2cap_uuid));
   1928 
   1929 	sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
   1930 	proto = sdp_list_append(proto, sdp_list_append(
   1931 			sdp_list_append(NULL, &rfcomm_uuid),
   1932 			sdp_data_alloc(SDP_UINT8, &channel)));
   1933 
   1934 	sdp_set_access_protos(record, sdp_list_append(NULL, proto));
   1935 
   1936 	svclass = sdp_list_append(NULL, &uuid);
   1937 	sdp_set_service_classes(record, svclass);
   1938 
   1939 	sdp_set_info_attr(record, name, NULL, NULL);
   1940 
   1941 	return record;
   1942 }
   1943 
   1944 static DBusMessage *add_rfcomm_service_record(DBusConnection *conn,
   1945 					DBusMessage *msg, void *data)
   1946 {
   1947 	uuid_t uuid;
   1948 	const char *name;
   1949 	uint8_t channel;
   1950 	uint32_t *uuid_p;
   1951 	uint32_t uuid_net[4];   // network order
   1952 	uint64_t uuid_host[2];  // host
   1953 	sdp_record_t *record;
   1954 	struct btd_adapter *adapter = data;
   1955 
   1956 	DBusMessage *reply;
   1957 
   1958 	if (!dbus_message_get_args(msg, NULL,
   1959 			DBUS_TYPE_STRING, &name,
   1960 			DBUS_TYPE_UINT64, &uuid_host[0],
   1961 			DBUS_TYPE_UINT64, &uuid_host[1],
   1962 			DBUS_TYPE_UINT16, &channel,
   1963 			DBUS_TYPE_INVALID))
   1964 		return btd_error_invalid_args(msg);
   1965 
   1966 	uuid_p = (uint32_t *)uuid_host;
   1967 	uuid_net[1] = htonl(*uuid_p++);
   1968 	uuid_net[0] = htonl(*uuid_p++);
   1969 	uuid_net[3] = htonl(*uuid_p++);
   1970 	uuid_net[2] = htonl(*uuid_p++);
   1971 
   1972 	sdp_uuid128_create(&uuid, (void *)uuid_net);
   1973 
   1974 	record = create_rfcomm_record(adapter, name, uuid, channel);
   1975 
   1976 	if (!record)
   1977 		return g_dbus_create_error(msg,
   1978 				ERROR_INTERFACE ".Failed",
   1979 				"Failed to create sdp record");
   1980 
   1981 	if (add_record_to_server(&adapter->bdaddr, record))
   1982 		return g_dbus_create_error(msg,
   1983 				ERROR_INTERFACE ".Failed",
   1984 				"Failed to register sdp record");
   1985 
   1986 	reply = dbus_message_new_method_return(msg);
   1987 	dbus_message_append_args(reply,
   1988 			DBUS_TYPE_UINT32, &record->handle,
   1989 			DBUS_TYPE_INVALID);
   1990 
   1991 	return reply;
   1992 }
   1993 
   1994 static DBusMessage *remove_service_record(DBusConnection *conn,
   1995 					DBusMessage *msg, void *data)
   1996 {
   1997 	struct btd_adapter *adapter = data;
   1998 	dbus_uint32_t handle;
   1999 
   2000 	if (!dbus_message_get_args(msg, NULL,
   2001 			DBUS_TYPE_UINT32, &handle,
   2002 			DBUS_TYPE_INVALID))
   2003 		return btd_error_invalid_args(msg);
   2004 
   2005 	if (remove_record_from_server(handle))
   2006 		return g_dbus_create_error(msg,
   2007 				ERROR_INTERFACE ".Failed",
   2008 				"Failed to remove sdp record");
   2009 
   2010 	return dbus_message_new_method_return(msg);
   2011 }
   2012 
   2013 static int add_headset_ag_record(struct btd_adapter* adapter)
   2014 {
   2015 	sdp_list_t *svclass_id, *pfseq, *apseq, *root;
   2016 	uuid_t root_uuid, svclass_uuid, ga_svclass_uuid, l2cap_uuid, rfcomm_uuid;
   2017 	sdp_profile_desc_t profile;
   2018 	sdp_list_t *aproto, *proto[2];
   2019 	sdp_record_t *record;
   2020 	uint8_t u8 = 11;
   2021 	sdp_data_t *channel;
   2022 	uint8_t netid = 0x01; // ???? profile document
   2023 	sdp_data_t *network = sdp_data_alloc(SDP_UINT8, &netid);
   2024 	int ret = 0;
   2025 
   2026 	record = sdp_record_alloc();
   2027 	if (!record) return -1;
   2028 
   2029 	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
   2030 	root = sdp_list_append(0, &root_uuid);
   2031 	sdp_set_browse_groups(record, root);
   2032 
   2033 	sdp_uuid16_create(&svclass_uuid, HEADSET_AGW_SVCLASS_ID);
   2034 	svclass_id = sdp_list_append(0, &svclass_uuid);
   2035 	sdp_uuid16_create(&ga_svclass_uuid, GENERIC_AUDIO_SVCLASS_ID);
   2036 	svclass_id = sdp_list_append(svclass_id, &ga_svclass_uuid);
   2037 	sdp_set_service_classes(record, svclass_id);
   2038 
   2039 	sdp_uuid16_create(&profile.uuid, HEADSET_PROFILE_ID);
   2040 	profile.version = 0x0100;
   2041 	pfseq = sdp_list_append(0, &profile);
   2042 	sdp_set_profile_descs(record, pfseq);
   2043 
   2044 	sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
   2045 	proto[0] = sdp_list_append(0, &l2cap_uuid);
   2046 	apseq = sdp_list_append(0, proto[0]);
   2047 
   2048 	sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
   2049 	proto[1] = sdp_list_append(0, &rfcomm_uuid);
   2050 	channel = sdp_data_alloc(SDP_UINT8, &u8);
   2051 	proto[1] = sdp_list_append(proto[1], channel);
   2052 	apseq = sdp_list_append(apseq, proto[1]);
   2053 
   2054 	aproto = sdp_list_append(0, apseq);
   2055 	sdp_set_access_protos(record, aproto);
   2056 
   2057 	sdp_set_info_attr(record, "Voice Gateway", 0, 0);
   2058 
   2059 	if (add_record_to_server(&adapter->bdaddr, record) < 0)
   2060 		ret = -1;
   2061 
   2062 	sdp_data_free(channel);
   2063 	sdp_list_free(proto[0], 0);
   2064 	sdp_list_free(proto[1], 0);
   2065 	sdp_list_free(apseq, 0);
   2066 	sdp_list_free(aproto, 0);
   2067 
   2068 	if (!ret)
   2069 		return record->handle;
   2070 	return ret;
   2071 }
   2072 
   2073 static int add_handsfree_ag_record(struct btd_adapter* adapter) {
   2074 	sdp_list_t *svclass_id, *pfseq, *apseq, *root;
   2075 	uuid_t root_uuid, svclass_uuid, ga_svclass_uuid, l2cap_uuid, rfcomm_uuid;
   2076 	sdp_profile_desc_t profile;
   2077 	sdp_list_t *aproto, *proto[2];
   2078 	sdp_record_t *record;
   2079 	uint8_t u8 = 10;
   2080 	uint16_t u16 = 0x17;
   2081 #ifdef ANDROID
   2082 	u16 = 0x07;
   2083 #endif
   2084 	sdp_data_t *channel, *features;
   2085 	uint8_t netid = 0x01; // ???? profile document
   2086 	sdp_data_t *network = sdp_data_alloc(SDP_UINT8, &netid);
   2087 	int ret = 0;
   2088 
   2089 	record = sdp_record_alloc();
   2090 	if (!record) return -1;
   2091 
   2092 	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
   2093 	root = sdp_list_append(0, &root_uuid);
   2094 	sdp_set_browse_groups(record, root);
   2095 
   2096 	sdp_uuid16_create(&svclass_uuid, HANDSFREE_AGW_SVCLASS_ID);
   2097 	svclass_id = sdp_list_append(0, &svclass_uuid);
   2098 	sdp_uuid16_create(&ga_svclass_uuid, GENERIC_AUDIO_SVCLASS_ID);
   2099 	svclass_id = sdp_list_append(svclass_id, &ga_svclass_uuid);
   2100 	sdp_set_service_classes(record, svclass_id);
   2101 
   2102 	sdp_uuid16_create(&profile.uuid, HANDSFREE_PROFILE_ID);
   2103 	profile.version = 0x0105;
   2104 	pfseq = sdp_list_append(0, &profile);
   2105 	sdp_set_profile_descs(record, pfseq);
   2106 
   2107 	sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
   2108 	proto[0] = sdp_list_append(0, &l2cap_uuid);
   2109 	apseq = sdp_list_append(0, proto[0]);
   2110 
   2111 	sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
   2112 	proto[1] = sdp_list_append(0, &rfcomm_uuid);
   2113 	channel = sdp_data_alloc(SDP_UINT8, &u8);
   2114 	proto[1] = sdp_list_append(proto[1], channel);
   2115 	apseq = sdp_list_append(apseq, proto[1]);
   2116 
   2117 	features = sdp_data_alloc(SDP_UINT16, &u16);
   2118 	sdp_attr_add(record, SDP_ATTR_SUPPORTED_FEATURES, features);
   2119 
   2120 	aproto = sdp_list_append(0, apseq);
   2121 	sdp_set_access_protos(record, aproto);
   2122 
   2123 	sdp_set_info_attr(record, "Voice Gateway", 0, 0);
   2124 
   2125 	sdp_attr_add(record, SDP_ATTR_EXTERNAL_NETWORK, network);
   2126 
   2127 	if (add_record_to_server(&adapter->bdaddr, record) < 0)
   2128 		ret = -1;
   2129 
   2130 	sdp_data_free(channel);
   2131 	sdp_list_free(proto[0], 0);
   2132 	sdp_list_free(proto[1], 0);
   2133 	sdp_list_free(apseq, 0);
   2134         sdp_list_free(aproto, 0);
   2135 
   2136 	if (!ret)
   2137 		return record->handle;
   2138 	return ret;
   2139 }
   2140 
   2141 static int add_pbap_pse_record(struct btd_adapter *adapter)
   2142 {
   2143 	sdp_list_t *svclass_id, *pfseq, *apseq, *root;
   2144 	uuid_t root_uuid, pbap_uuid, l2cap_uuid, rfcomm_uuid, obex_uuid;
   2145 	sdp_profile_desc_t profile[1];
   2146 	sdp_list_t *aproto, *proto[3];
   2147 	sdp_record_t *record;
   2148 	uint8_t u8 = 19;
   2149 	sdp_data_t *channel;
   2150 	uint8_t formats[] = {0x01};
   2151 	uint8_t dtd = SDP_UINT8;
   2152 	sdp_data_t *sflist;
   2153 	int ret = 0;
   2154 
   2155 	record = sdp_record_alloc();
   2156 	if (!record) return -1;
   2157 
   2158 	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
   2159 	root = sdp_list_append(0, &root_uuid);
   2160 	sdp_set_browse_groups(record, root);
   2161 
   2162 	sdp_uuid16_create(&pbap_uuid, PBAP_PSE_SVCLASS_ID);
   2163 	svclass_id = sdp_list_append(0, &pbap_uuid);
   2164 	sdp_set_service_classes(record, svclass_id);
   2165 
   2166 	sdp_uuid16_create(&profile[0].uuid, PBAP_PROFILE_ID);
   2167 	profile[0].version = 0x0100;
   2168 	pfseq = sdp_list_append(0, profile);
   2169 	sdp_set_profile_descs(record, pfseq);
   2170 
   2171 	sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
   2172 	proto[0] = sdp_list_append(0, &l2cap_uuid);
   2173 	apseq = sdp_list_append(0, proto[0]);
   2174 
   2175 	sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
   2176 	proto[1] = sdp_list_append(0, &rfcomm_uuid);
   2177 	channel = sdp_data_alloc(SDP_UINT8, &u8);
   2178 	proto[1] = sdp_list_append(proto[1], channel);
   2179 	apseq = sdp_list_append(apseq, proto[1]);
   2180 
   2181 	sdp_uuid16_create(&obex_uuid, OBEX_UUID);
   2182 	proto[2] = sdp_list_append(0, &obex_uuid);
   2183 	apseq = sdp_list_append(apseq, proto[2]);
   2184 
   2185 	aproto = sdp_list_append(0, apseq);
   2186 	sdp_set_access_protos(record, aproto);
   2187 
   2188 	sflist = sdp_data_alloc(dtd,formats);
   2189 	sdp_attr_add(record, SDP_ATTR_SUPPORTED_REPOSITORIES, sflist);
   2190 
   2191 	sdp_set_info_attr(record, "OBEX Phonebook Access Server", 0, 0);
   2192 
   2193 	if (add_record_to_server(&adapter->bdaddr, record) < 0)
   2194 		ret = -1;
   2195 
   2196 	sdp_data_free(channel);
   2197 	sdp_list_free(proto[0], 0);
   2198 	sdp_list_free(proto[1], 0);
   2199 	sdp_list_free(proto[2], 0);
   2200 	sdp_list_free(apseq, 0);
   2201 	sdp_list_free(aproto, 0);
   2202 
   2203 	if (!ret)
   2204 		return record->handle;
   2205 	return ret;
   2206 }
   2207 
   2208 static int add_opush_record(struct btd_adapter *adapter)
   2209 {
   2210 	sdp_list_t *svclass_id, *pfseq, *apseq, *root;
   2211 	uuid_t root_uuid, opush_uuid, l2cap_uuid, rfcomm_uuid, obex_uuid;
   2212 	sdp_profile_desc_t profile[1];
   2213 	sdp_list_t *aproto, *proto[3];
   2214 	sdp_record_t *record;
   2215 	uint8_t u8 = 12;
   2216 	sdp_data_t *channel;
   2217 #ifdef ANDROID
   2218 	uint8_t formats[] = { 0x01, 0x02, 0xff };
   2219 #else
   2220 	uint8_t formats[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0xff };
   2221 #endif
   2222 	void *dtds[sizeof(formats)], *values[sizeof(formats)];
   2223 	unsigned int i;
   2224 	uint8_t dtd = SDP_UINT8;
   2225 	sdp_data_t *sflist;
   2226 	int ret = 0;
   2227 
   2228 	record = sdp_record_alloc();
   2229 	if (!record) return -1;
   2230 
   2231 	sdp_uuid16_create(&root_uuid, PUBLIC_BROWSE_GROUP);
   2232 	root = sdp_list_append(0, &root_uuid);
   2233 	sdp_set_browse_groups(record, root);
   2234 
   2235 	sdp_uuid16_create(&opush_uuid, OBEX_OBJPUSH_SVCLASS_ID);
   2236 	svclass_id = sdp_list_append(0, &opush_uuid);
   2237 	sdp_set_service_classes(record, svclass_id);
   2238 
   2239 	sdp_uuid16_create(&profile[0].uuid, OBEX_OBJPUSH_PROFILE_ID);
   2240 	profile[0].version = 0x0100;
   2241 	pfseq = sdp_list_append(0, profile);
   2242 	sdp_set_profile_descs(record, pfseq);
   2243 
   2244 	sdp_uuid16_create(&l2cap_uuid, L2CAP_UUID);
   2245 	proto[0] = sdp_list_append(0, &l2cap_uuid);
   2246 	apseq = sdp_list_append(0, proto[0]);
   2247 
   2248 	sdp_uuid16_create(&rfcomm_uuid, RFCOMM_UUID);
   2249 	proto[1] = sdp_list_append(0, &rfcomm_uuid);
   2250 	channel = sdp_data_alloc(SDP_UINT8, &u8);
   2251 	proto[1] = sdp_list_append(proto[1], channel);
   2252 	apseq = sdp_list_append(apseq, proto[1]);
   2253 
   2254 	sdp_uuid16_create(&obex_uuid, OBEX_UUID);
   2255 	proto[2] = sdp_list_append(0, &obex_uuid);
   2256 	apseq = sdp_list_append(apseq, proto[2]);
   2257 
   2258 	aproto = sdp_list_append(0, apseq);
   2259 	sdp_set_access_protos(record, aproto);
   2260 
   2261 	for (i = 0; i < sizeof(formats); i++) {
   2262 		dtds[i] = &dtd;
   2263 		values[i] = &formats[i];
   2264 	}
   2265 	sflist = sdp_seq_alloc(dtds, values, sizeof(formats));
   2266 	sdp_attr_add(record, SDP_ATTR_SUPPORTED_FORMATS_LIST, sflist);
   2267 
   2268 	sdp_set_info_attr(record, "OBEX Object Push", 0, 0);
   2269 
   2270 	if (add_record_to_server(&adapter->bdaddr, record) < 0)
   2271 		ret = -1;
   2272 
   2273 	sdp_data_free(channel);
   2274 	sdp_list_free(proto[0], 0);
   2275 	sdp_list_free(proto[1], 0);
   2276 	sdp_list_free(proto[2], 0);
   2277 	sdp_list_free(apseq, 0);
   2278 	sdp_list_free(aproto, 0);
   2279 
   2280 	if (!ret)
   2281 		return record->handle;
   2282 	return ret;
   2283 }
   2284 
   2285 static DBusMessage *add_reserved_service_records(DBusConnection *conn,
   2286 						DBusMessage *msg, void *data) {
   2287 	DBusMessage *reply;
   2288 	struct btd_adapter *adapter = data;
   2289 	uint32_t *svc_classes;
   2290 	uint32_t *handles;
   2291 	uint32_t len, i;
   2292 	int ret;
   2293 
   2294 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32,
   2295 				&svc_classes, &len, DBUS_TYPE_INVALID) == FALSE)
   2296 		return btd_error_invalid_args(msg);
   2297 
   2298 	handles = g_malloc0(sizeof(uint32_t) * len);
   2299 
   2300 	for (i = 0; i < len; i++) {
   2301 		switch (svc_classes[i]) {
   2302 			case PBAP_PSE_SVCLASS_ID:
   2303 				ret = add_pbap_pse_record(adapter);
   2304 				break;
   2305 			case HEADSET_AGW_SVCLASS_ID:
   2306 				ret = add_headset_ag_record(adapter);
   2307 				break;
   2308 			case HANDSFREE_AGW_SVCLASS_ID:
   2309 				ret = add_handsfree_ag_record(adapter);
   2310 				break;
   2311 			case OBEX_OBJPUSH_SVCLASS_ID:
   2312 				ret = add_opush_record(adapter);
   2313 				break;
   2314 		}
   2315 		if (ret < 0) {
   2316 			g_free(handles);
   2317 			return g_dbus_create_error(msg,
   2318 				ERROR_INTERFACE ".Failed", "Failed to add sdp record");
   2319 		} else
   2320 			handles[i] = ret;
   2321 	}
   2322 
   2323 	reply = dbus_message_new_method_return(msg);
   2324 	dbus_message_append_args(reply, DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32,
   2325 					&handles, len, DBUS_TYPE_INVALID);
   2326 
   2327 	g_free(handles);
   2328 	return reply;
   2329 }
   2330 
   2331 static DBusMessage *remove_reserved_service_records(DBusConnection *conn,
   2332 							DBusMessage *msg, void *data) {
   2333 	uint32_t *handles;
   2334 	uint32_t len, i;
   2335 
   2336 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_ARRAY, DBUS_TYPE_UINT32,
   2337 				&handles, &len, DBUS_TYPE_INVALID) == FALSE)
   2338 		return btd_error_invalid_args(msg);
   2339 
   2340 	for (i = 0; i < len; i++)
   2341 		if (remove_record_from_server(handles[i]))
   2342 			return g_dbus_create_error(msg,
   2343 					ERROR_INTERFACE ".Failed", "Failed to remove sdp record");
   2344 
   2345 	return dbus_message_new_method_return(msg);
   2346 }
   2347 
   2348 static DBusMessage *set_link_timeout(DBusConnection *conn,
   2349 					DBusMessage *msg, void *data)
   2350 {
   2351 	struct btd_adapter *adapter = data;
   2352         struct btd_device *device;
   2353 	const char *path;
   2354 	GSList *l;
   2355 	uint32_t num_slots;
   2356         int dd, err;
   2357 	bdaddr_t bdaddr;
   2358 
   2359 	if (!dbus_message_get_args(msg, NULL,
   2360 			DBUS_TYPE_OBJECT_PATH, &path,
   2361 			DBUS_TYPE_UINT32, &num_slots,
   2362 			DBUS_TYPE_INVALID))
   2363 		return btd_error_invalid_args(msg);
   2364 
   2365         l = g_slist_find_custom(adapter->devices,
   2366                         path, (GCompareFunc) device_path_cmp);
   2367         if (!l)
   2368                 return g_dbus_create_error(msg,
   2369                                 ERROR_INTERFACE ".DoesNotExist",
   2370                                 "Device does not exist");
   2371 	device_get_address(l->data, &bdaddr);
   2372 
   2373 	err = adapter_ops->set_link_timeout(adapter->dev_id, &bdaddr,
   2374 			num_slots);
   2375 	if (err < 0)
   2376 		return btd_error_failed(msg, strerror(-err));
   2377 
   2378 	return dbus_message_new_method_return(msg);
   2379 }
   2380 
   2381 static GDBusMethodTable adapter_methods[] = {
   2382 	{ "GetProperties",	"",	"a{sv}",get_properties		},
   2383 	{ "SetProperty",	"sv",	"",	set_property,
   2384 						G_DBUS_METHOD_FLAG_ASYNC},
   2385 	{ "RequestSession",	"",	"",	request_session,
   2386 						G_DBUS_METHOD_FLAG_ASYNC},
   2387 	{ "ReleaseSession",	"",	"",	release_session		},
   2388 	{ "StartDiscovery",	"",	"",	adapter_start_discovery },
   2389 	{ "StopDiscovery",	"",	"",	adapter_stop_discovery,
   2390 						G_DBUS_METHOD_FLAG_ASYNC},
   2391 	{ "ListDevices",	"",	"ao",	list_devices,
   2392 						G_DBUS_METHOD_FLAG_DEPRECATED},
   2393 	{ "CreateDevice",	"s",	"o",	create_device,
   2394 						G_DBUS_METHOD_FLAG_ASYNC},
   2395 	{ "CreatePairedDevice",	"sos",	"o",	create_paired_device,
   2396 						G_DBUS_METHOD_FLAG_ASYNC},
   2397 	{ "CancelDeviceCreation","s",	"",	cancel_device_creation,
   2398 						G_DBUS_METHOD_FLAG_ASYNC},
   2399 	{ "RemoveDevice",	"o",	"",	remove_device,
   2400 						G_DBUS_METHOD_FLAG_ASYNC},
   2401 	{ "FindDevice",		"s",	"o",	find_device		},
   2402 	{ "RegisterAgent",	"os",	"",	register_agent		},
   2403 	{ "UnregisterAgent",	"o",	"",	unregister_agent	},
   2404 	{ "AddRfcommServiceRecord",	"sttq",	"u",	add_rfcomm_service_record },
   2405 	{ "RemoveServiceRecord",	"u",	"",	remove_service_record },
   2406 	{ "SetLinkTimeout",	"ou",	"",	set_link_timeout	},
   2407 	{ "AddReservedServiceRecords",   "au",    "au",    add_reserved_service_records  },
   2408 	{ "RemoveReservedServiceRecords", "au",    "",	remove_reserved_service_records  },
   2409 	{ }
   2410 };
   2411 
   2412 static GDBusSignalTable adapter_signals[] = {
   2413 	{ "PropertyChanged",		"sv"		},
   2414 	{ "DeviceCreated",		"o"		},
   2415 	{ "DeviceRemoved",		"o"		},
   2416 	{ "DeviceFound",		"sa{sv}"	},
   2417 	{ "DeviceDisappeared",		"s"		},
   2418 	{ }
   2419 };
   2420 
   2421 static void create_stored_device_from_profiles(char *key, char *value,
   2422 						void *user_data)
   2423 {
   2424 	struct btd_adapter *adapter = user_data;
   2425 	GSList *list, *uuids = bt_string2list(value);
   2426 	struct btd_device *device;
   2427 
   2428 	if (g_slist_find_custom(adapter->devices,
   2429 				key, (GCompareFunc) device_address_cmp))
   2430 		return;
   2431 
   2432 	device = device_create(connection, adapter, key, DEVICE_TYPE_BREDR);
   2433 	if (!device)
   2434 		return;
   2435 
   2436 	device_set_temporary(device, FALSE);
   2437 	adapter->devices = g_slist_append(adapter->devices, device);
   2438 
   2439 	device_probe_drivers(device, uuids);
   2440 	list = device_services_from_record(device, uuids);
   2441 	if (list)
   2442 		device_register_services(connection, device, list, ATT_PSM);
   2443 
   2444 	g_slist_foreach(uuids, (GFunc) g_free, NULL);
   2445 	g_slist_free(uuids);
   2446 }
   2447 
   2448 struct adapter_keys {
   2449 	struct btd_adapter *adapter;
   2450 	GSList *keys;
   2451 };
   2452 
   2453 static struct link_key_info *get_key_info(const char *addr, const char *value)
   2454 {
   2455 	struct link_key_info *info;
   2456 	char tmp[3];
   2457 	long int l;
   2458 	int i;
   2459 
   2460 	if (strlen(value) < 36) {
   2461 		error("Unexpectedly short (%zu) link key line", strlen(value));
   2462 		return NULL;
   2463 	}
   2464 
   2465 	info = g_new0(struct link_key_info, 1);
   2466 
   2467 	str2ba(addr, &info->bdaddr);
   2468 
   2469 	memset(tmp, 0, sizeof(tmp));
   2470 
   2471 	for (i = 0; i < 16; i++) {
   2472 		memcpy(tmp, value + (i * 2), 2);
   2473 		info->key[i] = (uint8_t) strtol(tmp, NULL, 16);
   2474 	}
   2475 
   2476 	memcpy(tmp, value + 33, 2);
   2477 	info->type = (uint8_t) strtol(tmp, NULL, 10);
   2478 
   2479 	memcpy(tmp, value + 35, 2);
   2480 	l = strtol(tmp, NULL, 10);
   2481 	if (l < 0)
   2482 		l = 0;
   2483 	info->pin_len = l;
   2484 
   2485 	return info;
   2486 }
   2487 
   2488 static void create_stored_device_from_linkkeys(char *key, char *value,
   2489 							void *user_data)
   2490 {
   2491 	struct adapter_keys *keys = user_data;
   2492 	struct btd_adapter *adapter = keys->adapter;
   2493 	struct btd_device *device;
   2494 	struct link_key_info *info;
   2495 
   2496 	info = get_key_info(key, value);
   2497 	if (info)
   2498 		keys->keys = g_slist_append(keys->keys, info);
   2499 
   2500 	if (g_slist_find_custom(adapter->devices, key,
   2501 					(GCompareFunc) device_address_cmp))
   2502 		return;
   2503 
   2504 	device = device_create(connection, adapter, key, DEVICE_TYPE_BREDR);
   2505 	if (device) {
   2506 		device_set_temporary(device, FALSE);
   2507 		adapter->devices = g_slist_append(adapter->devices, device);
   2508 	}
   2509 }
   2510 
   2511 static void create_stored_device_from_blocked(char *key, char *value,
   2512 							void *user_data)
   2513 {
   2514 	struct btd_adapter *adapter = user_data;
   2515 	struct btd_device *device;
   2516 
   2517 	if (g_slist_find_custom(adapter->devices,
   2518 				key, (GCompareFunc) device_address_cmp))
   2519 		return;
   2520 
   2521 	device = device_create(connection, adapter, key, DEVICE_TYPE_BREDR);
   2522 	if (device) {
   2523 		device_set_temporary(device, FALSE);
   2524 		adapter->devices = g_slist_append(adapter->devices, device);
   2525 	}
   2526 }
   2527 
   2528 static void create_stored_device_from_types(char *key, char *value,
   2529 							void *user_data)
   2530 {
   2531 	GSList *l;
   2532 	struct btd_adapter *adapter = user_data;
   2533 	struct btd_device *device;
   2534 	uint8_t type;
   2535 
   2536 	type = strtol(value, NULL, 16);
   2537 
   2538 	l = g_slist_find_custom(adapter->devices,
   2539 				key, (GCompareFunc) device_address_cmp);
   2540 	if (l) {
   2541 		device = l->data;
   2542 		device_set_type(device, type);
   2543 		return;
   2544 	}
   2545 
   2546 	device = device_create(connection, adapter, key, type);
   2547 	if (device) {
   2548 		device_set_temporary(device, FALSE);
   2549 		adapter->devices = g_slist_append(adapter->devices, device);
   2550 	}
   2551 }
   2552 
   2553 static GSList *string_to_primary_list(char *str)
   2554 {
   2555 	GSList *l = NULL;
   2556 	char **services;
   2557 	int i;
   2558 
   2559 	if (str == NULL)
   2560 		return NULL;
   2561 
   2562 	services = g_strsplit(str, " ", 0);
   2563 	if (services == NULL)
   2564 		return NULL;
   2565 
   2566 	for (i = 0; services[i]; i++) {
   2567 		struct att_primary *prim;
   2568 		int ret;
   2569 
   2570 		prim = g_new0(struct att_primary, 1);
   2571 
   2572 		ret = sscanf(services[i], "%04hX#%04hX#%s", &prim->start,
   2573 							&prim->end, prim->uuid);
   2574 
   2575 		if (ret < 3) {
   2576 			g_free(prim);
   2577 			continue;
   2578 		}
   2579 
   2580 		l = g_slist_append(l, prim);
   2581 	}
   2582 
   2583 	g_strfreev(services);
   2584 
   2585 	return l;
   2586 }
   2587 
   2588 static void create_stored_device_from_primary(char *key, char *value,
   2589 							void *user_data)
   2590 {
   2591 	struct btd_adapter *adapter = user_data;
   2592 	struct btd_device *device;
   2593 	GSList *services, *uuids, *l;
   2594 
   2595 	if (g_slist_find_custom(adapter->devices,
   2596 			key, (GCompareFunc) device_address_cmp))
   2597 		return;
   2598 
   2599 	device = device_create(connection, adapter, key, DEVICE_TYPE_LE);
   2600 	if (!device)
   2601 		return;
   2602 
   2603 	device_set_temporary(device, FALSE);
   2604 	adapter->devices = g_slist_append(adapter->devices, device);
   2605 
   2606 	services = string_to_primary_list(value);
   2607 	if (services == NULL)
   2608 		return;
   2609 
   2610 	for (l = services, uuids = NULL; l; l = l->next) {
   2611 		struct att_primary *prim = l->data;
   2612 		uuids = g_slist_append(uuids, prim->uuid);
   2613 	}
   2614 
   2615 	device_probe_drivers(device, uuids);
   2616 	device_register_services(connection, device, services, -1);
   2617 
   2618 	g_slist_free(uuids);
   2619 }
   2620 
   2621 static void load_devices(struct btd_adapter *adapter)
   2622 {
   2623 	char filename[PATH_MAX + 1];
   2624 	char srcaddr[18];
   2625 	struct adapter_keys keys = { adapter, NULL };
   2626 	int err;
   2627 
   2628 	ba2str(&adapter->bdaddr, srcaddr);
   2629 
   2630 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr, "profiles");
   2631 	textfile_foreach(filename, create_stored_device_from_profiles,
   2632 								adapter);
   2633 
   2634 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr, "primary");
   2635 	textfile_foreach(filename, create_stored_device_from_primary,
   2636 								adapter);
   2637 
   2638 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr, "linkkeys");
   2639 	textfile_foreach(filename, create_stored_device_from_linkkeys, &keys);
   2640 
   2641 	err = adapter_ops->load_keys(adapter->dev_id, keys.keys,
   2642 							main_opts.debug_keys);
   2643 	if (err < 0) {
   2644 		error("Unable to load keys to adapter_ops: %s (%d)",
   2645 							strerror(-err), -err);
   2646 		g_slist_foreach(keys.keys, (GFunc) g_free, NULL);
   2647 		g_slist_free(keys.keys);
   2648 	}
   2649 
   2650 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr, "blocked");
   2651 	textfile_foreach(filename, create_stored_device_from_blocked, adapter);
   2652 
   2653 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr, "types");
   2654 	textfile_foreach(filename, create_stored_device_from_types, adapter);
   2655 }
   2656 
   2657 int btd_adapter_block_address(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   2658 {
   2659 	return adapter_ops->block_device(adapter->dev_id, bdaddr);
   2660 }
   2661 
   2662 int btd_adapter_unblock_address(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   2663 {
   2664 	return adapter_ops->unblock_device(adapter->dev_id, bdaddr);
   2665 }
   2666 
   2667 static void clear_blocked(struct btd_adapter *adapter)
   2668 {
   2669 	int err;
   2670 
   2671 	err = adapter_ops->unblock_device(adapter->dev_id, BDADDR_ANY);
   2672 	if (err < 0)
   2673 		error("Clearing blocked list failed: %s (%d)",
   2674 						strerror(-err), -err);
   2675 }
   2676 
   2677 static void probe_driver(struct btd_adapter *adapter, gpointer user_data)
   2678 {
   2679 	struct btd_adapter_driver *driver = user_data;
   2680 	int err;
   2681 
   2682 	if (!adapter->up)
   2683 		return;
   2684 
   2685 	if (driver->probe == NULL)
   2686 		return;
   2687 
   2688 	err = driver->probe(adapter);
   2689 	if (err < 0) {
   2690 		error("%s: %s (%d)", driver->name, strerror(-err), -err);
   2691 		return;
   2692 	}
   2693 
   2694 	adapter->loaded_drivers = g_slist_prepend(adapter->loaded_drivers,
   2695 									driver);
   2696 }
   2697 
   2698 static void load_drivers(struct btd_adapter *adapter)
   2699 {
   2700 	GSList *l;
   2701 
   2702 	for (l = adapter_drivers; l; l = l->next)
   2703 		probe_driver(adapter, l->data);
   2704 }
   2705 
   2706 static void load_connections(struct btd_adapter *adapter)
   2707 {
   2708 	GSList *l, *conns;
   2709 	int err;
   2710 
   2711 	err = adapter_ops->get_conn_list(adapter->dev_id, &conns);
   2712 	if (err < 0) {
   2713 		error("Unable to fetch existing connections: %s (%d)",
   2714 							strerror(-err), -err);
   2715 		return;
   2716 	}
   2717 
   2718 	for (l = conns; l != NULL; l = g_slist_next(l)) {
   2719 		bdaddr_t *bdaddr = l->data;
   2720 		struct btd_device *device;
   2721 		char address[18];
   2722 
   2723 		ba2str(bdaddr, address);
   2724 		DBG("Adding existing connection to %s", address);
   2725 
   2726 		device = adapter_get_device(connection, adapter, address);
   2727 		if (device)
   2728 			adapter_add_connection(adapter, device);
   2729 	}
   2730 
   2731 	g_slist_foreach(conns, (GFunc) g_free, NULL);
   2732 	g_slist_free(conns);
   2733 }
   2734 
   2735 static int get_discoverable_timeout(const char *src)
   2736 {
   2737 	int timeout;
   2738 
   2739 	if (read_discoverable_timeout(src, &timeout) == 0)
   2740 		return timeout;
   2741 
   2742 	return main_opts.discovto;
   2743 }
   2744 
   2745 static int get_pairable_timeout(const char *src)
   2746 {
   2747 	int timeout;
   2748 
   2749 	if (read_pairable_timeout(src, &timeout) == 0)
   2750 		return timeout;
   2751 
   2752 	return main_opts.pairto;
   2753 }
   2754 
   2755 static void call_adapter_powered_callbacks(struct btd_adapter *adapter,
   2756 						gboolean powered)
   2757 {
   2758 	GSList *l;
   2759 
   2760 	for (l = adapter->powered_callbacks; l; l = l->next) {
   2761 		btd_adapter_powered_cb cb = l->data;
   2762 
   2763 		cb(adapter, powered);
   2764        }
   2765 }
   2766 
   2767 static void emit_device_disappeared(gpointer data, gpointer user_data)
   2768 {
   2769 	struct remote_dev_info *dev = data;
   2770 	struct btd_adapter *adapter = user_data;
   2771 	char address[18];
   2772 	const char *paddr = address;
   2773 
   2774 	ba2str(&dev->bdaddr, address);
   2775 
   2776 	g_dbus_emit_signal(connection, adapter->path,
   2777 			ADAPTER_INTERFACE, "DeviceDisappeared",
   2778 			DBUS_TYPE_STRING, &paddr,
   2779 			DBUS_TYPE_INVALID);
   2780 
   2781 	adapter->found_devices = g_slist_remove(adapter->found_devices, dev);
   2782 }
   2783 
   2784 static void update_oor_devices(struct btd_adapter *adapter)
   2785 {
   2786 	g_slist_foreach(adapter->oor_devices, emit_device_disappeared, adapter);
   2787 	g_slist_foreach(adapter->oor_devices, (GFunc) dev_info_free, NULL);
   2788 	g_slist_free(adapter->oor_devices);
   2789 	adapter->oor_devices =  g_slist_copy(adapter->found_devices);
   2790 }
   2791 
   2792 void btd_adapter_get_mode(struct btd_adapter *adapter, uint8_t *mode,
   2793 					uint8_t *on_mode, gboolean *pairable)
   2794 {
   2795 	char str[14], address[18];
   2796 
   2797 	ba2str(&adapter->bdaddr, address);
   2798 
   2799 	if (mode) {
   2800 		if (main_opts.remember_powered == FALSE)
   2801 			*mode = main_opts.mode;
   2802 		else if (read_device_mode(address, str, sizeof(str)) == 0)
   2803 			*mode = get_mode(&adapter->bdaddr, str);
   2804 		else
   2805 			*mode = main_opts.mode;
   2806 	}
   2807 
   2808 	if (on_mode) {
   2809 		if (main_opts.remember_powered == FALSE)
   2810 			*on_mode = get_mode(&adapter->bdaddr, "on");
   2811 		else if (read_on_mode(address, str, sizeof(str)) == 0)
   2812 			*on_mode = get_mode(&adapter->bdaddr, str);
   2813 		else
   2814 			*on_mode = main_opts.mode;
   2815 	}
   2816 
   2817 	if (pairable)
   2818 		*pairable = adapter->pairable;
   2819 }
   2820 
   2821 void btd_adapter_start(struct btd_adapter *adapter)
   2822 {
   2823 	char address[18];
   2824 	uint8_t cls[3];
   2825 	gboolean powered;
   2826 
   2827 	ba2str(&adapter->bdaddr, address);
   2828 
   2829 	adapter->dev_class = 0;
   2830 	adapter->off_requested = FALSE;
   2831 	adapter->up = TRUE;
   2832 	adapter->discov_timeout = get_discoverable_timeout(address);
   2833 	adapter->pairable_timeout = get_pairable_timeout(address);
   2834 	adapter->state = STATE_IDLE;
   2835 	adapter->mode = MODE_CONNECTABLE;
   2836 
   2837 	if (main_opts.le)
   2838 		adapter_ops->enable_le(adapter->dev_id);
   2839 
   2840 	adapter_ops->set_name(adapter->dev_id, adapter->name);
   2841 
   2842 	if (read_local_class(&adapter->bdaddr, cls) < 0) {
   2843 		uint32_t class = htobl(main_opts.class);
   2844 		memcpy(cls, &class, 3);
   2845 	}
   2846 
   2847 	btd_adapter_set_class(adapter, cls[1], cls[0]);
   2848 
   2849 	powered = TRUE;
   2850 	emit_property_changed(connection, adapter->path,
   2851 					ADAPTER_INTERFACE, "Powered",
   2852 					DBUS_TYPE_BOOLEAN, &powered);
   2853 
   2854 	call_adapter_powered_callbacks(adapter, TRUE);
   2855 
   2856 	adapter_ops->disable_cod_cache(adapter->dev_id);
   2857 
   2858 	info("Adapter %s has been enabled", adapter->path);
   2859 }
   2860 
   2861 static void reply_pending_requests(struct btd_adapter *adapter)
   2862 {
   2863 	GSList *l;
   2864 
   2865 	if (!adapter)
   2866 		return;
   2867 
   2868 	/* pending bonding */
   2869 	for (l = adapter->devices; l; l = l->next) {
   2870 		struct btd_device *device = l->data;
   2871 
   2872 		if (device_is_bonding(device, NULL))
   2873 			device_cancel_bonding(device,
   2874 						HCI_OE_USER_ENDED_CONNECTION);
   2875 	}
   2876 }
   2877 
   2878 static void remove_driver(gpointer data, gpointer user_data)
   2879 {
   2880 	struct btd_adapter_driver *driver = data;
   2881 	struct btd_adapter *adapter = user_data;
   2882 
   2883 	if (driver->remove)
   2884 		driver->remove(adapter);
   2885 }
   2886 
   2887 static void unload_drivers(struct btd_adapter *adapter)
   2888 {
   2889 	g_slist_foreach(adapter->loaded_drivers, remove_driver, adapter);
   2890 	g_slist_free(adapter->loaded_drivers);
   2891 	adapter->loaded_drivers = NULL;
   2892 }
   2893 
   2894 static void set_mode_complete(struct btd_adapter *adapter)
   2895 {
   2896 	struct session_req *pending;
   2897 	const char *modestr;
   2898 	int err;
   2899 
   2900 	DBG("");
   2901 
   2902 	/*
   2903 	 * g_slist_free is not called after g_slist_foreach because the list is
   2904 	 * updated using g_slist_remove in session_remove which is called by
   2905          * session_free, which is called for each element by g_slist_foreach.
   2906 	 */
   2907 	if (adapter->mode == MODE_OFF)
   2908 		g_slist_foreach(adapter->mode_sessions, (GFunc) session_free,
   2909 									NULL);
   2910 
   2911 	if (adapter->pending_mode == NULL)
   2912 		return;
   2913 
   2914 	pending = adapter->pending_mode;
   2915 	adapter->pending_mode = NULL;
   2916 
   2917 	err = (pending->mode != adapter->mode) ? -EINVAL : 0;
   2918 
   2919 	if (pending->msg != NULL) {
   2920 		DBusMessage *msg = pending->msg;
   2921 		DBusMessage *reply;
   2922 
   2923 		if (err < 0)
   2924 			reply = btd_error_failed(msg, strerror(-err));
   2925 		else {
   2926 			if (strcmp(dbus_message_get_member(msg),
   2927 						"SetProperty") == 0)
   2928 				adapter->global_mode = adapter->mode;
   2929 			reply = g_dbus_create_reply(msg, DBUS_TYPE_INVALID);
   2930 		}
   2931 
   2932 		g_dbus_send_message(connection, reply);
   2933 	}
   2934 
   2935 	modestr = mode2str(adapter->mode);
   2936 
   2937 	DBG("%s", modestr);
   2938 
   2939 	/* restore if the mode doesn't matches the pending */
   2940 	if (err != 0) {
   2941 		write_device_mode(&adapter->bdaddr, modestr);
   2942 		error("unable to set mode: %s", mode2str(pending->mode));
   2943 	}
   2944 
   2945 	session_unref(pending);
   2946 }
   2947 
   2948 int btd_adapter_stop(struct btd_adapter *adapter)
   2949 {
   2950 	gboolean powered, discoverable, pairable;
   2951 
   2952 	/* cancel pending timeout */
   2953 	if (adapter->discov_timeout_id) {
   2954 		g_source_remove(adapter->discov_timeout_id);
   2955 		adapter->discov_timeout_id = 0;
   2956 	}
   2957 
   2958 	/* check pending requests */
   2959 	reply_pending_requests(adapter);
   2960 
   2961 	stop_discovery(adapter);
   2962 
   2963 	if (adapter->disc_sessions) {
   2964 		g_slist_foreach(adapter->disc_sessions, (GFunc) session_free,
   2965 				NULL);
   2966 		g_slist_free(adapter->disc_sessions);
   2967 		adapter->disc_sessions = NULL;
   2968 	}
   2969 
   2970 	while (adapter->connections) {
   2971 		struct btd_device *device = adapter->connections->data;
   2972 		adapter_remove_connection(adapter, device);
   2973 	}
   2974 
   2975 	if (adapter->scan_mode == (SCAN_PAGE | SCAN_INQUIRY)) {
   2976 		discoverable = FALSE;
   2977 		emit_property_changed(connection, adapter->path,
   2978 					ADAPTER_INTERFACE, "Discoverable",
   2979 					DBUS_TYPE_BOOLEAN, &discoverable);
   2980 	}
   2981 
   2982 	if ((adapter->scan_mode & SCAN_PAGE) && adapter->pairable == TRUE) {
   2983 		pairable = FALSE;
   2984 		emit_property_changed(connection, adapter->path,
   2985 					ADAPTER_INTERFACE, "Pairable",
   2986 					DBUS_TYPE_BOOLEAN, &pairable);
   2987 	}
   2988 
   2989 	powered = FALSE;
   2990 	emit_property_changed(connection, adapter->path, ADAPTER_INTERFACE,
   2991 				"Powered", DBUS_TYPE_BOOLEAN, &powered);
   2992 
   2993 	adapter->up = 0;
   2994 	adapter->scan_mode = SCAN_DISABLED;
   2995 	adapter->mode = MODE_OFF;
   2996 	adapter->state = STATE_IDLE;
   2997 	adapter->off_requested = FALSE;
   2998 	adapter->name_stored = FALSE;
   2999 
   3000 	call_adapter_powered_callbacks(adapter, FALSE);
   3001 
   3002 	info("Adapter %s has been disabled", adapter->path);
   3003 
   3004 	set_mode_complete(adapter);
   3005 
   3006 	return 0;
   3007 }
   3008 
   3009 static void adapter_free(gpointer user_data)
   3010 {
   3011 	struct btd_adapter *adapter = user_data;
   3012 
   3013 	agent_free(adapter->agent);
   3014 	adapter->agent = NULL;
   3015 
   3016 	DBG("%p", adapter);
   3017 
   3018 	if (adapter->auth_idle_id)
   3019 		g_source_remove(adapter->auth_idle_id);
   3020 
   3021 	sdp_list_free(adapter->services, NULL);
   3022 
   3023 	g_slist_foreach(adapter->found_devices, (GFunc) dev_info_free, NULL);
   3024 	g_slist_free(adapter->found_devices);
   3025 
   3026 	g_slist_free(adapter->oor_devices);
   3027 
   3028 	g_free(adapter->path);
   3029 	g_free(adapter);
   3030 }
   3031 
   3032 struct btd_adapter *btd_adapter_ref(struct btd_adapter *adapter)
   3033 {
   3034 	adapter->ref++;
   3035 
   3036 	DBG("%p: ref=%d", adapter, adapter->ref);
   3037 
   3038 	return adapter;
   3039 }
   3040 
   3041 void btd_adapter_unref(struct btd_adapter *adapter)
   3042 {
   3043 	gchar *path;
   3044 
   3045 	adapter->ref--;
   3046 
   3047 	DBG("%p: ref=%d", adapter, adapter->ref);
   3048 
   3049 	if (adapter->ref > 0)
   3050 		return;
   3051 
   3052 	path = g_strdup(adapter->path);
   3053 
   3054 	g_dbus_unregister_interface(connection, path, ADAPTER_INTERFACE);
   3055 
   3056 	g_free(path);
   3057 }
   3058 
   3059 gboolean adapter_init(struct btd_adapter *adapter)
   3060 {
   3061 	int err;
   3062 
   3063 	/* adapter_ops makes sure that newly registered adapters always
   3064 	 * start off as powered */
   3065 	adapter->up = TRUE;
   3066 
   3067 	adapter_ops->read_bdaddr(adapter->dev_id, &adapter->bdaddr);
   3068 
   3069 	if (bacmp(&adapter->bdaddr, BDADDR_ANY) == 0) {
   3070 		error("No address available for hci%d", adapter->dev_id);
   3071 		return FALSE;
   3072 	}
   3073 
   3074 	err = adapter_ops->read_local_features(adapter->dev_id,
   3075 							adapter->features);
   3076 	if (err < 0) {
   3077 		error("Can't read features for hci%d: %s (%d)",
   3078 					adapter->dev_id, strerror(-err), -err);
   3079 		return FALSE;
   3080 	}
   3081 
   3082 	if (read_local_name(&adapter->bdaddr, adapter->name) < 0)
   3083 		expand_name(adapter->name, MAX_NAME_LENGTH, main_opts.name,
   3084 							adapter->dev_id);
   3085 
   3086 	if (main_opts.attrib_server)
   3087 		attrib_gap_set(GATT_CHARAC_DEVICE_NAME,
   3088 			(const uint8_t *) adapter->name, strlen(adapter->name));
   3089 
   3090 	sdp_init_services_list(&adapter->bdaddr);
   3091 	load_drivers(adapter);
   3092 	clear_blocked(adapter);
   3093 	load_devices(adapter);
   3094 
   3095 	/* Set pairable mode */
   3096 	if (read_device_pairable(&adapter->bdaddr, &adapter->pairable) < 0)
   3097 		adapter->pairable = TRUE;
   3098 
   3099 	/* retrieve the active connections: address the scenario where
   3100 	 * the are active connections before the daemon've started */
   3101 	load_connections(adapter);
   3102 
   3103 	adapter->initialized = TRUE;
   3104 
   3105 	return TRUE;
   3106 }
   3107 
   3108 struct btd_adapter *adapter_create(DBusConnection *conn, int id)
   3109 {
   3110 	char path[MAX_PATH_LENGTH];
   3111 	struct btd_adapter *adapter;
   3112 	const char *base_path = manager_get_base_path();
   3113 
   3114 	if (!connection)
   3115 		connection = conn;
   3116 
   3117 	adapter = g_try_new0(struct btd_adapter, 1);
   3118 	if (!adapter) {
   3119 		error("adapter_create: failed to alloc memory for hci%d", id);
   3120 		return NULL;
   3121 	}
   3122 
   3123 	adapter->dev_id = id;
   3124 
   3125 	snprintf(path, sizeof(path), "%s/hci%d", base_path, id);
   3126 	adapter->path = g_strdup(path);
   3127 
   3128 	if (!g_dbus_register_interface(conn, path, ADAPTER_INTERFACE,
   3129 					adapter_methods, adapter_signals, NULL,
   3130 					adapter, adapter_free)) {
   3131 		error("Adapter interface init failed on path %s", path);
   3132 		adapter_free(adapter);
   3133 		return NULL;
   3134 	}
   3135 
   3136 	return btd_adapter_ref(adapter);
   3137 }
   3138 
   3139 void adapter_remove(struct btd_adapter *adapter)
   3140 {
   3141 	GSList *l;
   3142 
   3143 	DBG("Removing adapter %s", adapter->path);
   3144 
   3145 	for (l = adapter->devices; l; l = l->next)
   3146 		device_remove(l->data, FALSE);
   3147 	g_slist_free(adapter->devices);
   3148 
   3149 	unload_drivers(adapter);
   3150 
   3151 	/* Return adapter to down state if it was not up on init */
   3152 	adapter_ops->restore_powered(adapter->dev_id);
   3153 
   3154 	btd_adapter_unref(adapter);
   3155 }
   3156 
   3157 uint16_t adapter_get_dev_id(struct btd_adapter *adapter)
   3158 {
   3159 	return adapter->dev_id;
   3160 }
   3161 
   3162 const gchar *adapter_get_path(struct btd_adapter *adapter)
   3163 {
   3164 	if (!adapter)
   3165 		return NULL;
   3166 
   3167 	return adapter->path;
   3168 }
   3169 
   3170 void adapter_get_address(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   3171 {
   3172 	bacpy(bdaddr, &adapter->bdaddr);
   3173 }
   3174 
   3175 static inline void suspend_discovery(struct btd_adapter *adapter)
   3176 {
   3177 	if (adapter->state != STATE_SUSPENDED)
   3178 		return;
   3179 
   3180 	if (adapter->oor_devices) {
   3181 		g_slist_free(adapter->oor_devices);
   3182 		adapter->oor_devices = NULL;
   3183 	}
   3184 
   3185 	if (adapter->scheduler_id) {
   3186 		g_source_remove(adapter->scheduler_id);
   3187 		adapter->scheduler_id = 0;
   3188 	}
   3189 
   3190 	adapter_ops->stop_discovery(adapter->dev_id);
   3191 }
   3192 
   3193 static inline void resolve_names(struct btd_adapter *adapter)
   3194 {
   3195 	int err;
   3196 
   3197 	if (adapter->state != STATE_RESOLVNAME)
   3198 		return;
   3199 
   3200 	err = adapter_resolve_names(adapter);
   3201 	if (err < 0)
   3202 		adapter_set_state(adapter, STATE_IDLE);
   3203 }
   3204 
   3205 void adapter_set_state(struct btd_adapter *adapter, int state)
   3206 {
   3207 	const char *path = adapter->path;
   3208 	gboolean discov_active;
   3209 
   3210 	if (adapter->state == state)
   3211 		return;
   3212 
   3213 	adapter->state = state;
   3214 
   3215 	DBG("hci%d: new state %d", adapter->dev_id, adapter->state);
   3216 
   3217 	switch (adapter->state) {
   3218 	case STATE_IDLE:
   3219 		update_oor_devices(adapter);
   3220 
   3221 		discov_active = FALSE;
   3222 		emit_property_changed(connection, path,
   3223 					ADAPTER_INTERFACE, "Discovering",
   3224 					DBUS_TYPE_BOOLEAN, &discov_active);
   3225 
   3226 		if (adapter_has_discov_sessions(adapter)) {
   3227 			adapter->scheduler_id = g_timeout_add_seconds(
   3228 						main_opts.discov_interval,
   3229 						discovery_cb, adapter);
   3230 		}
   3231 		break;
   3232 	case STATE_DISCOV:
   3233 		discov_active = TRUE;
   3234 		emit_property_changed(connection, path,
   3235 					ADAPTER_INTERFACE, "Discovering",
   3236 					DBUS_TYPE_BOOLEAN, &discov_active);
   3237 		break;
   3238 	case STATE_RESOLVNAME:
   3239 		resolve_names(adapter);
   3240 		break;
   3241 	case STATE_SUSPENDED:
   3242 		suspend_discovery(adapter);
   3243 		break;
   3244 	}
   3245 }
   3246 
   3247 int adapter_get_state(struct btd_adapter *adapter)
   3248 {
   3249 	return adapter->state;
   3250 }
   3251 
   3252 struct remote_dev_info *adapter_search_found_devices(struct btd_adapter *adapter,
   3253 						struct remote_dev_info *match)
   3254 {
   3255 	GSList *l;
   3256 
   3257 	l = g_slist_find_custom(adapter->found_devices, match,
   3258 					(GCompareFunc) found_device_cmp);
   3259 	if (l)
   3260 		return l->data;
   3261 
   3262 	return NULL;
   3263 }
   3264 
   3265 static int dev_rssi_cmp(struct remote_dev_info *d1, struct remote_dev_info *d2)
   3266 {
   3267 	int rssi1, rssi2;
   3268 
   3269 	rssi1 = d1->rssi < 0 ? -d1->rssi : d1->rssi;
   3270 	rssi2 = d2->rssi < 0 ? -d2->rssi : d2->rssi;
   3271 
   3272 	return rssi1 - rssi2;
   3273 }
   3274 
   3275 static void append_dict_valist(DBusMessageIter *iter,
   3276 					const char *first_key,
   3277 					va_list var_args)
   3278 {
   3279 	DBusMessageIter dict;
   3280 	const char *key;
   3281 	int type;
   3282 	int n_elements;
   3283 	void *val;
   3284 
   3285 	dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
   3286 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
   3287 			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
   3288 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
   3289 
   3290 	key = first_key;
   3291 	while (key) {
   3292 		type = va_arg(var_args, int);
   3293 		val = va_arg(var_args, void *);
   3294 		if (type == DBUS_TYPE_ARRAY) {
   3295 			n_elements = va_arg(var_args, int);
   3296 			if (n_elements > 0)
   3297 				dict_append_array(&dict, key, DBUS_TYPE_STRING,
   3298 						val, n_elements);
   3299 		} else
   3300 			dict_append_entry(&dict, key, type, val);
   3301 		key = va_arg(var_args, char *);
   3302 	}
   3303 
   3304 	dbus_message_iter_close_container(iter, &dict);
   3305 }
   3306 
   3307 static void emit_device_found(const char *path, const char *address,
   3308 				const char *first_key, ...)
   3309 {
   3310 	DBusMessage *signal;
   3311 	DBusMessageIter iter;
   3312 	va_list var_args;
   3313 
   3314 	signal = dbus_message_new_signal(path, ADAPTER_INTERFACE,
   3315 					"DeviceFound");
   3316 	if (!signal) {
   3317 		error("Unable to allocate new %s.DeviceFound signal",
   3318 				ADAPTER_INTERFACE);
   3319 		return;
   3320 	}
   3321 	dbus_message_iter_init_append(signal, &iter);
   3322 	dbus_message_iter_append_basic(&iter, DBUS_TYPE_STRING, &address);
   3323 
   3324 	va_start(var_args, first_key);
   3325 	append_dict_valist(&iter, first_key, var_args);
   3326 	va_end(var_args);
   3327 
   3328 	g_dbus_send_message(connection, signal);
   3329 }
   3330 
   3331 static char **strlist2array(GSList *list)
   3332 {
   3333 	unsigned int i, n;
   3334 	char **array;
   3335 
   3336 	if (list == NULL)
   3337 		return NULL;
   3338 
   3339 	n = g_slist_length(list);
   3340 	array = g_new0(char *, n + 1);
   3341 
   3342 	for (i = 0; list; list = list->next, i++)
   3343 		array[i] = g_strdup((const gchar *) list->data);
   3344 
   3345 	return array;
   3346 }
   3347 
   3348 void adapter_emit_device_found(struct btd_adapter *adapter,
   3349 						struct remote_dev_info *dev)
   3350 {
   3351 	struct btd_device *device;
   3352 	char peer_addr[18], local_addr[18];
   3353 	const char *icon, *paddr = peer_addr;
   3354 	dbus_bool_t paired = FALSE;
   3355 	dbus_int16_t rssi = dev->rssi;
   3356 	char *alias;
   3357 	size_t uuid_count;
   3358 
   3359 	ba2str(&dev->bdaddr, peer_addr);
   3360 	ba2str(&adapter->bdaddr, local_addr);
   3361 
   3362 	device = adapter_find_device(adapter, paddr);
   3363 	if (device)
   3364 		paired = device_is_paired(device);
   3365 
   3366 	/* The uuids string array is updated only if necessary */
   3367 	uuid_count = g_slist_length(dev->services);
   3368 	if (dev->services && dev->uuid_count != uuid_count) {
   3369 		g_strfreev(dev->uuids);
   3370 		dev->uuids = strlist2array(dev->services);
   3371 		dev->uuid_count = uuid_count;
   3372 	}
   3373 
   3374 	if (dev->le) {
   3375 		gboolean broadcaster;
   3376 
   3377 		if (dev->flags & (EIR_LIM_DISC | EIR_GEN_DISC))
   3378 			broadcaster = FALSE;
   3379 		else
   3380 			broadcaster = TRUE;
   3381 
   3382 		emit_device_found(adapter->path, paddr,
   3383 				"Address", DBUS_TYPE_STRING, &paddr,
   3384 				"RSSI", DBUS_TYPE_INT16, &rssi,
   3385 				"Name", DBUS_TYPE_STRING, &dev->name,
   3386 				"Paired", DBUS_TYPE_BOOLEAN, &paired,
   3387 				"Broadcaster", DBUS_TYPE_BOOLEAN, &broadcaster,
   3388 				"UUIDs", DBUS_TYPE_ARRAY, &dev->uuids, uuid_count,
   3389 				NULL);
   3390 		return;
   3391 	}
   3392 
   3393 	icon = class_to_icon(dev->class);
   3394 
   3395 	if (!dev->alias) {
   3396 		if (!dev->name) {
   3397 			alias = g_strdup(peer_addr);
   3398 			g_strdelimit(alias, ":", '-');
   3399 		} else
   3400 			alias = g_strdup(dev->name);
   3401 	} else
   3402 		alias = g_strdup(dev->alias);
   3403 
   3404 	emit_device_found(adapter->path, paddr,
   3405 			"Address", DBUS_TYPE_STRING, &paddr,
   3406 			"Class", DBUS_TYPE_UINT32, &dev->class,
   3407 			"Icon", DBUS_TYPE_STRING, &icon,
   3408 			"RSSI", DBUS_TYPE_INT16, &rssi,
   3409 			"Name", DBUS_TYPE_STRING, &dev->name,
   3410 			"Alias", DBUS_TYPE_STRING, &alias,
   3411 			"LegacyPairing", DBUS_TYPE_BOOLEAN, &dev->legacy,
   3412 			"Paired", DBUS_TYPE_BOOLEAN, &paired,
   3413 			"UUIDs", DBUS_TYPE_ARRAY, &dev->uuids, uuid_count,
   3414 			NULL);
   3415 
   3416 	g_free(alias);
   3417 }
   3418 
   3419 static struct remote_dev_info *found_device_new(const bdaddr_t *bdaddr,
   3420 					gboolean le, const char *name,
   3421 					const char *alias, uint32_t class,
   3422 					gboolean legacy, name_status_t status,
   3423 					int flags)
   3424 {
   3425 	struct remote_dev_info *dev;
   3426 
   3427 	dev = g_new0(struct remote_dev_info, 1);
   3428 	bacpy(&dev->bdaddr, bdaddr);
   3429 	dev->le = le;
   3430 	dev->name = g_strdup(name);
   3431 	dev->alias = g_strdup(alias);
   3432 	dev->class = class;
   3433 	dev->legacy = legacy;
   3434 	dev->name_status = status;
   3435 	if (flags >= 0)
   3436 		dev->flags = flags;
   3437 
   3438 	return dev;
   3439 }
   3440 
   3441 static void remove_same_uuid(gpointer data, gpointer user_data)
   3442 {
   3443 	struct remote_dev_info *dev = user_data;
   3444 	GSList *l;
   3445 
   3446 	for (l = dev->services; l; l = l->next) {
   3447 		char *current_uuid = l->data;
   3448 		char *new_uuid = data;
   3449 
   3450 		if (strcmp(current_uuid, new_uuid) == 0) {
   3451 			g_free(current_uuid);
   3452 			dev->services = g_slist_delete_link(dev->services, l);
   3453 			break;
   3454 		}
   3455 	}
   3456 }
   3457 
   3458 static void dev_prepend_uuid(gpointer data, gpointer user_data)
   3459 {
   3460 	struct remote_dev_info *dev = user_data;
   3461 	char *new_uuid = data;
   3462 
   3463 	dev->services = g_slist_prepend(dev->services, g_strdup(new_uuid));
   3464 }
   3465 
   3466 static gboolean pairing_is_legacy(bdaddr_t *local, bdaddr_t *peer,
   3467 					const uint8_t *eir, const char *name)
   3468 {
   3469 	unsigned char features[8];
   3470 
   3471 	if (eir)
   3472 		return FALSE;
   3473 
   3474 	if (name == NULL)
   3475 		return TRUE;
   3476 
   3477 	if (read_remote_features(local, peer, NULL, features) < 0)
   3478 		return TRUE;
   3479 
   3480 	if (features[0] & 0x01)
   3481 		return FALSE;
   3482 	else
   3483 		return TRUE;
   3484 }
   3485 
   3486 static char *read_stored_data(bdaddr_t *local, bdaddr_t *peer, const char *file)
   3487 {
   3488 	char local_addr[18], peer_addr[18], filename[PATH_MAX + 1];
   3489 
   3490 	ba2str(local, local_addr);
   3491 	ba2str(peer, peer_addr);
   3492 
   3493 	create_name(filename, PATH_MAX, STORAGEDIR, local_addr, file);
   3494 
   3495 	return textfile_get(filename, peer_addr);
   3496 }
   3497 
   3498 void adapter_update_found_devices(struct btd_adapter *adapter, bdaddr_t *bdaddr,
   3499 						uint32_t class, int8_t rssi,
   3500 						uint8_t *data)
   3501 {
   3502 	struct remote_dev_info *dev, match;
   3503 	struct eir_data eir_data;
   3504 	char *alias, *name;
   3505 	gboolean legacy, le;
   3506 	name_status_t name_status;
   3507 	int err;
   3508 
   3509 	memset(&eir_data, 0, sizeof(eir_data));
   3510 	err = eir_parse(&eir_data, data);
   3511 	if (err < 0) {
   3512 		error("Error parsing EIR data: %s (%d)", strerror(-err), -err);
   3513 		return;
   3514 	}
   3515 
   3516 	if (eir_data.name != NULL && eir_data.name_complete)
   3517 		write_device_name(&adapter->bdaddr, bdaddr, eir_data.name);
   3518 
   3519 	/* Device already seen in the discovery session ? */
   3520 	memset(&match, 0, sizeof(struct remote_dev_info));
   3521 	bacpy(&match.bdaddr, bdaddr);
   3522 	match.name_status = NAME_ANY;
   3523 
   3524 	dev = adapter_search_found_devices(adapter, &match);
   3525 	if (dev) {
   3526 		adapter->oor_devices = g_slist_remove(adapter->oor_devices,
   3527 							dev);
   3528 		if (dev->rssi != rssi)
   3529 			goto done;
   3530 
   3531 		eir_data_free(&eir_data);
   3532 
   3533 		return;
   3534 	}
   3535 
   3536 	/* New device in the discovery session */
   3537 
   3538 	name = read_stored_data(&adapter->bdaddr, bdaddr, "names");
   3539 
   3540 	if (eir_data.flags < 0) {
   3541 		le = FALSE;
   3542 
   3543 		legacy = pairing_is_legacy(&adapter->bdaddr, bdaddr, data,
   3544 									name);
   3545 
   3546 		if (!name && main_opts.name_resolv &&
   3547 				adapter_has_discov_sessions(adapter))
   3548 			name_status = NAME_REQUIRED;
   3549 		else
   3550 			name_status = NAME_NOT_REQUIRED;
   3551 	} else {
   3552 		le = TRUE;
   3553 		legacy = FALSE;
   3554 		name_status = NAME_NOT_REQUIRED;
   3555 	}
   3556 
   3557 	alias = read_stored_data(&adapter->bdaddr, bdaddr, "aliases");
   3558 
   3559 	dev = found_device_new(bdaddr, le, name, alias, class, legacy,
   3560 						name_status, eir_data.flags);
   3561 	free(name);
   3562 	free(alias);
   3563 
   3564 	adapter->found_devices = g_slist_prepend(adapter->found_devices, dev);
   3565 
   3566 done:
   3567 	dev->rssi = rssi;
   3568 
   3569 	adapter->found_devices = g_slist_sort(adapter->found_devices,
   3570 						(GCompareFunc) dev_rssi_cmp);
   3571 
   3572 	g_slist_foreach(eir_data.services, remove_same_uuid, dev);
   3573 	g_slist_foreach(eir_data.services, dev_prepend_uuid, dev);
   3574 
   3575 	adapter_emit_device_found(adapter, dev);
   3576 
   3577 	eir_data_free(&eir_data);
   3578 }
   3579 
   3580 int adapter_remove_found_device(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   3581 {
   3582 	struct remote_dev_info *dev, match;
   3583 
   3584 	memset(&match, 0, sizeof(struct remote_dev_info));
   3585 	bacpy(&match.bdaddr, bdaddr);
   3586 
   3587 	dev = adapter_search_found_devices(adapter, &match);
   3588 	if (!dev)
   3589 		return -1;
   3590 
   3591 	dev->name_status = NAME_NOT_REQUIRED;
   3592 
   3593 	return 0;
   3594 }
   3595 
   3596 void adapter_mode_changed(struct btd_adapter *adapter, uint8_t scan_mode)
   3597 {
   3598 	const gchar *path = adapter_get_path(adapter);
   3599 	gboolean discoverable, pairable;
   3600 
   3601 	DBG("old 0x%02x new 0x%02x", adapter->scan_mode, scan_mode);
   3602 
   3603 	if (adapter->scan_mode == scan_mode)
   3604 		return;
   3605 
   3606 	adapter_remove_discov_timeout(adapter);
   3607 
   3608 	switch (scan_mode) {
   3609 	case SCAN_DISABLED:
   3610 		adapter->mode = MODE_OFF;
   3611 		discoverable = FALSE;
   3612 		pairable = FALSE;
   3613 		break;
   3614 	case SCAN_PAGE:
   3615 		adapter->mode = MODE_CONNECTABLE;
   3616 		discoverable = FALSE;
   3617 		pairable = adapter->pairable;
   3618 		break;
   3619 	case (SCAN_PAGE | SCAN_INQUIRY):
   3620 		adapter->mode = MODE_DISCOVERABLE;
   3621 		discoverable = TRUE;
   3622 		pairable = adapter->pairable;
   3623 		if (adapter->discov_timeout != 0)
   3624 			adapter_set_discov_timeout(adapter,
   3625 						adapter->discov_timeout);
   3626 		break;
   3627 	case SCAN_INQUIRY:
   3628 		/* Address the scenario where a low-level application like
   3629 		 * hciconfig changed the scan mode */
   3630 		if (adapter->discov_timeout != 0)
   3631 			adapter_set_discov_timeout(adapter,
   3632 						adapter->discov_timeout);
   3633 
   3634 		/* ignore, this event should not be sent */
   3635 	default:
   3636 		/* ignore, reserved */
   3637 		return;
   3638 	}
   3639 
   3640 	/* If page scanning gets toggled emit the Pairable property */
   3641 	if ((adapter->scan_mode & SCAN_PAGE) != (scan_mode & SCAN_PAGE))
   3642 		emit_property_changed(connection, adapter->path,
   3643 					ADAPTER_INTERFACE, "Pairable",
   3644 					DBUS_TYPE_BOOLEAN, &pairable);
   3645 
   3646 	if (!discoverable)
   3647 		adapter_set_limited_discoverable(adapter, FALSE);
   3648 
   3649 	emit_property_changed(connection, path,
   3650 				ADAPTER_INTERFACE, "Discoverable",
   3651 				DBUS_TYPE_BOOLEAN, &discoverable);
   3652 
   3653 	adapter->scan_mode = scan_mode;
   3654 
   3655 	set_mode_complete(adapter);
   3656 }
   3657 
   3658 struct agent *adapter_get_agent(struct btd_adapter *adapter)
   3659 {
   3660 	if (!adapter)
   3661 		return NULL;
   3662 
   3663 	return adapter->agent;
   3664 }
   3665 
   3666 void adapter_add_connection(struct btd_adapter *adapter,
   3667 						struct btd_device *device)
   3668 {
   3669 	if (g_slist_find(adapter->connections, device)) {
   3670 		error("Device is already marked as connected");
   3671 		return;
   3672 	}
   3673 
   3674 	device_add_connection(device, connection);
   3675 
   3676 	adapter->connections = g_slist_append(adapter->connections, device);
   3677 }
   3678 
   3679 void adapter_remove_connection(struct btd_adapter *adapter,
   3680 						struct btd_device *device)
   3681 {
   3682 	DBG("");
   3683 
   3684 	if (!g_slist_find(adapter->connections, device)) {
   3685 		error("No matching connection for device");
   3686 		return;
   3687 	}
   3688 
   3689 	device_remove_connection(device, connection);
   3690 
   3691 	adapter->connections = g_slist_remove(adapter->connections, device);
   3692 
   3693 	if (device_is_authenticating(device))
   3694 		device_cancel_authentication(device, TRUE);
   3695 
   3696 	if (device_is_temporary(device)) {
   3697 		const char *path = device_get_path(device);
   3698 
   3699 		DBG("Removing temporary device %s", path);
   3700 		adapter_remove_device(connection, adapter, device, TRUE);
   3701 	}
   3702 }
   3703 
   3704 gboolean adapter_has_discov_sessions(struct btd_adapter *adapter)
   3705 {
   3706 	if (!adapter || !adapter->disc_sessions)
   3707 		return FALSE;
   3708 
   3709 	return TRUE;
   3710 }
   3711 
   3712 void adapter_suspend_discovery(struct btd_adapter *adapter)
   3713 {
   3714 	if (adapter->disc_sessions == NULL ||
   3715 			adapter->state == STATE_SUSPENDED)
   3716 		return;
   3717 
   3718 	DBG("Suspending discovery");
   3719 
   3720 	adapter_set_state(adapter, STATE_SUSPENDED);
   3721 }
   3722 
   3723 void adapter_resume_discovery(struct btd_adapter *adapter)
   3724 {
   3725 	DBG("Resuming discovery");
   3726 
   3727 	adapter_set_state(adapter, STATE_IDLE);
   3728 }
   3729 
   3730 int btd_register_adapter_driver(struct btd_adapter_driver *driver)
   3731 {
   3732 	adapter_drivers = g_slist_append(adapter_drivers, driver);
   3733 
   3734 	if (driver->probe == NULL)
   3735 		return 0;
   3736 
   3737 	manager_foreach_adapter(probe_driver, driver);
   3738 
   3739 	return 0;
   3740 }
   3741 
   3742 static void unload_driver(struct btd_adapter *adapter, gpointer data)
   3743 {
   3744 	adapter->loaded_drivers = g_slist_remove(adapter->loaded_drivers, data);
   3745 }
   3746 
   3747 void btd_unregister_adapter_driver(struct btd_adapter_driver *driver)
   3748 {
   3749 	adapter_drivers = g_slist_remove(adapter_drivers, driver);
   3750 
   3751 	manager_foreach_adapter(unload_driver, driver);
   3752 }
   3753 
   3754 static void agent_auth_cb(struct agent *agent, DBusError *derr,
   3755 							void *user_data)
   3756 {
   3757 	struct service_auth *auth = user_data;
   3758 
   3759 	device_set_authorizing(auth->device, FALSE);
   3760 
   3761 	auth->cb(derr, auth->user_data);
   3762 }
   3763 
   3764 static gboolean auth_idle_cb(gpointer user_data)
   3765 {
   3766 	struct service_auth *auth = user_data;
   3767 	struct btd_adapter *adapter = auth->adapter;
   3768 
   3769 	adapter->auth_idle_id = 0;
   3770 
   3771 	auth->cb(NULL, auth->user_data);
   3772 
   3773 	return FALSE;
   3774 }
   3775 
   3776 static int adapter_authorize(struct btd_adapter *adapter, const bdaddr_t *dst,
   3777 					const char *uuid, service_auth_cb cb,
   3778 					void *user_data)
   3779 {
   3780 	struct service_auth *auth;
   3781 	struct btd_device *device;
   3782 	struct agent *agent;
   3783 	char address[18];
   3784 	const gchar *dev_path;
   3785 	int err;
   3786 
   3787 	ba2str(dst, address);
   3788 	device = adapter_find_device(adapter, address);
   3789 	if (!device)
   3790 		return -EPERM;
   3791 
   3792 	/* Device connected? */
   3793 	if (!g_slist_find(adapter->connections, device))
   3794 		return -ENOTCONN;
   3795 
   3796 	if (adapter->auth_idle_id)
   3797 		return -EBUSY;
   3798 
   3799 	auth = g_try_new0(struct service_auth, 1);
   3800 	if (!auth)
   3801 		return -ENOMEM;
   3802 
   3803 	auth->cb = cb;
   3804 	auth->user_data = user_data;
   3805 	auth->device = device;
   3806 	auth->adapter = adapter;
   3807 
   3808 	if (device_is_trusted(device) == TRUE) {
   3809 		adapter->auth_idle_id = g_idle_add_full(G_PRIORITY_DEFAULT_IDLE,
   3810 							auth_idle_cb, auth,
   3811 							g_free);
   3812 		return 0;
   3813 	}
   3814 
   3815 	agent = device_get_agent(device);
   3816 	if (!agent) {
   3817 		g_free(auth);
   3818 		return -EPERM;
   3819 	}
   3820 
   3821 	dev_path = device_get_path(device);
   3822 
   3823 	err = agent_authorize(agent, dev_path, uuid, agent_auth_cb, auth, g_free);
   3824 	if (err < 0)
   3825 		g_free(auth);
   3826 	else
   3827 		device_set_authorizing(device, TRUE);
   3828 
   3829 	return err;
   3830 }
   3831 
   3832 int btd_request_authorization(const bdaddr_t *src, const bdaddr_t *dst,
   3833 					const char *uuid, service_auth_cb cb,
   3834 					void *user_data)
   3835 {
   3836 	struct btd_adapter *adapter;
   3837 	GSList *l;
   3838 
   3839 	if (bacmp(src, BDADDR_ANY) != 0) {
   3840 		adapter = manager_find_adapter(src);
   3841 		if (!adapter)
   3842 			return -EPERM;
   3843 
   3844 		return adapter_authorize(adapter, dst, uuid, cb, user_data);
   3845 	}
   3846 
   3847 	for (l = manager_get_adapters(); l != NULL; l = g_slist_next(l)) {
   3848 		int err;
   3849 
   3850 		adapter = l->data;
   3851 
   3852 		err = adapter_authorize(adapter, dst, uuid, cb, user_data);
   3853 		if (err == 0)
   3854 			return 0;
   3855 	}
   3856 
   3857 	return -EPERM;
   3858 }
   3859 
   3860 int btd_cancel_authorization(const bdaddr_t *src, const bdaddr_t *dst)
   3861 {
   3862 	struct btd_adapter *adapter = manager_find_adapter(src);
   3863 	struct btd_device *device;
   3864 	struct agent *agent;
   3865 	char address[18];
   3866 	int err;
   3867 
   3868 	if (!adapter)
   3869 		return -EPERM;
   3870 
   3871 	ba2str(dst, address);
   3872 	device = adapter_find_device(adapter, address);
   3873 	if (!device)
   3874 		return -EPERM;
   3875 
   3876 	if (adapter->auth_idle_id) {
   3877 		g_source_remove(adapter->auth_idle_id);
   3878 		adapter->auth_idle_id = 0;
   3879 		return 0;
   3880 	}
   3881 
   3882 	/*
   3883 	 * FIXME: Cancel fails if authorization is requested to adapter's
   3884 	 * agent and in the meanwhile CreatePairedDevice is called.
   3885 	 */
   3886 
   3887 	agent = device_get_agent(device);
   3888 	if (!agent)
   3889 		return -EPERM;
   3890 
   3891 	err = agent_cancel(agent);
   3892 
   3893 	if (err == 0)
   3894 		device_set_authorizing(device, FALSE);
   3895 
   3896 	return err;
   3897 }
   3898 
   3899 static gchar *adapter_any_path = NULL;
   3900 static int adapter_any_refcount = 0;
   3901 
   3902 const char *adapter_any_get_path(void)
   3903 {
   3904 	return adapter_any_path;
   3905 }
   3906 
   3907 const char *btd_adapter_any_request_path(void)
   3908 {
   3909 	if (adapter_any_refcount++ > 0)
   3910 		return adapter_any_path;
   3911 
   3912 	adapter_any_path = g_strdup_printf("%s/any", manager_get_base_path());
   3913 
   3914 	return adapter_any_path;
   3915 }
   3916 
   3917 void btd_adapter_any_release_path(void)
   3918 {
   3919 	adapter_any_refcount--;
   3920 
   3921 	if (adapter_any_refcount > 0)
   3922 		return;
   3923 
   3924 	g_free(adapter_any_path);
   3925 	adapter_any_path = NULL;
   3926 }
   3927 
   3928 gboolean adapter_is_pairable(struct btd_adapter *adapter)
   3929 {
   3930 	return adapter->pairable;
   3931 }
   3932 
   3933 gboolean adapter_powering_down(struct btd_adapter *adapter)
   3934 {
   3935 	return adapter->off_requested;
   3936 }
   3937 
   3938 int btd_adapter_restore_powered(struct btd_adapter *adapter)
   3939 {
   3940 	char mode[14], address[18];
   3941 
   3942 	if (!adapter_ops)
   3943 		return -EINVAL;
   3944 
   3945 	if (!main_opts.remember_powered)
   3946 		return -EINVAL;
   3947 
   3948 	if (adapter->up)
   3949 		return 0;
   3950 
   3951 	ba2str(&adapter->bdaddr, address);
   3952 	if (read_device_mode(address, mode, sizeof(mode)) == 0 &&
   3953 						g_str_equal(mode, "off"))
   3954 		return 0;
   3955 
   3956 	return adapter_ops->set_powered(adapter->dev_id, TRUE);
   3957 }
   3958 
   3959 int btd_adapter_switch_online(struct btd_adapter *adapter)
   3960 {
   3961 	if (!adapter_ops)
   3962 		return -EINVAL;
   3963 
   3964 	if (adapter->up)
   3965 		return 0;
   3966 
   3967 	return adapter_ops->set_powered(adapter->dev_id, TRUE);
   3968 }
   3969 
   3970 int btd_adapter_switch_offline(struct btd_adapter *adapter)
   3971 {
   3972 	if (!adapter_ops)
   3973 		return -EINVAL;
   3974 
   3975 	if (!adapter->up)
   3976 		return 0;
   3977 
   3978 	return adapter_ops->set_powered(adapter->dev_id, FALSE);
   3979 }
   3980 
   3981 int btd_register_adapter_ops(struct btd_adapter_ops *ops, gboolean priority)
   3982 {
   3983 	if (ops->setup == NULL)
   3984 		return -EINVAL;
   3985 
   3986 	if (priority)
   3987 		ops_candidates = g_slist_prepend(ops_candidates, ops);
   3988 	else
   3989 		ops_candidates = g_slist_append(ops_candidates, ops);
   3990 
   3991 	return 0;
   3992 }
   3993 
   3994 void btd_adapter_cleanup_ops(struct btd_adapter_ops *ops)
   3995 {
   3996 	ops_candidates = g_slist_remove(ops_candidates, ops);
   3997 	ops->cleanup();
   3998 
   3999 	if (adapter_ops == ops)
   4000 		adapter_ops = NULL;
   4001 }
   4002 
   4003 int adapter_ops_setup(void)
   4004 {
   4005 	GSList *l;
   4006 	int ret;
   4007 
   4008 	if (!ops_candidates)
   4009 		return -EINVAL;
   4010 
   4011 	for (l = ops_candidates; l != NULL; l = g_slist_next(l)) {
   4012 		struct btd_adapter_ops *ops = l->data;
   4013 
   4014 		ret = ops->setup();
   4015 		if (ret < 0)
   4016 			continue;
   4017 
   4018 		adapter_ops = ops;
   4019 		break;
   4020 	}
   4021 
   4022 	return ret;
   4023 }
   4024 
   4025 void btd_adapter_register_powered_callback(struct btd_adapter *adapter,
   4026 						btd_adapter_powered_cb cb)
   4027 {
   4028 	adapter->powered_callbacks =
   4029 			g_slist_append(adapter->powered_callbacks, cb);
   4030 }
   4031 
   4032 void btd_adapter_unregister_powered_callback(struct btd_adapter *adapter,
   4033 						btd_adapter_powered_cb cb)
   4034 {
   4035 	adapter->powered_callbacks =
   4036 			g_slist_remove(adapter->powered_callbacks, cb);
   4037 }
   4038 
   4039 int btd_adapter_set_fast_connectable(struct btd_adapter *adapter,
   4040 							gboolean enable)
   4041 {
   4042 	if (!adapter_ops)
   4043 		return -EINVAL;
   4044 
   4045 	if (!adapter->up)
   4046 		return -EINVAL;
   4047 
   4048 	return adapter_ops->set_fast_connectable(adapter->dev_id, enable);
   4049 }
   4050 
   4051 int btd_adapter_read_clock(struct btd_adapter *adapter, bdaddr_t *bdaddr,
   4052 				int which, int timeout, uint32_t *clock,
   4053 				uint16_t *accuracy)
   4054 {
   4055 	if (!adapter_ops)
   4056 		return -EINVAL;
   4057 
   4058 	if (!adapter->up)
   4059 		return -EINVAL;
   4060 
   4061 	return adapter_ops->read_clock(adapter->dev_id, bdaddr, which,
   4062 						timeout, clock, accuracy);
   4063 }
   4064 
   4065 int btd_adapter_disconnect_device(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   4066 {
   4067 	return adapter_ops->disconnect(adapter->dev_id, bdaddr);
   4068 }
   4069 
   4070 int btd_adapter_remove_bonding(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   4071 {
   4072 	return adapter_ops->remove_bonding(adapter->dev_id, bdaddr);
   4073 }
   4074 
   4075 int btd_adapter_pincode_reply(struct btd_adapter *adapter, bdaddr_t *bdaddr,
   4076 					const char *pin, size_t pin_len)
   4077 {
   4078 	return adapter_ops->pincode_reply(adapter->dev_id, bdaddr, pin,
   4079 								pin_len);
   4080 }
   4081 
   4082 int btd_adapter_confirm_reply(struct btd_adapter *adapter, bdaddr_t *bdaddr,
   4083 							gboolean success)
   4084 {
   4085 	return adapter_ops->confirm_reply(adapter->dev_id, bdaddr, success);
   4086 }
   4087 
   4088 int btd_adapter_passkey_reply(struct btd_adapter *adapter, bdaddr_t *bdaddr,
   4089 							uint32_t passkey)
   4090 {
   4091 	return adapter_ops->passkey_reply(adapter->dev_id, bdaddr, passkey);
   4092 }
   4093 
   4094 int btd_adapter_encrypt_link(struct btd_adapter *adapter, bdaddr_t *bdaddr,
   4095 					bt_hci_result_t cb, gpointer user_data)
   4096 {
   4097 	return adapter_ops->encrypt_link(adapter->dev_id, bdaddr, cb, user_data);
   4098 }
   4099 
   4100 int btd_adapter_set_did(struct btd_adapter *adapter, uint16_t vendor,
   4101 					uint16_t product, uint16_t version)
   4102 {
   4103 	return adapter_ops->set_did(adapter->dev_id, vendor, product, version);
   4104 }
   4105 
   4106 int btd_adapter_retry_authentication(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   4107 {
   4108 	return adapter_ops->retry_authentication(adapter->dev_id, bdaddr);
   4109 }
   4110 
   4111 int adapter_create_bonding(struct btd_adapter *adapter, bdaddr_t *bdaddr,
   4112 								uint8_t io_cap)
   4113 {
   4114 	return adapter_ops->create_bonding(adapter->dev_id, bdaddr, io_cap);
   4115 }
   4116 
   4117 int adapter_cancel_bonding(struct btd_adapter *adapter, bdaddr_t *bdaddr)
   4118 {
   4119 	return adapter_ops->cancel_bonding(adapter->dev_id, bdaddr);
   4120 }
   4121 
   4122 int btd_adapter_read_local_oob_data(struct btd_adapter *adapter)
   4123 {
   4124 	return adapter_ops->read_local_oob_data(adapter->dev_id);
   4125 }
   4126 
   4127 int btd_adapter_add_remote_oob_data(struct btd_adapter *adapter,
   4128 			bdaddr_t *bdaddr, uint8_t *hash, uint8_t *randomizer)
   4129 {
   4130 	return adapter_ops->add_remote_oob_data(adapter->dev_id, bdaddr, hash,
   4131 								randomizer);
   4132 }
   4133 
   4134 int btd_adapter_remove_remote_oob_data(struct btd_adapter *adapter,
   4135 							bdaddr_t *bdaddr)
   4136 {
   4137 	return adapter_ops->remove_remote_oob_data(adapter->dev_id, bdaddr);
   4138 }
   4139