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

188
DCC.py
View File

@ -1,4 +1,5 @@
import imp
import re
import socket
import threading
import time
@ -6,6 +7,7 @@ import time
message = __import__("message")
imp.reload(message)
#Store all used ports
PORTS = list()
class DCC(threading.Thread):
@ -14,9 +16,8 @@ class DCC(threading.Thread):
self.error = False
self.stop = False
self.stopping = threading.Event()
self.s = socket
self.connected = self.s is not None
self.conn = None
self.conn = socket
self.connected = self.conn is not None
self.messages = list()
self.named = dest
@ -44,14 +45,6 @@ class DCC(threading.Thread):
return p
return None
@property
def isDCC(self):
return self.DCC and not self.error
@property
def nick(self):
return self.srv.nick
@property
def id(self):
return self.srv.id + "/" + self.named
@ -60,10 +53,66 @@ class DCC(threading.Thread):
self.error = True
self.srv.send_msg_usr(dest, msg)
def send_ctcp(self, to, line, cmd = None, endl = None):
if cmd is None: self.srv.send_ctcp(to, line)
elif endl is None: self.srv.send_ctcp(to, line, cmd)
else: self.srv.send_ctcp(to, line, cmd, endl)
def disconnect(self):
if self.connected:
self.stop = True
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):
if to is None or to == self.named or to == self.dest:
@ -80,91 +129,22 @@ class DCC(threading.Thread):
else:
self.srv.send_dcc(msg, to)
def send_msg_final(self, channel, msg, cmd = None, endl = None):
if channel == self.named or channel == self.dest:
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):
def send_file(self, filename):
self.request_user("FILE", os.path.basename(filename))
if self.connected:
self.stop = True
self.s.shutdown(socket.SHUT_RDWR)
self.stopping.wait()
return True
else:
return False
with open(filename, 'r') as f:
#TODO: don't send the entire file in one packet
self.conn.sendall(f.read())
def kill(self):
if self.connected:
self.stop = True
#TODO: Waiting for response
self.conn.close()
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):
self.stopping.clear()
#Open the port
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
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
if not self.connected:
self.request_user()
#Start by sending all queued messages
for mess in self.messages:
@ -173,6 +153,8 @@ class DCC(threading.Thread):
time.sleep(1)
readbuffer = b''
nicksize = len(self.srv.nick)
Bnick = self.srv.nick.encode()
while not self.stop:
raw = self.conn.recv(1024) #recieve server messages
if not raw:
@ -182,7 +164,23 @@ class DCC(threading.Thread):
readbuffer = temp.pop()
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:
self.conn.close()

View File

@ -11,6 +11,8 @@ import time
from credits import Credits
import credits
dcc = __import__("DCC")
imp.reload(dcc)
CREDITS = {}
filename = ""
@ -174,8 +176,19 @@ class Message:
self.srv.send_ctcp(self.sender, "USERINFO %s" % (self.srv.realname))
elif self.content == '\x01VERSION\x01':
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':
print (self.content[:7])
print (self.content)
self.srv.send_ctcp(self.sender, "ERRMSG Unknown or unimplemented CTCP request")
def reparsemsg(self):

View File

@ -1,9 +1,9 @@
import sys
import traceback
import socket
import threading
import time
import imp
import socket
import sys
import threading
import traceback
import time
message = __import__("message")
imp.reload(message)
@ -35,8 +35,8 @@ class Server(threading.Thread):
threading.Thread.__init__(self)
@property
def isDCC(self):
return False
def isDCC(self, to=None):
return to is not None and to in self.dcc_clients
@property
def host(self):
@ -66,6 +66,26 @@ class Server(threading.Thread):
else:
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
def autoconnect(self):
if self.node.hasAttribute("autoconnect"):
@ -85,6 +105,7 @@ class Server(threading.Thread):
self.s.send (("%s %s :\x01%s\x01%s" % (cmd, to, line, endl)).encode ())
def send_dcc(self, msg, to):
"""Send a message through DCC connection"""
if msg is not None and to is not None:
if to not in self.dcc_clients.keys():
d = dcc.DCC(self, to)
@ -95,6 +116,8 @@ class Server(threading.Thread):
def send_msg_final(self, channel, msg, cmd = "PRIVMSG", endl = "\r\n"):
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)
if msg is not None and channel is not None:
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 ())
def send_msg_prtn(self, msg):
"""Send a message to partner bot"""
self.send_msg_final(self.partner, msg)
def send_msg_usr(self, user, msg):
@ -137,6 +161,11 @@ class Server(threading.Thread):
if self.connected:
self.stop = True
self.s.shutdown(socket.SHUT_RDWR)
#Close all DCC connection
for clt in self.dcc_clients:
self.dcc_clients[clt].disconnect()
self.stopping.wait()
return True
else:
@ -194,7 +223,7 @@ class Server(threading.Thread):
msg = message.Message (srv, line)
msg.treat (self.mods)
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()
traceback.print_exception(exc_type, exc_value, exc_traceback)