pybatmesh/naxalnet/scripts.py

95 lines
3.1 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
# Copyright (C) 2021 The naxalnet Authors
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Setup a working BATMAN Advanced network
with systemd-networkd and iwd
"""
import sys
from pathlib import Path
from shutil import copy
# from dasbus.connection import SystemMessageBus
from dasbus.error import DBusError
from naxalnet.iwd import IWD, Device, Adapter
NETWORKD_CONFIGS = "/usr/share/naxalnet/networkd"
NETWORKD_VOLATILE_DIR = "/run/systemd/network"
ADHOC_SSID = "HelloWorld"
AP_SSID = "NaxalNet"
AP_PASSWD = "naxalnet256"
def here_be_dragons():
# Copy networkd configs to volatile dir.
# The D-Bus API does not support creating new interfaces
# or linking to bridges. So we use config files.
# See man:systemd.network(5)
try:
print("Copying network config files")
dest = Path(NETWORKD_VOLATILE_DIR)
src = Path(NETWORKD_CONFIGS)
# Create the volatile directory if it doesn't exist
dest.mkdir(parents=True, exist_ok=True)
# Copy all files in src to dest
for i in src.iterdir():
copy(i, dest)
except PermissionError as error:
print(error)
sys.exit("Make sure you are root")
# Now, the iwd part
try:
iwd = IWD()
devices = iwd.get_devices()
adhoc_devices = []
ap_devices = []
for i in devices:
d = Device(i)
a = Adapter(d.adapter)
if a.supports_mode("ad-hoc"):
adhoc_devices.append(i)
if a.supports_mode("ap"):
ap_devices.append(i)
if len(adhoc_devices) != 0:
# Start ad-hoc on first device supporting ad-hoc
adhoc_device = Device(adhoc_devices.pop())
# The same device is likely to have ap support too.
# But we can't start ad-hoc and ap on the same interface.
# Remove dev1 from ap_devices if it exists there
if adhoc_device.name in ap_devices:
ap_devices.remove(adhoc_device.name)
print("Working on ad-hoc")
adhoc_device.start_adhoc_open(ADHOC_SSID)
# Start Access point if ap_device is not empty,
# ie, we have more devices
if len(ap_devices) != 0:
print("Working on AP")
ap_device = Device(ap_devices.pop())
ap_device.start_ap(AP_SSID, AP_PASSWD)
except DBusError as error:
print(error)
sys.exit("An error occured while communicating with iwd")
print("Bye")