Cleaning DCC class

Accept DCC CHAT CTCP request
Disconnect DCC connexions when disconnecting the server
This commit is contained in:
Némunaire 2012-07-23 01:23:04 +02:00
parent 9d4cdc4931
commit 469053a529
3 changed files with 146 additions and 106 deletions

190
DCC.py
View File

@ -1,4 +1,5 @@
import imp import imp
import re
import socket import socket
import threading import threading
import time import time
@ -6,6 +7,7 @@ import time
message = __import__("message") message = __import__("message")
imp.reload(message) imp.reload(message)
#Store all used ports
PORTS = list() PORTS = list()
class DCC(threading.Thread): class DCC(threading.Thread):
@ -14,9 +16,8 @@ class DCC(threading.Thread):
self.error = False self.error = False
self.stop = False self.stop = False
self.stopping = threading.Event() self.stopping = threading.Event()
self.s = socket self.conn = socket
self.connected = self.s is not None self.connected = self.conn is not None
self.conn = None
self.messages = list() self.messages = list()
self.named = dest self.named = dest
@ -34,7 +35,7 @@ class DCC(threading.Thread):
if self.port is None: if self.port is None:
print ("No more available slot for DCC connection") print ("No more available slot for DCC connection")
self.setError("Il n'y a plus de place disponible sur le serveur pour initialiser une session DCC.") self.setError("Il n'y a plus de place disponible sur le serveur pour initialiser une session DCC.")
threading.Thread.__init__(self) threading.Thread.__init__(self)
def foundPort(self): def foundPort(self):
@ -44,14 +45,6 @@ class DCC(threading.Thread):
return p return p
return None return None
@property
def isDCC(self):
return self.DCC and not self.error
@property
def nick(self):
return self.srv.nick
@property @property
def id(self): def id(self):
return self.srv.id + "/" + self.named return self.srv.id + "/" + self.named
@ -60,10 +53,66 @@ class DCC(threading.Thread):
self.error = True self.error = True
self.srv.send_msg_usr(dest, msg) self.srv.send_msg_usr(dest, msg)
def send_ctcp(self, to, line, cmd = None, endl = None): def disconnect(self):
if cmd is None: self.srv.send_ctcp(to, line) if self.connected:
elif endl is None: self.srv.send_ctcp(to, line, cmd) self.stop = True
else: self.srv.send_ctcp(to, line, cmd, endl) self.conn.shutdown(socket.SHUT_RDWR)
self.stopping.wait()
return True
else:
return False
def kill(self):
if self.connected:
self.stop = True
self.connected = False
#self.stopping.wait()#Compare with server before delete me
return True
else:
return False
def launch(self, mods = None):
if not self.connected:
self.stop = False
self.start()
def accept_user(self, host, port):
self.conn = socket.socket()
try:
self.conn.connect((host, port))
print ('Accepted user from', host, port, "for", self.named)
self.connected = True
self.stop = False
except:
self.connected = False
self.error = True
return False
self.start()
return True
def request_user(self, type="CHAT", filename="CHAT"):
#Open the port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(('', self.port))
except:
try:
self.port = self.foundPort()
s.bind(('', self.port))
except:
self.setError("Une erreur s'est produite durant la tentative d'ouverture d'une session DCC.")
return
print ('Listen on', self.port, "for", self.named)
#Send CTCP request for DCC
self.srv.send_ctcp(self.dest, "DCC %s %s %d %d" % (type, filename, self.srv.ip, self.port), "PRIVMSG")
s.listen(1)
#Waiting for the client
(self.conn, addr) = s.accept()
print ('Connected by', addr)
self.connected = True
def send_dcc(self, msg, to = None): def send_dcc(self, msg, to = None):
if to is None or to == self.named or to == self.dest: if to is None or to == self.named or to == self.dest:
@ -80,91 +129,22 @@ class DCC(threading.Thread):
else: else:
self.srv.send_dcc(msg, to) self.srv.send_dcc(msg, to)
def send_msg_final(self, channel, msg, cmd = None, endl = None): def send_file(self, filename):
if channel == self.named or channel == self.dest: self.request_user("FILE", os.path.basename(filename))
self.send_dcc(msg, channel)
else:
if cmd is None: self.srv.send_msg_final(to, line)
elif endl is None: self.srv.send_msg_final(to, line, cmd)
else: self.srv.send_msg_final(to, line, cmd, endl)
def send_msg_prtn(self, msg):
self.srv.send_msg_prtn(msg)
def send_msg_usr(self, user, msg):
if user == self.named or user == self.dest:
self.send_dcc(msg, user)
else:
self.srv.send_msg_usr(user, msg)
def send_msg (self, channel, msg, cmd = None, endl = None):
if cmd is None: self.srv.send_msg(channel, line)
elif endl is None: self.srv.send_msg(channel, line, cmd)
else: self.srv.send_msg(channel, line, cmd, endl)
def send_global (self, msg, cmd = None, endl = None):
if cmd is None: self.srv.send_global(channel, line)
elif endl is None: self.srv.send_global(channel, line, cmd)
else: self.srv.send_global(channel, line, cmd, endl)
def accepted_channel(self, chan):
self.srv.accepted_channel(chan)
def disconnect(self):
if self.connected: if self.connected:
self.stop = True with open(filename, 'r') as f:
self.s.shutdown(socket.SHUT_RDWR) #TODO: don't send the entire file in one packet
self.stopping.wait() self.conn.sendall(f.read())
return True
else:
return False
def kill(self): #TODO: Waiting for response
if self.connected:
self.stop = True self.conn.close()
self.connected = False self.connected = False
#self.stopping.wait()#Compare with server before delete me
return True
else:
return False
def join(self, chan, password = None):
self.srv.join(chan, password)
def leave(self, chan):
self.srv.leave(chan)
def update_mods(self, mods):
self.srv.update_mods(mods)
def launch(self, mods = None):
if not self.connected:
self.stop = False
self.start()
def run(self): def run(self):
self.stopping.clear() self.stopping.clear()
#Open the port if not self.connected:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.request_user()
try:
self.s.bind(('', self.port))
except:
try:
self.port = self.foundPort()
self.s.bind(('', self.port))
except:
self.setError("Une erreur s'est produite durant la tentative d'ouverture d'une session DCC.")
return
print ('Listen on', self.port, "for", self.named)
#Send CTCP request for DCC
self.srv.send_ctcp(self.dest, "DCC CHAT CHAT 1488679878 %d" % self.port, "PRIVMSG")
self.s.listen(1)
#Waiting for the client
(self.conn, addr) = self.s.accept()
print ('Connected by', addr)
self.connected = True
#Start by sending all queued messages #Start by sending all queued messages
for mess in self.messages: for mess in self.messages:
@ -173,6 +153,8 @@ class DCC(threading.Thread):
time.sleep(1) time.sleep(1)
readbuffer = b'' readbuffer = b''
nicksize = len(self.srv.nick)
Bnick = self.srv.nick.encode()
while not self.stop: while not self.stop:
raw = self.conn.recv(1024) #recieve server messages raw = self.conn.recv(1024) #recieve server messages
if not raw: if not raw:
@ -182,7 +164,23 @@ class DCC(threading.Thread):
readbuffer = temp.pop() readbuffer = temp.pop()
for line in temp: for line in temp:
self.srv.treat_msg((":%s PRIVMSG %s :" % (self.named, self.srv.nick)).encode() + line, self) if line[:nicksize] == Bnick and line[nicksize+1:].strip()[:10] == b'my name is':
name = line[nicksize+1:].strip()[11:].decode('utf-8', 'replace')
if re.match("^[a-zA-Z0-9_-]+$", name):
if name not in self.srv.dcc_clients:
del self.srv.dcc_clients[self.dest]
del self.srv.dcc_clients[self.named]
self.dest = name
self.named = self.dest + "!" + self.named.split("!")[1]
self.srv.dcc_clients[self.dest] = self
self.srv.dcc_clients[self.named] = self
self.send_dcc("Hi "+self.dest)
else:
self.send_dcc("This nickname is already in use, please choose another one.")
else:
self.send_dcc("The name you entered contain invalid char.")
else:
self.srv.treat_msg((":%s PRIVMSG %s :" % (self.named, self.srv.nick)).encode() + line, self.srv)
if self.connected: if self.connected:
self.conn.close() self.conn.close()

