This repository has been archived on 2024-12-14. You can view files and clone it, but cannot push or open issues or pull requests.
PyBitmessage-2024-12-14/src/bmconfigparser.py

275 lines
9.9 KiB
Python
Raw Normal View History

2018-04-19 13:02:12 +02:00
"""
BMConfigParser class definition and default configuration settings
"""
import os
import shutil
import sys # FIXME: bad style! write more generally
2018-04-19 13:02:12 +02:00
from datetime import datetime
from six import string_types
from six.moves import configparser
try:
import state
from singleton import Singleton
except ImportError:
from pybitmessage import state
from pybitmessage.singleton import Singleton
SafeConfigParser = configparser.SafeConfigParser
BMConfigDefaults = {
"bitmessagesettings": {
"maxaddrperstreamsend": 500,
"maxbootstrapconnections": 20,
"maxdownloadrate": 0,
"maxoutboundconnections": 8,
"maxtotalconnections": 200,
"maxuploadrate": 0,
"apiinterface": "127.0.0.1",
"apiport": 8442,
"udp": "True"
},
"threads": {
"receive": 3,
},
"network": {
"bind": "",
"dandelion": 90,
},
"inventory": {
"storage": "sqlite",
"acceptmismatch": "False",
},
2017-06-24 12:17:01 +02:00
"knownnodes": {
"maxnodes": 20000,
},
"zlib": {
"maxsize": 1048576
}
}
2018-04-19 13:02:12 +02:00
@Singleton
2021-03-16 10:48:38 +01:00
class BMConfigParser(SafeConfigParser):
"""
Singleton class inherited from :class:`ConfigParser.SafeConfigParser`
with additional methods specific to bitmessage config.
"""
2020-01-17 14:27:36 +01:00
# pylint: disable=too-many-ancestors
_temp = {}
def set(self, section, option, value=None):
2016-12-06 11:01:17 +01:00
if self._optcre is self.OPTCRE or value:
if not isinstance(value, string_types):
2016-12-06 11:01:17 +01:00
raise TypeError("option values must be strings")
if not self.validate(section, option, value):
2018-04-19 13:02:12 +02:00
raise ValueError("Invalid value %s" % value)
return SafeConfigParser.set(self, section, option, value)
2016-12-06 11:01:17 +01:00
2021-03-16 10:48:38 +01:00
def get(self, section, option, raw=False, vars=None):
if sys.version_info[0] == 3:
# pylint: disable=arguments-differ
2021-03-04 15:15:41 +01:00
try:
2021-03-16 10:48:38 +01:00
if section == "bitmessagesettings" and option == "timeformat":
return SafeConfigParser.get(
2021-03-04 15:15:41 +01:00
self, section, option, raw=True, vars=vars)
2021-03-16 10:48:38 +01:00
try:
return self._temp[section][option]
except KeyError:
pass
return SafeConfigParser.get(
2021-03-04 15:15:41 +01:00
self, section, option, raw=True, vars=vars)
except configparser.InterpolationError:
return SafeConfigParser.get(
2021-03-04 15:15:41 +01:00
self, section, option, raw=True, vars=vars)
except (configparser.NoSectionError, configparser.NoOptionError) as e:
2021-03-16 10:48:38 +01:00
try:
return BMConfigDefaults[section][option]
except (KeyError, ValueError, AttributeError):
raise e
else:
# pylint: disable=arguments-differ
try:
2021-03-16 10:48:38 +01:00
if section == "bitmessagesettings" and option == "timeformat":
return SafeConfigParser.get(
2021-03-16 10:48:38 +01:00
self, section, option, raw, vars)
try:
return self._temp[section][option]
except KeyError:
pass
return SafeConfigParser.get(
2021-03-16 10:48:38 +01:00
self, section, option, True, vars)
except configparser.InterpolationError:
return SafeConfigParser.get(
2021-03-16 10:48:38 +01:00
self, section, option, True, vars)
except (configparser.NoSectionError, configparser.NoOptionError) as e:
2021-03-16 10:48:38 +01:00
try:
return BMConfigDefaults[section][option]
except (KeyError, ValueError, AttributeError):
raise e
2016-12-06 11:01:17 +01:00
def setTemp(self, section, option, value=None):
"""Temporary set option to value, not saving."""
try:
self._temp[section][option] = value
except KeyError:
self._temp[section] = {option: value}
def safeGetBoolean(self, section, field):
2019-11-04 15:45:02 +01:00
"""Return value as boolean, False on exceptions"""
try:
2021-03-04 15:15:41 +01:00
# Used in the python2.7
# return self.getboolean(section, field)
# Used in the python3.5.2
# print(config, section, field)
return self.getboolean(section, field)
except (configparser.NoSectionError, configparser.NoOptionError,
2018-04-19 13:02:12 +02:00
ValueError, AttributeError):
return False
def safeGetInt(self, section, field, default=0):
2020-01-17 14:27:36 +01:00
"""Return value as integer, default on exceptions,
0 if default missing"""
try:
2021-03-04 15:15:41 +01:00
# Used in the python2.7
# return self.getint(section, field)
# Used in the python3.7.0
return int(self.get(section, field))
except (configparser.NoSectionError, configparser.NoOptionError,
2018-04-19 13:02:12 +02:00
ValueError, AttributeError):
return default
2017-01-14 23:18:06 +01:00
def safeGetFloat(self, section, field, default=0.0):
"""Return value as float, default on exceptions,
0.0 if default missing"""
try:
return self.getfloat(section, field)
except (configparser.NoSectionError, configparser.NoOptionError,
ValueError, AttributeError):
return default
2018-04-19 13:02:12 +02:00
def safeGet(self, section, option, default=None):
2019-11-04 15:45:02 +01:00
"""Return value as is, default on exceptions, None if default missing"""
try:
return self.get(section, option)
except (configparser.NoSectionError, configparser.NoOptionError,
2018-04-19 13:02:12 +02:00
ValueError, AttributeError):
return default
2020-01-15 11:47:26 +01:00
def items(self, section, raw=False, variables=None):
2021-03-04 15:15:41 +01:00
# pylint: disable=signature-differs
2020-01-17 14:27:36 +01:00
"""Return section variables as parent,
but override the "raw" argument to always True"""
return SafeConfigParser.items(self, section, True, variables)
2016-12-06 11:01:17 +01:00
2021-03-04 15:15:41 +01:00
if sys.version_info[0] == 3:
@staticmethod
def addresses(hidden=False):
"""Return a list of local bitmessage addresses (from section labels)"""
return [x for x in BMConfigParser().sections() if x.startswith('BM-') and (
hidden or not BMConfigParser().safeGetBoolean(x, 'hidden'))]
def _reset(self):
"""Reset current config. There doesn't appear to be a built in
method for this"""
sections = self.sections()
for x in sections:
self.remove_section(x)
2021-03-04 15:15:41 +01:00
def read(self, filenames):
SafeConfigParser.read(self, filenames)
2021-03-04 15:15:41 +01:00
for section in self.sections():
for option in self.options(section):
try:
if not self.validate(
section, option,
self[section][option]
):
try:
newVal = BMConfigDefaults[section][option]
except configparser.NoSectionError:
2021-03-04 15:15:41 +01:00
continue
except KeyError:
continue
SafeConfigParser.set(
2021-03-04 15:15:41 +01:00
self, section, option, newVal)
except configparser.InterpolationError:
2021-03-04 15:15:41 +01:00
continue
else:
@staticmethod
def addresses():
"""Return a list of local bitmessage addresses (from section labels)"""
return [
x for x in BMConfigParser().sections() if x.startswith('BM-')]
def _reset(self):
"""Reset current config. There doesn't appear to be a built in
method for this"""
sections = self.sections()
for x in sections:
self.remove_section(x)
def read(self, filenames):
"""Read config and populate defaults"""
self._reset()
SafeConfigParser.read(self, filenames)
2021-03-04 15:15:41 +01:00
for section in self.sections():
for option in self.options(section):
try:
if not self.validate(
section, option,
SafeConfigParser.get(self, section, option)
2021-03-04 15:15:41 +01:00
):
try:
newVal = BMConfigDefaults[section][option]
except KeyError:
continue
SafeConfigParser.set(
2021-03-04 15:15:41 +01:00
self, section, option, newVal)
except configparser.InterpolationError:
2021-03-04 15:15:41 +01:00
continue
def save(self):
2019-11-04 15:45:02 +01:00
"""Save the runtime config onto the filesystem"""
fileName = os.path.join(state.appdata, 'keys.dat')
2018-04-19 13:02:12 +02:00
fileNameBak = '.'.join([
fileName, datetime.now().strftime("%Y%j%H%M%S%f"), 'bak'])
# create a backup copy to prevent the accidental loss due to
# the disk write failure
try:
shutil.copyfile(fileName, fileNameBak)
# The backup succeeded.
fileNameExisted = True
except (IOError, Exception):
2018-04-19 13:02:12 +02:00
# The backup failed. This can happen if the file
# didn't exist before.
fileNameExisted = False
2021-03-04 15:15:41 +01:00
with open(fileName, 'w') as configfile:
self.write(configfile)
# delete the backup
if fileNameExisted:
os.remove(fileNameBak)
def validate(self, section, option, value):
2019-11-04 15:45:02 +01:00
"""Input validator interface (using factory pattern)"""
try:
return getattr(self, 'validate_%s_%s' % (section, option))(value)
except AttributeError:
return True
2019-11-04 15:45:02 +01:00
@staticmethod
def validate_bitmessagesettings_maxoutboundconnections(value):
"""Reject maxoutboundconnections that are too high or too low"""
try:
value = int(value)
except ValueError:
return False
if value < 0 or value > 8:
return False
return True