Skip to content

Commit

Permalink
Mainly improved the plugin framework
Browse files Browse the repository at this point in the history
  • Loading branch information
x committed Oct 25, 2022
1 parent f4a9d81 commit 0118ce0
Show file tree
Hide file tree
Showing 28 changed files with 207 additions and 243 deletions.
13 changes: 1 addition & 12 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,28 +11,17 @@
/dist/
/deb_dist/
/doc/private/
/plugins/
/res/private/
/test/
/yotta_modules/
/yotta_targets/

/install.rec
/bluescan-0.7.0.tar.gz

/src/bluescan/poc/bugs.md
/src/bluescan/res/*.cache
/src/bluescan/bluescan_prompt.bash

# symbolic link, not directory
/src/xpycommon
/src/pyclui
/src/btatt
/src/btgatt
/src/btl2cap
/src/btsm
/src/btsdp
/src/bthci

__pycache__/
bluescan.spec
*.egg-info
3 changes: 2 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@
include /home/x/OneDrive/Projects/makefile-common/src/Makefile.twine
include /home/x/OneDrive/Projects/makefile-common/src/Makefile.python
include /home/x/OneDrive/Projects/makefile-common/src/Makefile.nethunter
include ./plugins/Makefile

$(info PROJECT_NAME: $(PROJECT_NAME))
$(info machine: $(MACHINE))
$(info MACHINE: $(MACHINE))
$(info INSTALL_REQUIRED_PY_PKGS: $(INSTALL_REQUIRED_PY_PKGS))

.DEFAULT_GOAL := build
Expand Down
4 changes: 2 additions & 2 deletions README-cn.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ Usage:
bluescan --list-installed-plugins
bluescan --install-plugin=<path>
bluescan --uninstall-plugin=<name>
bluescan --run-plugin=<name> [--] [<plugin-opt>...]
bluescan --plugin=<name> [--] [<plugin-opt>...]
Arguments:
BD_ADDR Target Bluetooth device address. FF:FF:FF:00:00:00 means local
Expand Down Expand Up @@ -170,7 +170,7 @@ Options:
--list-installed-plugins List plugins in local system
--install-plugin=<path> Install a plugin
--uninstall-plugin=<name> Uninstall a plugin
--run-plugin=<name> Execute plugin by name.
--plugin=<name> Execute plugin by name.
```

### BR 设备扫描 `-m br`
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ Usage:
bluescan --list-installed-plugins
bluescan --install-plugin=<path>
bluescan --uninstall-plugin=<name>
bluescan --run-plugin=<name> [--] [<plugin-opt>...]
bluescan --plugin=<name> [--] [<plugin-opt>...]
Arguments:
BD_ADDR Target Bluetooth device address. FF:FF:FF:00:00:00 means local
Expand Down Expand Up @@ -170,7 +170,7 @@ Options:
--list-installed-plugins List plugins in local system
--install-plugin=<path> Install a plugin
--uninstall-plugin=<name> Uninstall a plugin
--run-plugin=<name> Execute plugin by name.
--plugin=<name> Execute plugin by name.
```

### Scan BR devices `-m br`
Expand Down
4 changes: 2 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[build-system]
requires = [
"setuptools>=59.6.0",
"setuptools>=65.3.0",
"wheel",
"stdeb"
]
build-backend = "setuptools.build_meta"
build-backend = "setuptools.build_meta"
13 changes: 6 additions & 7 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ author_email = [email protected]
description = A Bluetooth scanner for hacking
long_description = file: README.md
long_description_content_type = text/markdown
license_file = LICENSE.txt
license_files = LICENSE.txt
url = https://github.com/fO-000/bluescan
classifiers =
Operating System :: POSIX :: Linux
Expand Down Expand Up @@ -37,12 +37,11 @@ install_requires =
pyserial >= 3.5
PyGObject >= 3.42.2
dbus-python >= 1.3.2
pyclui >= 0.0.18
xpycommon >= 0.0.13
bthci >= 0.0.34
btsm >= 0.0.12
btatt >= 0.0.15
btgatt >= 0.0.18
xpycommon >= 0.0.14
bthci >= 0.0.36
btsm >= 0.0.13
btatt >= 0.0.16
btgatt >= 0.0.19

# specified via MANIFEST.in
include_package_data = True
Expand Down
20 changes: 9 additions & 11 deletions src/bluescan/__init__.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
#!/usr/bin/env python3
#!/usr/bin/env python

PKG_NAME = 'bluescan'
VERSION = '0.8.6'
DEBUG_VERSION = None
VERSION = '0.8.7'
DEBUG_VERSION = ''

from pyclui import Logger, INFO, DEBUG

LOG_LEVEL = INFO
logger = Logger(__name__, LOG_LEVEL)
from xpycommon import py_pkg_init

if DEBUG_VERSION is not None:
LOG_LEVEL = DEBUG
logger.setLevel(LOG_LEVEL)
logger.warning("Using the debug version {} of {}".format(DEBUG_VERSION, PKG_NAME))
locals_dict = {}
py_pkg_init(globals(), locals_dict)
LOG_LEVEL = locals_dict['LOG_LEVEL']
VERSION_STR = locals_dict['VERSION_STR']


import io
Expand Down Expand Up @@ -85,7 +83,7 @@ def __init__(self, type: str) -> None:
self.type = type

def store(self):
logger.debug("Not implemented")
pass


__all__ = []
53 changes: 36 additions & 17 deletions src/bluescan/__main__.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
#!/usr/bin/env python3
#!/usr/bin/env python

import sys
import os
import subprocess
import traceback
from traceback import format_exception
from subprocess import STDOUT, CalledProcessError
from pathlib import PosixPath

from pyclui import Logger, blue
from xpycommon.log import Logger
from xpycommon.ui import blue
from bthci import HCI, ControllerErrorCodes, HciError
from bluepy.btle import BTLEException
from xpycommon.bluetooth import restart_bluetooth_service
from xpycommon.bluetooth import restart_bluetooth_service, find_rfkill_devid

from . import BlueScanner, LOG_LEVEL
from .ui import parse_cmdline
from .helper import find_rfkill_devid, get_microbit_devpaths
from .plugin import BluescanPluginInstallError, list_plugins, install_plugin, uninstall_plugin, run_plugin
from .helper import get_microbit_devpaths
from .plugin import BluescanPluginError, BluescanPluginNotFoundError, BluescanPluginInstallError, list_plugins, install_plugin, uninstall_plugin, exec_plugin
from .br_scan import BRScanner
from .le_scan import LeScanner
from .gatt_scan import GattScanner
Expand All @@ -35,7 +37,11 @@ def prepare_hci(iface: str = 'hci0'):
# hciconfig <hci> up 的前提是 rfkill 先 unblock
subprocess.check_output('rfkill unblock %d' % find_rfkill_devid(iface),
stderr=STDOUT, timeout=5, shell=True)
restart_bluetooth_service()
try:
restart_bluetooth_service()
except CalledProcessError as e:
logger.warning("Failed to restart bluetooth service")

subprocess.check_output('hciconfig {} up'.format(iface),
stderr=STDOUT, timeout=5, shell=True)

Expand Down Expand Up @@ -143,10 +149,9 @@ def main():
uninstall_plugin(plugin_name)
return

if args['--run-plugin']:
plugin_name = args['--run-plugin']
opts = args['<plugin-opt>']
run_plugin(plugin_name, opts)
if args['--plugin']:
plugin_name = args['--plugin']
exec_plugin(plugin_name)
return

if not args['--adv']:
Expand Down Expand Up @@ -205,20 +210,34 @@ def main():
scan_result.print()
scan_result.store()
# except (RuntimeError, ValueError, BluetoothError) as e:
except (RuntimeError, ValueError) as e:
except BluescanPluginError as e:
logger.error("{}: {}".format(e.__class__.__name__, e))
traceback.print_exc()
sys.exit(1)
except (BTLEException) as e:
except BTLEException as e:
logger.error(str(e) + ("\nNo BLE adapter or missing sudo?" if 'le on' in str(e) else ""))
except BluescanPluginInstallError as e:
logger.error("Failed to install plugin: {}".format(e))
sys.exit(1)
except KeyboardInterrupt:
if args != None and args['-i'] != None:
output = subprocess.check_output(' '.join(['hciconfig', args['-i'], 'reset']),
stderr=STDOUT, timeout=60, shell=True)
try:
output = subprocess.check_output(' '.join(['hciconfig', args['-i'], 'reset']),
stderr=STDOUT, timeout=60, shell=True)
except CalledProcessError as e:
logger.warning("{}: {}".format(e.__class__.__name__, e))
print()
logger.info("Canceled\n")
except TimeoutError as e:
logger.error("Timeout")
if args != None and args['-i'] != None:
try:
output = subprocess.check_output(' '.join(['hciconfig', args['-i'], 'reset']),
stderr=STDOUT, timeout=60, shell=True)
except CalledProcessError as e:
logger.warning("{}: {}".format(e.__class__.__name__, e))
except Exception as e:
e_info = ''.join(format_exception(*sys.exc_info()))
logger.debug("e_info: {{}}".format(e_info))
logger.error("{}: {}".format(e.__class__.__name__, e))
sys.exit(1)


if __name__ == '__main__':
Expand Down
4 changes: 2 additions & 2 deletions src/bluescan/agent.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
#!/usr/bin/env python

import dbus
from dbus import SystemBus
from pyclui import Logger
from xpycommon.log import Logger

from . import LOG_LEVEL
from .common import mainloop, Rejected, APP_NAME
Expand Down
6 changes: 3 additions & 3 deletions src/bluescan/br_scan.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/env python

import sys
import struct
Expand All @@ -7,8 +7,8 @@
from bthci.events import HciEventCodes, HCI_Inquiry_Result, HCI_Inquiry_Result_with_RSSI, \
HCI_Extended_Inquiry_Result
from bthci.bluez_hci import HCI_CHANNEL_USER
from pyclui import Logger
from pyclui import green, blue, yellow, red
from xpycommon.log import Logger
from xpycommon.ui import green, blue, yellow, red
from xpycommon.bluetooth import bd_addr_str2bytes

from . import BlueScanner, service_cls_profile_ids, LOG_LEVEL
Expand Down
7 changes: 4 additions & 3 deletions src/bluescan/common.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#!/usr/bin/env python3
#!/usr/bin/env python

import io
import pkg_resources

from dbus.exceptions import DBusException
from gi.repository import GObject

from pyclui import Logger, blue, red
from xpycommon.log import Logger
from xpycommon.ui import blue, red

from . import LOG_LEVEL

Expand All @@ -28,7 +29,7 @@
company_id = items[0].removesuffix(' (hex)')
oui_company_names[company_id] = items[1]

logger.debug("oui_company_names: {}".format(oui_company_names))
# logger.debug("oui_company_names: {}".format(oui_company_names))


class InvalidArgsException(DBusException):
Expand Down
2 changes: 1 addition & 1 deletion src/bluescan/gap_data.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/env python

# EIR Data Type, Advertising Data Type (AD Type) and OOB Data Type Definitions
# https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile/
Expand Down
6 changes: 3 additions & 3 deletions src/bluescan/gatt_scan.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python3
#!/usr/bin/env python

import io
from multiprocessing.sharedctypes import Value
Expand All @@ -11,8 +11,8 @@

import pkg_resources
from bthci import ADDR_TYPE_PUBLIC, ADDR_TYPE_RANDOM
from pyclui import green, blue, yellow, red
from pyclui import Logger
from xpycommon.ui import green, blue, yellow, red
from xpycommon.log import Logger
from halo import Halo

import dbus
Expand Down
30 changes: 3 additions & 27 deletions src/bluescan/helper.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
#!/usr/bin/env python3
#!/usr/bin/env python

# import pickle
import subprocess

from serial.tools.list_ports import comports

from pyclui import Logger, blue, green, yellow, red
from xpycommon.log import Logger
from xpycommon.ui import blue, green, yellow, red

from . import LOG_LEVEL

Expand Down Expand Up @@ -36,19 +37,6 @@
# raise RuntimeError("Couldn't determine the LE address type. Please provide it explicitly.")


def find_rfkill_devid(dev='hci0') -> int:
exitcode, output = subprocess.getstatusoutput('rfkill -rno ID,DEVICE')

for line in output.splitlines():
id_dev = line.split()
if len(id_dev) == 2 and id_dev[1] == dev:
return int(id_dev[0])
else:
continue

raise RuntimeError("Can't find the ID of %s in rfkill" % blue(dev))


def get_microbit_devpaths() -> list:
"""Get serial device path of all connected micro:bits."""
# microbit_infos = []
Expand Down Expand Up @@ -84,15 +72,3 @@ def get_microbit_devpaths() -> list:

logger.debug("get_microbit_devpaths, dev_paths: {}".format(dev_paths))
return dev_paths


def __test():
#valid_bdaddr('11:22:33:44:55:66')
try:
print(find_rfkill_devid('hci0'))
except RuntimeError as e:
print(e)


if __name__ == '__main__':
__test()
Loading

0 comments on commit 0118ce0

Please sign in to comment.