cfg.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2021 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. cfg.py: API for the MMGen runtime configuration file and related files
  20. """
  21. # NB: This module is used by override_from_cfg_file(), which is called before override_from_env()
  22. # during init, so global config vars that are set from the environment (such as g.test_suite)
  23. # cannot be used here.
  24. import sys,os,re,hashlib
  25. from collections import namedtuple
  26. from .globalvars import *
  27. from .util import *
  28. def cfg_file(id_str):
  29. return CfgFile.get_cls_by_id(id_str)()
  30. class CfgFile(object):
  31. cur_ver = 2
  32. ver = None
  33. write_ok = False
  34. warn_missing = True
  35. write_metadata = False
  36. fn_base = g.proj_name.lower() + '.cfg'
  37. line_data = namedtuple('cfgfile_line',['name','value','lineno','chunk'])
  38. class warn_missing_file(oneshot_warning):
  39. color = 'yellow' # has no effect, as color not initialized yet
  40. message = '{} not found at {!r}'
  41. def __init__(self):
  42. self.fn = os.path.join(self.fn_dir,self.fn_base)
  43. try:
  44. self.data = open(self.fn).read().splitlines()
  45. except:
  46. if self.warn_missing:
  47. self.warn_missing_file( div=self.fn, fmt_args=(self.desc,self.fn) )
  48. self.data = ''
  49. def copy_data(self):
  50. assert self.write_ok, f'writing to file {self.fn!r} not allowed!'
  51. src = cfg_file('sys')
  52. if src.data:
  53. data = src.data + src.make_metadata() if self.write_metadata else src.data
  54. try:
  55. open(self.fn,'w').write('\n'.join(data)+'\n')
  56. os.chmod(self.fn,0o600)
  57. except:
  58. die(2,f'ERROR: unable to write to {self.fn!r}')
  59. def parse_value(self,value,refval):
  60. if isinstance(refval,dict):
  61. m = re.fullmatch(r'((\s+\w+:\S+)+)',' '+value) # expect one or more colon-separated values
  62. if m:
  63. return dict([i.split(':') for i in m[1].split()])
  64. elif isinstance(refval,list) or isinstance(refval,tuple):
  65. m = re.fullmatch(r'((\s+\S+)+)',' '+value) # expect single value or list
  66. if m:
  67. ret = m[1].split()
  68. return ret if isinstance(refval,list) else tuple(ret)
  69. else:
  70. return value
  71. def get_lines(self):
  72. def gen_lines():
  73. for lineno,line in enumerate(self.data,1):
  74. line = strip_comment(line)
  75. if line == '':
  76. continue
  77. m = re.fullmatch(r'(\w+)(\s+)(.*)',line)
  78. if m:
  79. yield self.line_data(m[1],m[3],lineno,None)
  80. else:
  81. raise CfgFileParseError(f'Parse error in file {self.fn!r}, line {lineno}')
  82. return gen_lines()
  83. @classmethod
  84. def get_cls_by_id(self,id_str):
  85. d = {
  86. 'usr': CfgFileUsr,
  87. 'sys': CfgFileSampleSys,
  88. 'sample': CfgFileSampleUsr,
  89. }
  90. return d[id_str]
  91. class CfgFileSample(CfgFile):
  92. @classmethod
  93. def cls_make_metadata(cls,data):
  94. return [f'# Version {cls.cur_ver} {cls.compute_chksum(data)}']
  95. @staticmethod
  96. def compute_chksum(data):
  97. return hashlib.new('ripemd160','\n'.join(data).encode()).hexdigest()
  98. @property
  99. def computed_chksum(self):
  100. return type(self).compute_chksum(self.data)
  101. def get_lines(self):
  102. """
  103. The config file template contains some 'magic':
  104. - lines must either be empty or begin with '# '
  105. - each commented chunk must end with a parsable cfg variable line
  106. - chunks are delimited by one or more blank lines
  107. - lines beginning with '##' are ignored
  108. - everything up to first line beginning with '##' is ignored
  109. - last line is metadata line of the form '# Version VER_NUM HASH'
  110. """
  111. def process_chunk(chunk,lineno):
  112. m = re.fullmatch(r'(#\s*)(\w+)(\s+)(.*)',chunk[-1])
  113. if m:
  114. return self.line_data(m[2],m[4],lineno,chunk)
  115. else:
  116. raise CfgFileParseError(f'Parse error in file {self.fn!r}, line {lineno}')
  117. def gen_chunks(lines):
  118. hdr = True
  119. chunk = []
  120. in_chunk = False
  121. for lineno,line in enumerate(lines,1):
  122. if line.startswith('##'):
  123. hdr = False
  124. continue
  125. if hdr:
  126. continue
  127. if line == '':
  128. in_chunk = False
  129. elif line.startswith('#'):
  130. if in_chunk == False:
  131. if chunk:
  132. yield process_chunk(chunk,last_nonblank)
  133. chunk = [line]
  134. in_chunk = True
  135. else:
  136. chunk.append(line)
  137. last_nonblank = lineno
  138. else:
  139. raise CfgFileParseError(f'Parse error in file {self.fn!r}, line {lineno}')
  140. if chunk:
  141. yield process_chunk(chunk,last_nonblank)
  142. return list(gen_chunks(self.data))
  143. class CfgFileUsr(CfgFile):
  144. desc = 'user configuration file'
  145. warn_missing = False
  146. fn_dir = g.data_dir_root
  147. write_ok = True
  148. def __init__(self):
  149. super().__init__()
  150. if not self.data:
  151. self.copy_data()
  152. class CfgFileSampleSys(CfgFileSample):
  153. desc = 'system sample configuration file'
  154. test_fn_subdir = 'usr.local.share'
  155. def __init__(self):
  156. if os.getenv('MMGEN_TEST_SUITE_CFGTEST'):
  157. self.fn = os.path.join(g.data_dir_root,self.test_fn_subdir,self.fn_base)
  158. self.data = open(self.fn).read().splitlines()
  159. else:
  160. # self.fn is used for error msgs only, so file need not exist on filesystem
  161. self.fn = os.path.join(os.path.dirname(__file__),'data',self.fn_base)
  162. # Resource will be unpacked and then cleaned up if necessary, see:
  163. # https://docs.python.org/3/library/importlib.html:
  164. # Note: This module provides functionality similar to pkg_resources Basic
  165. # Resource Access without the performance overhead of that package.
  166. # https://importlib-resources.readthedocs.io/en/latest/migration.html
  167. # https://setuptools.readthedocs.io/en/latest/pkg_resources.html
  168. try:
  169. from importlib.resources import files # Python 3.9
  170. except ImportError:
  171. from importlib_resources import files
  172. self.data = files('mmgen').joinpath('data',self.fn_base).read_text().splitlines()
  173. def make_metadata(self):
  174. return [f'# Version {self.cur_ver} {self.computed_chksum}']
  175. class CfgFileSampleUsr(CfgFileSample):
  176. desc = 'sample configuration file'
  177. warn_missing = False
  178. fn_base = g.proj_name.lower() + '.cfg.sample'
  179. fn_dir = g.data_dir_root
  180. write_ok = True
  181. chksum = None
  182. write_metadata = True
  183. details_confirm_prompt = 'View details?'
  184. out_of_date_fs = 'File {!r} is out of date - replacing'
  185. altered_by_user_fs = 'File {!r} was altered by user - replacing'
  186. def __init__(self):
  187. super().__init__()
  188. src = cfg_file('sys')
  189. if not src.data:
  190. return
  191. if self.data:
  192. if self.parse_metadata():
  193. if self.chksum == self.computed_chksum:
  194. diff = self.diff(self.get_lines(),src.get_lines())
  195. if not diff:
  196. return
  197. self.show_changes(diff)
  198. else:
  199. msg(self.altered_by_user_fs.format(self.fn))
  200. else:
  201. msg(self.out_of_date_fs.format(self.fn))
  202. self.copy_data()
  203. def parse_metadata(self):
  204. if self.data:
  205. m = re.match(r'# Version (\d+) ([a-f0-9]{40})$',self.data[-1])
  206. if m:
  207. self.ver = m[1]
  208. self.chksum = m[2]
  209. self.data = self.data[:-1] # remove metadata line
  210. return True
  211. def diff(self,a_tup,b_tup): # a=user, b=system
  212. a = [i.name for i in a_tup]#[3:] # Debug
  213. b = [i.name for i in b_tup]#[:-2] # Debug
  214. removed = set(a) - set(b)
  215. added = set(b) - set(a)
  216. if removed or added:
  217. return {
  218. 'removed': [i for i in a_tup if i.name in removed],
  219. 'added': [i for i in b_tup if i.name in added],
  220. }
  221. else:
  222. return None
  223. def show_changes(self,diff):
  224. ymsg('Warning: configuration file options have changed!\n')
  225. for desc in ('added','removed'):
  226. data = diff[desc]
  227. if data:
  228. opts = fmt_list([i.name for i in data],fmt='bare')
  229. msg(f' The following option{suf(data,verb="has")} been {desc}:\n {opts}\n')
  230. if desc == 'removed' and data:
  231. uc = cfg_file('usr')
  232. usr_names = [i.name for i in uc.get_lines()]
  233. rm_names = [i.name for i in data]
  234. bad = sorted(set(usr_names).intersection(rm_names))
  235. if bad:
  236. m = f"""
  237. The following removed option{suf(bad,verb='is')} set in {uc.fn!r}
  238. and must be deleted or commented out:
  239. {' ' + fmt_list(bad,fmt='bare')}
  240. """
  241. ymsg(fmt(m,indent=' ',strip_char='\t'))
  242. while True:
  243. if not keypress_confirm(self.details_confirm_prompt,no_nl=True):
  244. return
  245. def get_details():
  246. for desc,data in diff.items():
  247. sep,sep2 = ('\n ','\n\n ')
  248. if data:
  249. yield (
  250. f'{capfirst(desc)} section{suf(data)}:'
  251. + sep2
  252. + sep2.join([f'{sep.join(v.chunk)}' for v in data])
  253. )
  254. do_pager(
  255. 'CONFIGURATION FILE CHANGES\n\n'
  256. + '\n\n'.join(get_details()) + '\n'
  257. )