verarbeitung der statusdaten umgestellt, code verschlankt

statusdaten werden jetzt mit den funktionen encode() und decode() verarbeitet,
antwort des servers als variable, finaly klausel wieder entfernt
This commit is contained in:
example 2022-03-06 11:55:29 +01:00
parent 9894af021e
commit 5f3bb44c7b
2 changed files with 20 additions and 39 deletions

View file

@ -1,6 +1,6 @@
#!/usr/bin/python3
# file: statusd.py
# file: apistatusd.py
# date: 26.07.2019
# email: berhsi@web.de
@ -76,13 +76,12 @@ def display_peercert(cert):
def receive_buffer_is_valid(raw_data):
'''
Checks validity of the received buffer contents.
param 1: byte
param 1: byte object
return: boolean
'''
if raw_data in (b'\x00', b'\x01'):
if raw_data.decode('utf-8', 'strict') in ('0', '1'):
logging.debug('Argument is valid: {}'.format(raw_data))
return True
logging.debug('Argument is not valid: {}'.format(raw_data))
return False
@ -90,7 +89,7 @@ def receive_buffer_is_valid(raw_data):
def change_status(raw_data, api):
'''
Write the new status together with a timestamp into the Space API JSON.
param 1: byte
param 1: byte object
param 2: string
return: boolean
'''
@ -113,6 +112,7 @@ def change_status(raw_data, api):
except Exception as e:
logging.error('Failed to change API file')
logging.error('{}'.format(e))
return False
logging.debug('API file changed')
else:
logging.error('API file is not writable. Wrong permissions?')
@ -152,10 +152,10 @@ def set_values(raw_data):
'''
Create a timestamp, changes the value of the given byte into a string
and returns both.
param 1: byte
param 1: byte object
return: tuple
'''
status = True if raw_data == b'\x01' else False
status = True if raw_data.decode('utf-8', 'strict') == '1' else False
timestamp = int(str(time()).split('.')[0])
logging.debug('Set values for timestamp: {} and status: {}'.format(
@ -173,6 +173,7 @@ def main():
(cve-2011-3389)
'''
answer = '3'.encode(encoding='utf-8', errors='strict')
loglevel = logging.WARNING
formatstring = '%(asctime)s: %(levelname)s: %(message)s'
logging.basicConfig(format=formatstring, level=loglevel)
@ -196,7 +197,7 @@ def main():
'template': './api_template'
}
}
configfile = './statusd.conf'
configfile = './apistatusd.conf'
config = configparser.ConfigParser()
config.read_dict(default_config)
if not config.read(configfile):
@ -273,19 +274,10 @@ def main():
raw_data = conn.recv(1)
if receive_buffer_is_valid(raw_data) is True:
if change_status(raw_data, config['api']['api']) is True:
answer = raw_data
if conn:
logging.debug('Send {} back'.format(raw_data))
conn.send(raw_data)
# change_status returns false:
else:
logging.info('Failed to change status')
if conn:
conn.send(b'\x03')
# receive_handle returns false:
else:
logging.info('Invalid argument received: {}'.format(raw_data))
logging.debug('Send {} back'.format(b'\x03'))
if conn:
conn.send(b'\x03')
conn.send(answer)
sleep(0.1) # protection against dos
except KeyboardInterrupt:
logging.info('Keyboard interrupt received')
@ -293,13 +285,6 @@ def main():
except Exception as e:
logging.error('{}'.format(e))
continue
finally:
if mySocket:
logging.info('Shutdown socket')
try:
mySocket.shutdown(socket.SHUT_RDWR)
except Exception as e:
logging.error(f'Error while shutdown socket: {e}')
return 0

View file

@ -60,15 +60,10 @@ class SetStatus:
"""
return: boolean
"""
try:
self.status = int(self.status)
except Exception as e:
self.log.error('Status argument does not represent a integer')
return False
if self.status in (0, 1):
self.log.debug('Set value to {}'.format(self.status))
self.status = bytes([self.status])
if self.status in ('0', '1'):
self.log.debug('Set status to {}'.format(self.status))
return True
self.log.debug('{} is not a valid status'.format(self.status))
return False
def set_config(self):
@ -197,7 +192,6 @@ class SetStatus:
# check given status
if self.check_status() is False:
self.log.error('No valid status given')
exit(1)
# log config if level is debug
@ -222,12 +216,14 @@ class SetStatus:
# send status
try:
self.log.debug('Send new status: {}'.format(self.status))
self.connection.send(self.status)
self.connection.send(self.status.encode(encoding='utf-8',
errors='strict'))
except Exception as e:
self.log.error('Error: {}'.format(e))
exit(6)
try:
response = self.connection.recv(1)
response = self.connection.recv(1).decode(encoding='utf-8',
errors='strict')
self.log.debug('Server returns: {}'.format(response))
if response == self.status:
self.log.info('Status sucessfull updated')