This repository has been archived on 2021-09-15. You can view files and clone it, but cannot push or open issues or pull requests.
L3DNC/serveur/Server.py

248 lines
7.6 KiB
Python
Raw Normal View History

2015-03-30 20:54:29 +02:00
import argparse
2015-04-02 16:53:31 +02:00
import os
2015-03-30 20:54:29 +02:00
import socket
import threading
import sys
2015-04-02 16:53:31 +02:00
import configparser
import re
2015-03-30 20:54:29 +02:00
from serveur import Log
def handleConnection(connection, client_address) :
2015-03-31 13:25:34 +02:00
#try:
log.printL("Connection from IP -> {}".format(client_address), Log.lvl.INFO)
while True:
data = connection.recv(4096)
if data:
log.printL("Request from IP -> {}"
" {}".format(client_address,data.decode()), Log.lvl.INFO)
threading.Thread(target=handleRequest, args=(connection, data.decode())).start()
else:
break
"""except Exception as e :
log.printL(str(e), Log.lvl.FAIL)"""
2015-03-30 20:54:29 +02:00
def handleRequest(connection, data):
2015-03-31 13:25:34 +02:00
#try:
arrayData = data.split(" ")
2015-04-01 08:37:05 +02:00
if usersConnected[connection][1] is not None :
if(not arrayData[0][0] == "/"):
broadcastMsg( "NEW_MSG {} {} ".format(usersConnected[connection][1], data))
2015-03-31 13:25:34 +02:00
return
2015-04-01 08:37:05 +02:00
else :
if arrayData[0] == "/name" :
changeName(connection, arrayData[1])
return
if arrayData[0] == "/askpm" :
askPrivateMsg(connection,arrayData[1])
return
if arrayData[0] == "/acceptpm" :
acceptPrivateMsg(connection,arrayData[1])
return
if arrayData[0] == "/rejectpm" :
rejectPrivateMsg(connection,arrayData[1])
return
if arrayData[0] == "/pm" :
privateMsg(connection,arrayData[1],arrayData[2:])
return
if arrayData[0] == "/enable":
enableUser(connection)
return
if arrayData[0] == "/disable":
disableUser(connection)
return
2015-04-02 16:53:31 +02:00
if arrayData[0] == "/quit" :
quit(connection)
return
2015-04-01 08:37:05 +02:00
connection.send("ERR_COMMAND_NOT_FOUND".encode())
else:
2015-04-02 13:47:02 +02:00
if arrayData[0] == "/newname" :
2015-04-02 14:15:11 +02:00
newName(connection, arrayData[1])
2015-04-02 13:47:02 +02:00
return
if arrayData[0] == "/quit" :
quit(connection)
return
2015-04-02 16:53:31 +02:00
connection.send("ERR_NO_NICKNAME".encode())
2015-03-31 13:25:34 +02:00
"""except Exception as e :
log.printL(str(e), Log.lvl.FAIL)"""
2015-03-30 20:54:29 +02:00
2015-03-31 11:53:24 +02:00
def broadcastMsg(message):
2015-03-31 13:25:34 +02:00
for con, value in usersConnected.items() :
2015-04-02 13:47:02 +02:00
if usersConnected[con][1] is not None :
2015-04-02 16:53:31 +02:00
try:
con.send(message.encode())
except Exception as e :
log.printL(str(e), Log.lvl.FAIL)
2015-03-31 11:53:24 +02:00
def userListActive(connection):
l = "USERLIST "
for con,value in usersConnected :
if value[2] == True :
l += value[1] + " "
connection.send(l[:-1].encode())
def userListAway(connection):
l = "USERAWAY "
for con,value in usersConnected :
if value[2] == False :
l += value[1] + " "
connection.send(l[:-1].encode())
2015-03-30 20:54:29 +02:00
2015-03-31 11:53:24 +02:00
def changeName(connection, pseudo):
2015-04-02 16:53:31 +02:00
if not re.match("^\w{3,15}$",pseudo) :
connection.send("ERR_INVALID_NICKNAME".encode())
else:
broadcastMsg("NAME_CHANGED {} {}".format(usersConnected[connection][1], pseudo))
usersConnected[connection][1] = pseudo
2015-03-30 20:54:29 +02:00
2015-04-02 13:47:02 +02:00
def newName(connection, pseudo):
broadcastMsg("HAS_JOIN {} ".format(pseudo))
2015-04-02 14:15:11 +02:00
connection.send("SUCC_VALID_NICKNAME".encode())
2015-04-02 13:47:02 +02:00
usersConnected[connection][1] = pseudo
2015-03-31 11:53:24 +02:00
def askPrivateMsg(connection,pseudo):
c = getConnectionByPseudo(pseudo)
if c is None :
connection.send("ERR_USER_NOT_FOUND".encode())
else:
pm = (connection,c)
if pm in askPM :
connection.send("ALREADY_ASKED".encode())
else:
askPM.append(pm)
2015-04-02 16:53:31 +02:00
c.send("ASKING_FOR_PM {}".format(pseudo).encode())
2015-03-31 11:53:24 +02:00
connection.send("SUCC_INVITED".encode())
def acceptPrivateMsg(connection, pseudo):
c = getConnectionByPseudo(pseudo)
if c is None :
connection.send("ERR_USER_NOT_FOUND".encode())
else:
pm = (connection,c)
if pm not in askPM :
connection.send("ERR_USER_HAS_NOT_ASK".encode())
else:
askPM.remove(pm)
validatePM.append(pm)
connection.send("SUCC_PRIVATE_DISCUSSION_ACCEPTED".encode())
def rejectPrivateMsg(connection, pseudo):
c = getConnectionByPseudo(pseudo)
if c is None :
connection.send("ERR_USER_NOT_FOUND".encode())
else:
pm = (connection,c)
if pm not in askPM :
connection.send("ERR_USER_HAS_NOT_ASK".encode())
else:
askPM.remove(pm)
connection.send("SUCC_PRIVATE_DISCUSSION_REFUSED".encode())
def privateMsg(connection, pseudo, msg):
c = getConnectionByPseudo(pseudo)
if c is None :
connection.send("ERR_DEST_NOT_FOUND".encode())
else:
pm = (connection,c)
if sorted(pm) not in sorted(validatePM) :
connection.send("ERR_NOT_ACCEPTED".encode())
else:
c.send("NEW_PM {} {}".format(pseudo,msg).encode())
connection.send("SUCC_PM_SENDED".encode())
2015-04-01 08:37:05 +02:00
def enableUser(connection):
if usersConnected[connection][2] == False :
usersConnected[connection][2] = True
connection.send("SUCC_ENABLED".encode())
else:
connection.send("ERR_NOT_DISABLED".encode())
def disableUser(connection):
if usersConnected[connection][2] == True :
usersConnected[connection][2] = False
connection.send("SUCC_DISABLED".encode())
else:
connection.send("ERR_NOT_ENABLED".encode())
2015-03-30 20:54:29 +02:00
def quit(connection) :
2015-03-31 11:53:24 +02:00
connection.send("SUCCESSFUL_LOGOUT".encode())
2015-03-30 20:54:29 +02:00
connection.close()
log.printL("Disconnection from IP -> {}".format(usersConnected[connection][0]), Log.lvl.INFO)
2015-03-31 13:25:34 +02:00
usersConnected.pop(connection)
broadcastMsg("HAS_LEFT {}".format(usersConnected[connection][1]))
2015-03-30 20:54:29 +02:00
2015-03-31 11:53:24 +02:00
def getConnectionByPseudo(pseudo):
for con, value in usersConnected.items() :
if value[1] == pseudo :
return con
return None
2015-03-30 20:54:29 +02:00
def main():
#Global vars
2015-03-31 11:53:24 +02:00
global usersConnected, log, sock
2015-03-30 20:54:29 +02:00
usersConnected = {}
2015-03-31 11:53:24 +02:00
global askPM, validatePM
global askFT, validateFT
askPM = []
validatePM = []
2015-04-02 16:53:31 +02:00
2015-03-31 11:53:24 +02:00
log.printL("Server start", Log.lvl.INFO)
2015-04-02 16:53:31 +02:00
config = configparser.ConfigParser()
if not os.path.isfile("dncserver.conf") :
config['NETWORK'] = {'port': '2222'}
config['LOG'] = {'logDirectory': 'log'}
with open('dncserver.conf', 'w') as configfile:
config.write(configfile)
config.read("dncserver.conf")
log = Log.Log(config["LOG"]["logdirectory"])
2015-03-30 20:54:29 +02:00
#Init socket serv
sock = socket.socket()
2015-04-02 16:53:31 +02:00
sock.bind(("", int(config["NETWORK"]["port"])))
2015-03-30 20:54:29 +02:00
sock.listen(5)
2015-04-02 16:53:31 +02:00
log.printL("Server Listen on port {}".format(config["NETWORK"]["port"]), Log.lvl.INFO)
2015-03-30 20:54:29 +02:00
try :
while True :
#Connection client
connection, client_address = sock.accept()
2015-04-01 08:37:05 +02:00
usersConnected[connection] = [client_address,None,True] # ip pseudo status
2015-03-30 20:54:29 +02:00
threading.Thread(target=handleConnection,args=(connection,client_address)).start()
except KeyboardInterrupt :
# Disable to received more requests on socket
for con, value in usersConnected.items():
con.shutdown(socket.SHUT_RD)
finally :
#Wait for threads finish
log.printL("Wait for threads ending", Log.lvl.INFO)
for t in threading.enumerate():
if t!= threading.main_thread():
t.join()
#Close all clients sockets
for con, value in usersConnected.items():
2015-03-31 11:53:24 +02:00
quit(con)
#Close the socket server
2015-03-30 20:54:29 +02:00
sock.close()
log.printL("Server shutdown", Log.lvl.INFO)
sys.exit(0)
if __name__ == '__main__':
main()