diff --git a/etc/ahenk/ahenk.conf b/etc/ahenk/ahenk.conf index df26fe3..8ef4e27 100644 --- a/etc/ahenk/ahenk.conf +++ b/etc/ahenk/ahenk.conf @@ -6,8 +6,11 @@ pluginFolderPath=/home/ismail/devzone/ mainModuleName=main [CONNECTION] -jid=jid +uid= +host=localhost +port=5222 +receiverJid=lider_sunucu +serviceName=im.mys.pardus.org.tr nick=nick -receiverJid=receiverJid sendFilePath=sendFilePath receiveFileParam=receiveFileParam diff --git a/opt/ahenk/ahenkd.py b/opt/ahenk/ahenkd.py index de8de8a..1618328 100644 --- a/opt/ahenk/ahenkd.py +++ b/opt/ahenk/ahenkd.py @@ -7,6 +7,9 @@ from base.deamon.BaseDeamon import BaseDaemon from base.logger.AhenkLogger import Logger from base.Scope import Scope from base.messaging.Messaging import Messaging +from base.messaging.MessageReceiver import MessageReceiver +from base.messaging.MessageSender import MessageSender +from base.registration.Registration import Registration from multiprocessing import Process from threading import Thread import sys,logging @@ -18,6 +21,7 @@ class AhenkDeamon(BaseDaemon): def run(self): print ("merhaba dunya") + globalscope = Scope() globalscope.setInstance(globalscope) @@ -30,20 +34,24 @@ class AhenkDeamon(BaseDaemon): globalscope.setConfigurationManager(config) logger = Logger() - logger.info("obaraaa") + logger.debug("[AhenkDeamon]logging") globalscope.setLogger(logger) + registration = Registration() + registration.register() - xmpp = Messaging() - print("xmpp is created") - p = Process(target=xmpp.connect_to_server) - print("Process thread starting") - p.start() - print("Process tread started") - print("waiting 5sn ") - time.sleep(5) - print("sleep is over ") - xmpp.send_direct_message("asdasdas")# not working ->connection error + #TODO send register message according to register status + print("sending registration message") + message_sender = MessageSender(registration.get_registration_message()) + message_sender.connect_to_server() + print("registration message were sent") + #TODO add sender to scope + + message_receiver = MessageReceiver() + rec_process = Process(target=message_receiver.connect_to_server) + rec_process.start() + print("receiver online") + #set parameters which will use for message sending if __name__ == '__main__': diff --git a/opt/ahenk/base/messaging/MessageReceiver.py b/opt/ahenk/base/messaging/MessageReceiver.py new file mode 100644 index 0000000..f7d7905 --- /dev/null +++ b/opt/ahenk/base/messaging/MessageReceiver.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# Author: Volkan Şahin +# Author: İsmail BAŞARAN +import sys +sys.path.append('../..') +import slixmpp +import asyncio +import threading +from threading import Thread +from multiprocessing import Process +from slixmpp.exceptions import IqError, IqTimeout +from base.Scope import Scope + +""" +--fetch parameters of connection from conf file +--connect xmpp +--send direct message +--receive direct message +--send muc message +--receive muc message +--listen to muc invites +--auto accept muc invites +--send auto reply to muc messages +--receive file (0065) +--send file (0065) + +""" + +class MessageReceiver(slixmpp.ClientXMPP): + + def __init__(self): + + # global scope of ahenk + scope = Scope() + scope = scope.getInstance() + + # logger comes from ahenk deamon + # configurationManager comes from ahenk deamon + self.logger = scope.getLogger() + self.configurationManager = scope.getConfigurationManager() + + #self.full_jid =str(self.configurationManager.get('REGISTRATION', 'from'))+'@'+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, "volkan@localhost", "volkan") + self.receiver="caner@localhost" + + """ + self.nick = self.configurationManager.get('CONNECTION', 'nick') + self.receiver=self.configurationManager.get('CONNECTION','receiverJid') + self.sendfile=open(self.configurationManager.get('CONNECTION','sendFilePath'), 'rb') + self.receivefile=self.configurationManager.get('CONNECTION', 'receiveFileParam') + self.logger.info('Parameters were established') + """ + self.room=None + self.register_extensions() + self.add_listeners() + self.connect() + + #!!! you have to use modified slixmpp for file transfering + #self.send_file() + + def add_listeners(self): + + self.add_event_handler("session_start", self.session_start) + self.add_event_handler("groupchat_message", self.recv_muc_message) + self.add_event_handler("message", self.recv_direct_message) + + #self.room=self.add_event_handler("groupchat_invite", self.invite_auto_accept) + + #file_listeners + #self.add_event_handler("socks5_connected", self.stream_opened) + #self.add_event_handler("socks5_data", self.stream_data) + #self.add_event_handler("socks5_closed", self.stream_closed) + + #self.logger.info('Listeners were added') + + + 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 session_start(self, event): + self.get_roster() + self.send_presence() + + + def invite_auto_accept(self, inv): + + self.room=inv['from'] + print("(%s) invite is accepted" % str(self.room)) + self.plugin['xep_0045'].joinMUC(self.room,self.nick,wait=True) + self.send_message(mto=self.room.bare,mbody="Hi all!",mtype='groupchat') + return self.room + + def recv_muc_message(self, msg):#auto reply + + if msg['mucnick'] != self.nick: + print("%s : %s" % (str(msg['from']),str(msg['body'])) ) + self.send_message(mto=msg['from'].bare,mbody="I got it, %s." % msg['mucnick'],mtype='groupchat') + else: + print("%s : %s" % (str(msg['mucnick']),str(msg['body']))) + + def recv_direct_message(self, msg): + if msg['type'] in ('chat', 'normal'): + self.disconnect() + print ("%s : %s" % (msg['from'], msg['body'])) + + def connect_to_server(self):# Connect to the XMPP server and start processing XMPP stanzas. + try: + + loop = asyncio.get_event_loop() + loop.run_until_complete(self.process()) + + #self.logger.info('Connection were established successfully') + return True + except Exception as e: + print('Connection to server is failed (%s)\n' % (e.strerror)) + #self.logger.error('Connection to server is failed! '+e) + return False + + def register_extensions(self): + try: + self.register_plugin('xep_0030') # Service Discovery + self.register_plugin('xep_0045') # Multi-User Chat + self.register_plugin('xep_0199') # XMPP Ping + self.register_plugin('xep_0065') # SOCKS5 Bytestreams + + #self.logger.info('Extension were registered: xep_0030,xep_0045,xep_0199,xep_0065') + return True + except Exception as e: + #self.logger.error('Extension registration is failed!(%s)\n' % (e.errno, e.strerror)) + return False diff --git a/opt/ahenk/base/messaging/MessageSender.py b/opt/ahenk/base/messaging/MessageSender.py new file mode 100644 index 0000000..92b3748 --- /dev/null +++ b/opt/ahenk/base/messaging/MessageSender.py @@ -0,0 +1,130 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# Author: Volkan Şahin +# Author: İsmail BAŞARAN +import sys +sys.path.append('../..') +import slixmpp +import asyncio +import threading +from threading import Thread +from multiprocessing import Process +from slixmpp.exceptions import IqError, IqTimeout +from base.Scope import Scope + +""" +--fetch parameters of connection from conf file +--connect xmpp +--send direct message +--receive direct message +--send muc message +--receive muc message +--listen to muc invites +--auto accept muc invites +--send auto reply to muc messages +--receive file (0065) +--send file (0065) + +""" + +class MessageSender(slixmpp.ClientXMPP): + + def __init__(self,message): + + # global scope of ahenk + scope = Scope() + scope = scope.getInstance() + + # logger comes from ahenk deamon + #configurationManager comes from ahenk deamon + self.logger = scope.getLogger() + self.configurationManager = scope.getConfigurationManager() + #set parameters + #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") + #self.receiver="caner@localhost" + """ + self.nick = self.configurationManager.get('CONNECTION', 'nick') + self.receiver=self.configurationManager.get('CONNECTION','receiverJid') + self.sendfile=open(self.configurationManager.get('CONNECTION','sendFilePath'), 'rb') + self.receivefile=self.configurationManager.get('CONNECTION', 'receiveFileParam') + self.logger.info('Parameters were established') + """ + self.room=None + self.message=message + + self.add_event_handler("session_start", self.session_start) + self.register_extensions() + + #!!! you have to use modified slixmpp for file transfering + #self.send_file() + + def session_start(self, event): + self.get_roster() + self.send_presence() + 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): + #need connection control + self.send_message(mto=self.receiver,mbody=msg,mtype='chat') + self.disconnect() + + def connect_to_server(self):# Connect to the XMPP server and start processing XMPP stanzas. + try: + self.connect() + self.process() + #self.logger.info('Connection were established successfully') + return True + except Exception as e: + print('Connection to server is failed (%s)\n' % (e.strerror)) + #self.logger.error('Connection to server is failed! '+e) + return False + + def register_extensions(self): + try: + self.register_plugin('xep_0030') # Service Discovery + self.register_plugin('xep_0045') # Multi-User Chat + self.register_plugin('xep_0199') # XMPP Ping + self.register_plugin('xep_0065') # SOCKS5 Bytestreams + + #self.logger.info('Extension were registered: xep_0030,xep_0045,xep_0199,xep_0065') + return True + except Exception as e: + #self.logger.error('Extension registration is failed!(%s)\n' % (e.errno, e.strerror)) + return False diff --git a/opt/ahenk/base/registration/Registration.py b/opt/ahenk/base/registration/Registration.py new file mode 100644 index 0000000..0de3aa2 --- /dev/null +++ b/opt/ahenk/base/registration/Registration.py @@ -0,0 +1,94 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- +# Author: Volkan Şahin + +from base.config.ConfigManager import ConfigManager +from base.logger.AhenkLogger import Logger +from base.Scope import Scope +from uuid import getnode as get_mac +import json +import uuid +import sys,logging +import datetime +import time +import netifaces +import re +import socket +import configparser + + +class Registration(): + + #TODO try catches + + def __init__(self): + scope = Scope.getInstance() + self.conf_manager = scope.getConfigurationManager() + self.logger=scope.getLogger() + + self.logger.debug('[Registration] creating registration') + self.message="" + self.mac = ':'.join(("%012X" % get_mac())[i:i+2] for i in range(0, 12, 2)) + self.uid = self.generate_uuid(True) + self.time_stamp = datetime.datetime.now().strftime("%d-%m-%Y %I:%M") + self.ip_address = self.get_ip_addresses() + self.host_name =socket.gethostname() + self.logger.debug('[Registration] registration parameters were set up') + + #print("to do create jid"+str(self.generate_uuid(True))) + + def get_registration_message(self): + self.logger.debug('[Registration] creating registration message according to parameters of registration') + data = {} + data['message_type'] = 'registration' + data['from'] = str(self.uid) + data['password'] = 'password' + data['mac_address'] = str(self.mac) + data['ip_address'] = str(self.ip_address) + data['hostname'] = str(self.host_name) + data['timestamp'] = str(self.time_stamp) + self.logger.debug('[Registration] json of registration message was created') + + json_data = json.dumps(data) + self.logger.debug('[Registration] json converted to str') + return json_data + + def register(self): + self.logger.debug('[Registration] configuration parameters of registration is checking') + if self.conf_manager.has_section('REGISTRATION'): + self.logger.debug('[Registration] REGISTRATION section is already created') + else: + 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.logger.debug('[Registration] parameters were set up, section will write to configuration file') + with open('/etc/ahenk/ahenk.conf', 'a') as configfile: + config.write(configfile) + self.logger.debug('[Registration] REGISTRATION section wrote to configuration file successfully') + + def generate_uuid(self,depend_mac=True): + self.logger.debug('[Registration] universal user id will be created') + if depend_mac is False: + self.logger.debug('[Registration] uuid creating randomly') + return uuid.uuid4() # make a random UUID + else: + 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 + + def get_ip_addresses(self): + self.logger.debug('[Registration] looking for network interces') + ip_address="" + for interface in netifaces.interfaces(): + if(str(interface) != "lo"): + ip_address+=str(netifaces.ifaddresses(interface)[netifaces.AF_INET]) + self.logger.debug('[Registration] returning ip addresses from every interfaces') + return ip_address diff --git a/opt/ahenk/base/registration/__init__.py b/opt/ahenk/base/registration/__init__.py new file mode 100644 index 0000000..e69de29