-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
blocking.py
2171 lines (1956 loc) · 80.8 KB
/
blocking.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
__filename__ = "blocking.py"
__author__ = "Bob Mottram"
__license__ = "AGPL3+"
__version__ = "1.5.0"
__maintainer__ = "Bob Mottram"
__email__ = "[email protected]"
__status__ = "Production"
__module_group__ = "Core"
import os
import json
import time
from session import get_json_valid
from session import create_session
from flags import is_evil
from utils import get_user_paths
from utils import contains_statuses
from utils import data_dir
from utils import string_contains
from utils import date_from_string_format
from utils import date_utcnow
from utils import remove_eol
from utils import has_object_string
from utils import has_object_string_object
from utils import has_object_string_type
from utils import remove_domain_port
from utils import has_object_dict
from utils import is_account_dir
from utils import get_cached_post_filename
from utils import load_json
from utils import save_json
from utils import file_last_modified
from utils import set_config_param
from utils import has_users_path
from utils import get_full_domain
from utils import remove_id_ending
from utils import locate_post
from utils import evil_incarnate
from utils import get_domain_from_actor
from utils import get_nickname_from_actor
from utils import acct_dir
from utils import local_actor_url
from utils import has_actor
from utils import text_in_file
from utils import get_actor_from_post
from conversation import mute_conversation
from conversation import unmute_conversation
from auth import create_basic_auth_header
from session import get_json
def get_global_block_reason(search_text: str,
blocking_reasons_filename: str) -> str:
"""Returns the reason why a domain was globally blocked
"""
if not text_in_file(search_text, blocking_reasons_filename):
return ''
reasons_str = ''
try:
with open(blocking_reasons_filename, 'r',
encoding='utf-8') as fp_reas:
reasons_str = fp_reas.read()
except OSError:
print('WARN: Failed to read blocking reasons ' +
blocking_reasons_filename)
if not reasons_str:
return ''
reasons_lines = reasons_str.split('\n')
for line in reasons_lines:
if line.startswith(search_text):
if ' ' in line:
return line.split(' ', 1)[1]
return ''
def get_account_blocks(base_dir: str,
nickname: str, domain: str) -> str:
"""Return the text for the textarea for "blocked accounts"
when editing profile
"""
account_directory = acct_dir(base_dir, nickname, domain)
blocking_filename = \
account_directory + '/blocking.txt'
blocking_reasons_filename = \
account_directory + '/blocking_reasons.txt'
if not os.path.isfile(blocking_filename):
return ''
blocked_accounts_textarea = ''
blocking_file_text = ''
try:
with open(blocking_filename, 'r', encoding='utf-8') as fp_block:
blocking_file_text = fp_block.read()
except OSError:
print('EX: Failed to read account blocks ' + blocking_filename)
return ''
blocklist = blocking_file_text.split('\n')
for handle in blocklist:
handle = handle.strip()
if not handle:
continue
reason = \
get_global_block_reason(handle,
blocking_reasons_filename)
if reason:
blocked_accounts_textarea += \
handle + ' - ' + reason + '\n'
continue
blocked_accounts_textarea += handle + '\n'
return blocked_accounts_textarea
def blocked_timeline_json(actor: str, page_number: int, items_per_page: int,
base_dir: str,
nickname: str, domain: str) -> {}:
"""Returns blocked collection for an account
https://codeberg.org/fediverse/fep/src/branch/main/fep/c648/fep-c648.md
"""
blocked_accounts_textarea = \
get_account_blocks(base_dir, nickname, domain)
blocked_list = []
if blocked_accounts_textarea:
blocked_list = blocked_accounts_textarea.split('\n')
start_index = (page_number - 1) * items_per_page
if start_index >= len(blocked_list):
start_index = 0
last_page_number = (len(blocked_list) / items_per_page) + 1
result_json = {
"@context": [
'https://www.w3.org/ns/activitystreams',
'https://w3id.org/security/v1',
"https://purl.archive.org/socialweb/blocked"
],
"id": actor + '?page=' + str(page_number),
"first": actor + '?page=1',
"last": actor + '?page=' + str(last_page_number),
"type": "OrderedCollection",
"name": nickname + "'s Blocked Collection",
"orderedItems": []
}
index = start_index
for _ in range(items_per_page):
if index >= len(blocked_list):
break
block_handle = blocked_list[index]
block_reason = ''
if ' - ' in block_handle:
block_reason = block_handle.split(' - ')[1]
block_handle = block_handle.split(' - ')[0]
block_type = "Person"
if block_handle.startswith('*@'):
block_type = "Application"
block_handle = block_handle.split('*@', 1)[1]
block_json = {
"type": "Block",
"id": actor + '/' + str(index),
"object": {
"type": block_type,
"id": block_handle
}
}
if block_reason:
block_json["object"]["name"] = block_reason
result_json["orderedItems"].append(block_json)
index += 1
return result_json
def add_account_blocks(base_dir: str,
nickname: str, domain: str,
blocked_accounts_textarea: str) -> bool:
"""Update the blockfile for an account after editing their
profile and changing "blocked accounts"
"""
if blocked_accounts_textarea is None:
return False
blocklist = blocked_accounts_textarea.split('\n')
blocking_file_text = ''
blocking_reasons_file_text = ''
for line in blocklist:
line = line.strip()
reason = None
if ' - ' in line:
block_id = line.split(' - ', 1)[0]
reason = line.split(' - ', 1)[1]
blocking_reasons_file_text += block_id + ' ' + reason + '\n'
elif ' ' in line:
block_id = line.split(' ', 1)[0]
reason = line.split(' ', 1)[1]
blocking_reasons_file_text += block_id + ' ' + reason + '\n'
else:
block_id = line
blocking_file_text += block_id + '\n'
account_directory = acct_dir(base_dir, nickname, domain)
blocking_filename = \
account_directory + '/blocking.txt'
blocking_reasons_filename = \
account_directory + '/blocking_reasons.txt'
if not blocking_file_text:
if os.path.isfile(blocking_filename):
try:
os.remove(blocking_filename)
except OSError:
print('EX: _profile_edit unable to delete blocking ' +
blocking_filename)
if os.path.isfile(blocking_reasons_filename):
try:
os.remove(blocking_reasons_filename)
except OSError:
print('EX: _profile_edit unable to delete blocking reasons' +
blocking_reasons_filename)
return True
try:
with open(blocking_filename, 'w+', encoding='utf-8') as fp_block:
fp_block.write(blocking_file_text)
except OSError:
print('EX: Failed to write ' + blocking_filename)
try:
with open(blocking_reasons_filename, 'w+',
encoding='utf-8') as fp_block:
fp_block.write(blocking_reasons_file_text)
except OSError:
print('EX: Failed to write ' + blocking_reasons_filename)
return True
def _add_global_block_reason(base_dir: str,
block_nickname: str, block_domain: str,
reason: str) -> bool:
"""Store a global block reason
"""
if not reason:
return False
blocking_reasons_filename = \
data_dir(base_dir) + '/blocking_reasons.txt'
if not block_nickname.startswith('#'):
# is the handle already blocked?
block_id = block_nickname + '@' + block_domain
else:
block_id = block_nickname
reason = reason.replace('\n', '').strip()
reason_line = block_id + ' ' + reason + '\n'
if os.path.isfile(blocking_reasons_filename):
if not text_in_file(block_id,
blocking_reasons_filename):
try:
with open(blocking_reasons_filename, 'a+',
encoding='utf-8') as fp_reas:
fp_reas.write(reason_line)
except OSError:
print('EX: unable to add blocking reason ' +
block_id)
else:
reasons_str = ''
try:
with open(blocking_reasons_filename, 'r',
encoding='utf-8') as fp_reas:
reasons_str = fp_reas.read()
except OSError:
print('EX: unable to read blocking reasons')
reasons_lines = reasons_str.split('\n')
new_reasons_str = ''
for line in reasons_lines:
if not line.startswith(block_id + ' '):
new_reasons_str += line + '\n'
continue
new_reasons_str += reason_line
try:
with open(blocking_reasons_filename, 'w+',
encoding='utf-8') as fp_reas:
fp_reas.write(new_reasons_str)
except OSError:
print('EX: unable to save blocking reasons' +
blocking_reasons_filename)
else:
try:
with open(blocking_reasons_filename, 'w+',
encoding='utf-8') as fp_reas:
fp_reas.write(reason_line)
except OSError:
print('EX: unable to save blocking reason ' +
block_id + ' ' + blocking_reasons_filename)
return True
def add_global_block(base_dir: str,
block_nickname: str, block_domain: str,
reason: str) -> bool:
"""Global block which applies to all accounts
"""
_add_global_block_reason(base_dir,
block_nickname, block_domain,
reason)
blocking_filename = data_dir(base_dir) + '/blocking.txt'
if not block_nickname.startswith('#'):
# is the handle already blocked?
block_handle = block_nickname + '@' + block_domain
if os.path.isfile(blocking_filename):
if text_in_file(block_handle, blocking_filename):
return False
# block an account handle or domain
try:
with open(blocking_filename, 'a+', encoding='utf-8') as fp_block:
fp_block.write(block_handle + '\n')
except OSError:
print('EX: unable to save blocked handle ' + block_handle)
return False
else:
block_hashtag = block_nickname
# is the hashtag already blocked?
if os.path.isfile(blocking_filename):
if text_in_file(block_hashtag + '\n', blocking_filename):
return False
# block a hashtag
try:
with open(blocking_filename, 'a+', encoding='utf-8') as fp_block:
fp_block.write(block_hashtag + '\n')
except OSError:
print('EX: unable to save blocked hashtag ' + block_hashtag)
return False
return True
def _add_block_reason(base_dir: str,
nickname: str, domain: str,
block_nickname: str, block_domain: str,
reason: str) -> bool:
"""Store an account level block reason
"""
if not reason:
return False
domain = remove_domain_port(domain)
blocking_reasons_filename = \
acct_dir(base_dir, nickname, domain) + '/blocking_reasons.txt'
if not block_nickname.startswith('#'):
# is the handle already blocked?
block_id = block_nickname + '@' + block_domain
else:
block_id = block_nickname
reason = reason.replace('\n', '').strip()
reason_line = block_id + ' ' + reason + '\n'
if os.path.isfile(blocking_reasons_filename):
if not text_in_file(block_id,
blocking_reasons_filename):
try:
with open(blocking_reasons_filename, 'a+',
encoding='utf-8') as fp_reas:
fp_reas.write(reason_line)
except OSError:
print('EX: unable to add blocking reason 2 ' +
block_id)
else:
reasons_str = ''
try:
with open(blocking_reasons_filename, 'r',
encoding='utf-8') as fp_reas:
reasons_str = fp_reas.read()
except OSError:
print('EX: unable to read blocking reasons 2')
reasons_lines = reasons_str.split('\n')
new_reasons_str = ''
for line in reasons_lines:
if not line.startswith(block_id + ' '):
new_reasons_str += line + '\n'
continue
new_reasons_str += reason_line
try:
with open(blocking_reasons_filename, 'w+',
encoding='utf-8') as fp_reas:
fp_reas.write(new_reasons_str)
except OSError:
print('EX: unable to save blocking reasons 2' +
blocking_reasons_filename)
else:
try:
with open(blocking_reasons_filename, 'w+',
encoding='utf-8') as fp_reas:
fp_reas.write(reason_line)
except OSError:
print('EX: unable to save blocking reason 2 ' +
block_id + ' ' + blocking_reasons_filename)
return True
def add_block(base_dir: str, nickname: str, domain: str,
block_nickname: str, block_domain: str,
reason: str) -> bool:
"""Block the given account
"""
if block_domain.startswith(domain) and nickname == block_nickname:
# don't block self
return False
domain = remove_domain_port(domain)
blocking_filename = acct_dir(base_dir, nickname, domain) + '/blocking.txt'
block_handle = block_nickname + '@' + block_domain
if os.path.isfile(blocking_filename):
if text_in_file(block_handle + '\n', blocking_filename):
return False
# if we are following then unfollow
following_filename = \
acct_dir(base_dir, nickname, domain) + '/following.txt'
if os.path.isfile(following_filename):
if text_in_file(block_handle + '\n', following_filename):
following_str = ''
try:
with open(following_filename, 'r',
encoding='utf-8') as fp_foll:
following_str = fp_foll.read()
except OSError:
print('EX: Unable to read following ' + following_filename)
return False
if following_str:
following_str = following_str.replace(block_handle + '\n', '')
try:
with open(following_filename, 'w+',
encoding='utf-8') as fp_foll:
fp_foll.write(following_str)
except OSError:
print('EX: Unable to write following ' + following_str)
return False
# if they are a follower then remove them
followers_filename = \
acct_dir(base_dir, nickname, domain) + '/followers.txt'
if os.path.isfile(followers_filename):
if text_in_file(block_handle + '\n', followers_filename):
followers_str = ''
try:
with open(followers_filename, 'r',
encoding='utf-8') as fp_foll:
followers_str = fp_foll.read()
except OSError:
print('EX: Unable to read followers ' + followers_filename)
return False
if followers_str:
followers_str = followers_str.replace(block_handle + '\n', '')
try:
with open(followers_filename, 'w+',
encoding='utf-8') as fp_foll:
fp_foll.write(followers_str)
except OSError:
print('EX: Unable to write followers ' + followers_str)
return False
try:
with open(blocking_filename, 'a+', encoding='utf-8') as fp_block:
fp_block.write(block_handle + '\n')
except OSError:
print('EX: unable to append block handle ' + block_handle)
return False
if reason:
_add_block_reason(base_dir, nickname, domain,
block_nickname, block_domain, reason)
return True
def _remove_global_block_reason(base_dir: str,
unblock_nickname: str,
unblock_domain: str) -> bool:
"""Remove a globla block reason
"""
unblocking_filename = data_dir(base_dir) + '/blocking_reasons.txt'
if not os.path.isfile(unblocking_filename):
return False
if not unblock_nickname.startswith('#'):
unblock_id = unblock_nickname + '@' + unblock_domain
else:
unblock_id = unblock_nickname
if not text_in_file(unblock_id + ' ', unblocking_filename):
return False
reasons_str = ''
try:
with open(unblocking_filename, 'r',
encoding='utf-8') as fp_reas:
reasons_str = fp_reas.read()
except OSError:
print('EX: unable to read blocking reasons 3')
reasons_lines = reasons_str.split('\n')
new_reasons_str = ''
for line in reasons_lines:
if line.startswith(unblock_id + ' '):
continue
new_reasons_str += line + '\n'
try:
with open(unblocking_filename, 'w+',
encoding='utf-8') as fp_reas:
fp_reas.write(new_reasons_str)
except OSError:
print('EX: unable to save blocking reasons 2' +
unblocking_filename)
return True
def remove_global_block(base_dir: str,
unblock_nickname: str,
unblock_domain: str) -> bool:
"""Unblock the given global block
"""
_remove_global_block_reason(base_dir,
unblock_nickname,
unblock_domain)
unblocking_filename = data_dir(base_dir) + '/blocking.txt'
if not unblock_nickname.startswith('#'):
unblock_handle = unblock_nickname + '@' + unblock_domain
if os.path.isfile(unblocking_filename):
if text_in_file(unblock_handle, unblocking_filename):
try:
with open(unblocking_filename, 'r',
encoding='utf-8') as fp_unblock:
with open(unblocking_filename + '.new', 'w+',
encoding='utf-8') as fpnew:
for line in fp_unblock:
handle = remove_eol(line)
if unblock_handle not in line:
fpnew.write(handle + '\n')
except OSError as ex:
print('EX: failed to remove global block ' +
unblocking_filename + ' ' + str(ex))
return False
if os.path.isfile(unblocking_filename + '.new'):
try:
os.rename(unblocking_filename + '.new',
unblocking_filename)
except OSError:
print('EX: remove_global_block unable to rename ' +
unblocking_filename)
return False
return True
else:
unblock_hashtag = unblock_nickname
if os.path.isfile(unblocking_filename):
if text_in_file(unblock_hashtag + '\n', unblocking_filename):
try:
with open(unblocking_filename, 'r',
encoding='utf-8') as fp_unblock:
with open(unblocking_filename + '.new', 'w+',
encoding='utf-8') as fpnew:
for line in fp_unblock:
block_line = remove_eol(line)
if unblock_hashtag not in line:
fpnew.write(block_line + '\n')
except OSError as ex:
print('EX: failed to remove global hashtag block ' +
unblocking_filename + ' ' + str(ex))
return False
if os.path.isfile(unblocking_filename + '.new'):
try:
os.rename(unblocking_filename + '.new',
unblocking_filename)
except OSError:
print('EX: remove_global_block unable to rename 2 ' +
unblocking_filename)
return False
return True
return False
def remove_block(base_dir: str, nickname: str, domain: str,
unblock_nickname: str, unblock_domain: str) -> bool:
"""Unblock the given account
"""
domain = remove_domain_port(domain)
unblocking_filename = \
acct_dir(base_dir, nickname, domain) + '/blocking.txt'
unblock_handle = unblock_nickname + '@' + unblock_domain
if os.path.isfile(unblocking_filename):
if text_in_file(unblock_handle, unblocking_filename):
try:
with open(unblocking_filename, 'r',
encoding='utf-8') as fp_unblock:
with open(unblocking_filename + '.new', 'w+',
encoding='utf-8') as fpnew:
for line in fp_unblock:
handle = remove_eol(line)
if unblock_handle not in line:
fpnew.write(handle + '\n')
except OSError as ex:
print('EX: failed to remove block ' +
unblocking_filename + ' ' + str(ex))
return False
if os.path.isfile(unblocking_filename + '.new'):
try:
os.rename(unblocking_filename + '.new',
unblocking_filename)
except OSError:
print('EX: remove_block unable to rename 3 ' +
unblocking_filename)
return False
return True
return False
def is_blocked_hashtag(base_dir: str, hashtag: str) -> bool:
"""Is the given hashtag blocked?
"""
# avoid very long hashtags
if len(hashtag) > 32:
return True
global_blocking_filename = data_dir(base_dir) + '/blocking.txt'
if os.path.isfile(global_blocking_filename):
hashtag = hashtag.strip('\n').strip('\r')
if not hashtag.startswith('#'):
hashtag = '#' + hashtag
if text_in_file(hashtag + '\n', global_blocking_filename):
return True
return False
def get_domain_blocklist(base_dir: str) -> str:
"""Returns all globally blocked domains as a string
This can be used for fast matching to mitigate flooding
"""
blocked_str = ''
evil_domains = evil_incarnate()
for evil in evil_domains:
blocked_str += evil + '\n'
global_blocking_filename = data_dir(base_dir) + '/blocking.txt'
if not os.path.isfile(global_blocking_filename):
return blocked_str
try:
with open(global_blocking_filename, 'r',
encoding='utf-8') as fp_blocked:
blocked_str += fp_blocked.read()
except OSError:
print('EX: get_domain_blocklist unable to read ' +
global_blocking_filename)
return blocked_str
def update_blocked_cache(base_dir: str,
blocked_cache: [],
blocked_cache_last_updated: int,
blocked_cache_update_secs: int) -> int:
"""Updates the cache of globally blocked domains held in memory
"""
curr_time = int(time.time())
if blocked_cache_last_updated > curr_time:
print('WARN: Cache updated in the future')
blocked_cache_last_updated = 0
seconds_since_last_update = curr_time - blocked_cache_last_updated
if seconds_since_last_update < blocked_cache_update_secs:
return blocked_cache_last_updated
global_blocking_filename = data_dir(base_dir) + '/blocking.txt'
if not os.path.isfile(global_blocking_filename):
return blocked_cache_last_updated
try:
with open(global_blocking_filename, 'r',
encoding='utf-8') as fp_blocked:
blocked_lines = fp_blocked.readlines()
# remove newlines
for index, _ in enumerate(blocked_lines):
blocked_lines[index] = remove_eol(blocked_lines[index])
# update the cache
blocked_cache.clear()
blocked_cache += blocked_lines
except OSError as ex:
print('EX: update_blocked_cache unable to read ' +
global_blocking_filename + ' ' + str(ex))
return curr_time
def _get_short_domain(domain: str) -> str:
""" by checking a shorter version we can thwart adversaries
who constantly change their subdomain
e.g. subdomain123.mydomain.com becomes mydomain.com
"""
sections = domain.split('.')
no_of_sections = len(sections)
if no_of_sections > 2:
return sections[no_of_sections-2] + '.' + sections[-1]
return None
def is_blocked_domain(base_dir: str, domain: str,
blocked_cache: [],
block_federated: []) -> bool:
"""Is the given domain blocked?
"""
if '.' not in domain:
return False
if is_evil(domain):
return True
short_domain = _get_short_domain(domain)
search_str = '*@' + domain
if not broch_mode_is_active(base_dir):
if block_federated:
if domain in block_federated:
return True
if blocked_cache:
for blocked_str in blocked_cache:
if blocked_str == search_str:
return True
if short_domain:
if blocked_str == '*@' + short_domain:
return True
else:
# instance block list
global_blocking_filename = data_dir(base_dir) + '/blocking.txt'
if os.path.isfile(global_blocking_filename):
search_str += '\n'
search_str_short = None
if short_domain:
search_str_short = '*@' + short_domain + '\n'
try:
with open(global_blocking_filename, 'r',
encoding='utf-8') as fp_blocked:
blocked_str = fp_blocked.read()
if search_str in blocked_str:
return True
if short_domain:
if search_str_short in blocked_str:
return True
except OSError as ex:
print('EX: is_blocked_domain unable to read ' +
global_blocking_filename + ' ' + str(ex))
else:
allow_filename = data_dir(base_dir) + '/allowedinstances.txt'
# instance allow list
if not short_domain:
if not text_in_file(domain, allow_filename):
return True
else:
if not text_in_file(short_domain, allow_filename):
return True
return False
def is_blocked_nickname(base_dir: str, nickname: str,
blocked_cache: [] = None) -> bool:
"""Is the given nickname blocked?
"""
search_str = nickname + '@*'
if blocked_cache:
for blocked_str in blocked_cache:
if blocked_str == search_str:
return True
else:
# instance-wide block list
global_blocking_filename = data_dir(base_dir) + '/blocking.txt'
if os.path.isfile(global_blocking_filename):
search_str += '\n'
try:
with open(global_blocking_filename, 'r',
encoding='utf-8') as fp_blocked:
blocked_str = fp_blocked.read()
if search_str in blocked_str:
return True
except OSError as ex:
print('EX: is_blocked_nickname unable to read ' +
global_blocking_filename + ' ' + str(ex))
return False
def is_blocked(base_dir: str, nickname: str, domain: str,
block_nickname: str, block_domain: str,
blocked_cache: [],
block_federated: []) -> bool:
"""Is the given account blocked?
"""
if is_evil(block_domain):
return True
block_handle = None
if block_nickname and block_domain:
block_handle = block_nickname + '@' + block_domain
if not broch_mode_is_active(base_dir):
# instance level block list
if block_federated:
for blocked_str in block_federated:
if '@' in blocked_str or '://' in blocked_str:
if block_handle:
if blocked_str == block_handle:
return True
elif blocked_str == block_domain:
return True
if blocked_cache:
for blocked_str in blocked_cache:
if block_nickname:
if block_nickname + '@*' in blocked_str:
return True
if block_domain:
if '*@' + block_domain in blocked_str:
return True
if block_handle:
if blocked_str == block_handle:
return True
else:
global_blocks_filename = data_dir(base_dir) + '/blocking.txt'
if os.path.isfile(global_blocks_filename):
if block_nickname:
if text_in_file(block_nickname + '@*\n',
global_blocks_filename):
return True
if text_in_file('*@' + block_domain, global_blocks_filename):
return True
if block_handle:
block_str = block_handle + '\n'
if text_in_file(block_str, global_blocks_filename):
return True
if not block_federated:
federated_blocks_filename = \
data_dir(base_dir) + '/block_api.txt'
if os.path.isfile(federated_blocks_filename):
block_federated = []
try:
with open(federated_blocks_filename, 'r',
encoding='utf-8') as fp_fed:
block_federated = fp_fed.read().split('\n')
except OSError:
print('EX: is_blocked unable to load ' +
federated_blocks_filename)
if block_domain in block_federated:
return True
if block_handle:
if block_handle in block_federated:
return True
else:
# instance allow list
allow_filename = data_dir(base_dir) + '/allowedinstances.txt'
short_domain = _get_short_domain(block_domain)
if not short_domain and block_domain:
if not text_in_file(block_domain + '\n', allow_filename):
return True
else:
if not text_in_file(short_domain + '\n', allow_filename):
return True
# account level allow list
account_dir = acct_dir(base_dir, nickname, domain)
allow_filename = account_dir + '/allowedinstances.txt'
if block_domain and os.path.isfile(allow_filename):
if not text_in_file(block_domain + '\n', allow_filename):
return True
# account level block list
blocking_filename = account_dir + '/blocking.txt'
if os.path.isfile(blocking_filename):
if block_nickname:
if text_in_file(block_nickname + '@*\n', blocking_filename):
return True
if block_domain:
if text_in_file('*@' + block_domain + '\n', blocking_filename):
return True
if block_handle:
if text_in_file(block_handle + '\n', blocking_filename):
return True
return False
def allowed_announce(base_dir: str, nickname: str, domain: str,
block_nickname: str, block_domain: str,
announce_blocked_cache: [] = None) -> bool:
"""Is the given nickname allowed to send announces?
"""
block_handle = None
if block_nickname and block_domain:
block_handle = block_nickname + '@' + block_domain
# cached announce blocks
if announce_blocked_cache:
for blocked_str in announce_blocked_cache:
if block_nickname:
if block_nickname + '@*' in blocked_str:
return False
if block_domain:
if '*@' + block_domain in blocked_str:
return False
if block_handle:
if blocked_str == block_handle:
return False
# non-cached instance level announce blocks
global_announce_blocks_filename = \
data_dir(base_dir) + '/noannounce.txt'
if os.path.isfile(global_announce_blocks_filename):
if block_nickname:
if text_in_file(block_nickname + '@*',
global_announce_blocks_filename, False):
return False
if block_domain:
if text_in_file('*@' + block_domain,
global_announce_blocks_filename, False):
return False
if block_handle:
block_str = block_handle + '\n'
if text_in_file(block_str,
global_announce_blocks_filename, False):
return False
# non-cached account level announce blocks
account_dir = acct_dir(base_dir, nickname, domain)
blocking_filename = account_dir + '/noannounce.txt'
if os.path.isfile(blocking_filename):
if block_nickname:
if text_in_file(block_nickname + '@*\n',
blocking_filename, False):
return False
if block_domain:
if text_in_file('*@' + block_domain + '\n',
blocking_filename, False):
return False
if block_handle:
if text_in_file(block_handle + '\n', blocking_filename, False):
return False
return True
def allowed_announce_add(base_dir: str, nickname: str, domain: str,
following_nickname: str,
following_domain: str) -> None:
"""Allow announces for a handle
"""
account_dir = acct_dir(base_dir, nickname, domain)
blocking_filename = account_dir + '/noannounce.txt'
# if the noannounce.txt file doesn't yet exist
if not os.path.isfile(blocking_filename):
return
handle = following_nickname + '@' + following_domain
if text_in_file(handle + '\n', blocking_filename, False):
file_text = ''
try:
with open(blocking_filename, 'r',
encoding='utf-8') as fp_noannounce:
file_text = fp_noannounce.read()
except OSError:
print('EX: unable to read noannounce add: ' +
blocking_filename + ' ' + handle)
new_file_text = ''
file_text_list = file_text.split('\n')
handle_lower = handle.lower()
for allowed in file_text_list:
if allowed.lower() != handle_lower:
new_file_text += allowed + '\n'
file_text = new_file_text
try:
with open(blocking_filename, 'w+',
encoding='utf-8') as fp_noannounce:
fp_noannounce.write(file_text)
except OSError:
print('EX: unable to write noannounce add: ' +
blocking_filename + ' ' + handle)
def allowed_announce_remove(base_dir: str, nickname: str, domain: str,
following_nickname: str,
following_domain: str) -> None:
"""Don't allow announces from a handle
"""
account_dir = acct_dir(base_dir, nickname, domain)
blocking_filename = account_dir + '/noannounce.txt'
handle = following_nickname + '@' + following_domain