Reticulum/RNS/__init__.py

426 lines
13 KiB
Python
Raw Normal View History

2022-04-01 15:18:18 +00:00
# MIT License
#
2023-09-29 08:31:20 +00:00
# Copyright (c) 2016-2023 Mark Qvist / unsigned.io and contributors
2022-04-01 15:18:18 +00:00
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
2016-06-03 17:02:02 +00:00
import os
2018-04-16 20:04:28 +00:00
import sys
2016-06-03 17:02:02 +00:00
import glob
2018-03-19 15:39:08 +00:00
import time
import random
import threading
2016-06-03 17:02:02 +00:00
2021-08-19 12:10:37 +00:00
from ._version import __version__
from .Reticulum import Reticulum
2018-03-16 09:50:37 +00:00
from .Identity import Identity
2021-09-02 18:35:42 +00:00
from .Link import Link, RequestReceipt
from .Channel import MessageBase
from .Buffer import Buffer, RawChannelReader, RawChannelWriter
2018-03-16 09:50:37 +00:00
from .Transport import Transport
2018-03-19 15:39:08 +00:00
from .Destination import Destination
from .Packet import Packet
2018-04-17 15:46:48 +00:00
from .Packet import PacketReceipt
2023-09-29 08:31:20 +00:00
from .Resolver import Resolver
from .Resource import Resource, ResourceAdvertisement
from .Cryptography import HKDF
from .Cryptography import Hashes
2018-03-16 09:50:37 +00:00
2016-06-03 17:02:02 +00:00
modules = glob.glob(os.path.dirname(__file__)+"/*.py")
2018-03-19 15:39:08 +00:00
__all__ = [ os.path.basename(f)[:-3] for f in modules if not f.endswith('__init__.py')]
LOG_CRITICAL = 0
LOG_ERROR = 1
LOG_WARNING = 2
LOG_NOTICE = 3
LOG_INFO = 4
LOG_VERBOSE = 5
LOG_DEBUG = 6
2018-04-23 21:42:16 +00:00
LOG_EXTREME = 7
2018-03-19 15:39:08 +00:00
2020-08-13 10:15:56 +00:00
LOG_STDOUT = 0x91
2018-03-19 15:39:08 +00:00
LOG_FILE = 0x92
2021-10-08 17:23:10 +00:00
LOG_MAXSIZE = 5*1024*1024
2022-11-01 19:26:55 +00:00
loglevel = LOG_NOTICE
logfile = None
logdest = LOG_STDOUT
logtimefmt = "%Y-%m-%d %H:%M:%S"
compact_log_fmt = False
2018-03-19 15:39:08 +00:00
instance_random = random.Random()
instance_random.seed(os.urandom(10))
_always_override_destination = False
logging_lock = threading.Lock()
2018-03-19 15:39:08 +00:00
def loglevelname(level):
2020-08-13 10:15:56 +00:00
if (level == LOG_CRITICAL):
return "Critical"
if (level == LOG_ERROR):
return "Error"
if (level == LOG_WARNING):
return "Warning"
if (level == LOG_NOTICE):
return "Notice"
if (level == LOG_INFO):
return "Info"
if (level == LOG_VERBOSE):
return "Verbose"
if (level == LOG_DEBUG):
return "Debug"
if (level == LOG_EXTREME):
return "Extra"
2024-10-07 08:52:43 +00:00
2020-08-13 10:15:56 +00:00
return "Unknown"
2018-03-19 15:39:08 +00:00
2021-08-19 12:10:37 +00:00
def version():
return __version__
2021-12-01 10:40:44 +00:00
def host_os():
from .vendor.platformutils import get_platform
return get_platform()
def timestamp_str(time_s):
timestamp = time.localtime(time_s)
return time.strftime(logtimefmt, timestamp)
def log(msg, level=3, _override_destination = False):
2022-11-01 19:26:55 +00:00
global _always_override_destination, compact_log_fmt
msg = str(msg)
2020-08-13 10:15:56 +00:00
if loglevel >= level:
2022-11-01 19:26:55 +00:00
if not compact_log_fmt:
logstring = "["+timestamp_str(time.time())+"] ["+loglevelname(level)+"] "+msg
else:
logstring = "["+timestamp_str(time.time())+"] "+msg
logging_lock.acquire()
2018-03-19 15:39:08 +00:00
2021-08-19 12:10:37 +00:00
if (logdest == LOG_STDOUT or _always_override_destination or _override_destination):
2020-08-13 10:15:56 +00:00
print(logstring)
logging_lock.release()
2018-03-19 15:39:08 +00:00
elif (logdest == LOG_FILE and logfile != None):
try:
file = open(logfile, "a")
file.write(logstring+"\n")
file.close()
2024-10-07 08:52:43 +00:00
2021-10-08 17:23:10 +00:00
if os.path.getsize(logfile) > LOG_MAXSIZE:
prevfile = logfile+".1"
if os.path.isfile(prevfile):
os.unlink(prevfile)
os.rename(logfile, prevfile)
logging_lock.release()
except Exception as e:
logging_lock.release()
_always_override_destination = True
log("Exception occurred while writing log message to log file: "+str(e), LOG_CRITICAL)
log("Dumping future log events to console!", LOG_CRITICAL)
log(msg, level)
2024-10-07 08:52:43 +00:00
2018-03-19 17:11:50 +00:00
def rand():
result = instance_random.random()
2020-08-13 10:15:56 +00:00
return result
2024-01-14 17:56:20 +00:00
def trace_exception(e):
import traceback
exception_info = "".join(traceback.TracebackException.from_exception(e).format())
2024-10-07 08:44:18 +00:00
log(f"An unhandled {type(e)} exception occurred: {e}", LOG_ERROR)
2024-01-14 17:56:20 +00:00
log(exception_info, LOG_ERROR)
2018-03-19 17:11:50 +00:00
def hexrep(data, delimit=True):
try:
iter(data)
except TypeError:
data = [data]
2024-10-07 08:52:43 +00:00
2020-08-13 10:15:56 +00:00
delimiter = ":"
if not delimit:
delimiter = ""
hexrep = delimiter.join("{:02x}".format(c) for c in data)
return hexrep
2018-03-20 11:32:41 +00:00
def prettyhexrep(data):
2020-08-13 10:15:56 +00:00
delimiter = ""
hexrep = "<"+delimiter.join("{:02x}".format(c) for c in data)+">"
return hexrep
2018-04-16 20:04:28 +00:00
def prettyspeed(num, suffix="b"):
return prettysize(num/8, suffix=suffix)+"ps"
2022-06-09 12:46:36 +00:00
def prettysize(num, suffix='B'):
units = ['','K','M','G','T','P','E','Z']
last_unit = 'Y'
if suffix == 'b':
num *= 8
units = ['','K','M','G','T','P','E','Z']
last_unit = 'Y'
for unit in units:
if abs(num) < 1000.0:
if unit == "":
2024-10-07 08:44:18 +00:00
return "{:.0f} {}{}".format(num, unit, suffix)
2022-06-09 12:46:36 +00:00
else:
2024-10-07 08:44:18 +00:00
return "{:.2f} {}{}".format(num, unit, suffix)
2022-06-09 12:46:36 +00:00
num /= 1000.0
2024-10-07 08:44:18 +00:00
return "{:.2f}{}{}".format(num, last_unit, suffix)
2022-06-09 12:46:36 +00:00
def prettyfrequency(hz, suffix="Hz"):
num = hz*1e6
units = ["µ", "m", "", "K","M","G","T","P","E","Z"]
last_unit = "Y"
for unit in units:
if abs(num) < 1000.0:
2024-10-07 08:44:18 +00:00
return "{:.2f} {}{}".format(num, unit, suffix)
num /= 1000.0
2024-10-07 08:44:18 +00:00
return "{:.2f}{}{}".format(num, last_unit, suffix)
2023-10-24 11:24:40 +00:00
def prettydistance(m, suffix="m"):
num = m*1e6
units = ["µ", "m", "c", ""]
last_unit = "K"
2023-10-23 23:41:49 +00:00
for unit in units:
2023-10-24 11:24:40 +00:00
divisor = 1000.0
if unit == "m": divisor = 10
if unit == "c": divisor = 100
if abs(num) < divisor:
2024-10-07 08:44:18 +00:00
return "{:.2f} {}{}".format(num, unit, suffix)
2023-10-24 11:24:40 +00:00
num /= divisor
2023-10-23 23:41:49 +00:00
2024-10-07 08:44:18 +00:00
return "{:.2f} {}{}".format(num, last_unit, suffix)
2023-10-23 23:41:49 +00:00
def prettytime(time, verbose=False, compact=False):
2022-07-02 11:12:54 +00:00
days = int(time // (24 * 3600))
time = time % (24 * 3600)
hours = int(time // 3600)
time %= 3600
minutes = int(time // 60)
time %= 60
2023-10-23 23:41:49 +00:00
if compact:
seconds = int(time)
else:
seconds = round(time, 2)
2024-10-07 08:52:43 +00:00
2022-07-02 11:12:54 +00:00
ss = "" if seconds == 1 else "s"
sm = "" if minutes == 1 else "s"
sh = "" if hours == 1 else "s"
sd = "" if days == 1 else "s"
2023-10-23 23:41:49 +00:00
displayed = 0
2022-07-02 11:12:54 +00:00
components = []
2023-10-23 23:41:49 +00:00
if days > 0 and ((not compact) or displayed < 2):
2022-07-02 11:12:54 +00:00
components.append(str(days)+" day"+sd if verbose else str(days)+"d")
2023-10-23 23:41:49 +00:00
displayed += 1
2022-07-02 11:12:54 +00:00
2023-10-23 23:41:49 +00:00
if hours > 0 and ((not compact) or displayed < 2):
2022-07-02 11:12:54 +00:00
components.append(str(hours)+" hour"+sh if verbose else str(hours)+"h")
2023-10-23 23:41:49 +00:00
displayed += 1
2022-07-02 11:12:54 +00:00
2023-10-23 23:41:49 +00:00
if minutes > 0 and ((not compact) or displayed < 2):
2022-07-02 11:12:54 +00:00
components.append(str(minutes)+" minute"+sm if verbose else str(minutes)+"m")
2023-10-23 23:41:49 +00:00
displayed += 1
2022-07-02 11:12:54 +00:00
2023-10-23 23:41:49 +00:00
if seconds > 0 and ((not compact) or displayed < 2):
2022-07-02 11:12:54 +00:00
components.append(str(seconds)+" second"+ss if verbose else str(seconds)+"s")
2023-10-23 23:41:49 +00:00
displayed += 1
2022-07-02 11:12:54 +00:00
i = 0
tstr = ""
for c in components:
i += 1
if i == 1:
pass
elif i < len(components):
tstr += ", "
elif i == len(components):
tstr += " and "
tstr += c
2022-11-23 16:15:46 +00:00
if tstr == "":
return "0s"
else:
return tstr
2022-07-02 11:12:54 +00:00
2024-09-15 13:12:53 +00:00
def prettyshorttime(time, verbose=False, compact=False):
time = time*1e6
2024-10-07 08:52:43 +00:00
2024-09-15 13:12:53 +00:00
seconds = int(time // 1e6); time %= 1e6
milliseconds = int(time // 1e3); time %= 1e3
if compact:
microseconds = int(time)
else:
microseconds = round(time, 2)
2024-10-07 08:52:43 +00:00
2024-09-15 13:12:53 +00:00
ss = "" if seconds == 1 else "s"
sms = "" if milliseconds == 1 else "s"
sus = "" if microseconds == 1 else "s"
displayed = 0
components = []
if seconds > 0 and ((not compact) or displayed < 2):
components.append(str(seconds)+" second"+ss if verbose else str(seconds)+"s")
displayed += 1
if milliseconds > 0 and ((not compact) or displayed < 2):
components.append(str(milliseconds)+" millisecond"+sms if verbose else str(milliseconds)+"ms")
displayed += 1
if microseconds > 0 and ((not compact) or displayed < 2):
components.append(str(microseconds)+" microsecond"+sus if verbose else str(microseconds)+"µs")
displayed += 1
i = 0
tstr = ""
for c in components:
i += 1
if i == 1:
pass
elif i < len(components):
tstr += ", "
elif i == len(components):
tstr += " and "
tstr += c
if tstr == "":
return "0us"
else:
return tstr
2022-06-30 12:02:57 +00:00
def phyparams():
print("Required Physical Layer MTU : "+str(Reticulum.MTU)+" bytes")
print("Plaintext Packet MDU : "+str(Packet.PLAIN_MDU)+" bytes")
print("Encrypted Packet MDU : "+str(Packet.ENCRYPTED_MDU)+" bytes")
print("Link Curve : "+str(Link.CURVE))
2023-03-04 17:37:28 +00:00
print("Link Packet MDU : "+str(Link.MDU)+" bytes")
2022-06-30 12:02:57 +00:00
print("Link Public Key Size : "+str(Link.ECPUBSIZE*8)+" bits")
print("Link Private Key Size : "+str(Link.KEYSIZE*8)+" bits")
2018-04-16 20:04:28 +00:00
def panic():
os._exit(255)
def exit():
print("")
sys.exit(0)
2024-09-15 13:12:53 +00:00
profiler_ran = False
profiler_tags = {}
2024-09-15 14:46:52 +00:00
def profiler(tag=None, capture=False, super_tag=None):
2024-09-15 13:12:53 +00:00
global profiler_ran, profiler_tags
try:
thread_ident = threading.get_ident()
if capture:
end = time.perf_counter()
2024-09-15 14:46:52 +00:00
if tag in profiler_tags and thread_ident in profiler_tags[tag]["threads"]:
if profiler_tags[tag]["threads"][thread_ident]["current_start"] != None:
begin = profiler_tags[tag]["threads"][thread_ident]["current_start"]
profiler_tags[tag]["threads"][thread_ident]["current_start"] = None
profiler_tags[tag]["threads"][thread_ident]["captures"].append(end-begin)
if not profiler_ran:
profiler_ran = True
2024-09-15 13:12:53 +00:00
else:
if not tag in profiler_tags:
2024-09-15 14:46:52 +00:00
profiler_tags[tag] = {"threads": {}, "super": super_tag}
2024-09-15 13:12:53 +00:00
if not thread_ident in profiler_tags[tag]["threads"]:
profiler_tags[tag]["threads"][thread_ident] = {"current_start": None, "captures": []}
profiler_tags[tag]["threads"][thread_ident]["current_start"] = time.perf_counter()
except Exception as e:
trace_exception(e)
def profiler_results():
from statistics import mean, median, stdev
results = {}
2024-10-07 08:52:43 +00:00
2024-09-15 13:12:53 +00:00
for tag in profiler_tags:
tag_captures = []
tag_entry = profiler_tags[tag]
2024-10-07 08:52:43 +00:00
2024-09-15 13:12:53 +00:00
for thread_ident in tag_entry["threads"]:
thread_entry = tag_entry["threads"][thread_ident]
thread_captures = thread_entry["captures"]
sample_count = len(thread_captures)
2024-10-07 08:52:43 +00:00
2024-09-15 13:12:53 +00:00
if sample_count > 2:
thread_results = {
"count": sample_count,
"mean": mean(thread_captures),
"median": median(thread_captures),
"stdev": stdev(thread_captures)
}
tag_captures.extend(thread_captures)
sample_count = len(tag_captures)
if sample_count > 2:
tag_results = {
2024-09-15 14:46:52 +00:00
"name": tag,
"super": tag_entry["super"],
2024-09-15 13:12:53 +00:00
"count": len(tag_captures),
"mean": mean(tag_captures),
"median": median(tag_captures),
"stdev": stdev(tag_captures)
}
results[tag] = tag_results
2024-09-15 14:46:52 +00:00
def print_results_recursive(tag, results, level=0):
print_tag_results(tag, level+1)
for tag_name in results:
sub_tag = results[tag_name]
if sub_tag["super"] == tag["name"]:
print_results_recursive(sub_tag, results, level=level+1)
def print_tag_results(tag, level):
ind = " "*level
2024-09-16 16:20:31 +00:00
name = tag["name"]; count = tag["count"]
mean = tag["mean"]; tag["median"]; stdev = tag["stdev"]
print(f"{ind}{name}")
print(f"{ind} Samples : {count}")
print(f"{ind} Mean : {prettyshorttime(mean)}")
print(f"{ind} Median : {prettyshorttime(median)}")
print(f"{ind} St.dev. : {prettyshorttime(stdev)}")
2024-09-15 14:46:52 +00:00
print("")
2024-09-15 13:12:53 +00:00
print("\nProfiler results:\n")
for tag_name in results:
tag = results[tag_name]
2024-09-15 14:46:52 +00:00
if tag["super"] == None:
print_results_recursive(tag, results)