View File

@ -11,6 +11,8 @@ import time
from credits import Credits from credits import Credits
import credits import credits
dcc = __import__("DCC")
imp.reload(dcc)
CREDITS = {} CREDITS = {}
filename = "" filename = ""
@ -174,8 +176,19 @@ class Message:
self.srv.send_ctcp(self.sender, "USERINFO %s" % (self.srv.realname)) self.srv.send_ctcp(self.sender, "USERINFO %s" % (self.srv.realname))
elif self.content == '\x01VERSION\x01': elif self.content == '\x01VERSION\x01':
self.srv.send_ctcp(self.sender, "VERSION nemubot v3") self.srv.send_ctcp(self.sender, "VERSION nemubot v3")
elif self.content[:9] == '\x01DCC CHAT':
words = self.content[1:len(self.content) - 1].split(' ')
ip = self.srv.toIP(int(words[3]))
fullname = "guest"+ words[4] + words[3] +"!"+ip
conn = dcc.DCC(self.srv, fullname)
if conn.accept_user(ip, int(words[4])):
self.srv.dcc_clients[fullname] = conn
self.srv.dcc_clients[conn.dest] = conn
conn.send_dcc("Hi %s. Changes your name saying \"%s: my name is yournickname\"." % (conn.dest, self.srv.nick))
else:
print ("DCC: unable to connect to %s:%s" % (ip, words[4]))
elif self.content[:7] != '\x01ACTION': elif self.content[:7] != '\x01ACTION':
print (self.content[:7]) print (self.content)
self.srv.send_ctcp(self.sender, "ERRMSG Unknown or unimplemented CTCP request") self.srv.send_ctcp(self.sender, "ERRMSG Unknown or unimplemented CTCP request")
def reparsemsg(self): def reparsemsg(self):

View File

@ -1,9 +1,9 @@
import sys
import traceback
import socket
import threading
import time
import imp import imp
import socket
import sys
import threading
import traceback
import time
message = __import__("message") message = __import__("message")
imp.reload(message) imp.reload(message)
@ -35,8 +35,8 @@ class Server(threading.Thread):
threading.Thread.__init__(self) threading.Thread.__init__(self)
@property @property
def isDCC(self): def isDCC(self, to=None):
return False return to is not None and to in self.dcc_clients
@property @property
def host(self): def host(self):
@ -66,6 +66,26 @@ class Server(threading.Thread):
else: else:
return None return None
@property
def ip(self):
sum = 0
if self.node.hasAttribute("ip"):
for b in self.node["ip"].split("."):
sum = 256 * sum + int(b)
else:
#TODO: find the external IP
pass
return sum
def toIP(self, input):
"""Convert little-endian int to IPv4 adress"""
ip = ""
for i in range(0,4):
mod = input % 256
ip = "%d.%s" % (mod, ip)
input = (input - mod) / 256
return ip[:len(ip) - 1]
@property @property
def autoconnect(self): def autoconnect(self):
if self.node.hasAttribute("autoconnect"): if self.node.hasAttribute("autoconnect"):
@ -85,16 +105,19 @@ class Server(threading.Thread):
self.s.send (("%s %s :\x01%s\x01%s" % (cmd, to, line, endl)).encode ()) self.s.send (("%s %s :\x01%s\x01%s" % (cmd, to, line, endl)).encode ())
def send_dcc(self, msg, to): def send_dcc(self, msg, to):
"""Send a message through DCC connection"""
if msg is not None and to is not None: if msg is not None and to is not None:
if to not in self.dcc_clients.keys(): if to not in self.dcc_clients.keys():
d = dcc.DCC(self, to) d = dcc.DCC(self, to)
self.dcc_clients[to] = d self.dcc_clients[to] = d
self.dcc_clients[d.dest] = d self.dcc_clients[d.dest] = d
self.dcc_clients[to].send_dcc(msg) self.dcc_clients[to].send_dcc(msg)
def send_msg_final(self, channel, msg, cmd = "PRIVMSG", endl = "\r\n"): def send_msg_final(self, channel, msg, cmd = "PRIVMSG", endl = "\r\n"):
if channel == self.nick: if channel == self.nick:
exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback)
print ("\033[1;35mWarning:\033[0m Nemubot talks to himself: %s" % msg) print ("\033[1;35mWarning:\033[0m Nemubot talks to himself: %s" % msg)
if msg is not None and channel is not None: if msg is not None and channel is not None:
for line in msg.split("\n"): for line in msg.split("\n"):
@ -105,6 +128,7 @@ class Server(threading.Thread):
self.s.send (("%s %s :%s%s" % (cmd, channel, line[0:442]+"...", endl)).encode ()) self.s.send (("%s %s :%s%s" % (cmd, channel, line[0:442]+"...", endl)).encode ())
def send_msg_prtn(self, msg): def send_msg_prtn(self, msg):
"""Send a message to partner bot"""
self.send_msg_final(self.partner, msg) self.send_msg_final(self.partner, msg)
def send_msg_usr(self, user, msg): def send_msg_usr(self, user, msg):
@ -137,6 +161,11 @@ class Server(threading.Thread):
if self.connected: if self.connected:
self.stop = True self.stop = True
self.s.shutdown(socket.SHUT_RDWR) self.s.shutdown(socket.SHUT_RDWR)
#Close all DCC connection
for clt in self.dcc_clients:
self.dcc_clients[clt].disconnect()
self.stopping.wait() self.stopping.wait()
return True return True
else: else:
@ -194,7 +223,7 @@ class Server(threading.Thread):
msg = message.Message (srv, line) msg = message.Message (srv, line)
msg.treat (self.mods) msg.treat (self.mods)
except: except:
print ("\033[1;31mERROR:\033[0m occurred during the processing of the message: %s"%line) print ("\033[1;31mERROR:\033[0m occurred during the processing of the message: %s" % line)
exc_type, exc_value, exc_traceback = sys.exc_info() exc_type, exc_value, exc_traceback = sys.exc_info()
traceback.print_exception(exc_type, exc_value, exc_traceback) traceback.print_exception(exc_type, exc_value, exc_traceback)