1#!/bin/sh
2#-
3# ----------------------------------------------------------------------------
4# "THE BEER-WARE LICENSE" (Revision 42):
5# <erdgeist@erdgeist.org> wrote this file. As long as you retain this notice you
6# can do whatever you want with this stuff. If we meet some day, and you think
7# this stuff is worth it, you can buy me a beer in return Poul-Henning Kamp
8# ----------------------------------------------------------------------------
9#
10#
11
12# define our bail out shortcut
13exerr () { echo -e "Error: $*" >&2 ; exit 1; }
14print_syntax () { echo -e "Syntax: $0 scan [-d device] [-n node]"; exit 1; }
15
16main() {
17unset node device started bdaddresses retry
18
19# Only one command at the moment is scan (+ add)
20[ "$#" -eq 1 -a "$1" = "scan" ] || print_syntax
21shift
22
23# Get command line options
24while getopts :d:n: arg; do
25	case ${arg} in
26		d) device="$OPTARG";;
27		n) node="$OPTARG";;
28		?) print_syntax;;
29	esac
30done
31
32# No use running without super user rights
33if [ $( id -u ) -ne 0 ]; then
34	exerr "$0 must modify files that belong to root.  Re-run as root."
35fi
36
37known_nodes=$( /usr/sbin/hccontrol read_node_list 2>/dev/null |\
38	/usr/bin/tail -n +2 | /usr/bin/cut -d ' ' -f 1 )
39
40# Check if netgraph knows about any HCI nodes
41if ! [ "${known_nodes}" ]; then
42	ng_nodes=$( /usr/sbin/ngctl list 2>/dev/null | \
43		/usr/bin/grep -o "Name: .* Type: ubt" |/usr/bin/cut -d' ' -f2 )
44
45	[ "${ng_nodes}" ] || exerr "No Bluetooth host controllers found."
46
47	unset found
48	for n in ${ng_nodes}; do
49		if [ "${n}" = "${node%hci}" ]; then
50			# Found the node but its stack is not set up? Do it now.
51			/usr/sbin/service bluetooth start ${node%hci} || exit 1
52			found="YES"
53		fi
54	done
55
56	# If we have Bluetooth controller nodes without a set up stack,
57	# ask the user if we shall start it up
58	if ! [ "${found}" ]; then
59		printf "No usable Bluetooth host controllers were found.\n"
60		printf "These host controllers exist in the system:\n"
61		printf "  %s\n" "${ng_nodes}"
62		prompt="Choose a host controller to set up: [${ng_nodes%% *}]"
63		read -p "${prompt}" node
64		: ${node:="${ng_nodes%% *}"}
65		/usr/sbin/service bluetooth start ${node} || exit 1
66	fi
67
68	# Re-read known nodes
69	known_nodes=$(/usr/sbin/hccontrol read_node_list 2>/dev/null |
70		/usr/bin/tail -n +2 | /usr/bin/cut -d ' ' -f 1 )
71
72	# check if we succeeded in bringing it up
73	[ "${known_nodes}" ] || exerr "Failed to set up Bluetooth stack"
74fi
75
76# if a node was requested on command line, check if it is there
77if [ "${node}" ]; then
78	unset found
79	for n in ${known_nodes}; do
80		[ "${n}" = "${node}" ] && found="YES"
81		[ "${n}" = "${node}hci" ] && node="${node}hci" && found="YES"
82	done
83	[ "${found}" ] || exerr "Node ${node} not found"
84fi
85
86[ "${node}" ] && node="-n ${node}"
87
88while ! [ "${bdaddresses}" ]; do
89	retry=X${retry}
90	printf "Scanning for new Bluetooth devices (Attempt %d of 5) ... " \
91		${#retry}
92	bdaddresses=$( /usr/sbin/hccontrol -N ${node} inquiry 2>/dev/null |
93		/usr/bin/grep -o "BD_ADDR: .*" | /usr/bin/cut -d ' ' -f 2 )
94
95	# Count entries and, if a device was requested on command line,
96	# try to find it
97	unset found count
98	for bdaddress in ${bdaddresses}; do
99		count=X${count}
100		if [ "${bdaddress}" = "${device}" ]; then
101			found=YES
102			bdaddresses="${device}"
103			count=X
104			break
105		fi
106	done
107
108	# If device was requested on command line but is not found,
109	# or no devices found at all, rescan until retry is exhausted
110	if ! [ "${found}" -o "${count}" -a -z "${device}" ]; then
111		printf "failed.\n"
112		if [ "${#retry}" -eq 5 ]; then
113			[ "${device}" ] && exerr "Device ${device} not found"
114			exerr "No new Bluetooth devices found"
115		fi
116		unset bdaddresses
117		sleep 2
118		continue
119	fi
120
121	[ ${#count} -gt 1 ] && plural=s || plural=''
122	printf "done.\nFound %d new bluetooth device%s " ${#count} ${plural}
123	printf "(now scanning for names):\n"
124
125	# Looping again for the faster feedback
126	unset count
127	for bdaddress in ${bdaddresses}; do
128		count=X${count}
129		bdname=$( /usr/bin/bthost -b "${bdaddress}" 2>/dev/null )
130		friendlyname=$( /usr/sbin/hccontrol Remote_Name_Request \
131			${bdaddress} 2> /dev/null |
132			/usr/bin/grep -o "Name: .*" |/usr/bin/cut -d ' ' -f 2- )
133
134		# sdpcontrol should be able to pull vendor + product id via sdp
135		printf "[%2d] %s\t\"%s\" (%s)\n" ${#count} "${bdaddress}" \
136			"${friendlyname}" "${bdname}"
137
138		eval bdaddress_${#count}=\${bdaddress}
139		eval bdname_${#count}=\${bdname}
140		eval friendlyname_${#count}=\${friendlyname}
141	done
142
143	# If a device was pre-selected, do not query the user
144	[ "${device}" ] && topair=1 || unset topair
145
146	# Even if only one device was found, user may chose 0 to rescan
147	while ! [ "${topair}" ]; do
148		prompt="Select device to pair with [1"
149		[ ${#count} -gt 1 ] && prompt="${prompt}-${#count}"
150		read -p "${prompt}, or 0 to rescan]: " topair
151		if ! [ "${topair}" -ge 0 -a "${topair}" -le "${#count}" ] \
152			2>/dev/null ; then
153			printf "Value out of range: %s.\n" {topair}
154			unset topair
155		fi
156	done
157
158	[ "${topair}" -eq "0" ] && unset bdaddresses retry
159done
160
161eval bdaddress=\${bdaddress_${topair}}
162eval bdname=\${bdname_${topair}}
163eval friendlyname=\${friendlyname_${topair}}
164
165# Do we need to add an entry to /etc/bluetooth/hosts?
166if ! [ "${bdname}" ]; then
167	printf "\nAdding device ${bdaddress} to /etc/bluetooth/hosts.\n"
168
169	while ! [ "${bdname}" ]; do
170		read -p "Enter friendly name. [${friendlyname}]: " _r
171		: ${_r:="${friendlyname}"}
172
173		if [ "${_r}" ]; then
174			# Remove white space and non-friendly characters
175			bdname=$( printf "%s" "${_r}" | tr -c '[:alnum:]-,.' _ )
176			if [ "${_r}" != "${bdname}" ]; then
177				printf "Notice: Using sanitized name"
178				printf "\"%s\" in /etc/bluetooth/hosts.\n" \
179					"${bdname}"
180			fi
181		fi
182	done
183
184	printf "%s\t%s\n" "${bdaddress}" "${bdname}" >> /etc/bluetooth/hosts
185fi
186
187# If scanning for the name did not succeed, resort to bdname
188: ${friendlyname:="${bdname}"}
189
190# now over to hcsecd
191
192# Since hcsecd does not allow querying for known devices, we need to
193# check for bdaddr entries manually.
194#
195# Also we cannot really modify the PIN in an existing entry. So we
196# need to prompt the user to manually do it and restart this script
197if ! /usr/sbin/service hcsecd enabled; then
198	printf "\nWarning: hcsecd is not enabled.\n"
199	printf "This daemon manages pairing requests.\n"
200	read -p "Enable hcsecd? [yes]: " _r
201	case "${_r}" in
202		no|n|NO|N|No|nO) ;;
203		*) /usr/sbin/service hcsecd enable;;
204	esac
205fi
206
207secd_config=$( /usr/sbin/sysrc -n hcsecd_config )
208secd_entries=$( /usr/bin/grep -Eo "bdaddr[[:space:]]+(${bdaddress}|${bdname})" \
209	${secd_config} | awk '{ print $2; }' )
210
211if [ "${secd_entries}" ]; then
212	printf "\nWarning: An entry for device %s is already present in %s.\n" \
213		${secd_entries} ${secd_config}
214	printf "To modify pairing information, edit this file and run\n"
215	printf "  service hcsecd restart\n"
216	read -p "Continue? [yes]: " _r
217	case "${_r}" in no|n|NO|N|No|nO) exit;; esac
218else
219	printf "\nWriting pairing information description block to %s.\n" \
220		${secd_config}
221	printf "(To get PIN, put device in pairing mode first.)\n"
222	read -p "Enter PIN [nopin]: " pin
223	[ "${pin}" ] && pin=\""${pin}"\" || pin="nopin"
224
225	# Write out new hcsecd config block
226	printf "\ndevice {\n\tbdaddr\t%s;\n\tname\t\"%s\";\n\tkey\tnokey\;\n\tpin\t%s\;\n}\n" \
227		"${bdaddress}" "${friendlyname}" "${pin}" >> ${secd_config}
228
229	# ... and make daemon reload config
230	# TODO: hcsecd should provide a reload hook
231	/usr/sbin/service hcsecd onerestart
232
233	# TODO: we should check if hcsecd succeeded pairing and revert to an
234	# old version of hcsecd.conf so we can undo adding the block above and
235	# retry with a new PIN
236	# also, if there's a way to force devices to re-pair, try this
237fi
238
239# now check for specific services to be provided by the device
240# first up: HID
241
242/usr/sbin/sdpcontrol -a "${bdaddress}" search HID | \
243	/usr/bin/grep -q "^Record Handle: " || exit 0
244
245printf "\nThis device provides human interface device services.\n"
246read -p "Set it up? [yes]: " _r
247case "${_r}" in
248	no|n|NO|N|No|nO) exit 0;;
249	*);;
250esac
251
252# Here we have found an HID and were asked to set it up
253# NOTE: look out for the two exit 0 above if you extend this script
254
255if ! /usr/sbin/service bthidd enabled; then
256	printf "\nWarning: bthidd is not enabled."
257	printf "\nThis daemon manages Bluetooth HID devices.\n"
258	read -p "Enable bthidd? [yes]: " _r
259	case "${_r}" in
260		no|n|NO|N|No|nO) ;;
261		 *) /usr/sbin/service bthidd enable;;
262	esac
263fi
264
265# Check if bthidd already knows about this device
266bthidd_known=$( /usr/sbin/bthidcontrol -a "${bdaddress}" known | \
267	/usr/bin/grep "${bdaddress}" )
268
269if [ "${bthidd_known}" ]; then
270	printf "Notice: Device %s already known to bthidd.\n" "${bdaddress}"
271	return 0
272fi
273
274bthidd_config=$( /usr/sbin/sysrc -n bthidd_config )
275printf "Writing HID descriptor block to %s ... " "${bthidd_config}"
276/usr/sbin/bthidcontrol -a "${bdaddress}" query >> "${bthidd_config}"
277
278# Re-read config to see if we succeeded adding the device
279bthidd_known=$( /usr/sbin/bthidcontrol -a "${bdaddress}" known | \
280	grep "${bdaddress}" )
281if ! [ "${bthidd_known}" ]; then
282	printf "failed.\n"
283else
284	printf "success.\nTo re-read its config, bthidd must be restarted.\n"
285	printf "Warning: If a Bluetooth keyboard is being used, the connection"
286	printf "might be lost.\n"
287	printf "It can be manually restarted later with\n"
288	printf " service bthidd restart\n"
289	read -p "Restart bthidd now? [yes]: " _r
290	case "${_r}" in
291		no|n|NO|N|No|nO) ;;
292		*) /usr/sbin/service bthidd onerestart;;
293	esac
294fi
295
296}
297
298# After function definitions, main() can use them
299main "$@"
300exit 0
301
302# TODO
303# * If device is a keyboard, offer a text entry test field and if it does
304#   not succeed, leave some clues for debugging (i.e. if the node responds
305#   to pings, maybe switch keyboard on/off, etc)
306# * Same if device is a mouse, i.e. hexdump /dev/sysmouse.
307# * If device offers DUN profiles, ask the user if an entry in
308#   /etc/ppp/ppp.conf should be created
309# * If OPUSH or SPP is offered, refer to the respective man pages to give
310#   some clues how to continue
311