-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbluetooth_serial_service
551 lines (440 loc) · 18.3 KB
/
bluetooth_serial_service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
#!/usr/bin/python3
"""
This file demonstrates how to setup a 'Linux' bluetooth RFCOMM serial service. This code
has been tested on the following platforms and versions:
Platform Linux Bluetooth/BlueZ Ver Paired With
-------------------------------------------------------------------------------------
AMD64 Desktop Ubuntu 18.04 5.48-0ubuntu3.1 Android
NanoPiNeoAir Ubuntu 16.04 5.37-0ubuntu5.1 Android
This file implements the bluez 'org.bluez.Profile1' interface utilizing the Python DBUS extensions
and publishes that interface onto the DBUS and registers the agent as the default bluetooth
agent. The 'org.bluez.Profile1' interface in this file is setup establish a RFCOMM serial port
profile on 'Channel 4'. Before being able to utilize this service, a trust relationship must
have already been established between the two devices utilizing a pairing agent like the example PIN
based agent in this repository. This service runs a couple of commands on startup, to make sure the
rf is on and that the bluetooth interface is up.
NOTE: This RFCOM service only handles serial connections for devices that have already been
authenticated and or registered as a trusted device.
"""
import argparse
import atexit
import ctypes
import ctypes.util
import json
import logging
import os
import resource
import signal
import socket
import subprocess
import sys
import time
import traceback
import uuid
import dbus
import dbus.service
import dbus.mainloop.glib
try:
from gi.repository import GObject
except ImportError:
import gobject as GObject
try:
import pwd
except ImportError:
import getpass
pwd = None
def current_user():
if pwd:
return pwd.getpwuid(os.geteuid()).pw_name
else:
return getpass.getuser()
USER = current_user()
DEBUG_MODE = False
BLUEZ_BUS_NAME = "org.bluez"
BLUEZ_BUS_PATH = "/org/bluez"
BLUEZ_INTERFACE_DEVICE1 = "org.bluez.Device1"
BLUEZ_INTERFACE_PROFILE1 = "org.bluez.Profile1"
BLUEZ_INTERFACE_PROFILEMANAGER1 = "org.bluez.ProfileManager1"
DBUS_INTERFACE_PROPERTIES = "org.freedesktop.DBus.Properties"
SERIAL_PROFILE_PATH = "/serial/bluetooth/profile"
AGENT_DIR = os.path.abspath(os.path.dirname(__file__))
LOG_DIR = "/var/log"
if USER != 'root':
LOG_DIR = os.path.join(os.path.expanduser("~"), "logs")
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
SERVICE_LOGFILE = os.path.join(LOG_DIR, "bluetooth_serial_service.log")
SERVICE_PID_FILE = "/var/run/bluetooth_serial_service.pid"
SERVICE_LOGGER = "bluetooth_serial_service"
# Service Globals
device_obj = None
dev_path = None
mainloop = None
service_logger = None
svclog_stream = None
def ask(prompt):
try:
return raw_input(prompt)
except:
return input(prompt)
def log_message(message):
global service_logger
# print("%s: %s" % (SERVICE_LOGGER, message))
if not service_logger is None:
service_logger.log(50, message)
svclog_stream.flush()
return
def open_logger(clean_file=False):
global service_logger
global svclog_stream
mode = 'a'
if clean_file:
mode = 'w'
logf = open(SERVICE_LOGFILE, mode)
svclog_stream = logging.StreamHandler(logf)
service_logger = logging.getLogger(SERVICE_LOGGER)
service_logger.addHandler(svclog_stream)
service_logger.log(50, "Successfully opened the %r logger." % SERVICE_LOGGER)
return
def run_command(command_line):
sproc = subprocess.Popen(command_line,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
bufsize = -1, shell = True)
stdout, stderr = sproc.communicate()
rtncode = sproc.returncode
return rtncode, stdout, stderr
def run_command_detached(command_line):
sproc = subprocess.Popen(command_line, shell=False, stdin=None, stdout=None, stderr=None, close_fds=True)
return
class GoodbyeError(Exception):
"""
Raised when a connection should exit gracefully.
"""
class BluetoothSerialProfile(dbus.service.Object):
fd = -1
protocol = 1
TEMPLATE_ERROR_EXCEPTION = b"ERROR Exception thrown for %r command."
TEMPLATE_ERROR_INVALID_COMMAND = b"ERROR Invalid command %r."
TEMPLATE_ERROR_INVALID_DATA = b"ERROR Invalid data %r passed with %r command."
TEMPLATE_ERROR_INVALID_REQUEST = b"ERROR Invalid request format."
TEMPLATE_SUCCESS = b"SUCCESS %s"
@dbus.service.method(BLUEZ_INTERFACE_PROFILE1, in_signature="", out_signature="")
def Release(self):
log_message("BluetoothSerialProfile: - Release called.")
return
@dbus.service.method(BLUEZ_INTERFACE_PROFILE1, in_signature="", out_signature="")
def Cancel(self):
log_message("BluetoothSerialProfile: - Cancel called.")
return
@dbus.service.method(BLUEZ_INTERFACE_PROFILE1, in_signature="oha{sv}", out_signature="")
def NewConnection(self, path, fd, properties):
log_message("BluetoothSerialProfile: - NewConnection called.")
try:
self.fd = fd.take()
server_sock = socket.fromfd(self.fd, socket.AF_UNIX, socket.SOCK_STREAM)
try:
server_sock.setblocking(1)
server_sock.send(b"WAITING")
while True:
req_reply = self.TEMPLATE_ERROR_INVALID_REQUEST
req_buffer = server_sock.recv(4096).strip()
log_message("BluetoothSerialProfile: Buffer received %r" % req_buffer.decode("utf-8"))
cmd_parts = req_buffer.split(b" ", 1)
if len(cmd_parts) > 0:
cmd_word = cmd_parts[0]
cmd_data = None
if len(cmd_parts) > 1:
cmd_data = cmd_parts[1]
req_reply = self._process_request(cmd_word, cmd_data, req_buffer)
else:
req_reply = b"ERROR Empty or Invalid request"
server_sock.send(req_reply)
except GoodbyeError:
pass
except:
err_msg = traceback.format_exc()
log_message(err_msg)
except:
err_msg = traceback.format_exc()
server_sock.send(err_msg + "\n")
log_message(err_msg)
return
@dbus.service.method(BLUEZ_INTERFACE_PROFILE1, in_signature="o", out_signature="")
def RequestDisconnection(self, path):
log_message("BluetoothSerialProfile: - RequestDisconnection called %r." % path)
if self.fd > 0:
os.close(self.fd)
self.fd = -1
return
def _process_request(self, cmd_word, cmd_data, req_buffer):
req_reply = self.TEMPLATE_SUCCESS % cmd_word
return req_reply
class BluetoothService(object):
#Default maximum for the number of available file descriptors
DEFAULT_MAXFD = 1024
#Default file mode creation mask for the daemon
DEFAULT_UMASK = 0
#Default working directory for the daemon
DEFAULT_ROOTDIR = "/"
#Default device null
DEFAULT_DEVNULL = "/dev/null"
SERVICE_PID_FILE = SERVICE_PID_FILE
PROFILE_UUID = "1101"
PROFILE_ARGS = {
"AutoConnect": False,
"Name": "RFCOMM Serial Service",
"Role": "server",
"Channel": dbus.UInt16("4"),
"Service": "rfcomm/serial"
}
def __init__(self):
""" This is a generic daemon class intended to make it easy to create a daemon. A daemon has the following configurable
behaviors:
1. Resets the current working directory to '/'
2. Resets the current file creation mode mask to 0
3. Closes all open files (1024)
4. Detaches from the starting terminal and redirects standard I/O streams to '/dev/null'
References:
1. Advanced Programming in the Unix Environment: W. Richard Stevens
"""
self._pid_file = self.SERVICE_PID_FILE
self._profile_uuid = self.PROFILE_UUID
self._profile_args = self.PROFILE_ARGS
self._daemon_logfile = None
return
def daemonize(self):
"""
This method detaches the current process from the controlling terminal and forks
it to a process that is a background daemon process.
"""
self._daemon_logfile = "/tmp/bluetooth_serial_service.log"
if os.path.exists(self._daemon_logfile):
os.remove(self._daemon_logfile)
proc_id = None
try:
# Fork the 'FIRST' child process and let the parent process where (pid > 0) exit cleanly and return
# to the terminal
proc_id = os.fork()
except OSError as os_err:
err_msg = "%s\n errno=%d\n" % (os_err.strerror, os_err.errno)
log_message(err_msg)
raise Exception (err_msg)
# Fork returns 0 in the child and a process id in the parent. If we are running in the parent
# process then exit cleanly with no error.
if proc_id > 0:
sys.exit(0)
# Call os.setsid() to:
# 1. Become the session leader of this new session
# 2. Become the process group leader of this new process group
# 3. This also guarantees that this process will not have controlling terminal
os.setsid()
proc_id = None
try:
# For the 'SECOND' child process and let the parent process where (proc_id > 0) exit cleanly
# This second process fork has the following effects:
# 1. Since the first child is a session leader without controlling terminal, it is possible
# for it to acquire one be opening one in the future. This second fork guarantees that
# the child is no longer a session leader, preventing the daemon from ever acquiring a
# controlling terminal.
proc_id = os.fork()
except OSError as os_err:
err_msg = "%s\n errno=%d\n" % (os_err.strerror, os_err.errno)
log_message(err_msg)
raise Exception (err_msg)
# Fork returns 0 in the child and a process id in the parent. If we are running in the parent
# process then exit cleanly with no error.
if proc_id > 0:
sys.exit(0)
log_message("Second fork successful.")
# We want to change the working directory of the daemon to '/' to avoid the issue of not being
# able to unmount the file system at shutdown time.
os.chdir(self.DEFAULT_ROOTDIR)
# We don't want to inherit the file mode creation flags from the parent process. We
# give the child process complete control over the permissions
os.umask(self.DEFAULT_UMASK)
maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
if (maxfd == resource.RLIM_INFINITY):
maxfd = self.DEFAULT_MAXFD
stdin_fileno = sys.stdin.fileno()
stdout_fileno = sys.stdout.fileno()
stderr_fileno = sys.stderr.fileno()
# Go through all the file descriptors that could have possibly been open and close them
# This includes the existing stdin, stdout and stderr
sys.stdout.flush()
sys.stderr.flush()
# Close all 1024 possible open FDs
for fd in range(maxfd):
try:
os.close(fd)
except OSError as os_err:
pass
except:
err_trace = traceback.format_exc()
# Create the standard file descriptors and redirect them to the standard file descriptor
# numbers 0 stdin, 1 stdout, 2 stderr
stdin_f = open(self.DEFAULT_DEVNULL , 'r')
stdout_f = open(self.DEFAULT_DEVNULL, 'a+')
stderr_f = open(self.DEFAULT_DEVNULL, 'a+')
os.dup2(stdin_f.fileno(), stdin_fileno)
os.dup2(stdout_f.fileno(), stdout_fileno)
os.dup2(stderr_f.fileno(), stderr_fileno)
# Register an the removal of the PID file on python interpreter exit
atexit.register(self._remove_pidfile)
# Create the pid file to prevent multiple launches of the daemon
pid_str = str(os.getpid())
with open(self._pid_file, 'w') as pid_f:
pid_f.write("%s\n" % pid_str)
return
def process_exists(self, process_id):
"""
Checks to see if a process exists
"""
result = None
try:
os.kill(process_id, 0)
result = True
except OSError:
result = False
return result
def restart(self):
"""
Restart the Bluetooth Serial Service
"""
self.stop()
self.start()
return
def run(self):
"""
This is the main 'Bluetooth Serial Service' entry method that will setup the DBUS interfaces
to handle the Bluetooth integration for the service.
"""
nxt_cmd = "/usr/sbin/rfkill unblock bluetooth"
rtncode, stdout, stderr = run_command(nxt_cmd);
if rtncode != 0:
log_message("'%s' command failed. rtncode=%d" % (nxt_cmd, rtncode))
time.sleep(1)
nxt_cmd = "/usr/bin/hciconfig hci0 up"
run_command(nxt_cmd);
if rtncode != 0:
log_message("'%s' command failed. rtncode=%d" % (nxt_cmd, rtncode))
time.sleep(3)
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
bus = dbus.SystemBus()
if bus != None:
profile = BluetoothSerialProfile(bus, SERIAL_PROFILE_PATH)
bluez_obj = bus.get_object(BLUEZ_BUS_NAME, BLUEZ_BUS_PATH)
if bluez_obj != None:
mainloop = GObject.MainLoop()
profile_manager = dbus.Interface(bluez_obj, BLUEZ_INTERFACE_PROFILEMANAGER1)
try:
resp = profile_manager.RegisterProfile(SERIAL_PROFILE_PATH, self._profile_uuid, self._profile_args)
log_message("RFCOMM serial profile registered. resp=%r" % resp)
# This is where our thread enters our GObject dispatching loop
log_message("Starting 'RFCOMM serial service' DBUS main loop.")
mainloop.run()
log_message("Main loop exited normally.")
except:
err_msg = traceback.format_exc()
log_message(err_msg)
finally:
profile_manager.UnregisterAgent(SERIAL_PROFILE_PATH)
log_message("Pairing agent unregistered.")
else:
log_message("Unable to open the BlueZ bus.")
else:
log_message("Unable to open DBUS system bus.")
return
def start(self):
"""
Start the Bluetooth Serial Service
"""
#Check to see if the pid file exists to see if the daemon is already running
proc_id = None
try:
with open(self._pid_file, 'r') as pid_f:
proc_id_str = pid_f.read().strip()
proc_id = int(proc_id_str)
# If we found a PID file but the process in the PID file does not exists,
# then we are most likely reading a stale PID file. Go ahead and startup
# a new instance of the daemon
if not self.process_exists(proc_id):
os.remove(self._pid_file)
proc_id = None
except IOError:
proc_id = None
if proc_id != None:
log_message("The 'Bluetooth Serial Service' was already running.")
sys.exit(1)
if not DEBUG_MODE:
# Start the daemon
log_message("The 'Bluetooth Serial Service' is about to become a daemon.")
self.daemonize()
else:
log_message("The 'Bluetooth Serial Service' skipping daemonization.")
# Now that we are a daemon we need to switch over to using the logger
open_logger()
log_message("The 'Bluetooth Serial Service' is now a daemon, lets run with it.")
self.run()
return
def stop(self):
"""
Stop the Bluetooth Serial Service
"""
#Check to see if the PID file exists to see if the daemon is already running
proc_id = None
try:
with open(self._pid_file, 'r') as pid_f:
proc_id_str = pid_f.read().strip()
proc_id = int(proc_id_str)
except IOError:
proc_id = None
if not proc_id:
log_message("The 'Bluetooth Serial Service' was not running.")
return # This is not an error in a restart so don't exit with a error code
# The process was running so we need to shut it down
try:
while True:
os.kill(proc_id, signal.SIGTERM)
time.sleep(0.1)
except OSError as os_err:
err_str = str(os_err)
if err_str.find("No such process") > 0:
if os.path.exists(self._pid_file):
os.remove(self._pid_file)
else:
log_message(err_str)
sys.exit(1)
return
def _remove_pidfile(self):
if os.path.exists(self._pid_file):
os.remove(self._pid_file)
return
if __name__ == '__main__':
parser = argparse.ArgumentParser("Description bluetooth 'pin' based pairing agent.")
parser.add_argument("action", choices=['start', 'stop', 'restart'], help="The action to perform with the service.")
parser.add_argument("--debug", default=False, action='store_true', help="Launches the service as a non-daemon process in debug mode.")
try:
args = parser.parse_args()
action = args.action
DEBUG_MODE = args.debug
if DEBUG_MODE:
action = 'start'
service = BluetoothService()
if action == 'restart':
service.restart()
elif action == 'start':
service.start()
elif action == 'stop':
service.stop()
else:
sys.stderr.write("Unknown command '%s'.\n" % action)
sys.stderr.write("usage: %s start|stop|restart\n" % sys.argv[0])
exit(2)
exit(0)
except SystemExit:
raise
except:
err_trace = traceback.format_exc()
log_message(err_trace)
exit(1)