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