initial registration processimplemented using anonymous connection via xmpp

This commit is contained in:
Volkan Şahin 2016-03-04 19:23:21 +02:00
parent 092cb69d43
commit 80006577ed
7 changed files with 153 additions and 94 deletions

View file

@ -1,16 +1,17 @@
[BASE] [BASE]
logConfigurationFilePath=/etc/ahenk/log.conf logconfigurationfilepath = /etc/ahenk/log.conf
[PLUGIN] [PLUGIN]
pluginFolderPath=/home/ismail/devzone/ pluginfolderpath = /home/volkan/devzone/
mainModuleName=main mainmodulename = main
[CONNECTION] [CONNECTION]
uid = uid =
password=
host = localhost host = localhost
port = 5222 port = 5222
receiverJid=lider_sunucu receiverjid = lider_sunucu
serviceName=im.mys.pardus.org.tr servicename = im.mys.pardus.org.tr
nick = nick nick = nick
sendFilePath=sendFilePath sendfilepath = sendFilePath
receiveFileParam=receiveFileParam receivefileparam = receiveFileParam

View file

@ -47,8 +47,24 @@ class AhenkDeamon(BaseDaemon):
globalscope.setTaskManager(taskManger) globalscope.setTaskManager(taskManger)
registration=Registration() registration=Registration()
registration.register() globalscope.setRegistration(registration)
if registration.is_registered() is False:
message_sender=MessageSender(registration.get_registration_request_message())
message_sender.connect_to_server()
registration.confirm_registration()
""""
message_receiver = MessageReceiver()
rec_process = Process(target=message_receiver.connect_to_server)
rec_process.start()
"""
"""
else:
"""
""" """
#TODO send register message according to register status #TODO send register message according to register status
print("sending registration message") print("sending registration message")
@ -73,6 +89,7 @@ class AhenkDeamon(BaseDaemon):
globalscope.setResponseQueue(responseQueue) globalscope.setResponseQueue(responseQueue)
""" """
if __name__ == '__main__': if __name__ == '__main__':
pidfilePath='/var/run/ahenk.pid' pidfilePath='/var/run/ahenk.pid'

View file

@ -17,6 +17,7 @@ class Scope(object):
self.pluginManager=None self.pluginManager=None
self.taskManager=None self.taskManager=None
self.responseQueue=None self.responseQueue=None
self.registration=None
@staticmethod @staticmethod
def getInstance(): def getInstance():
@ -71,3 +72,9 @@ class Scope(object):
def setResponseQueue(self,responseQueue): def setResponseQueue(self,responseQueue):
self.responseQueue=responseQueue self.responseQueue=responseQueue
def getRegistration(self):
return self.registration
def setRegistration(self,registration):
self.registration=registration

View file

@ -32,21 +32,20 @@ class MessageReceiver(slixmpp.ClientXMPP):
def __init__(self): def __init__(self):
# global scope of ahenk # global scope of ahenk
scope = Scope() scope = Scope().getInstance()
scope = scope.getInstance()
# logger comes from ahenk deamon # logger comes from ahenk deamon
# configurationManager comes from ahenk deamon # configurationManager comes from ahenk deamon
self.logger = scope.getLogger() self.logger = scope.getLogger()
self.configurationManager = scope.getConfigurationManager() self.configurationManager = scope.getConfigurationManager()
#self.full_jid =str(self.configurationManager.get('REGISTRATION', 'from'))+'@'+str(self.configurationManager.get('CONNECTION', 'host')) self.full_jid =str(self.configurationManager.get('CONNECTION', 'uid'))+'@'+str(self.configurationManager.get('CONNECTION', 'host'))
#print("self.jid nedir:"+self.full_jid )
#set parameters
#slixmpp.ClientXMPP.__init__(self, self.full_jid, 'pass') #slixmpp.ClientXMPP.__init__(self, self.full_jid, 'pass')
#TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST
slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan") slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan")
self.receiver="caner@localhost" self.receiver="caner@localhost"
#TESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTESTTEST
""" """
self.nick = self.configurationManager.get('CONNECTION', 'nick') self.nick = self.configurationManager.get('CONNECTION', 'nick')
@ -66,7 +65,7 @@ class MessageReceiver(slixmpp.ClientXMPP):
def add_listeners(self): def add_listeners(self):
self.add_event_handler("session_start", self.session_start) self.add_event_handler("session_start", self.session_start)
self.add_event_handler("groupchat_message", self.recv_muc_message) #self.add_event_handler("groupchat_message", self.recv_muc_message)
self.add_event_handler("message", self.recv_direct_message) self.add_event_handler("message", self.recv_direct_message)
#self.room=self.add_event_handler("groupchat_invite", self.invite_auto_accept) #self.room=self.add_event_handler("groupchat_invite", self.invite_auto_accept)
@ -115,7 +114,7 @@ class MessageReceiver(slixmpp.ClientXMPP):
def recv_direct_message(self, msg): def recv_direct_message(self, msg):
if msg['type'] in ('chat', 'normal'): if msg['type'] in ('chat', 'normal'):
self.disconnect() #self.disconnect()
print ("%s : %s" % (msg['from'], msg['body'])) print ("%s : %s" % (msg['from'], msg['body']))
def connect_to_server(self):# Connect to the XMPP server and start processing XMPP stanzas. def connect_to_server(self):# Connect to the XMPP server and start processing XMPP stanzas.

