Files
mi8-platina-linux/scripts/phone-cellular-rpmsg.py
2026-11-18 01:39:26 +09:00

552 lines
23 KiB
Python

#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-only
"""Probe modem AT support or run experimental PPP over an unused GLINK channel.
Default mode sends AT only. --query reads registration and PDP capabilities.
--connect requires an explicit APN and never installs a default route or DNS.
An AT OK or CONNECT response alone does not prove cellular IP connectivity.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager, nullcontext
import errno
import fcntl
import ipaddress
import json
import os
from pathlib import Path
import pty
import re
import select
import shutil
import signal
import socket
import struct
import subprocess
import time
import tty
class PPPFrameStats:
"""Count validated async PPP frames without retaining packet contents."""
def __init__(self):
self.frame = None
self.escaped = False
self.protocols = {}
self.invalid_fcs = 0
self.oversized = 0
self.ipv4_bytes = 0
@staticmethod
def fcs(data):
value = 0xffff
for byte in data:
value ^= byte
for _ in range(8):
value = (value >> 1) ^ (0x8408 if value & 1 else 0)
return value
def feed(self, data):
for byte in data:
if byte == 0x7e:
if self.frame and not self.escaped:
self.record(bytes(self.frame))
self.frame = bytearray()
self.escaped = False
elif self.frame is not None:
if self.escaped:
self.frame.append(byte ^ 0x20)
self.escaped = False
elif byte == 0x7d:
self.escaped = True
else:
self.frame.append(byte)
if len(self.frame) > 65536:
self.oversized += 1
self.frame = None
self.escaped = False
def record(self, frame):
if len(frame) < 3 or self.fcs(frame) != 0xf0b8:
self.invalid_fcs += 1
return
payload = frame[:-2]
if payload.startswith(b'\xff\x03'):
payload = payload[2:]
if not payload:
return
size = 1 if payload[0] & 1 else 2
if len(payload) < size:
return
protocol = int.from_bytes(payload[:size], 'big')
name = {0x21: 'ipv4', 0x57: 'ipv6', 0xc021: 'lcp',
0x8021: 'ipcp', 0xc023: 'pap', 0xc223: 'chap'}.get(
protocol, f'0x{protocol:04x}')
self.protocols[name] = self.protocols.get(name, 0) + 1
if protocol == 0x21:
self.ipv4_bytes += len(payload) - size
def summary(self):
return {'protocol_frames': dict(self.protocols), 'ipv4_bytes': self.ipv4_bytes,
'invalid_fcs': self.invalid_fcs, 'oversized_frames': self.oversized}
@contextmanager
def exclusive_session(path='/run/lock/platina-cellular-rpmsg.lock'):
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise RuntimeError('Another RPMsg cellular session is active') from None
yield
finally:
os.close(fd)
@contextmanager
def open_channel(channel='DS', timeout=5, sys_path='/sys', dev_path='/dev'):
if not re.fullmatch(r'DS|DATA(?:1|2|3|4|11)', channel):
raise ValueError('Select DS, DATA1, DATA2, DATA3, DATA4, or DATA11')
root = Path(sys_path)
matches = list((root / 'bus/rpmsg/devices').glob(
f'4080000.remoteproc:glink-edge.{channel}.*'))
if len(matches) != 1:
raise RuntimeError(f'Expected one modem {channel} channel, found {len(matches)}')
device = matches[0]
if (device / 'driver').exists():
raise RuntimeError(f'{channel} is already bound; refusing to take it over')
driver = root / 'bus/rpmsg/drivers/rpmsg_chrdev'
override = device / 'driver_override'
previous = override.read_text().strip()
if previous == '(null)':
previous = ''
fd = None
bound = False
try:
override.write_text('rpmsg_chrdev\n')
(driver / 'bind').write_text(device.name + '\n')
bound = True
deadline = time.monotonic() + timeout
while True:
endpoints = [p for p in (device / 'rpmsg').glob('rpmsg*')
if re.fullmatch(r'rpmsg\d+', p.name)]
if len(endpoints) == 1:
node = Path(dev_path) / endpoints[0].name
if node.exists():
break
if time.monotonic() >= deadline:
raise TimeoutError('RPMsg endpoint device did not appear')
time.sleep(0.05)
fd = os.open(node, os.O_RDWR | os.O_NONBLOCK)
yield fd
finally:
if fd is not None:
os.close(fd)
try:
if bound and (device / 'driver').exists() and (device / 'driver').resolve() == driver.resolve():
try:
(driver / 'unbind').write_text(device.name + '\n')
except OSError as exc:
if exc.errno not in (errno.ENOENT, errno.ENODEV):
raise
finally:
# GLINK closes and re-announces the service during unbind, which
# can remove the old sysfs device (and its override) immediately.
if override.exists():
try:
override.write_text(previous + '\n')
except OSError as exc:
if exc.errno not in (errno.ENOENT, errno.ENODEV):
raise
def send_message(fd, data):
# A blocking GLINK send requests a remote RX intent. trysend alone
# cannot make progress on channels which advertise intents on demand.
# GLINK bounds its intent request wait in the kernel (currently 10 s).
os.set_blocking(fd, True)
try:
if os.write(fd, data) != len(data):
raise RuntimeError('Incomplete RPMsg message write')
finally:
os.set_blocking(fd, False)
AT_RESULT = re.compile(rb'(?:^|[\r\n])(OK|ERROR|CONNECT(?: [^\r\n]*)?|'
rb'NO CARRIER|BUSY|NO DIALTONE|\+CME ERROR:[^\r\n]*)[\r\n]')
def at_command(fd, command, timeout=5):
if '\r' in command or '\n' in command or not command.startswith('AT'):
raise ValueError('Expected one AT command')
send_message(fd, command.encode('ascii') + b'\r')
deadline = time.monotonic() + timeout
response = bytearray()
while time.monotonic() < deadline and len(response) < 65536:
if not select.select([fd], [], [], max(0, deadline - time.monotonic()))[0]:
break
try:
data = os.read(fd, 65536)
except BlockingIOError:
continue
if not data:
raise RuntimeError('RPMsg channel closed')
response.extend(data)
match = AT_RESULT.search(response)
if match:
return {'command': command, 'result': match[1].decode('ascii'),
'response': response[:match.end()].decode('ascii', errors='replace'),
'trailing': bytes(response[match.end():])}
return {'command': command, 'result': 'TIMEOUT',
'response': response.decode('ascii', errors='replace'), 'trailing': b''}
def query(fd, timeout=5):
results = []
for command in ('AT', 'AT+CFUN?', 'AT+CPIN?', 'AT+CSQ', 'AT+COPS?',
'AT+CEREG?', 'AT+CGREG?', 'AT+CGATT?', 'AT+CGDCONT?',
'AT+CGACT?', 'AT+CGPADDR', 'AT+CGCONTRDP',
'AT+CGDATA=?', 'AT+CEER'):
result = at_command(fd, command, timeout)
result.pop('trailing')
results.append(result)
if result['result'] == 'TIMEOUT':
break
return results
def ppp_command(terminal, interface='ppp0'):
if not re.fullmatch(r'ppp\d+', interface):
raise ValueError('PPP interface must be ppp followed by a number')
return ['pppd', terminal, '115200', 'nodetach', 'local', 'nocrtscts',
'noauth', 'noipdefault', 'nodefaultroute', 'noipv6', 'noccp',
'ipcp-accept-local', 'ipcp-accept-remote', 'ifname', interface,
'lcp-echo-interval', '10', 'lcp-echo-failure', '3', 'debug']
def interface_ipv4(interface):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
try:
data = fcntl.ioctl(sock.fileno(), 0x8915, struct.pack('256s', interface.encode()))
address = socket.inet_ntoa(data[20:24])
return address if address != '0.0.0.0' else None
except OSError:
return None
def stop_ppp(proc, fd, master, timeout=5):
"""Keep the transport alive while pppd sends its termination handshake."""
if proc.poll() is not None:
return
proc.terminate()
deadline = time.monotonic() + timeout
pending = bytearray()
try:
while proc.poll() is None and time.monotonic() < deadline:
readable, writable, _ = select.select(
[fd, master], [master] if pending else [], [],
min(0.1, max(0, deadline - time.monotonic())))
if master in writable:
try:
count = os.write(master, pending)
del pending[:count]
except BlockingIOError:
pass
if fd in readable:
try:
data = os.read(fd, 65536)
except BlockingIOError:
data = None
if data == b'':
break
if data:
pending.extend(data)
if len(pending) > 1024 * 1024:
break
if master in readable:
try:
data = os.read(master, 1024)
except BlockingIOError:
continue
if data:
send_message(fd, data)
except (OSError, RuntimeError):
# Remote modem teardown can remove the endpoint before pppd exits.
# Process cleanup must still finish, and must not hide the main error.
pass
finally:
if proc.poll() is None:
proc.kill()
proc.wait(timeout=5)
def probe_dns(interface, target):
"""Query a public resolver over a socket explicitly bound to the PPP device."""
transaction = os.urandom(2)
request = transaction + struct.pack('!HHHHH', 0x0100, 1, 0, 0, 0)
request += b'\x07example\x03com\x00' + struct.pack('!HH', 1, 1)
errors = []
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, interface.encode() + b'\0')
sock.settimeout(3)
sock.connect((target, 53))
for _ in range(3):
try:
sock.send(request)
response = sock.recv(4096)
if len(response) < 12 or response[:2] != transaction:
errors.append('Invalid DNS transaction')
continue
_, flags, questions, answers, _, _ = struct.unpack('!6H', response[:12])
if flags & 0x8000 and flags & 0x000f == 0 and questions == 1 and answers:
return {'kind': 'dns', 'interface': interface, 'target': target,
'exit_code': 0, 'response_bytes': len(response), 'answers': answers}
errors.append('DNS response without a successful answer')
except OSError as exc:
errors.append(str(exc))
return {'kind': 'dns', 'interface': interface, 'target': target,
'exit_code': 1, 'errors': errors}
def wait_registration(fd, timeout=60):
deadline = time.monotonic() + timeout
last_response = None
while True:
result = at_command(fd, 'AT+CEREG?', min(5, max(0.1, deadline - time.monotonic())))
result.pop('trailing')
if result['response'] != last_response:
print(json.dumps(result), flush=True)
last_response = result['response']
if re.search(r'\+CEREG:\s*\d+,\s*[15](?:\s*[,\r\n]|$)', result['response']):
return
if time.monotonic() >= deadline:
raise TimeoutError('Modem did not register for LTE packet service')
time.sleep(min(2, max(0, deadline - time.monotonic())))
@contextmanager
def data_session():
"""Temporarily own modem control, restoring the manager's initial state."""
subprocess.run(['platina-cellular', '--battery-check'], check=True)
manager_running = subprocess.run(['rc-service', 'modemmanager', 'status'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL).returncode == 0
if manager_running:
subprocess.run(['rc-service', 'modemmanager', 'stop'], check=True)
try:
subprocess.run(['qmicli', '-d', 'qrtr://0', '--dms-set-operating-mode=online'],
check=True)
yield
finally:
if manager_running:
subprocess.run(['rc-service', 'modemmanager', 'start'], check=True)
def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='atd',
registration_timeout=180, verify_target=None, verify_kind='ping'):
if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9.-]{0,99}', apn):
raise ValueError('Invalid APN')
ppp_command('/dev/pts/0', interface) # validate before changing modem settings
if (Path('/sys/class/net') / interface).exists():
raise RuntimeError(f'{interface} already exists; refusing to take over a link')
if verify_target is not None:
address = ipaddress.IPv4Address(verify_target)
if not address.is_global:
raise ValueError('Verification requires a public IPv4 address')
verify_target = str(address)
if not shutil.which('pppd'):
raise RuntimeError('Install ppp-daemon first; pppd was not found')
subprocess.run(['platina-cellular', '--battery-check'], check=True)
for module in ('ppp_generic', 'ppp_async'):
subprocess.run(['modprobe', module], check=True)
# Keep the AT endpoint open while RF registers, before requesting a call.
for command in ('AT', 'ATE0', 'AT+CMEE=2'):
result = at_command(fd, command, timeout)
result.pop('trailing')
print(json.dumps(result), flush=True)
if result['result'] != 'OK':
raise RuntimeError(f'{command} returned {result["result"]}')
wait_registration(fd, registration_timeout)
dial = {'cgdata': 'AT+CGDATA="PPP",1', 'atd': 'ATD*99#'}[dial_method]
for command in (f'AT+CGDCONT=1,"IP","{apn}"', dial):
result = at_command(fd, command, timeout)
trailing = result.pop('trailing')
print(json.dumps(result), flush=True)
expected = 'CONNECT' if command == dial else 'OK'
if not result['result'].startswith(expected):
if command == dial:
error = at_command(fd, 'AT+CEER', 5)
error.pop('trailing')
print(json.dumps(error), flush=True)
raise RuntimeError(f'{command} returned {result["result"]}')
master, slave = pty.openpty()
proc = None
ping = None
dns_pool = None
dns_future = None
route = None
local_ip = None
verification = None
tx_bytes = rx_bytes = 0
tx_frames, rx_frames = PPPFrameStats(), PPPFrameStats()
rx_frames.feed(trailing)
try:
tty.setraw(slave)
os.set_blocking(master, False)
command = ppp_command(os.ttyname(slave), interface)
proc = subprocess.Popen(command)
to_pty = bytearray(trailing)
deadline = time.monotonic() + duration if duration else float('inf')
while proc.poll() is None and time.monotonic() < deadline:
if not local_ip:
local_ip = interface_ipv4(interface)
if verify_target and local_ip and ping is None and dns_future is None:
# Add, never replace, an exact host route and remove it below.
candidate = [f'{verify_target}/32', 'dev', interface, 'metric', '42760']
subprocess.run(['ip', 'route', 'add'] + candidate, check=True)
route = candidate
if verify_kind == 'dns':
dns_pool = ThreadPoolExecutor(max_workers=1)
dns_future = dns_pool.submit(probe_dns, interface, verify_target)
else:
ping = subprocess.Popen(['ping', '-n', '-I', interface, '-c', '4',
'-W', '3', verify_target], stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, text=True)
if dns_future is not None and dns_future.done():
verification = dns_future.result()
break
if ping is not None and ping.poll() is not None:
output, _ = ping.communicate()
verification = {'kind': 'ping', 'target': verify_target, 'exit_code': ping.returncode,
'output': output, 'interface': interface}
break
readable, writable, _ = select.select(
[fd, master], [master] if to_pty else [], [], 0.2)
if master in writable:
try:
count = os.write(master, to_pty)
del to_pty[:count]
except BlockingIOError:
pass
if fd in readable:
try:
data = os.read(fd, 65536)
except BlockingIOError:
data = None
if data == b'':
raise RuntimeError('Modem closed PPP channel')
if data:
to_pty.extend(data)
rx_bytes += len(data)
rx_frames.feed(data)
if len(to_pty) > 1024 * 1024:
raise RuntimeError('PPP receive queue exceeded 1 MiB')
if master in readable:
try:
data = os.read(master, 1024)
except BlockingIOError:
continue
except OSError as exc:
if exc.errno == errno.EIO:
break
raise
if data:
send_message(fd, data)
tx_bytes += len(data)
tx_frames.feed(data)
return {'interface': interface, 'local_ip': local_ip,
'bridge_tx_bytes': tx_bytes,
'bridge_rx_bytes': rx_bytes, 'pppd_exit': proc.poll(),
'ppp_frames': {'tx': tx_frames.summary(), 'rx': rx_frames.summary()},
'verification': verification,
'ip_connectivity': bool(verification and verification['exit_code'] == 0)}
finally:
if ping is not None and ping.poll() is None:
ping.terminate()
try:
ping.wait(timeout=5)
except subprocess.TimeoutExpired:
ping.kill()
ping.wait()
if route is not None:
subprocess.run(['ip', 'route', 'del'] + route, check=False)
if dns_pool is not None:
dns_pool.shutdown(wait=True, cancel_futures=True)
if proc is not None and proc.poll() is None:
stop_ppp(proc, fd, master)
os.close(master)
os.close(slave)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--channel', default='DS')
parser.add_argument('--timeout', type=float, default=5)
modes = parser.add_mutually_exclusive_group()
modes.add_argument('--query', action='store_true')
modes.add_argument('--connect', action='store_true')
parser.add_argument('--apn', help='Required for --connect')
parser.add_argument('--interface', default='ppp0')
parser.add_argument('--dial-method', choices=('cgdata', 'atd'), default='atd')
parser.add_argument('--registration-timeout', type=float, default=180)
parser.add_argument('--glink-signals', type=int, choices=(0, 1),
help='Experimental GLINK signal value: 1 sets DTR/RTS, 0 clears them')
parser.add_argument('--verify-target', help='Temporarily route and probe this public IPv4 via PPP only')
parser.add_argument('--verify-kind', choices=('ping', 'dns'), default='ping')
parser.add_argument('--duration', type=float, default=120,
help='PPP run time in seconds; 0 runs until interrupted')
args = parser.parse_args()
if not 0 < args.timeout <= 30:
parser.error('--timeout must be between 0 and 30 seconds')
if args.connect and not args.apn:
parser.error('--connect requires --apn')
if args.duration < 0 or not args.duration < float('inf'):
parser.error('--duration must be finite and nonnegative')
if not 0 < args.registration_timeout <= 300:
parser.error('--registration-timeout must be between 0 and 300 seconds')
signal.signal(signal.SIGTERM, interrupted)
try:
with exclusive_session(), data_session() if args.connect else nullcontext():
with open_channel(args.channel, args.timeout) as fd:
signals = args.glink_signals
if args.connect and signals is None:
signals = 1
if signals is not None:
# _IOR(0xb5, 6, int); rpmsg_char consumes the scalar argument.
fcntl.ioctl(fd, 0x8004B506, signals)
if args.connect:
result = connect(fd, args.apn, args.interface, args.duration,
dial_method=args.dial_method,
registration_timeout=args.registration_timeout,
verify_target=args.verify_target,
verify_kind=args.verify_kind)
elif args.query:
result = query(fd, args.timeout)
else:
result = at_command(fd, 'AT', args.timeout)
result.pop('trailing')
print(json.dumps(result, indent=2))
if args.connect:
# A bridge's byte counts are not an Internet connectivity test.
if args.verify_target:
return 0 if result['ip_connectivity'] else 1
return 0 if result['local_ip'] and result['pppd_exit'] in (None, 0) else 1
if args.query:
return 0 if result and result[0]['result'] == 'OK' else 1
return 0 if result['result'] == 'OK' else 1
except (OSError, RuntimeError, ValueError, subprocess.SubprocessError) as exc:
print(json.dumps({'channel': args.channel, 'error': str(exc)}))
return 1
except KeyboardInterrupt:
return 130
def interrupted(signum, frame):
raise KeyboardInterrupt
if __name__ == '__main__':
raise SystemExit(main())