-
Notifications
You must be signed in to change notification settings - Fork 277
Expand file tree
/
Copy pathtc_client.py
More file actions
2129 lines (1828 loc) · 84.3 KB
/
tc_client.py
File metadata and controls
2129 lines (1828 loc) · 84.3 KB
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
# -*- coding: UTF-8 -*-
##############################################################################
# #
# Copyright (c) 2007-2010 Bernd Kreuss <prof7bit@gmail.com> #
# #
# This program is licensed under the GNU General Public License V3, #
# the full source code is included in the binary distribution. #
# #
# Included in the distribution are files from other open source projects: #
# - TOR Onion Router (c) The Tor Project, 3-clause-BSD #
# - SocksiPy (c) Dan Haim, BSD Style License #
# - Gajim buddy status icons (c) The Gajim Team, GNU GPL #
# #
##############################################################################
# This is the TorChat client library. Import this module, make an instance
# of BuddyList, give it your call-back function and your client is running.
import SocksiPy.socks as socks
import socket
import threading
import random
import time
import sys
import os
import shutil
import subprocess
import tempfile
import hashlib
import config
import version
TORCHAT_PORT = 11009 #do NOT change this.
TOR_CONFIG = "tor" #the name of the active section in the .ini file
STATUS_OFFLINE = 0
STATUS_HANDSHAKE = 1
STATUS_ONLINE = 2
STATUS_AWAY = 3
STATUS_XA = 4
CB_TYPE_CHAT = 1
CB_TYPE_FILE = 2
CB_TYPE_OFFLINE_SENT = 3
CB_TYPE_STATUS = 4
CB_TYPE_LIST_CHANGED = 5
CB_TYPE_AVATAR = 6
CB_TYPE_PROFILE = 7
CB_TYPE_REMOVE = 8
tb = config.tb # the traceback function has moved to config
tb1 = config.tb1
tor_pid = None
tor_proc = None
tor_timer = None
def splitLine(text):
"""split a line of text on the first space character and return
two strings, the first word and the remaining string. This is
used for parsing the incoming messages from left to right since
the command and its arguments are all delimited by spaces and
the command may not contain spaces"""
sp = text.split(" ")
try:
a = sp[0]
b = " ".join(sp[1:])
except:
a = text
b = ""
return a, b
def encodeLF(blob):
"""takes a string of 8 bit binary data and encodes
it so that there are no 0x0a (LF) bytes anymore"""
# first we get all '\' out of the way by encoding each
# backslash '\' as the character sequence '\/'
# so there will not remain any '\n' sequence anymore,
# and then we can safely encode every 0x0a as '\n'.
#
# Please do not rant in the source code comments of your
# own protocol implementations about how "suboptimal" my
# decision was, actally I spent quite some time thinking
# about it in the early design phase and this solution is
# pragmatic, easy to implement and rock solid.
#
# Also please do not suggest alternative encodings like
# bandwidth wasting base64, there is NO NEED for it,
# TorChat is NOT a text based protocol in the common
# sense, we are transmitting binary data over 8-bit-clean
# sockets. We don't have to fit them into RFC confoming
# message bodies of SMTP or NNTP messages, print them
# line by line on a terminal or a printer or anything
# else that would interpret control characters. The
# only special character in this protocol is the message
# delimiter which I chose to be 0x0a and because 0x0a is
# often referred to as "newline" I call the chunks of
# encoded data between them "lines" and each "line" is
# representing exactly one protocol message.
#
# The first word of each line will be the command and
# may only consist of [a..z] or underscore, see the
# individual message classes for detailed descriptions.
return blob.replace("\\", "\\/").replace("\n", "\\n")
def decodeLF(line):
"""takes the line as it comes from the socket and decodes it to
the original binary data contained in a string of bytes"""
return line.replace("\\n", "\n").replace("\\/", "\\")
def createTemporaryFile(file_name):
if config.getint("files", "temp_files_in_data_dir"):
dir = config.getDataDir()
else:
dir = config.get("files", "temp_files_custom_dir")
try:
if dir == "":
dir = None
tmp = tempfile.mkstemp("_" + file_name, "torchat_incoming_", dir)
except:
print "(1) could not create temporary file in %s" % dir
tb()
print "(1) trying system temporary folder"
tmp = tempfile.mkstemp("_" + file_name, "torchat_incoming_")
fd, file_name_tmp = tmp
file_handle_tmp = os.fdopen(fd, "w+b")
os.chmod(file_name_tmp, 0600)
print "(2) created temporary file %s" % file_name_tmp
return (file_name_tmp, file_handle_tmp)
class WipeFileThread(threading.Thread):
"""This wipes a file in a separate thread because
wiping a file is a long running task and we don't
want to freeze parts of the application. This is
only called by the function wipeFile(). Call the
function wipeFile() if you want to wipe a file."""
def __init__(self, file_name):
threading.Thread.__init__(self)
self.file_name = file_name
self.start()
def run(self):
BLOCK_SIZE = 8192
print "(2) wiping %s" % self.file_name
if os.path.exists(self.file_name):
try:
handle = open(self.file_name, mode="r+b")
handle.seek(0, 2) #SEEK_END
size = handle.tell()
handle.seek(0)
blocks = size / BLOCK_SIZE + 1
for i in range(blocks):
handle.write(os.urandom(BLOCK_SIZE))
print "(2) sync to disk"
handle.flush()
os.fsync(handle.fileno())
handle.close()
print "(2) unlinking wiped file"
os.unlink(self.file_name)
except:
print "(0) could not wipe file %s (file is locked or wrong permissions)" % self.file_name
else:
print "(2) file %s does not exist" % self.file_name
def wipeFile(file_name):
"""Wipe a file by first overwriting it with random data,
synching it to disk and finally unlinking it. For this
purpose it will start a separat thread to do this in the
background and return immediately."""
WipeFileThread(file_name)
#--- ### Client API
class Buddy(object):
"""Represets a buddy. Every buddy on the buddy list will have sich
an instance created directly after program start and also every new
connection from unknown addresses will result in the instantiation
of a new buddy object when a valid ping message has been processed.
All Buddy objects are maintained by and contained in the BuddyList
object"""
def __init__(self, address, buddy_list, name=u"", temporary=False):
assert isinstance(buddy_list, BuddyList) #type hint for PyDev
print "(2) initializing buddy %s, temporary=%s" % (address, temporary)
self.bl = buddy_list
self.address = address
self.name = name
self.profile_name = u""
self.profile_text = u""
self.profile_avatar_data = "" # uncompressed 64*64*24 bit RGB.
self.profile_avatar_data_alpha = "" # uncompressed 64*64*8 bit alpha. (optional)
self.profile_avatar_object = None # tc_gui.py will cache a wx.Bitmap here, tc_client will not touch this
self.random1 = str(random.getrandbits(256))
self.random2 = str(random.getrandbits(256))
self.conn_out = None
self.conn_in = None
self.status = STATUS_OFFLINE
self.client = ""
self.version = ""
self.timer = False
self.last_status_time = 0
self.count_failed_connects = 0
self.count_unanswered_pings = 0
self.active = True
self.temporary = temporary
self.startTimer()
def connect(self):
print "(2) %s.connect()" % self.address
if self.conn_out == None:
self.conn_out = OutConnection(self.address + ".onion", self.bl, self)
self.count_unanswered_pings = 0
self.sendPing()
def isFullyConnected(self):
return self.conn_in and self.conn_out and self.conn_out.pong_sent
def isAlreadyPonged(self):
return self.conn_out and self.conn_out.pong_sent
def disconnect(self):
print "(2) %s.disconnect()" % self.address
if self.conn_out != None:
self.conn_out.close()
self.conn_out = None
if self.conn_in != None:
self.conn_in.close()
self.conn_in = None
self.onStatus(STATUS_OFFLINE)
def onOutConnectionFail(self):
print "(2) %s.onOutConnectionFail()" % self.address
self.count_failed_connects += 1
self.startTimer()
def onInConnectionFail(self):
print "(2) %s.onInConnectionFail()" % self.address
self.resetConnectionFailCounter()
self.startTimer()
def onOutConnectionSuccess(self):
print "(2) %s.onOutConnectionSuccess()" % self.address
self.resetConnectionFailCounter()
self.count_unanswered_pings = 0
self.startTimer()
def onInConnectionFound(self, connection):
print "(2) %s.onInConnectionFound()" % self.address
self.count_unanswered_pings = 0
conn_old = self.conn_in
if conn_old == connection:
print "(2) this connection is already the current conn_in. doing nothing."
return
self.conn_in = connection
connection.buddy = self
if conn_old:
print "(2) closing old connection of %s, %s" % (self.address, conn_old)
print "(2) new connection is %s" % connection
conn_old.buddy = None
conn_old.close()
def resetConnectionFailCounter(self):
self.count_failed_connects = 0
def setActive(self, active):
print "(2) %s.setActive(%s)" % (self.address, active)
self.active = active
def setTemporary(self, temporary):
print "(2) %s.setTemporary(%s)" % (self.address, temporary)
self.temporary = temporary
def onStatus(self, status):
print "(2) %s.onStatus(%s)" % (self.address, status)
self.last_status_time = time.time()
if status <> self.status:
self.status = status
self.bl.gui(CB_TYPE_STATUS, self)
def onProfileName(self, name):
print "(2) %s.onProfile" % self.address
self.profile_name = name
if self.name == "" and name <> "":
self.name = name
self.bl.save()
self.bl.gui(CB_TYPE_PROFILE, self)
def onProfileText(self, text):
print "(2) %s.onProfile" % self.address
self.profile_text = text
self.bl.gui(CB_TYPE_PROFILE, self)
def onAvatarDataAlpha(self, data):
print "(2) %s.onAvatarDataAplha()" % self.address
# just store it, no gui callback because this is always sent first.
# The next message will be the acual image data which will finally notify the GUI
self.profile_avatar_data_alpha = data
def onAvatarData(self, data):
print "(2) %s.onAvatarData()" % self.address
if data <> self.profile_avatar_data:
self.profile_avatar_data = data
self.bl.gui(CB_TYPE_AVATAR, self)
def onChatMessage(self, message):
self.bl.gui(CB_TYPE_CHAT, (self, message))
def sendChatMessage(self, text):
#text must be unicode, will be encoded to UTF-8
if self.isFullyConnected():
message = ProtocolMsg_message(self, text.encode("UTF-8"))
message.send()
else:
self.storeOfflineChatMessage(text)
def getOfflineFileName(self):
return os.path.join(config.getDataDir(),self.address + "_offline.txt")
def storeOfflineChatMessage(self, text):
#text must be unicode
print "(2) storing offline message to %s" % self.address
file = open(self.getOfflineFileName(), "a")
file.write("[delayed] " + text.encode("UTF-8") + os.linesep)
file.close()
def getOfflineMessages(self):
#will return the string as unicode
try:
file = open(self.getOfflineFileName(), "r")
text = file.read().rstrip()
file.close()
return text.decode("UTF-8")
except:
return ""
def sendOfflineMessages(self):
#this will be called in the incoming status message
#FIXME: call this from onStatus() instead, this would be the ntural place for it
text = self.getOfflineMessages()
if text:
if self.isFullyConnected():
wipeFile(self.getOfflineFileName())
print "(2) sending offline messages to %s" % self.address
#we send it without checking online status. because we have sent
#a pong before, the receiver will have set the status to online.
#text is unicode, so we must encode it to UTF-8 again.
message = ProtocolMsg_message(self, text.encode("UTF-8"))
message.send()
self.bl.gui(CB_TYPE_OFFLINE_SENT, self)
else:
print "(2) could not send offline messages, not fully connected."
pass
def getDisplayNameOrAddress(self):
if self.name == "":
return self.address
else:
return self.name
def getAddressAndDisplayName(self):
if self.name == "":
return self.address
else:
return self.address + " (" + self.name + ")"
def sendFile(self, filename, gui_callback):
sender = FileSender(self, filename, gui_callback)
return sender
def startTimer(self):
if not self.active:
print "(2) %s is not active. Will not start a new timer" % self.address
return
if self.status == STATUS_OFFLINE:
if self.count_failed_connects < 10:
t = random.randrange(50, 150) / 10.0
else:
if self.count_failed_connects < 20:
t = random.randrange(300, 400)
else:
# more than an hour. The other one will ping us if it comes
# online which will immediately connect and reset the counting
t = random.randrange(5000, 6000)
print "(2) %s had %i failed connections. Setting timer to %f seconds" \
% (self.address, self.count_failed_connects, t)
else:
#whenever we are connected to someone we use a fixed timer.
#otherwise we would create a unique pattern of activity
#over time that could be identified at the other side
if self.status == STATUS_HANDSHAKE:
# ping more agressively during handshake
# to trigger more connect back attempts there
t = config.KEEPALIVE_INTERVAL / 4
else:
# when fully connected we can slow down to normal
t = config.KEEPALIVE_INTERVAL
if self.timer:
self.timer.cancel()
self.timer = threading.Timer(t, self.onTimer)
self.timer.start()
def onTimer(self):
print "(2) %s.onTimer()" % self.address
if not self.active:
print "(2) %s is not active, onTimer() won't do anything" % self.address
return
self.keepAlive()
#only restart the timer automatically if we are connected (or handshaking).
#else it will be restarted by outConnectionFail() / outConnectionSuccess()
if self.status != STATUS_OFFLINE:
self.startTimer()
def keepAlive(self):
print "(2) %s.keepAlive()" % self.address
if self.conn_out == None:
self.connect()
else:
if self.conn_in:
self.sendStatus()
else:
# still waiting for return connection
if self.count_unanswered_pings < config.MAX_UNANSWERED_PINGS:
self.sendPing()
print "(2) unanswered pings to %s so far: %i" % (self.address, self.count_unanswered_pings)
else:
# maybe this will help
print "(2) too many unanswered pings to %s on same connection" % self.address
self.disconnect()
def sendPing(self):
print "(2) PING >>> %s" % self.address
#self.random1 = str(random.getrandbits(256))
ping = ProtocolMsg_ping(self, (config.get("client","own_hostname"), self.random1))
ping.send()
self.count_unanswered_pings += 1
def sendStatus(self):
if self.isAlreadyPonged():
status = ""
if self.bl.own_status == STATUS_ONLINE:
status = "available"
if self.bl.own_status == STATUS_AWAY:
status = "away"
if self.bl.own_status == STATUS_XA:
status = "xa"
if status != "":
print "(2) %s.sendStatus(): sending %s" % (self.address, status)
msg = ProtocolMsg_status(self, status)
msg.send()
else:
print "(2) %s.sendStatus(): not connected, not sending" % self.address
def sendProfile(self):
if self.isAlreadyPonged():
print "(2) %s.sendProfile()" % self.address
# this message is optional
name = config.get("profile", "name")
if name <> "":
msg = ProtocolMsg_profile_name(self, name.encode("UTF-8"))
msg.send()
# this message is optional
text = config.get("profile", "text")
if text <> "":
msg = ProtocolMsg_profile_text(self, text.encode("UTF-8"))
msg.send()
def sendAvatar(self, send_empty=False):
if self.isAlreadyPonged():
print "(2) %s.sendAvatar()" % self.address
# the GUI has put our own avatar into the BuddyList object, ready for sending.
# avatar is optional but if sent then both messages must be in the following order:
if self.bl.own_avatar_data or send_empty:
# alpha might be empty (0 bytes) but we must always send it.
data = self.bl.own_avatar_data_alpha
msg = ProtocolMsg_profile_avatar_alpha(self, data) #send raw binary data
msg.send()
data = self.bl.own_avatar_data
msg = ProtocolMsg_profile_avatar(self, data) #send raw binary data
msg.send()
else:
print "(2) we have no avatar, sending nothing"
else:
print "(2) %s.sendAvatar(): not connected, not sending avatar" % self.address
def sendAddMe(self):
if self.isAlreadyPonged():
msg = ProtocolMsg_add_me(self)
msg.send()
else:
print "(2) not connected, not sending add_me to %s" % self.address
def sendRemoveMe(self):
if self.isFullyConnected():
msg = ProtocolMsg_remove_me(self)
msg.send()
else:
print "(2) not connected, not sending remove_me to %s" % self.address
def sendVersion(self):
if self.isAlreadyPonged():
msg = ProtocolMsg_client(self, version.NAME)
msg.send()
msg = ProtocolMsg_version(self, version.VERSION)
msg.send()
else:
print "(2) not connected, not sending version to %s" % self.address
def getDisplayName(self):
if self.name != "":
line = "%s (%s)" % (self.address, self.name)
else:
line = self.address
return line
class BuddyList(object):
"""the BuddyList object is the central API of the client.
Initializing it will start the client, load and initialize
all Buddy objects on the buddy list, etc. It does much more
than only maintaining the buddies, it also maintains a bunch
of other objects like for example the FileSender and
FileReceiver objects for currrently running file transfers etc.
BuddyList actually represents the whole client functionality
and controls everything else.
The GUI will instantiate a BuddyList object and this is all
it needs to do in order to start the client and access
all functionality"""
def __init__(self, callback, socket=None):
print "(1) initializing buddy list"
self.gui = callback
startPortableTor()
self.file_sender = {}
self.file_receiver = {}
#temporary buddies, created from incoming pings with new hostnames
#these buddies are not yet in the list and if they do not
#answer and authenticate on the first try they will be deleted
self.incoming_buddies = []
self.listener = Listener(self, socket)
self.own_status = STATUS_ONLINE
filename = os.path.join(config.getDataDir(), "buddy-list.txt")
#create empty buddy list file if it does not already exist
f = open(filename, "a")
f.close()
f = open(filename, "r")
l = f.read().replace("\r", "\n").replace("\n\n", "\n").split("\n")
f.close
self.list = []
for line in l:
line = line.rstrip().decode("UTF-8")
if len(line) > 15:
address = line[0:16]
if len(line) > 17:
name = line[17:]
else:
name = u""
buddy = Buddy(address, self, name)
self.list.append(buddy)
found = False
for buddy in self.list:
if buddy.address == config.get("client", "own_hostname"):
found = True
self.own_buddy = buddy
break
if not found:
print "(1) adding own hostname %s to list" % config.get("client", "own_hostname")
if config.get("client", "own_hostname") != "0000000000000000":
self.own_buddy = Buddy(config.get("client", "own_hostname"),
self,
"myself")
self.addBuddy(self.own_buddy)
# the own avatar is set by the GUI.
# Only the GUI knows how to deal with graphics, so we just
# provide these variables, if the GUI puts the 64*64*24 RGB bitmaps
# here and an optional alpha channel 64*64*8 and then it will be
# transmitted as it is. tc_client.py will not interpret or convert it,
# only transmit and receive this raw data and notify the GUI
self.own_avatar_data = ""
self.own_avatar_data_alpha = ""
print "(1) BuddList initialized"
def save(self):
f = open(os.path.join(config.getDataDir(), "buddy-list.txt"), "w")
for buddy in self.list:
line = ("%s %s\r\n" % (buddy.address, buddy.name.rstrip())).encode("UTF-8")
f.write(line)
f.close()
print "(2) buddy list saved"
# this is the optimal spot to notify the GUI to redraw the list
self.gui(CB_TYPE_LIST_CHANGED, None)
def logMyselfMessage(self, msg):
self.own_buddy.onChatMessage("*** %s" % msg)
def addBuddy(self, buddy):
if self.getBuddyFromAddress(buddy.address) == None:
self.list.append(buddy)
buddy.setTemporary(False)
buddy.setActive(True)
if buddy in self.incoming_buddies:
self.incoming_buddies.remove(buddy)
self.save()
buddy.keepAlive()
return buddy
else:
return False
def removeBuddy(self, buddy_to_remove, disconnect=True):
print "(2) removeBuddy(%s, %s)" % (buddy_to_remove.address, disconnect)
self.gui(CB_TYPE_REMOVE, buddy_to_remove)
buddy_to_remove.setActive(False)
if not disconnect:
# send remove_me and leave the connections open
# but remove them from this buddy.
# the connections will be closed by the other buddy
# or if the timeout for unused connections occurs
buddy_to_remove.sendRemoveMe()
if buddy_to_remove.conn_out:
buddy_to_remove.conn_out.buddy = None
buddy_to_remove.conn_out = None
if buddy_to_remove.conn_in:
buddy_to_remove.conn_in.buddy = None
buddy_to_remove.conn_in = None
else:
buddy_to_remove.disconnect()
self.list.remove(buddy_to_remove)
file_name = buddy_to_remove.getOfflineFileName()
try:
wipeFile(file_name)
except:
pass
self.save()
def removeBuddyWithAddress(self, address):
buddy = self.getBuddyFromAddress(address)
if buddy != None:
self.removeBuddy(buddy)
def getBuddyFromAddress(self, address):
for buddy in self.list:
if buddy.address == address:
return buddy
return None
def getIncomingBuddyFromAddress(self, address):
for buddy in self.incoming_buddies:
if buddy.address == address:
return buddy
return None
def getBuddyFromRandom(self, random):
for buddy in self.list:
if buddy.random1 == random:
return buddy
return None
def getIncomingBuddyFromRandom(self, random):
for buddy in self.incoming_buddies:
if buddy.random1 == random:
return buddy
return None
def getFileReceiver(self, address, id):
try:
return self.file_receiver[address, id]
except:
return None
def getFileSender(self, address, id):
try:
return self.file_sender[address, id]
except:
return None
def setStatus(self, status):
self.own_status = status
for buddy in self.list:
buddy.sendStatus()
def onErrorIn(self, connection):
for buddy in self.incoming_buddies:
if buddy.conn_in == connection:
print "(2) in-connection %s of temporary buddy %s failed" % (connection, buddy.address)
print "(2) removing buddy instance %s" % buddy.address
buddy.setActive(False)
buddy.disconnect()
if buddy in self.incoming_buddies:
self.incoming_buddies.remove(buddy)
break
for buddy in self.list:
if buddy.conn_in == connection:
buddy.disconnect()
buddy.onInConnectionFail()
break
def onErrorOut(self, connection):
buddy = connection.buddy
if buddy:
if buddy.temporary:
print "(2) out-connection of temporary buddy %s failed" % buddy.address
print "(2) removing buddy instance %s" % buddy.address
buddy.setActive(False)
if buddy in self.incoming_buddies:
self.incoming_buddies.remove(buddy)
buddy.disconnect()
buddy.onOutConnectionFail()
else:
print "(2) out-connection without buddy failed"
def onConnected(self, connection):
connection.buddy.onStatus(STATUS_HANDSHAKE)
connection.buddy.onOutConnectionSuccess()
def stopClient(self):
stopPortableTor()
for buddy in self.list + self.incoming_buddies:
buddy.disconnect()
self.listener.close() #FIXME: does this really work?
class FileSender(threading.Thread):
def __init__(self, buddy, file_name, callback):
threading.Thread.__init__(self)
self.buddy = buddy
self.bl = buddy.bl
self.file_name = file_name
self.file_name_short = os.path.basename(self.file_name)
self.gui = callback
self.id = str(random.getrandbits(32))
self.buddy.bl.file_sender[self.buddy.address, self.id] = self
self.file_size = 0
self.block_size = 8192
self.blocks_wait = 16
self.start_ok = -1
self.restart_at = 0
self.restart_flag = False
self.completed = False
self.timeout_count = 0
self.start()
def testTimeout(self):
#this will be called every 0.1 seconds whenever the sender
#is waiting for confirmation messages. Either in the
#sendBlocks() loop or when all blocks are sent in the
#outer loop in run()
#if a timeout is detected then the restart flag will be set
if self.buddy.isFullyConnected():
#we only increase timeout if we are connected
#otherwise other mechanisms are responsible and trying
#to get us connected again and we just wait
self.timeout_count += 1
else:
self.timeout_count = 0
if self.timeout_count == 6000:
#ten minutes without filedata_ok
new_start = self.start_ok + self.block_size
self.restart(new_start)
#enforce a new connection
try:
self.buddy.disconnect()
except:
pass
print "(2) timeout file sender restart at %i" % new_start
def canGoOn(self, start):
position_ok = self.start_ok + self.blocks_wait * self.block_size
if not self.running or self.restart_flag:
return True
else:
return position_ok > start
def sendBlocks(self, first):
blocks = int(self.file_size / self.block_size) + 1
print "(2) FileSender now entering inner loop, starting at block #%i, last block in file #%i" \
% (first, blocks - 1)
#the inner loop (of the two loops
for i in range(blocks):
start = i * self.block_size
#jump over already sent blocks
if start >= first:
remaining = self.file_size - start
if remaining > self.block_size:
size = self.block_size
else:
size = remaining
self.file_handle.seek(start)
data = self.file_handle.read(size)
hash = hashlib.md5(data).hexdigest()
#we can only send data if we are connected
while not self.buddy.isFullyConnected() and not self.restart_flag:
time.sleep(0.1)
self.testTimeout()
# the message is sent over conn_in
msg = ProtocolMsg_filedata(self.buddy.conn_in, (self.id, start, hash, data))
msg.send()
#wait for confirmations more than blocks_wait behind
while not self.canGoOn(start):
time.sleep(0.1)
self.testTimeout() #this can trigger the restart flag
if self.restart_flag:
#the outer loop in run() will start us again
print "(2) FileSender restart_flag, breaking innner loop"
break
if not self.running:
#the outer loop in run() will also end
print "(2) FileSender not running, breaking innner loop"
break
print "(2) FileSender inner loop ended, last sent block: #%i, last block in file #%i" % (i, blocks-1)
def run(self):
self.running = True
try:
self.file_handle = open(self.file_name, mode="rb")
self.file_handle.seek(0, 2) #SEEK_END
self.file_size = self.file_handle.tell()
self.gui(self.file_size, 0)
filename_utf8 = self.file_name_short.encode("utf-8")
if not self.buddy.isFullyConnected():
print "(2) file transfer waiting for connection"
self.gui(self.file_size, 0, "waiting for connection")
# self.running will be set to false when the user hits "cancel"
# wait for connection to start file transfer
while self.running and not self.buddy.isFullyConnected():
time.sleep(1)
# user could have aborted while waiting in the loop above
if self.running:
print "(2) sending 'filename' message"
self.gui(self.file_size, 0, "starting transfer")
msg = ProtocolMsg_filename(self.buddy.conn_in, (self.id, self.file_size, self.block_size, filename_utf8))
msg.send()
#the outer loop (of the two sender loops)
#runs forever until completed ore canceled
while self.running and not self.completed:
print "(2) FileSender now at start of retry loop"
self.restart_flag = False
#(re)start the inner loop
self.sendBlocks(self.restart_at)
#wait for *last* filedata_ok or restart flag
while self.running and not self.completed and not self.restart_flag:
time.sleep(0.1)
self.testTimeout() #this can trigger the restart flag
if self.running:
print "(2) FileSender, retry loop ended because of success"
else:
print "(2) FileSender, retry loop ended because of cancel"
self.running = False
self.file_handle.close()
except:
# haven't seen this happening yet
self.gui(self.file_size,
-1,
"error")
self.close()
tb()
def receivedOK(self, start):
self.timeout_count = 0 # we have received a sign of life
end = start + self.block_size
if end > self.file_size:
end = self.file_size
try:
self.gui(self.file_size, end)
except:
#cannot update gui
tb()
self.close()
self.start_ok = start
if end == self.file_size:
#the outer sender loop can now stop waiting for timeout
self.gui(self.file_size, end, "transfer complete")
self.completed = True
def restart(self, start):
#trigger the reatart flag
self.timeout_count = 0
self.restart_at = start
self.restart_flag = True
#the inner loop will now immediately break and
#the outer loop will start it again at position restart_at
def sendStopMessage(self):
msg = ProtocolMsg_file_stop_receiving(self.buddy, self.id)
msg.send()
def close(self):
if self.running:
self.running = False
self.sendStopMessage()
try:
self.gui(self.file_size, -1, "transfer aborted")
except:
pass
del self.buddy.bl.file_sender[self.buddy.address, self.id]
class FileReceiver(object):
# ths will be instantiated automatically on an incoming file transfer.
# it will then notify the GUI which will open a window and give us a callback to interact
def __init__(self, buddy, id, block_size, file_size, file_name):
self.buddy = buddy
self.id = id
self.closed = False
self.block_size = block_size
self.file_name = file_name
self.file_name_save = ""
tmp = createTemporaryFile(self.file_name)
self.file_name_tmp, self.file_handle_tmp = tmp
print "(2) FileReceiver: created temp file: %s" % self.file_name_tmp
self.file_size = file_size
self.next_start = 0
self.wrong_block_number_count = 0
self.buddy.bl.file_receiver[self.buddy.address, self.id] = self
#this will (MUST) point to the file transfer GUI callback
self.gui = None
#the following will result in a call into the GUI
#the GUI will then give us a callback function
print "(2) FileReceiver: notifying GUI about new file transfer"
self.buddy.bl.gui(CB_TYPE_FILE, self)
#we cannot receive without a GUI (or other piece of code
#that provides the callback) because this other code
#(usually the GUI) will decide what to do with the file
#and will be responsible to close this FileReceiver object
#again after it is done.
#therefore now we wait for the callback
#function to be provided before we continue.
#It CANNOT get stuck in this loop unless the GUI
#code is broken. The GUI WILL provide this callback!
while self.gui == None:
time.sleep(0.1)
print "(2) FileReceiver: attached GUI seems ready, initialization done"
def setCallbackFunction(self, callback):
# this must be called from the GUI
# to set the callback function so we can notify
# the GUI about the progress (or errors)
self.gui = callback
def data(self, start, hash, data):
if self.closed:
# ignore still incoming data blocks
# for already aborted transfers
print "(2) ignoring incoming file data block for canceled receiver"
return
if start > self.next_start:
if self.wrong_block_number_count == 0: