forked from hcwang95/P2PChat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
P2PChat.py
1130 lines (1053 loc) · 41.5 KB
/
P2PChat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
# Student name and No.: WANG Haicheng 3035140108
# Student name and No.: N/A
# Development platform: Ubuntu 1604
# Python version: Python 3.5.2
# Version: 1.2
from tkinter import *
import sys
import socket
import re
from threading import Thread, Lock
from time import sleep
from functools import reduce
from select import select
#
# Global constant
#
BUFSIZ = 1024
PROTOCAL_END = '::\r\n'
PROTOCAL_TIME = 20
#
# Global variables
# define some state, actions and self-defined exceptions
#
States = {'STARTED' : 0,
'NAMED' : 1,
'JOINED' : 2,
'CONNECTED' : 3,
'TERMINATED' : 4 }
Actions = {'USER' : 5,
'LIST' : 6,
'JOIN' : 7,
'SEND' : 8,
'QUIT' : 9,
'HANDSHAKE' : 10}
Exceptions = {'INVALID_USERNAME' : 11,
'SOCKET_ERROR' : 12,
'BACKWARDLINK_NOT_EXIST' : 13,
'BACKWARDLINK_ALREADY_EXIST' : 14,
'TIMEOUT' : 15,
'ROOMSERVERE_ERROR' : 16,
'SOCKET_BIND_ERROR' : 17,
'NOT_FIND_ERROR' : 18}
# two core global variables that maintain crucial info
currentState = None
user = None
# two lock for maintaining user info and current state info
stateLock = Lock()
userInfoLock = Lock()
# user class
# maintaining user program basic info
# include:
# 1. roomserver ipv4 address (type: string, accept 'localhost')
# and port number (type:int)
# 2. p2pclient listening port (type:int)
# 3. user socket connecting to roomserver and
# and socket as local server socket
# 4. username validation rules
class User():
def __init__(self , serverIP, serverPort,
localIP , localPort):
self._setip(localIP)
self._setportnumber(localPort)
self._username = None
self._clientSocket = None
self._serverSocket = None
## here we define the username validation rule
self.validation = re.compile("^[\x00-\x7F]+$")
self._socketSetup(serverIP, serverPort)
def _socketSetup(self, serverIP=None, serverPort=None, localIP=None, localPort=None):
# procedure for setting up user socket
# this function will be call twice,
# first for setting up socket connecting roomserver
# second for setting listening socket (server socket)
print("setting up user socket...")
if (serverIP is not None and serverPort is not None):
self._clientSocket = socket.socket()
# connect with room server with clientSocket
try:
self._clientSocket.connect((serverIP, serverPort))
print('finish setting user socket: connected to roomserver[',
serverIP,',',serverPort,']')
except OSError as errmsg:
print('Failed to connect to roomServer: ', errmsg)
print('try again')
try:
self._clientSocket.connect((serverIP, serverPort))
print('finish setting user socket: connected to roomserver[',
serverIP,',',serverPort,']')
except:
print('Failed to connect to roomServer again: ', errmsg)
print(('p2pclient program shutdowns due to failure to connect to roomserver, '
'please check if the server address and port are correct, or check if '
'the server is already working'))
self._clientSocket.close()
sys.exit(1)
if (localPort is not None):
# establish p2p server socket and start listening
self._serverSocket = socket.socket()
try:
self._serverSocket.bind((localIP,localPort))
self._serverSocket.listen(10)
print('finish setting user socket: open server port:', localPort)
except OSError as emsg:
print("Socket bind error: ", emsg)
print("try again")
try:
self._serverSocket.bind((localIP,localPort))
# personal choice of length of listen queue
# enough to pass all pressure test at most 50 concurrent requests
self._serverSocket.listen(10)
print('finish setting user socket: open server port:', localPort)
except OSError as emsg:
print("Socket bind error again: ", emsg)
print( ('p2pclient program shutdowns due to failure to bind the listening socket '
', please check your socket usage and try another available port'))
self._serverSocket.close()
return[Exceptions['SOCKET_BIND_ERROR']]
else:
print('Ignore binding port for the time being')
# some basic private setter and getter
def _setname(self, name):
self._username = name
def _setip(self, ip):
if ip == '':
self._IP = 'localhost'
else:
self._IP = ip
def _setportnumber(self, port):
self._port = port
def _getname(self):
return self._username
def _getip(self):
return self._IP
def _getport(self):
return self._port
def _getClientSocket(self):
return self._clientSocket
def _getServerSocket(self):
return self._serverSocket
# boolean function for condition checking
def hasUserName(self):
return self._getname() is not None
# higher public function to set name
def setUserName(self, username):
# check first
if (self.validation.match(username) is None) or (':' in username):
return Exceptions['INVALID_USERNAME']
self._setname(username)
# public function for set up server socket binding
# call lower private function for clean abstraction
def bindServerSocket(self):
return self._socketSetup(serverIP = None, serverPort = None,
localIP = self._getip(), localPort = self._getport())
# state class
# containing current state info
# include:
# 1. current room name (default None)
# 2. current room info (a list [MSID, userAName, userAIp, userAPort,
# userBName, userBIp, userBPort,...])
# 3. forward Links and corresponding update function
# 4. backward Links List and corresponding update function
# 5. msgID and corresponding update function
# 6. some facilitate function for better abstraction and
# seperate of responsibility
class State():
def __init__(self):
self._setstate(States['STARTED'])
self._setroomname(None)
self._setroominfo(None)
self._setmsgid(0)
self._linksetup()
# basic setter and getter
def _setstate(self,state):
self._state = state
def _getstate(self):
return self._state
def _setroomname(self,name):
self._roomname = name
def _getroomname(self):
return self._roomname
def _setroominfo(self,info):
# print('setting room info')
# print('info is ', info)
self._roominfo = info
# print('after setting, roominfo is', self._roominfo)
def _getroominfo(self):
return self._roominfo
def _setforwardlink(self, forwardLink):
self._forwardlink = forwardLink
if forwardLink is not None:
print("set forward link with hash", forwardLink[0])
def _linksetup(self):
self._backwardlinks = []
self._setforwardlink(None)
def _setmsgid(self, msgID):
self._msgid = msgID
def _getmsgid(self):
return self._msgid
def _getforwardlink(self):
return self._forwardlink
def _addbackwardlinks(self, tuple):
if hash in self._backwardlinks:
return Exceptions['BACKWARDLINK_ALREADY_EXIST']
else:
self._backwardlinks.append(tuple)
# print('add new backward link with hash', tuple[0])
def _removeforwardlink(self):
self._forwardlink = None
def _removebackwardlinksBySocket(self, socket):
for socketTuple in self._getbackwardlinks():
if socketTuple[1] is socket:
self._backwardlinks.remove(socketTuple)
return
return Exceptions['BACKWARDLINK_NOT_EXIST']
def _getbackwardlinks(self):
return self._backwardlinks
# function for state transition record
def stateTransition(self, action):
self._setstate(transition(self._getstate(),action))
# print('state transit:', self._getstate())
# public function to update room name
def updateRoomName(self, roomName):
self._setroomname(roomName)
# public function to update room infomation
def updateRoomInfo(self, roomInfo):
if self._getroominfo() is None:
self._setroominfo(roomInfo)
elif self._getroominfo()[0] != roomInfo[0]:
self._setroominfo(roomInfo)
else:
pass
# print('room member list: duplicated info, do not update')
# function for condition checking
# isAfter means strictly after one of the state
# for example, after 'Joined' is 'connected' and 'terminated'
def isAfter(self, state):
return self._getstate() > state
# function for condition checking
# return true if the peer program now is in chatroom
def inRoom(self):
return self._getroomname() is not None
# public function for update message ID
# when getting message passively
def updateMsgID(self, msgID):
if self._getmsgid() < msgID:
self._setmsgid(msgID)
# public function for update message ID when
# sending message actively
def newMsgID(self):
msgID = self._getmsgid()
self._setmsgid(msgID+1)
return msgID+1
# facilite function for getting socket base on its hash value
# will return error if cannot find
def getSocketFromHash(self, hash_):
if (self._getforwardlink() is not None) and (self._getforwardlink()[0] == hash_):
return self._getforwardlink()[1]
for i in self._getbackwardlinks():
if i[0] == hash_:
return i[1]
return Exceptions['NOT_FIND_ERROR']
#
# This is the hash function for generating a unique
# Hash ID for each peer.
# Source: http://www.cse.yorku.ca/~oz/hash.html
#
# Concatenate the peer's username, str(IP address),
# and str(Port) to form the input to this hash function
#
def sdbm_hash(instr):
hash = 0
for c in instr:
hash = int(ord(c)) + (hash << 6) + (hash << 16) - hash
return hash & 0xffffffffffffffff
# facilite function for getting hashlist based on the roominfo
def getHashList(roomInfo):
return list(map(lambda x: sdbm_hash(x),
map(lambda x: reduce(lambda m, n: m+n, x),
[roomInfo[y:y+3] for y in range(1,len(roomInfo),3)])))
# five facilited state transition functions:
def FromStarted(action):
return {Actions['LIST']: States['STARTED'],
Actions['USER']: States['NAMED'],
Actions['QUIT']: States['TERMINATED']}[action]
def FromNamed(action):
return {Actions['LIST']: States['NAMED'],
Actions['USER']: States['NAMED'],
Actions['JOIN']: States['JOINED'],
Actions['QUIT']: States['TERMINATED']}[action]
def FromJoined(action):
return {Actions['LIST']: States['JOINED'],
Actions['SEND']: States['JOINED'],
Actions['HANDSHAKE']: States['CONNECTED'],
Actions['QUIT']: States['TERMINATED']}[action]
def FromConnected(action):
return {Actions['LIST']: States['CONNECTED'],
Actions['SEND']: States['CONNECTED'],
Actions['HANDSHAKE']: States['CONNECTED'],
Actions['QUIT']: States['TERMINATED']}[action]
def FromTerminated(action):
return States['TERMINATED']
# state transition function, critical, calling should be protected by logic
def transition(currentState, action):
return {States['STARTED']: lambda x: FromStarted(x),
States['NAMED']: lambda x: FromNamed(x),
States['JOINED']: lambda x: FromJoined(x),
States['CONNECTED']: lambda x: FromConnected(x),
States['TERMINATED']: lambda x : FromTerminated(x)}[currentState](action)
# function for handshake process in stage 2
# can find the index in the roomInfo based
# on three infomation provided
def findPosition(roomInfo, name, ip, port):
for i in range(1,len(roomInfo),3):
# print(roomInfo[i], roomInfo[i+1], roomInfo[i+2])
if name == roomInfo[i] and ip == roomInfo[i+1] and port == int(roomInfo[i+2]):
return int((i-1)/3)
return None
#
# functions for socket sending and receiving with block
# similar to C and C++ marco just for reducing duplication
# one extra argument for option whether sender is looking for
# response message
#
def socketOperation(socket, sendMessage, receive = True):
try:
socket.send(sendMessage.encode('ascii'))
except IOError as errmsg:
print('socket', socket, ' sending error: ', errmsg)
return Exceptions['SOCKET_ERROR']
if receive:
try:
responseData = socket.recv(BUFSIZ)
except IOError as errmsg:
print('socket', socket, ' receving error: ', errmsg)
return Exceptions['SOCKET_ERROR']
return responseData.decode('ascii')
#
# functions for blocking socket to send and recv message
# with timeout option, return Exception['TIMEOUT'] if timeout
# para: timeout (type-> seconds)
# will return timeout exception if timeout occurs
#
def socketOperationTimeout(socket, sendMessage, timeout):
readList = [socket]
try:
socket.send(sendMessage.encode('ascii'))
except OSError as errmsg:
print('socket sending error: ', errmsg)
return Exceptions['SOCKET_ERROR']
# realize timeout feature by select
available = select(readList, [], [], timeout)
if available:
sockfd = readList[0]
try:
responseData = sockfd.recv(BUFSIZ)
return responseData.decode('ascii')
except OSError as errmsg:
print('socket receving error: ', errmsg)
return Exceptions['SOCKET_ERROR']
else:
return Exceptions['TIMEOUT']
# abstraction for checking exit status
# must be inside of stateLock
def checkExit(threadName):
global currentState
if currentState.isAfter(States['CONNECTED']):
print(threadName + ': find exit state, quiting ...')
stateLock.release()
sys.exit(1)
#
# functions for facilitation threads of keep alive procedure
# resend 'JOIN' request ever 20 seconds after successfully joining
#
def keepAliveThread():
global currentState, user
print('\nkeep alive thread start working ... ')
while True:
for i in range(20):
stateLock.acquire()
checkExit("Keep alive")
stateLock.release()
sleep(PROTOCAL_TIME / 20)
userInfoLock.acquire()
clientSocket = user._getClientSocket()
message = ':'.join([currentState._getroomname(), user._getname(), user._getip(), str(user._getport())])
requestMessage = 'J:' + message + PROTOCAL_END
responseMessage = socketOperation(clientSocket, requestMessage)
userInfoLock.release()
if (responseMessage[0] != 'M'):
CmdWin.insert(1.0, "\nFailed to join: roomserver error\n")
continue
stateLock.acquire()
currentState.updateRoomInfo(responseMessage.replace(PROTOCAL_END,'').split(':')[1:])
stateLock.release()
print('Keep alive: keep alive action finish\n')
#
# thread for handshake procedure
# follow the logic of spec
#
def handShakeThread(startListen):
# get info of chatroom
global currentState, user
# find myself position in the roomInfo
userInfoLock.acquire()
myName = user._getname()
myIp = user._getip()
myPort = user._getport()
userInfoLock.release()
successFlag = 0
while 1:
# update roominfo again
# and check state in order to quit elegantly
userInfoLock.acquire()
clientSocket = user._getClientSocket()
message = ':'.join([currentState._getroomname(), user._getname(), user._getip(), str(user._getport())])
requestMessage = 'J:' + message + PROTOCAL_END
responseMessage = socketOperation(clientSocket, requestMessage)
# validate the responseMessage it get back
if (responseMessage[0] != 'M'):
print('Handshake: failed to request roomserver to update data')
CmdWin.insert(1.0, "\nroomserver error\n")
userInfoLock.release()
continue
userInfoLock.release()
stateLock.acquire()
# check if it need to exit
checkExit("Handshake")
currentState.updateRoomInfo(responseMessage.replace(PROTOCAL_END,'').split(':')[1:])
roomName = currentState._getroomname()
roomInfo = currentState._getroominfo()
msgID = currentState._getmsgid()
stateLock.release()
myPosition = findPosition(roomInfo, myName, myIp, myPort)
# calculate hash of each user in the chatroom
hashList = getHashList(roomInfo)
myHash = hashList[myPosition]
indexHashList = zip(range(len(hashList)), hashList)
gList = sorted(indexHashList, key=lambda x : x[1])
start = (gList.index((myPosition, myHash)) + 1) % len(gList)
# probe and connect precedure
handShakeSocket = socket.socket()
while gList[start][0] != myPosition:
print('HandShake: approach user',roomInfo[1+3*gList[start][0]:4+3*gList[start][0]])
stateLock.acquire()
backwardLinkTupleList = currentState._getbackwardlinks()
backwardLinkHashList = [i[0] for i in backwardLinkTupleList]
stateLock.release()
if gList[start][1] in backwardLinkHashList:
print('HandShake: try with one connection but find it already in backward list, try another')
start = (start + 1) % len(gList)
continue
else:
# try to approach by connecting
realIndex = gList[start][0]*3 + 1
try:
handShakeSocket.connect((roomInfo[realIndex+1], int(roomInfo[realIndex+2])))
except OSError as errmsg:
print('HandShake: try to connect with[', roomInfo[realIndex+1],
',',roomInfo[realIndex+2],
']but failed, try another')
start = (start + 1) % len(gList)
handShakeSocket = socket.socket()
continue
# run peer to peer handshake
message = ":".join([roomName,myName,myIp,str(myPort),str(msgID)])
requestMessage = 'P:' + message + PROTOCAL_END
# use blocking with timeout to handle no response case
responseMessage = socketOperationTimeout(handShakeSocket, requestMessage, 1)
if responseMessage is Exceptions['TIMEOUT']:
print("HandShake: timeout, try another socket")
handShakeSocket = socket.socket()
start = (start + 1) % len(gList)
continue
if responseMessage is Exceptions['SOCKET_ERROR']:
print('HandShake: try peer-to-peer handshake with [', roomInfo[realIndex+1],
',',roomInfo[realIndex+2],
'] but failed, try another')
start = (start + 1) % len(gList)
continue
# if sucessfully establish handshake (forwardlink)
if responseMessage[0] == 'S':
print('HandShake: successfully connect with a peer through peer-to-peer handshake with',
roomInfo[realIndex])
message = responseMessage.replace(PROTOCAL_END, '').split(':')[1:]
stateLock.acquire()
currentState.updateMsgID(int(message[0]))
stateLock.release()
successFlag = 1
hashStr = reduce(lambda x, y: x+y, roomInfo[realIndex: realIndex+3])
forwardHash = sdbm_hash(hashStr)
break
# after first probing of forwardlink
# set up server socket no matter of success or not
if not startListen:
userInfoLock.acquire()
flag = user.bindServerSocket()
userInfoLock.release()
if flag is Exceptions['SOCKET_BIND_ERROR']:
stateLock.acquire()
currentState.stateTransition(Actions['QUIT'])
stateLock.release()
sys.exit(1)
serverThread = Thread(target=serverSocketThread, name='server')
serverThread.start()
startListen = 1
# if sucess then store the forwardlink info and quit
if successFlag == 1:
stateLock.acquire()
currentState.stateTransition(Actions['HANDSHAKE'])
handShakeTuple = (forwardHash, handShakeSocket)
currentState._setforwardlink(handShakeTuple)
stateLock.release()
CmdWin.insert(1.0, '\nSuccessfully connected with one of the peer in the chatroom!\n')
break
# if failed, report it in the terminal and then try 4 seconds later
else:
handshakeTime = PROTOCAL_TIME / 5
print('HandShake: currently cannot find a forward link with one loop, do it again', handshakeTime,'seconds later\n')
for i in range(4):
stateLock.acquire()
checkExit("Handshake")
stateLock.release()
sleep(handshakeTime / 4)
print('HandShake: finish work and shutdown ... \n')
#
# server socket thread logic
# core thread handle p2p process and message sending
# constantly listening at the port after starting
# handle 1. p2p backwardlink establishment
# 2. message receiving and broadcast
# 3. handle backward or forward link quitting
# and trigger next round of p2p procedure
#
def serverSocketThread():
# setup basic variable
global user, currentState
print("\nServer Thread: start working ...")
userInfoLock.acquire()
serverSocket = user._getServerSocket()
clientSocket = user._getClientSocket()
myName = user._getname()
myIp = user._getip()
myPort = user._getport()
userInfoLock.release()
stateLock.acquire()
forwardLinkTuple = currentState._getforwardlink()
roomName = currentState._getroomname()
roomInfo = currentState._getroominfo()
stateLock.release()
hashList = getHashList(roomInfo)
readList = [serverSocket]
forwardLinkHash = None
if (forwardLinkTuple):
readList.append(forwardLinkTuple[1])
forwardLinkHash = forwardLinkTuple[0]
# main loop
while 1:
# check exit condition
stateLock.acquire()
checkExit('Server Thread')
# check if there is a forward link
forwardLinkTuple = currentState._getforwardlink()
if forwardLinkTuple is not None and forwardLinkTuple[1] not in readList:
readList.append(forwardLinkTuple[1])
forwardLinkHash = forwardLinkTuple[0]
else:
pass
# print("Server Thread: havn't got forward link socket, try it later")
stateLock.release()
print('Server Thread: listening ...')
# use select to realize server listening procedure
try:
readable, writeable, exceptions = select(readList,[],[],PROTOCAL_TIME/5)
except Exception as errmsg:
# if server failed then close the program
# rarely happens in the test
print("Server Thread: encounter error", errmsg)
print("Server Thread: shutdown due to server socket ... ")
stateLock.acquire()
currentState.stateTransition(Actions['QUIT'])
stateLock.release()
sys.exit(1)
if readable:
print('\nServer Thread: catch something')
for sockfd in readable:
# check forwardlink again
stateLock.acquire()
forwardLinkTuple = currentState._getforwardlink()
if forwardLinkTuple is not None and forwardLinkTuple[1] not in readList:
readList.append(forwardLinkTuple[1])
forwardLinkHash = forwardLinkTuple[0]
else:
pass
# print("Server Thread: havn't got forward link socket, try it later")
stateLock.release()
# handle p2p connection procedure
if sockfd is serverSocket:
backwardLink, address = sockfd.accept()
requestData = backwardLink.recv(BUFSIZ)
requestMessage = requestData.decode('ascii')
# validate message
# frist filter to ensure it is not quiting message:
if requestMessage == 'QUIT'+PROTOCAL_END:
print('Server Thread: receive quitting message, quiting ...\n')
responseMessage = 'OK'+PROTOCAL_END
socketOperation(backwardLink, responseMessage, receive=False)
# close all sockets
for socketToClose in readList:
socketToClose.close()
sys.exit(0)
# check protocol pattern
pattern ="^P:[^:]+:[^:]+:(((\d+\.){3}\d+)|localhost):\d+:\d+::\r\n$"
if (re.match(pattern, requestMessage) is None):
print('Server Thread: receive an invlid request', requestMessage)
print('Server Thread: refuse that request by ignoring it')
backwardLink.close()
continue
# check if there exist in the room info
message = requestMessage.replace(PROTOCAL_END, '').split(':')[1:]
roomNameGet = message[0]
backwardLinkUserName = message[1]
backwardLinkIp = message[2]
backwardLinkPort = int(message[3])
backwardLinkMsgID = int(message[4])
stateLock.acquire()
roomInfo = currentState._getroominfo()
stateLock.release()
# update room infomation if needed
if (findPosition(roomInfo, backwardLinkUserName, backwardLinkIp, backwardLinkPort) is None):
print('Server Thread: finding that there is no info of newly backward link, update roominfo and check again')
stateLock.acquire()
message_ = ':'.join([currentState._getroomname(), user._getname(), user._getip(), str(user._getport())])
requestMessage = 'J:' + message_ + PROTOCAL_END
responseMessage = socketOperation(clientSocket, requestMessage)
if (responseMessage[0] != 'M'):
print("Server Thread: Failed to join: roomserver error, try again")
responseMessage = socketOperation(clientSocket, requestMessage)
if (responseMessage[0] != 'M'):
print("Server Thread: Failed to join: roomserver error, discard current action")
backwardLink.close()
stateLock.release()
continue
currentState.updateRoomInfo(responseMessage.replace(PROTOCAL_END,'').split(':')[1:])
roomInfo = currentState._getroominfo()
stateLock.release()
print('Server Thread: Joined finish and check the info again')
if (findPosition(roomInfo, backwardLinkUserName, backwardLinkIp, backwardLinkPort) is None):
print('Server Thread: No info for the newly coming backward link')
print('Server Thread: refuse that request by ignoring it')
backwardLink.close()
continue
# if the backwardlinke is accidently the forward link peer, then discard it
elif sdbm_hash(backwardLinkUserName+backwardLinkIp+str(backwardLinkPort)) == forwardLinkHash:
print('Server Thread: find a backward link from forward link peer, discard it')
backwardLink.close()
continue
# a valid backwardlink request, establish p2p connection
else:
print('Server Thread: match the info of newly coming backward link')
print('Server Thread: establish connection ...')
stateLock.acquire()
backwardLinkTuple = (sdbm_hash(backwardLinkUserName+backwardLinkIp+str(backwardLinkPort)),backwardLink)
currentState._addbackwardlinks(backwardLinkTuple)
msgID = currentState._getmsgid()
responseMessage = "S:" + str(msgID) + "::\r\n"
output = socketOperation(backwardLink, responseMessage, receive = False)
if output == Exceptions["SOCKET_ERROR"]:
print('Server Thread: Failed to send back data')
handShakeSocket = socket.socket()
continue
# state transition if neccessary
currentState.stateTransition(Actions['HANDSHAKE'])
stateLock.release()
# update readList for later listening
readList.append(backwardLink)
print('Server Thread: successfully connected a new backward link')
CmdWin.insert(1.0, '\nsuccessfully receive a connecting request and establish connection\n')
else:
print('Server Thread: Get an message')
try:
messageData = sockfd.recv(BUFSIZ)
message = messageData.decode('ascii')
except:
print('Server Thread: Exception happended, usually caused by the close connection.')
message = ''
# extract header of the message
messageHeader = message.replace(PROTOCAL_END, '').split(':')[0:6]
# check if in the same room
print ("Server Thread: Receive message:", message)
if message == '':
print('Server Thread: Find a socket quit')
readList.remove(sockfd)
sockfd.close()
stateLock.acquire()
# if closing socket is forward link, remove it from the current state
# and start handshake again
forwardLinkTuple = currentState._getforwardlink()
if forwardLinkTuple is not None:
if sockfd is forwardLinkTuple[1]:
currentState._removeforwardlink()
print('Server Thread: remove the forward link')
print('Server Thread: start handshake thread again')
CmdWin.insert(1.0, '\ndetected the forward link peer quit, try to establish forwardlink again\n')
handShake = Thread(target=handShakeThread, name='handShake', args=(1,))
handShake.start()
else:
# if it is backwardlink
# remove the it with no other action
if currentState._removebackwardlinksBySocket(sockfd) is Exceptions['BACKWARDLINK_NOT_EXIST']:
print("Server Thread: cannot find the particular quitting socket")
else:
CmdWin.insert(1.0, '\ndetected one of the backward links peer quit, release the connection\n')
print("Server Thread: remove the backward link")
else:
# if it is backwardlink
# remove the it with no other action
if currentState._removebackwardlinksBySocket(sockfd) is Exceptions['BACKWARDLINK_NOT_EXIST']:
print("Server Thread: cannot find the particular quitting socket")
else:
print("Server Thread: remove the backward link")
stateLock.release()
continue
# report if it's a invalid message
if messageHeader[0] != "T":
print('Server Thread: Unknown message')
continue
# report if it's from another room accidently
if messageHeader[1] != roomName:
print('Server Thread: Bad message from other chatroom')
CmdWin.insert(1.0, "\nError: Received an message from other chatroom\n")
continue
# check if update room info is needed
if not int(messageHeader[2]) in hashList:
print('Server Thread: Get an message with unknow sender, check roomserver for update')
stateLock.acquire()
message_ = ':'.join([currentState._getroomname(), user._getname(), user._getip(), str(user._getport())])
requestMessage = 'J:' + message_ + PROTOCAL_END
responseMessage = socketOperation(clientSocket, requestMessage)
if (responseMessage[0] != 'M'):
print("Server Thread: Failed to join: roomserver error, try again")
responseMessage = socketOperation(clientSocket, requestMessage)
if (responseMessage[0] != 'M'):
print("Server Thread: Failed to join: roomserver error, discard current action")
stateLock.release()
continue
currentState.updateRoomInfo(responseMessage.replace(PROTOCAL_END,'').split(':')[1:])
roomInfo = currentState._getroominfo()
stateLock.release()
print('Server Thread: Joined finish and check the info again')
hashList = getHashList(roomInfo)
if not int(messageHeader[2]) in hashList:
print('hashList', hashList)
print('sender', messageHeader[2])
print('is equal', hashList)
print('Server Thread: Receive an message from an unknown sender, discard it')
continue
stateLock.acquire()
senderSocket = currentState.getSocketFromHash(int(messageHeader[2]))
if senderSocket is Exceptions['NOT_FIND_ERROR']:
pass
# print("Server Thread: cannot find sender socket")
# check if it's duplicated message
if int(messageHeader[4]) <= currentState._getmsgid():
print('Server Thread: Receive a previous message, discard it')
print('Server Thread: original megID is', currentState._getmsgid())
print('Server Thread: but now we get a message with msgID:',messageHeader[4])
# report true error, it is usual to have equal msgID
if int(messageHeader[4]) < currentState._getmsgid():
CmdWin.insert(1.0, '\nReceive a previous message!\n')
stateLock.release()
continue
# update msgID if the msgID is larger
currentState.updateMsgID(int(messageHeader[4]))
stateLock.release()
hashList = getHashList(roomInfo)
senderName = roomInfo[hashList.index(int(messageHeader[2]))*3+1]
# check sender name
if senderName != messageHeader[3]:
print('Server Thread: Find the username does not match the roominfo')
print('roomInfo,', roomInfo)
print('hashList.index(int(messageHeader[2]))*3+1', hashList.index(int(messageHeader[2]))*3+1)
# extract the message content
content = message.replace((':'.join(messageHeader)+':'), '').replace(PROTOCAL_END, '')
if len(content) == int(messageHeader[5]):
MsgWin.insert(1.0, '\n['+senderName+']: '+content)
else:
print("Server Thread: the length content does not match the header")
continue
# dispatch all messages to other users who have not possibly seen this message
print("Server Thread: dispatch the message to other peers in the same room")
for listener in readList:
if listener in [sockfd, senderSocket, serverSocket]:
continue
output = socketOperation(listener, message, receive=False)
if output is Exceptions['SOCKET_ERROR']:
print("Server Thread: failed to dispatch the message to ", listener.getsockname())
readable = []
# if select get timeout
else:
print ("Server Thread: idling")
#
# Functions to handle user input
#
def do_User():
global currentState, user
invalidMessage = ['invalid username',
'change username after join']
outstr = "\n[User] username: " + userentry.get()
CmdWin.insert(1.0, outstr)
username = userentry.get()
# check if is joined.
stateLock.acquire()
if currentState.isAfter(States['NAMED']):
CmdWin.insert(1.0, '\nFailed: ' + invalidMessage[1] + '\n')
print('\nFailed: ' + invalidMessage[1])
stateLock.release()
return
stateLock.release()
# change the username
userInfoLock.acquire()
flag = user.hasUserName()
if (user.setUserName(username) is Exceptions['INVALID_USERNAME']):
CmdWin.insert(1.0, '\nFailed: ' + invalidMessage[0] +'\n')
print('\nFailed: ' + invalidMessage[0])
userInfoLock.release()
return
userInfoLock.release()
# set state to named
stateLock.acquire()
currentState.stateTransition(Actions['USER'])
stateLock.release()
# clear the entry if success
userentry.delete(0, END)
# give some output in CmdWin
if flag:
CmdWin.insert(1.0, '\nSuccess: change name to '+username+' \n')
print('\nSuccess: change name to '+username+' \n')
else:
CmdWin.insert(1.0, '\nSuccess: set your nickname as '+username+' \n')
print('\nSuccess: set your nickname as '+username+' \n')
def do_List():
global user, currentState
CmdWin.insert(1.0, "\nPress List")
userInfoLock.acquire()
clientSocket = user._getClientSocket()
requestMessage = 'L' + PROTOCAL_END
responseMessage = socketOperationTimeout(clientSocket, requestMessage, 1)
userInfoLock.release()
if responseMessage is Exceptions['TIMEOUT']:
print('\nMain Thread: list request timeout, try again')
userInfoLock.acquire()
requestMessage = 'L' + PROTOCAL_END
responseMessage = socketOperationTimeout(clientSocket, requestMessage, 1)
userInfoLock.release()
if responseMessage is Exceptions['TIMEOUT']:
print('\nMain Thread: second try timeout, discard the list request')
else:
presentMessage = '\n'.join(responseMessage.replace(PROTOCAL_END,'').split(':')[1:])
CmdWin.insert(1.0, "\nHere are the active chatrooms:\n"+presentMessage+'\n')
else:
presentMessage = '\n'.join(responseMessage.replace(PROTOCAL_END,'').split(':')[1:])
CmdWin.insert(1.0, "\nHere are the active chatrooms:\n"+presentMessage+'\n')
# no need actually but standard for state transition procedure
stateLock.acquire()
currentState.stateTransition(Actions['LIST'])
stateLock.release()
def do_Join():
global currentState, user
CmdWin.insert(1.0, "\nPress JOIN")
#check username
userInfoLock.acquire()
if not user.hasUserName():
CmdWin.insert(1.0, "\nError: Please input username first!\n")
print("\nError: Please input username first!\n")
userInfoLock.release()
return
userInfoLock.release()
# check if it is already in a chatroom
stateLock.acquire()
if currentState.inRoom():
CmdWin.insert(1.0, "\nError: You are already in the chat room!\n")
print("\nError: You are already in the chat room!\n")
stateLock.release()
return
stateLock.release()
# get and validate the name of chatroom
roomName = userentry.get()
if (re.match('^[\x00-\x7f]+$', roomName) is None) or (':' in roomName):
CmdWin.insert(1.0, "\nFailed: invalid room name")
print("\nFailed: invalid room name")
return
# send request to roomserver
userInfoLock.acquire()
clientSocket = user._getClientSocket()
message = ':'.join([roomName, user._getname(), user._getip(), str(user._getport())])
requestMessage = 'J:' + message + PROTOCAL_END
responseMessage = socketOperation(clientSocket, requestMessage)
userInfoLock.release()
if (responseMessage[0] != 'M'):
CmdWin.insert(1.0, "\nFailed to join: roomserver error")
return
presentMessage = '\n'.join(responseMessage.replace(PROTOCAL_END,'').split(':')[2::3])
CmdWin.insert(1.0, '\nJoin Success!\nHere are members in the room:\n' + presentMessage+ '\n' )
print('\nJoin Success!\nHere are members in the room:\n' + presentMessage)
# change the state if success
stateLock.acquire()
currentState.updateRoomName(roomName)
currentState.updateRoomInfo(responseMessage.replace(PROTOCAL_END,'').split(':')[1:])
currentState.stateTransition(Actions['JOIN'])
stateLock.release()
# clear the entry if success
userentry.delete(0, END)
# open the keep alive thread
keepAlive = Thread(target=keepAliveThread, name='keepAlive')
keepAlive.start()
# open the handshake thread
handShake = Thread(target=handShakeThread, name='handShake', args=(0,))
handShake.start()
def do_Send():
global currentState, user
inputData = userentry.get()
if len(inputData.strip(' ')) == 0:
print('Detect nothing to send!\n')
return
CmdWin.insert(1.0, "\nPress Send")
# check stage
stateLock.acquire()
checkFlag = currentState.isAfter(States['NAMED'])
stateLock.release()
if not checkFlag:
CmdWin.insert(1.0, "\nSend Error: You are not in any chatroom, please join a chatroom first!")
return
# check for all back and forward link
sendingList = []
stateLock.acquire()
forwardLinkTuple = currentState._getforwardlink()