mirror of
https://github.com/markqvist/LXMF
synced 2026-11-22 23:10:36 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
abe2e78283 | ||
|
|
edbb887d81 | ||
|
|
540aa1a496 | ||
|
|
3d31620160 | ||
|
|
6b983872fa | ||
|
|
bb7bbaf124 | ||
|
|
dad21bcca7 | ||
|
|
f75ea842d9 | ||
|
|
f7ee4c1d86 | ||
|
|
58c61a2557 | ||
|
|
730a611f7a | ||
|
|
ab68c15d2d | ||
|
|
564cd9b18c | ||
|
|
cacddfdf30 | ||
|
|
adbbaa532b | ||
|
|
2d81b47b6a | ||
|
|
1c4928a29b | ||
|
|
2181584f69 | ||
|
|
8bb21688e5 | ||
|
|
8cdf12e866 | ||
|
|
a1dae1fc15 | ||
|
|
2f43d660d5 | ||
|
|
920beaf6f5 | ||
|
|
6b28cd8698 | ||
|
|
323a968525 | ||
|
|
a26dfe3b7b | ||
|
|
ce91cab7ef | ||
|
|
ff48661f60 | ||
|
|
afe529fa0a | ||
|
|
5bb187a502 | ||
|
|
e5204423b0 | ||
|
|
8be54bcc5f | ||
|
|
3dfb05a25c | ||
|
|
ca84f4c8fe | ||
|
|
039df2bd46 | ||
|
|
0a84d9da76 | ||
|
|
33e41caf4a | ||
|
|
b2aba3f6db | ||
|
|
ece55d10d6 | ||
|
|
323241a4b8 | ||
|
|
bd3ace0885 | ||
|
|
ed4effdab7 | ||
|
|
2d1828513f | ||
|
|
505176b6ee | ||
|
|
853e70dcbe | ||
|
|
38cc471eaf | ||
|
|
704930f91a | ||
|
|
137db1e6a3 | ||
|
|
5e8b2d87af | ||
|
|
38b6f7651c | ||
|
|
6aa793252f | ||
|
|
1ca2493c36 | ||
|
|
38bbf19421 | ||
|
|
776e72d0ba | ||
|
|
29f6089967 | ||
|
|
512a34e2c3 | ||
|
|
934a208965 | ||
|
|
d2bc7fc32e | ||
|
|
ca18d067f2 | ||
|
|
fbbda8153e | ||
|
|
831e91a87a | ||
|
|
2a6c602e9b | ||
|
|
f391b95597 | ||
|
|
71a9f16bde | ||
|
|
b2596bd561 | ||
|
|
0c34dae1af | ||
|
|
25bcba84d2 | ||
|
|
937ae70a85 | ||
|
|
92b4aaaaee | ||
|
|
156109bf0b | ||
|
|
9a75b9c1ec | ||
|
|
b675e1c47e | ||
|
|
f5cb49b46b | ||
|
|
52dc086a26 | ||
|
|
354e1932dc | ||
|
|
093d4f1317 | ||
|
|
734305e9c7 | ||
|
|
ad773dcbc5 | ||
|
|
1c5e879abd | ||
|
|
7e34b201e1 | ||
|
|
335d9b1adf | ||
|
|
6cb3a23c9d | ||
|
|
4d3e529e63 | ||
|
|
3b0c2cac22 | ||
|
|
aa36f0ef6d | ||
|
|
a1bdcdf7f1 | ||
|
|
b7de273d16 | ||
|
|
11a9ea989f | ||
|
|
1ac9c3ad72 | ||
|
|
1e8ef437b9 | ||
|
|
ad541b3db9 | ||
|
|
e7f2ccc002 | ||
|
|
e8413be3dc | ||
|
|
81ab9f5a28 |
No files matched your search
@@ -8,6 +8,8 @@ __pycache__/
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
LXMF/Utilities/LXMF
|
||||
RNS
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import time
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
from .LXMF import APP_NAME
|
||||
|
||||
from .LXMessage import LXMessage
|
||||
|
||||
class LXMFDeliveryAnnounceHandler:
|
||||
def __init__(self, lxmrouter):
|
||||
self.aspect_filter = APP_NAME+".delivery"
|
||||
self.lxmrouter = lxmrouter
|
||||
|
||||
def received_announce(self, destination_hash, announced_identity, app_data):
|
||||
for lxmessage in self.lxmrouter.pending_outbound:
|
||||
if destination_hash == lxmessage.destination_hash:
|
||||
if lxmessage.method == LXMessage.DIRECT:
|
||||
lxmessage.next_delivery_attempt = time.time()
|
||||
|
||||
while self.lxmrouter.processing_outbound:
|
||||
time.sleep(0.1)
|
||||
|
||||
self.lxmrouter.process_outbound()
|
||||
|
||||
|
||||
class LXMFPropagationAnnounceHandler:
|
||||
def __init__(self, lxmrouter):
|
||||
self.aspect_filter = APP_NAME+".propagation"
|
||||
self.lxmrouter = lxmrouter
|
||||
|
||||
def received_announce(self, destination_hash, announced_identity, app_data):
|
||||
try:
|
||||
if type(app_data) == bytes:
|
||||
data = msgpack.unpackb(app_data)
|
||||
|
||||
if self.lxmrouter.propagation_node and self.lxmrouter.autopeer:
|
||||
if data[0] == True:
|
||||
if RNS.Transport.hops_to(destination_hash) <= self.lxmrouter.autopeer_maxdepth:
|
||||
self.lxmrouter.peer(destination_hash, data[1])
|
||||
elif data[0] == False:
|
||||
self.lxmrouter.unpeer(destination_hash, data[1])
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while evaluating propagation node announce, ignoring announce.", RNS.LOG_DEBUG)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
|
||||
+1
-684
@@ -1,684 +1 @@
|
||||
import math
|
||||
import time
|
||||
import threading
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
APP_NAME = "lxmf"
|
||||
|
||||
class LXMessage:
|
||||
DRAFT = 0x00
|
||||
OUTBOUND = 0x01
|
||||
SENDING = 0x02
|
||||
SENT = 0x04
|
||||
DELIVERED = 0x08
|
||||
FAILED = 0xFF
|
||||
states = [DRAFT, OUTBOUND, SENDING, SENT, DELIVERED, FAILED]
|
||||
|
||||
UNKNOWN = 0x00
|
||||
PACKET = 0x01
|
||||
RESOURCE = 0x02
|
||||
representations = [UNKNOWN, PACKET, RESOURCE]
|
||||
|
||||
OPPORTUNISTIC = 0x01
|
||||
DIRECT = 0x02
|
||||
PROPAGATED = 0x03
|
||||
valid_methods = [OPPORTUNISTIC, DIRECT, PROPAGATED]
|
||||
|
||||
SOURCE_UNKNOWN = 0x01
|
||||
SIGNATURE_INVALID = 0x02
|
||||
unverified_reasons = [SOURCE_UNKNOWN, SIGNATURE_INVALID]
|
||||
|
||||
DESTINATION_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
|
||||
SIGNATURE_LENGTH = RNS.Identity.SIGLENGTH//8
|
||||
|
||||
# LXMF overhead is 99 bytes per message:
|
||||
# 10 bytes for destination hash
|
||||
# 10 bytes for source hash
|
||||
# 64 bytes for Ed25519 signature
|
||||
# 8 bytes for timestamp
|
||||
# 7 bytes for msgpack structure
|
||||
LXMF_OVERHEAD = 2*DESTINATION_LENGTH + SIGNATURE_LENGTH + 8 + 7
|
||||
|
||||
# With an MTU of 500, the maximum amount of data
|
||||
# we can send in a single encrypted packet is
|
||||
# 383 bytes.
|
||||
ENCRYPTED_PACKET_MDU = RNS.Packet.ENCRYPTED_MDU
|
||||
|
||||
# The max content length we can fit in LXMF message
|
||||
# inside a single RNS packet is the encrypted MDU, minus
|
||||
# the LXMF overhead. We can optimise a bit though, by
|
||||
# inferring the destination hash from the destination
|
||||
# field of the packet, therefore we also add the length
|
||||
# of a destination hash to the calculation. With default
|
||||
# RNS and LXMF parameters, the largest single-packet
|
||||
# LXMF message we can send is 294 bytes. If a message
|
||||
# is larger than that, a Reticulum link will be used.
|
||||
ENCRYPTED_PACKET_MAX_CONTENT = ENCRYPTED_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
|
||||
|
||||
# Links can carry a larger MDU, due to less overhead per
|
||||
# packet. The link MDU with default Reticulum parameters
|
||||
# is 415 bytes.
|
||||
LINK_PACKET_MDU = RNS.Link.MDU
|
||||
|
||||
# Which means that we can deliver single-packet LXMF
|
||||
# messages with content of up to 316 bytes over a link.
|
||||
# If a message is larger than that, LXMF will sequence
|
||||
# and transfer it as a RNS resource over the link instead.
|
||||
LINK_PACKET_MAX_CONTENT = LINK_PACKET_MDU - LXMF_OVERHEAD
|
||||
|
||||
# For plain packets without encryption, we can
|
||||
# fit up to 324 bytes of content.
|
||||
PLAIN_PACKET_MDU = RNS.Packet.PLAIN_MDU
|
||||
PLAIN_PACKET_MAX_CONTENT = PLAIN_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
|
||||
|
||||
# Descriptive strings regarding transport encryption
|
||||
ENCRYPTION_DESCRIPTION_AES = "AES-128"
|
||||
ENCRYPTION_DESCRIPTION_EC = "Curve25519"
|
||||
ENCRYPTION_DESCRIPTION_UNENCRYPTED = "Unencrypted"
|
||||
|
||||
def __str__(self):
|
||||
if self.hash != None:
|
||||
return "<LXMessage "+RNS.hexrep(self.hash, delimit=False)+">"
|
||||
else:
|
||||
return "<LXMessage>"
|
||||
|
||||
def __init__(self, destination, source, content = "", title = "", fields = None, desired_method = None, destination_hash = None, source_hash = None):
|
||||
if isinstance(destination, RNS.Destination) or destination == None:
|
||||
self.__destination = destination
|
||||
if destination != None:
|
||||
self.destination_hash = destination.hash
|
||||
else:
|
||||
self.destination_hash = destination_hash
|
||||
else:
|
||||
raise ValueError("LXMessage initialised with invalid destination")
|
||||
|
||||
if isinstance(source, RNS.Destination) or source == None:
|
||||
self.__source = source
|
||||
if source != None:
|
||||
self.source_hash = source.hash
|
||||
else:
|
||||
self.source_hash = source_hash
|
||||
else:
|
||||
raise ValueError("LXMessage initialised with invalid source")
|
||||
|
||||
self.set_title_from_string(title)
|
||||
self.set_content_from_string(content)
|
||||
|
||||
self.set_fields(fields)
|
||||
|
||||
self.payload = None
|
||||
self.timestamp = None
|
||||
self.signature = None
|
||||
self.hash = None
|
||||
self.packed = None
|
||||
self.progress = None
|
||||
self.state = LXMessage.DRAFT
|
||||
self.method = LXMessage.UNKNOWN
|
||||
|
||||
self.incoming = False
|
||||
self.signature_validated = False
|
||||
self.unverified_reason = None
|
||||
|
||||
self.representation = LXMessage.UNKNOWN
|
||||
self.desired_method = desired_method
|
||||
self.delivery_attempts = 0
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = None
|
||||
self.packet_representation = None
|
||||
self.resource_representation = None
|
||||
self.__delivery_destination = None
|
||||
self.__delivery_callback = None
|
||||
self.failed_callback = None
|
||||
|
||||
def set_title_from_string(self, title_string):
|
||||
self.title = title_string.encode("utf-8")
|
||||
|
||||
def set_title_from_bytes(self, title_bytes):
|
||||
self.title = title_bytes
|
||||
|
||||
def title_as_string(self):
|
||||
return self.title.decode("utf-8")
|
||||
|
||||
def set_content_from_string(self, content_string):
|
||||
self.content = content_string.encode("utf-8")
|
||||
|
||||
def set_content_from_bytes(self, content_bytes):
|
||||
self.content = content_bytes
|
||||
|
||||
def content_as_string(self):
|
||||
return self.content.decode("utf-8")
|
||||
|
||||
def set_fields(self, fields):
|
||||
if isinstance(fields, dict) or fields == None:
|
||||
self.fields = fields
|
||||
else:
|
||||
raise ValueError("LXMessage property \"fields\" can only be dict or None")
|
||||
|
||||
def get_fields(self):
|
||||
return self.__fields
|
||||
|
||||
def set_destination(self, destination):
|
||||
if self.destination == None:
|
||||
if isinstance(destination, RNS.Destination):
|
||||
self.__destination = destination
|
||||
else:
|
||||
raise ValueError("Invalid destination set on LXMessage")
|
||||
else:
|
||||
raise ValueError("Cannot reassign destination on LXMessage")
|
||||
|
||||
def get_destination(self):
|
||||
return self.__destination
|
||||
|
||||
def set_source(self, source):
|
||||
if self.source == None:
|
||||
if isinstance(source, RNS.Destination):
|
||||
self.__source = source
|
||||
else:
|
||||
raise ValueError("Invalid source set on LXMessage")
|
||||
else:
|
||||
raise ValueError("Cannot reassign source on LXMessage")
|
||||
|
||||
def get_source(self):
|
||||
return self.__source
|
||||
|
||||
def set_delivery_destination(self, delivery_destination):
|
||||
self.__delivery_destination = delivery_destination
|
||||
|
||||
def register_delivery_callback(self, callback):
|
||||
self.__delivery_callback = callback
|
||||
|
||||
def register_failed_callback(self, callback):
|
||||
self.failed_callback = callback
|
||||
|
||||
def pack(self):
|
||||
if not self.packed:
|
||||
if self.timestamp == None:
|
||||
self.timestamp = time.time()
|
||||
|
||||
self.payload = [self.timestamp, self.title, self.content, self.fields]
|
||||
|
||||
hashed_part = b""
|
||||
hashed_part += self.__destination.hash
|
||||
hashed_part += self.__source.hash
|
||||
hashed_part += msgpack.packb(self.payload)
|
||||
self.hash = RNS.Identity.full_hash(hashed_part)
|
||||
self.message_id = self.hash
|
||||
|
||||
signed_part = b""
|
||||
signed_part += hashed_part
|
||||
signed_part += self.hash
|
||||
self.signature = self.__source.sign(signed_part)
|
||||
self.signature_validated = True
|
||||
|
||||
self.packed = b""
|
||||
self.packed += self.__destination.hash
|
||||
self.packed += self.__source.hash
|
||||
self.packed += self.signature
|
||||
packed_payload = msgpack.packb(self.payload)
|
||||
self.packed += packed_payload
|
||||
self.packed_size = len(self.packed)
|
||||
content_size = len(packed_payload)
|
||||
|
||||
# If no desired delivery method has been defined,
|
||||
# one will be chosen according to these rules:
|
||||
if self.desired_method == None:
|
||||
self.desired_method == LXMessage.DIRECT
|
||||
# TODO: Expand rules to something more intelligent
|
||||
|
||||
if self.desired_method == LXMessage.OPPORTUNISTIC:
|
||||
if self.__destination.type == RNS.Destination.SINGLE:
|
||||
single_packet_content_limit = LXMessage.RSA_PACKET_MAX_CONTENT
|
||||
elif self.__destination.type == RNS.Destination.PLAIN:
|
||||
single_packet_content_limit = LXMessage.PLAIN_PACKET_MAX_CONTENT
|
||||
|
||||
if content_size > single_packet_content_limit:
|
||||
raise TypeError("LXMessage desired opportunistic delivery method, but content exceeds single-packet size.")
|
||||
else:
|
||||
self.method = LXMessage.OPPORTUNISTIC
|
||||
self.representation = LXMessage.PACKET
|
||||
self.__delivery_destination = self.__destination
|
||||
|
||||
elif self.desired_method == LXMessage.DIRECT or self.desired_method == LXMessage.PROPAGATED:
|
||||
single_packet_content_limit = LXMessage.LINK_PACKET_MAX_CONTENT
|
||||
if content_size <= single_packet_content_limit:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.PACKET
|
||||
else:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.RESOURCE
|
||||
else:
|
||||
raise ValueError("Attempt to re-pack LXMessage "+str(self)+" that was already packed")
|
||||
|
||||
def send(self):
|
||||
self.determine_transport_encryption()
|
||||
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
self.__as_packet().send().set_delivery_callback(self.__mark_delivered)
|
||||
self.state = LXMessage.SENT
|
||||
elif self.method == LXMessage.DIRECT:
|
||||
self.state = LXMessage.SENDING
|
||||
self.resource_representation = self.__as_resource()
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
# TODO: Implement propagation
|
||||
pass
|
||||
|
||||
def determine_transport_encryption(self):
|
||||
if RNS.Reticulum.should_allow_unencrypted():
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
|
||||
else:
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
if self.destination.type == RNS.Destination.SINGLE:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
|
||||
elif destination_type == RNS.Destination.GROUP:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_AES
|
||||
else:
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
|
||||
elif self.method == LXMessage.DIRECT:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
if self.destination.type == RNS.Destination.SINGLE:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
|
||||
elif destination_type == RNS.Destination.GROUP:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_AES
|
||||
else:
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
|
||||
else:
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
|
||||
|
||||
def __mark_delivered(self, receipt = None):
|
||||
RNS.log("Received delivery notification for "+str(self), RNS.LOG_DEBUG)
|
||||
self.state = LXMessage.DELIVERED
|
||||
|
||||
if self.__delivery_callback != None:
|
||||
self.__delivery_callback(self)
|
||||
|
||||
def __resource_concluded(self, resource):
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
self.__mark_delivered()
|
||||
else:
|
||||
resource.link.teardown()
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
|
||||
def __update_transfer_progress(self, resource):
|
||||
self.progress = resource.progress()
|
||||
|
||||
def __as_packet(self):
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
if not self.__delivery_destination:
|
||||
raise ValueError("Can't synthesize packet for LXMF message before delivery destination is known")
|
||||
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
return RNS.Packet(self.__delivery_destination, self.packed[LXMessage.DESTINATION_LENGTH:])
|
||||
elif self.method == LXMessage.DIRECT or self.method == LXMessage.PROPAGATED:
|
||||
return RNS.Packet(self.__delivery_destination, self.packed)
|
||||
|
||||
def __as_resource(self):
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
if not self.__delivery_destination:
|
||||
raise ValueError("Can't synthesize resource for LXMF message before delivery destination is known")
|
||||
|
||||
if not self.__delivery_destination.type == RNS.Destination.LINK:
|
||||
raise TypeError("Tried to synthesize resource for LXMF message on a delivery destination that was not a link")
|
||||
|
||||
if not self.__delivery_destination.status == RNS.Link.ACTIVE:
|
||||
raise ConnectionError("Tried to synthesize resource for LXMF message on a link that was not active")
|
||||
|
||||
self.progress = 0.0
|
||||
return RNS.Resource(self.packed, self.__delivery_destination, callback = self.__resource_concluded, progress_callback = self.__update_transfer_progress)
|
||||
|
||||
def write_to_directory(self, directory_path):
|
||||
file_name = RNS.hexrep(self.hash, delimit=False)
|
||||
file_path = directory_path+"/"+file_name
|
||||
|
||||
try:
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
container = {
|
||||
"state": self.state,
|
||||
"lxmf_bytes": self.packed,
|
||||
"transport_encrypted": self.transport_encrypted,
|
||||
"transport_encryption": self.transport_encryption
|
||||
}
|
||||
|
||||
packed_container = msgpack.packb(container)
|
||||
|
||||
file = open(file_path, "wb")
|
||||
file.write(packed_container)
|
||||
file.close()
|
||||
|
||||
return file_path
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while writing LXMF message to file \""+str(file_path)+"\". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
|
||||
@staticmethod
|
||||
def unpack_from_bytes(lxmf_bytes):
|
||||
destination_hash = lxmf_bytes[:LXMessage.DESTINATION_LENGTH]
|
||||
source_hash = lxmf_bytes[LXMessage.DESTINATION_LENGTH:2*LXMessage.DESTINATION_LENGTH]
|
||||
signature = lxmf_bytes[2*LXMessage.DESTINATION_LENGTH:2*LXMessage.DESTINATION_LENGTH+LXMessage.SIGNATURE_LENGTH]
|
||||
packed_payload = lxmf_bytes[2*LXMessage.DESTINATION_LENGTH+LXMessage.SIGNATURE_LENGTH:]
|
||||
hashed_part = b"" + destination_hash + source_hash + packed_payload
|
||||
message_hash = RNS.Identity.full_hash(hashed_part)
|
||||
signed_part = b"" + hashed_part + message_hash
|
||||
unpacked_payload = msgpack.unpackb(packed_payload)
|
||||
timestamp = unpacked_payload[0]
|
||||
title_bytes = unpacked_payload[1]
|
||||
content_bytes = unpacked_payload[2]
|
||||
fields = unpacked_payload[3]
|
||||
|
||||
destination_identity = RNS.Identity.recall(destination_hash)
|
||||
if destination_identity != None:
|
||||
destination = RNS.Destination(destination_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "delivery")
|
||||
else:
|
||||
destination = None
|
||||
|
||||
source_identity = RNS.Identity.recall(source_hash)
|
||||
if source_identity != None:
|
||||
source = RNS.Destination(source_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "delivery")
|
||||
else:
|
||||
source = None
|
||||
|
||||
message = LXMessage(
|
||||
destination = destination,
|
||||
source = source,
|
||||
content = "",
|
||||
title = "",
|
||||
fields = fields,
|
||||
destination_hash = destination_hash,
|
||||
source_hash = source_hash)
|
||||
|
||||
message.hash = message_hash
|
||||
message.signature = signature
|
||||
message.incoming = True
|
||||
message.timestamp = timestamp
|
||||
message.packed = lxmf_bytes
|
||||
message.packed_size = len(lxmf_bytes)
|
||||
message.set_title_from_bytes(title_bytes)
|
||||
message.set_content_from_bytes(content_bytes)
|
||||
|
||||
try:
|
||||
if source:
|
||||
if source.identity.validate(signature, signed_part):
|
||||
message.signature_validated = True
|
||||
else:
|
||||
message.signature_validated = False
|
||||
message.unverified_reason = LXMessage.SIGNATURE_INVALID
|
||||
else:
|
||||
signature_validated = False
|
||||
message.unverified_reason = LXMessage.SOURCE_UNKNOWN
|
||||
RNS.log("Unpacked LXMF message signature could not be validated, since source identity is unknown", RNS.LOG_DEBUG)
|
||||
except Exception as e:
|
||||
message.signature_validated = False
|
||||
RNS.log("Error while validating LXMF message signature. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def unpack_from_file(lxmf_file_handle):
|
||||
try:
|
||||
container = msgpack.unpackb(lxmf_file_handle.read())
|
||||
lxm = LXMessage.unpack_from_bytes(container["lxmf_bytes"])
|
||||
|
||||
if "state" in container:
|
||||
lxm.state = container["state"]
|
||||
if "transport_encrypted" in container:
|
||||
lxm.transport_encrypted = container["transport_encrypted"]
|
||||
if "transport_encryption" in container:
|
||||
lxm.transport_encryption = container["transport_encryption"]
|
||||
|
||||
return lxm
|
||||
except Exception as e:
|
||||
RNS.log("Could not unpack LXMessage from file. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
|
||||
class LXMRouter:
|
||||
MAX_DELIVERY_ATTEMPTS = 3
|
||||
PROCESSING_INTERVAL = 5
|
||||
DELIVERY_RETRY_WAIT = 15
|
||||
LINK_MAX_INACTIVITY = 10*60
|
||||
|
||||
def __init__(self):
|
||||
self.pending_inbound = []
|
||||
self.pending_outbound = []
|
||||
self.failed_outbound = []
|
||||
self.direct_links = {}
|
||||
self.delivery_destinations = {}
|
||||
|
||||
self.processing_outbound = False
|
||||
self.processing_inbound = False
|
||||
|
||||
self.identity = RNS.Identity()
|
||||
self.lxmf_query_destination = RNS.Destination(None, RNS.Destination.IN, RNS.Destination.PLAIN, APP_NAME, "query")
|
||||
self.propagation_destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
|
||||
self.__delivery_callback = None
|
||||
|
||||
job_thread = threading.Thread(target=self.jobloop)
|
||||
job_thread.setDaemon(True)
|
||||
job_thread.start()
|
||||
|
||||
def register_delivery_identity(self, identity, display_name = None):
|
||||
delivery_destination = RNS.Destination(identity, RNS.Destination.IN, RNS.Destination.SINGLE, "lxmf", "delivery")
|
||||
delivery_destination.set_packet_callback(self.delivery_packet)
|
||||
delivery_destination.set_link_established_callback(self.delivery_link_established)
|
||||
delivery_destination.display_name = display_name
|
||||
|
||||
if display_name != None:
|
||||
delivery_destination.set_default_app_data(display_name.encode("utf-8"))
|
||||
|
||||
self.delivery_destinations[delivery_destination.hash] = delivery_destination
|
||||
return delivery_destination
|
||||
|
||||
def register_delivery_callback(self, callback):
|
||||
self.__delivery_callback = callback
|
||||
|
||||
def announce(self, destination_hash):
|
||||
if destination_hash in self.delivery_destinations:
|
||||
delivery_destination = self.delivery_destinations[destination_hash]
|
||||
delivery_destination.announce(delivery_destination.display_name.encode("utf-8"))
|
||||
|
||||
def handle_outbound(self, lxmessage):
|
||||
lxmessage.state = LXMessage.OUTBOUND
|
||||
if not lxmessage.packed:
|
||||
lxmessage.pack()
|
||||
|
||||
lxmessage.determine_transport_encryption()
|
||||
|
||||
while self.processing_outbound:
|
||||
time.sleep(0.1)
|
||||
|
||||
self.pending_outbound.append(lxmessage)
|
||||
self.process_outbound()
|
||||
|
||||
def lxmf_delivery(self, lxmf_data, destination_type = None):
|
||||
try:
|
||||
message = LXMessage.unpack_from_bytes(lxmf_data)
|
||||
|
||||
if RNS.Reticulum.should_allow_unencrypted():
|
||||
message.transport_encrypted = False
|
||||
message.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
|
||||
else:
|
||||
if destination_type == RNS.Destination.SINGLE:
|
||||
message.transport_encrypted = True
|
||||
message.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_RSA
|
||||
elif destination_type == RNS.Destination.GROUP:
|
||||
message.transport_encrypted = True
|
||||
message.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_AES
|
||||
elif destination_type == RNS.Destination.LINK:
|
||||
message.transport_encrypted = True
|
||||
message.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
|
||||
else:
|
||||
message.transport_encrypted = False
|
||||
message.transport_encryption = None
|
||||
|
||||
if self.__delivery_callback != None:
|
||||
self.__delivery_callback(message)
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not assemble LXMF message from received data", RNS.LOG_NOTICE)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
|
||||
return False
|
||||
|
||||
|
||||
def delivery_packet(self, data, packet):
|
||||
try:
|
||||
if packet.destination.type != RNS.Destination.LINK:
|
||||
lxmf_data = b""
|
||||
lxmf_data += packet.destination.hash
|
||||
lxmf_data += data
|
||||
else:
|
||||
lxmf_data = data
|
||||
|
||||
if self.lxmf_delivery(lxmf_data, packet.destination.type):
|
||||
packet.prove()
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Exception occurred while parsing incoming LXMF data.", RNS.LOG_ERROR)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
def delivery_link_established(self, link):
|
||||
link.set_packet_callback(self.delivery_packet)
|
||||
link.set_resource_strategy(RNS.Link.ACCEPT_ALL)
|
||||
link.set_resource_started_callback(self.resource_transfer_began)
|
||||
link.set_resource_concluded_callback(self.resource_transfer_concluded)
|
||||
|
||||
def delivery_link_closed(self, link):
|
||||
pass
|
||||
|
||||
def resource_transfer_began(self, resource):
|
||||
RNS.log("Transfer began for resource "+str(resource), RNS.LOG_DEBUG)
|
||||
|
||||
def resource_transfer_concluded(self, resource):
|
||||
RNS.log("Transfer concluded for resource "+str(resource), RNS.LOG_DEBUG)
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
self.lxmf_delivery(resource.data.read(), resource.link.type)
|
||||
|
||||
def jobloop(self):
|
||||
while (True):
|
||||
# TODO: Improve this to scheduling, so manual
|
||||
# triggers can delay next run
|
||||
self.jobs()
|
||||
time.sleep(LXMRouter.PROCESSING_INTERVAL)
|
||||
|
||||
def jobs(self):
|
||||
self.process_outbound()
|
||||
self.clean_links()
|
||||
|
||||
def clean_links(self):
|
||||
closed_links = []
|
||||
for link_hash in self.direct_links:
|
||||
link = self.direct_links[link_hash]
|
||||
inactive_time = link.inactive_for()
|
||||
|
||||
if inactive_time > LXMRouter.LINK_MAX_INACTIVITY:
|
||||
link.teardown()
|
||||
closed_links.append(link_hash)
|
||||
|
||||
for link_hash in closed_links:
|
||||
cleaned_link = self.direct_links.pop(link_hash)
|
||||
RNS.log("Cleaned link "+str(cleaned_link), RNS.LOG_DEBUG)
|
||||
|
||||
def fail_message(self, lxmessage):
|
||||
RNS.log(str(lxmessage)+" failed to send", RNS.LOG_DEBUG)
|
||||
|
||||
self.pending_outbound.remove(lxmessage)
|
||||
self.failed_outbound.append(lxmessage)
|
||||
|
||||
lxmessage.state = LXMessage.FAILED
|
||||
if lxmessage.failed_callback != None:
|
||||
lxmessage.failed_callback(lxmessage)
|
||||
|
||||
def process_outbound(self, sender = None):
|
||||
if self.processing_outbound:
|
||||
return
|
||||
|
||||
for lxmessage in self.pending_outbound:
|
||||
if lxmessage.state == LXMessage.DELIVERED:
|
||||
RNS.log("Delivery has occurred for "+str(lxmessage)+", removing from outbound queue", RNS.LOG_DEBUG)
|
||||
self.pending_outbound.remove(lxmessage)
|
||||
else:
|
||||
RNS.log("Starting outbound processing for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
# Outbound handling for opportunistic messages
|
||||
if lxmessage.method == LXMessage.OPPORTUNISTIC:
|
||||
if lxmessage.delivery_attempts <= LXMRouter.MAX_DELIVERY_ATTEMPTS:
|
||||
if not hasattr(lxmessage, "next_delivery_attempt") or time.time() > lxmessage.next_delivery_attempt:
|
||||
lxmessage.delivery_attempts += 1
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
|
||||
RNS.log("Opportunistic delivery attempt "+str(lxmessage.delivery_attempts)+" for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
lxmessage.send()
|
||||
else:
|
||||
RNS.log("Max delivery attempts reached for oppertunistic "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
self.fail_message(lxmessage)
|
||||
|
||||
# Outbound handling for messages transferred
|
||||
# over a direct link to the final recipient
|
||||
elif lxmessage.method == LXMessage.DIRECT:
|
||||
if lxmessage.delivery_attempts <= LXMRouter.MAX_DELIVERY_ATTEMPTS:
|
||||
delivery_destination_hash = lxmessage.get_destination().hash
|
||||
|
||||
if delivery_destination_hash in self.direct_links:
|
||||
# A link already exists, so we'll try to use it
|
||||
# to deliver the message
|
||||
direct_link = self.direct_links[delivery_destination_hash]
|
||||
if direct_link.status == RNS.Link.ACTIVE:
|
||||
if lxmessage.state != LXMessage.SENDING:
|
||||
RNS.log("Starting transfer of "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
lxmessage.set_delivery_destination(direct_link)
|
||||
lxmessage.send()
|
||||
else:
|
||||
RNS.log("The transfer of "+str(lxmessage)+" is in progress ("+str(round(lxmessage.progress*100, 1))+"%)", RNS.LOG_DEBUG)
|
||||
elif direct_link.status == RNS.Link.CLOSED:
|
||||
RNS.log("The link to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+" was closed", RNS.LOG_DEBUG)
|
||||
lxmessage.set_delivery_destination(None)
|
||||
self.direct_links.pop(delivery_destination_hash)
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
|
||||
else:
|
||||
# Simply wait for the link to become
|
||||
# active or close
|
||||
RNS.log("The link to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+" is pending, waiting for link to become active", RNS.LOG_DEBUG)
|
||||
else:
|
||||
# No link exists, so we'll try to establish one, but
|
||||
# only if we've never tried before, or the retry wait
|
||||
# period has elapsed.
|
||||
if not hasattr(lxmessage, "next_delivery_attempt") or time.time() > lxmessage.next_delivery_attempt:
|
||||
lxmessage.delivery_attempts += 1
|
||||
lxmessage.next_delivery_attempt = time.time() + LXMRouter.DELIVERY_RETRY_WAIT
|
||||
if lxmessage.delivery_attempts < LXMRouter.MAX_DELIVERY_ATTEMPTS:
|
||||
if RNS.Transport.has_path(lxmessage.get_destination().hash):
|
||||
RNS.log("Establishing link to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+" for delivery attempt "+str(lxmessage.delivery_attempts)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
delivery_link = RNS.Link(lxmessage.get_destination())
|
||||
delivery_link.set_link_established_callback(self.process_outbound)
|
||||
self.direct_links[delivery_destination_hash] = delivery_link
|
||||
else:
|
||||
RNS.log("No path known for delivery attempt "+str(lxmessage.delivery_attempts)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash)+". Requesting path...", RNS.LOG_DEBUG)
|
||||
RNS.Transport.request_path(lxmessage.get_destination().hash)
|
||||
else:
|
||||
RNS.log("Max delivery attempts reached for direct "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
self.fail_message(lxmessage)
|
||||
|
||||
# Outbound handling for messages transported via
|
||||
# propagation to a LXMF router network.
|
||||
elif lxmessage.method == LXMessage.PROPAGATED:
|
||||
RNS.log("Attempting propagated delivery for "+str(lxmessage)+" to "+RNS.prettyhexrep(lxmessage.get_destination().hash), RNS.LOG_DEBUG)
|
||||
raise NotImplementedError("LXMF propagation is not implemented yet")
|
||||
APP_NAME = "lxmf"
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
import os
|
||||
import time
|
||||
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
from .LXMF import APP_NAME
|
||||
|
||||
class LXMPeer:
|
||||
OFFER_REQUEST_PATH = "/offer"
|
||||
MESSAGE_GET_PATH = "/get"
|
||||
|
||||
IDLE = 0x00
|
||||
LINK_ESTABLISHING = 0x01
|
||||
LINK_READY = 0x02
|
||||
REQUEST_SENT = 0x03
|
||||
RESPONSE_RECEIVED = 0x04
|
||||
RESOURCE_TRANSFERRING = 0x05
|
||||
|
||||
ERROR_NO_IDENTITY = 0xf0
|
||||
ERROR_NO_ACCESS = 0xf1
|
||||
|
||||
# Maximum amount of time a peer can
|
||||
# be unreachable before it is removed
|
||||
MAX_UNREACHABLE = 4*24*60*60
|
||||
|
||||
@staticmethod
|
||||
def from_bytes(peer_bytes, router):
|
||||
dictionary = msgpack.unpackb(peer_bytes)
|
||||
|
||||
peer = LXMPeer(router, dictionary["destination_hash"])
|
||||
peer.peering_timebase = dictionary["peering_timebase"]
|
||||
peer.alive = dictionary["alive"]
|
||||
peer.last_heard = dictionary["last_heard"]
|
||||
|
||||
for transient_id in dictionary["handled_ids"]:
|
||||
if transient_id in router.propagation_entries:
|
||||
peer.handled_messages[transient_id] = router.propagation_entries[transient_id]
|
||||
|
||||
for transient_id in dictionary["unhandled_ids"]:
|
||||
if transient_id in router.propagation_entries:
|
||||
peer.unhandled_messages[transient_id] = router.propagation_entries[transient_id]
|
||||
|
||||
return peer
|
||||
|
||||
def to_bytes(self):
|
||||
dictionary = {}
|
||||
dictionary["peering_timebase"] = self.peering_timebase
|
||||
dictionary["alive"] = self.alive
|
||||
dictionary["last_heard"] = self.last_heard
|
||||
dictionary["destination_hash"] = self.destination_hash
|
||||
|
||||
handled_ids = []
|
||||
for transient_id in self.handled_messages:
|
||||
handled_ids.append(transient_id)
|
||||
|
||||
unhandled_ids = []
|
||||
for transient_id in self.unhandled_messages:
|
||||
unhandled_ids.append(transient_id)
|
||||
|
||||
dictionary["handled_ids"] = handled_ids
|
||||
dictionary["unhandled_ids"] = unhandled_ids
|
||||
|
||||
return msgpack.packb(dictionary)
|
||||
|
||||
def __init__(self, router, destination_hash):
|
||||
self.alive = False
|
||||
self.last_heard = 0
|
||||
self.peering_timebase = 0
|
||||
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
self.unhandled_messages = {}
|
||||
self.handled_messages = {}
|
||||
|
||||
self.router = router
|
||||
self.destination_hash = destination_hash
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
|
||||
def sync(self):
|
||||
RNS.log("Initiating LXMF Propagation Node sync with peer "+RNS.prettyhexrep(self.destination_hash), RNS.LOG_DEBUG)
|
||||
|
||||
if not RNS.Transport.has_path(self.destination_hash):
|
||||
RNS.log("No path to peer "+RNS.prettyhexrep(self.destination_hash)+" exists, requesting...", RNS.LOG_DEBUG)
|
||||
RNS.Transport.request_path(self.destination_hash)
|
||||
RNS.log("Path requested, retrying sync later", RNS.LOG_DEBUG)
|
||||
|
||||
else:
|
||||
if self.identity == None:
|
||||
self.identity = RNS.Identity.recall(destination_hash)
|
||||
self.destination = RNS.Destination(self.identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "propagation")
|
||||
|
||||
if self.identity != None:
|
||||
if len(self.unhandled_messages) > 0:
|
||||
if self.state == LXMPeer.IDLE:
|
||||
RNS.log("Establishing link for sync to peer "+RNS.prettyhexrep(self.destination_hash)+"...", RNS.LOG_DEBUG)
|
||||
self.link = RNS.Link(self.destination, established_callback = self.link_established, closed_callback = self.link_closed)
|
||||
self.state = LXMPeer.LINK_ESTABLISHING
|
||||
|
||||
else:
|
||||
if self.state == LXMPeer.LINK_READY:
|
||||
self.alive = True
|
||||
self.last_heard = time.time()
|
||||
|
||||
RNS.log("Synchronisation link to peer "+RNS.prettyhexrep(self.destination_hash)+" established, preparing request...", RNS.LOG_DEBUG)
|
||||
unhandled_ids = []
|
||||
purged_ids = []
|
||||
for transient_id in self.unhandled_messages:
|
||||
if transient_id in self.router.propagation_entries:
|
||||
unhandled_ids.append(transient_id)
|
||||
else:
|
||||
purged_ids.append(transient_id)
|
||||
|
||||
for transient_id in purged_ids:
|
||||
RNS.log("Dropping unhandled message "+RNS.prettyhexrep(transient_id)+" for peer "+RNS.prettyhexrep(self.destination_hash)+" since it no longer exists in the message store.", RNS.LOG_DEBUG)
|
||||
self.unhandled_messages.pop(transient_id)
|
||||
|
||||
RNS.log("Sending sync request to peer "+str(self.destination), RNS.LOG_DEBUG)
|
||||
self.link.request(LXMPeer.OFFER_REQUEST_PATH, unhandled_ids, response_callback=self.offer_response, failed_callback=self.request_failed)
|
||||
self.state = LXMPeer.REQUEST_SENT
|
||||
else:
|
||||
RNS.log("Could not request sync to peer "+RNS.prettyhexrep(self.destination_hash)+" since its identity could not be recalled.", RNS.LOG_ERROR)
|
||||
|
||||
def request_failed(self, request_receipt):
|
||||
RNS.log("Sync request to peer "+str(self.destination)+" failed", RNS.LOG_DEBUG)
|
||||
if self.link != None:
|
||||
self.link.teardown()
|
||||
else:
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
def offer_response(self, request_receipt):
|
||||
try:
|
||||
self.state = LXMPeer.RESPONSE_RECEIVED
|
||||
response = request_receipt.response
|
||||
|
||||
wanted_messages = []
|
||||
wanted_message_ids = []
|
||||
|
||||
if response == LXMPeer.ERROR_NO_IDENTITY:
|
||||
if self.link != None:
|
||||
RNS.log("Remote peer indicated that no identification was received, retrying...", RNS.LOG_DEBUG)
|
||||
self.link.indentify()
|
||||
self.state = LXMPeer.LINK_READY
|
||||
self.sync()
|
||||
|
||||
elif response == False:
|
||||
# Peer already has all advertised messages
|
||||
for transient_id in self.unhandled_messages:
|
||||
message_entry = self.unhandled_messages[transient_id]
|
||||
self.handled_messages[transient_id] = message_entry
|
||||
|
||||
self.unhandled_messages = {}
|
||||
|
||||
elif response == True:
|
||||
# Peer wants all advertised messages
|
||||
for transient_id in self.unhandled_messages:
|
||||
wanted_messages.append(self.unhandled_messages[transient_id])
|
||||
wanted_message_ids.append(transient_id)
|
||||
|
||||
else:
|
||||
# Peer wants some advertised messages
|
||||
peer_had_messages = []
|
||||
for transient_id in self.unhandled_messages.copy():
|
||||
# If the peer did not want the message, it has
|
||||
# already received it from another peer.
|
||||
if not transient_id in response:
|
||||
message_entry = self.unhandled_messages.pop(transient_id)
|
||||
self.handled_messages[transient_id] = message_entry
|
||||
|
||||
for transient_id in response:
|
||||
wanted_messages.append(self.unhandled_messages[transient_id])
|
||||
wanted_message_ids.append(transient_id)
|
||||
|
||||
if len(wanted_messages) > 0:
|
||||
RNS.log("Peer wanted "+str(len(wanted_messages))+" of the available messages", RNS.LOG_DEBUG)
|
||||
|
||||
lxm_list = []
|
||||
|
||||
for message_entry in wanted_messages:
|
||||
file_path = message_entry[1]
|
||||
if os.path.isfile(file_path):
|
||||
file = open(file_path, "rb")
|
||||
lxmf_data = file.read()
|
||||
file.close()
|
||||
lxm_list.append(lxmf_data)
|
||||
|
||||
data = msgpack.packb([time.time(), lxm_list])
|
||||
resource = RNS.Resource(data, self.link, callback = self.resource_concluded)
|
||||
resource.transferred_messages = wanted_message_ids
|
||||
self.state = LXMPeer.RESOURCE_TRANSFERRING
|
||||
else:
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while handling offer response from peer "+str(self.destination), RNS.LOG_ERROR)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
if self.link != None:
|
||||
self.link.teardown()
|
||||
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
|
||||
def resource_concluded(self, resource):
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
for transient_id in resource.transferred_messages:
|
||||
message = self.unhandled_messages.pop(transient_id)
|
||||
self.handled_messages[transient_id] = message
|
||||
self.state = LXMPeer.IDLE
|
||||
self.link.teardown()
|
||||
RNS.log("Sync to peer "+RNS.prettyhexrep(self.destination_hash)+" completed", RNS.LOG_DEBUG)
|
||||
self.alive = True
|
||||
self.last_heard = time.time()
|
||||
else:
|
||||
RNS.log("Resource transfer for LXMF peer sync failed to "+str(self.destination), RNS.LOG_DEBUG)
|
||||
if self.link != None:
|
||||
self.link.teardown()
|
||||
else:
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
|
||||
|
||||
def link_established(self, link):
|
||||
self.link.identify(self.router.identity)
|
||||
self.state = LXMPeer.LINK_READY
|
||||
self.sync()
|
||||
|
||||
def link_closed(self, link):
|
||||
self.link = None
|
||||
self.state = LXMPeer.IDLE
|
||||
|
||||
def handle_message(self, transient_id):
|
||||
if not transient_id in self.handled_messages and not transient_id in self.unhandled_messages:
|
||||
# TODO: Remove at some point
|
||||
RNS.log("The message "+RNS.prettyhexrep(transient_id)+" was added to distribution queue for "+RNS.prettyhexrep(self.destination_hash), RNS.LOG_EXTREME)
|
||||
self.unhandled_messages[transient_id] = self.router.propagation_entries[transient_id]
|
||||
|
||||
def __str__(self):
|
||||
if self.destination_hash:
|
||||
return RNS.prettyhexrep(self.destination_hash)
|
||||
else:
|
||||
return "<Unknown>"
|
||||
+1275
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,618 @@
|
||||
import RNS
|
||||
import RNS.vendor.umsgpack as msgpack
|
||||
|
||||
import time
|
||||
import base64
|
||||
|
||||
from .LXMF import APP_NAME
|
||||
|
||||
class LXMessage:
|
||||
DRAFT = 0x00
|
||||
OUTBOUND = 0x01
|
||||
SENDING = 0x02
|
||||
SENT = 0x04
|
||||
DELIVERED = 0x08
|
||||
FAILED = 0xFF
|
||||
states = [DRAFT, OUTBOUND, SENDING, SENT, DELIVERED, FAILED]
|
||||
|
||||
UNKNOWN = 0x00
|
||||
PACKET = 0x01
|
||||
RESOURCE = 0x02
|
||||
representations = [UNKNOWN, PACKET, RESOURCE]
|
||||
|
||||
OPPORTUNISTIC = 0x01
|
||||
DIRECT = 0x02
|
||||
PROPAGATED = 0x03
|
||||
PAPER = 0x05
|
||||
valid_methods = [OPPORTUNISTIC, DIRECT, PROPAGATED, PAPER]
|
||||
|
||||
SOURCE_UNKNOWN = 0x01
|
||||
SIGNATURE_INVALID = 0x02
|
||||
unverified_reasons = [SOURCE_UNKNOWN, SIGNATURE_INVALID]
|
||||
|
||||
DESTINATION_LENGTH = RNS.Identity.TRUNCATED_HASHLENGTH//8
|
||||
SIGNATURE_LENGTH = RNS.Identity.SIGLENGTH//8
|
||||
|
||||
# LXMF overhead is 99 bytes per message:
|
||||
# 10 bytes for destination hash
|
||||
# 10 bytes for source hash
|
||||
# 64 bytes for Ed25519 signature
|
||||
# 8 bytes for timestamp
|
||||
# 7 bytes for msgpack structure
|
||||
LXMF_OVERHEAD = 2*DESTINATION_LENGTH + SIGNATURE_LENGTH + 8 + 7
|
||||
|
||||
# With an MTU of 500, the maximum amount of data
|
||||
# we can send in a single encrypted packet is
|
||||
# 383 bytes.
|
||||
ENCRYPTED_PACKET_MDU = RNS.Packet.ENCRYPTED_MDU
|
||||
|
||||
# The max content length we can fit in LXMF message
|
||||
# inside a single RNS packet is the encrypted MDU, minus
|
||||
# the LXMF overhead. We can optimise a bit though, by
|
||||
# inferring the destination hash from the destination
|
||||
# field of the packet, therefore we also add the length
|
||||
# of a destination hash to the calculation. With default
|
||||
# RNS and LXMF parameters, the largest single-packet
|
||||
# LXMF message we can send is 294 bytes. If a message
|
||||
# is larger than that, a Reticulum link will be used.
|
||||
ENCRYPTED_PACKET_MAX_CONTENT = ENCRYPTED_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
|
||||
|
||||
# Links can carry a larger MDU, due to less overhead per
|
||||
# packet. The link MDU with default Reticulum parameters
|
||||
# is 431 bytes.
|
||||
LINK_PACKET_MDU = RNS.Link.MDU
|
||||
|
||||
# Which means that we can deliver single-packet LXMF
|
||||
# messages with content of up to 332 bytes over a link.
|
||||
# If a message is larger than that, LXMF will sequence
|
||||
# and transfer it as a RNS resource over the link instead.
|
||||
LINK_PACKET_MAX_CONTENT = LINK_PACKET_MDU - LXMF_OVERHEAD
|
||||
|
||||
# For plain packets without encryption, we can
|
||||
# fit up to 388 bytes of content.
|
||||
PLAIN_PACKET_MDU = RNS.Packet.PLAIN_MDU
|
||||
PLAIN_PACKET_MAX_CONTENT = PLAIN_PACKET_MDU - LXMF_OVERHEAD + DESTINATION_LENGTH
|
||||
|
||||
# Descriptive strings regarding transport encryption
|
||||
ENCRYPTION_DESCRIPTION_AES = "AES-128"
|
||||
ENCRYPTION_DESCRIPTION_EC = "Curve25519"
|
||||
ENCRYPTION_DESCRIPTION_UNENCRYPTED = "Unencrypted"
|
||||
|
||||
# Constants for QR/URI encoding LXMs
|
||||
URI_SCHEMA = "lxm"
|
||||
QR_ERROR_CORRECTION = "ERROR_CORRECT_L"
|
||||
QR_MAX_STORAGE = 2953
|
||||
PAPER_MDU = ((QR_MAX_STORAGE-(len(URI_SCHEMA)+len("://")))*6)//8
|
||||
|
||||
def __str__(self):
|
||||
if self.hash != None:
|
||||
return "<LXMessage "+RNS.hexrep(self.hash, delimit=False)+">"
|
||||
else:
|
||||
return "<LXMessage>"
|
||||
|
||||
def __init__(self, destination, source, content = "", title = "", fields = None, desired_method = None, destination_hash = None, source_hash = None):
|
||||
if isinstance(destination, RNS.Destination) or destination == None:
|
||||
self.__destination = destination
|
||||
if destination != None:
|
||||
self.destination_hash = destination.hash
|
||||
else:
|
||||
self.destination_hash = destination_hash
|
||||
else:
|
||||
raise ValueError("LXMessage initialised with invalid destination")
|
||||
|
||||
if isinstance(source, RNS.Destination) or source == None:
|
||||
self.__source = source
|
||||
if source != None:
|
||||
self.source_hash = source.hash
|
||||
else:
|
||||
self.source_hash = source_hash
|
||||
else:
|
||||
raise ValueError("LXMessage initialised with invalid source")
|
||||
|
||||
self.set_title_from_string(title)
|
||||
self.set_content_from_string(content)
|
||||
|
||||
self.set_fields(fields)
|
||||
|
||||
self.payload = None
|
||||
self.timestamp = None
|
||||
self.signature = None
|
||||
self.hash = None
|
||||
self.packed = None
|
||||
self.progress = None
|
||||
self.state = LXMessage.DRAFT
|
||||
self.method = LXMessage.UNKNOWN
|
||||
|
||||
self.propagation_packed = None
|
||||
self.paper_packed = None
|
||||
|
||||
self.incoming = False
|
||||
self.signature_validated = False
|
||||
self.unverified_reason = None
|
||||
|
||||
self.representation = LXMessage.UNKNOWN
|
||||
self.desired_method = desired_method
|
||||
self.delivery_attempts = 0
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = None
|
||||
self.packet_representation = None
|
||||
self.resource_representation = None
|
||||
self.__delivery_destination = None
|
||||
self.__delivery_callback = None
|
||||
self.failed_callback = None
|
||||
|
||||
def set_title_from_string(self, title_string):
|
||||
self.title = title_string.encode("utf-8")
|
||||
|
||||
def set_title_from_bytes(self, title_bytes):
|
||||
self.title = title_bytes
|
||||
|
||||
def title_as_string(self):
|
||||
return self.title.decode("utf-8")
|
||||
|
||||
def set_content_from_string(self, content_string):
|
||||
self.content = content_string.encode("utf-8")
|
||||
|
||||
def set_content_from_bytes(self, content_bytes):
|
||||
self.content = content_bytes
|
||||
|
||||
def content_as_string(self):
|
||||
return self.content.decode("utf-8")
|
||||
|
||||
def set_fields(self, fields):
|
||||
if isinstance(fields, dict) or fields == None:
|
||||
self.fields = fields
|
||||
else:
|
||||
raise ValueError("LXMessage property \"fields\" can only be dict or None")
|
||||
|
||||
def get_fields(self):
|
||||
return self.__fields
|
||||
|
||||
def set_destination(self, destination):
|
||||
if self.destination == None:
|
||||
if isinstance(destination, RNS.Destination):
|
||||
self.__destination = destination
|
||||
else:
|
||||
raise ValueError("Invalid destination set on LXMessage")
|
||||
else:
|
||||
raise ValueError("Cannot reassign destination on LXMessage")
|
||||
|
||||
def get_destination(self):
|
||||
return self.__destination
|
||||
|
||||
def set_source(self, source):
|
||||
if self.source == None:
|
||||
if isinstance(source, RNS.Destination):
|
||||
self.__source = source
|
||||
else:
|
||||
raise ValueError("Invalid source set on LXMessage")
|
||||
else:
|
||||
raise ValueError("Cannot reassign source on LXMessage")
|
||||
|
||||
def get_source(self):
|
||||
return self.__source
|
||||
|
||||
def set_delivery_destination(self, delivery_destination):
|
||||
self.__delivery_destination = delivery_destination
|
||||
|
||||
def register_delivery_callback(self, callback):
|
||||
self.__delivery_callback = callback
|
||||
|
||||
def register_failed_callback(self, callback):
|
||||
self.failed_callback = callback
|
||||
|
||||
def pack(self):
|
||||
if not self.packed:
|
||||
if self.timestamp == None:
|
||||
self.timestamp = time.time()
|
||||
|
||||
self.propagation_packed = None
|
||||
self.paper_packed = None
|
||||
|
||||
self.payload = [self.timestamp, self.title, self.content, self.fields]
|
||||
|
||||
hashed_part = b""
|
||||
hashed_part += self.__destination.hash
|
||||
hashed_part += self.__source.hash
|
||||
hashed_part += msgpack.packb(self.payload)
|
||||
self.hash = RNS.Identity.full_hash(hashed_part)
|
||||
self.message_id = self.hash
|
||||
|
||||
signed_part = b""
|
||||
signed_part += hashed_part
|
||||
signed_part += self.hash
|
||||
self.signature = self.__source.sign(signed_part)
|
||||
self.signature_validated = True
|
||||
|
||||
self.packed = b""
|
||||
self.packed += self.__destination.hash
|
||||
self.packed += self.__source.hash
|
||||
self.packed += self.signature
|
||||
packed_payload = msgpack.packb(self.payload)
|
||||
self.packed += packed_payload
|
||||
self.packed_size = len(self.packed)
|
||||
content_size = len(packed_payload)
|
||||
|
||||
# If no desired delivery method has been defined,
|
||||
# one will be chosen according to these rules:
|
||||
if self.desired_method == None:
|
||||
self.desired_method = LXMessage.DIRECT
|
||||
# TODO: Expand rules to something more intelligent
|
||||
|
||||
if self.desired_method == LXMessage.OPPORTUNISTIC:
|
||||
if self.__destination.type == RNS.Destination.SINGLE:
|
||||
single_packet_content_limit = LXMessage.ENCRYPTED_PACKET_MAX_CONTENT
|
||||
elif self.__destination.type == RNS.Destination.PLAIN:
|
||||
single_packet_content_limit = LXMessage.PLAIN_PACKET_MAX_CONTENT
|
||||
|
||||
if content_size > single_packet_content_limit:
|
||||
raise TypeError("LXMessage desired opportunistic delivery method, but content exceeds single-packet size.")
|
||||
else:
|
||||
self.method = LXMessage.OPPORTUNISTIC
|
||||
self.representation = LXMessage.PACKET
|
||||
self.__delivery_destination = self.__destination
|
||||
|
||||
elif self.desired_method == LXMessage.DIRECT:
|
||||
single_packet_content_limit = LXMessage.LINK_PACKET_MAX_CONTENT
|
||||
if content_size <= single_packet_content_limit:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.PACKET
|
||||
else:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.RESOURCE
|
||||
|
||||
elif self.desired_method == LXMessage.PROPAGATED:
|
||||
single_packet_content_limit = LXMessage.LINK_PACKET_MAX_CONTENT
|
||||
|
||||
encrypted_data = self.__destination.encrypt(self.packed[LXMessage.DESTINATION_LENGTH:])
|
||||
self.propagation_packed = msgpack.packb([time.time(), [self.packed[:LXMessage.DESTINATION_LENGTH]+encrypted_data]])
|
||||
|
||||
content_size = len(self.propagation_packed)
|
||||
if content_size <= single_packet_content_limit:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.PACKET
|
||||
else:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.RESOURCE
|
||||
|
||||
elif self.desired_method == LXMessage.PAPER:
|
||||
paper_content_limit = LXMessage.PAPER_MDU
|
||||
|
||||
encrypted_data = self.__destination.encrypt(self.packed[LXMessage.DESTINATION_LENGTH:])
|
||||
self.paper_packed = self.packed[:LXMessage.DESTINATION_LENGTH]+encrypted_data
|
||||
|
||||
content_size = len(self.paper_packed)
|
||||
if content_size <= paper_content_limit:
|
||||
self.method = self.desired_method
|
||||
self.representation = LXMessage.PAPER
|
||||
else:
|
||||
raise TypeError("LXMessage desired paper delivery method, but content exceeds paper message maximum size.")
|
||||
|
||||
else:
|
||||
raise ValueError("Attempt to re-pack LXMessage "+str(self)+" that was already packed")
|
||||
|
||||
def send(self):
|
||||
self.determine_transport_encryption()
|
||||
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
self.__as_packet().send().set_delivery_callback(self.__mark_delivered)
|
||||
self.state = LXMessage.SENT
|
||||
|
||||
elif self.method == LXMessage.DIRECT:
|
||||
self.state = LXMessage.SENDING
|
||||
|
||||
if self.representation == LXMessage.PACKET:
|
||||
receipt = self.__as_packet().send()
|
||||
if receipt:
|
||||
receipt.set_delivery_callback(self.__mark_delivered)
|
||||
receipt.set_timeout_callback(self.__link_packet_timed_out)
|
||||
else:
|
||||
if self.__delivery_destination:
|
||||
self.__delivery_destination.teardown()
|
||||
|
||||
elif self.representation == LXMessage.RESOURCE:
|
||||
self.resource_representation = self.__as_resource()
|
||||
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
self.state = LXMessage.SENDING
|
||||
|
||||
if self.representation == LXMessage.PACKET:
|
||||
receipt = self.__as_packet().send()
|
||||
if receipt:
|
||||
receipt.set_delivery_callback(self.__mark_propagated)
|
||||
receipt.set_timeout_callback(self.__link_packet_timed_out)
|
||||
else:
|
||||
self.__delivery_destination.teardown()
|
||||
|
||||
elif self.representation == LXMessage.RESOURCE:
|
||||
self.resource_representation = self.__as_resource()
|
||||
|
||||
|
||||
def determine_transport_encryption(self):
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
if self.__destination.type == RNS.Destination.SINGLE:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
|
||||
elif self.__destination.type == RNS.Destination.GROUP:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_AES
|
||||
else:
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
|
||||
elif self.method == LXMessage.DIRECT:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
if self.__destination.type == RNS.Destination.SINGLE:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
|
||||
elif self.__destination.type == RNS.Destination.GROUP:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_AES
|
||||
else:
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
|
||||
elif self.method == LXMessage.PAPER:
|
||||
if self.__destination.type == RNS.Destination.SINGLE:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_EC
|
||||
elif self.__destination.type == RNS.Destination.GROUP:
|
||||
self.transport_encrypted = True
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_AES
|
||||
else:
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
|
||||
else:
|
||||
self.transport_encrypted = False
|
||||
self.transport_encryption = LXMessage.ENCRYPTION_DESCRIPTION_UNENCRYPTED
|
||||
|
||||
def __mark_delivered(self, receipt = None):
|
||||
RNS.log("Received delivery notification for "+str(self), RNS.LOG_DEBUG)
|
||||
self.state = LXMessage.DELIVERED
|
||||
|
||||
if self.__delivery_callback != None and callable(self.__delivery_callback):
|
||||
try:
|
||||
self.__delivery_callback(self)
|
||||
except Exception as e:
|
||||
RNS.log("An error occurred in the external delivery callback for "+str(message), RNS.LOG_ERROR)
|
||||
|
||||
def __mark_propagated(self, receipt = None):
|
||||
RNS.log("Received propagation success notification for "+str(self), RNS.LOG_DEBUG)
|
||||
self.state = LXMessage.SENT
|
||||
|
||||
if self.__delivery_callback != None and callable(self.__delivery_callback):
|
||||
try:
|
||||
self.__delivery_callback(self)
|
||||
except Exception as e:
|
||||
RNS.log("An error occurred in the external delivery callback for "+str(message), RNS.LOG_ERROR)
|
||||
|
||||
def __mark_paper_generated(self, receipt = None):
|
||||
RNS.log("Paper message generation succeeded for "+str(self), RNS.LOG_DEBUG)
|
||||
self.state = LXMessage.PAPER
|
||||
|
||||
if self.__delivery_callback != None and callable(self.__delivery_callback):
|
||||
try:
|
||||
self.__delivery_callback(self)
|
||||
except Exception as e:
|
||||
RNS.log("An error occurred in the external delivery callback for "+str(message), RNS.LOG_ERROR)
|
||||
|
||||
def __resource_concluded(self, resource):
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
self.__mark_delivered()
|
||||
else:
|
||||
resource.link.teardown()
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
def __propagation_resource_concluded(self, resource):
|
||||
if resource.status == RNS.Resource.COMPLETE:
|
||||
self.__mark_propagated()
|
||||
else:
|
||||
resource.link.teardown()
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
def __link_packet_timed_out(self, packet_receipt):
|
||||
if packet_receipt:
|
||||
packet_receipt.destination.teardown()
|
||||
|
||||
self.state = LXMessage.OUTBOUND
|
||||
|
||||
|
||||
def __update_transfer_progress(self, resource):
|
||||
self.progress = resource.get_progress()
|
||||
|
||||
def __as_packet(self):
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
if not self.__delivery_destination:
|
||||
raise ValueError("Can't synthesize packet for LXMF message before delivery destination is known")
|
||||
|
||||
if self.method == LXMessage.OPPORTUNISTIC:
|
||||
return RNS.Packet(self.__delivery_destination, self.packed[LXMessage.DESTINATION_LENGTH:])
|
||||
elif self.method == LXMessage.DIRECT:
|
||||
return RNS.Packet(self.__delivery_destination, self.packed)
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
return RNS.Packet(self.__delivery_destination, self.propagation_packed)
|
||||
|
||||
def __as_resource(self):
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
if not self.__delivery_destination:
|
||||
raise ValueError("Can't synthesize resource for LXMF message before delivery destination is known")
|
||||
|
||||
if not self.__delivery_destination.type == RNS.Destination.LINK:
|
||||
raise TypeError("Tried to synthesize resource for LXMF message on a delivery destination that was not a link")
|
||||
|
||||
if not self.__delivery_destination.status == RNS.Link.ACTIVE:
|
||||
raise ConnectionError("Tried to synthesize resource for LXMF message on a link that was not active")
|
||||
|
||||
self.progress = 0.0
|
||||
|
||||
if self.method == LXMessage.DIRECT:
|
||||
return RNS.Resource(self.packed, self.__delivery_destination, callback = self.__resource_concluded, progress_callback = self.__update_transfer_progress)
|
||||
elif self.method == LXMessage.PROPAGATED:
|
||||
return RNS.Resource(self.propagation_packed, self.__delivery_destination, callback = self.__propagation_resource_concluded, progress_callback = self.__update_transfer_progress)
|
||||
else:
|
||||
return None
|
||||
|
||||
def packed_container(self):
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
container = {
|
||||
"state": self.state,
|
||||
"lxmf_bytes": self.packed,
|
||||
"transport_encrypted": self.transport_encrypted,
|
||||
"transport_encryption": self.transport_encryption,
|
||||
"method": self.method
|
||||
}
|
||||
|
||||
return msgpack.packb(container)
|
||||
|
||||
|
||||
def write_to_directory(self, directory_path):
|
||||
file_name = RNS.hexrep(self.hash, delimit=False)
|
||||
file_path = directory_path+"/"+file_name
|
||||
|
||||
try:
|
||||
file = open(file_path, "wb")
|
||||
file.write(self.packed_container())
|
||||
file.close()
|
||||
|
||||
return file_path
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while writing LXMF message to file \""+str(file_path)+"\". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
return None
|
||||
|
||||
def as_uri(self, finalise=True):
|
||||
self.determine_transport_encryption()
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
if self.desired_method == LXMessage.PAPER and self.paper_packed != None:
|
||||
# Encode packed LXM with URL-safe base64 and remove padding
|
||||
encoded_bytes = base64.urlsafe_b64encode(self.paper_packed)
|
||||
|
||||
# Add protocol specifier and return
|
||||
lxm_uri = LXMessage.URI_SCHEMA+"://"+encoded_bytes.decode("utf-8").replace("=","")
|
||||
|
||||
if finalise:
|
||||
self.__mark_paper_generated()
|
||||
|
||||
return lxm_uri
|
||||
|
||||
else:
|
||||
raise TypeError("Attempt to represent LXM with non-paper delivery method as URI")
|
||||
|
||||
def as_qr(self):
|
||||
self.determine_transport_encryption()
|
||||
if not self.packed:
|
||||
self.pack()
|
||||
|
||||
if self.desired_method == LXMessage.PAPER and self.paper_packed != None:
|
||||
import importlib
|
||||
if importlib.util.find_spec('qrcode') != None:
|
||||
import qrcode
|
||||
|
||||
qr = qrcode.make(
|
||||
error_correction = qrcode.constants.__dict__[LXMessage.QR_ERROR_CORRECTION],
|
||||
border = 1,
|
||||
data = self.as_uri(finalise=False),
|
||||
)
|
||||
|
||||
self.__mark_paper_generated()
|
||||
|
||||
return qr
|
||||
|
||||
else:
|
||||
RNS.log("Generating QR-code representanions of LXMs requires the \"qrcode\" module to be installed.", RNS.LOG_CRITICAL)
|
||||
RNS.log("You can install it with the command: python3 -m pip install qrcode", RNS.LOG_CRITICAL)
|
||||
return None
|
||||
|
||||
else:
|
||||
raise TypeError("Attempt to represent LXM with non-paper delivery method as QR-code")
|
||||
|
||||
@staticmethod
|
||||
def unpack_from_bytes(lxmf_bytes, original_method = None):
|
||||
destination_hash = lxmf_bytes[:LXMessage.DESTINATION_LENGTH]
|
||||
source_hash = lxmf_bytes[LXMessage.DESTINATION_LENGTH:2*LXMessage.DESTINATION_LENGTH]
|
||||
signature = lxmf_bytes[2*LXMessage.DESTINATION_LENGTH:2*LXMessage.DESTINATION_LENGTH+LXMessage.SIGNATURE_LENGTH]
|
||||
packed_payload = lxmf_bytes[2*LXMessage.DESTINATION_LENGTH+LXMessage.SIGNATURE_LENGTH:]
|
||||
hashed_part = b"" + destination_hash + source_hash + packed_payload
|
||||
message_hash = RNS.Identity.full_hash(hashed_part)
|
||||
signed_part = b"" + hashed_part + message_hash
|
||||
unpacked_payload = msgpack.unpackb(packed_payload)
|
||||
timestamp = unpacked_payload[0]
|
||||
title_bytes = unpacked_payload[1]
|
||||
content_bytes = unpacked_payload[2]
|
||||
fields = unpacked_payload[3]
|
||||
|
||||
destination_identity = RNS.Identity.recall(destination_hash)
|
||||
if destination_identity != None:
|
||||
destination = RNS.Destination(destination_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "delivery")
|
||||
else:
|
||||
destination = None
|
||||
|
||||
source_identity = RNS.Identity.recall(source_hash)
|
||||
if source_identity != None:
|
||||
source = RNS.Destination(source_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, APP_NAME, "delivery")
|
||||
else:
|
||||
source = None
|
||||
|
||||
message = LXMessage(
|
||||
destination = destination,
|
||||
source = source,
|
||||
content = "",
|
||||
title = "",
|
||||
fields = fields,
|
||||
destination_hash = destination_hash,
|
||||
source_hash = source_hash,
|
||||
desired_method = original_method)
|
||||
|
||||
message.hash = message_hash
|
||||
message.signature = signature
|
||||
message.incoming = True
|
||||
message.timestamp = timestamp
|
||||
message.packed = lxmf_bytes
|
||||
message.packed_size = len(lxmf_bytes)
|
||||
message.set_title_from_bytes(title_bytes)
|
||||
message.set_content_from_bytes(content_bytes)
|
||||
|
||||
try:
|
||||
if source:
|
||||
if source.identity.validate(signature, signed_part):
|
||||
message.signature_validated = True
|
||||
else:
|
||||
message.signature_validated = False
|
||||
message.unverified_reason = LXMessage.SIGNATURE_INVALID
|
||||
else:
|
||||
signature_validated = False
|
||||
message.unverified_reason = LXMessage.SOURCE_UNKNOWN
|
||||
RNS.log("Unpacked LXMF message signature could not be validated, since source identity is unknown", RNS.LOG_DEBUG)
|
||||
except Exception as e:
|
||||
message.signature_validated = False
|
||||
RNS.log("Error while validating LXMF message signature. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
return message
|
||||
|
||||
@staticmethod
|
||||
def unpack_from_file(lxmf_file_handle):
|
||||
try:
|
||||
container = msgpack.unpackb(lxmf_file_handle.read())
|
||||
lxm = LXMessage.unpack_from_bytes(container["lxmf_bytes"])
|
||||
|
||||
if "state" in container:
|
||||
lxm.state = container["state"]
|
||||
if "transport_encrypted" in container:
|
||||
lxm.transport_encrypted = container["transport_encrypted"]
|
||||
if "transport_encryption" in container:
|
||||
lxm.transport_encryption = container["transport_encryption"]
|
||||
if "method" in container:
|
||||
lxm.method = container["method"]
|
||||
|
||||
return lxm
|
||||
except Exception as e:
|
||||
RNS.log("Could not unpack LXMessage from file. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
return None
|
||||
@@ -0,0 +1,499 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
# MIT License
|
||||
#
|
||||
# Copyright (c) 2016-2022 Mark Qvist / unsigned.io
|
||||
#
|
||||
# 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.
|
||||
|
||||
DEFFERED_JOBS_DELAY = 10
|
||||
JOBS_INTERVAL = 5
|
||||
|
||||
import RNS
|
||||
import LXMF
|
||||
import argparse
|
||||
import threading
|
||||
import subprocess
|
||||
import shlex
|
||||
import time
|
||||
import os
|
||||
|
||||
from LXMF._version import __version__
|
||||
|
||||
from RNS.vendor.configobj import ConfigObj
|
||||
|
||||
configpath = None
|
||||
ignoredpath = None
|
||||
identitypath = None
|
||||
storagedir = None
|
||||
lxmdir = None
|
||||
targetloglevel = None
|
||||
|
||||
identity = None
|
||||
lxmd_config = None
|
||||
message_router = None
|
||||
lxmf_destination = None
|
||||
active_configuration = {}
|
||||
|
||||
last_peer_announce = None
|
||||
last_node_announce = None
|
||||
|
||||
def create_default_config(configpath):
|
||||
lxmd_config = ConfigObj(__default_lxmd_config__.splitlines())
|
||||
lxmd_config.filename = configpath
|
||||
lxmd_config.write()
|
||||
|
||||
def apply_config():
|
||||
global active_configuration, targetloglevel
|
||||
try:
|
||||
# Load peer settings
|
||||
if "lxmf" in lxmd_config and "display_name" in lxmd_config["lxmf"]:
|
||||
active_configuration["display_name"] = lxmd_config["lxmf"]["display_name"]
|
||||
else:
|
||||
active_configuration["display_name"] = "Anonymous Peer"
|
||||
|
||||
if "lxmf" in lxmd_config and "announce_at_start" in lxmd_config["lxmf"]:
|
||||
active_configuration["peer_announce_at_start"] = lxmd_config["lxmf"].as_bool("announce_at_start")
|
||||
else:
|
||||
active_configuration["peer_announce_at_start"] = False
|
||||
|
||||
if "lxmf" in lxmd_config and "announce_interval" in lxmd_config["lxmf"]:
|
||||
active_configuration["peer_announce_interval"] = lxmd_config["lxmf"].as_int("announce_interval")*60
|
||||
else:
|
||||
active_configuration["peer_announce_interval"] = None
|
||||
|
||||
if "lxmf" in lxmd_config and "on_inbound" in lxmd_config["lxmf"]:
|
||||
active_configuration["on_inbound"] = lxmd_config["lxmf"]["on_inbound"]
|
||||
else:
|
||||
active_configuration["on_inbound"] = None
|
||||
|
||||
# Load propagation node settings
|
||||
if "propagation" in lxmd_config and "enable_node" in lxmd_config["propagation"]:
|
||||
active_configuration["enable_propagation_node"] = lxmd_config["propagation"].as_bool("enable_node")
|
||||
else:
|
||||
active_configuration["enable_propagation_node"] = False
|
||||
|
||||
if "propagation" in lxmd_config and "auth_required" in lxmd_config["propagation"]:
|
||||
active_configuration["auth_required"] = lxmd_config["propagation"].as_bool("auth_required")
|
||||
else:
|
||||
active_configuration["auth_required"] = False
|
||||
|
||||
if "propagation" in lxmd_config and "announce_at_start" in lxmd_config["propagation"]:
|
||||
active_configuration["node_announce_at_start"] = lxmd_config["propagation"].as_bool("announce_at_start")
|
||||
else:
|
||||
active_configuration["node_announce_at_start"] = False
|
||||
|
||||
if "propagation" in lxmd_config and "autopeer" in lxmd_config["propagation"]:
|
||||
active_configuration["autopeer"] = lxmd_config["propagation"].as_bool("autopeer")
|
||||
else:
|
||||
active_configuration["autopeer"] = True
|
||||
|
||||
if "propagation" in lxmd_config and "autopeer_maxdepth" in lxmd_config["propagation"]:
|
||||
active_configuration["autopeer_maxdepth"] = lxmd_config["propagation"].as_int("autopeer_maxdepth")
|
||||
else:
|
||||
active_configuration["autopeer_maxdepth"] = None
|
||||
|
||||
if "propagation" in lxmd_config and "announce_interval" in lxmd_config["propagation"]:
|
||||
active_configuration["node_announce_interval"] = lxmd_config["propagation"].as_int("announce_interval")*60
|
||||
else:
|
||||
active_configuration["node_announce_interval"] = None
|
||||
|
||||
if "propagation" in lxmd_config and "message_storage_limit" in lxmd_config["propagation"]:
|
||||
active_configuration["message_storage_limit"] = lxmd_config["propagation"].as_float("message_storage_limit")
|
||||
if active_configuration["message_storage_limit"] < 0.005:
|
||||
active_configuration["message_storage_limit"] = 0.005
|
||||
else:
|
||||
active_configuration["message_storage_limit"] = 2000
|
||||
|
||||
if "propagation" in lxmd_config and "prioritise_destinations" in lxmd_config["propagation"]:
|
||||
active_configuration["prioritised_lxmf_destinations"] = lxmd_config["propagation"].as_list("prioritise_destinations")
|
||||
else:
|
||||
active_configuration["prioritised_lxmf_destinations"] = []
|
||||
|
||||
# Load various settings
|
||||
if "logging" in lxmd_config and "loglevel" in lxmd_config["logging"]:
|
||||
targetloglevel = lxmd_config["logging"].as_int("loglevel")
|
||||
|
||||
active_configuration["ignored_lxmf_destinations"] = []
|
||||
if os.path.isfile(ignoredpath):
|
||||
try:
|
||||
fh = open(ignoredpath, "rb")
|
||||
ignored_input = fh.read()
|
||||
fh.close()
|
||||
|
||||
ignored_hash_strs = ignored_input.splitlines()
|
||||
|
||||
for hash_str in ignored_hash_strs:
|
||||
if len(hash_str) == RNS.Identity.TRUNCATED_HASHLENGTH//8*2:
|
||||
try:
|
||||
ignored_hash = bytes.fromhex(hash_str.decode("utf-8"))
|
||||
active_configuration["ignored_lxmf_destinations"].append(ignored_hash)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not decode hash from: "+str(hash_str), RNS.LOG_DEBUG)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while loading list of ignored destinations: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
active_configuration["allowed_identities"] = []
|
||||
if os.path.isfile(allowedpath):
|
||||
try:
|
||||
fh = open(allowedpath, "rb")
|
||||
allowed_input = fh.read()
|
||||
fh.close()
|
||||
|
||||
allowed_hash_strs = allowed_input.splitlines()
|
||||
|
||||
for hash_str in allowed_hash_strs:
|
||||
if len(hash_str) == RNS.Identity.TRUNCATED_HASHLENGTH//8*2:
|
||||
try:
|
||||
allowed_hash = bytes.fromhex(hash_str.decode("utf-8"))
|
||||
active_configuration["allowed_identities"].append(allowed_hash)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not decode hash from: "+str(hash_str), RNS.LOG_DEBUG)
|
||||
RNS.log("The contained exception was: "+str(e), RNS.LOG_DEBUG)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error while loading list of allowed identities: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Could not apply LXM Daemon configuration. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
raise e
|
||||
exit(3)
|
||||
|
||||
def lxmf_delivery(lxm):
|
||||
global active_configuration, lxmdir
|
||||
|
||||
try:
|
||||
written_path = lxm.write_to_directory(lxmdir)
|
||||
RNS.log("Received "+str(lxm)+" written to "+str(written_path), RNS.LOG_DEBUG)
|
||||
|
||||
if active_configuration["on_inbound"]:
|
||||
RNS.log("Calling external program to handle message", RNS.LOG_DEBUG)
|
||||
command = active_configuration["on_inbound"]
|
||||
processing_command = command+" \""+written_path+"\""
|
||||
return_code = subprocess.call(shlex.split(processing_command), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
else:
|
||||
RNS.log("No action defined for inbound messages, ignoring", RNS.LOG_DEBUG)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Error occurred while processing received message "+str(lxm)+". The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
|
||||
def program_setup(configdir = None, rnsconfigdir = None, run_pn = False, on_inbound = None, verbosity = 0, quietness = 0, service = False):
|
||||
global configpath, ignoredpath, identitypath, allowedpath, storagedir, lxmdir
|
||||
global lxmd_config, active_configuration, targetloglevel
|
||||
global message_router, lxmf_destination
|
||||
|
||||
targetloglevel = 3+verbosity-quietness
|
||||
|
||||
if service:
|
||||
targetlogdest = RNS.LOG_FILE
|
||||
targetloglevel = None
|
||||
else:
|
||||
targetlogdest = RNS.LOG_STDOUT
|
||||
|
||||
# Get configuration
|
||||
if configdir == None:
|
||||
if os.path.isdir("/etc/lxmd") and os.path.isfile("/etc/lxmd/config"):
|
||||
configdir = "/etc/lxmd"
|
||||
elif os.path.isdir(RNS.Reticulum.userdir+"/.config/lxmd") and os.path.isfile(Reticulum.userdir+"/.config/lxmd/config"):
|
||||
configdir = RNS.Reticulum.userdir+"/.config/lxmd"
|
||||
else:
|
||||
configdir = RNS.Reticulum.userdir+"/.lxmd"
|
||||
|
||||
configpath = configdir+"/config"
|
||||
ignoredpath = configdir+"/ignored"
|
||||
allowedpath = configdir+"/allowed"
|
||||
identitypath = configdir+"/identity"
|
||||
storagedir = configdir+"/storage"
|
||||
lxmdir = storagedir+"/messages"
|
||||
|
||||
if not os.path.isdir(storagedir):
|
||||
os.makedirs(storagedir)
|
||||
|
||||
if not os.path.isdir(lxmdir):
|
||||
os.makedirs(lxmdir)
|
||||
|
||||
if os.path.isfile(configpath):
|
||||
try:
|
||||
lxmd_config = ConfigObj(configpath)
|
||||
except Exception as e:
|
||||
RNS.log("Could not parse the configuration at "+configpath, RNS.LOG_ERROR)
|
||||
RNS.log("Check your configuration file for errors!", RNS.LOG_ERROR)
|
||||
RNS.panic()
|
||||
else:
|
||||
RNS.log("Could not load config file, creating default configuration file...")
|
||||
create_default_config(configpath)
|
||||
RNS.log("Default config file created. Make any necessary changes in "+configpath+" and restart Reticulum if needed.")
|
||||
time.sleep(1.5)
|
||||
|
||||
apply_config()
|
||||
RNS.log("Configuration loaded from "+configpath, RNS.LOG_VERBOSE)
|
||||
|
||||
# Start Reticulum
|
||||
RNS.log("Substantiating Reticulum...")
|
||||
reticulum = RNS.Reticulum(configdir=rnsconfigdir, loglevel=targetloglevel, logdest=targetlogdest)
|
||||
|
||||
# Generate or load primary identity
|
||||
if os.path.isfile(identitypath):
|
||||
try:
|
||||
identity = RNS.Identity.from_file(identitypath)
|
||||
if identity != None:
|
||||
RNS.log("Loaded Primary Identity %s" % (str(identity)))
|
||||
else:
|
||||
RNS.log("Could not load the Primary Identity from "+identitypath, RNS.LOG_ERROR)
|
||||
exit(4)
|
||||
except Exception as e:
|
||||
RNS.log("Could not load the Primary Identity from "+identitypath, RNS.LOG_ERROR)
|
||||
RNS.log("The contained exception was: %s" % (str(e)), RNS.LOG_ERROR)
|
||||
exit(1)
|
||||
else:
|
||||
try:
|
||||
RNS.log("No Primary Identity file found, creating new...")
|
||||
identity = RNS.Identity()
|
||||
identity.to_file(identitypath)
|
||||
RNS.log("Created new Primary Identity %s" % (str(identity)))
|
||||
except Exception as e:
|
||||
RNS.log("Could not create and save a new Primary Identity", RNS.LOG_ERROR)
|
||||
RNS.log("The contained exception was: %s" % (str(e)), RNS.LOG_ERROR)
|
||||
exit(2)
|
||||
|
||||
# Start LXMF
|
||||
message_router = LXMF.LXMRouter(
|
||||
identity = identity,
|
||||
storagepath = storagedir,
|
||||
autopeer = active_configuration["autopeer"],
|
||||
autopeer_maxdepth = active_configuration["autopeer_maxdepth"],
|
||||
)
|
||||
message_router.register_delivery_callback(lxmf_delivery)
|
||||
|
||||
for destination_hash in active_configuration["ignored_lxmf_destinations"]:
|
||||
message_router.ignore_destination(destination_hash)
|
||||
|
||||
lxmf_destination = message_router.register_delivery_identity(identity, display_name=active_configuration["display_name"])
|
||||
|
||||
RNS.Identity.remember(
|
||||
packet_hash=None,
|
||||
destination_hash=lxmf_destination.hash,
|
||||
public_key=identity.get_public_key(),
|
||||
app_data=None
|
||||
)
|
||||
|
||||
# Set up authentication
|
||||
if active_configuration["auth_required"]:
|
||||
message_router.set_authentication(required=True)
|
||||
for identity_hash in active_configuration["allowed_identities"]:
|
||||
message_router.allow(identity_hash)
|
||||
|
||||
RNS.log("LXMF Router ready to receive on "+RNS.prettyhexrep(lxmf_destination.hash))
|
||||
|
||||
if run_pn or active_configuration["enable_propagation_node"]:
|
||||
message_router.set_message_storage_limit(megabytes=active_configuration["message_storage_limit"])
|
||||
for dest_str in active_configuration["prioritised_lxmf_destinations"]:
|
||||
try:
|
||||
dest_hash = bytes.fromhex(dest_str)
|
||||
if len(dest_hash) == RNS.Reticulum.TRUNCATED_HASHLENGTH//8:
|
||||
message_router.prioritise(dest_hash)
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("Cannot prioritise "+str(dest_str)+", it is not a valid destination hash", RNS.LOG_ERROR)
|
||||
|
||||
message_router.enable_propagation()
|
||||
|
||||
RNS.log("LXMF Propagation Node started on "+RNS.prettyhexrep(message_router.propagation_destination.hash))
|
||||
|
||||
if len(active_configuration["allowed_identities"]) == 0:
|
||||
RNS.log("Clint authentication was enabled, but no identity hashes could be loaded from "+str(allowedpath)+". Nobody will be able to sync messages from this propagation node.", RNS.LOG_WARNING)
|
||||
|
||||
RNS.log("Started lxmd version {version}".format(version=__version__), RNS.LOG_NOTICE)
|
||||
|
||||
threading.Thread(target=deferred_start_jobs, daemon=True).start()
|
||||
|
||||
while True:
|
||||
time.sleep(1)
|
||||
|
||||
def jobs():
|
||||
global active_configuration, last_peer_announce, last_node_announce
|
||||
global message_router, lxmf_destination
|
||||
|
||||
while True:
|
||||
try:
|
||||
if time.time() > last_peer_announce + active_configuration["peer_announce_interval"]:
|
||||
RNS.log("Sending announce for LXMF delivery destination", RNS.LOG_EXTREME)
|
||||
message_router.announce(lxmf_destination.hash)
|
||||
last_peer_announce = time.time()
|
||||
|
||||
if time.time() > last_node_announce + active_configuration["node_announce_interval"]:
|
||||
RNS.log("Sending announce for LXMF Propagation Node", RNS.LOG_EXTREME)
|
||||
message_router.announce_propagation_node()
|
||||
last_node_announce = time.time()
|
||||
|
||||
except Exception as e:
|
||||
RNS.log("An error occurred while running periodic jobs. The contained exception was: "+str(e), RNS.LOG_ERROR)
|
||||
|
||||
time.sleep(JOBS_INTERVAL)
|
||||
|
||||
def deferred_start_jobs():
|
||||
global active_configuration, last_peer_announce, last_node_announce
|
||||
global message_router, lxmf_destination
|
||||
time.sleep(DEFFERED_JOBS_DELAY)
|
||||
RNS.log("Running deferred start jobs")
|
||||
if active_configuration["peer_announce_at_start"]:
|
||||
RNS.log("Sending announce for LXMF delivery destination", RNS.LOG_EXTREME)
|
||||
message_router.announce(lxmf_destination.hash)
|
||||
|
||||
if active_configuration["node_announce_at_start"]:
|
||||
RNS.log("Sending announce for LXMF Propagation Node", RNS.LOG_EXTREME)
|
||||
message_router.announce_propagation_node()
|
||||
|
||||
last_peer_announce = time.time()
|
||||
last_node_announce = time.time()
|
||||
threading.Thread(target=jobs, daemon=True).start()
|
||||
|
||||
def main():
|
||||
try:
|
||||
parser = argparse.ArgumentParser(description="Lightweight Extensible Messaging Daemon")
|
||||
parser.add_argument("--config", action="store", default=None, help="path to alternative lxmd config directory", type=str)
|
||||
parser.add_argument("--rnsconfig", action="store", default=None, help="path to alternative Reticulum config directory", type=str)
|
||||
parser.add_argument("-p", "--propagation-node", action="store_true", default=False, help="run an LXMF Propagation Node")
|
||||
parser.add_argument("-i", "--on-inbound", action="store", metavar="PATH", default=None, help="executable to run when a message is received", type=str)
|
||||
parser.add_argument("-v", "--verbose", action="count", default=0)
|
||||
parser.add_argument("-q", "--quiet", action="count", default=0)
|
||||
parser.add_argument("-s", "--service", action="store_true", default=False, help="lxmd is running as a service and should log to file")
|
||||
parser.add_argument("--exampleconfig", action="store_true", default=False, help="print verbose configuration example to stdout and exit")
|
||||
parser.add_argument("--version", action="version", version="lxmd {version}".format(version=__version__))
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.exampleconfig:
|
||||
print(__default_lxmd_config__)
|
||||
exit()
|
||||
|
||||
program_setup(
|
||||
configdir = args.config,
|
||||
rnsconfigdir=args.rnsconfig,
|
||||
run_pn=args.propagation_node,
|
||||
on_inbound=args.on_inbound,
|
||||
verbosity=args.verbose,
|
||||
quietness=args.quiet,
|
||||
service=args.service
|
||||
)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("")
|
||||
exit()
|
||||
|
||||
__default_lxmd_config__ = """# This is an example LXM Daemon config file.
|
||||
# You should probably edit it to suit your
|
||||
# intended usage.
|
||||
|
||||
[propagation]
|
||||
|
||||
# Whether to enable propagation node
|
||||
enable_node = no
|
||||
|
||||
# Automatic announce interval in minutes.
|
||||
# 6 hours by default.
|
||||
announce_interval = 360
|
||||
|
||||
# Whether to announce when the node starts.
|
||||
announce_at_start = yes
|
||||
|
||||
# Wheter to automatically peer with other
|
||||
# propagation nodes on the network.
|
||||
autopeer = yes
|
||||
|
||||
# The maximum peering depth (in hops) for
|
||||
# automatically peered nodes.
|
||||
autopeer_maxdepth = 4
|
||||
|
||||
# The maximum amount of storage to use for
|
||||
# the LXMF Propagation Node message store,
|
||||
# specified in megabytes. When this limit
|
||||
# is reached, LXMF will periodically remove
|
||||
# messages in its message store. By default,
|
||||
# LXMF prioritises keeping messages that are
|
||||
# new and small. Large and old messages will
|
||||
# be removed first. This setting is optional
|
||||
# and defaults to 2 gigabytes.
|
||||
# message_storage_limit = 2000
|
||||
|
||||
# You can tell the LXMF message router to
|
||||
# prioritise storage for one or more
|
||||
# destinations. If the message store reaches
|
||||
# the specified limit, LXMF will prioritise
|
||||
# keeping messages for destinations specified
|
||||
# with this option. This setting is optional,
|
||||
# and generally you do not need to use it.
|
||||
# prioritise_destinations = 41d20c727598a3fbbdf9106133a3a0ed, d924b81822ca24e68e2effea99bcb8cf
|
||||
|
||||
# By default, any destination is allowed to
|
||||
# connect and download messages, but you can
|
||||
# optionally restrict this. If you enable
|
||||
# authentication, you must provide a list of
|
||||
# allowed identity hashes in the a file named
|
||||
# "allowed" in the lxmd config directory.
|
||||
auth_required = no
|
||||
|
||||
|
||||
[lxmf]
|
||||
|
||||
# The LXM Daemon will create an LXMF destination
|
||||
# that it can receive messages on. This option sets
|
||||
# the announced display name for this destination.
|
||||
display_name = Anonymous Peer
|
||||
|
||||
# It is possible to announce the internal LXMF
|
||||
# destination when the LXM Daemon starts up.
|
||||
announce_at_start = no
|
||||
|
||||
# You can also announce the delivery destination
|
||||
# at a specified interval. This is not enabled by
|
||||
# default.
|
||||
# announce_interval = 360
|
||||
|
||||
# You can configure an external program to be run
|
||||
# every time a message is received. The program
|
||||
# will receive as an argument the full path to the
|
||||
# message saved as a file. The example below will
|
||||
# simply result in the message getting deleted as
|
||||
# soon as it has been received.
|
||||
# on_inbound = rm
|
||||
|
||||
|
||||
[logging]
|
||||
# Valid log levels are 0 through 7:
|
||||
# 0: Log only critical information
|
||||
# 1: Log errors and lower log levels
|
||||
# 2: Log warnings and lower log levels
|
||||
# 3: Log notices and lower log levels
|
||||
# 4: Log info and lower (this is the default)
|
||||
# 5: Verbose logging
|
||||
# 6: Debug logging
|
||||
# 7: Extreme logging
|
||||
loglevel = 4
|
||||
|
||||
"""
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+4
-2
@@ -1,7 +1,9 @@
|
||||
import os
|
||||
import glob
|
||||
from .LXMF import LXMessage
|
||||
from .LXMF import LXMRouter
|
||||
from .LXMessage import LXMessage
|
||||
from .LXMRouter import LXMRouter
|
||||
|
||||
from ._version import __version__
|
||||
|
||||
modules = glob.glob(os.path.dirname(__file__)+"/*.py")
|
||||
__all__ = [ os.path.basename(f)[:-3] for f in modules if not f.endswith('__init__.py')]
|
||||
@@ -0,0 +1 @@
|
||||
__version__ = "0.2.5"
|
||||
@@ -0,0 +1,25 @@
|
||||
all: release
|
||||
|
||||
clean:
|
||||
@echo Cleaning...
|
||||
-rm -r ./build
|
||||
-rm -r ./dist
|
||||
|
||||
remove_symlinks:
|
||||
@echo Removing symlinks for build...
|
||||
-rm ./RNS
|
||||
-rm ./LXMF/Utilities/LXMF
|
||||
|
||||
create_symlinks:
|
||||
@echo Creating symlinks...
|
||||
-ln -s ../Reticulum/RNS ./
|
||||
-ln -s ../../LXMF ./LXMF/Utilities/LXMF
|
||||
|
||||
build_wheel:
|
||||
python3 setup.py sdist bdist_wheel
|
||||
|
||||
release: remove_symlinks build_wheel create_symlinks
|
||||
|
||||
upload:
|
||||
@echo Uploading to PyPi...
|
||||
twine upload dist/*
|
||||
-847
@@ -1,847 +0,0 @@
|
||||
<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>@font-face {
|
||||
font-family: octicons-anchor;
|
||||
src: url(https://cdnjs.cloudflare.com/ajax/libs/octicons/4.4.0/font/octicons.woff) format('woff');
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
width: 980px;
|
||||
margin-right: auto;
|
||||
margin-left: auto;
|
||||
color:#333;
|
||||
background:#fff;
|
||||
}
|
||||
|
||||
body .markdown-body {
|
||||
padding: 45px;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 3px;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
pre {
|
||||
font: 12px Consolas, "Liberation Mono", Menlo, Courier, monospace;
|
||||
}
|
||||
|
||||
.markdown-body {
|
||||
-webkit-text-size-adjust: 100%;
|
||||
text-size-adjust: 100%;
|
||||
color: #333;
|
||||
font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
|
||||
font-size: 16px;
|
||||
line-height: 1.6;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.markdown-body a {
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.markdown-body a:active,
|
||||
.markdown-body a:hover {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
.markdown-body strong {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-body h1 {
|
||||
font-size: 2em;
|
||||
margin: 0.67em 0;
|
||||
}
|
||||
|
||||
.markdown-body img {
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.markdown-body hr {
|
||||
box-sizing: content-box;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.markdown-body pre {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.markdown-body code,
|
||||
.markdown-body kbd,
|
||||
.markdown-body pre {
|
||||
font-family: monospace, monospace;
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
.markdown-body input {
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.markdown-body html input[disabled] {
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.markdown-body input {
|
||||
line-height: normal;
|
||||
}
|
||||
|
||||
.markdown-body input[type="checkbox"] {
|
||||
box-sizing: border-box;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.markdown-body table {
|
||||
border-collapse: collapse;
|
||||
border-spacing: 0;
|
||||
}
|
||||
|
||||
.markdown-body td,
|
||||
.markdown-body th {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.markdown-body input {
|
||||
font: 13px / 1.4 Helvetica, arial, nimbussansl, liberationsans, freesans, clean, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
|
||||
}
|
||||
|
||||
.markdown-body a {
|
||||
color: #4078c0;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.markdown-body a:hover,
|
||||
.markdown-body a:active {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.markdown-body hr {
|
||||
height: 0;
|
||||
margin: 15px 0;
|
||||
overflow: hidden;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-bottom: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.markdown-body hr:before {
|
||||
display: table;
|
||||
content: "";
|
||||
}
|
||||
|
||||
.markdown-body hr:after {
|
||||
display: table;
|
||||
clear: both;
|
||||
content: "";
|
||||
}
|
||||
|
||||
.markdown-body h1,
|
||||
.markdown-body h2,
|
||||
.markdown-body h3,
|
||||
.markdown-body h4,
|
||||
.markdown-body h5,
|
||||
.markdown-body h6 {
|
||||
margin-top: 15px;
|
||||
margin-bottom: 15px;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.markdown-body h1 {
|
||||
font-size: 30px;
|
||||
}
|
||||
|
||||
.markdown-body h2 {
|
||||
font-size: 21px;
|
||||
}
|
||||
|
||||
.markdown-body h3 {
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.markdown-body h4 {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.markdown-body h5 {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.markdown-body h6 {
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.markdown-body blockquote {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.markdown-body ul,
|
||||
.markdown-body ol {
|
||||
padding: 0;
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.markdown-body ol ol,
|
||||
.markdown-body ul ol {
|
||||
list-style-type: lower-roman;
|
||||
}
|
||||
|
||||
.markdown-body ul ul ol,
|
||||
.markdown-body ul ol ol,
|
||||
.markdown-body ol ul ol,
|
||||
.markdown-body ol ol ol {
|
||||
list-style-type: lower-alpha;
|
||||
}
|
||||
|
||||
.markdown-body dd {
|
||||
margin-left: 0;
|
||||
}
|
||||
|
||||
.markdown-body code {
|
||||
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.markdown-body pre {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
font: 12px Consolas, "Liberation Mono", Menlo, Courier, monospace;
|
||||
}
|
||||
|
||||
.markdown-body .select::-ms-expand {
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.markdown-body .octicon {
|
||||
font: normal normal normal 16px/1 octicons-anchor;
|
||||
display: inline-block;
|
||||
text-decoration: none;
|
||||
text-rendering: auto;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
-webkit-user-select: none;
|
||||
-moz-user-select: none;
|
||||
-ms-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.markdown-body .octicon-link:before {
|
||||
content: '\f05c';
|
||||
}
|
||||
|
||||
.markdown-body:before {
|
||||
display: table;
|
||||
content: "";
|
||||
}
|
||||
|
||||
.markdown-body:after {
|
||||
display: table;
|
||||
clear: both;
|
||||
content: "";
|
||||
}
|
||||
|
||||
.markdown-body>*:first-child {
|
||||
margin-top: 0 !important;
|
||||
}
|
||||
|
||||
.markdown-body>*:last-child {
|
||||
margin-bottom: 0 !important;
|
||||
}
|
||||
|
||||
.markdown-body a:not([href]) {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.markdown-body .anchor {
|
||||
display: inline-block;
|
||||
padding-right: 2px;
|
||||
margin-left: -18px;
|
||||
}
|
||||
|
||||
.markdown-body .anchor:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.markdown-body h1,
|
||||
.markdown-body h2,
|
||||
.markdown-body h3,
|
||||
.markdown-body h4,
|
||||
.markdown-body h5,
|
||||
.markdown-body h6 {
|
||||
margin-top: 1em;
|
||||
margin-bottom: 16px;
|
||||
font-weight: bold;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.markdown-body h1 .octicon-link,
|
||||
.markdown-body h2 .octicon-link,
|
||||
.markdown-body h3 .octicon-link,
|
||||
.markdown-body h4 .octicon-link,
|
||||
.markdown-body h5 .octicon-link,
|
||||
.markdown-body h6 .octicon-link {
|
||||
color: #000;
|
||||
vertical-align: middle;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.markdown-body h1:hover .anchor,
|
||||
.markdown-body h2:hover .anchor,
|
||||
.markdown-body h3:hover .anchor,
|
||||
.markdown-body h4:hover .anchor,
|
||||
.markdown-body h5:hover .anchor,
|
||||
.markdown-body h6:hover .anchor {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.markdown-body h1:hover .anchor .octicon-link,
|
||||
.markdown-body h2:hover .anchor .octicon-link,
|
||||
.markdown-body h3:hover .anchor .octicon-link,
|
||||
.markdown-body h4:hover .anchor .octicon-link,
|
||||
.markdown-body h5:hover .anchor .octicon-link,
|
||||
.markdown-body h6:hover .anchor .octicon-link {
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.markdown-body h1 {
|
||||
padding-bottom: 0.3em;
|
||||
font-size: 2.25em;
|
||||
line-height: 1.2;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.markdown-body h1 .anchor {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.markdown-body h2 {
|
||||
padding-bottom: 0.3em;
|
||||
font-size: 1.75em;
|
||||
line-height: 1.225;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
.markdown-body h2 .anchor {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.markdown-body h3 {
|
||||
font-size: 1.5em;
|
||||
line-height: 1.43;
|
||||
}
|
||||
|
||||
.markdown-body h3 .anchor {
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.markdown-body h4 {
|
||||
font-size: 1.25em;
|
||||
}
|
||||
|
||||
.markdown-body h4 .anchor {
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.markdown-body h5 {
|
||||
font-size: 1em;
|
||||
}
|
||||
|
||||
.markdown-body h5 .anchor {
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.markdown-body h6 {
|
||||
font-size: 1em;
|
||||
color: #777;
|
||||
}
|
||||
|
||||
.markdown-body h6 .anchor {
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.markdown-body p,
|
||||
.markdown-body blockquote,
|
||||
.markdown-body ul,
|
||||
.markdown-body ol,
|
||||
.markdown-body dl,
|
||||
.markdown-body table,
|
||||
.markdown-body pre {
|
||||
margin-top: 0;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.markdown-body hr {
|
||||
height: 4px;
|
||||
padding: 0;
|
||||
margin: 16px 0;
|
||||
background-color: #e7e7e7;
|
||||
border: 0 none;
|
||||
}
|
||||
|
||||
.markdown-body ul,
|
||||
.markdown-body ol {
|
||||
padding-left: 2em;
|
||||
}
|
||||
|
||||
.markdown-body ul ul,
|
||||
.markdown-body ul ol,
|
||||
.markdown-body ol ol,
|
||||
.markdown-body ol ul {
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.markdown-body li>p {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.markdown-body dl {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.markdown-body dl dt {
|
||||
padding: 0;
|
||||
margin-top: 16px;
|
||||
font-size: 1em;
|
||||
font-style: italic;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-body dl dd {
|
||||
padding: 0 16px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.markdown-body blockquote {
|
||||
padding: 0 15px;
|
||||
color: #777;
|
||||
border-left: 4px solid #ddd;
|
||||
}
|
||||
|
||||
.markdown-body blockquote>:first-child {
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.markdown-body blockquote>:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.markdown-body table {
|
||||
display: block;
|
||||
width: 100%;
|
||||
overflow: auto;
|
||||
word-break: normal;
|
||||
word-break: keep-all;
|
||||
}
|
||||
|
||||
.markdown-body table th {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-body table th,
|
||||
.markdown-body table td {
|
||||
padding: 6px 13px;
|
||||
border: 1px solid #ddd;
|
||||
}
|
||||
|
||||
.markdown-body table tr {
|
||||
background-color: #fff;
|
||||
border-top: 1px solid #ccc;
|
||||
}
|
||||
|
||||
.markdown-body table tr:nth-child(2n) {
|
||||
background-color: #f8f8f8;
|
||||
}
|
||||
|
||||
.markdown-body img {
|
||||
max-width: 100%;
|
||||
box-sizing: content-box;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
.markdown-body code {
|
||||
padding: 0;
|
||||
padding-top: 0.2em;
|
||||
padding-bottom: 0.2em;
|
||||
margin: 0;
|
||||
font-size: 85%;
|
||||
background-color: rgba(0,0,0,0.04);
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.markdown-body code:before,
|
||||
.markdown-body code:after {
|
||||
letter-spacing: -0.2em;
|
||||
content: "\00a0";
|
||||
}
|
||||
|
||||
.markdown-body pre>code {
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
font-size: 100%;
|
||||
word-break: normal;
|
||||
white-space: pre;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.markdown-body .highlight {
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.markdown-body .highlight pre,
|
||||
.markdown-body pre {
|
||||
padding: 16px;
|
||||
overflow: auto;
|
||||
font-size: 85%;
|
||||
line-height: 1.45;
|
||||
background-color: #f7f7f7;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.markdown-body .highlight pre {
|
||||
margin-bottom: 0;
|
||||
word-break: normal;
|
||||
}
|
||||
|
||||
.markdown-body pre {
|
||||
word-wrap: normal;
|
||||
}
|
||||
|
||||
.markdown-body pre code {
|
||||
display: inline;
|
||||
max-width: initial;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
overflow: initial;
|
||||
line-height: inherit;
|
||||
word-wrap: normal;
|
||||
background-color: transparent;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.markdown-body pre code:before,
|
||||
.markdown-body pre code:after {
|
||||
content: normal;
|
||||
}
|
||||
|
||||
.markdown-body kbd {
|
||||
display: inline-block;
|
||||
padding: 3px 5px;
|
||||
font-size: 11px;
|
||||
line-height: 10px;
|
||||
color: #555;
|
||||
vertical-align: middle;
|
||||
background-color: #fcfcfc;
|
||||
border: solid 1px #ccc;
|
||||
border-bottom-color: #bbb;
|
||||
border-radius: 3px;
|
||||
box-shadow: inset 0 -1px 0 #bbb;
|
||||
}
|
||||
|
||||
.markdown-body .pl-c {
|
||||
color: #969896;
|
||||
}
|
||||
|
||||
.markdown-body .pl-c1,
|
||||
.markdown-body .pl-s .pl-v {
|
||||
color: #0086b3;
|
||||
}
|
||||
|
||||
.markdown-body .pl-e,
|
||||
.markdown-body .pl-en {
|
||||
color: #795da3;
|
||||
}
|
||||
|
||||
.markdown-body .pl-s .pl-s1,
|
||||
.markdown-body .pl-smi {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
.markdown-body .pl-ent {
|
||||
color: #63a35c;
|
||||
}
|
||||
|
||||
.markdown-body .pl-k {
|
||||
color: #a71d5d;
|
||||
}
|
||||
|
||||
.markdown-body .pl-pds,
|
||||
.markdown-body .pl-s,
|
||||
.markdown-body .pl-s .pl-pse .pl-s1,
|
||||
.markdown-body .pl-sr,
|
||||
.markdown-body .pl-sr .pl-cce,
|
||||
.markdown-body .pl-sr .pl-sra,
|
||||
.markdown-body .pl-sr .pl-sre {
|
||||
color: #183691;
|
||||
}
|
||||
|
||||
.markdown-body .pl-v {
|
||||
color: #ed6a43;
|
||||
}
|
||||
|
||||
.markdown-body .pl-id {
|
||||
color: #b52a1d;
|
||||
}
|
||||
|
||||
.markdown-body .pl-ii {
|
||||
background-color: #b52a1d;
|
||||
color: #f8f8f8;
|
||||
}
|
||||
|
||||
.markdown-body .pl-sr .pl-cce {
|
||||
color: #63a35c;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-body .pl-ml {
|
||||
color: #693a17;
|
||||
}
|
||||
|
||||
.markdown-body .pl-mh,
|
||||
.markdown-body .pl-mh .pl-en,
|
||||
.markdown-body .pl-ms {
|
||||
color: #1d3e81;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-body .pl-mq {
|
||||
color: #008080;
|
||||
}
|
||||
|
||||
.markdown-body .pl-mi {
|
||||
color: #333;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.markdown-body .pl-mb {
|
||||
color: #333;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-body .pl-md {
|
||||
background-color: #ffecec;
|
||||
color: #bd2c00;
|
||||
}
|
||||
|
||||
.markdown-body .pl-mi1 {
|
||||
background-color: #eaffea;
|
||||
color: #55a532;
|
||||
}
|
||||
|
||||
.markdown-body .pl-mdr {
|
||||
color: #795da3;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.markdown-body .pl-mo {
|
||||
color: #1d3e81;
|
||||
}
|
||||
|
||||
.markdown-body kbd {
|
||||
display: inline-block;
|
||||
padding: 3px 5px;
|
||||
font: 11px Consolas, "Liberation Mono", Menlo, Courier, monospace;
|
||||
line-height: 10px;
|
||||
color: #555;
|
||||
vertical-align: middle;
|
||||
background-color: #fcfcfc;
|
||||
border: solid 1px #ccc;
|
||||
border-bottom-color: #bbb;
|
||||
border-radius: 3px;
|
||||
box-shadow: inset 0 -1px 0 #bbb;
|
||||
}
|
||||
|
||||
.markdown-body .plan-price-unit {
|
||||
color: #767676;
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
.markdown-body .task-list-item {
|
||||
list-style-type: none;
|
||||
}
|
||||
|
||||
.markdown-body .task-list-item+.task-list-item {
|
||||
margin-top: 3px;
|
||||
}
|
||||
|
||||
.markdown-body .task-list-item input {
|
||||
margin: 0 0.35em 0.25em -1.6em;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.markdown-body .plan-choice {
|
||||
padding: 15px;
|
||||
padding-left: 40px;
|
||||
display: block;
|
||||
border: 1px solid #e0e0e0;
|
||||
position: relative;
|
||||
font-weight: normal;
|
||||
background-color: #fafafa;
|
||||
}
|
||||
|
||||
.markdown-body .plan-choice.open {
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
.markdown-body .plan-choice.open .plan-choice-seat-breakdown {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.markdown-body .plan-choice-free {
|
||||
border-radius: 3px 3px 0 0;
|
||||
}
|
||||
|
||||
.markdown-body .plan-choice-paid {
|
||||
border-radius: 0 0 3px 3px;
|
||||
border-top: 0;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.markdown-body .plan-choice-radio {
|
||||
position: absolute;
|
||||
left: 15px;
|
||||
top: 18px;
|
||||
}
|
||||
|
||||
.markdown-body .plan-choice-exp {
|
||||
color: #999;
|
||||
font-size: 12px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.markdown-body .plan-choice-seat-breakdown {
|
||||
margin-top: 10px;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.markdown-body :checked+.radio-label {
|
||||
z-index: 1;
|
||||
position: relative;
|
||||
border-color: #4078c0;
|
||||
}
|
||||
|
||||
@media print {
|
||||
body .markdown-body {
|
||||
padding: 0;
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
</style><title>README</title></head><body><article class="markdown-body"><h1>
|
||||
<a id="user-content-lightweight-extensible-message-format" class="anchor" href="#lightweight-extensible-message-format" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Lightweight Extensible Message Format</h1>
|
||||
<p>LXMF is a simple and flexible messaging format that allows a wide variety of implementations, while using as little bandwidth as possible. It is built on top of <a href="https://github.com/markqvist/reticulum">Reticulum</a> and offers zero-conf message routing, end-to-end encryption and Perfect Forward Secrecy by default.</p>
|
||||
<h2>
|
||||
<a id="user-content-structure" class="anchor" href="#structure" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Structure</h2>
|
||||
<p>LXMF messages are stored in a simple and efficient format, that's easy to parse and write.</p>
|
||||
<h5>
|
||||
<a id="user-content-the-format-follows-this-general-structure" class="anchor" href="#the-format-follows-this-general-structure" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>The format follows this general structure:</h5>
|
||||
<ul>
|
||||
<li>Destination</li>
|
||||
<li>Source</li>
|
||||
<li>RSA Signature</li>
|
||||
<li>Payload
|
||||
<ul>
|
||||
<li>Timestamp</li>
|
||||
<li>Content</li>
|
||||
<li>Title</li>
|
||||
<li>Fields</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
<h5>
|
||||
<a id="user-content-and-these-rules" class="anchor" href="#and-these-rules" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>And these rules:</h5>
|
||||
<ol>
|
||||
<li>
|
||||
<p>A LXMF message is identified by it's <strong>message-id</strong>, which is a SHA-256 hash of the <strong>Destination</strong>, <strong>Source</strong> and <strong>Payload</strong>. The message-id is never included directly in the message, since it can always be inferred from the message itself.</p>
|
||||
<p>In some cases the actual message-id cannot be inferred, for example when a Propagation Node is storing an encrypted message for an offline user. In theses cases a <em>transient-id</em> is used to identify the message while in storage or transit.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p><strong>Destination</strong>, <strong>Source</strong>, <strong>Signature</strong> and <strong>Payload</strong> parts are mandatory, as is the <strong>Timestamp</strong> part of the payload.</p>
|
||||
<ul>
|
||||
<li>The <strong>Destination</strong> and <strong>Source</strong> fields are Reticulum destination hashes</li>
|
||||
<li>The <strong>Signature</strong> field is a RSA signature of the <strong>Destination</strong>, <strong>Source</strong>, <strong>Payload</strong> and <strong>message-id</strong>
|
||||
</li>
|
||||
<li>The <strong>Payload</strong> part is a list containing four items:
|
||||
<ol>
|
||||
<li>The <strong>Timestamp</strong> is a double-precision floating point number representing the number of seconds since the UNIX epoch.</li>
|
||||
<li>The <strong>Content</strong> is the optional content or body of the message</li>
|
||||
<li>The <strong>Title</strong> is an optional title for the message</li>
|
||||
<li>The <strong>Fields</strong> is an optional dictionary</li>
|
||||
</ol>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<p>The <strong>Content</strong>, <strong>Title</strong> and <strong>Fields</strong> parts must be included in the message structure, but can be left empty.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>The <strong>Fields</strong> part can be left empty, or contain a dictionary of any structure or depth.</p>
|
||||
</li>
|
||||
</ol>
|
||||
<h2>
|
||||
<a id="user-content-usage-examples" class="anchor" href="#usage-examples" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Usage Examples</h2>
|
||||
<p>LXMF offers flexibility to implement many different messaging schemes, ranging from human communication to machine control and sensor monitoring. Here's a few examples:</p>
|
||||
<ul>
|
||||
<li>
|
||||
<p>A messaging system for passing short, simple messages between human users, akin to SMS can be implemented using only the <strong>Content</strong> field, and leaving all other optional fields empty.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>For sending full-size mail, an email-like system can be implemented using the <strong>Title</strong> and <strong>Content</strong> fields to store "subject" and "body" parts of the message, and optionally the <strong>Fields</strong> part can be used to store attachments or other metadata.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Machine-control messages or sensor readings can be implemented using command structures embedded in the <strong>Fields</strong> dictionary.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>Distributed discussion or news-groups, akin to USENET or similar systems, can be implemented using the relevant fields and LXMF Propagation Nodes. Broadcast bulletins can be implemented in a similar fashion.</p>
|
||||
</li>
|
||||
</ul>
|
||||
<h2>
|
||||
<a id="user-content-propagation-nodes" class="anchor" href="#propagation-nodes" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Propagation Nodes</h2>
|
||||
<p>LXM Propagation Nodes offer a way to store and forward messages to users or endpoints that are not directly reachable at the time of message emission. Propagation Nodes can also provide infrastructure for distributed bulletin, news or discussion boards.</p>
|
||||
<h2>
|
||||
<a id="user-content-the-lxm-router" class="anchor" href="#the-lxm-router" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>The LXM Router</h2>
|
||||
<p>The LXM Router handles transporting messages over a Reticulum network, managing delivery receipts, outbound and inbound queues, and is the point of API interaction for client programs. The LXM Router also implements functionality for acting as an LXMF Propagation Node.</p>
|
||||
<p>Programatically, using the LXM Router to send a message is as simple as:</p>
|
||||
<div class="highlight highlight-source-python"><pre><span class="pl-k">import</span> <span class="pl-v">LXMF</span>
|
||||
|
||||
<span class="pl-s1">lxm_router</span> <span class="pl-c1">=</span> <span class="pl-v">LXMF</span>.<span class="pl-v">LXMRouter</span>()
|
||||
|
||||
<span class="pl-s1">message</span> <span class="pl-c1">=</span> <span class="pl-v">LXMF</span>.<span class="pl-v">LXMessage</span>(<span class="pl-s1">destination</span>, <span class="pl-s1">source</span>, <span class="pl-s">"This is a short, simple message."</span>)
|
||||
|
||||
<span class="pl-s1">lxm_router</span>.<span class="pl-en">handle_outbound</span>(<span class="pl-s1">message</span>)</pre></div>
|
||||
<p>The LXM Router then handles the heavy lifting, such as message packing, encryption, delivery confirmation, path lookup, routing, retries and failure notifications.</p>
|
||||
<h2>
|
||||
<a id="user-content-transport-encryption" class="anchor" href="#transport-encryption" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Transport Encryption</h2>
|
||||
<p>LXMF uses encryption provided by <a href="https://github.com/markqvist/reticulum">Reticulum</a>, and thus uses end-to-end encryption by default. The delivery method of a message will influence which transport encryption scheme is used.</p>
|
||||
<ul>
|
||||
<li>
|
||||
<p>A message can be delivered opportunistically, embedded in a single Reticulum packet. In this cases the message will be opportunistically routed through the network, and use <em>RSA-1024</em> asymmetric encryption.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>If a message is delivered to the Reticulum GROUP destination type, the message will be transported using <em>AES-128</em> encryption.</p>
|
||||
</li>
|
||||
<li>
|
||||
<p>If a message is delivered over a Reticulum link (which is the default method), the message will be encrypted with <em>ephemeral</em> keys derived with <em>ECDH</em> on the <em>SECP256R1</em> curve. This mode offers Perfect Forward Secrecy.</p>
|
||||
</li>
|
||||
</ul>
|
||||
<h2>
|
||||
<a id="user-content-wire-format--overhead" class="anchor" href="#wire-format--overhead" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Wire Format & Overhead</h2>
|
||||
<p>Assuming the default Reticulum configuration, the binary wire-format is as follows:</p>
|
||||
<ul>
|
||||
<li>10 bytes destination hash</li>
|
||||
<li>10 bytes source hash</li>
|
||||
<li>128 bytes RSA signature</li>
|
||||
<li>Remaining bytes of <a href="https://msgpack.org" rel="nofollow">msgpack</a> payload data, in accordance with the structure defined above</li>
|
||||
</ul>
|
||||
<p>The complete message overhead for LXMF is only 163 bytes, which in return gives you timestamped, digitally signed, infinitely extensible, end-to-end encrypted, zero-conf routed, minimal-infrastructure messaging that's easy to use and build applications with.</p>
|
||||
<h2>
|
||||
<a id="user-content-caveat-emptor" class="anchor" href="#caveat-emptor" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Caveat Emptor</h2>
|
||||
<p>As with Reticulum, LXMF is alpha software, and should be considered experimental. While it has been built with cryptography best-practices very foremost in mind, it <em>has not</em> been externally security audited, and there could very well be privacy-breaking bugs. If you want to help out, or help sponsor an audit, please do get in touch.</p>
|
||||
<h2>
|
||||
<a id="user-content-installation" class="anchor" href="#installation" aria-hidden="true"><span aria-hidden="true" class="octicon octicon-link"></span></a>Installation</h2>
|
||||
<p>If you want to try out LXMF, you can install it with pip:</p>
|
||||
<div class="highlight highlight-source-shell"><pre>pip3 install lxmf</pre></div>
|
||||
</article></body></html>
|
||||
@@ -1,33 +1,38 @@
|
||||
Lightweight Extensible Message Format
|
||||
==========
|
||||
# Lightweight Extensible Message Format
|
||||
|
||||
LXMF is a simple and flexible messaging format that allows a wide variety of implementations, while using as little bandwidth as possible. It is built on top of [Reticulum](https://github.com/markqvist/reticulum) and offers zero-conf message routing, end-to-end encryption and Perfect Forward Secrecy by default.
|
||||
LXMF is a simple and flexible messaging format and delivery protocol that allows a wide variety of implementations, while using as little bandwidth as possible. It is built on top of [Reticulum](https://reticulum.network) and offers zero-conf message routing, end-to-end encryption and Forward Secrecy by default.
|
||||
|
||||
User-facing clients built on LXMF include:
|
||||
|
||||
- [Sideband](https://unsigned.io/sideband)
|
||||
- [Nomad Network](https://unsigned.io/nomadnet)
|
||||
- [Nexus Messenger](https://github.com/HarlekinSimplex/nexus_messenger)
|
||||
|
||||
## Structure
|
||||
|
||||
LXMF messages are stored in a simple and efficient format, that's easy to parse and write.
|
||||
|
||||
##### The format follows this general structure:
|
||||
### The format follows this general structure:
|
||||
|
||||
- Destination
|
||||
- Source
|
||||
- RSA Signature
|
||||
- Ed25519 Signature
|
||||
- Payload
|
||||
- Timestamp
|
||||
- Content
|
||||
- Title
|
||||
- Fields
|
||||
|
||||
##### And these rules:
|
||||
### And these rules:
|
||||
|
||||
1. A LXMF message is identified by it's __message-id__, which is a SHA-256 hash of the __Destination__, __Source__ and __Payload__. The message-id is never included directly in the message, since it can always be inferred from the message itself.
|
||||
1. A LXMF message is identified by its __message-id__, which is a SHA-256 hash of the __Destination__, __Source__ and __Payload__. The message-id is never included directly in the message, since it can always be inferred from the message itself.
|
||||
|
||||
In some cases the actual message-id cannot be inferred, for example when a Propagation Node is storing an encrypted message for an offline user. In theses cases a _transient-id_ is used to identify the message while in storage or transit.
|
||||
|
||||
2. __Destination__, __Source__, __Signature__ and __Payload__ parts are mandatory, as is the __Timestamp__ part of the payload.
|
||||
- The __Destination__ and __Source__ fields are Reticulum destination hashes
|
||||
- The __Signature__ field is a RSA signature of the __Destination__, __Source__, __Payload__ and __message-id__
|
||||
- The __Payload__ part is a list containing four items:
|
||||
- The __Destination__ and __Source__ fields are 10-byte Reticulum destination hashes
|
||||
- The __Signature__ field is a 64-byte Ed25519 signature of the __Destination__, __Source__, __Payload__ and __message-id__
|
||||
- The __Payload__ part is a [msgpacked](https://msgpack.org) list containing four items:
|
||||
1. The __Timestamp__ is a double-precision floating point number representing the number of seconds since the UNIX epoch.
|
||||
2. The __Content__ is the optional content or body of the message
|
||||
3. The __Title__ is an optional title for the message
|
||||
@@ -53,6 +58,8 @@ LXMF offers flexibility to implement many different messaging schemes, ranging f
|
||||
|
||||
LXM Propagation Nodes offer a way to store and forward messages to users or endpoints that are not directly reachable at the time of message emission. Propagation Nodes can also provide infrastructure for distributed bulletin, news or discussion boards.
|
||||
|
||||
When Propagation Nodes exist on a Reticulum network, they will by default peer with each other and synchronise messages, automatically creating an encrypted, distributed message store. Users and other endpoints can retrieve messages destined for them from any available Propagation Nodes on the network.
|
||||
|
||||
## The LXM Router
|
||||
|
||||
The LXM Router handles transporting messages over a Reticulum network, managing delivery receipts, outbound and inbound queues, and is the point of API interaction for client programs. The LXM Router also implements functionality for acting as an LXMF Propagation Node.
|
||||
@@ -74,9 +81,9 @@ The LXM Router then handles the heavy lifting, such as message packing, encrypti
|
||||
|
||||
## Transport Encryption
|
||||
|
||||
LXMF uses encryption provided by [Reticulum](https://github.com/markqvist/reticulum), and thus uses end-to-end encryption by default. The delivery method of a message will influence which transport encryption scheme is used.
|
||||
LXMF uses encryption provided by [Reticulum](https://reticulum.network), and thus uses end-to-end encryption by default. The delivery method of a message will influence which transport encryption scheme is used.
|
||||
|
||||
- A message can be delivered opportunistically, embedded in a single Reticulum packet. In this cases the message will be opportunistically routed through the network, and use _RSA-1024_ asymmetric encryption.
|
||||
- A message can be delivered opportunistically, embedded in a single Reticulum packet. In this cases the message will be opportunistically routed through the network, and will be encrypted with _ephemeral_ keys derived with _ECDH_ on _Curve25519_. This mode offers Perfect Forward Secrecy.
|
||||
|
||||
- If a message is delivered to the Reticulum GROUP destination type, the message will be transported using _AES-128_ encryption.
|
||||
|
||||
@@ -86,16 +93,16 @@ LXMF uses encryption provided by [Reticulum](https://github.com/markqvist/reticu
|
||||
|
||||
Assuming the default Reticulum configuration, the binary wire-format is as follows:
|
||||
|
||||
- 10 bytes destination hash
|
||||
- 10 bytes source hash
|
||||
- 128 bytes RSA signature
|
||||
- 16 bytes destination hash
|
||||
- 16 bytes source hash
|
||||
- 64 bytes Ed25519 signature
|
||||
- Remaining bytes of [msgpack](https://msgpack.org) payload data, in accordance with the structure defined above
|
||||
|
||||
The complete message overhead for LXMF is only 163 bytes, which in return gives you timestamped, digitally signed, infinitely extensible, end-to-end encrypted, zero-conf routed, minimal-infrastructure messaging that's easy to use and build applications with.
|
||||
The complete message overhead for LXMF is only 99 bytes, which in return gives you timestamped, digitally signed, infinitely extensible, end-to-end encrypted, zero-conf routed, minimal-infrastructure messaging that's easy to use and build applications with.
|
||||
|
||||
## Caveat Emptor
|
||||
|
||||
LXMF is alpha software, and should be considered experimental. While it has been built with cryptography best-practices very foremost in mind, it _has not_ been externally security audited, and there could very well be privacy-breaking bugs. If you want to help out, or help sponsor an audit, please do get in touch.
|
||||
LXMF is beta software, and should be considered experimental. While it has been built with cryptography best-practices very foremost in mind, it _has not_ been externally security audited, and there could very well be privacy-breaking bugs. If you want to help out, or help sponsor an audit, please do get in touch.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -104,3 +111,16 @@ If you want to try out LXMF, you can install it with pip:
|
||||
```bash
|
||||
pip3 install lxmf
|
||||
```
|
||||
|
||||
## Development Roadmap
|
||||
|
||||
LXMF is actively being developed, and the following improvements and features are currently planned for implementation:
|
||||
|
||||
- Write and release full API and protocol documentation
|
||||
- Update examples in readme to actually work
|
||||
- Content Destinations, and easy to use API for group messaging and discussion threads
|
||||
- Sneakernet and physical transport functionality
|
||||
- LXMF paper- and QR-encoded messages
|
||||
- Documenting and possibly expanding LXMF limits and priorities
|
||||
- Sync affinity based on link speeds and distances, for more intelligently choosing peer sync order
|
||||
- Markets on LXMF
|
||||
@@ -3,21 +3,28 @@ import setuptools
|
||||
with open("README.md", "r") as fh:
|
||||
long_description = fh.read()
|
||||
|
||||
exec(open("LXMF/_version.py", "r").read())
|
||||
|
||||
setuptools.setup(
|
||||
name="lxmf",
|
||||
version="0.0.5",
|
||||
version=__version__,
|
||||
author="Mark Qvist",
|
||||
author_email="mark@unsigned.io",
|
||||
description="Lightweight Extensible Message Format for Reticulum",
|
||||
long_description=long_description,
|
||||
long_description_content_type="text/markdown",
|
||||
url="https://github.com/markqvist/lxmf",
|
||||
packages=setuptools.find_packages(),
|
||||
packages=["LXMF", "LXMF.Utilities"],
|
||||
classifiers=[
|
||||
"Programming Language :: Python :: 3",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
],
|
||||
install_requires=['rns>=0.2.0'],
|
||||
entry_points= {
|
||||
'console_scripts': [
|
||||
'lxmd=LXMF.Utilities.lxmd:main',
|
||||
]
|
||||
},
|
||||
install_requires=['rns>=0.4.1'],
|
||||
python_requires='>=3.6',
|
||||
)
|
||||
)
|
||||
Reference in new issue
Block a user