forked from hyphanet/pyFreenet
-
Notifications
You must be signed in to change notification settings - Fork 4
/
babcom_cli
executable file
·2123 lines (1815 loc) · 89.9 KB
/
babcom_cli
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
# encoding: utf-8
# babcom.py --- Implementation of Freenet Communication Primitives
# Copyright (C) 2016 Arne Babenhauserheide <[email protected]>
# Copyright (C) 2013 Steve Dougherty (Freemail and WoT concepts)
# Author: Arne Babenhauserheide <[email protected]>
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Implementation of Freenet Commmunication Primitives"""
import sys
import os
import glob
import time
import datetime
import shutil
import stat
import zipfile
import urllib.request
import subprocess
import argparse # commandline arguments
import cmd # interactive shell
import getpass
import fcp3 as fcp
import freenet3 as freenet
import freenet3.appdirs as appdirs
import random
import threading # TODO: replace by futures for Python3
import concurrent.futures
import logging
import functools
import hashlib
import smtplib
from email.mime.text import MIMEText
import imaplib
import base64
import re
try:
import passlib.hash as passlib_hash
except ImportError:
import freenet_passlib_170.hash as passlib_hash
try:
import newbase60
numtostring = newbase60.numtosxg
except Exception:
numtostring = str
if "--debug" in sys.argv:
logging.basicConfig(level=logging.DEBUG,
format=' [%(levelname)-7s] (%(asctime)s) %(filename)s::%(lineno)d %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
else:
logging.basicConfig(level=logging.WARNING,
format=' [%(levelname)-7s] %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
PY3 = sys.version_info > (3,)
slowtests = False
in_doctest = False
# first, parse commandline arguments
def parse_args():
"""Parse commandline arguments."""
parser = argparse.ArgumentParser(description="Implementation of Freenet Communication Primitives")
parser.add_argument('-u', '--user', default=None, help="Identity to use (default: create new)")
parser.add_argument('--recover', action='store_true', help="Recover an identity from its recovery secret")
parser.add_argument('--host', default=None, help="Freenet host address (default: 127.0.0.1)")
parser.add_argument('--port', default=None, help="Freenet FCP port (default: random, or 9481 if using --no-spawn)")
parser.add_argument('--verbosity', default=None, help="Set verbosity. For tests any verbosity activates verbose tests (default: 3, to FCP calls: 5)")
parser.add_argument('--debug', action="store_true", help="Show debug messages and use more debug-friendly output.")
parser.add_argument('--transient', default=False, action="store_true", help="Do not store any data in babcom (to preserve data in the node, use --no-spawn)")
parser.add_argument('--no-spawn', default=False, action="store_true", help="Do not spawn a Freenet node: Use an existing node at the given --port instead.")
parser.add_argument('--spawn', default=True, action="store_true", help="Spawn a freenet node. If the fcp-port is given, and no node is active at that port, spawn with the given FCP port. Otherwise spawn with a random port (option active by default, kept for backwards compatibility. Use --no-spawn to disable).")
parser.add_argument('--test', default=False, action="store_true", help="Run the tests")
parser.add_argument('--slowtests', default=False, action="store_true", help="Run slow tests, many of them with actual network operation in Freenet")
args = parser.parse_args()
return args
# then prepare giving progress
def withprogress(func):
"""Provide progress, if we are the main thread (blocking others)"""
@functools.wraps(func)
def fun(*args, **kwds):
# avoid giving progress when we’re not the main thread
if not isinstance(threading.current_thread(), threading._MainThread):
return func(*args, **kwds)
# also avoid progress when running in doctests, from https://stackoverflow.com/a/22734497
if in_doctest:
return func(*args, **kwds)
def waiting(letter):
def w():
sys.stderr.write(letter)
sys.stderr.flush()
return w
def funcinfo(fun):
_n = func.__name__
return "".join(["[",
_n[:2],
hashlib.sha256(_n.encode("utf-8")).hexdigest()[:1],
_n[-2:],
"]"])
tasks = []
# start with the function name
tasks.append(threading.Timer(0.9, waiting(funcinfo(func))))
# one per second for 20 seconds
for i in range(1, 21):
tasks.append(threading.Timer(i, waiting(".")))
# one per 3 seconds for 1 minute
for i in range(1, 21):
tasks.append(threading.Timer(20 + i*3, waiting(":")))
# one per 10 seconds for 3.5 minutes
for i in range(1, 22):
tasks.append(threading.Timer(80 + i*10, waiting("#")))
# one per 5 minutes for the rest of the hour
for i in range(1, 12):
tasks.append(threading.Timer(300 + i*300, waiting("!")))
# one per hour for 6 hours
for i in range(1, 7):
tasks.append(threading.Timer(3600 + i*3600, waiting("?")))
[i.start() for i in tasks]
try:
res = func(*args, **kwds)
except Exception:
raise
finally:
[i.cancel() for i in tasks]
sys.stderr.write("\n")
sys.stderr.flush()
return res
return fun
# and output that does not disturb doctests
# then add interactive usage, since this will be a communication tool
class Babcom(cmd.Cmd):
# attributes to be changed from outside
recover = False
username = None
identity = None
requestkey = None
recoverysecret0 = None
recoverysecret1 = None
recoverysecret2 = None
transient = False # in transient operation, nothing is saved to disk
spawn = False # was the node spawned for this run? Transient
# spawns are destroyed on quit.
fcp_port = None # needed for spawns to track down their folder
prompt = "--> "
# internal attributes
finished_startup = False
_messageprompt = "{newidentities}{messages}> "
_emptyprompt = "--> "
# TODO: change to "!5> " for 5 messages which can then be checked
# with the command read.
#: seed identity keys for initial visibility. This is currently BabcomTest. They need to be maintained: a daemon needs to actually check their CAPTCHA queue and update the trust, and a human needs to check whether what they post is spam or not.
seedkeys = [
# ("USK@fVzf7fg0Va7vNTZZQNKMCDGo6-FSxzF3PhthcXKRRvA,"
# "~JBPb2wjAfP68F1PVriphItLMzioBP9V9BnN59mYb0o,"
# "AQACAAE/WebOfTrust/12"),
# ("USK@IUqsUoSRuuJgEk7CkFWyXRK4fSffYZGlzPWxcHlLYWM,nbI93BRVXKvXsAwB5112i8aC09fwo6Md1nju6Jg5nHs,AQACAAE/WebOfTrust/0")
("USK@IOvW0rVk5OyP4~XlTAu8bEyIa6WevsA3HlSKW7hIx-A,0pfAVljMzxx8Jxp~cW6ABaUeoEbsucKH1wCCUnjexaY,AQACAAE/WebOfTrust/0")
]
seedtrust = 100
# iterators which either return a CAPTCHA or None.
captchaiters = [] # one iterator per set of captcha-sources to check
captchas = [] # retrieved captchas I could solve
captchawatchers = [] # one iterator per set of captchasolutionkeys
captchasolutions = [] # captcha solutions to watch for new identities
newlydiscovered = [] # newly discovered IDs
messages = [] # new messages the user can read
timers = []
nod_own = None # news of the day, own
nod_shared = None # news of the day
nods = None # news of the day to read
def preloop(self):
creatednewid = False
if self.recover:
if self.username:
print("Specified both username and recovery. Ignoring username in favor of recovery.")
# TOOD: Upload recovery information. Create and show the secret.
# load the secret user information from Freenet
print("Recovering identity, please type your recovery secret.")
recoverysecret = getpass.getpass("Recovery Secret: ").strip()
self.recoverysecret0, self.recoverysecret1, self.recoverysecret2 = split_recovery_secret_string(recoverysecret)
logging.info("Waiting until Freenet has at least five connections...")
def realpeers(n):
return [i for i in n.listpeers() if "seed" in i and i["seed"] == "false"]
with fcp.FCPNode() as n:
while len(realpeers(n)) < 5:
time.sleep(1)
print("... retrieving recovery information...")
try:
username, self.identity = recover_request_key_and_name(
self.recoverysecret0, self.recoverysecret1).split(b"@")
except fcp.FCPGetFailed as e:
print("could not retrieve the recovery information from Freenet. Please check your recovery secret. Recovery should work for at least 4 weeks after the last insert.")
raise
with fcp.FCPNode() as n:
self.insertkey = recover_insert_key(self.recoverysecret2, self.identity, username)
print("Creating a local version of your ID with your recovered username and insert key...")
try:
self.username = createidentity(name=username, insertkey=self.insertkey)
except fcp.FCPProtocolError as e:
# InvalidParameterException means that an ID with this key already exists. We can simply grab the matching username in the next step.
if str(e).startswith("plugins.WebOfTrust.exceptions.InvalidParameterException"):
print("An ID with this insert key is already in the local Web of Trust. Will chose the existing one in the next step.")
else:
raise
elif self.username is None:
print("No user given, creating random name...")
self.username = randomname()
print("... generating random identity with name", self.username, ". Please wait...")
else:
print("Retrieving identity information from Freenet using name", self.username + ". Please wait ...")
if not in_doctest:
print("... checking for existing identities which match", self.username, "...")
matches = getownidentities(self.username)
if not matches:
if not in_doctest:
print("... no matches found, creating new identity...")
createidentity(self.username)
creatednewid = True
print("... created identity. Please type down the following recovery secret to be able to recover the identity from another computer:")
self.recoverysecret0 = str(time.gmtime()[0])
self.recoverysecret1 = create_recovery_secret_part(2) # entropy ~ 44
self.recoverysecret2 = create_recovery_secret_part(3) # entropy ~ 72
print(join_recovery_secret_string(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2))
matches = getownidentities(self.username)
print("... retrieved", len(matches), "identities matching", self.username)
if matches[1:]:
choice = None
print("more than one identity with name", self.username, "please select one.")
while choice is None:
for i in range(len(matches)):
print(i+1, matches[i][0]+"@"+matches[i][1]["Identity"])
res = input("Insert the number of the identity to use (1 to " + str(len(matches)) + "): ")
try:
choice = int(res)
except ValueError:
print("not a number")
if choice < 1 or len(matches) < choice:
choice = None
print("the number is not in the range", str(i+1), "to", str(len(matches)))
self.username = matches[choice - 1][0]
self.identity = matches[choice - 1][1]["Identity"]
self.requestkey = matches[choice - 1][1]["RequestURI"]
else:
self.username = matches[0][0]
self.identity = matches[0][1]["Identity"]
self.requestkey = matches[0][1]["RequestURI"]
# load persistent state from disk (i.e. unused captcha solutions)
self.load()
print("Logged in as", self.username + "@" + self.identity)
print(" with key", self.requestkey)
if creatednewid:
print("Uploading recovery information using the recovery secret",
join_recovery_secret_string(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2))
def upload_recovery_fun():
upload_recovery(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2,
self.identity, self.username,
captchasolutions="\n".join(self.captchasolutions))
def upload_recovery_done_callback(fut):
self.messages.append("Uploaded recovery information to "
+ join_recovery_secret_string(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2))
if self.transient: # must ensure that the upload succeeded
upload_recovery_fun()
else:
executor = concurrent.futures.ThreadPoolExecutor()
executor.submit(upload_recovery_fun).add_done_callback(upload_recovery_done_callback)
# start watching captcha solutions
self.watchcaptchasolutionloop()
def introduce():
# TODO: write solutions to a file on disk and re-read a
# limited number of them on login.
solutions = providecaptchas(self.identity)
self.captchasolutions.extend(solutions)
self.watchcaptchasolutions(solutions)
self.messages.append("New CAPTCHAs uploaded successfully.")
print("\a", end="") # alert / bell FIXME: does not work yet.
t = threading.Timer(0, introduce)
t.daemon = True
t.start()
self.timers.append(t)
print("Providing new CAPTCHAs, so others can make themselves visible.""")
print()
self.finished_startup = True
def postloop(self):
"""Cleanup and save state."""
# TODO: This does not fire on quit or EOF. The functionality
# is for now implemented in do_quit and do_EOF.
def postcmd(self, stop, line):
# update message information after every command
self.updateprompt()
def cmdloop(self, *args, **kwds):
try:
super().cmdloop(*args, **kwds)
except KeyboardInterrupt as e:
if not self.finished_startup:
raise # if we do not have a command loop yet where the
# user can exit, actually do go down on CTRL-C.
logging.warning("Caught Keyboard Interrupt (CTRL-C). Restarting commandloop. Use CTRL-D to exit.")
self.cmdloop(*args, **kwds)
def teardown(self):
"""Delete the node folder. Only for spawns!"""
if not self.spawn:
logging.warning("Tried to teardown a node which is no spawn")
return
if self.transient:
print("Stopping and deleting the spawned Freenet node.")
return freenet.spawn.teardown_node(self.fcp_port,
delete_node_folder=self.transient)
def save(self):
"""Save state like the CAPTCHA solutions."""
if self.transient:
return # not saving anything in transient mode
dirs = appdirs.AppDirs("babcom", "freenet")
# dirs.user_data_dir
# dirs.user_config_dir
# dirs.user_cache_dir
# dirs.user_log_dir
identity_info_dir = os.path.join(dirs.user_data_dir, self.identity)
if not os.path.isdir(identity_info_dir):
os.makedirs(identity_info_dir)
with open(os.path.join(
identity_info_dir, "unusedcaptchasolutions.txt"), "w") as f:
f.write("\n".join(self.captchasolutions))
if None in (self.recoverysecret0, self.recoverysecret1, self.recoverysecret2):
self.createrecovery()
upload_recovery(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2,
self.identity, self.username,
captchasolutions="\n".join(self.captchasolutions))
with open(os.path.join(
identity_info_dir, "recoverysecret.txt"), "w") as f:
f.write(join_recovery_secret_string(
self.recoverysecret0, self.recoverysecret1, self.recoverysecret2))
# add the user to the known users to be able to recover it.
knownusersfile = os.path.join(dirs.user_data_dir, "knownusers")
adduser = False
if not os.path.isfile(knownusersfile):
adduser = True
else:
with open(knownusersfile) as f:
if self.identity not in f:
adduser = True
if adduser:
with open(knownusersfile, "a") as f:
f.write("{} {} {}\n".format(self.identity, self.fcp_port, self.username))
logging.info("saved user {} as new known user with id {} and port {}".format(
self.username, self.identity, self.fcp_port))
logging.debug("saved recoverysecret and {}".format(self.captchasolutions))
def load(self):
"""Save state like the CAPTCHA solutions."""
dirs = appdirs.AppDirs("babcom", "freenet")
identity_info_dir = os.path.join(dirs.user_data_dir, self.identity)
if not os.path.isdir(identity_info_dir):
if None in (self.recoverysecret0, self.recoverysecret1, self.recoverysecret2):
print("... no recovery secret found, creating and uploading a new one...")
recoverysecret = self.createrecovery()
upload_recovery(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2,
self.identity, self.username,
captchasolutions="\n".join(self.captchasolutions))
print("... please write down the following recovery secret:")
print(recoverysecret)
return
with open(os.path.join(
identity_info_dir, "unusedcaptchasolutions.txt")) as f:
solutions = [i.strip() for i in f.readlines()]
c = set(self.captchasolutions)
self.captchasolutions.extend(
[i for i in solutions if i not in c])
logging.debug("loaded {}".format(solutions))
try:
with open(os.path.join(
identity_info_dir, "recoverysecret.txt")) as f:
self.recoverysecret0, self.recoverysecret1, self.recoverysecret2 = split_recovery_secret_string(
f.read().strip())
except ValueError: # does not exist
print("... no recovery secret found, creating and uploading a new one...")
recoverysecret = self.createrecovery()
upload_recovery(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2,
self.identity, self.username,
captchasolutions="\n".join(self.captchasolutions))
print("... please write down the following recovery secret:")
print(recoverysecret)
def createrecovery(self):
"""Create and remember a recovery secret.
Returns the secret string.
"""
self.recoverysecret0 = str(time.gmtime()[0])
self.recoverysecret1 = create_recovery_secret_part(2) # entropy ~ 44
self.recoverysecret2 = create_recovery_secret_part(3) # entropy ~ 72
upload_recovery(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2,
self.identity, self.username,
captchasolutions="\n".join(self.captchasolutions))
return join_recovery_secret_string(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2)
def watchcaptchasolutions(self, solutions, maxwatchers=100):
"""Start watching the solutions of captchas, adding trust 0 as needed.
The real work is done by watchcaptchasolutionsloop.
"""
# avoid duplicates
c = set(self.captchasolutions)
s = [i for i in solutions if i not in c]
self.captchasolutions.extend(s)
# never watch more than maxwatchers solutions: drop old entries
self.captchasolutions = self.captchasolutions[-maxwatchers:]
# watch the solutions.
self.captchawatchers.append(watchcaptchas(s))
def updateprompt(self):
nummsg = len(self.messages)
numnew = len(self.newlydiscovered)
if nummsg + numnew != 0:
newids = (numtostring(numnew) if numnew > 0 else "!")
newmsg = (numtostring(nummsg) if nummsg > 0 else "-")
self.prompt = self._messageprompt.format(newidentities=newids,
messages=newmsg)
else:
self.prompt = self._emptyprompt
def watchcaptchasolutionloop(self, intervalseconds=300):
"""Watch for captchasolutions in an infinite, offthread loop, adding solutions to newlydiscovered."""
def loop():
# resubmit all unsolved captchas if there are no captchasolutions left.
if not self.captchawatchers and self.captchasolutions:
self.watchcaptchasolutions(self.captchasolutions)
for watcher in self.captchawatchers[:]:
try:
res = next(watcher)
except StopIteration:
self.captchawatchers.remove(watcher)
continue
if res is None:
continue
solution, newrequestkey = res
# remember that the captcha has been solved: do not try again
try:
self.captchasolutions.remove(solution)
except ValueError: # already removed
pass
newidentity = identityfrom(newrequestkey)
print(newidentity)
trustifmissing = 0
commentifmissing = "Trust received from solving a CAPTCHA"
trustadded = ensureavailability(newidentity, newrequestkey, self.identity,
trustifmissing=trustifmissing,
commentifmissing=commentifmissing)
# now the identity is there, but it might not have needed explicit trust.
# but captchas should give that.
if not trustadded:
trust = gettrust(self.identity, newidentity)
if trust == "Nonexistent" or int(trust) < 0:
settrust(self.identity, newidentity, trustifmissing, commentifmissing)
trustadded = True
if trustadded:
self.newlydiscovered.append(newrequestkey)
self.messages.append("New identity added who solved a CAPTCHA: {}".format(newidentity))
print("\a", end="") # alert / bell
else:
self.messages.append("Identity {} who solved a CAPTCHA was already known.".format(newidentity))
t = threading.Timer(intervalseconds, loop)
t.daemon = True
t.start()
self.timers.append(t)
# cleanup the timers
for t in self.timers:
if not t.is_alive():
t.join()
self.timers.remove(t)
loop()
def do_intro(self, *args):
"Introduce Babcom"
print("""
> It began in the Earth year 2016, with the founding of the first of
the Babcom systems, located deep in decentralized space. It was a
port of call for journalists, writers, hackers, activists . . . and
travelers from a hundred worlds. Could be a dangerous place – but we
accepted the risk, because Babcom 1 was societies next, best hope
for survival.
— Tribute to Babylon 5, where humanity learned to forge its own path.
Type help or help <command> and a newline to learn how to use babcom.
Use introduce to become visible.
If the prompt changes from --> to !M>, N-> or NM>,
you have new messages. Read them with read
""")
# for testing:
# introduce USK@FpcnriKy19ztmHhg0QzTJjGwEJJ0kG7xgLiOvKXC7JE,CIpXjQej5StQRC8LUZnu3nvvh1l9UbZMinyFQyLSdMY,AQACAAE/WebOfTrust/0
# introduce USK@0kq3fHCn12-93PSV4kk56B~beIkh-XfjennLapmmapM,9hQr66rxc9O5ptdmfhMk37h2vZGrsE6NYXcFDMGMiTw,AQACAAE/WebOfTrust/1
# introduce USK@0kq3fHCn12-93PSV4kk56B~beIkh-XfjennLapmmapM,9hQr66rxc9O5ptdmfhMk37h2vZGrsE6NYXcFDMGMiTw,AQACAAE/WebOfTrust/1
# introduce USK@FZynnK5Ngi6yTkBAZXGbdRLHVPvQbd2poW6DmZT8vbs,bcPW8yREf-66Wfh09yvx-WUt5mJkhGk5a2NFvbCUDsA,AQACAAE/WebOfTrust/1
# introduce USK@B324z0kMF27IjNEVqn6oRJPJohAP2NRZDFhQngZ1GOI,DRf8JZviHLIFOYOdu42GLL2tDhVaWb6ihdNO18DkTpc,AQACAAE/WebOfTrust/0
def do_read(self, *args):
"""Read messages."""
if len(self.messages) + len(self.newlydiscovered) == 0:
print("No new messages.")
i = 1
while self.messages:
print("[{}]".format(i), end=' ')
print(self.messages.pop())
print()
i += 1
if self.newlydiscovered:
print("discovered {} new identities:".format(len(self.newlydiscovered)))
i = 1
while self.newlydiscovered:
print(i, "-", self.newlydiscovered.pop())
i += 1
self.updateprompt()
def do_introduce(self, *args):
"""Introduce your own ID to others. Usage: introduce [<other id key> ...]"""
usingseeds = args[0] == ""
if usingseeds and self.captchas:
return self.onecmd("solvecaptcha")
def usecaptchas(captchas):
cap = captchas.splitlines()
c = set(cap) # avoid duplicates
# shuffle all new captchas, but not the old ones
self.captchas = [i for i in self.captchas
if i not in c]
random.shuffle(cap)
self.captchas.extend(cap)
return self.onecmd("solvecaptcha")
if usingseeds and self.captchaiters:
for captchaiter in self.captchaiters[:]:
try:
captchas = next(captchaiter)
except StopIteration: # captchaiter is finished, nothing more to gain
self.captchhaiters.remove(captchaiter)
else:
if captchas is not None:
return usecaptchas(captchas)
return
if usingseeds:
ids = [i.split("@")[1].split(",")[0] for i in self.seedkeys]
keys = self.seedkeys
trustifmissing = self.seedtrust
commentifmissing = "Automatically assigned trust to a seed identity."
else:
try:
ids = [i.split("@")[1].split(",")[0] for i in args[0].split()]
except IndexError:
print("Invalid id key. Interpreting as ID")
try:
ids = args[0].split()
keys = [getrequestkey(i, self.identity) for i in args[0].split()]
except fcp.FCPProtocolError as e:
if len(ids) == 1:
print("Cannot retrieve request uri for identity {} - please give a requestkey like {}".format(
ids[0], self.seedkeys[0]))
else:
print("Cannot retrieve request uris for the identities {} - please give requestkeys like {}".format(
ids, self.seedkeys[0]))
print("Reason: {}".format(e))
return
keys = args[0].split()
trustifmissing = 0
commentifmissing = "babcom introduce"
# store the iterator. If there is at least one captcha in it
captchaiter = prepareintroduce(ids, keys, self.identity, trustifmissing, commentifmissing)
try:
captchas = next(captchaiter)
except StopIteration:
pass # iteration finished
else:
self.captchaiters.append(captchaiter)
if captchas is not None:
return usecaptchas(captchas)
def do_solvecaptcha(self, *args):
"""Solve a captcha. Usage: solvecaptcha [captcha]"""
if args and args[0].strip():
captcha = args[0].strip()
else:
if not self.captchas:
print("no captchas available. Please run introduce.")
return
# choose at random from the newest 20 captchas, because
# pop() after shuffle(l) gave too many repetitions, which
# seems pretty odd.
captcha = random.choice(self.captchas[-20:])
self.captchas.remove(captcha)
print("Please solve the following CAPTCHA to introduce your identity.")
try:
question = captcha.split(" with ")[1]
except IndexError:
print("broken CAPTCHA", captcha, "Please run introduce.")
return
solution = input(question + ": ").strip() # strip away spaces
while solution == "":
# catch accidentally hitting enter
print("Received empty solution. Please type a solution to introduce.")
solution = input(question + ": ").strip() # strip away spaces
try:
captchakey = solvecaptcha(captcha, self.identity, solution)
print("Inserted own identity to {}".format(captchakey))
except Exception as e:
captchakey = _captchasolutiontokey(captcha, solution)
print("Could not insert identity to {}:\n {}\n".format(captchakey, e))
print("Run introduce again to try a different CAPTCHA")
def do_visibleto(self, *args):
"""Check whether the other can currently see me. Usage: visibleto ID
Example: visibleto FZynnK5Ngi6yTkBAZXGbdRLHVPvQbd2poW6DmZT8vbs"""
# TODO: allow using nicknames.
if args[0] == "":
print("visibleto needs an ID")
self.onecmd("help visibleto")
return
other = args[0].split()[0]
# remove name or keypart
other = identityfrom(other)
# check whether we’re visible for the otherone
visible = checkvisible(self.identity, other)
if visible is None:
print("We do not know whether", other, "can see you.")
print("There is no explicit trust but there might be propagating trust.")
# TODO: check whether I can get the score the other sees for me.
if visible is False:
print(other, "marked you as spammer and cannot see anything from you.")
if visible is True:
print("You are visible to {}: there is explicit trust.".format(other))
def do_known(self, *args):
"""List all known identities."""
for i in gettrustees(self.identity):
name, info = getidentity(i, self.identity)
if name:
print(name+"@"+i)
def do_uploadrecovery(self, *args):
"""Upload recovery information for this identity."""
print("Uploading recovery information using the recovery secret",
join_recovery_secret_string(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2))
upload_recovery(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2,
self.identity, self.username,
captchasolutions="\n".join(self.captchasolutions))
print("Please write down the recovery secret:")
print(join_recovery_secret_string(self.recoverysecret0, self.recoverysecret1, self.recoverysecret2))
print("Now you can use babcom.py --recover to recover an identity on any computer with the secret.")
def do_exec(self, *args):
"""Execute the code entered. WARNING! Only for development purposes!"""
code = [args[0]]
if args[0] == "":
print("# type your code. Finish with an empty line.")
nextline = input()
while nextline != "":
code.append(nextline)
nextline = input()
exec("\n".join(code))
def do_contact(self, *args):
"""Contact someone by private message (Freemail). Usage: contact USK@..."""
otherkey = args[0]
otherid = identityfrom(otherkey)
trustifmissing = 0
commentifmissing = "Trust received from solving a CAPTCHA" # fake captcha to hide traces. TODO: find a way to set hidden trust 0
ensureavailability(otherid, otherkey, self.identity,
trustifmissing=trustifmissing,
commentifmissing=commentifmissing)
name, info = getidentity(otherid, self.identity)
with fcp.FCPNode() as n:
fproxy_port = n.modifyconfig()["current.fproxy.port"]
send_freemail(self.username + "@" + self.identity,
name + "@" + otherid,
"test",
fproxyport=fproxy_port)
def do_hello(self, *args):
"""Says Hello. Usage: hello [<name>]"""
name = args[0] if args else 'World'
print("Hello {}".format(name))
# TODO: implement do_recover and show the insert URI on start and stop
def do_nod(self, *args):
"""News Of the Day. Usage: nod [discover | subscribe | read | share | write | upload <own | share>]"""
cmd = args[0] if args else 'read'
if cmd.startswith("write"):
def nod_input():
text = []
nextline = input()
while nextline != "":
text.append(nextline)
nextline = input()
return "\n".join(text)
if self.nod_own:
print("You already set the news of the day: {}".format(self.nod_own))
yn = input("Do you want to replace it? (yes/No) ").strip()
if not yn.lower().startswith("y"):
return
print("Type your news message. End with an empty line.")
self.nod_own = nod_input()
print("New news of the day entry recorded. It will be uploaded tomorrow.")
print("You can force an irreversible upload with: nod upload own")
return
if cmd.startswith("upload"):
if not cmd.split()[1:]:
print("Please specify own or share to upload.")
return self.onecmd("help nod")
target = cmd.split()[1]
if target == "own":
if not self.nod_own:
print("No own news of the day set. Use nod write to set it.")
return self.onecmd("help nod")
key = nod_uploadkey(getinsertkey(self.identity), own=True)
try:
fastput(key, self.nod_own)
except fcp.node.FCPPutFailed as e:
print("Could not upload the news of the day. Did you already upload today?")
logging.debug(e)
else:
self.nod_own = None
print("Uploaded own news of the day. You can upload the next nod tomorrow.")
return
if target == "share":
if not self.nod_shared:
print("No shared news of the day set. Use nod share to set it.")
return self.onecmd("help nod")
key = nod_uploadkey(getinsertkey(self.identity), shared=True)
try:
fastput(key, self.nod_shared)
except fcp.node.FCPPutFailed as e:
print("Could not upload the news of the day. Did you already upload today?")
logging.debug(e)
else:
self.nod_shared = None
print("Uploaded shared news of the day. You can upload the next nod tomorrow.")
return
if cmd.startswith("discover"):
print(getknownids(self.identity, context="babcom"))
return
def do_quit(self, *args):
"Leaves the program"
print("Received quit request. Shutting down!")
[i.cancel() for i in self.timers]
self.save()
if self.spawn:
self.teardown()
print("Good bye. Thank you for using babcom!")
raise SystemExit
def do_EOF(self, *args):
"Same as quit. Commonly called via CTRL-D"
return self.onecmd("quit")
def emptyline(self, *args):
"What is done for an empty line"
print("Type help and hit enter to get help")
class ProtocolError(Exception):
"""
Did not get the expected reply.
"""
def _parse_name(wot_identifier):
"""
Parse identifier of the forms: nick
nick@key
@key
:Return: nick, key. If a part is not given return an empty string for it.
>>> _parse_name("BabcomTest@123")
('BabcomTest', '123')
"""
split = wot_identifier.split('@', 1)
nickname_prefix = split[0]
key_prefix = (split[1] if split[1:] else '')
return nickname_prefix, key_prefix
@withprogress
def wotmessage(messagetype, **params):
"""Send a message to the Web of Trust plugin
>>> name = wotmessage("RandomName")["Replies.Name"]
"""
params["Message"] = messagetype
def sendmessage(params):
with fcp.FCPNode() as n:
return n.fcpPluginMessage(plugin_name="plugins.WebOfTrust.WebOfTrust",
plugin_params=params)[0]
try:
resp = sendmessage(params)
except fcp.FCPProtocolError as e:
if str(e) == "ProtocolError;No such plugin":
ensureofficialpluginloaded("WebOfTrust")
resp = sendmessage(params)
else: raise
return resp
def ensureofficialpluginloaded(pluginname):
"""Ensure that the given plugin is loaded.
:param pluginname: Freemail
"""
logging.info("Waiting before loading %s until Freenet has at least five connections. Below this it is pointless to try to get an official plugin.", pluginname)
def realpeers(n):
return [i for i in n.listpeers() if "seed" in i and i["seed"] == "false"]
with fcp.FCPNode() as n:
while len(realpeers(n)) < 5:
time.sleep(1)
loaded = False
try:
with fcp.FCPNode() as n:
jobid = n._getUniqueId()
resp = n._submitCmd(jobid, "GetPluginInfo",
PluginName=pluginname)[0]
loaded = True
except fcp.FCPProtocolError as e:
if str(e) == "ProtocolError;No such plugin":
logging.warning("Plugin " + pluginname + " not loaded. Trying to load it.")
with fcp.FCPNode() as n:
jobid = n._getUniqueId()
try:
resp = n._submitCmd(jobid, "LoadPlugin",
PluginURL=pluginname,
URLType="official",
OfficialSource="freenet")[0]
except fcp.node.FCPProtocolError as e:
logging.warning("Could not load the Web of Trust: %s", e)
else: raise
# if that didn’t wait long enough, just wait longer. longer. Longer. Until it exists.
retry_timeout_seconds = 300
start = time.time()
while not loaded:
try:
with fcp.FCPNode() as n:
jobid = n._getUniqueId()
resp = n._submitCmd(jobid, "GetPluginInfo",
PluginName=pluginname)[0]
loaded = True
except fcp.FCPProtocolError as e:
logging.warning(str(e))
if time.time() - start > retry_timeout_seconds:
# issue another load plugin command.
return ensureofficialpluginloaded(pluginname)
logging.info("Plugin Loaded: %s", pluginname)
return resp
def randomname():
return wotmessage("RandomName")["Replies.Name"]
def createidentity(name="BabcomTest", removedefaultseeds=True, insertkey=None):
"""Create a new Web of Trust identity.
>>> name = "BabcomTest"
>>> if slowtests:
... createidentity(name)
... else: name
'BabcomTest'
:returns: the name of the identity created.
"""
if not name:
name = wotmessage("RandomName")["Name"]
if not isinstance(name, str):
name = name.decode("utf-8")
msgopts = dict(Nickname=name, Context="babcom", # context cannot be empty
PublishTrustList="true", # must use string "true"
PublishIntroductionPuzzles="true")
if insertkey is not None:
if not isinstance(insertkey, str):
insertkey = insertkey.decode("utf-8")
msgopts["InsertURI"] = insertkey
resp = wotmessage("CreateIdentity", **msgopts)
if resp['header'] != 'FCPPluginReply' or resp.get('Replies.Message', "") != 'IdentityCreated':
raise ProtocolError(resp)
# prune seed-trust, since babcom does its own bootstrapping.
# TODO: consider changing this when we add support for other services.
if removedefaultseeds:
identity = resp['Replies.ID']
for trustee in gettrustees(identity):
removetrust(identity, trustee)
return name
def parseownidentitiesresponse(response):
"""Parse the response to Get OwnIdentities from the WoT plugin.
:returns: [(name, {InsertURI: ..., ...}), ...]
>>> resp = parseownidentitiesresponse({'Replies.Nickname0': 'FAKE', 'Replies.RequestURI0': 'USK@...', 'Replies.InsertURI0': 'USK@...', 'Replies.Identity0': 'fVzf7fg0Va7vNTZZQNKMCDGo6-FSxzF3PhthcXKRRvA', 'Replies.Message': 'OwnIdentities', 'Success': 'true', 'header': 'FCPPluginReply', 'Replies.Properties0.Property0.Name': 'fake', 'Replies.Properties0.Property0.Value': 'true'})
>>> list(sorted([(name, list(sorted(info.items()))) for name, info in resp]))
[('FAKE', [('Contexts', []), ('Identity', 'fVzf7fg0Va7vNTZZQNKMCDGo6-FSxzF3PhthcXKRRvA'), ('InsertURI', 'USK@...'), ('Properties', {'fake': 'true'}), ('RequestURI', 'USK@...'), ('id_num', '0')])]
"""
field = "Replies.Nickname"
identities = []
for i in response:
if i.startswith(field):
# format: Replies.Nickname<id_num>
id_num = i[len(field):]
nickname = response[i]
pubkey_hash = response['Replies.Identity{}'.format(id_num)]
request = response['Replies.RequestURI{}'.format(id_num)]
insert = response['Replies.InsertURI{}'.format(id_num)]
contexts = [response[j] for j in response if j.startswith("Replies.Contexts{}.Context".format(id_num))]
property_keys_keys = [j for j in sorted(response.keys())
if (j.startswith("Replies.Properties{}.Property".format(id_num))
and j.endswith(".Name"))]
property_value_keys = [j for j in sorted(response.keys())
if (j.startswith("Replies.Properties{}.Property".format(id_num))
and j.endswith(".Value"))]
properties = dict((response[j], response[k]) for j,k in zip(property_keys_keys, property_value_keys))
identities.append((nickname, {"id_num": id_num, "Identity":
pubkey_hash, "RequestURI": request, "InsertURI": insert,
"Contexts": contexts, "Properties": properties}))
return identities
def parseidentityresponse(response):
"""Parse the response to Get OwnIdentities from the WoT plugin.
:returns: [(name, {InsertURI: ..., ...}), ...]
>>> resp = {'Replies.Identity': 'jFEicE8bMY0pBN4x6VaN8PsCW342VuuTr0hAc0t39Ls', 'Replies.Identities.0.CurrentEditionFetchState': 'Fetched', 'Replies.Identities.0.Property0.Name': 'IntroductionPuzzleCount', 'Replies.Property0.Value': 10, 'Replies.Rank': 'null', 'Replies.Identities.0.Contexts.0.Name': 'babcom', 'Replies.Identities.0.Property0.Value': 10, 'Replies.Properties0.Property0.Name': 'IntroductionPuzzleCount', 'header': 'FCPPluginReply', 'Replies.Type': 'OwnIdentity', 'Replies.Identities.0.Nickname': 'BabcomTest_other', 'Replies.ID': 'jFEicE8bMY0pBN4x6VaN8PsCW342VuuTr0hAc0t39Ls', 'Replies.Identities.0.Type': 'OwnIdentity', 'Replies.Message': 'Identity', 'Replies.Contexts0.Amount': 2, 'Replies.Identity0': 'jFEicE8bMY0pBN4x6VaN8PsCW342VuuTr0hAc0t39Ls', 'Replies.Identities.Amount': 1, 'Replies.Scores.0.Value': 'Nonexistent', 'Replies.PublishesTrustList0': 'true', 'Replies.RequestURI': 'USK@jFEicE8bMY0pBN4x6VaN8PsCW342VuuTr0hAc0t39Ls,-6yAY9Qq2YildfGRFikIsWQf6RDzPAc84q-gPcbXR7o,AQACAAE/WebOfTrust/1', 'Replies.VersionID': 'a60e2f40-d5e0-4069-8297-05ce8819d817', 'Replies.ID0': 'jFEicE8bMY0pBN4x6VaN8PsCW342VuuTr0hAc0t39Ls', 'Replies.Score0': 'null', 'Replies.CurrentEditionFetchState0': 'Fetched', 'Replies.Contexts0.Context1': 'Introduction', 'Replies.Rank0': 'null', 'Replies.Identities.0.PublishesTrustList': 'true', 'Replies.Contexts.1.Name': 'Introduction', 'Replies.Properties0.Amount': 1, 'Replies.Trust0': 'null', 'Replies.Nickname': 'BabcomTest_other', 'Replies.Identities.0.Properties.0.Value': 10, 'Replies.Properties.0.Value': 10, 'Replies.Score': 'null', 'Replies.Trusts.0.Value': 'Nonexistent', 'Replies.Identities.0.VersionID': '118044f9-0ee8-4986-b798-d0645779ac1b', 'Replies.Properties.0.Name': 'IntroductionPuzzleCount', 'Replies.Context1': 'Introduction', 'Replies.Context0': 'babcom', 'Success': 'true', 'Replies.VersionID0': '84e4aba7-ebfe-4ee6-884f-ea7275decc7b', 'Replies.CurrentEditionFetchState': 'Fetched', 'Replies.Contexts.Amount': 2, 'Replies.Contexts0.Context0': 'babcom', 'Replies.Identities.0.Contexts.1.Name': 'Introduction', 'Replies.Trust': 'null', 'Replies.Properties0.Property0.Value': 10, 'Replies.PublishesTrustList': 'true', 'Identifier': 'id2342652746084203', 'Replies.Nickname0': 'BabcomTest_other', 'Replies.Property0.Name': 'IntroductionPuzzleCount', 'Replies.Contexts.0.Name': 'babcom', 'Replies.Type0': 'OwnIdentity', 'Replies.Properties.Amount': 1, 'Replies.Identities.0.ID': 'jFEicE8bMY0pBN4x6VaN8PsCW342VuuTr0hAc0t39Ls', 'PluginName': 'plugins.WebOfTrust.WebOfTrust', 'Replies.Identities.0.Identity': 'jFEicE8bMY0pBN4x6VaN8PsCW342VuuTr0hAc0t39Ls', 'Replies.Identities.0.RequestURI': 'USK@jFEicE8bMY0pBN4x6VaN8PsCW342VuuTr0hAc0t39Ls,-6yAY9Qq2YildfGRFikIsWQf6RDzPAc84q-gPcbXR7o,AQACAAE/WebOfTrust/1', 'Replies.Identities.0.Context0': 'babcom', 'Replies.Identities.0.Context1': 'Introduction', 'Replies.Identities.0.Properties.0.Name': 'IntroductionPuzzleCount', 'Replies.Identities.0.Contexts.Amount': 2, 'Replies.Identities.0.Properties.Amount': 1, 'Replies.RequestURI0': 'USK@jFEicE8bMY0pBN4x6VaN8PsCW342VuuTr0hAc0t39Ls,-6yAY9Qq2YildfGRFikIsWQf6RDzPAc84q-gPcbXR7o,AQACAAE/WebOfTrust/1'}
>>> name, info = parseidentityresponse(resp)
>>> name
'BabcomTest_other'
>>> info['RequestURI'].split(",")[-1]
'AQACAAE/WebOfTrust/1'
>>> list(sorted(info.keys()))
['Contexts', 'CurrentEditionFetchState', 'Identity', 'Properties', 'RequestURI']
"""