1/*
2 *
3 *  BlueZ - Bluetooth protocol stack for Linux
4 *
5 *  Copyright (C) 2000-2001  Qualcomm Incorporated
6 *  Copyright (C) 2002-2003  Maxim Krasnyansky <maxk@qualcomm.com>
7 *  Copyright (C) 2002-2010  Marcel Holtmann <marcel@holtmann.org>
8 *
9 *
10 *  This program is free software; you can redistribute it and/or modify
11 *  it under the terms of the GNU General Public License as published by
12 *  the Free Software Foundation; either version 2 of the License, or
13 *  (at your option) any later version.
14 *
15 *  This program is distributed in the hope that it will be useful,
16 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 *  GNU General Public License for more details.
19 *
20 *  You should have received a copy of the GNU General Public License
21 *  along with this program; if not, write to the Free Software
22 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
23 *
24 */
25
26#ifdef HAVE_CONFIG_H
27#include <config.h>
28#endif
29
30#include <stdio.h>
31#include <errno.h>
32#include <stdlib.h>
33#include <time.h>
34#include <unistd.h>
35#include <sys/time.h>
36#include <sys/param.h>
37#include <sys/ioctl.h>
38#include <sys/socket.h>
39
40#include <bluetooth/bluetooth.h>
41#include <bluetooth/hci.h>
42#include <bluetooth/hci_lib.h>
43#include <bluetooth/sdp.h>
44
45#include <glib.h>
46
47#include <dbus/dbus.h>
48
49#include "hcid.h"
50#include "log.h"
51#include "textfile.h"
52
53#include "adapter.h"
54#include "device.h"
55#include "dbus-hci.h"
56#include "storage.h"
57#include "manager.h"
58
59typedef enum {
60	REQ_PENDING,
61	REQ_SENT
62} req_status_t;
63
64struct hci_req_data {
65	int dev_id;
66	int event;
67	req_status_t status;
68	bdaddr_t dba;
69	uint16_t ogf;
70	uint16_t ocf;
71	void *cparam;
72	int clen;
73};
74
75struct g_io_info {
76	GIOChannel	*channel;
77	int		watch_id;
78	int		pin_length;
79};
80
81static struct g_io_info io_data[HCI_MAX_DEV];
82
83static GSList *hci_req_queue = NULL;
84
85static struct hci_req_data *hci_req_data_new(int dev_id, const bdaddr_t *dba,
86					uint16_t ogf, uint16_t ocf, int event,
87					const void *cparam, int clen)
88{
89	struct hci_req_data *data;
90
91	data = g_new0(struct hci_req_data, 1);
92
93	data->cparam = g_malloc(clen);
94	memcpy(data->cparam, cparam, clen);
95
96	bacpy(&data->dba, dba);
97
98	data->dev_id = dev_id;
99	data->status = REQ_PENDING;
100	data->ogf    = ogf;
101	data->ocf    = ocf;
102	data->event  = event;
103	data->clen   = clen;
104
105	return data;
106}
107
108static int hci_req_find_by_devid(const void *data, const void *user_data)
109{
110	const struct hci_req_data *req = data;
111	const int *dev_id = user_data;
112
113	return (*dev_id - req->dev_id);
114}
115
116static void hci_req_queue_process(int dev_id)
117{
118	int dd, ret_val;
119
120	/* send the next pending cmd */
121	dd = hci_open_dev(dev_id);
122	if (dd < 0) {
123		error("hci_open_dev(%d): %s (%d)", dev_id, strerror(errno),
124									errno);
125		return;
126	}
127
128	do {
129		struct hci_req_data *data;
130		GSList *l = g_slist_find_custom(hci_req_queue, &dev_id,
131							hci_req_find_by_devid);
132
133		if (!l)
134			break;
135
136		data = l->data;
137		data->status = REQ_SENT;
138
139		ret_val = hci_send_cmd(dd, data->ogf, data->ocf,
140						data->clen, data->cparam);
141		if (ret_val < 0) {
142			hci_req_queue = g_slist_remove(hci_req_queue, data);
143			g_free(data->cparam);
144			g_free(data);
145		}
146
147	} while (ret_val < 0);
148
149	hci_close_dev(dd);
150}
151
152static void hci_req_queue_append(struct hci_req_data *data)
153{
154	GSList *l;
155	struct hci_req_data *match;
156
157	hci_req_queue = g_slist_append(hci_req_queue, data);
158
159	l = g_slist_find_custom(hci_req_queue, &data->dev_id,
160							hci_req_find_by_devid);
161	match = l->data;
162
163	if (match->status == REQ_SENT)
164		return;
165
166	hci_req_queue_process(data->dev_id);
167}
168
169void hci_req_queue_remove(int dev_id, bdaddr_t *dba)
170{
171	GSList *cur, *next;
172	struct hci_req_data *req;
173
174	for (cur = hci_req_queue; cur != NULL; cur = next) {
175		req = cur->data;
176		next = cur->next;
177		if ((req->dev_id != dev_id) || (bacmp(&req->dba, dba)))
178			continue;
179
180		hci_req_queue = g_slist_remove(hci_req_queue, req);
181		g_free(req->cparam);
182		g_free(req);
183	}
184}
185
186static void check_pending_hci_req(int dev_id, int event)
187{
188	struct hci_req_data *data;
189	GSList *l;
190
191	if (!hci_req_queue)
192		return;
193
194	/* find the first element(pending)*/
195	l = g_slist_find_custom(hci_req_queue, &dev_id, hci_req_find_by_devid);
196
197	if (!l)
198		return;
199
200	data = l->data;
201
202	/* skip if there is pending confirmation */
203	if (data->status == REQ_SENT) {
204		if (data->event != event)
205			return;
206
207		/* remove the confirmed cmd */
208		hci_req_queue = g_slist_remove(hci_req_queue, data);
209		g_free(data->cparam);
210		g_free(data);
211	}
212
213	hci_req_queue_process(dev_id);
214}
215
216static int get_handle(int dev, bdaddr_t *sba, bdaddr_t *dba, uint16_t *handle)
217{
218	struct hci_conn_list_req *cl;
219	struct hci_conn_info *ci;
220	char addr[18];
221	int i;
222
223	cl = g_malloc0(10 * sizeof(*ci) + sizeof(*cl));
224
225	ba2str(sba, addr);
226	cl->dev_id = hci_devid(addr);
227	cl->conn_num = 10;
228	ci = cl->conn_info;
229
230	if (ioctl(dev, HCIGETCONNLIST, (void *) cl) < 0) {
231		g_free(cl);
232		return -EIO;
233	}
234
235	for (i = 0; i < cl->conn_num; i++, ci++) {
236		if (bacmp(&ci->bdaddr, dba) == 0) {
237			*handle = ci->handle;
238			g_free(cl);
239			return 0;
240		}
241	}
242
243	g_free(cl);
244
245	return -ENOENT;
246}
247
248static inline int get_bdaddr(int dev, bdaddr_t *sba, uint16_t handle, bdaddr_t *dba)
249{
250	struct hci_conn_list_req *cl;
251	struct hci_conn_info *ci;
252	char addr[18];
253	int i;
254
255	cl = g_malloc0(10 * sizeof(*ci) + sizeof(*cl));
256
257	ba2str(sba, addr);
258	cl->dev_id = hci_devid(addr);
259	cl->conn_num = 10;
260	ci = cl->conn_info;
261
262	if (ioctl(dev, HCIGETCONNLIST, (void *) cl) < 0) {
263		g_free(cl);
264		return -EIO;
265	}
266
267	for (i = 0; i < cl->conn_num; i++, ci++)
268		if (ci->handle == handle) {
269			bacpy(dba, &ci->bdaddr);
270			g_free(cl);
271			return 0;
272		}
273
274	g_free(cl);
275
276	return -ENOENT;
277}
278
279static inline void update_lastseen(bdaddr_t *sba, bdaddr_t *dba)
280{
281	time_t t;
282	struct tm *tm;
283
284	t = time(NULL);
285	tm = gmtime(&t);
286
287	write_lastseen_info(sba, dba, tm);
288}
289
290static inline void update_lastused(bdaddr_t *sba, bdaddr_t *dba)
291{
292	time_t t;
293	struct tm *tm;
294
295	t = time(NULL);
296	tm = gmtime(&t);
297
298	write_lastused_info(sba, dba, tm);
299}
300
301/* Link Key handling */
302
303static void link_key_request(int dev, bdaddr_t *sba, bdaddr_t *dba)
304{
305	struct btd_adapter *adapter;
306	struct btd_device *device;
307	struct hci_auth_info_req req;
308	unsigned char key[16];
309	char sa[18], da[18];
310	uint8_t type;
311	int err;
312
313	if (!get_adapter_and_device(sba, dba, &adapter, &device, FALSE))
314		device = NULL;
315
316	ba2str(sba, sa); ba2str(dba, da);
317	info("link_key_request (sba=%s, dba=%s)", sa, da);
318
319	memset(&req, 0, sizeof(req));
320	bacpy(&req.bdaddr, dba);
321
322	err = ioctl(dev, HCIGETAUTHINFO, (unsigned long) &req);
323	if (err < 0) {
324		if (errno != EINVAL)
325			DBG("HCIGETAUTHINFO failed %s (%d)",
326						strerror(errno), errno);
327		req.type = 0x00;
328	}
329
330	DBG("kernel auth requirements = 0x%02x", req.type);
331
332	if (main_opts.debug_keys && device && device_get_debug_key(device, key))
333		type = 0x03;
334	else if (read_link_key(sba, dba, key, &type) < 0 || type == 0x03) {
335		/* Link key not found */
336		hci_send_cmd(dev, OGF_LINK_CTL, OCF_LINK_KEY_NEG_REPLY, 6, dba);
337		return;
338	}
339
340	/* Link key found */
341
342	DBG("link key type = 0x%02x", type);
343
344	/* Don't use unauthenticated combination keys if MITM is
345	 * required */
346	if (type == 0x04 && req.type != 0xff && (req.type & 0x01))
347		hci_send_cmd(dev, OGF_LINK_CTL, OCF_LINK_KEY_NEG_REPLY,
348								6, dba);
349	else {
350		link_key_reply_cp lr;
351
352		memcpy(lr.link_key, key, 16);
353		bacpy(&lr.bdaddr, dba);
354
355		hci_send_cmd(dev, OGF_LINK_CTL, OCF_LINK_KEY_REPLY,
356						LINK_KEY_REPLY_CP_SIZE, &lr);
357	}
358}
359
360static void link_key_notify(int dev, bdaddr_t *sba, void *ptr)
361{
362	evt_link_key_notify *evt = ptr;
363	bdaddr_t *dba = &evt->bdaddr;
364	char sa[18], da[18];
365	int dev_id, err;
366	unsigned char old_key[16];
367	uint8_t old_key_type;
368
369	ba2str(sba, sa); ba2str(dba, da);
370	info("link_key_notify (sba=%s, dba=%s, type=%d)", sa, da,
371							evt->key_type);
372
373	err = read_link_key(sba, dba, old_key, &old_key_type);
374	if (err < 0)
375		old_key_type = 0xff;
376
377	dev_id = hci_devid(sa);
378	if (dev_id < 0)
379		err = -errno;
380	else {
381		err = hcid_dbus_link_key_notify(sba, dba, evt->link_key,
382						evt->key_type,
383						io_data[dev_id].pin_length,
384						old_key_type);
385		io_data[dev_id].pin_length = -1;
386	}
387
388	if (err < 0) {
389		uint16_t handle;
390
391		if (err == -ENODEV)
392			hcid_dbus_bonding_process_complete(sba, dba,
393							HCI_OE_LOW_RESOURCES);
394		else
395			hcid_dbus_bonding_process_complete(sba, dba,
396							HCI_MEMORY_FULL);
397
398		if (get_handle(dev, sba, dba, &handle) == 0) {
399			disconnect_cp cp;
400
401			memset(&cp, 0, sizeof(cp));
402			cp.handle = htobs(handle);
403			cp.reason = HCI_OE_LOW_RESOURCES;
404
405			hci_send_cmd(dev, OGF_LINK_CTL, OCF_DISCONNECT,
406						DISCONNECT_CP_SIZE, &cp);
407		}
408	}
409}
410
411static void return_link_keys(int dev, bdaddr_t *sba, void *ptr)
412{
413	evt_return_link_keys *evt = ptr;
414	uint8_t num = evt->num_keys;
415	unsigned char key[16];
416	char sa[18], da[18];
417	bdaddr_t dba;
418	int i;
419
420	ba2str(sba, sa);
421	ptr++;
422
423	for (i = 0; i < num; i++) {
424		bacpy(&dba, ptr); ba2str(&dba, da);
425		memcpy(key, ptr + 6, 16);
426
427		info("return_link_keys (sba=%s, dba=%s)", sa, da);
428
429		hcid_dbus_returned_link_key(sba, &dba);
430
431		ptr += 22;
432	}
433}
434
435/* Simple Pairing handling */
436
437static void user_confirm_request(int dev, bdaddr_t *sba, void *ptr)
438{
439	evt_user_confirm_request *req = ptr;
440
441	if (hcid_dbus_user_confirm(sba, &req->bdaddr,
442					btohl(req->passkey)) < 0)
443		hci_send_cmd(dev, OGF_LINK_CTL,
444				OCF_USER_CONFIRM_NEG_REPLY, 6, ptr);
445}
446
447static void user_passkey_request(int dev, bdaddr_t *sba, void *ptr)
448{
449	evt_user_passkey_request *req = ptr;
450
451	if (hcid_dbus_user_passkey(sba, &req->bdaddr) < 0)
452		hci_send_cmd(dev, OGF_LINK_CTL,
453				OCF_USER_PASSKEY_NEG_REPLY, 6, ptr);
454}
455
456static void user_passkey_notify(int dev, bdaddr_t *sba, void *ptr)
457{
458	evt_user_passkey_notify *req = ptr;
459
460	hcid_dbus_user_notify(sba, &req->bdaddr, btohl(req->passkey));
461}
462
463static void remote_oob_data_request(int dev, bdaddr_t *sba, void *ptr)
464{
465	evt_remote_oob_data_request *req = ptr;
466
467	if (hcid_dbus_get_oob_data(sba, &req->bdaddr) < 0)
468		hci_send_cmd(dev, OGF_LINK_CTL, OCF_REMOTE_OOB_DATA_NEG_REPLY,
469				6, ptr);
470}
471
472static void io_capa_request(int dev, bdaddr_t *sba, bdaddr_t *dba)
473{
474	char sa[18], da[18];
475
476	ba2str(sba, sa);
477	ba2str(dba, da);
478	info("io_capa_request (sba=%s, dba=%s)", sa, da);
479
480	if (hcid_dbus_get_io_cap(sba, dba) < 0) {
481		io_capability_neg_reply_cp cp;
482		memset(&cp, 0, sizeof(cp));
483		bacpy(&cp.bdaddr, dba);
484		cp.reason = HCI_PAIRING_NOT_ALLOWED;
485		hci_send_cmd(dev, OGF_LINK_CTL, OCF_IO_CAPABILITY_NEG_REPLY,
486					IO_CAPABILITY_NEG_REPLY_CP_SIZE, &cp);
487	}
488}
489
490static void io_capa_response(int dev, bdaddr_t *sba, void *ptr)
491{
492	evt_io_capability_response *evt = ptr;
493	char sa[18], da[18];
494
495	ba2str(sba, sa); ba2str(&evt->bdaddr, da);
496	info("io_capa_response (sba=%s, dba=%s)", sa, da);
497
498	hcid_dbus_set_io_cap(sba, &evt->bdaddr,
499				evt->capability, evt->authentication);
500}
501
502/* PIN code handling */
503
504void set_pin_length(bdaddr_t *sba, int length)
505{
506	char addr[18];
507	int dev_id;
508
509	ba2str(sba, addr);
510	dev_id = hci_devid(addr);
511
512	if (dev_id >= 0)
513		io_data[dev_id].pin_length = length;
514}
515
516static void pin_code_request(int dev, bdaddr_t *sba, bdaddr_t *dba)
517{
518	pin_code_reply_cp pr;
519	struct hci_conn_info_req *cr;
520	struct hci_conn_info *ci;
521	char sa[18], da[18], pin[17];
522	int pinlen;
523
524	memset(&pr, 0, sizeof(pr));
525	bacpy(&pr.bdaddr, dba);
526
527	ba2str(sba, sa); ba2str(dba, da);
528	info("pin_code_request (sba=%s, dba=%s)", sa, da);
529
530	cr = g_malloc0(sizeof(*cr) + sizeof(*ci));
531
532	bacpy(&cr->bdaddr, dba);
533	cr->type = ACL_LINK;
534	if (ioctl(dev, HCIGETCONNINFO, (unsigned long) cr) < 0) {
535		error("Can't get conn info: %s (%d)", strerror(errno), errno);
536		goto reject;
537	}
538	ci = cr->conn_info;
539
540	memset(pin, 0, sizeof(pin));
541	pinlen = read_pin_code(sba, dba, pin);
542
543	if (pinlen > 0) {
544		set_pin_length(sba, pinlen);
545		memcpy(pr.pin_code, pin, pinlen);
546		pr.pin_len = pinlen;
547		hci_send_cmd(dev, OGF_LINK_CTL, OCF_PIN_CODE_REPLY,
548				PIN_CODE_REPLY_CP_SIZE, &pr);
549	} else {
550		/* Request PIN from passkey agent */
551		if (hcid_dbus_request_pin(dev, sba, ci) < 0)
552			goto reject;
553	}
554
555	g_free(cr);
556
557	return;
558
559reject:
560	g_free(cr);
561
562	hci_send_cmd(dev, OGF_LINK_CTL, OCF_PIN_CODE_NEG_REPLY, 6, dba);
563}
564
565static void start_inquiry(bdaddr_t *local, uint8_t status, gboolean periodic)
566{
567	struct btd_adapter *adapter;
568	int state;
569
570	/* Don't send the signal if the cmd failed */
571	if (status) {
572		error("Inquiry Failed with status 0x%02x", status);
573		return;
574	}
575
576	adapter = manager_find_adapter(local);
577	if (!adapter) {
578		error("Unable to find matching adapter");
579		return;
580	}
581
582	state = adapter_get_state(adapter);
583
584	/* Disable name resolution for non D-Bus clients */
585	if (!adapter_has_discov_sessions(adapter))
586		state &= ~RESOLVE_NAME;
587
588	if (periodic) {
589		state |= PERIODIC_INQUIRY;
590		adapter_set_state(adapter, state);
591		return;
592	}
593
594	state |= STD_INQUIRY;
595	adapter_set_state(adapter, state);
596
597	/*
598	 * Cancel pending remote name request and clean the device list
599	 * when inquiry is supported in periodic inquiry idle state.
600	 */
601	if (adapter_get_state(adapter) & PERIODIC_INQUIRY) {
602		pending_remote_name_cancel(adapter);
603
604		clear_found_devices_list(adapter);
605	}
606}
607
608static void inquiry_complete(bdaddr_t *local, uint8_t status, gboolean periodic)
609{
610	struct btd_adapter *adapter;
611	int state;
612
613	/* Don't send the signal if the cmd failed */
614	if (status) {
615		error("Inquiry Failed with status 0x%02x", status);
616		return;
617	}
618
619	adapter = manager_find_adapter(local);
620	if (!adapter) {
621		error("Unable to find matching adapter");
622		return;
623	}
624
625	/*
626	 * The following scenarios can happen:
627	 * 1. standard inquiry: always send discovery completed signal
628	 * 2. standard inquiry + name resolving: send discovery completed
629	 *    after name resolving
630	 * 3. periodic inquiry: skip discovery completed signal
631	 * 4. periodic inquiry + standard inquiry: always send discovery
632	 *    completed signal
633	 *
634	 * Keep in mind that non D-Bus requests can arrive.
635	 */
636	if (periodic) {
637		state = adapter_get_state(adapter);
638		state &= ~PERIODIC_INQUIRY;
639		adapter_set_state(adapter, state);
640		return;
641	}
642
643	if (adapter_resolve_names(adapter) == 0)
644		return;
645
646	state = adapter_get_state(adapter);
647	/*
648	 * workaround to identify situation when there is no devices around
649	 * but periodic inquiry is active.
650	 */
651	if (!(state & STD_INQUIRY) && !(state & PERIODIC_INQUIRY)) {
652		state |= PERIODIC_INQUIRY;
653		adapter_set_state(adapter, state);
654		return;
655	}
656
657	/* reset the discover type to be able to handle D-Bus and non D-Bus
658	 * requests */
659	state &= ~STD_INQUIRY;
660	state &= ~PERIODIC_INQUIRY;
661	adapter_set_state(adapter, state);
662}
663
664static inline void remote_features_notify(int dev, bdaddr_t *sba, void *ptr)
665{
666	evt_remote_host_features_notify *evt = ptr;
667
668	if (evt->features[0] & 0x01)
669		hcid_dbus_set_legacy_pairing(sba, &evt->bdaddr, FALSE);
670	else
671		hcid_dbus_set_legacy_pairing(sba, &evt->bdaddr, TRUE);
672
673	write_features_info(sba, &evt->bdaddr, NULL, evt->features);
674}
675
676static inline void cmd_status(int dev, bdaddr_t *sba, void *ptr)
677{
678	evt_cmd_status *evt = ptr;
679	uint16_t opcode = btohs(evt->opcode);
680
681	if (opcode == cmd_opcode_pack(OGF_LINK_CTL, OCF_INQUIRY))
682		start_inquiry(sba, evt->status, FALSE);
683}
684
685static inline void cmd_complete(int dev, bdaddr_t *sba, void *ptr)
686{
687	evt_cmd_complete *evt = ptr;
688	uint16_t opcode = btohs(evt->opcode);
689	uint8_t status = *((uint8_t *) ptr + EVT_CMD_COMPLETE_SIZE);
690
691	switch (opcode) {
692	case cmd_opcode_pack(OGF_LINK_CTL, OCF_PERIODIC_INQUIRY):
693		start_inquiry(sba, status, TRUE);
694		break;
695	case cmd_opcode_pack(OGF_LINK_CTL, OCF_EXIT_PERIODIC_INQUIRY):
696		inquiry_complete(sba, status, TRUE);
697		break;
698	case cmd_opcode_pack(OGF_LINK_CTL, OCF_INQUIRY_CANCEL):
699		inquiry_complete(sba, status, FALSE);
700		break;
701	case cmd_opcode_pack(OGF_HOST_CTL, OCF_CHANGE_LOCAL_NAME):
702		adapter_setname_complete(sba, status);
703		break;
704	case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_SCAN_ENABLE):
705		hcid_dbus_setscan_enable_complete(sba);
706		break;
707	case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_CLASS_OF_DEV):
708		adapter_set_class_complete(sba, status);
709		break;
710	case cmd_opcode_pack(OGF_HOST_CTL, OCF_WRITE_SIMPLE_PAIRING_MODE):
711		hcid_dbus_write_simple_pairing_mode_complete(sba);
712		break;
713	case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_LOCAL_NAME):
714		ptr += sizeof(evt_cmd_complete);
715		adapter_update_local_name(sba, status, ptr);
716		break;
717	case cmd_opcode_pack(OGF_HOST_CTL, OCF_READ_INQ_RESPONSE_TX_POWER_LEVEL):
718		ptr += sizeof(evt_cmd_complete);
719		adapter_update_tx_power(sba, status, ptr);
720		break;
721	};
722}
723
724static inline void remote_name_information(int dev, bdaddr_t *sba, void *ptr)
725{
726	evt_remote_name_req_complete *evt = ptr;
727	bdaddr_t dba;
728	char name[MAX_NAME_LENGTH + 1];
729
730	memset(name, 0, sizeof(name));
731	bacpy(&dba, &evt->bdaddr);
732
733	if (!evt->status) {
734		char *end;
735		memcpy(name, evt->name, MAX_NAME_LENGTH);
736		/* It's ok to cast end between const and non-const since
737		 * we know it points to inside of name which is non-const */
738		if (!g_utf8_validate(name, -1, (const char **) &end))
739			*end = '\0';
740		write_device_name(sba, &dba, name);
741	}
742
743	hcid_dbus_remote_name(sba, &dba, evt->status, name);
744}
745
746static inline void remote_version_information(int dev, bdaddr_t *sba, void *ptr)
747{
748	evt_read_remote_version_complete *evt = ptr;
749	bdaddr_t dba;
750
751	if (evt->status)
752		return;
753
754	if (get_bdaddr(dev, sba, btohs(evt->handle), &dba) < 0)
755		return;
756
757	write_version_info(sba, &dba, btohs(evt->manufacturer),
758				evt->lmp_ver, btohs(evt->lmp_subver));
759}
760
761static inline void inquiry_result(int dev, bdaddr_t *sba, int plen, void *ptr)
762{
763	uint8_t num = *(uint8_t *) ptr++;
764	int i;
765
766	for (i = 0; i < num; i++) {
767		inquiry_info *info = ptr;
768		uint32_t class = info->dev_class[0]
769			| (info->dev_class[1] << 8)
770			| (info->dev_class[2] << 16);
771
772		hcid_dbus_inquiry_result(sba, &info->bdaddr, class, 0, NULL);
773
774		update_lastseen(sba, &info->bdaddr);
775
776		ptr += INQUIRY_INFO_SIZE;
777	}
778}
779
780static inline void inquiry_result_with_rssi(int dev, bdaddr_t *sba,
781							int plen, void *ptr)
782{
783	uint8_t num = *(uint8_t *) ptr++;
784	int i;
785
786	if (!num)
787		return;
788
789	if ((plen - 1) / num == INQUIRY_INFO_WITH_RSSI_AND_PSCAN_MODE_SIZE) {
790		for (i = 0; i < num; i++) {
791			inquiry_info_with_rssi_and_pscan_mode *info = ptr;
792			uint32_t class = info->dev_class[0]
793				| (info->dev_class[1] << 8)
794				| (info->dev_class[2] << 16);
795
796			hcid_dbus_inquiry_result(sba, &info->bdaddr,
797						class, info->rssi, NULL);
798
799			update_lastseen(sba, &info->bdaddr);
800
801			ptr += INQUIRY_INFO_WITH_RSSI_AND_PSCAN_MODE_SIZE;
802		}
803	} else {
804		for (i = 0; i < num; i++) {
805			inquiry_info_with_rssi *info = ptr;
806			uint32_t class = info->dev_class[0]
807				| (info->dev_class[1] << 8)
808				| (info->dev_class[2] << 16);
809
810			hcid_dbus_inquiry_result(sba, &info->bdaddr,
811						class, info->rssi, NULL);
812
813			update_lastseen(sba, &info->bdaddr);
814
815			ptr += INQUIRY_INFO_WITH_RSSI_SIZE;
816		}
817	}
818}
819
820static inline void extended_inquiry_result(int dev, bdaddr_t *sba,
821							int plen, void *ptr)
822{
823	uint8_t num = *(uint8_t *) ptr++;
824	int i;
825
826	for (i = 0; i < num; i++) {
827		extended_inquiry_info *info = ptr;
828		uint32_t class = info->dev_class[0]
829			| (info->dev_class[1] << 8)
830			| (info->dev_class[2] << 16);
831
832		hcid_dbus_inquiry_result(sba, &info->bdaddr, class,
833						info->rssi, info->data);
834
835		update_lastseen(sba, &info->bdaddr);
836
837		ptr += EXTENDED_INQUIRY_INFO_SIZE;
838	}
839}
840
841static inline void remote_features_information(int dev, bdaddr_t *sba,
842								void *ptr)
843{
844	evt_read_remote_features_complete *evt = ptr;
845	bdaddr_t dba;
846
847	if (evt->status)
848		return;
849
850	if (get_bdaddr(dev, sba, btohs(evt->handle), &dba) < 0)
851		return;
852
853	write_features_info(sba, &dba, evt->features, NULL);
854}
855
856static inline void conn_complete(int dev, int dev_id, bdaddr_t *sba, void *ptr)
857{
858	evt_conn_complete *evt = ptr;
859	char filename[PATH_MAX];
860	remote_name_req_cp cp_name;
861	struct hci_req_data *data;
862	char local_addr[18], peer_addr[18], *str;
863
864	if (evt->link_type != ACL_LINK)
865		return;
866
867	hcid_dbus_conn_complete(sba, evt->status, btohs(evt->handle),
868				&evt->bdaddr);
869
870	if (evt->status)
871		return;
872
873	update_lastused(sba, &evt->bdaddr);
874
875	/* Request remote name */
876	memset(&cp_name, 0, sizeof(cp_name));
877	bacpy(&cp_name.bdaddr, &evt->bdaddr);
878	cp_name.pscan_rep_mode = 0x02;
879
880	data = hci_req_data_new(dev_id, &evt->bdaddr, OGF_LINK_CTL,
881				OCF_REMOTE_NAME_REQ,
882				EVT_REMOTE_NAME_REQ_COMPLETE,
883				&cp_name, REMOTE_NAME_REQ_CP_SIZE);
884
885	hci_req_queue_append(data);
886
887	/* check if the remote version needs be requested */
888	ba2str(sba, local_addr);
889	ba2str(&evt->bdaddr, peer_addr);
890
891	create_name(filename, sizeof(filename), STORAGEDIR, local_addr,
892							"manufacturers");
893
894	str = textfile_get(filename, peer_addr);
895	if (!str) {
896		read_remote_version_cp cp;
897
898		memset(&cp, 0, sizeof(cp));
899		cp.handle = evt->handle;
900
901		data = hci_req_data_new(dev_id, &evt->bdaddr, OGF_LINK_CTL,
902					OCF_READ_REMOTE_VERSION,
903					EVT_READ_REMOTE_VERSION_COMPLETE,
904					&cp, READ_REMOTE_VERSION_CP_SIZE);
905
906		hci_req_queue_append(data);
907	} else
908		free(str);
909}
910
911static inline void disconn_complete(int dev, bdaddr_t *sba, void *ptr)
912{
913	evt_disconn_complete *evt = ptr;
914
915	hcid_dbus_disconn_complete(sba, evt->status, btohs(evt->handle),
916					evt->reason);
917}
918
919static inline void auth_complete(int dev, bdaddr_t *sba, void *ptr)
920{
921	evt_auth_complete *evt = ptr;
922	bdaddr_t dba;
923
924	if (get_bdaddr(dev, sba, btohs(evt->handle), &dba) < 0)
925		return;
926
927	hcid_dbus_bonding_process_complete(sba, &dba, evt->status);
928}
929
930static inline void simple_pairing_complete(int dev, bdaddr_t *sba, void *ptr)
931{
932	evt_simple_pairing_complete *evt = ptr;
933
934	hcid_dbus_simple_pairing_complete(sba, &evt->bdaddr, evt->status);
935}
936
937static inline void conn_request(int dev, bdaddr_t *sba, void *ptr)
938{
939	evt_conn_request *evt = ptr;
940	uint32_t class = evt->dev_class[0] | (evt->dev_class[1] << 8)
941				| (evt->dev_class[2] << 16);
942
943	hcid_dbus_remote_class(sba, &evt->bdaddr, class);
944
945	write_remote_class(sba, &evt->bdaddr, class);
946}
947
948static void delete_channel(GIOChannel *chan)
949{
950	int i;
951
952	/* Look for the GIOChannel in the table */
953	for (i = 0; i < HCI_MAX_DEV; i++)
954		if (io_data[i].channel == chan) {
955			stop_security_manager(i);
956			return;
957		}
958
959	error("IO channel not found in the io_data table");
960}
961
962static gboolean io_security_event(GIOChannel *chan, GIOCondition cond,
963								gpointer data)
964{
965	unsigned char buf[HCI_MAX_EVENT_SIZE], *ptr = buf;
966	struct hci_dev_info *di = data;
967	int type, dev;
968	size_t len;
969	hci_event_hdr *eh;
970	GIOError err;
971	evt_cmd_status *evt;
972
973	if (cond & (G_IO_NVAL | G_IO_HUP | G_IO_ERR)) {
974		delete_channel(chan);
975		return FALSE;
976	}
977
978	if ((err = g_io_channel_read(chan, (gchar *) buf, sizeof(buf), &len))) {
979		if (err == G_IO_ERROR_AGAIN)
980			return TRUE;
981		delete_channel(chan);
982		return FALSE;
983	}
984
985	type = *ptr++;
986
987	if (type != HCI_EVENT_PKT)
988		return TRUE;
989
990	eh = (hci_event_hdr *) ptr;
991	ptr += HCI_EVENT_HDR_SIZE;
992
993	dev = g_io_channel_unix_get_fd(chan);
994
995	ioctl(dev, HCIGETDEVINFO, (void *) di);
996
997	if (hci_test_bit(HCI_RAW, &di->flags))
998		return TRUE;
999
1000	switch (eh->evt) {
1001	case EVT_CMD_STATUS:
1002		cmd_status(dev, &di->bdaddr, ptr);
1003		break;
1004
1005	case EVT_CMD_COMPLETE:
1006		cmd_complete(dev, &di->bdaddr, ptr);
1007		break;
1008
1009	case EVT_REMOTE_NAME_REQ_COMPLETE:
1010		remote_name_information(dev, &di->bdaddr, ptr);
1011		break;
1012
1013	case EVT_READ_REMOTE_VERSION_COMPLETE:
1014		remote_version_information(dev, &di->bdaddr, ptr);
1015		break;
1016
1017	case EVT_READ_REMOTE_FEATURES_COMPLETE:
1018		remote_features_information(dev, &di->bdaddr, ptr);
1019		break;
1020
1021	case EVT_REMOTE_HOST_FEATURES_NOTIFY:
1022		remote_features_notify(dev, &di->bdaddr, ptr);
1023		break;
1024
1025	case EVT_INQUIRY_COMPLETE:
1026		evt = (evt_cmd_status *) ptr;
1027		inquiry_complete(&di->bdaddr, evt->status, FALSE);
1028		break;
1029
1030	case EVT_INQUIRY_RESULT:
1031		inquiry_result(dev, &di->bdaddr, eh->plen, ptr);
1032		break;
1033
1034	case EVT_INQUIRY_RESULT_WITH_RSSI:
1035		inquiry_result_with_rssi(dev, &di->bdaddr, eh->plen, ptr);
1036		break;
1037
1038	case EVT_EXTENDED_INQUIRY_RESULT:
1039		extended_inquiry_result(dev, &di->bdaddr, eh->plen, ptr);
1040		break;
1041
1042	case EVT_CONN_COMPLETE:
1043		conn_complete(dev, di->dev_id, &di->bdaddr, ptr);
1044		break;
1045
1046	case EVT_DISCONN_COMPLETE:
1047		disconn_complete(dev, &di->bdaddr, ptr);
1048		break;
1049
1050	case EVT_AUTH_COMPLETE:
1051		auth_complete(dev, &di->bdaddr, ptr);
1052		break;
1053
1054	case EVT_SIMPLE_PAIRING_COMPLETE:
1055		simple_pairing_complete(dev, &di->bdaddr, ptr);
1056		break;
1057
1058	case EVT_CONN_REQUEST:
1059		conn_request(dev, &di->bdaddr, ptr);
1060		break;
1061	}
1062
1063	/* Check for pending command request */
1064	check_pending_hci_req(di->dev_id, eh->evt);
1065
1066	switch (eh->evt) {
1067	case EVT_PIN_CODE_REQ:
1068		pin_code_request(dev, &di->bdaddr, (bdaddr_t *) ptr);
1069		break;
1070
1071	case EVT_LINK_KEY_REQ:
1072		link_key_request(dev, &di->bdaddr, (bdaddr_t *) ptr);
1073		break;
1074
1075	case EVT_LINK_KEY_NOTIFY:
1076		link_key_notify(dev, &di->bdaddr, ptr);
1077		break;
1078
1079	case EVT_RETURN_LINK_KEYS:
1080		return_link_keys(dev, &di->bdaddr, ptr);
1081		break;
1082
1083	case EVT_IO_CAPABILITY_REQUEST:
1084		io_capa_request(dev, &di->bdaddr, (bdaddr_t *) ptr);
1085		break;
1086
1087	case EVT_IO_CAPABILITY_RESPONSE:
1088		io_capa_response(dev, &di->bdaddr, ptr);
1089		break;
1090
1091	case EVT_USER_CONFIRM_REQUEST:
1092		user_confirm_request(dev, &di->bdaddr, ptr);
1093		break;
1094
1095	case EVT_USER_PASSKEY_REQUEST:
1096		user_passkey_request(dev, &di->bdaddr, ptr);
1097		break;
1098
1099	case EVT_USER_PASSKEY_NOTIFY:
1100		user_passkey_notify(dev, &di->bdaddr, ptr);
1101		break;
1102
1103	case EVT_REMOTE_OOB_DATA_REQUEST:
1104		remote_oob_data_request(dev, &di->bdaddr, ptr);
1105		break;
1106	}
1107
1108	return TRUE;
1109}
1110
1111void start_security_manager(int hdev)
1112{
1113	GIOChannel *chan = io_data[hdev].channel;
1114	struct hci_dev_info *di;
1115	struct hci_filter flt;
1116	read_stored_link_key_cp cp;
1117	int dev;
1118
1119	if (chan)
1120		return;
1121
1122	info("Starting security manager %d", hdev);
1123
1124	if ((dev = hci_open_dev(hdev)) < 0) {
1125		error("Can't open device hci%d: %s (%d)",
1126						hdev, strerror(errno), errno);
1127		return;
1128	}
1129
1130	/* Set filter */
1131	hci_filter_clear(&flt);
1132	hci_filter_set_ptype(HCI_EVENT_PKT, &flt);
1133	hci_filter_set_event(EVT_CMD_STATUS, &flt);
1134	hci_filter_set_event(EVT_CMD_COMPLETE, &flt);
1135	hci_filter_set_event(EVT_PIN_CODE_REQ, &flt);
1136	hci_filter_set_event(EVT_LINK_KEY_REQ, &flt);
1137	hci_filter_set_event(EVT_LINK_KEY_NOTIFY, &flt);
1138	hci_filter_set_event(EVT_RETURN_LINK_KEYS, &flt);
1139	hci_filter_set_event(EVT_IO_CAPABILITY_REQUEST, &flt);
1140	hci_filter_set_event(EVT_IO_CAPABILITY_RESPONSE, &flt);
1141	hci_filter_set_event(EVT_USER_CONFIRM_REQUEST, &flt);
1142	hci_filter_set_event(EVT_USER_PASSKEY_REQUEST, &flt);
1143	hci_filter_set_event(EVT_REMOTE_OOB_DATA_REQUEST, &flt);
1144	hci_filter_set_event(EVT_USER_PASSKEY_NOTIFY, &flt);
1145	hci_filter_set_event(EVT_KEYPRESS_NOTIFY, &flt);
1146	hci_filter_set_event(EVT_SIMPLE_PAIRING_COMPLETE, &flt);
1147	hci_filter_set_event(EVT_AUTH_COMPLETE, &flt);
1148	hci_filter_set_event(EVT_REMOTE_NAME_REQ_COMPLETE, &flt);
1149	hci_filter_set_event(EVT_READ_REMOTE_VERSION_COMPLETE, &flt);
1150	hci_filter_set_event(EVT_READ_REMOTE_FEATURES_COMPLETE, &flt);
1151	hci_filter_set_event(EVT_REMOTE_HOST_FEATURES_NOTIFY, &flt);
1152	hci_filter_set_event(EVT_INQUIRY_COMPLETE, &flt);
1153	hci_filter_set_event(EVT_INQUIRY_RESULT, &flt);
1154	hci_filter_set_event(EVT_INQUIRY_RESULT_WITH_RSSI, &flt);
1155	hci_filter_set_event(EVT_EXTENDED_INQUIRY_RESULT, &flt);
1156	hci_filter_set_event(EVT_CONN_REQUEST, &flt);
1157	hci_filter_set_event(EVT_CONN_COMPLETE, &flt);
1158	hci_filter_set_event(EVT_DISCONN_COMPLETE, &flt);
1159	if (setsockopt(dev, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) {
1160		error("Can't set filter on hci%d: %s (%d)",
1161						hdev, strerror(errno), errno);
1162		close(dev);
1163		return;
1164	}
1165
1166	di = g_new(struct hci_dev_info, 1);
1167	if (hci_devinfo(hdev, di) < 0) {
1168		error("Can't get device info: %s (%d)",
1169							strerror(errno), errno);
1170		close(dev);
1171		g_free(di);
1172		return;
1173	}
1174
1175	chan = g_io_channel_unix_new(dev);
1176	g_io_channel_set_close_on_unref(chan, TRUE);
1177	io_data[hdev].watch_id = g_io_add_watch_full(chan, G_PRIORITY_LOW,
1178						G_IO_IN | G_IO_NVAL | G_IO_HUP | G_IO_ERR,
1179						io_security_event, di, (GDestroyNotify) g_free);
1180	io_data[hdev].channel = chan;
1181	io_data[hdev].pin_length = -1;
1182
1183	if (hci_test_bit(HCI_RAW, &di->flags))
1184		return;
1185
1186	bacpy(&cp.bdaddr, BDADDR_ANY);
1187	cp.read_all = 1;
1188
1189	hci_send_cmd(dev, OGF_HOST_CTL, OCF_READ_STORED_LINK_KEY,
1190			READ_STORED_LINK_KEY_CP_SIZE, (void *) &cp);
1191}
1192
1193void stop_security_manager(int hdev)
1194{
1195	GIOChannel *chan = io_data[hdev].channel;
1196
1197	if (!chan)
1198		return;
1199
1200	info("Stopping security manager %d", hdev);
1201
1202	g_source_remove(io_data[hdev].watch_id);
1203	g_io_channel_unref(io_data[hdev].channel);
1204	io_data[hdev].watch_id = -1;
1205	io_data[hdev].channel = NULL;
1206	io_data[hdev].pin_length = -1;
1207}
1208
1209