-
Notifications
You must be signed in to change notification settings - Fork 6
/
lxmf_distribution_group_extended.py
executable file
·5850 lines (4810 loc) · 275 KB
/
lxmf_distribution_group_extended.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
##############################################################################################################
#
# Copyright (c) 2024 Sebastian Obele / obele.eu
#
# 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.
#
# This software uses the following software-parts:
# Reticulum, LXMF, NomadNet / Copyright (c) 2016-2022 Mark Qvist / unsigned.io / MIT License
#
##############################################################################################################
##############################################################################################################
# Include
#### System ####
import sys
import os
import time
import datetime
import argparse
import random
#### Config ####
import configparser
#### Variables ####
from collections import defaultdict
#### JSON ####
import json
import pickle
#### String ####
import string
#### Regex ####
import re
#### Search ####
import fnmatch
#### Process ####
import signal
import threading
#### Reticulum, LXMF ####
# Install: pip3 install rns lxmf
# Source: https://markqvist.github.io
import RNS
import LXMF
import RNS.vendor.umsgpack as msgpack
##############################################################################################################
# Globals
#### Global Variables - Configuration ####
NAME = "LXMF Distribution Group"
DESCRIPTION = "Server-Side group functions for LXMF based apps"
VERSION = "0.0.1 (2024-05-31)"
COPYRIGHT = "(c) 2024 Sebastian Obele / obele.eu"
PATH = os.path.expanduser("~")+"/.config/"+os.path.splitext(os.path.basename(__file__))[0]
PATH_RNS = None
#### Global Variables - System (Not changeable) ####
DATA = None
CONFIG = None
STATISTIC = None
RNS_MAIN_CONNECTION = None
LXMF_PEER = None
RNS_CONNECTION = None
CONV_P2P = 0x01
CONV_GROUP = 0x02
CONV_BROADCAST = 0x03
CONV_DISTRIBUTION_GROUP = 0x04
MSG_FIELD_EMBEDDED_LXMS = 0x01
MSG_FIELD_TELEMETRY = 0x02
MSG_FIELD_TELEMETRY_STREAM = 0x03
MSG_FIELD_ICON_APPEARANCE = 0x04
MSG_FIELD_FILE_ATTACHMENTS = 0x05
MSG_FIELD_IMAGE = 0x06
MSG_FIELD_AUDIO = 0x07
MSG_FIELD_THREAD = 0x08
MSG_FIELD_COMMANDS = 0x09
MSG_FIELD_RESULTS = 0x0A
MSG_FIELD_GROUP = 0x0B
MSG_FIELD_TICKET = 0x0C
MSG_FIELD_EVENT = 0x0D
MSG_FIELD_RNR_REFS = 0x0E
MSG_FIELD_RENDERER = 0x0F
MSG_FIELD_CUSTOM_TYPE = 0xFB
MSG_FIELD_CUSTOM_DATA = 0xFC
MSG_FIELD_CUSTOM_META = 0xFD
MSG_FIELD_NON_SPECIFIC = 0xFE
MSG_FIELD_DEBUG = 0xFF
MSG_FIELD_ANSWER = 0xA0
MSG_FIELD_ATTACHMENT = 0xA1
MSG_FIELD_COMMANDS_EXECUTE = 0xA2
MSG_FIELD_COMMANDS_RESULT = 0xA3
MSG_FIELD_CONTACT = 0xA4
MSG_FIELD_DATA = 0xA5
MSG_FIELD_DELETE = 0xA6
MSG_FIELD_EDIT = 0xA7
MSG_FIELD_GROUP = 0xA8
MSG_FIELD_HASH = 0xA9
MSG_FIELD_ICON = 0xC1
MSG_FIELD_ICON_MENU = 0xAA
MSG_FIELD_ICON_SRC = 0xAB
MSG_FIELD_KEYBOARD = 0xAC
MSG_FIELD_KEYBOARD_INLINE = 0xAD
MSG_FIELD_LOCATION = 0xAE
MSG_FIELD_OWNER = 0xC0
MSG_FIELD_POLL = 0xAF
MSG_FIELD_POLL_ANSWER = 0xB0
MSG_FIELD_REACTION = 0xB1
MSG_FIELD_RECEIPT = 0xB2
MSG_FIELD_SCHEDULED = 0xB3
MSG_FIELD_SILENT = 0xB4
MSG_FIELD_SRC = 0xB5
MSG_FIELD_STATE = 0xB6
MSG_FIELD_STICKER = 0xB7
MSG_FIELD_TELEMETRY_DB = 0xB8
MSG_FIELD_TELEMETRY_PEER = 0xB9
MSG_FIELD_TELEMETRY_COMMANDS = 0xBA
MSG_FIELD_TEMPLATE = 0xBB
MSG_FIELD_TOPIC = 0xBC
MSG_FIELD_TYPE = 0xBD
MSG_FIELD_TYPE_FIELDS = 0xBE
MSG_FIELD_VOICE = 0xBF
##############################################################################################################
# LXMF Class
class LXMFPeer:
message_received_callback = None
message_notification_callback = None
message_notification_success_callback = None
message_notification_failed_callback = None
config_set_callback = None
def __init__(self, storage_path=None, identity_file="identity", identity=None, destination_name="lxmf", destination_type="delivery", announce_display_name="", announce_fields=None, announce_hidden=False, send_delay=0, method="auto", propagation_node=None, propagation_node_auto=False, propagation_node_active=None, stamps_enabled=False, stamps_required=False, stamps_cost=8, announce_startup=False, announce_startup_delay=0, announce_periodic=False, announce_periodic_interval=360, sync_startup=False, sync_startup_delay=0, sync_limit=8, sync_periodic=False, sync_periodic_interval=360):
self.storage_path = storage_path
self.identity_file = identity_file
self.identity = identity
self.destination_name = destination_name
self.destination_type = destination_type
self.aspect_filter = self.destination_name + "." + self.destination_type
self.announce_display_name = announce_display_name
self.announce_fields = announce_fields if announce_fields and len(announce_fields) > 0 else None
self.announce_hidden = announce_hidden
if stamps_enabled:
stamps_cost = int(stamps_cost)
if stamps_cost < 1 or stamps_cost > 255:
stamps_cost = None
else:
stamps_cost = None
if self.announce_fields:
self.announce_data = msgpack.packb([self.announce_display_name.encode("utf-8"), stamps_cost, self.announce_fields])
elif stamps_cost:
self.announce_data = msgpack.packb([self.announce_display_name.encode("utf-8"), stamps_cost])
else:
self.announce_data = self.announce_display_name.encode("utf-8")
log("LXMF - Configured announce data: " + str(self.announce_data), LOG_DEBUG)
self.send_delay = int(send_delay)
self.method = method
self.propagation_node = propagation_node
self.propagation_node_auto = propagation_node_auto
self.propagation_node_active = propagation_node_active
self.announce_startup = announce_startup
self.announce_startup_delay = int(announce_startup_delay)
if self.announce_startup_delay == 0:
self.announce_startup_delay = random.randint(5, 30)
self.announce_periodic = announce_periodic
self.announce_periodic_interval = int(announce_periodic_interval)
self.sync_startup = sync_startup
self.sync_startup_delay = int(sync_startup_delay)
if self.sync_startup_delay == 0:
self.sync_startup_delay = random.randint(5, 30)
self.sync_limit = int(sync_limit)
self.sync_periodic = sync_periodic
self.sync_periodic_interval = int(sync_periodic_interval)
if not self.storage_path:
log("LXMF - No storage_path parameter", LOG_ERROR)
return
if not os.path.isdir(self.storage_path):
os.makedirs(self.storage_path)
log("LXMF - Storage path was created", LOG_NOTICE)
log("LXMF - Storage path: " + self.storage_path, LOG_INFO)
if self.identity:
log("LXMF - Using existing Primary Identity %s" % (str(self.identity)))
else:
if not self.identity_file:
self.identity_file = "identity"
self.identity_path = self.storage_path + "/" + self.identity_file
if os.path.isfile(self.identity_path):
try:
self.identity = RNS.Identity.from_file(self.identity_path)
if self.identity != None:
log("LXMF - Loaded Primary Identity %s from %s" % (str(self.identity), self.identity_path))
else:
log("LXMF - Could not load the Primary Identity from "+self.identity_path, LOG_ERROR)
except Exception as e:
log("LXMF - Could not load the Primary Identity from "+self.identity_path, LOG_ERROR)
log("LXMF - The contained exception was: %s" % (str(e)), LOG_ERROR)
else:
try:
log("LXMF - No Primary Identity file found, creating new...")
self.identity = RNS.Identity()
self.identity.to_file(self.identity_path)
log("LXMF - Created new Primary Identity %s" % (str(self.identity)))
except Exception as e:
log("LXMF - Could not create and save a new Primary Identity", LOG_ERROR)
log("LXMF - The contained exception was: %s" % (str(e)), LOG_ERROR)
self.message_router = LXMF.LXMRouter(identity=self.identity, storagepath=self.storage_path)
if self.destination_name == "lxmf" and self.destination_type == "delivery":
self.destination = self.message_router.register_delivery_identity(self.identity, display_name=self.announce_display_name, stamp_cost=stamps_cost)
self.message_router.register_delivery_callback(self.process_lxmf_message_propagated)
else:
self.destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, self.destination_name, self.destination_type)
if self.announce_display_name == "":
self.announce_display_name = RNS.prettyhexrep(self.destination_hash())
if stamps_enabled and stamps_required:
self.message_router.enforce_stamps()
else:
self.message_router.ignore_stamps()
self.destination.set_default_app_data(self.announce_display_name.encode("utf-8"))
self.destination.set_proof_strategy(RNS.Destination.PROVE_ALL)
RNS.Identity.remember(packet_hash=None, destination_hash=self.destination.hash, public_key=self.identity.get_public_key(), app_data=None)
log("LXMF - Identity: " + str(self.identity), LOG_INFO)
log("LXMF - Destination: " + str(self.destination), LOG_INFO)
log("LXMF - Hash: " + RNS.prettyhexrep(self.destination_hash()), LOG_INFO)
self.destination.set_link_established_callback(self.client_connected)
if self.propagation_node_auto:
self.propagation_callback = LXMFPeerPropagation(self, "lxmf.propagation")
RNS.Transport.register_announce_handler(self.propagation_callback)
if self.propagation_node_active:
self.propagation_node_set(self.propagation_node_active)
elif self.propagation_node:
self.propagation_node_set(self.propagation_node)
else:
self.propagation_node_set(self.propagation_node)
if self.announce_startup or self.announce_periodic:
self.announce(initial=True)
if self.sync_startup or self.sync_periodic:
self.sync(True)
def register_announce_callback(self, handler_function):
self.announce_callback = handler_function(self.aspect_filter)
RNS.Transport.register_announce_handler(self.announce_callback)
def register_message_received_callback(self, handler_function):
self.message_received_callback = handler_function
def register_message_notification_callback(self, handler_function):
self.message_notification_callback = handler_function
def register_message_notification_success_callback(self, handler_function):
self.message_notification_success_callback = handler_function
def register_message_notification_failed_callback(self, handler_function):
self.message_notification_failed_callback = handler_function
def register_config_set_callback(self, handler_function):
self.config_set_callback = handler_function
def destination_hash(self):
return self.destination.hash
def destination_hash_str(self):
return RNS.hexrep(self.destination.hash, False)
def destination_check(self, destination):
if type(destination) is not bytes:
if len(destination) == ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2)+2:
destination = destination[1:-1]
if len(destination) != ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2):
log("LXMF - Destination length is invalid", LOG_ERROR)
return False
try:
destination = bytes.fromhex(destination)
except Exception as e:
log("LXMF - Destination is invalid", LOG_ERROR)
return False
return True
def destination_correct(self, destination):
if type(destination) is not bytes:
if len(destination) == ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2)+2:
destination = destination[1:-1]
if len(destination) != ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2):
return ""
try:
destination_bytes = bytes.fromhex(destination)
return destination
except Exception as e:
return ""
return ""
def send(self, destination, content="", title="", fields=None, timestamp=None, app_data="", destination_name=None, destination_type=None, method=None):
if type(destination) is not bytes:
if len(destination) == ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2)+2:
destination = destination[1:-1]
if len(destination) != ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2):
log("LXMF - Destination length is invalid", LOG_ERROR)
return None
try:
destination = bytes.fromhex(destination)
except Exception as e:
log("LXMF - Destination is invalid", LOG_ERROR)
return None
if destination_name == None:
destination_name = self.destination_name
if destination_type == None:
destination_type = self.destination_type
if method == None:
method = self.method
destination_identity = RNS.Identity.recall(destination)
destination = RNS.Destination(destination_identity, RNS.Destination.OUT, RNS.Destination.SINGLE, destination_name, destination_type)
return self.send_message(destination, self.destination, content, title, fields, timestamp, app_data, method)
def send_message(self, destination, source, content="", title="", fields=None, timestamp=None, app_data="", method=None):
if destination == self.destination:
return None
if method.lower() == "auto":
opportunistic = True
propagation = False
propagation_on_fail = True
elif method.lower() == "opportunistic":
opportunistic = True
propagation = False
propagation_on_fail = False
elif method.lower() == "direct":
opportunistic = False
propagation = False
propagation_on_fail = False
elif method.lower() == "propagated":
opportunistic = False
propagation = True
propagation_on_fail = False
elif method.lower() == "command":
opportunistic = True
propagation = False
propagation_on_fail = False
else:
opportunistic = True
propagation = False
propagation_on_fail = True
if propagation:
desired_method = LXMF.LXMessage.PROPAGATED
elif opportunistic and not self.message_router.delivery_link_available(destination.hash) and RNS.Identity.current_ratchet_id(destination.hash) != None:
desired_method = LXMF.LXMessage.OPPORTUNISTIC
else:
desired_method = LXMF.LXMessage.DIRECT
message = LXMF.LXMessage(destination, source, content, title=title, desired_method=desired_method)
if fields is not None:
message.fields = fields
if timestamp is not None:
message.timestamp = timestamp
message.app_data = app_data
self.log_message(message, "LXMF - Message send")
message.register_delivery_callback(self.message_notification)
message.register_failed_callback(self.message_notification)
if self.message_router.get_outbound_propagation_node() != None:
message.try_propagation_on_fail = propagation_on_fail
try:
self.message_router.handle_outbound(message)
time.sleep(self.send_delay)
return message.hash
except Exception as e:
log("LXMF - Could not send message " + str(message), LOG_ERROR)
log("LXMF - The contained exception was: " + str(e), LOG_ERROR)
return None
def message_notification(self, message):
if self.message_notification_callback is not None:
self.message_notification_callback(message)
if message.state == LXMF.LXMessage.FAILED and hasattr(message, "try_propagation_on_fail") and message.try_propagation_on_fail:
if hasattr(message, "stamp_generation_failed") and message.stamp_generation_failed == True:
self.log_message(message, "LXMF - Delivery receipt (failed)")
if self.message_notification_failed_callback is not None:
self.message_notification_failed_callback(message)
else:
self.log_message(message, "LXMF - Delivery receipt (failed) Retrying as propagated message")
message.try_propagation_on_fail = None
message.delivery_attempts = 0
if hasattr(message, "next_delivery_attempt"):
del message.next_delivery_attempt
message.packed = None
message.desired_method = LXMF.LXMessage.PROPAGATED
self.message_router.handle_outbound(message)
elif message.state == LXMF.LXMessage.FAILED:
self.log_message(message, "LXMF - Delivery receipt (failed)")
if self.message_notification_failed_callback is not None:
self.message_notification_failed_callback(message)
else:
self.log_message(message, "LXMF - Delivery receipt (success)")
if self.message_notification_success_callback is not None:
self.message_notification_success_callback(message)
def announce(self, app_data=None, attached_interface=None, initial=False):
announce_timer = None
if self.announce_periodic and self.announce_periodic_interval > 0:
announce_timer = threading.Timer(self.announce_periodic_interval*60, self.announce)
announce_timer.daemon = True
announce_timer.start()
if initial:
if self.announce_startup:
if self.announce_startup_delay > 0:
if announce_timer is not None:
announce_timer.cancel()
announce_timer = threading.Timer(self.announce_startup_delay, self.announce)
announce_timer.daemon = True
announce_timer.start()
else:
self.announce_now(app_data=app_data, attached_interface=attached_interface)
return
self.announce_now(app_data=app_data, attached_interface=attached_interface)
def announce_now(self, app_data=None, attached_interface=None):
if self.announce_hidden:
self.destination.announce("".encode("utf-8"), attached_interface=attached_interface)
log("LXMF - Announced: " + RNS.prettyhexrep(self.destination_hash()) +" (Hidden)", LOG_DEBUG)
elif app_data != None:
if isinstance(app_data, str):
self.destination.announce(app_data.encode("utf-8"), attached_interface=attached_interface)
log("LXMF - Announced: " + RNS.prettyhexrep(self.destination_hash()) +": " + app_data, LOG_DEBUG)
else:
self.destination.announce(app_data, attached_interface=attached_interface)
log("LMF - Announced: " + RNS.prettyhexrep(self.destination_hash()), LOG_DEBUG)
else:
self.destination.announce(self.announce_data, attached_interface=attached_interface)
log("LXMF - Announced: " + RNS.prettyhexrep(self.destination_hash()), LOG_DEBUG)
def sync(self, initial=False):
sync_timer = None
if self.sync_periodic and self.sync_periodic_interval > 0:
sync_timer = threading.Timer(self.sync_periodic_interval*60, self.sync)
sync_timer.daemon = True
sync_timer.start()
if initial:
if self.sync_startup:
if self.sync_startup_delay > 0:
if sync_timer is not None:
sync_timer.cancel()
sync_timer = threading.Timer(self.sync_startup_delay, self.sync)
sync_timer.daemon = True
sync_timer.start()
else:
self.sync_now(self.sync_limit)
return
self.sync_now(self.sync_limit)
def sync_now(self, limit=None):
if self.message_router.get_outbound_propagation_node() is not None:
if self.message_router.propagation_transfer_state == LXMF.LXMRouter.PR_IDLE or self.message_router.propagation_transfer_state == LXMF.LXMRouter.PR_COMPLETE:
log("LXMF - Message sync requested from propagation node " + RNS.prettyhexrep(self.message_router.get_outbound_propagation_node()) + " for " + str(self.identity), LOG_DEBUG)
self.message_router.request_messages_from_propagation_node(self.identity, max_messages = limit)
return True
else:
return False
else:
return False
def propagation_node_set(self, dest_str):
if not dest_str:
return False
if len(dest_str) != ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2):
log("LXMF - Propagation node length is invalid", LOG_ERROR)
return False
try:
dest_hash = bytes.fromhex(dest_str)
except Exception as e:
log("LXMF - Propagation node is invalid", LOG_ERROR)
return False
node_identity = RNS.Identity.recall(dest_hash)
if node_identity != None:
log("LXMF - Propagation node: " + RNS.prettyhexrep(dest_hash), LOG_INFO)
dest_hash = RNS.Destination.hash_from_name_and_identity("lxmf.propagation", node_identity)
self.message_router.set_outbound_propagation_node(dest_hash)
self.propagation_node_active = dest_str
return True
else:
log("LXMF - Propagation node identity not known", LOG_ERROR)
return False
def propagation_node_update(self, dest_str):
if self.propagation_node_hash_str() != dest_str:
if self.propagation_node_set(dest_str) and self.config_set_callback is not None:
self.config_set_callback("propagation_node_active", dest_str)
def propagation_node_hash(self):
try:
return bytes.fromhex(self.propagation_node_active)
except:
return None
def propagation_node_hash_str(self):
if self.propagation_node_active:
return self.propagation_node_active
else:
return ""
def client_connected(self, link):
log("LXMF - Client connected " + str(link), LOG_EXTREME)
link.set_resource_strategy(RNS.Link.ACCEPT_ALL)
link.set_resource_concluded_callback(self.resource_concluded)
link.set_packet_callback(self.packet_received)
def packet_received(self, lxmf_bytes, packet):
log("LXMF - Single packet delivered " + str(packet), LOG_EXTREME)
self.process_lxmf_message_bytes(lxmf_bytes)
def resource_concluded(self, resource):
log("LXMF - Resource data transfer (multi packet) delivered " + str(resource.file), LOG_EXTREME)
if resource.status == RNS.Resource.COMPLETE:
lxmf_bytes = resource.data.read()
self.process_lxmf_message_bytes(lxmf_bytes)
else:
log("LXMF - Received resource message is not complete", LOG_EXTREME)
def process_lxmf_message_bytes(self, lxmf_bytes):
try:
message = LXMF.LXMessage.unpack_from_bytes(lxmf_bytes)
except Exception as e:
log("LXMF - Could not assemble LXMF message from received data", LOG_ERROR)
log("LXMF - The contained exception was: " + str(e), LOG_ERROR)
return
message.desired_method = LXMF.LXMessage.DIRECT
self.log_message(message, "LXMF - Message received")
if self.message_received_callback is not None:
log("LXMF - Call to registered message received callback", LOG_DEBUG)
self.message_received_callback(message)
else:
log("LXMF - No message received callback registered", LOG_DEBUG)
def process_lxmf_message_propagated(self, message):
message.desired_method = LXMF.LXMessage.PROPAGATED
self.log_message(message, "LXMF - Message received")
if self.message_received_callback is not None:
log("LXMF - Call to registered message received callback", LOG_DEBUG)
self.message_received_callback(message)
else:
log("LXMF - No message received callback registered", LOG_DEBUG)
def log_message(self, message, message_tag="LXMF - Message log"):
if message.signature_validated:
signature_string = "Validated"
else:
if message.unverified_reason == LXMF.LXMessage.SIGNATURE_INVALID:
signature_string = "Invalid signature"
elif message.unverified_reason == LXMF.LXMessage.SOURCE_UNKNOWN:
signature_string = "Cannot verify, source is unknown"
else:
signature_string = "Signature is invalid, reason undetermined"
title = message.title.decode("utf-8")
content = message.content.decode("utf-8")
fields = message.fields
log(message_tag + ":", LOG_DEBUG)
log("- Date/Time: " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(message.timestamp)), LOG_DEBUG)
log("- Title: " + title, LOG_DEBUG)
log("- Content: " + content, LOG_DEBUG)
log("- Fields: " + str(fields), LOG_DEBUG)
log("- Size: " + str(len(title) + len(content) + len(title) + len(pickle.dumps(fields))) + " bytes", LOG_DEBUG)
log("- Source: " + RNS.prettyhexrep(message.source_hash), LOG_DEBUG)
log("- Destination: " + RNS.prettyhexrep(message.destination_hash), LOG_DEBUG)
log("- Signature: " + signature_string, LOG_DEBUG)
log("- Attempts: " + str(message.delivery_attempts), LOG_DEBUG)
log("- Method: " + str(message.desired_method), LOG_DEBUG)
if hasattr(message, "app_data"):
log("- App Data: " + message.app_data, LOG_DEBUG)
class LXMFPeerPropagation():
def __init__(self, owner, aspect_filter=None):
self.owner = owner
self.aspect_filter = aspect_filter
EMITTED_DELTA_GRACE = 300
EMITTED_DELTA_IGNORE = 10
def received_announce(self, destination_hash, announced_identity, app_data):
if app_data == None:
return
if len(app_data) == 0:
return
try:
unpacked = msgpack.unpackb(app_data)
if not LXMF.pn_announce_data_is_valid(unpacked):
raise ValueError("Received malformed propagation node announce")
node_active = unpacked[0]
emitted = unpacked[1]
hop_count = RNS.Transport.hops_to(destination_hash)
age = time.time() - emitted
if age < 0:
if age < -1*PropDetector.EMITTED_DELTA_GRACE:
return
log("LXMF - Received an propagation node announce from "+RNS.prettyhexrep(destination_hash)+": "+str(age)+" seconds ago, "+str(hop_count)+" hops away", LOG_INFO)
if self.owner.propagation_node_active == None:
self.owner.propagation_node_update(RNS.hexrep(destination_hash, False))
else:
prev_hop_count = RNS.Transport.hops_to(self.owner.propagation_node_hash())
if hop_count <= prev_hop_count:
self.owner.propagation_node_update(RNS.hexrep(destination_hash, False))
except:
return
##############################################################################################################
# RNS Class
class rns_connection:
def __init__(self, storage_path=None, identity_file="identity", identity=None, destination_name="rns", destination_type="connect", announce_startup=False, announce_startup_delay=0, announce_periodic=False, announce_periodic_interval=360, announce_data="", announce_hidden=False):
self.storage_path = storage_path
self.identity_file = identity_file
self.identity = identity
self.destination_name = destination_name
self.destination_type = destination_type
self.aspect_filter = self.destination_name + "." + self.destination_type
self.announce_startup = announce_startup
self.announce_startup_delay = int(announce_startup_delay)
if self.announce_startup_delay == 0:
self.announce_startup_delay = random.randint(5, 30)
self.announce_periodic = announce_periodic
self.announce_periodic_interval = int(announce_periodic_interval)
self.announce_data = announce_data
self.announce_hidden = announce_hidden
if not self.storage_path:
log("RNS - No storage_path parameter", LOG_ERROR)
return
if not os.path.isdir(self.storage_path):
os.makedirs(self.storage_path)
log("RNS - Storage path was created", LOG_NOTICE)
log("RNS - Storage path: " + self.storage_path, LOG_INFO)
if self.identity:
log("RNS - Using existing Primary Identity %s" % (str(self.identity)))
else:
if not self.identity_file:
self.identity_file = "identity"
self.identity_path = self.storage_path + "/" + self.identity_file
if os.path.isfile(self.identity_path):
try:
self.identity = RNS.Identity.from_file(self.identity_path)
if self.identity != None:
log("RNS - Loaded Primary Identity %s from %s" % (str(self.identity), self.identity_path))
else:
log("RNS - Could not load the Primary Identity from "+self.identity_path, LOG_ERROR)
except Exception as e:
log("RNS - Could not load the Primary Identity from "+self.identity_path, LOG_ERROR)
log("RNS - The contained exception was: %s" % (str(e)), LOG_ERROR)
else:
try:
log("RNS - No Primary Identity file found, creating new...")
self.identity = RNS.Identity()
self.identity.to_file(self.identity_path)
log("RNS - Created new Primary Identity %s" % (str(self.identity)))
except Exception as e:
log("RNS - Could not create and save a new Primary Identity", LOG_ERROR)
log("RNS - The contained exception was: %s" % (str(e)), LOG_ERROR)
self.destination = RNS.Destination(self.identity, RNS.Destination.IN, RNS.Destination.SINGLE, self.destination_name, self.destination_type)
self.destination.set_proof_strategy(RNS.Destination.PROVE_ALL)
if self.announce_startup or self.announce_periodic:
self.announce(initial=True)
def register_announce_callback(self, handler_function):
self.announce_callback = handler_function(self.aspect_filter)
RNS.Transport.register_announce_handler(self.announce_callback)
def destination_hash(self):
return self.destination.hash
def destination_hash_str(self):
return RNS.hexrep(self.destination.hash, False)
def destination_check(self, destination):
if type(destination) is not bytes:
if len(destination) == ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2)+2:
destination = destination[1:-1]
if len(destination) != ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2):
log("RNS - Destination length is invalid", LOG_ERROR)
return False
try:
destination = bytes.fromhex(destination)
except Exception as e:
log("RNS - Destination is invalid", LOG_ERROR)
return False
return True
def destination_correct(self, destination):
if type(destination) is not bytes:
if len(destination) == ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2)+2:
destination = destination[1:-1]
if len(destination) != ((RNS.Reticulum.TRUNCATED_HASHLENGTH//8)*2):
return ""
try:
destination_bytes = bytes.fromhex(destination)
return destination
except Exception as e:
return ""
return ""
def announce(self, app_data=None, attached_interface=None, initial=False):
announce_timer = None
if self.announce_periodic and self.announce_periodic_interval > 0:
announce_timer = threading.Timer(self.announce_periodic_interval*60, self.announce)
announce_timer.daemon = True
announce_timer.start()
if initial:
if self.announce_startup:
if self.announce_startup_delay > 0:
if announce_timer is not None:
announce_timer.cancel()
announce_timer = threading.Timer(self.announce_startup_delay, self.announce)
announce_timer.daemon = True
announce_timer.start()
else:
self.announce_now(app_data=app_data, attached_interface=attached_interface)
return
self.announce_now(app_data=app_data, attached_interface=attached_interface)
def announce_now(self, app_data=None, attached_interface=None):
if self.announce_hidden:
self.destination.announce("".encode("utf-8"), attached_interface=attached_interface)
log("RNS - Announced: " + RNS.prettyhexrep(self.destination_hash()) +" (Hidden)", LOG_DEBUG)
elif app_data != None:
if isinstance(app_data, str):
self.destination.announce(app_data.encode("utf-8"), attached_interface=attached_interface)
log("RNS - Announced: " + RNS.prettyhexrep(self.destination_hash()) +": " + app_data, LOG_DEBUG)
else:
self.destination.announce(app_data, attached_interface=attached_interface)
log("RNS - Announced: " + RNS.prettyhexrep(self.destination_hash()), LOG_DEBUG)
else:
if isinstance(self.announce_data, str):
self.destination.announce(self.announce_data.encode("utf-8"), attached_interface=attached_interface)
log("RNS - Announced: " + RNS.prettyhexrep(self.destination_hash()) +": " + self.announce_data, LOG_DEBUG)
else:
self.destination.announce(self.announce_data, attached_interface=attached_interface)
log("RNS - Announced: " + RNS.prettyhexrep(self.destination_hash()), LOG_DEBUG)
##############################################################################################################
# LXMF Functions
#### LXMF - Announce ####
class lxmf_announce_callback:
def __init__(self, aspect_filter=None):
self.aspect_filter = aspect_filter
@staticmethod
def received_announce(destination_hash, announced_identity, app_data):
if app_data == None:
return
if len(app_data) == 0:
return
try:
if (app_data[0] >= 0x90 and app_data[0] <= 0x9f) or app_data[0] == 0xdc:
app_data = msgpack.unpackb(app_data)
if isinstance(app_data, list):
if len(app_data) > 2 and app_data[2] != None and isinstance(app_data[2], dict):
if MSG_FIELD_TYPE in app_data[2]:
denys = config_getarray(CONFIG, "lxmf", "announce_deny_type")
if len(denys) > 0:
if "*" in denys:
return
for deny in denys:
if app_data[2][MSG_FIELD_TYPE] == deny:
return
if len(app_data) > 1 and app_data[0] != None:
app_data = app_data[0]
else:
app_data = b""
else:
app_data = b""
except:
app_data = b""
try:
app_data = app_data.decode("utf-8")
except:
return
log("LXMF - Received an announce from " + RNS.prettyhexrep(destination_hash) + ": " + app_data, LOG_INFO)
global DATA
lng_key = "-" + CONFIG["main"]["lng"]
sections = []
for (key, val) in CONFIG.items("rights"):
if DATA.has_section(key):
sections.append(key)
if DATA["main"].getboolean("auto_add_user_announce"):
source_hash = RNS.hexrep(destination_hash, False)
exist = False
hop_count = RNS.Transport.hops_to(destination_hash)
hop_min = DATA.getint("main", "auto_add_user_announce_hop_min")
hop_max = DATA.getint("main", "auto_add_user_announce_hop_max")
if hop_min > 0 and hop_count < hop_min:
exist = True
if hop_max > 0 and hop_count < hop_max:
exist = True
for section in DATA.sections():
for (key, val) in DATA.items(section):
if key == source_hash:
exist = True
break
if exist:
break
if not exist:
source_right = DATA["main"]["auto_add_user_type"]
if DATA.has_section(source_right) and source_right != "main":
if CONFIG["main"].getboolean("auto_name_add"):
source_name = app_data
else:
source_name = ""
DATA[source_right][source_hash] = source_name
content = config_get(CONFIG, "interface_messages", "auto_add_"+source_right, "", lng_key)
content_group = config_get(CONFIG, "interface_messages", "member_join", "", lng_key)
content_group = replace(content_group, source_hash, source_name, source_right, lng_key)
fields = fields_generate(src_hash=destination_hash, src_name=source_name, members=True, result_key="join", lng_key=lng_key)
for section in sections:
if "receive_join" in config_get(CONFIG, "rights", section).split(","):
for (key, val) in DATA.items(section):
if key != source_hash:
LXMF_PEER.send(key, content_group, "", fields, None, "interface_send")
if CONFIG["main"].getboolean("auto_save_data"):
DATA.remove_option("main", "unsaved")
if not data_save(PATH + "/data.cfg"):
DATA["main"]["unsaved"] = "True"
else:
DATA["main"]["unsaved"] = "True"
content = replace(content, source_hash, source_name, source_right, lng_key)
LXMF_PEER.send(source_hash, content, "", fields_generate(members=True, data=True, cmd=source_right, config=source_right, result_key="join", lng_key=lng_key), None, "interface_send")
return
elif source_right == "":
log("LXMF - Source " + RNS.prettyhexrep(message.source_hash) + " not exist (auto add disabled)", LOG_DEBUG)
return
if CONFIG["main"].getboolean("auto_name_def") or CONFIG["main"].getboolean("auto_name_change"):
source_hash = RNS.hexrep(destination_hash, False)
for section in DATA.sections():
for (key, val) in DATA.items(section):
if key == source_hash:
if (val == "" and CONFIG["main"].getboolean("auto_name_def")) or (val != "" and CONFIG["main"].getboolean("auto_name_change")):
value = app_data
if value != DATA[section][key]:
if DATA[section][key] == "":