cfg.py 8.8 KB

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