main.c revision a3fbc8a1d14cd97eb9d59db2fcf9ce9fd4c64ec7
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-2008  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 <fcntl.h>
33#include <unistd.h>
34#include <stdlib.h>
35#include <string.h>
36#include <signal.h>
37#include <sys/stat.h>
38#include <sys/ioctl.h>
39#include <sys/socket.h>
40#include <sys/types.h>
41#include <sys/wait.h>
42
43#include <bluetooth/bluetooth.h>
44#include <bluetooth/hci.h>
45#include <bluetooth/hci_lib.h>
46
47#include <glib.h>
48
49#include <dbus/dbus.h>
50
51#include "logging.h"
52
53#include "hcid.h"
54#include "sdpd.h"
55#include "adapter.h"
56#include "dbus-hci.h"
57#include "dbus-common.h"
58#include "agent.h"
59#include "manager.h"
60#include "storage.h"
61
62#define HCID_DEFAULT_DISCOVERABLE_TIMEOUT 180 /* 3 minutes */
63
64enum {
65	HCID_SET_NAME,
66	HCID_SET_CLASS,
67	HCID_SET_PAGETO,
68	HCID_SET_DISCOVTO,
69};
70
71struct main_opts main_opts;
72
73static int child_pipe[2];
74
75static GKeyFile *load_config(const char *file)
76{
77	GError *err = NULL;
78	GKeyFile *keyfile;
79
80	keyfile = g_key_file_new();
81
82	g_key_file_set_list_separator(keyfile, ',');
83
84	if (!g_key_file_load_from_file(keyfile, file, 0, &err)) {
85		error("Parsing %s failed: %s", file, err->message);
86		g_error_free(err);
87		g_key_file_free(keyfile);
88		return NULL;
89	}
90
91	return keyfile;
92}
93
94static void parse_config(GKeyFile *config)
95{
96	GError *err = NULL;
97	char *str;
98	int val;
99
100	if (!config)
101		return;
102
103	debug("parsing main.conf");
104
105	str = g_key_file_get_string(config, "General",
106					"OffMode", &err);
107	if (err) {
108		debug("%s", err->message);
109		g_error_free(err);
110		err = NULL;
111	} else {
112		debug("offmode=%s", str);
113		if (g_str_equal(str, "DevDown"))
114			main_opts.offmode = HCID_OFFMODE_DEVDOWN;
115		g_free(str);
116	}
117
118	val = g_key_file_get_integer(config, "General",
119					"DiscoverableTimeout",
120					&err);
121	if (err) {
122		debug("%s", err->message);
123		g_error_free(err);
124		err = NULL;
125	} else {
126		debug("discovto=%d", val);
127		main_opts.discovto = val;
128		main_opts.flags |= 1 << HCID_SET_DISCOVTO;
129	}
130
131	val = g_key_file_get_integer(config, "General",
132					"PageTimeout",
133					&err);
134	if (err) {
135		debug("%s", err->message);
136		g_error_free(err);
137		err = NULL;
138	} else {
139		debug("pageto=%d", val);
140		main_opts.pageto = val;
141		main_opts.flags |= 1 << HCID_SET_PAGETO;
142	}
143
144	str = g_key_file_get_string(config, "General",
145					"Name", &err);
146	if (err) {
147		debug("%s", err->message);
148		g_error_free(err);
149		err = NULL;
150	} else {
151		debug("name=%s", str);
152		g_free(main_opts.name);
153		main_opts.name = g_strdup(str);
154		main_opts.flags |= 1 << HCID_SET_NAME;
155		g_free(str);
156	}
157
158	str = g_key_file_get_string(config, "General",
159					"Class", &err);
160	if (err) {
161		debug("%s", err->message);
162		g_error_free(err);
163		err = NULL;
164	} else {
165		debug("class=%s", str);
166		main_opts.class = strtol(str, NULL, 16);
167		main_opts.flags |= 1 << HCID_SET_CLASS;
168		g_free(str);
169	}
170
171	val = g_key_file_get_integer(config, "General",
172					"DiscoverSchedulerInterval",
173					&err);
174	if (err) {
175		debug("%s", err->message);
176		g_error_free(err);
177		err = NULL;
178	} else {
179		debug("inqmode=%d", val);
180		main_opts.inqmode = val;
181	}
182
183	main_opts.link_mode = HCI_LM_ACCEPT;
184
185	main_opts.link_policy = HCI_LP_RSWITCH | HCI_LP_SNIFF |
186						HCI_LP_HOLD | HCI_LP_PARK;
187}
188
189static void update_service_classes(const bdaddr_t *bdaddr, uint8_t value)
190{
191	struct hci_dev_list_req *dl;
192	struct hci_dev_req *dr;
193	int i, sk;
194
195	sk = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI);
196	if (sk < 0)
197		return;
198
199	dl = g_malloc0(HCI_MAX_DEV * sizeof(*dr) + sizeof(*dl));
200
201	dl->dev_num = HCI_MAX_DEV;
202	dr = dl->dev_req;
203
204	if (ioctl(sk, HCIGETDEVLIST, dl) < 0) {
205		close(sk);
206		g_free(dl);
207		return;
208	}
209
210	dr = dl->dev_req;
211
212	for (i = 0; i < dl->dev_num; i++, dr++) {
213		struct hci_dev_info di;
214		uint8_t cls[3];
215		int dd;
216
217		if (hci_devinfo(dr->dev_id, &di) < 0)
218			continue;
219
220		if (hci_test_bit(HCI_RAW, &di.flags))
221			continue;
222
223		if (!hci_test_bit(HCI_UP, &di.flags))
224			continue;
225
226		if (manager_get_adapter_class(di.dev_id, cls) < 0)
227			continue;
228
229		dd = hci_open_dev(di.dev_id);
230		if (dd < 0)
231			continue;
232
233		set_service_classes(dd, cls, value);
234
235		hci_close_dev(dd);
236
237		manager_update_adapter(di.dev_id);
238	}
239
240	g_free(dl);
241
242	close(sk);
243}
244
245/*
246 * Device name expansion
247 *   %d - device id
248 */
249static char *expand_name(char *dst, int size, char *str, int dev_id)
250{
251	register int sp, np, olen;
252	char *opt, buf[10];
253
254	if (!str && !dst)
255		return NULL;
256
257	sp = np = 0;
258	while (np < size - 1 && str[sp]) {
259		switch (str[sp]) {
260		case '%':
261			opt = NULL;
262
263			switch (str[sp+1]) {
264			case 'd':
265				sprintf(buf, "%d", dev_id);
266				opt = buf;
267				break;
268
269			case 'h':
270				opt = main_opts.host_name;
271				break;
272
273			case '%':
274				dst[np++] = str[sp++];
275				/* fall through */
276			default:
277				sp++;
278				continue;
279			}
280
281			if (opt) {
282				/* substitute */
283				olen = strlen(opt);
284				if (np + olen < size - 1)
285					memcpy(dst + np, opt, olen);
286				np += olen;
287			}
288			sp += 2;
289			continue;
290
291		case '\\':
292			sp++;
293			/* fall through */
294		default:
295			dst[np++] = str[sp++];
296			break;
297		}
298	}
299	dst[np] = '\0';
300	return dst;
301}
302
303static gboolean child_exit(GIOChannel *io, GIOCondition cond, void *user_data)
304{
305	int status, fd = g_io_channel_unix_get_fd(io);
306	pid_t child_pid;
307
308	if (read(fd, &child_pid, sizeof(child_pid)) != sizeof(child_pid)) {
309		error("child_exit: unable to read child pid from pipe");
310		return TRUE;
311	}
312
313	if (waitpid(child_pid, &status, 0) != child_pid)
314		error("waitpid(%d) failed", child_pid);
315	else
316		debug("child %d exited", child_pid);
317
318	return TRUE;
319}
320
321static void at_child_exit(void)
322{
323	pid_t pid = getpid();
324
325	if (write(child_pipe[1], &pid, sizeof(pid)) != sizeof(pid))
326		error("unable to write to child pipe");
327}
328
329static void configure_device(int dev_id)
330{
331	struct hci_dev_info di;
332	pid_t pid;
333	int dd;
334
335	if (hci_devinfo(dev_id, &di) < 0)
336		return;
337
338	if (hci_test_bit(HCI_RAW, &di.flags))
339		return;
340
341	/* Do configuration in the separate process */
342	pid = fork();
343	switch (pid) {
344		case 0:
345			atexit(at_child_exit);
346			break;
347		case -1:
348			error("Fork failed. Can't init device hci%d: %s (%d)",
349						dev_id, strerror(errno), errno);
350		default:
351			debug("configuration child %d forked", pid);
352			return;
353	}
354
355	dd = hci_open_dev(dev_id);
356	if (dd < 0) {
357		error("Can't open device hci%d: %s (%d)",
358						dev_id, strerror(errno), errno);
359		exit(1);
360	}
361
362	/* Set device name */
363	if ((main_opts.flags & (1 << HCID_SET_NAME)) && main_opts.name) {
364		change_local_name_cp cp;
365
366		memset(cp.name, 0, sizeof(cp.name));
367		expand_name((char *) cp.name, sizeof(cp.name),
368						main_opts.name, dev_id);
369
370		hci_send_cmd(dd, OGF_HOST_CTL, OCF_CHANGE_LOCAL_NAME,
371					CHANGE_LOCAL_NAME_CP_SIZE, &cp);
372	}
373
374	/* Set device class */
375	if ((main_opts.flags & (1 << HCID_SET_CLASS))) {
376		write_class_of_dev_cp cp;
377		uint32_t class;
378		uint8_t cls[3];
379
380		if (read_local_class(&di.bdaddr, cls) < 0) {
381			class = htobl(main_opts.class);
382			cls[2] = get_service_classes(&di.bdaddr);
383			memcpy(cp.dev_class, &class, 3);
384		} else {
385			if (!(main_opts.scan & SCAN_INQUIRY))
386				cls[1] &= 0xdf; /* Clear discoverable bit */
387			cls[2] = get_service_classes(&di.bdaddr);
388			memcpy(cp.dev_class, cls, 3);
389		}
390
391		hci_send_cmd(dd, OGF_HOST_CTL, OCF_WRITE_CLASS_OF_DEV,
392					WRITE_CLASS_OF_DEV_CP_SIZE, &cp);
393	}
394
395	/* Set page timeout */
396	if ((main_opts.flags & (1 << HCID_SET_PAGETO))) {
397		write_page_timeout_cp cp;
398
399		cp.timeout = htobs(main_opts.pageto);
400		hci_send_cmd(dd, OGF_HOST_CTL, OCF_WRITE_PAGE_TIMEOUT,
401					WRITE_PAGE_TIMEOUT_CP_SIZE, &cp);
402	}
403
404	exit(0);
405}
406
407static void init_device(int dev_id)
408{
409	struct hci_dev_req dr;
410	struct hci_dev_info di;
411	pid_t pid;
412	int dd;
413
414	/* Do initialization in the separate process */
415	pid = fork();
416	switch (pid) {
417		case 0:
418			atexit(at_child_exit);
419			break;
420		case -1:
421			error("Fork failed. Can't init device hci%d: %s (%d)",
422					dev_id, strerror(errno), errno);
423		default:
424			debug("initialization child %d forked", pid);
425			return;
426	}
427
428	dd = hci_open_dev(dev_id);
429	if (dd < 0) {
430		error("Can't open device hci%d: %s (%d)",
431					dev_id, strerror(errno), errno);
432		exit(1);
433	}
434
435	memset(&dr, 0, sizeof(dr));
436	dr.dev_id = dev_id;
437
438	/* Set link mode */
439	dr.dev_opt = main_opts.link_mode;
440	if (ioctl(dd, HCISETLINKMODE, (unsigned long) &dr) < 0) {
441		error("Can't set link mode on hci%d: %s (%d)",
442					dev_id, strerror(errno), errno);
443	}
444
445	/* Set link policy */
446	dr.dev_opt = main_opts.link_policy;
447	if (ioctl(dd, HCISETLINKPOL, (unsigned long) &dr) < 0) {
448		error("Can't set link policy on hci%d: %s (%d)",
449					dev_id, strerror(errno), errno);
450	}
451
452	/* Start HCI device */
453	if (ioctl(dd, HCIDEVUP, dev_id) < 0 && errno != EALREADY) {
454		error("Can't init device hci%d: %s (%d)",
455					dev_id, strerror(errno), errno);
456		goto fail;
457	}
458
459	if (hci_devinfo(dev_id, &di) < 0)
460		goto fail;
461
462	if (hci_test_bit(HCI_RAW, &di.flags))
463		goto done;
464
465	if (main_opts.offmode == HCID_OFFMODE_DEVDOWN) {
466		char mode[16], src[18];
467
468		ba2str(&di.bdaddr, src);
469		if (read_device_mode(src, mode, sizeof(mode)) == 0 &&
470						strcmp(mode, "off") == 0) {
471			ioctl(dd, HCIDEVDOWN, dev_id);
472			goto done;
473		}
474	}
475
476done:
477	hci_close_dev(dd);
478	exit(0);
479
480fail:
481	hci_close_dev(dd);
482	exit(1);
483}
484
485static void device_devreg_setup(int dev_id)
486{
487	struct hci_dev_info di;
488
489	init_device(dev_id);
490
491	if (hci_devinfo(dev_id, &di) < 0)
492		return;
493
494	if (!hci_test_bit(HCI_RAW, &di.flags))
495		manager_register_adapter(dev_id);
496}
497
498static void device_devup_setup(int dev_id)
499{
500	configure_device(dev_id);
501
502	manager_start_adapter(dev_id);
503	start_security_manager(dev_id);
504}
505
506static void init_all_devices(int ctl)
507{
508	struct hci_dev_list_req *dl;
509	struct hci_dev_req *dr;
510	int i;
511
512	dl = g_try_malloc0(HCI_MAX_DEV * sizeof(struct hci_dev_req) + sizeof(uint16_t));
513	if (!dl) {
514		info("Can't allocate devlist buffer: %s (%d)",
515							strerror(errno), errno);
516		exit(1);
517	}
518
519	dl->dev_num = HCI_MAX_DEV;
520	dr = dl->dev_req;
521
522	if (ioctl(ctl, HCIGETDEVLIST, (void *) dl) < 0) {
523		info("Can't get device list: %s (%d)",
524							strerror(errno), errno);
525		exit(1);
526	}
527
528	for (i = 0; i < dl->dev_num; i++, dr++) {
529		info("HCI dev %d registered", dr->dev_id);
530		device_devreg_setup(dr->dev_id);
531		if (hci_test_bit(HCI_UP, &dr->dev_opt)) {
532			info("HCI dev %d already up", dr->dev_id);
533			device_devup_setup(dr->dev_id);
534		}
535	}
536
537	g_free(dl);
538}
539
540static void init_defaults(void)
541{
542	/* Default HCId settings */
543	memset(&main_opts, 0, sizeof(main_opts));
544	main_opts.offmode	= HCID_OFFMODE_NOSCAN;
545	main_opts.scan	= SCAN_PAGE;
546	main_opts.mode	= MODE_CONNECTABLE;
547	main_opts.name	= g_strdup("BlueZ");
548	main_opts.discovto	= HCID_DEFAULT_DISCOVERABLE_TIMEOUT;
549
550	if (gethostname(main_opts.host_name, sizeof(main_opts.host_name) - 1) < 0)
551		strcpy(main_opts.host_name, "noname");
552}
553
554static inline void device_event(GIOChannel *chan, evt_stack_internal *si)
555{
556	evt_si_device *sd = (void *) &si->data;
557
558	switch (sd->event) {
559	case HCI_DEV_REG:
560		info("HCI dev %d registered", sd->dev_id);
561		device_devreg_setup(sd->dev_id);
562		break;
563
564	case HCI_DEV_UNREG:
565		info("HCI dev %d unregistered", sd->dev_id);
566		manager_unregister_adapter(sd->dev_id);
567		break;
568
569	case HCI_DEV_UP:
570		info("HCI dev %d up", sd->dev_id);
571		device_devup_setup(sd->dev_id);
572		break;
573
574	case HCI_DEV_DOWN:
575		info("HCI dev %d down", sd->dev_id);
576		manager_stop_adapter(sd->dev_id);
577		stop_security_manager(sd->dev_id);
578		break;
579	}
580}
581
582static gboolean io_stack_event(GIOChannel *chan, GIOCondition cond, gpointer data)
583{
584	unsigned char buf[HCI_MAX_FRAME_SIZE], *ptr;
585	evt_stack_internal *si;
586	hci_event_hdr *eh;
587	int type;
588	size_t len;
589	GIOError err;
590
591	ptr = buf;
592
593	if ((err = g_io_channel_read(chan, (gchar *) buf, sizeof(buf), &len))) {
594		if (err == G_IO_ERROR_AGAIN)
595			return TRUE;
596
597		error("Read from control socket failed: %s (%d)",
598							strerror(errno), errno);
599		return FALSE;
600	}
601
602	type = *ptr++;
603
604	if (type != HCI_EVENT_PKT)
605		return TRUE;
606
607	eh = (hci_event_hdr *) ptr;
608	if (eh->evt != EVT_STACK_INTERNAL)
609		return TRUE;
610
611	ptr += HCI_EVENT_HDR_SIZE;
612
613	si = (evt_stack_internal *) ptr;
614	switch (si->type) {
615	case EVT_SI_DEVICE:
616		device_event(chan, si);
617		break;
618	}
619
620	return TRUE;
621}
622
623static GMainLoop *event_loop;
624
625static void sig_term(int sig)
626{
627	g_main_loop_quit(event_loop);
628}
629
630static void sig_debug(int sig)
631{
632	toggle_debug();
633}
634
635static gboolean option_detach = TRUE;
636static gboolean option_debug = FALSE;
637
638static GOptionEntry options[] = {
639	{ "nodaemon", 'n', G_OPTION_FLAG_REVERSE,
640				G_OPTION_ARG_NONE, &option_detach,
641				"Don't run as daemon in background" },
642	{ "debug", 'd', 0, G_OPTION_ARG_NONE, &option_debug,
643				"Enable debug information output" },
644	{ NULL },
645};
646
647int main(int argc, char *argv[])
648{
649	GOptionContext *context;
650	GError *err = NULL;
651	struct sockaddr_hci addr;
652	struct hci_filter flt;
653	struct sigaction sa;
654	GIOChannel *ctl_io, *child_io;
655	uint16_t mtu = 0;
656	GKeyFile *config;
657
658	init_defaults();
659
660	context = g_option_context_new(NULL);
661	g_option_context_add_main_entries(context, options, NULL);
662
663	if (g_option_context_parse(context, &argc, &argv, &err) == FALSE) {
664		if (err != NULL) {
665			g_printerr("%s\n", err->message);
666			g_error_free(err);
667		} else
668			g_printerr("An unknown error occurred\n");
669		exit(1);
670	}
671
672	g_option_context_free(context);
673
674	if (option_detach == TRUE) {
675		if (daemon(0, 0)) {
676			perror("Can't start daemon");
677			exit(1);
678		}
679	}
680
681	umask(0077);
682
683	start_logging("bluetoothd", "Bluetooth daemon");
684
685	memset(&sa, 0, sizeof(sa));
686	sa.sa_flags = SA_NOCLDSTOP;
687	sa.sa_handler = sig_term;
688	sigaction(SIGTERM, &sa, NULL);
689	sigaction(SIGINT,  &sa, NULL);
690
691	sa.sa_handler = sig_debug;
692	sigaction(SIGUSR2, &sa, NULL);
693
694	sa.sa_handler = SIG_IGN;
695	sigaction(SIGPIPE, &sa, NULL);
696
697	if (option_debug == TRUE) {
698		info("Enabling debug information");
699		enable_debug();
700	}
701
702	/* Create and bind HCI socket */
703	if ((main_opts.sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)) < 0) {
704		error("Can't open HCI socket: %s (%d)",
705							strerror(errno), errno);
706		exit(1);
707	}
708
709	/* Set filter */
710	hci_filter_clear(&flt);
711	hci_filter_set_ptype(HCI_EVENT_PKT, &flt);
712	hci_filter_set_event(EVT_STACK_INTERNAL, &flt);
713	if (setsockopt(main_opts.sock, SOL_HCI, HCI_FILTER, &flt, sizeof(flt)) < 0) {
714		error("Can't set filter: %s (%d)",
715							strerror(errno), errno);
716		exit(1);
717	}
718
719	addr.hci_family = AF_BLUETOOTH;
720	addr.hci_dev = HCI_DEV_NONE;
721	if (bind(main_opts.sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) {
722		error("Can't bind HCI socket: %s (%d)",
723							strerror(errno), errno);
724		exit(1);
725	}
726
727	config = load_config(CONFIGDIR "/main.conf");
728
729	parse_config(config);
730
731	if (pipe(child_pipe) < 0) {
732		error("pipe(): %s (%d)", strerror(errno), errno);
733		exit(1);
734	}
735
736	child_io = g_io_channel_unix_new(child_pipe[0]);
737	g_io_channel_set_close_on_unref(child_io, TRUE);
738	g_io_add_watch(child_io,
739			G_IO_IN | G_IO_ERR | G_IO_HUP | G_IO_NVAL,
740			child_exit, NULL);
741	g_io_channel_unref(child_io);
742
743	agent_init();
744
745	if (hcid_dbus_init() < 0) {
746		error("Unable to get on D-Bus");
747		exit(1);
748	}
749
750	start_sdp_server(mtu, main_opts.deviceid, SDP_SERVER_COMPAT);
751	set_service_classes_callback(update_service_classes);
752
753	/* Loading plugins has to be done after D-Bus has been setup since
754	 * the plugins might wanna expose some paths on the bus. However the
755	 * best order of how to init various subsystems of the Bluetooth
756	 * daemon needs to be re-worked. */
757	plugin_init(config);
758
759	event_loop = g_main_loop_new(NULL, FALSE);
760
761	ctl_io = g_io_channel_unix_new(main_opts.sock);
762	g_io_channel_set_close_on_unref(ctl_io, TRUE);
763
764	g_io_add_watch(ctl_io, G_IO_IN, io_stack_event, NULL);
765
766	g_io_channel_unref(ctl_io);
767
768	/* Initialize already connected devices */
769	init_all_devices(main_opts.sock);
770
771	g_main_loop_run(event_loop);
772
773	hcid_dbus_unregister();
774
775	plugin_cleanup();
776
777	stop_sdp_server();
778
779	agent_exit();
780
781	hcid_dbus_exit();
782
783	g_main_loop_unref(event_loop);
784
785	if (config)
786		g_key_file_free(config);
787
788	info("Exit");
789
790	stop_logging();
791
792	return 0;
793}
794