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