View file

@ -32,18 +32,27 @@ class MessageSender(slixmpp.ClientXMPP):
def __init__(self,message): def __init__(self,message):
# global scope of ahenk # global scope of ahenk
scope = Scope() scope = Scope().getInstance()
scope = scope.getInstance()
# logger comes from ahenk deamon # logger comes from ahenk deamon
#configurationManager comes from ahenk deamon #configurationManager comes from ahenk deamon
self.logger = scope.getLogger() self.logger = scope.getLogger()
self.configurationManager = scope.getConfigurationManager() self.configurationManager = scope.getConfigurationManager()
self.registration=scope.getRegistration()
#set parameters #set parameters
#slixmpp.ClientXMPP.__init__(self, self.configurationManager.get('CONNECTION', 'jid'), self.configurationManager.get('Connection_Param', 'password')) #slixmpp.ClientXMPP.__init__(self, self.configurationManager.get('CONNECTION', 'jid'), self.configurationManager.get('Connection_Param', 'password'))
slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan") #is user want to create connection as anonymous
if self.configurationManager.get('CONNECTION', 'uid') == "" or self.configurationManager.get('CONNECTION', 'uid') is None:
print("uid not found")
slixmpp.ClientXMPP.__init__(self, self.configurationManager.get('CONNECTION', 'host'), None)
else:
print("uid:"+self.configurationManager.get('CONNECTION', 'uid'))
slixmpp.ClientXMPP.__init__(self, self.configurationManager.get('CONNECTION', 'uid'), self.configurationManager.get('CONNECTION', 'password'))
self.receiver="caner@localhost" self.receiver="caner@localhost"
#TODO lider account
#slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan") #slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan")
#self.receiver="caner@localhost" #self.receiver="caner@localhost"
""" """
@ -55,60 +64,35 @@ class MessageSender(slixmpp.ClientXMPP):
""" """
self.room=None self.room=None
self.message=message self.message=message
self.add_event_handler("session_start", self.session_start) self.add_event_handler("session_start", self.session_start)
self.add_event_handler("message", self.recv_direct_message)
self.register_extensions() self.register_extensions()
#!!! you have to use modified slixmpp for file transfering #!!! you have to use modified slixmpp for file transfering
#self.send_file() #self.send_file()
def recv_direct_message(self, msg):
if msg['type'] in ('chat', 'normal'):
print ("%s : %s" % (msg['from'], msg['body']))
self.registration.registration_reply=str(msg['body'])
self.disconnect(wait=False)
def session_start(self, event): def session_start(self, event):
self.get_roster() self.get_roster()
self.send_presence() self.send_presence()
self.send_direct_message(self.message) self.send_direct_message(self.message)
def stream_opened(self, sid):
#self.logger.info('Stream opened. %s', sid)
return open(self.receivefile, 'wb')
def stream_data(self, data):
#self.logger.info('Stream data.')
self.file.write(data)
def stream_closed(self, exception):
#self.logger.info('Stream closed. %s', exception)
self.file.close()
#self.disconnect()
def send_file(self):
try:
# Open the S5B stream in which to write to.
proxy = yield from self['xep_0065'].handshake(self.receiver)
# Send the entire file.
while True:
data = self.file.read(1048576)
if not data:
break
yield from proxy.write(data)
# And finally close the stream.
proxy.transport.write_eof()
except (IqError, IqTimeout):
print('File transfer errored')
else:
print('File transfer finished')
finally:
self.file.close()
def send_direct_message(self,msg): def send_direct_message(self,msg):
#need connection control #need connection control
self.send_message(mto=self.receiver,mbody=msg,mtype='chat') self.send_message(mto=self.receiver,mbody=msg,mtype='chat')
if self.configurationManager.get('CONNECTION', 'uid') != "" and self.configurationManager.get('CONNECTION', 'uid') is not None:
print("diskooo")
self.disconnect() self.disconnect()
def connect_to_server(self):# Connect to the XMPP server and start processing XMPP stanzas. def connect_to_server(self):# Connect to the XMPP server and start processing XMPP stanzas.
try: try:
self.connect() self.connect()
self.process() self.process(forever=False)
#self.logger.info('Connection were established successfully') #self.logger.info('Connection were established successfully')
return True return True
except Exception as e: except Exception as e:

