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 #include <stdio.h>
     30 #include <stdlib.h>
     31 #include <unistd.h>
     32 #include <fcntl.h>
     33 #include <sys/stat.h>
     34 #include <sys/ioctl.h>
     35 #include <errno.h>
     36 
     37 #include <bluetooth/bluetooth.h>
     38 #include <bluetooth/uuid.h>
     39 #include <bluetooth/sdp.h>
     40 #include <bluetooth/sdp_lib.h>
     41 
     42 #include <glib.h>
     43 #include <dbus/dbus.h>
     44 #include <gdbus.h>
     45 
     46 #include "log.h"
     47 #include "textfile.h"
     48 
     49 #include "att.h"
     50 #include "hcid.h"
     51 #include "adapter.h"
     52 #include "device.h"
     53 #include "dbus-common.h"
     54 #include "event.h"
     55 #include "error.h"
     56 #include "glib-helper.h"
     57 #include "gattrib.h"
     58 #include "gatt.h"
     59 #include "agent.h"
     60 #include "sdp-xml.h"
     61 #include "storage.h"
     62 #include "btio.h"
     63 #include "../attrib/client.h"
     64 
     65 #define DISCONNECT_TIMER	2
     66 #define DISCOVERY_TIMER		2
     67 
     68 /* When all services should trust a remote device */
     69 #define GLOBAL_TRUST "[all]"
     70 
     71 struct btd_disconnect_data {
     72 	guint id;
     73 	disconnect_watch watch;
     74 	void *user_data;
     75 	GDestroyNotify destroy;
     76 };
     77 
     78 struct bonding_req {
     79 	DBusConnection *conn;
     80 	DBusMessage *msg;
     81 	GIOChannel *io;
     82 	guint listener_id;
     83 	struct btd_device *device;
     84 };
     85 
     86 struct authentication_req {
     87 	auth_type_t type;
     88 	void *cb;
     89 	struct agent *agent;
     90 	struct btd_device *device;
     91 };
     92 
     93 struct browse_req {
     94 	DBusConnection *conn;
     95 	DBusMessage *msg;
     96 	GAttrib *attrib;
     97 	struct btd_device *device;
     98 	GSList *match_uuids;
     99 	GSList *profiles_added;
    100 	GSList *profiles_removed;
    101 	sdp_list_t *records;
    102 	int search_uuid;
    103 	int reconnect_attempt;
    104 	guint listener_id;
    105 };
    106 
    107 struct btd_device {
    108 	bdaddr_t	bdaddr;
    109 	device_type_t	type;
    110 	gchar		*path;
    111 	char		name[MAX_NAME_LENGTH + 1];
    112 	char		*alias;
    113 	struct btd_adapter	*adapter;
    114 	GSList		*uuids;
    115 	GSList		*services;		/* Primary services path */
    116 	GSList		*primaries;		/* List of primary services */
    117 	GSList		*drivers;		/* List of device drivers */
    118 	GSList		*watches;		/* List of disconnect_data */
    119 	gboolean	temporary;
    120 	struct agent	*agent;
    121 	guint		disconn_timer;
    122 	guint		discov_timer;
    123 	struct browse_req *browse;		/* service discover request */
    124 	struct bonding_req *bonding;
    125 	struct authentication_req *authr;	/* authentication request */
    126 	GSList		*disconnects;		/* disconnects message */
    127 
    128 	gboolean	connected;
    129 
    130 	sdp_list_t	*tmp_records;
    131 
    132 	gboolean	trusted;
    133 	gboolean	paired;
    134 	gboolean	blocked;
    135 	gboolean	bonded;
    136 
    137 	gboolean	authorizing;
    138 	gint		ref;
    139 };
    140 
    141 static uint16_t uuid_list[] = {
    142 	L2CAP_UUID,
    143 	PNP_INFO_SVCLASS_ID,
    144 	PUBLIC_BROWSE_GROUP,
    145 	0
    146 };
    147 
    148 static GSList *device_drivers = NULL;
    149 
    150 static void browse_request_free(struct browse_req *req)
    151 {
    152 	if (req->listener_id)
    153 		g_dbus_remove_watch(req->conn, req->listener_id);
    154 	if (req->msg)
    155 		dbus_message_unref(req->msg);
    156 	if (req->conn)
    157 		dbus_connection_unref(req->conn);
    158 	if (req->device)
    159 		btd_device_unref(req->device);
    160 	g_slist_foreach(req->profiles_added, (GFunc) g_free, NULL);
    161 	g_slist_free(req->profiles_added);
    162 	g_slist_free(req->profiles_removed);
    163 	if (req->records)
    164 		sdp_list_free(req->records, (sdp_free_func_t) sdp_record_free);
    165 
    166 	if (req->attrib)
    167 		g_attrib_unref(req->attrib);
    168 
    169 	g_free(req);
    170 }
    171 
    172 static void browse_request_cancel(struct browse_req *req)
    173 {
    174 	struct btd_device *device = req->device;
    175 	struct btd_adapter *adapter = device->adapter;
    176 	bdaddr_t src;
    177 
    178 	if (device_is_creating(device, NULL))
    179 		device_set_temporary(device, TRUE);
    180 
    181 	adapter_get_address(adapter, &src);
    182 
    183 	bt_cancel_discovery(&src, &device->bdaddr);
    184 
    185 	device->browse = NULL;
    186 	browse_request_free(req);
    187 }
    188 
    189 static void device_free(gpointer user_data)
    190 {
    191 	struct btd_device *device = user_data;
    192 	struct btd_adapter *adapter = device->adapter;
    193 	struct agent *agent = adapter_get_agent(adapter);
    194 
    195 	if (device->agent)
    196 		agent_free(device->agent);
    197 
    198 	if (agent && (agent_is_busy(agent, device) ||
    199 				agent_is_busy(agent, device->authr)))
    200 		agent_cancel(agent);
    201 
    202 	g_slist_foreach(device->services, (GFunc) g_free, NULL);
    203 	g_slist_free(device->services);
    204 
    205 	g_slist_foreach(device->uuids, (GFunc) g_free, NULL);
    206 	g_slist_free(device->uuids);
    207 
    208 	g_slist_foreach(device->primaries, (GFunc) g_free, NULL);
    209 	g_slist_free(device->primaries);
    210 
    211 	if (device->tmp_records)
    212 		sdp_list_free(device->tmp_records,
    213 					(sdp_free_func_t) sdp_record_free);
    214 
    215 	if (device->disconn_timer)
    216 		g_source_remove(device->disconn_timer);
    217 
    218 	if (device->discov_timer)
    219 		g_source_remove(device->discov_timer);
    220 
    221 	DBG("%p", device);
    222 
    223 	g_free(device->authr);
    224 	g_free(device->path);
    225 	g_free(device->alias);
    226 	g_free(device);
    227 }
    228 
    229 gboolean device_is_paired(struct btd_device *device)
    230 {
    231 	return device->paired;
    232 }
    233 
    234 gboolean device_is_trusted(struct btd_device *device)
    235 {
    236 	return device->trusted;
    237 }
    238 
    239 static DBusMessage *get_properties(DBusConnection *conn,
    240 				DBusMessage *msg, void *user_data)
    241 {
    242 	struct btd_device *device = user_data;
    243 	struct btd_adapter *adapter = device->adapter;
    244 	DBusMessage *reply;
    245 	DBusMessageIter iter;
    246 	DBusMessageIter dict;
    247 	bdaddr_t src;
    248 	char name[MAX_NAME_LENGTH + 1], srcaddr[18], dstaddr[18];
    249 	char **str;
    250 	const char *ptr;
    251 	dbus_bool_t boolean;
    252 	uint32_t class;
    253 	int i;
    254 	GSList *l;
    255 
    256 	ba2str(&device->bdaddr, dstaddr);
    257 
    258 	reply = dbus_message_new_method_return(msg);
    259 	if (!reply)
    260 		return NULL;
    261 
    262 	dbus_message_iter_init_append(reply, &iter);
    263 
    264 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
    265 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
    266 			DBUS_TYPE_STRING_AS_STRING DBUS_TYPE_VARIANT_AS_STRING
    267 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
    268 
    269 	/* Address */
    270 	ptr = dstaddr;
    271 	dict_append_entry(&dict, "Address", DBUS_TYPE_STRING, &ptr);
    272 
    273 	/* Name */
    274 	ptr = NULL;
    275 	memset(name, 0, sizeof(name));
    276 	adapter_get_address(adapter, &src);
    277 	ba2str(&src, srcaddr);
    278 
    279 	ptr = device->name;
    280 	dict_append_entry(&dict, "Name", DBUS_TYPE_STRING, &ptr);
    281 
    282 #ifdef ANDROID
    283 	/* Alias (Android doesn't fallback to name or address) */
    284 	if (device->alias != NULL) {
    285 		ptr = device->alias;
    286 		dict_append_entry(&dict, "Alias", DBUS_TYPE_STRING, &ptr);
    287 	}
    288 #else
    289 	/* Alias (fallback to name or address) */
    290 	if (device->alias != NULL)
    291 		ptr = device->alias;
    292 	else if (strlen(ptr) == 0) {
    293 		g_strdelimit(dstaddr, ":", '-');
    294 		ptr = dstaddr;
    295 	}
    296 
    297 	dict_append_entry(&dict, "Alias", DBUS_TYPE_STRING, &ptr);
    298 #endif
    299 
    300 	/* Class */
    301 	if (read_remote_class(&src, &device->bdaddr, &class) == 0) {
    302 		const char *icon = class_to_icon(class);
    303 
    304 		dict_append_entry(&dict, "Class", DBUS_TYPE_UINT32, &class);
    305 
    306 		if (icon)
    307 			dict_append_entry(&dict, "Icon",
    308 						DBUS_TYPE_STRING, &icon);
    309 	}
    310 
    311 	/* Paired */
    312 	boolean = device_is_paired(device);
    313 	dict_append_entry(&dict, "Paired", DBUS_TYPE_BOOLEAN, &boolean);
    314 
    315 	/* Trusted */
    316 	boolean = device_is_trusted(device);
    317 	dict_append_entry(&dict, "Trusted", DBUS_TYPE_BOOLEAN, &boolean);
    318 
    319 	/* Blocked */
    320 	boolean = device->blocked;
    321 	dict_append_entry(&dict, "Blocked", DBUS_TYPE_BOOLEAN, &boolean);
    322 
    323 	/* Connected */
    324 	dict_append_entry(&dict, "Connected", DBUS_TYPE_BOOLEAN,
    325 							&device->connected);
    326 
    327 	/* UUIDs */
    328 	str = g_new0(char *, g_slist_length(device->uuids) + 1);
    329 	for (i = 0, l = device->uuids; l; l = l->next, i++)
    330 		str[i] = l->data;
    331 	dict_append_array(&dict, "UUIDs", DBUS_TYPE_STRING, &str, i);
    332 	g_free(str);
    333 
    334 	/* Services */
    335 	str = g_new0(char *, g_slist_length(device->services) + 1);
    336 	for (i = 0, l = device->services; l; l = l->next, i++)
    337 		str[i] = l->data;
    338 	dict_append_array(&dict, "Services", DBUS_TYPE_OBJECT_PATH, &str, i);
    339 	g_free(str);
    340 
    341 	/* Adapter */
    342 	ptr = adapter_get_path(adapter);
    343 	dict_append_entry(&dict, "Adapter", DBUS_TYPE_OBJECT_PATH, &ptr);
    344 
    345 	dbus_message_iter_close_container(&iter, &dict);
    346 
    347 	return reply;
    348 }
    349 
    350 static DBusMessage *set_alias(DBusConnection *conn, DBusMessage *msg,
    351 					const char *alias, void *data)
    352 {
    353 	struct btd_device *device = data;
    354 	struct btd_adapter *adapter = device->adapter;
    355 	char srcaddr[18], dstaddr[18];
    356 	bdaddr_t src;
    357 	int err;
    358 
    359 	/* No change */
    360 	if ((device->alias == NULL && g_str_equal(alias, "")) ||
    361 			g_strcmp0(device->alias, alias) == 0)
    362 		return dbus_message_new_method_return(msg);
    363 
    364 	adapter_get_address(adapter, &src);
    365 	ba2str(&src, srcaddr);
    366 	ba2str(&device->bdaddr, dstaddr);
    367 
    368 	/* Remove alias if empty string */
    369 	err = write_device_alias(srcaddr, dstaddr,
    370 			g_str_equal(alias, "") ? NULL : alias);
    371 	if (err < 0)
    372 		return btd_error_failed(msg, strerror(-err));
    373 
    374 	g_free(device->alias);
    375 	device->alias = g_str_equal(alias, "") ? NULL : g_strdup(alias);
    376 
    377 	emit_property_changed(conn, dbus_message_get_path(msg),
    378 				DEVICE_INTERFACE, "Alias",
    379 				DBUS_TYPE_STRING, &alias);
    380 
    381 	return dbus_message_new_method_return(msg);
    382 }
    383 
    384 static DBusMessage *set_trust(DBusConnection *conn, DBusMessage *msg,
    385 					gboolean value, void *data)
    386 {
    387 	struct btd_device *device = data;
    388 	struct btd_adapter *adapter = device->adapter;
    389 	char srcaddr[18], dstaddr[18];
    390 	bdaddr_t src;
    391 	int err;
    392 
    393 	if (device->trusted == value)
    394 		return dbus_message_new_method_return(msg);
    395 
    396 	adapter_get_address(adapter, &src);
    397 	ba2str(&src, srcaddr);
    398 	ba2str(&device->bdaddr, dstaddr);
    399 
    400 	err = write_trust(srcaddr, dstaddr, GLOBAL_TRUST, value);
    401 	if (err < 0)
    402 		return btd_error_failed(msg, strerror(-err));
    403 
    404 	device->trusted = value;
    405 
    406 	emit_property_changed(conn, dbus_message_get_path(msg),
    407 				DEVICE_INTERFACE, "Trusted",
    408 				DBUS_TYPE_BOOLEAN, &value);
    409 
    410 	return dbus_message_new_method_return(msg);
    411 }
    412 
    413 static void driver_remove(struct btd_device_driver *driver,
    414 						struct btd_device *device)
    415 {
    416 	driver->remove(device);
    417 
    418 	device->drivers = g_slist_remove(device->drivers, driver);
    419 }
    420 
    421 static gboolean do_disconnect(gpointer user_data)
    422 {
    423 	struct btd_device *device = user_data;
    424 
    425 	device->disconn_timer = 0;
    426 
    427 	btd_adapter_disconnect_device(device->adapter, &device->bdaddr);
    428 
    429 	return FALSE;
    430 }
    431 
    432 static int device_block(DBusConnection *conn, struct btd_device *device)
    433 {
    434 	int err;
    435 	bdaddr_t src;
    436 
    437 	if (device->blocked)
    438 		return 0;
    439 
    440 	if (device->connected)
    441 		do_disconnect(device);
    442 
    443 	g_slist_foreach(device->drivers, (GFunc) driver_remove, device);
    444 
    445 	err = btd_adapter_block_address(device->adapter, &device->bdaddr);
    446 	if (err < 0)
    447 		return err;
    448 
    449 	device->blocked = TRUE;
    450 
    451 	adapter_get_address(device->adapter, &src);
    452 
    453 	err = write_blocked(&src, &device->bdaddr, TRUE);
    454 	if (err < 0)
    455 		error("write_blocked(): %s (%d)", strerror(-err), -err);
    456 
    457 	device_set_temporary(device, FALSE);
    458 
    459 	emit_property_changed(conn, device->path, DEVICE_INTERFACE, "Blocked",
    460 					DBUS_TYPE_BOOLEAN, &device->blocked);
    461 
    462 	return 0;
    463 }
    464 
    465 static int device_unblock(DBusConnection *conn, struct btd_device *device,
    466 							gboolean silent)
    467 {
    468 	int err;
    469 	bdaddr_t src;
    470 
    471 	if (!device->blocked)
    472 		return 0;
    473 
    474 	err = btd_adapter_unblock_address(device->adapter, &device->bdaddr);
    475 	if (err < 0)
    476 		return err;
    477 
    478 	device->blocked = FALSE;
    479 
    480 	adapter_get_address(device->adapter, &src);
    481 
    482 	err = write_blocked(&src, &device->bdaddr, FALSE);
    483 	if (err < 0)
    484 		error("write_blocked(): %s (%d)", strerror(-err), -err);
    485 
    486 	if (!silent) {
    487 		emit_property_changed(conn, device->path,
    488 					DEVICE_INTERFACE, "Blocked",
    489 					DBUS_TYPE_BOOLEAN, &device->blocked);
    490 		device_probe_drivers(device, device->uuids);
    491 	}
    492 
    493 	return 0;
    494 }
    495 
    496 static DBusMessage *set_blocked(DBusConnection *conn, DBusMessage *msg,
    497 						gboolean value, void *data)
    498 {
    499 	struct btd_device *device = data;
    500 	int err;
    501 
    502 	if (value)
    503 		err = device_block(conn, device);
    504 	else
    505 		err = device_unblock(conn, device, FALSE);
    506 
    507 	switch (-err) {
    508 	case 0:
    509 		return dbus_message_new_method_return(msg);
    510 	case EINVAL:
    511 		return btd_error_failed(msg, "Kernel lacks blacklist support");
    512 	default:
    513 		return btd_error_failed(msg, strerror(-err));
    514 	}
    515 }
    516 
    517 static DBusMessage *set_property(DBusConnection *conn,
    518 				DBusMessage *msg, void *data)
    519 {
    520 	DBusMessageIter iter;
    521 	DBusMessageIter sub;
    522 	const char *property;
    523 
    524 	if (!dbus_message_iter_init(msg, &iter))
    525 		return btd_error_invalid_args(msg);
    526 
    527 	if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_STRING)
    528 		return btd_error_invalid_args(msg);
    529 
    530 	dbus_message_iter_get_basic(&iter, &property);
    531 	dbus_message_iter_next(&iter);
    532 
    533 	if (dbus_message_iter_get_arg_type(&iter) != DBUS_TYPE_VARIANT)
    534 		return btd_error_invalid_args(msg);
    535 	dbus_message_iter_recurse(&iter, &sub);
    536 
    537 	if (g_str_equal("Trusted", property)) {
    538 		dbus_bool_t value;
    539 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
    540 			return btd_error_invalid_args(msg);
    541 		dbus_message_iter_get_basic(&sub, &value);
    542 
    543 		return set_trust(conn, msg, value, data);
    544 	} else if (g_str_equal("Alias", property)) {
    545 		const char *alias;
    546 
    547 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_STRING)
    548 			return btd_error_invalid_args(msg);
    549 		dbus_message_iter_get_basic(&sub, &alias);
    550 
    551 		return set_alias(conn, msg, alias, data);
    552 	} else if (g_str_equal("Blocked", property)) {
    553 		dbus_bool_t value;
    554 
    555 		if (dbus_message_iter_get_arg_type(&sub) != DBUS_TYPE_BOOLEAN)
    556 			return btd_error_invalid_args(msg);
    557 
    558 		dbus_message_iter_get_basic(&sub, &value);
    559 
    560 		return set_blocked(conn, msg, value, data);
    561 	}
    562 
    563 	return btd_error_invalid_args(msg);
    564 }
    565 
    566 static void discover_services_req_exit(DBusConnection *conn, void *user_data)
    567 {
    568 	struct browse_req *req = user_data;
    569 
    570 	DBG("DiscoverServices requestor exited");
    571 
    572 	browse_request_cancel(req);
    573 }
    574 
    575 static DBusMessage *discover_services(DBusConnection *conn,
    576 					DBusMessage *msg, void *user_data)
    577 {
    578 	struct btd_device *device = user_data;
    579 	const char *pattern;
    580 	int err;
    581 
    582 	if (device->browse)
    583 		return btd_error_in_progress(msg);
    584 
    585 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &pattern,
    586 						DBUS_TYPE_INVALID) == FALSE)
    587 		return btd_error_invalid_args(msg);
    588 
    589 	if (strlen(pattern) == 0) {
    590 		err = device_browse_sdp(device, conn, msg, NULL, FALSE);
    591 		if (err < 0)
    592 			goto fail;
    593 	} else {
    594 		uuid_t uuid;
    595 
    596 		if (bt_string2uuid(&uuid, pattern) < 0)
    597 			return btd_error_invalid_args(msg);
    598 
    599 		sdp_uuid128_to_uuid(&uuid);
    600 
    601 		err = device_browse_sdp(device, conn, msg, &uuid, FALSE);
    602 		if (err < 0)
    603 			goto fail;
    604 	}
    605 
    606 	return NULL;
    607 
    608 fail:
    609 	return btd_error_failed(msg, strerror(-err));
    610 }
    611 
    612 static const char *browse_request_get_requestor(struct browse_req *req)
    613 {
    614 	if (!req->msg)
    615 		return NULL;
    616 
    617 	return dbus_message_get_sender(req->msg);
    618 }
    619 
    620 static void iter_append_record(DBusMessageIter *dict, uint32_t handle,
    621 							const char *record)
    622 {
    623 	DBusMessageIter entry;
    624 
    625 	dbus_message_iter_open_container(dict, DBUS_TYPE_DICT_ENTRY,
    626 							NULL, &entry);
    627 
    628 	dbus_message_iter_append_basic(&entry, DBUS_TYPE_UINT32, &handle);
    629 
    630 	dbus_message_iter_append_basic(&entry, DBUS_TYPE_STRING, &record);
    631 
    632 	dbus_message_iter_close_container(dict, &entry);
    633 }
    634 
    635 static void discover_services_reply(struct browse_req *req, int err,
    636 							sdp_list_t *recs)
    637 {
    638 	DBusMessage *reply;
    639 	DBusMessageIter iter, dict;
    640 	sdp_list_t *seq;
    641 
    642 	if (err) {
    643 		const char *err_if;
    644 
    645 		if (err == -EHOSTDOWN)
    646 			err_if = ERROR_INTERFACE ".ConnectionAttemptFailed";
    647 		else
    648 			err_if = ERROR_INTERFACE ".Failed";
    649 
    650 		reply = dbus_message_new_error(req->msg, err_if,
    651 							strerror(-err));
    652 		g_dbus_send_message(req->conn, reply);
    653 		return;
    654 	}
    655 
    656 	reply = dbus_message_new_method_return(req->msg);
    657 	if (!reply)
    658 		return;
    659 
    660 	dbus_message_iter_init_append(reply, &iter);
    661 
    662 	dbus_message_iter_open_container(&iter, DBUS_TYPE_ARRAY,
    663 			DBUS_DICT_ENTRY_BEGIN_CHAR_AS_STRING
    664 			DBUS_TYPE_UINT32_AS_STRING DBUS_TYPE_STRING_AS_STRING
    665 			DBUS_DICT_ENTRY_END_CHAR_AS_STRING, &dict);
    666 
    667 	for (seq = recs; seq; seq = seq->next) {
    668 		sdp_record_t *rec = (sdp_record_t *) seq->data;
    669 		GString *result;
    670 
    671 		if (!rec)
    672 			break;
    673 
    674 		result = g_string_new(NULL);
    675 
    676 		convert_sdp_record_to_xml(rec, result,
    677 				(void *) g_string_append);
    678 
    679 		if (result->len)
    680 			iter_append_record(&dict, rec->handle, result->str);
    681 
    682 		g_string_free(result, TRUE);
    683 	}
    684 
    685 	dbus_message_iter_close_container(&iter, &dict);
    686 
    687 	g_dbus_send_message(req->conn, reply);
    688 }
    689 
    690 static DBusMessage *cancel_discover(DBusConnection *conn,
    691 					DBusMessage *msg, void *user_data)
    692 {
    693 	struct btd_device *device = user_data;
    694 	const char *sender = dbus_message_get_sender(msg);
    695 	const char *requestor;
    696 
    697 	if (!device->browse)
    698 		return btd_error_does_not_exist(msg);
    699 
    700 	if (!dbus_message_is_method_call(device->browse->msg, DEVICE_INTERFACE,
    701 					"DiscoverServices"))
    702 		return btd_error_not_authorized(msg);
    703 
    704 	requestor = browse_request_get_requestor(device->browse);
    705 
    706 	/* only the discover requestor can cancel the inquiry process */
    707 	if (!requestor || !g_str_equal(requestor, sender))
    708 		return btd_error_not_authorized(msg);
    709 
    710 	discover_services_reply(device->browse, -ECANCELED, NULL);
    711 
    712 	browse_request_cancel(device->browse);
    713 
    714 	return dbus_message_new_method_return(msg);
    715 }
    716 
    717 static void bonding_request_cancel(struct bonding_req *bonding)
    718 {
    719 	struct btd_device *device = bonding->device;
    720 	struct btd_adapter *adapter = device->adapter;
    721 
    722 	adapter_cancel_bonding(adapter, &device->bdaddr);
    723 }
    724 
    725 void device_request_disconnect(struct btd_device *device, DBusMessage *msg)
    726 {
    727 	DBusConnection *conn = get_dbus_connection();
    728 
    729 	if (device->bonding)
    730 		bonding_request_cancel(device->bonding);
    731 
    732 	if (device->browse) {
    733 		discover_services_reply(device->browse, -ECANCELED, NULL);
    734 		browse_request_cancel(device->browse);
    735 	}
    736 
    737 	if (msg)
    738 		device->disconnects = g_slist_append(device->disconnects,
    739 						dbus_message_ref(msg));
    740 
    741 	if (device->disconn_timer)
    742 		return;
    743 
    744 	while (device->watches) {
    745 		struct btd_disconnect_data *data = device->watches->data;
    746 
    747 		if (data->watch)
    748 			/* temporary is set if device is going to be removed */
    749 			data->watch(device, device->temporary,
    750 							data->user_data);
    751 
    752 		/* Check if the watch has been removed by callback function */
    753 		if (!g_slist_find(device->watches, data))
    754 			continue;
    755 
    756 		device->watches = g_slist_remove(device->watches, data);
    757 		g_free(data);
    758 	}
    759 
    760 	device->disconn_timer = g_timeout_add_seconds(DISCONNECT_TIMER,
    761 						do_disconnect, device);
    762 
    763 	g_dbus_emit_signal(conn, device->path,
    764 			DEVICE_INTERFACE, "DisconnectRequested",
    765 			DBUS_TYPE_INVALID);
    766 }
    767 
    768 static DBusMessage *disconnect(DBusConnection *conn, DBusMessage *msg,
    769 							void *user_data)
    770 {
    771 	struct btd_device *device = user_data;
    772 
    773 	if (!device->connected)
    774 		return btd_error_not_connected(msg);
    775 
    776 	device_request_disconnect(device, msg);
    777 
    778 	return NULL;
    779 }
    780 
    781 static DBusMessage *get_service_attribute_value_reply(DBusMessage *msg, DBusConnection *conn,
    782 							sdp_data_t *attr)
    783 {
    784 	DBusMessage *reply;
    785 	DBusMessageIter iter;
    786 
    787 	reply = dbus_message_new_method_return(msg);
    788 	if (!reply)
    789 		return NULL;
    790 	sdp_data_t *curr;
    791 	sdp_list_t *ap = 0;
    792 	for (; attr; attr = attr->next) {
    793 		sdp_list_t *pds = 0;
    794 		for (curr = attr->val.dataseq; curr; curr = curr->next)
    795 			pds = sdp_list_append(pds, curr->val.dataseq);
    796 		ap = sdp_list_append(ap, pds);
    797 	}
    798 
    799 	int ch = sdp_get_proto_port(ap, RFCOMM_UUID);
    800 	sdp_list_foreach(ap, (sdp_list_func_t) sdp_list_free, NULL);
    801 	sdp_list_free(ap, NULL);
    802 	ap = NULL;
    803 
    804 	dbus_message_append_args(reply, DBUS_TYPE_INT32, &ch, DBUS_TYPE_INVALID);
    805 
    806 	return reply;
    807 }
    808 
    809 static DBusMessage *get_service_attribute_value(DBusConnection *conn,
    810 						DBusMessage *msg,
    811 						void *user_data)
    812 {
    813 	struct btd_device *device = user_data;
    814 	const sdp_record_t *rec;
    815 	sdp_data_t *attr_data;
    816 	const char *pattern;
    817 	uint16_t attrId;
    818 	int err;
    819 
    820 	if (dbus_message_get_args(msg, NULL, DBUS_TYPE_STRING, &pattern,
    821 					DBUS_TYPE_UINT16, &attrId,
    822 					DBUS_TYPE_INVALID) == FALSE)
    823 		goto fail;
    824 
    825 	if (strlen(pattern) == 0)
    826 		return btd_error_invalid_args(msg);
    827 
    828 	rec = btd_device_get_record(device, pattern);
    829 	if (rec == NULL) {
    830 		error("rec is NULL");
    831 		goto fail;
    832 	}
    833 
    834 	attr_data = sdp_data_get(rec, attrId);
    835 
    836 	if (attr_data == NULL) {
    837 		error("attr in null");
    838 		goto fail;
    839 	}
    840 	return get_service_attribute_value_reply(msg, conn, attr_data);
    841 fail:
    842 	return g_dbus_create_error(msg, ERROR_INTERFACE ".Failed",
    843 					"GetServiceAttribute Failed");
    844 }
    845 
    846 static GDBusMethodTable device_methods[] = {
    847 	{ "GetProperties",	"",	"a{sv}",	get_properties	},
    848 	{ "SetProperty",	"sv",	"",		set_property	},
    849 	{ "DiscoverServices",	"s",	"a{us}",	discover_services,
    850 						G_DBUS_METHOD_FLAG_ASYNC},
    851 	{ "CancelDiscovery",	"",	"",		cancel_discover	},
    852 	{ "Disconnect",		"",	"",		disconnect,
    853 						G_DBUS_METHOD_FLAG_ASYNC},
    854 	{ "GetServiceAttributeValue",  "sq", "i",       get_service_attribute_value},
    855 	{ }
    856 };
    857 
    858 static GDBusSignalTable device_signals[] = {
    859 	{ "PropertyChanged",		"sv"	},
    860 	{ "DisconnectRequested",	""	},
    861 	{ }
    862 };
    863 
    864 gboolean device_is_connected(struct btd_device *device)
    865 {
    866 	return device->connected;
    867 }
    868 
    869 void device_add_connection(struct btd_device *device, DBusConnection *conn)
    870 {
    871 	if (device->connected) {
    872 		char addr[18];
    873 		ba2str(&device->bdaddr, addr);
    874 		error("Device %s is already connected", addr);
    875 		return;
    876 	}
    877 
    878 	device->connected = TRUE;
    879 
    880 	emit_property_changed(conn, device->path,
    881 					DEVICE_INTERFACE, "Connected",
    882 					DBUS_TYPE_BOOLEAN, &device->connected);
    883 }
    884 
    885 void device_remove_connection(struct btd_device *device, DBusConnection *conn)
    886 {
    887 	if (!device->connected) {
    888 		char addr[18];
    889 		ba2str(&device->bdaddr, addr);
    890 		error("Device %s isn't connected", addr);
    891 		return;
    892 	}
    893 
    894 	device->connected = FALSE;
    895 
    896 	if (device->disconn_timer > 0) {
    897 		g_source_remove(device->disconn_timer);
    898 		device->disconn_timer = 0;
    899 	}
    900 
    901 	while (device->disconnects) {
    902 		DBusMessage *msg = device->disconnects->data;
    903 
    904 		g_dbus_send_reply(conn, msg, DBUS_TYPE_INVALID);
    905 		device->disconnects = g_slist_remove(device->disconnects, msg);
    906 	}
    907 
    908 	if (device_is_paired(device) && !device->bonded)
    909 		device_set_paired(device, FALSE);
    910 
    911 	emit_property_changed(conn, device->path,
    912 					DEVICE_INTERFACE, "Connected",
    913 					DBUS_TYPE_BOOLEAN, &device->connected);
    914 }
    915 
    916 guint device_add_disconnect_watch(struct btd_device *device,
    917 				disconnect_watch watch, void *user_data,
    918 				GDestroyNotify destroy)
    919 {
    920 	struct btd_disconnect_data *data;
    921 	static guint id = 0;
    922 
    923 	data = g_new0(struct btd_disconnect_data, 1);
    924 	data->id = ++id;
    925 	data->watch = watch;
    926 	data->user_data = user_data;
    927 	data->destroy = destroy;
    928 
    929 	device->watches = g_slist_append(device->watches, data);
    930 
    931 	return data->id;
    932 }
    933 
    934 void device_remove_disconnect_watch(struct btd_device *device, guint id)
    935 {
    936 	GSList *l;
    937 
    938 	for (l = device->watches; l; l = l->next) {
    939 		struct btd_disconnect_data *data = l->data;
    940 
    941 		if (data->id == id) {
    942 			device->watches = g_slist_remove(device->watches,
    943 							data);
    944 			if (data->destroy)
    945 				data->destroy(data->user_data);
    946 			g_free(data);
    947 			return;
    948 		}
    949 	}
    950 }
    951 
    952 struct btd_device *device_create(DBusConnection *conn,
    953 				struct btd_adapter *adapter,
    954 				const gchar *address, device_type_t type)
    955 {
    956 	gchar *address_up;
    957 	struct btd_device *device;
    958 	const gchar *adapter_path = adapter_get_path(adapter);
    959 	bdaddr_t src;
    960 	char srcaddr[18], alias[MAX_NAME_LENGTH + 1];
    961 
    962 	device = g_try_malloc0(sizeof(struct btd_device));
    963 	if (device == NULL)
    964 		return NULL;
    965 
    966 	address_up = g_ascii_strup(address, -1);
    967 	device->path = g_strdup_printf("%s/dev_%s", adapter_path, address_up);
    968 	g_strdelimit(device->path, ":", '_');
    969 	g_free(address_up);
    970 
    971 	DBG("Creating device %s", device->path);
    972 
    973 	if (g_dbus_register_interface(conn, device->path, DEVICE_INTERFACE,
    974 				device_methods, device_signals, NULL,
    975 				device, device_free) == FALSE) {
    976 		device_free(device);
    977 		return NULL;
    978 	}
    979 
    980 	str2ba(address, &device->bdaddr);
    981 	device->adapter = adapter;
    982 	device->type = type;
    983 	adapter_get_address(adapter, &src);
    984 	ba2str(&src, srcaddr);
    985 	read_device_name(srcaddr, address, device->name);
    986 	if (read_device_alias(srcaddr, address, alias, sizeof(alias)) == 0)
    987 		device->alias = g_strdup(alias);
    988 	device->trusted = read_trust(&src, address, GLOBAL_TRUST);
    989 
    990 	if (read_blocked(&src, &device->bdaddr))
    991 		device_block(conn, device);
    992 
    993 	if (read_link_key(&src, &device->bdaddr, NULL, NULL) == 0) {
    994 		device->paired = TRUE;
    995 		device_set_bonded(device, TRUE);
    996 	}
    997 
    998 	return btd_device_ref(device);
    999 }
   1000 
   1001 void device_set_name(struct btd_device *device, const char *name)
   1002 {
   1003 	DBusConnection *conn = get_dbus_connection();
   1004 
   1005 	if (strncmp(name, device->name, MAX_NAME_LENGTH) == 0)
   1006 		return;
   1007 
   1008 	strncpy(device->name, name, MAX_NAME_LENGTH);
   1009 
   1010 	emit_property_changed(conn, device->path,
   1011 				DEVICE_INTERFACE, "Name",
   1012 				DBUS_TYPE_STRING, &name);
   1013 
   1014 	if (device->alias != NULL)
   1015 		return;
   1016 
   1017 	emit_property_changed(conn, device->path,
   1018 				DEVICE_INTERFACE, "Alias",
   1019 				DBUS_TYPE_STRING, &name);
   1020 }
   1021 
   1022 void device_get_name(struct btd_device *device, char *name, size_t len)
   1023 {
   1024 	strncpy(name, device->name, len);
   1025 }
   1026 
   1027 device_type_t device_get_type(struct btd_device *device)
   1028 {
   1029 	return device->type;
   1030 }
   1031 
   1032 void device_remove_bonding(struct btd_device *device)
   1033 {
   1034 	char filename[PATH_MAX + 1];
   1035 	char srcaddr[18], dstaddr[18];
   1036 	bdaddr_t bdaddr;
   1037 
   1038 	adapter_get_address(device->adapter, &bdaddr);
   1039 	ba2str(&bdaddr, srcaddr);
   1040 	ba2str(&device->bdaddr, dstaddr);
   1041 
   1042 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr,
   1043 			"linkkeys");
   1044 
   1045 	/* Delete the link key from storage */
   1046 	textfile_casedel(filename, dstaddr);
   1047 	device_set_bonded(device, FALSE);
   1048 
   1049 	btd_adapter_remove_bonding(device->adapter, &device->bdaddr);
   1050 }
   1051 
   1052 static void device_remove_stored(struct btd_device *device)
   1053 {
   1054 	bdaddr_t src;
   1055 	char addr[18];
   1056 	DBusConnection *conn = get_dbus_connection();
   1057 
   1058 	adapter_get_address(device->adapter, &src);
   1059 	ba2str(&device->bdaddr, addr);
   1060 
   1061 	if (device->paired)
   1062 		device_remove_bonding(device);
   1063 	delete_entry(&src, "profiles", addr);
   1064 	delete_entry(&src, "trusts", addr);
   1065 	delete_entry(&src, "types", addr);
   1066 	delete_entry(&src, "primary", addr);
   1067 	delete_all_records(&src, &device->bdaddr);
   1068 	delete_device_service(&src, &device->bdaddr);
   1069 
   1070 	if (device->blocked)
   1071 		device_unblock(conn, device, TRUE);
   1072 }
   1073 
   1074 void device_remove(struct btd_device *device, gboolean remove_stored)
   1075 {
   1076 
   1077 	DBG("Removing device %s", device->path);
   1078 
   1079 	if (device->agent)
   1080 		agent_free(device->agent);
   1081 
   1082 	if (device->bonding) {
   1083 		uint8_t status;
   1084 
   1085 		if (device->connected)
   1086 			status = HCI_OE_USER_ENDED_CONNECTION;
   1087 		else
   1088 			status = HCI_PAGE_TIMEOUT;
   1089 
   1090 		device_cancel_bonding(device, status);
   1091 	}
   1092 
   1093 	if (device->browse) {
   1094 		discover_services_reply(device->browse, -ECANCELED, NULL);
   1095 		browse_request_cancel(device->browse);
   1096 	}
   1097 
   1098 	if (device->connected)
   1099 		do_disconnect(device);
   1100 
   1101 	if (remove_stored)
   1102 		device_remove_stored(device);
   1103 
   1104 	g_slist_foreach(device->drivers, (GFunc) driver_remove, device);
   1105 	g_slist_free(device->drivers);
   1106 	device->drivers = NULL;
   1107 
   1108 	attrib_client_unregister(device);
   1109 
   1110 	btd_device_unref(device);
   1111 }
   1112 
   1113 gint device_address_cmp(struct btd_device *device, const gchar *address)
   1114 {
   1115 	char addr[18];
   1116 
   1117 	ba2str(&device->bdaddr, addr);
   1118 	return strcasecmp(addr, address);
   1119 }
   1120 
   1121 static gboolean record_has_uuid(const sdp_record_t *rec,
   1122 				const char *profile_uuid)
   1123 {
   1124 	sdp_list_t *pat;
   1125 
   1126 	for (pat = rec->pattern; pat != NULL; pat = pat->next) {
   1127 		char *uuid;
   1128 		int ret;
   1129 
   1130 		uuid = bt_uuid2string(pat->data);
   1131 		if (!uuid)
   1132 			continue;
   1133 
   1134 		ret = strcasecmp(uuid, profile_uuid);
   1135 
   1136 		g_free(uuid);
   1137 
   1138 		if (ret == 0)
   1139 			return TRUE;
   1140 	}
   1141 
   1142 	return FALSE;
   1143 }
   1144 
   1145 static GSList *device_match_pattern(struct btd_device *device,
   1146 					const char *match_uuid,
   1147 					GSList *profiles)
   1148 {
   1149 	GSList *l, *uuids = NULL;
   1150 
   1151 	for (l = profiles; l; l = l->next) {
   1152 		char *profile_uuid = l->data;
   1153 		const sdp_record_t *rec;
   1154 
   1155 		rec = btd_device_get_record(device, profile_uuid);
   1156 		if (!rec)
   1157 			continue;
   1158 
   1159 		if (record_has_uuid(rec, match_uuid))
   1160 			uuids = g_slist_append(uuids, profile_uuid);
   1161 	}
   1162 
   1163 	return uuids;
   1164 }
   1165 
   1166 static GSList *device_match_driver(struct btd_device *device,
   1167 					struct btd_device_driver *driver,
   1168 					GSList *profiles)
   1169 {
   1170 	const char **uuid;
   1171 	GSList *uuids = NULL;
   1172 
   1173 	for (uuid = driver->uuids; *uuid; uuid++) {
   1174 		GSList *match;
   1175 
   1176 		/* skip duplicated uuids */
   1177 		if (g_slist_find_custom(uuids, *uuid,
   1178 				(GCompareFunc) strcasecmp))
   1179 			continue;
   1180 
   1181 		/* match profile driver */
   1182 		match = g_slist_find_custom(profiles, *uuid,
   1183 					(GCompareFunc) strcasecmp);
   1184 		if (match) {
   1185 			uuids = g_slist_append(uuids, match->data);
   1186 			continue;
   1187 		}
   1188 
   1189 		/* match pattern driver */
   1190 		match = device_match_pattern(device, *uuid, profiles);
   1191 		uuids = g_slist_concat(uuids, match);
   1192 	}
   1193 
   1194 	return uuids;
   1195 }
   1196 
   1197 void device_probe_drivers(struct btd_device *device, GSList *profiles)
   1198 {
   1199 	GSList *list;
   1200 	char addr[18];
   1201 	int err;
   1202 
   1203 	ba2str(&device->bdaddr, addr);
   1204 
   1205 	if (device->blocked) {
   1206 		DBG("Skipping drivers for blocked device %s", addr);
   1207 		goto add_uuids;
   1208 	}
   1209 
   1210 	DBG("Probing drivers for %s", addr);
   1211 
   1212 	for (list = device_drivers; list; list = list->next) {
   1213 		struct btd_device_driver *driver = list->data;
   1214 		GSList *probe_uuids;
   1215 
   1216 		probe_uuids = device_match_driver(device, driver, profiles);
   1217 
   1218 		if (!probe_uuids)
   1219 			continue;
   1220 
   1221 		err = driver->probe(device, probe_uuids);
   1222 		if (err < 0) {
   1223 			error("%s driver probe failed for device %s",
   1224 							driver->name, addr);
   1225 			g_slist_free(probe_uuids);
   1226 			continue;
   1227 		}
   1228 
   1229 		device->drivers = g_slist_append(device->drivers, driver);
   1230 		g_slist_free(probe_uuids);
   1231 	}
   1232 
   1233 add_uuids:
   1234 	for (list = profiles; list; list = list->next) {
   1235 		GSList *l = g_slist_find_custom(device->uuids, list->data,
   1236 						(GCompareFunc) strcasecmp);
   1237 		if (l)
   1238 			continue;
   1239 
   1240 		device->uuids = g_slist_insert_sorted(device->uuids,
   1241 						g_strdup(list->data),
   1242 						(GCompareFunc) strcasecmp);
   1243 	}
   1244 }
   1245 
   1246 static void device_remove_drivers(struct btd_device *device, GSList *uuids)
   1247 {
   1248 	struct btd_adapter *adapter = device_get_adapter(device);
   1249 	GSList *list, *next;
   1250 	char srcaddr[18], dstaddr[18];
   1251 	bdaddr_t src;
   1252 	sdp_list_t *records;
   1253 
   1254 	adapter_get_address(adapter, &src);
   1255 	ba2str(&src, srcaddr);
   1256 	ba2str(&device->bdaddr, dstaddr);
   1257 
   1258 	records = read_records(&src, &device->bdaddr);
   1259 
   1260 	DBG("Removing drivers for %s", dstaddr);
   1261 
   1262 	for (list = device->drivers; list; list = next) {
   1263 		struct btd_device_driver *driver = list->data;
   1264 		const char **uuid;
   1265 
   1266 		next = list->next;
   1267 
   1268 		for (uuid = driver->uuids; *uuid; uuid++) {
   1269 			if (!g_slist_find_custom(uuids, *uuid,
   1270 						(GCompareFunc) strcasecmp))
   1271 				continue;
   1272 
   1273 			DBG("UUID %s was removed from device %s",
   1274 							*uuid, dstaddr);
   1275 
   1276 			driver->remove(device);
   1277 			device->drivers = g_slist_remove(device->drivers,
   1278 								driver);
   1279 			break;
   1280 		}
   1281 	}
   1282 
   1283 	for (list = uuids; list; list = list->next) {
   1284 		sdp_record_t *rec;
   1285 
   1286 		device->uuids = g_slist_remove(device->uuids, list->data);
   1287 
   1288 		rec = find_record_in_list(records, list->data);
   1289 		if (!rec)
   1290 			continue;
   1291 
   1292 		delete_record(srcaddr, dstaddr, rec->handle);
   1293 
   1294 		records = sdp_list_remove(records, rec);
   1295 		sdp_record_free(rec);
   1296 
   1297 	}
   1298 
   1299 	if (records)
   1300 		sdp_list_free(records, (sdp_free_func_t) sdp_record_free);
   1301 }
   1302 
   1303 static void services_changed(struct btd_device *device)
   1304 {
   1305 	DBusConnection *conn = get_dbus_connection();
   1306 	char **uuids;
   1307 	GSList *l;
   1308 	int i;
   1309 
   1310 	uuids = g_new0(char *, g_slist_length(device->uuids) + 1);
   1311 	for (i = 0, l = device->uuids; l; l = l->next, i++)
   1312 		uuids[i] = l->data;
   1313 
   1314 	emit_array_property_changed(conn, device->path, DEVICE_INTERFACE,
   1315 					"UUIDs", DBUS_TYPE_STRING, &uuids, i);
   1316 
   1317 	g_free(uuids);
   1318 }
   1319 
   1320 static int rec_cmp(const void *a, const void *b)
   1321 {
   1322 	const sdp_record_t *r1 = a;
   1323 	const sdp_record_t *r2 = b;
   1324 
   1325 	return r1->handle - r2->handle;
   1326 }
   1327 
   1328 static void update_services(struct browse_req *req, sdp_list_t *recs)
   1329 {
   1330 	struct btd_device *device = req->device;
   1331 	struct btd_adapter *adapter = device_get_adapter(device);
   1332 	sdp_list_t *seq;
   1333 	char srcaddr[18], dstaddr[18];
   1334 	bdaddr_t src;
   1335 
   1336 	adapter_get_address(adapter, &src);
   1337 	ba2str(&src, srcaddr);
   1338 	ba2str(&device->bdaddr, dstaddr);
   1339 
   1340 	for (seq = recs; seq; seq = seq->next) {
   1341 		sdp_record_t *rec = (sdp_record_t *) seq->data;
   1342 		sdp_list_t *svcclass = NULL;
   1343 		gchar *profile_uuid;
   1344 		GSList *l;
   1345 
   1346 		if (!rec)
   1347 			break;
   1348 
   1349 		if (sdp_get_service_classes(rec, &svcclass) < 0)
   1350 			continue;
   1351 
   1352 		/* Check for empty service classes list */
   1353 		if (svcclass == NULL) {
   1354 			DBG("Skipping record with no service classes");
   1355 			continue;
   1356 		}
   1357 
   1358 		/* Extract the first element and skip the remainning */
   1359 		profile_uuid = bt_uuid2string(svcclass->data);
   1360 		if (!profile_uuid) {
   1361 			sdp_list_free(svcclass, free);
   1362 			continue;
   1363 		}
   1364 
   1365 		if (!strcasecmp(profile_uuid, PNP_UUID)) {
   1366 			uint16_t source, vendor, product, version;
   1367 			sdp_data_t *pdlist;
   1368 
   1369 			pdlist = sdp_data_get(rec, SDP_ATTR_VENDOR_ID_SOURCE);
   1370 			source = pdlist ? pdlist->val.uint16 : 0x0000;
   1371 
   1372 			pdlist = sdp_data_get(rec, SDP_ATTR_VENDOR_ID);
   1373 			vendor = pdlist ? pdlist->val.uint16 : 0x0000;
   1374 
   1375 			pdlist = sdp_data_get(rec, SDP_ATTR_PRODUCT_ID);
   1376 			product = pdlist ? pdlist->val.uint16 : 0x0000;
   1377 
   1378 			pdlist = sdp_data_get(rec, SDP_ATTR_VERSION);
   1379 			version = pdlist ? pdlist->val.uint16 : 0x0000;
   1380 
   1381 			if (source || vendor || product || version)
   1382 				store_device_id(srcaddr, dstaddr, source,
   1383 						vendor, product, version);
   1384 		}
   1385 
   1386 		/* Check for duplicates */
   1387 		if (sdp_list_find(req->records, rec, rec_cmp)) {
   1388 			g_free(profile_uuid);
   1389 			sdp_list_free(svcclass, free);
   1390 			continue;
   1391 		}
   1392 
   1393 		store_record(srcaddr, dstaddr, rec);
   1394 
   1395 		/* Copy record */
   1396 		req->records = sdp_list_append(req->records,
   1397 							sdp_copy_record(rec));
   1398 
   1399 		l = g_slist_find_custom(device->uuids, profile_uuid,
   1400 							(GCompareFunc) strcmp);
   1401 		if (!l)
   1402 			req->profiles_added =
   1403 					g_slist_append(req->profiles_added,
   1404 							profile_uuid);
   1405 		else {
   1406 			req->profiles_removed =
   1407 					g_slist_remove(req->profiles_removed,
   1408 							l->data);
   1409 			g_free(profile_uuid);
   1410 		}
   1411 
   1412 		sdp_list_free(svcclass, free);
   1413 	}
   1414 }
   1415 
   1416 static void store_profiles(struct btd_device *device)
   1417 {
   1418 	struct btd_adapter *adapter = device->adapter;
   1419 	bdaddr_t src;
   1420 	char *str;
   1421 
   1422 	adapter_get_address(adapter, &src);
   1423 
   1424 	if (!device->uuids) {
   1425 		write_device_profiles(&src, &device->bdaddr, "");
   1426 		return;
   1427 	}
   1428 
   1429 	str = bt_list2string(device->uuids);
   1430 	write_device_profiles(&src, &device->bdaddr, str);
   1431 	g_free(str);
   1432 }
   1433 
   1434 static void create_device_reply(struct btd_device *device, struct browse_req *req)
   1435 {
   1436 	DBusMessage *reply;
   1437 
   1438 	reply = dbus_message_new_method_return(req->msg);
   1439 	if (!reply)
   1440 		return;
   1441 
   1442 	dbus_message_append_args(reply, DBUS_TYPE_OBJECT_PATH, &device->path,
   1443 					DBUS_TYPE_INVALID);
   1444 
   1445 	g_dbus_send_message(req->conn, reply);
   1446 }
   1447 
   1448 GSList *device_services_from_record(struct btd_device *device, GSList *profiles)
   1449 {
   1450 	GSList *l, *prim_list = NULL;
   1451 	char *att_uuid;
   1452 	uuid_t proto_uuid;
   1453 
   1454 	sdp_uuid16_create(&proto_uuid, ATT_UUID);
   1455 	att_uuid = bt_uuid2string(&proto_uuid);
   1456 
   1457 	for (l = profiles; l; l = l->next) {
   1458 		const char *profile_uuid = l->data;
   1459 		const sdp_record_t *rec;
   1460 		struct att_primary *prim;
   1461 		uint16_t start = 0, end = 0, psm = 0;
   1462 		uuid_t prim_uuid;
   1463 
   1464 		rec = btd_device_get_record(device, profile_uuid);
   1465 		if (!rec)
   1466 			continue;
   1467 
   1468 		if (!record_has_uuid(rec, att_uuid))
   1469 			continue;
   1470 
   1471 		if (!gatt_parse_record(rec, &prim_uuid, &psm, &start, &end))
   1472 			continue;
   1473 
   1474 		prim = g_new0(struct att_primary, 1);
   1475 		prim->start = start;
   1476 		prim->end = end;
   1477 		sdp_uuid2strn(&prim_uuid, prim->uuid, sizeof(prim->uuid));
   1478 
   1479 		prim_list = g_slist_append(prim_list, prim);
   1480 	}
   1481 
   1482 	g_free(att_uuid);
   1483 
   1484 	return prim_list;
   1485 }
   1486 
   1487 static void search_cb(sdp_list_t *recs, int err, gpointer user_data)
   1488 {
   1489 	struct browse_req *req = user_data;
   1490 	struct btd_device *device = req->device;
   1491 	char addr[18];
   1492 
   1493 	ba2str(&device->bdaddr, addr);
   1494 
   1495 	if (err < 0) {
   1496 		error("%s: error updating services: %s (%d)",
   1497 				addr, strerror(-err), -err);
   1498 		goto send_reply;
   1499 	}
   1500 
   1501 	update_services(req, recs);
   1502 
   1503 	if (device->tmp_records)
   1504 		sdp_list_free(device->tmp_records,
   1505 					(sdp_free_func_t) sdp_record_free);
   1506 
   1507 	device->tmp_records = req->records;
   1508 	req->records = NULL;
   1509 
   1510 	if (!req->profiles_added && !req->profiles_removed) {
   1511 		DBG("%s: No service update", addr);
   1512 		goto send_reply;
   1513 	}
   1514 
   1515 	/* Probe matching drivers for services added */
   1516 	if (req->profiles_added) {
   1517 		GSList *list;
   1518 
   1519 		device_probe_drivers(device, req->profiles_added);
   1520 
   1521 		list = device_services_from_record(device, req->profiles_added);
   1522 		if (list)
   1523 			device_register_services(req->conn, device, list,
   1524 								ATT_PSM);
   1525 	}
   1526 
   1527 	/* Remove drivers for services removed */
   1528 	if (req->profiles_removed)
   1529 		device_remove_drivers(device, req->profiles_removed);
   1530 
   1531 	/* Propagate services changes */
   1532 	services_changed(req->device);
   1533 
   1534 send_reply:
   1535 	if (!req->msg)
   1536 		goto cleanup;
   1537 
   1538 	if (dbus_message_is_method_call(req->msg, DEVICE_INTERFACE,
   1539 					"DiscoverServices"))
   1540 		discover_services_reply(req, err, device->tmp_records);
   1541 	else if (dbus_message_is_method_call(req->msg, ADAPTER_INTERFACE,
   1542 						"CreatePairedDevice"))
   1543 		create_device_reply(device, req);
   1544 	else if (dbus_message_is_method_call(req->msg, ADAPTER_INTERFACE,
   1545 						"CreateDevice")) {
   1546 		if (err < 0) {
   1547 			DBusMessage *reply;
   1548 			reply = btd_error_failed(req->msg, strerror(-err));
   1549 			g_dbus_send_message(req->conn, reply);
   1550 			goto cleanup;
   1551 		}
   1552 
   1553 		create_device_reply(device, req);
   1554 		device_set_temporary(device, FALSE);
   1555 	}
   1556 
   1557 cleanup:
   1558 	if (!device->temporary) {
   1559 		bdaddr_t sba, dba;
   1560 
   1561 		adapter_get_address(device->adapter, &sba);
   1562 		device_get_address(device, &dba);
   1563 
   1564 		store_profiles(device);
   1565 		write_device_type(&sba, &dba, device->type);
   1566 	}
   1567 
   1568 	device->browse = NULL;
   1569 	browse_request_free(req);
   1570 }
   1571 
   1572 static void browse_cb(sdp_list_t *recs, int err, gpointer user_data)
   1573 {
   1574 	struct browse_req *req = user_data;
   1575 	struct btd_device *device = req->device;
   1576 	struct btd_adapter *adapter = device->adapter;
   1577 	bdaddr_t src;
   1578 	uuid_t uuid;
   1579 
   1580 	/* If we have a valid response and req->search_uuid == 2, then L2CAP
   1581 	 * UUID & PNP searching was successful -- we are done */
   1582 	if (err < 0 || (req->search_uuid == 2 && req->records)) {
   1583 		if (err == -ECONNRESET && req->reconnect_attempt < 1) {
   1584 			req->search_uuid--;
   1585 			req->reconnect_attempt++;
   1586 		} else
   1587 			goto done;
   1588 	}
   1589 
   1590 	update_services(req, recs);
   1591 
   1592 	adapter_get_address(adapter, &src);
   1593 
   1594 	/* Search for mandatory uuids */
   1595 	if (uuid_list[req->search_uuid]) {
   1596 		sdp_uuid16_create(&uuid, uuid_list[req->search_uuid++]);
   1597 		bt_search_service(&src, &device->bdaddr, &uuid,
   1598 						browse_cb, user_data, NULL);
   1599 		return;
   1600 	}
   1601 
   1602 done:
   1603 	search_cb(recs, err, user_data);
   1604 }
   1605 
   1606 static void init_browse(struct browse_req *req, gboolean reverse)
   1607 {
   1608 	GSList *l;
   1609 
   1610 	/* If we are doing reverse-SDP don't try to detect removed profiles
   1611 	 * since some devices hide their service records while they are
   1612 	 * connected
   1613 	 */
   1614 	if (reverse)
   1615 		return;
   1616 
   1617 	for (l = req->device->uuids; l; l = l->next)
   1618 		req->profiles_removed = g_slist_append(req->profiles_removed,
   1619 						l->data);
   1620 }
   1621 
   1622 static char *primary_list_to_string(GSList *primary_list)
   1623 {
   1624 	GString *services;
   1625 	GSList *l;
   1626 
   1627 	services = g_string_new(NULL);
   1628 
   1629 	for (l = primary_list; l; l = l->next) {
   1630 		struct att_primary *primary = l->data;
   1631 		char service[64];
   1632 
   1633 		memset(service, 0, sizeof(service));
   1634 
   1635 		snprintf(service, sizeof(service), "%04X#%04X#%s ",
   1636 				primary->start, primary->end, primary->uuid);
   1637 
   1638 		services = g_string_append(services, service);
   1639 	}
   1640 
   1641 	return g_string_free(services, FALSE);
   1642 }
   1643 
   1644 static void store_services(struct btd_device *device)
   1645 {
   1646 	struct btd_adapter *adapter = device->adapter;
   1647 	bdaddr_t dba, sba;
   1648 	char *str = primary_list_to_string(device->primaries);
   1649 
   1650 	adapter_get_address(adapter, &sba);
   1651 	device_get_address(device, &dba);
   1652 
   1653 	write_device_type(&sba, &dba, device->type);
   1654 	write_device_services(&sba, &dba, str);
   1655 
   1656 	g_free(str);
   1657 }
   1658 
   1659 static void primary_cb(GSList *services, guint8 status, gpointer user_data)
   1660 {
   1661 	struct browse_req *req = user_data;
   1662 	struct btd_device *device = req->device;
   1663 	GSList *l, *uuids = NULL;
   1664 
   1665 	if (status) {
   1666 		DBusMessage *reply;
   1667 		reply = btd_error_failed(req->msg, att_ecode2str(status));
   1668 		g_dbus_send_message(req->conn, reply);
   1669 		goto done;
   1670 	}
   1671 
   1672 	services_changed(device);
   1673 	device_set_temporary(device, FALSE);
   1674 
   1675 	for (l = services; l; l = l->next) {
   1676 		struct att_primary *prim = l->data;
   1677 		uuids = g_slist_append(uuids, prim->uuid);
   1678 	}
   1679 
   1680 	device_probe_drivers(device, uuids);
   1681 
   1682 	device_register_services(req->conn, device, g_slist_copy(services), -1);
   1683 
   1684 	g_slist_free(uuids);
   1685 
   1686 	create_device_reply(device, req);
   1687 
   1688 	store_services(device);
   1689 
   1690 done:
   1691 	device->browse = NULL;
   1692 	browse_request_free(req);
   1693 }
   1694 
   1695 static void gatt_connect_cb(GIOChannel *io, GError *gerr, gpointer user_data)
   1696 {
   1697 	struct browse_req *req = user_data;
   1698 	struct btd_device *device = req->device;
   1699 
   1700 	if (gerr) {
   1701 		DBusMessage *reply;
   1702 
   1703 		DBG("%s", gerr->message);
   1704 
   1705 		reply = btd_error_failed(req->msg, gerr->message);
   1706 		g_dbus_send_message(req->conn, reply);
   1707 
   1708 		device->browse = NULL;
   1709 		browse_request_free(req);
   1710 
   1711 		return;
   1712 	}
   1713 
   1714 	req->attrib = g_attrib_new(io);
   1715 	g_io_channel_unref(io);
   1716 
   1717 	gatt_discover_primary(req->attrib, NULL, primary_cb, req);
   1718 }
   1719 
   1720 int device_browse_primary(struct btd_device *device, DBusConnection *conn,
   1721 				DBusMessage *msg, gboolean secure)
   1722 {
   1723 	struct btd_adapter *adapter = device->adapter;
   1724 	struct browse_req *req;
   1725 	BtIOSecLevel sec_level;
   1726 	GIOChannel *io;
   1727 	bdaddr_t src;
   1728 
   1729 	if (device->browse)
   1730 		return -EBUSY;
   1731 
   1732 	req = g_new0(struct browse_req, 1);
   1733 	req->device = btd_device_ref(device);
   1734 
   1735 	adapter_get_address(adapter, &src);
   1736 
   1737 	sec_level = secure ? BT_IO_SEC_HIGH : BT_IO_SEC_LOW;
   1738 
   1739 	io = bt_io_connect(BT_IO_L2CAP, gatt_connect_cb, req, NULL, NULL,
   1740 				BT_IO_OPT_SOURCE_BDADDR, &src,
   1741 				BT_IO_OPT_DEST_BDADDR, &device->bdaddr,
   1742 				BT_IO_OPT_CID, ATT_CID,
   1743 				BT_IO_OPT_SEC_LEVEL, sec_level,
   1744 				BT_IO_OPT_INVALID);
   1745 
   1746 	if (io == NULL ) {
   1747 		browse_request_free(req);
   1748 		return -EIO;
   1749 	}
   1750 
   1751 	if (conn == NULL)
   1752 		conn = get_dbus_connection();
   1753 
   1754 	req->conn = dbus_connection_ref(conn);
   1755 	device->browse = req;
   1756 
   1757 	if (msg) {
   1758 		const char *sender = dbus_message_get_sender(msg);
   1759 
   1760 		req->msg = dbus_message_ref(msg);
   1761 		/* Track the request owner to cancel it
   1762 		 * automatically if the owner exits */
   1763 		req->listener_id = g_dbus_add_disconnect_watch(conn,
   1764 						sender,
   1765 						discover_services_req_exit,
   1766 						req, NULL);
   1767 	}
   1768 
   1769 	return 0;
   1770 }
   1771 
   1772 int device_browse_sdp(struct btd_device *device, DBusConnection *conn,
   1773 			DBusMessage *msg, uuid_t *search, gboolean reverse)
   1774 {
   1775 	struct btd_adapter *adapter = device->adapter;
   1776 	struct browse_req *req;
   1777 	bt_callback_t cb;
   1778 	bdaddr_t src;
   1779 	uuid_t uuid;
   1780 	int err;
   1781 
   1782 	if (device->browse)
   1783 		return -EBUSY;
   1784 
   1785 	adapter_get_address(adapter, &src);
   1786 
   1787 	req = g_new0(struct browse_req, 1);
   1788 	req->device = btd_device_ref(device);
   1789 	if (search) {
   1790 		memcpy(&uuid, search, sizeof(uuid_t));
   1791 		cb = search_cb;
   1792 	} else {
   1793 		sdp_uuid16_create(&uuid, uuid_list[req->search_uuid++]);
   1794 		init_browse(req, reverse);
   1795 		cb = browse_cb;
   1796 	}
   1797 
   1798 	err = bt_search_service(&src, &device->bdaddr, &uuid, cb, req, NULL);
   1799 	if (err < 0) {
   1800 		browse_request_free(req);
   1801 		return err;
   1802 	}
   1803 
   1804 	if (conn == NULL)
   1805 		conn = get_dbus_connection();
   1806 
   1807 	req->conn = dbus_connection_ref(conn);
   1808 	device->browse = req;
   1809 
   1810 	if (msg) {
   1811 		const char *sender = dbus_message_get_sender(msg);
   1812 
   1813 		req->msg = dbus_message_ref(msg);
   1814 		/* Track the request owner to cancel it
   1815 		 * automatically if the owner exits */
   1816 		req->listener_id = g_dbus_add_disconnect_watch(conn,
   1817 						sender,
   1818 						discover_services_req_exit,
   1819 						req, NULL);
   1820 	}
   1821 
   1822 	return err;
   1823 }
   1824 
   1825 struct btd_adapter *device_get_adapter(struct btd_device *device)
   1826 {
   1827 	if (!device)
   1828 		return NULL;
   1829 
   1830 	return device->adapter;
   1831 }
   1832 
   1833 void device_get_address(struct btd_device *device, bdaddr_t *bdaddr)
   1834 {
   1835 	bacpy(bdaddr, &device->bdaddr);
   1836 }
   1837 
   1838 const gchar *device_get_path(struct btd_device *device)
   1839 {
   1840 	if (!device)
   1841 		return NULL;
   1842 
   1843 	return device->path;
   1844 }
   1845 
   1846 struct agent *device_get_agent(struct btd_device *device)
   1847 {
   1848 	if (!device)
   1849 		return NULL;
   1850 
   1851 	if (device->agent)
   1852 		return device->agent;
   1853 
   1854 	return adapter_get_agent(device->adapter);
   1855 }
   1856 
   1857 gboolean device_is_busy(struct btd_device *device)
   1858 {
   1859 	return device->browse ? TRUE : FALSE;
   1860 }
   1861 
   1862 gboolean device_is_temporary(struct btd_device *device)
   1863 {
   1864 	return device->temporary;
   1865 }
   1866 
   1867 void device_set_temporary(struct btd_device *device, gboolean temporary)
   1868 {
   1869 	if (!device)
   1870 		return;
   1871 
   1872 	DBG("temporary %d", temporary);
   1873 
   1874 	device->temporary = temporary;
   1875 }
   1876 
   1877 void device_set_bonded(struct btd_device *device, gboolean bonded)
   1878 {
   1879 	if (!device)
   1880 		return;
   1881 
   1882 	DBG("bonded %d", bonded);
   1883 
   1884 	device->bonded = bonded;
   1885 }
   1886 
   1887 void device_set_type(struct btd_device *device, device_type_t type)
   1888 {
   1889 	if (!device)
   1890 		return;
   1891 
   1892 	device->type = type;
   1893 }
   1894 
   1895 static gboolean start_discovery(gpointer user_data)
   1896 {
   1897 	struct btd_device *device = user_data;
   1898 
   1899 	device_browse_sdp(device, NULL, NULL, NULL, TRUE);
   1900 
   1901 	device->discov_timer = 0;
   1902 
   1903 	return FALSE;
   1904 }
   1905 
   1906 static DBusMessage *new_authentication_return(DBusMessage *msg, int status)
   1907 {
   1908 	switch (status) {
   1909 	case 0x00: /* success */
   1910 		return dbus_message_new_method_return(msg);
   1911 
   1912 	case 0x04: /* page timeout */
   1913 		return dbus_message_new_error(msg,
   1914 				ERROR_INTERFACE ".ConnectionAttemptFailed",
   1915 				"Page Timeout");
   1916 	case 0x08: /* connection timeout */
   1917 		return dbus_message_new_error(msg,
   1918 				ERROR_INTERFACE ".ConnectionAttemptFailed",
   1919 				"Connection Timeout");
   1920 	case 0x10: /* connection accept timeout */
   1921 	case 0x22: /* LMP response timeout */
   1922 	case 0x28: /* instant passed - is this a timeout? */
   1923 		return dbus_message_new_error(msg,
   1924 					ERROR_INTERFACE ".AuthenticationTimeout",
   1925 					"Authentication Timeout");
   1926 	case 0x17: /* too frequent pairing attempts */
   1927 		return dbus_message_new_error(msg,
   1928 					ERROR_INTERFACE ".RepeatedAttempts",
   1929 					"Repeated Attempts");
   1930 
   1931 	case 0x06:
   1932 	case 0x18: /* pairing not allowed (e.g. gw rejected attempt) */
   1933 		return dbus_message_new_error(msg,
   1934 					ERROR_INTERFACE ".AuthenticationRejected",
   1935 					"Authentication Rejected");
   1936 
   1937 	case 0x07: /* memory capacity */
   1938 	case 0x09: /* connection limit */
   1939 	case 0x0a: /* synchronous connection limit */
   1940 	case 0x0d: /* limited resources */
   1941 	case 0x13: /* user ended the connection */
   1942 	case 0x14: /* terminated due to low resources */
   1943 	case 0x16: /* connection terminated */
   1944 		return dbus_message_new_error(msg,
   1945 					ERROR_INTERFACE ".AuthenticationCanceled",
   1946 					"Authentication Canceled");
   1947 
   1948 	case 0x05: /* authentication failure */
   1949 	case 0x0E: /* rejected due to security reasons - is this auth failure? */
   1950 	case 0x25: /* encryption mode not acceptable - is this auth failure? */
   1951 	case 0x26: /* link key cannot be changed - is this auth failure? */
   1952 	case 0x29: /* pairing with unit key unsupported - is this auth failure? */
   1953 	case 0x2f: /* insufficient security - is this auth failure? */
   1954 	default:
   1955 		return dbus_message_new_error(msg,
   1956 					ERROR_INTERFACE ".AuthenticationFailed",
   1957 					"Authentication Failed");
   1958 	}
   1959 }
   1960 
   1961 static void bonding_request_free(struct bonding_req *bonding)
   1962 {
   1963 	struct btd_device *device;
   1964 
   1965 	if (!bonding)
   1966 		return;
   1967 
   1968 	if (bonding->listener_id)
   1969 		g_dbus_remove_watch(bonding->conn, bonding->listener_id);
   1970 
   1971 	if (bonding->msg)
   1972 		dbus_message_unref(bonding->msg);
   1973 
   1974 	if (bonding->conn)
   1975 		dbus_connection_unref(bonding->conn);
   1976 
   1977 	if (bonding->io)
   1978 		g_io_channel_unref(bonding->io);
   1979 
   1980 	device = bonding->device;
   1981 	g_free(bonding);
   1982 
   1983 	if (!device)
   1984 		return;
   1985 
   1986 	device->bonding = NULL;
   1987 
   1988 	adapter_resume_discovery(device->adapter);
   1989 
   1990 	if (!device->agent)
   1991 		return;
   1992 
   1993 	agent_cancel(device->agent);
   1994 	agent_free(device->agent);
   1995 	device->agent = NULL;
   1996 }
   1997 
   1998 void device_set_paired(struct btd_device *device, gboolean value)
   1999 {
   2000 	DBusConnection *conn = get_dbus_connection();
   2001 
   2002 	if (device->paired == value)
   2003 		return;
   2004 
   2005 	device->paired = value;
   2006 
   2007 	emit_property_changed(conn, device->path, DEVICE_INTERFACE, "Paired",
   2008 				DBUS_TYPE_BOOLEAN, &value);
   2009 }
   2010 
   2011 static void device_agent_removed(struct agent *agent, void *user_data)
   2012 {
   2013 	struct btd_device *device = user_data;
   2014 
   2015 	device->agent = NULL;
   2016 
   2017 	if (device->authr)
   2018 		device->authr->agent = NULL;
   2019 }
   2020 
   2021 static struct bonding_req *bonding_request_new(DBusConnection *conn,
   2022 						DBusMessage *msg,
   2023 						struct btd_device *device,
   2024 						const char *agent_path,
   2025 						uint8_t capability)
   2026 {
   2027 	struct bonding_req *bonding;
   2028 	const char *name = dbus_message_get_sender(msg);
   2029 	struct agent *agent;
   2030 	char addr[18];
   2031 
   2032 	ba2str(&device->bdaddr, addr);
   2033 	DBG("Requesting bonding for %s", addr);
   2034 
   2035 	if (!agent_path)
   2036 		goto proceed;
   2037 
   2038 	agent = agent_create(device->adapter, name, agent_path,
   2039 					capability,
   2040 					device_agent_removed,
   2041 					device);
   2042 	if (!agent) {
   2043 		error("Unable to create a new agent");
   2044 		return NULL;
   2045 	}
   2046 
   2047 	device->agent = agent;
   2048 
   2049 	DBG("Temporary agent registered for %s at %s:%s",
   2050 			addr, name, agent_path);
   2051 
   2052 proceed:
   2053 	bonding = g_new0(struct bonding_req, 1);
   2054 
   2055 	bonding->conn = dbus_connection_ref(conn);
   2056 	bonding->msg = dbus_message_ref(msg);
   2057 
   2058 	adapter_suspend_discovery(device->adapter);
   2059 
   2060 	return bonding;
   2061 }
   2062 
   2063 static void create_bond_req_exit(DBusConnection *conn, void *user_data)
   2064 {
   2065 	struct btd_device *device = user_data;
   2066 	char addr[18];
   2067 
   2068 	ba2str(&device->bdaddr, addr);
   2069 	DBG("%s: requestor exited before bonding was completed", addr);
   2070 
   2071 	if (device->authr)
   2072 		device_cancel_authentication(device, FALSE);
   2073 
   2074 	if (device->bonding) {
   2075 		device->bonding->listener_id = 0;
   2076 		device_request_disconnect(device, NULL);
   2077 	}
   2078 }
   2079 
   2080 DBusMessage *device_create_bonding(struct btd_device *device,
   2081 					DBusConnection *conn,
   2082 					DBusMessage *msg,
   2083 					const char *agent_path,
   2084 					uint8_t capability)
   2085 {
   2086 	char filename[PATH_MAX + 1];
   2087 	char *str, srcaddr[18], dstaddr[18];
   2088 	struct btd_adapter *adapter = device->adapter;
   2089 	struct bonding_req *bonding;
   2090 	bdaddr_t src;
   2091 	int err;
   2092 
   2093 	adapter_get_address(adapter, &src);
   2094 	ba2str(&src, srcaddr);
   2095 	ba2str(&device->bdaddr, dstaddr);
   2096 
   2097 	if (device->bonding)
   2098 		return btd_error_in_progress(msg);
   2099 
   2100 	/* check if a link key already exists */
   2101 	create_name(filename, PATH_MAX, STORAGEDIR, srcaddr,
   2102 			"linkkeys");
   2103 
   2104 	str = textfile_caseget(filename, dstaddr);
   2105 	if (str) {
   2106 		free(str);
   2107 		return btd_error_already_exists(msg);
   2108 	}
   2109 
   2110 	err = adapter_create_bonding(adapter, &device->bdaddr, capability);
   2111 	if (err < 0)
   2112 		return btd_error_failed(msg, strerror(-err));
   2113 
   2114 	bonding = bonding_request_new(conn, msg, device, agent_path,
   2115 					capability);
   2116 	if (!bonding) {
   2117 		adapter_cancel_bonding(adapter, &device->bdaddr);
   2118 		return NULL;
   2119 	}
   2120 
   2121 	bonding->listener_id = g_dbus_add_disconnect_watch(conn,
   2122 						dbus_message_get_sender(msg),
   2123 						create_bond_req_exit, device,
   2124 						NULL);
   2125 
   2126 	device->bonding = bonding;
   2127 	bonding->device = device;
   2128 
   2129 	return NULL;
   2130 }
   2131 
   2132 void device_simple_pairing_complete(struct btd_device *device, uint8_t status)
   2133 {
   2134 	struct authentication_req *auth = device->authr;
   2135 
   2136 	if (auth && auth->type == AUTH_TYPE_NOTIFY && auth->agent)
   2137 		agent_cancel(auth->agent);
   2138 }
   2139 
   2140 static void device_auth_req_free(struct btd_device *device)
   2141 {
   2142 	g_free(device->authr);
   2143 	device->authr = NULL;
   2144 }
   2145 
   2146 void device_bonding_complete(struct btd_device *device, uint8_t status)
   2147 {
   2148 	struct bonding_req *bonding = device->bonding;
   2149 	struct authentication_req *auth = device->authr;
   2150 	bdaddr_t bdaddr;
   2151 
   2152 	DBG("bonding %p status 0x%02x", bonding, status);
   2153 
   2154 	if (auth && auth->type == AUTH_TYPE_NOTIFY && auth->agent)
   2155 		agent_cancel(auth->agent);
   2156 
   2157 	// Temporary hack till we move to mgmt interface.
   2158 	if (status == 0x06 && auth == NULL) {
   2159 		device_remove_bonding(device);
   2160 		device_get_address(device, &bdaddr);
   2161 		btd_adapter_retry_authentication(device->adapter, &bdaddr);
   2162 		return;
   2163 	} else if (status) {
   2164 		device_cancel_authentication(device, TRUE);
   2165 		device_cancel_bonding(device, status);
   2166 		return;
   2167 	}
   2168 
   2169 	device_auth_req_free(device);
   2170 
   2171 	/* If we're already paired nothing more is needed */
   2172 	if (device->paired)
   2173 		return;
   2174 
   2175 	device_set_paired(device, TRUE);
   2176 
   2177 	/* If we were initiators start service discovery immediately.
   2178 	 * However if the other end was the initator wait a few seconds
   2179 	 * before SDP. This is due to potential IOP issues if the other
   2180 	 * end starts doing SDP at the same time as us */
   2181 	if (bonding) {
   2182 		DBG("Proceeding with service discovery");
   2183 		/* If we are initiators remove any discovery timer and just
   2184 		 * start discovering services directly */
   2185 		if (device->discov_timer) {
   2186 			g_source_remove(device->discov_timer);
   2187 			device->discov_timer = 0;
   2188 		}
   2189 
   2190 		device_browse_sdp(device, bonding->conn, bonding->msg,
   2191 				NULL, FALSE);
   2192 
   2193 		bonding_request_free(bonding);
   2194 	} else {
   2195 		if (!device->browse && !device->discov_timer &&
   2196 				main_opts.reverse_sdp) {
   2197 			/* If we are not initiators and there is no currently
   2198 			 * active discovery or discovery timer, set discovery
   2199 			 * timer */
   2200 			DBG("setting timer for reverse service discovery");
   2201 			device->discov_timer = g_timeout_add_seconds(
   2202 							DISCOVERY_TIMER,
   2203 							start_discovery,
   2204 							device);
   2205 		}
   2206 	}
   2207 }
   2208 
   2209 gboolean device_is_creating(struct btd_device *device, const char *sender)
   2210 {
   2211 	DBusMessage *msg;
   2212 
   2213 	if (device->bonding && device->bonding->msg)
   2214 		msg = device->bonding->msg;
   2215 	else if (device->browse && device->browse->msg)
   2216 		msg = device->browse->msg;
   2217 	else
   2218 		return FALSE;
   2219 
   2220 	if (!dbus_message_is_method_call(msg, ADAPTER_INTERFACE,
   2221 						"CreatePairedDevice") &&
   2222 			!dbus_message_is_method_call(msg, ADAPTER_INTERFACE,
   2223 							"CreateDevice"))
   2224 		return FALSE;
   2225 
   2226 	if (sender == NULL)
   2227 		return TRUE;
   2228 
   2229 	return g_str_equal(sender, dbus_message_get_sender(msg));
   2230 }
   2231 
   2232 gboolean device_is_bonding(struct btd_device *device, const char *sender)
   2233 {
   2234 	struct bonding_req *bonding = device->bonding;
   2235 
   2236 	if (!device->bonding)
   2237 		return FALSE;
   2238 
   2239 	if (!sender)
   2240 		return TRUE;
   2241 
   2242 	return g_str_equal(sender, dbus_message_get_sender(bonding->msg));
   2243 }
   2244 
   2245 void device_cancel_bonding(struct btd_device *device, uint8_t status)
   2246 {
   2247 	struct bonding_req *bonding = device->bonding;
   2248 	DBusMessage *reply;
   2249 	char addr[18];
   2250 
   2251 	if (!bonding)
   2252 		return;
   2253 
   2254 	ba2str(&device->bdaddr, addr);
   2255 	DBG("Canceling bonding request for %s", addr);
   2256 
   2257 	if (device->authr)
   2258 		device_cancel_authentication(device, FALSE);
   2259 
   2260 	reply = new_authentication_return(bonding->msg, status);
   2261 	g_dbus_send_message(bonding->conn, reply);
   2262 
   2263 	bonding_request_cancel(bonding);
   2264 	bonding_request_free(bonding);
   2265 }
   2266 
   2267 static void pincode_cb(struct agent *agent, DBusError *err,
   2268 					const char *pincode, void *data)
   2269 {
   2270 	struct authentication_req *auth = data;
   2271 	struct btd_device *device = auth->device;
   2272 
   2273 	/* No need to reply anything if the authentication already failed */
   2274 	if (auth->cb == NULL)
   2275 		return;
   2276 
   2277 	((agent_pincode_cb) auth->cb)(agent, err, pincode, device);
   2278 
   2279 	device->authr->cb = NULL;
   2280 	device->authr->agent = NULL;
   2281 }
   2282 
   2283 static void confirm_cb(struct agent *agent, DBusError *err, void *data)
   2284 {
   2285 	struct authentication_req *auth = data;
   2286 	struct btd_device *device = auth->device;
   2287 
   2288 	/* No need to reply anything if the authentication already failed */
   2289 	if (auth->cb == NULL)
   2290 		return;
   2291 
   2292 	((agent_cb) auth->cb)(agent, err, device);
   2293 
   2294 	device->authr->cb = NULL;
   2295 	device->authr->agent = NULL;
   2296 }
   2297 
   2298 static void passkey_cb(struct agent *agent, DBusError *err,
   2299 						uint32_t passkey, void *data)
   2300 {
   2301 	struct authentication_req *auth = data;
   2302 	struct btd_device *device = auth->device;
   2303 
   2304 	/* No need to reply anything if the authentication already failed */
   2305 	if (auth->cb == NULL)
   2306 		return;
   2307 
   2308 	((agent_passkey_cb) auth->cb)(agent, err, passkey, device);
   2309 
   2310 	device->authr->cb = NULL;
   2311 	device->authr->agent = NULL;
   2312 }
   2313 
   2314 static void pairing_consent_cb(struct agent *agent, DBusError *err, void *data)
   2315 {
   2316 	struct authentication_req *auth = data;
   2317 	struct btd_device *device = auth->device;
   2318 
   2319 	/* No need to reply anything if the authentication already failed */
   2320 	if (!auth->cb)
   2321 		return;
   2322 
   2323 	((agent_cb) auth->cb)(agent, err, device);
   2324 
   2325 	auth->cb = NULL;
   2326 }
   2327 
   2328 int device_request_authentication(struct btd_device *device, auth_type_t type,
   2329 						uint32_t passkey, void *cb)
   2330 {
   2331 	struct authentication_req *auth;
   2332 	struct agent *agent;
   2333 	char addr[18];
   2334 	int err;
   2335 
   2336 	ba2str(&device->bdaddr, addr);
   2337 	DBG("Requesting agent authentication for %s", addr);
   2338 
   2339 	if (device->authr) {
   2340 		error("Authentication already requested for %s", addr);
   2341 		return -EALREADY;
   2342 	}
   2343 
   2344 	agent = device_get_agent(device);
   2345 	if (!agent) {
   2346 		error("No agent available for request type %d", type);
   2347 		return -EPERM;
   2348 	}
   2349 
   2350 	auth = g_new0(struct authentication_req, 1);
   2351 	auth->agent = agent;
   2352 	auth->device = device;
   2353 	auth->cb = cb;
   2354 	auth->type = type;
   2355 	device->authr = auth;
   2356 
   2357 	switch (type) {
   2358 	case AUTH_TYPE_PINCODE:
   2359 		err = agent_request_pincode(agent, device, pincode_cb,
   2360 								auth, NULL);
   2361 		break;
   2362 	case AUTH_TYPE_PASSKEY:
   2363 		err = agent_request_passkey(agent, device, passkey_cb,
   2364 								auth, NULL);
   2365 		break;
   2366 	case AUTH_TYPE_CONFIRM:
   2367 		err = agent_request_confirmation(agent, device, passkey,
   2368 						confirm_cb, auth, NULL);
   2369 		break;
   2370 	case AUTH_TYPE_NOTIFY:
   2371 		err = agent_display_passkey(agent, device, passkey);
   2372 		break;
   2373 	case AUTH_TYPE_AUTO:
   2374 		err = 0;
   2375 		break;
   2376 	case AUTH_TYPE_PAIRING_CONSENT:
   2377 		err = agent_request_pairing_consent(agent, device,
   2378 							pairing_consent_cb, auth, NULL);
   2379 		break;
   2380 	default:
   2381 		err = -EINVAL;
   2382 	}
   2383 
   2384 	if (err < 0) {
   2385 		error("Failed requesting authentication");
   2386 		device_auth_req_free(device);
   2387 	}
   2388 
   2389 	return err;
   2390 }
   2391 
   2392 static void cancel_authentication(struct authentication_req *auth)
   2393 {
   2394 	struct btd_device *device;
   2395 	struct agent *agent;
   2396 	DBusError err;
   2397 
   2398 	if (!auth || !auth->cb)
   2399 		return;
   2400 
   2401 	device = auth->device;
   2402 	agent = auth->agent;
   2403 
   2404 	dbus_error_init(&err);
   2405 	dbus_set_error_const(&err, "org.bluez.Error.Canceled", NULL);
   2406 
   2407 	switch (auth->type) {
   2408 	case AUTH_TYPE_PINCODE:
   2409 		((agent_pincode_cb) auth->cb)(agent, &err, NULL, device);
   2410 		break;
   2411 	case AUTH_TYPE_CONFIRM:
   2412 		((agent_cb) auth->cb)(agent, &err, device);
   2413 		break;
   2414 	case AUTH_TYPE_PASSKEY:
   2415 		((agent_passkey_cb) auth->cb)(agent, &err, 0, device);
   2416 		break;
   2417 	case AUTH_TYPE_PAIRING_CONSENT:
   2418 		((agent_cb) auth->cb) (agent, &err, device);
   2419 		break;
   2420 	case AUTH_TYPE_NOTIFY:
   2421 		/* User Notify doesn't require any reply */
   2422 		break;
   2423 	}
   2424 
   2425 	dbus_error_free(&err);
   2426 	auth->cb = NULL;
   2427 }
   2428 
   2429 void device_cancel_authentication(struct btd_device *device, gboolean aborted)
   2430 {
   2431 	struct authentication_req *auth = device->authr;
   2432 	char addr[18];
   2433 
   2434 	if (!auth)
   2435 		return;
   2436 
   2437 	ba2str(&device->bdaddr, addr);
   2438 	DBG("Canceling authentication request for %s", addr);
   2439 
   2440 	if (auth->agent)
   2441 		agent_cancel(auth->agent);
   2442 
   2443 	if (!aborted)
   2444 		cancel_authentication(auth);
   2445 
   2446 	device_auth_req_free(device);
   2447 }
   2448 
   2449 gboolean device_is_authenticating(struct btd_device *device)
   2450 {
   2451 	return (device->authr != NULL);
   2452 }
   2453 
   2454 gboolean device_is_authorizing(struct btd_device *device)
   2455 {
   2456 	return device->authorizing;
   2457 }
   2458 
   2459 void device_set_authorizing(struct btd_device *device, gboolean auth)
   2460 {
   2461 	device->authorizing = auth;
   2462 }
   2463 
   2464 void device_register_services(DBusConnection *conn, struct btd_device *device,
   2465 						GSList *prim_list, int psm)
   2466 {
   2467 	device->services = attrib_client_register(conn, device, psm, NULL,
   2468 								prim_list);
   2469 	device->primaries = g_slist_concat(device->primaries, prim_list);
   2470 }
   2471 
   2472 GSList *btd_device_get_primaries(struct btd_device *device)
   2473 {
   2474 	return device->primaries;
   2475 }
   2476 
   2477 void btd_device_add_uuid(struct btd_device *device, const char *uuid)
   2478 {
   2479 	GSList *uuid_list;
   2480 	char *new_uuid;
   2481 
   2482 	if (g_slist_find_custom(device->uuids, uuid,
   2483 				(GCompareFunc) strcasecmp))
   2484 		return;
   2485 
   2486 	new_uuid = g_strdup(uuid);
   2487 	uuid_list = g_slist_append(NULL, new_uuid);
   2488 
   2489 	device_probe_drivers(device, uuid_list);
   2490 
   2491 	g_free(new_uuid);
   2492 	g_slist_free(uuid_list);
   2493 
   2494 	store_profiles(device);
   2495 	services_changed(device);
   2496 }
   2497 
   2498 const sdp_record_t *btd_device_get_record(struct btd_device *device,
   2499 							const char *uuid)
   2500 {
   2501 	bdaddr_t src;
   2502 
   2503 	if (device->tmp_records) {
   2504 		const sdp_record_t *record;
   2505 
   2506 		record = find_record_in_list(device->tmp_records, uuid);
   2507 		if (record != NULL)
   2508 			return record;
   2509 	}
   2510 
   2511 	adapter_get_address(device->adapter, &src);
   2512 
   2513 	device->tmp_records = read_records(&src, &device->bdaddr);
   2514 	if (!device->tmp_records)
   2515 		return NULL;
   2516 
   2517 	return find_record_in_list(device->tmp_records, uuid);
   2518 }
   2519 
   2520 int btd_register_device_driver(struct btd_device_driver *driver)
   2521 {
   2522 	device_drivers = g_slist_append(device_drivers, driver);
   2523 
   2524 	return 0;
   2525 }
   2526 
   2527 void btd_unregister_device_driver(struct btd_device_driver *driver)
   2528 {
   2529 	device_drivers = g_slist_remove(device_drivers, driver);
   2530 }
   2531 
   2532 struct btd_device *btd_device_ref(struct btd_device *device)
   2533 {
   2534 	device->ref++;
   2535 
   2536 	DBG("%p: ref=%d", device, device->ref);
   2537 
   2538 	return device;
   2539 }
   2540 
   2541 void btd_device_unref(struct btd_device *device)
   2542 {
   2543 	DBusConnection *conn = get_dbus_connection();
   2544 	gchar *path;
   2545 
   2546 	device->ref--;
   2547 
   2548 	DBG("%p: ref=%d", device, device->ref);
   2549 
   2550 	if (device->ref > 0)
   2551 		return;
   2552 
   2553 	path = g_strdup(device->path);
   2554 
   2555 	g_dbus_unregister_interface(conn, path, DEVICE_INTERFACE);
   2556 
   2557 	g_free(path);
   2558 }
   2559 
   2560 void device_set_class(struct btd_device *device, uint32_t value)
   2561 {
   2562 	DBusConnection *conn = get_dbus_connection();
   2563 
   2564 	emit_property_changed(conn, device->path, DEVICE_INTERFACE, "Class",
   2565 				DBUS_TYPE_UINT32, &value);
   2566 }
   2567