View file

@ -41,8 +41,10 @@ class Messaging(slixmpp.ClientXMPP):
#self.configurationManager = scope.getConfigurationManager() #self.configurationManager = scope.getConfigurationManager()
#set parameters #set parameters
slixmpp.ClientXMPP.__init__(self, self.configurationManager.get('CONNECTION', 'jid'), self.configurationManager.get('Connection_Param', 'password')) #slixmpp.ClientXMPP.__init__(self, self.configurationManager.get('CONNECTION', 'jid'), self.configurationManager.get('Connection_Param', 'password'))
slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan")
self.receiver="caner@localhost"
#slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan") #slixmpp.ClientXMPP.__init__(self, "volkan@localhost", "volkan")
#self.receiver="caner@localhost" #self.receiver="caner@localhost"
""" """

View file

@ -22,36 +22,72 @@ class Registration():
#TODO try catches #TODO try catches
def __init__(self): def __init__(self):
scope = Scope.getInstance() scope = Scope().getInstance()
self.conf_manager = scope.getConfigurationManager() self.conf_manager = scope.getConfigurationManager()
self.logger=scope.getLogger() self.logger=scope.getLogger()
self.logger.debug('[Registration] creating registration') if self.conf_manager.has_section('REGISTRATION'):
self.message="" if self.conf_manager.get('REGISTRATION', 'registered')=='false':
self.mac = ':'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2)) self.re_register()
self.uid = self.generate_uuid(True) else:
self.time_stamp = datetime.datetime.now().strftime("%d-%m-%Y %I:%M") self.logger.debug('[Registration] already registered')
self.ip_address = self.get_ip_addresses() else:
self.host_name =socket.gethostname() self.register()
self.logger.debug('[Registration] registration parameters were set up') self.registration_reply=""
self.logger.debug('[Registration] ')
#print("to do create jid"+str(self.generate_uuid(True))) def confirm_registration(self):
if self.registration_reply != "":
j = json.loads(self.registration_reply)
self.logger.info('[REGISTRATION] register reply: '+j['message'])
status =j['status']
dn=j['dn']
def get_registration_message(self): if(str(status).lower()=='registered'):
if self.conf_manager.has_section('CONNECTION') and self.conf_manager.get('REGISTRATION', 'from') is not None:
self.conf_manager.set('CONNECTION', 'uid',self.conf_manager.get('REGISTRATION', 'from'))
self.conf_manager.set('CONNECTION', 'password',self.conf_manager.get('REGISTRATION', 'password'))
self.conf_manager.set('REGISTRATION', 'dn',dn)
self.conf_manager.set('REGISTRATION', 'registered','true')
with open('/etc/ahenk/ahenk.conf', 'w') as configfile:
self.conf_manager.write(configfile)
self.logger.info('[REGISTRATION] registered successfully')
return True
elif(status=='registration_error'):
self.logger.info('[REGISTRATION] registration error')
return False
elif(status=='already_registered'):
self.logger.info('[REGISTRATION]already registered')
return False
def is_registered(self):
if self.conf_manager.has_section('REGISTRATION') and (self.conf_manager.get('REGISTRATION', 'registered')=='true'):
return True
else:
return False
def get_registration_request_message(self):
self.logger.debug('[Registration] creating registration message according to parameters of registration') self.logger.debug('[Registration] creating registration message according to parameters of registration')
if self.conf_manager.has_section('REGISTRATION'):
data = {} data = {}
data['message_type'] = 'registration' data['message_type'] = 'registration'
data['from'] = str(self.uid) data['from'] = str(self.conf_manager.get('REGISTRATION','from'))
data['password'] = 'password' data['password'] = str(self.conf_manager.get('REGISTRATION','password'))
data['mac_address'] = str(self.mac) data['mac_address'] = str(self.conf_manager.get('REGISTRATION','mac_address'))
data['ip_address'] = str(self.ip_address) data['ip_address'] = str(self.conf_manager.get('REGISTRATION','ip_address'))
data['hostname'] = str(self.host_name) data['hostname'] = str(self.conf_manager.get('REGISTRATION','hostname'))
data['timestamp'] = str(self.time_stamp) data['timestamp'] = str(self.conf_manager.get('REGISTRATION','timestamp'))
data['dn'] = str(self.conf_manager.get('REGISTRATION','dn'))
self.logger.debug('[Registration] json of registration message was created') self.logger.debug('[Registration] json of registration message was created')
json_data = json.dumps(data) json_data = json.dumps(data)
self.logger.debug('[Registration] json converted to str') self.logger.debug('[Registration] json converted to str')
return json_data return json_data
else:
print("reg sec yok :(")
return None
def register(self): def register(self):
self.logger.debug('[Registration] configuration parameters of registration is checking') self.logger.debug('[Registration] configuration parameters of registration is checking')
@ -59,22 +95,32 @@ class Registration():
self.logger.debug('[Registration] REGISTRATION section is already created') self.logger.debug('[Registration] REGISTRATION section is already created')
else: else:
self.logger.debug('[Registration] creating REGISTRATION section') self.logger.debug('[Registration] creating REGISTRATION section')
config = configparser.RawConfigParser()
config.add_section('REGISTRATION')
config.set('REGISTRATION', 'from',str(self.uid))
config.set('REGISTRATION', 'mac_address',str(self.mac))
config.set('REGISTRATION', 'ip_address',str(self.ip_address))
config.set('REGISTRATION', 'hostname',str(self.host_name))
config.set('REGISTRATION', 'timestamp',str(self.time_stamp))
config.set('REGISTRATION', 'password',str('password'))
config.set('REGISTRATION', 'registered','false')
#TODO self.conf_manager.configurationFilePath attribute error ? self.conf_manager.add_section('REGISTRATION')
self.conf_manager.set('REGISTRATION', 'from',str(self.generate_uuid(True)))
self.conf_manager.set('REGISTRATION', 'mac_address',str(':'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2))))
self.conf_manager.set('REGISTRATION', 'ip_address',str(self.get_ip_addresses()))
self.conf_manager.set('REGISTRATION', 'hostname',str(socket.gethostname()))
self.conf_manager.set('REGISTRATION', 'timestamp',str(datetime.datetime.now().strftime("%d-%m-%Y %I:%M")))
self.conf_manager.set('REGISTRATION', 'password',str(self.generate_password()))
self.conf_manager.set('REGISTRATION', 'dn','')
self.conf_manager.set('REGISTRATION', 'registered','false')
#TODO self.conf_manager.configurationFilePath attribute error ? READ olacak
self.logger.debug('[Registration] parameters were set up, section will write to configuration file') self.logger.debug('[Registration] parameters were set up, section will write to configuration file')
with open('/etc/ahenk/ahenk.conf', 'a') as configfile: with open('/etc/ahenk/ahenk.conf', 'a') as configfile:
config.write(configfile) self.conf_manager.write(configfile)
self.logger.debug('[Registration] REGISTRATION section wrote to configuration file successfully') self.logger.debug('[Registration] REGISTRATION section wrote to configuration file successfully')
def unregister(self):
if self.conf_manager.has_section('REGISTRATION'):
self.conf_manager.remove_section('REGISTRATION')
self.conf_manager.set('CONNECTION', 'uid','')
self.conf_manager.set('CONNECTION', 'password','')
with open('/etc/ahenk/ahenk.conf', 'w') as configfile:
self.conf_manager.write(configfile)
def generate_uuid(self,depend_mac=True): def generate_uuid(self,depend_mac=True):
self.logger.debug('[Registration] universal user id will be created') self.logger.debug('[Registration] universal user id will be created')
if depend_mac is False: if depend_mac is False:
@ -84,6 +130,9 @@ class Registration():
self.logger.debug('[Registration] uuid creating depends to mac address') self.logger.debug('[Registration] uuid creating depends to mac address')
return uuid.uuid3(uuid.NAMESPACE_DNS, str(get_mac()))# make a UUID using an MD5 hash of a namespace UUID and a mac address return uuid.uuid3(uuid.NAMESPACE_DNS, str(get_mac()))# make a UUID using an MD5 hash of a namespace UUID and a mac address
def generate_password(self):
return uuid.uuid4()
def get_ip_addresses(self): def get_ip_addresses(self):
self.logger.debug('[Registration] looking for network interces') self.logger.debug('[Registration] looking for network interces')
ip_address="" ip_address=""