cfg.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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
  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. die( '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. import hashlib
  100. return hashlib.new('ripemd160','\n'.join(data).encode()).hexdigest()
  101. @property
  102. def computed_chksum(self):
  103. return type(self).compute_chksum(self.data)
  104. def get_lines(self):
  105. """
  106. The config file template contains some 'magic':
  107. - lines must either be empty or begin with '# '
  108. - each commented chunk must end with a parsable cfg variable line
  109. - chunks are delimited by one or more blank lines
  110. - lines beginning with '##' are ignored
  111. - everything up to first line beginning with '##' is ignored
  112. - last line is metadata line of the form '# Version VER_NUM HASH'
  113. """
  114. def process_chunk(chunk,lineno):
  115. m = re.fullmatch(r'(#\s*)(\w+)(\s+)(.*)',chunk[-1])
  116. if m:
  117. return self.line_data(m[2],m[4],lineno,chunk)
  118. else:
  119. die( 'CfgFileParseError', f'Parse error in file {self.fn!r}, line {lineno}' )
  120. def gen_chunks(lines):
  121. hdr = True
  122. chunk = []
  123. in_chunk = False
  124. for lineno,line in enumerate(lines,1):
  125. if line.startswith('##'):
  126. hdr = False
  127. continue
  128. if hdr:
  129. continue
  130. if line == '':
  131. in_chunk = False
  132. elif line.startswith('#'):
  133. if in_chunk == False:
  134. if chunk:
  135. yield process_chunk(chunk,last_nonblank)
  136. chunk = [line]
  137. in_chunk = True
  138. else:
  139. chunk.append(line)
  140. last_nonblank = lineno
  141. else:
  142. die( 'CfgFileParseError', f'Parse error in file {self.fn!r}, line {lineno}' )
  143. if chunk:
  144. yield process_chunk(chunk,last_nonblank)
  145. return list(gen_chunks(self.data))
  146. class CfgFileUsr(CfgFile):
  147. desc = 'user configuration file'
  148. warn_missing = False
  149. fn_dir = g.data_dir_root
  150. write_ok = True
  151. def __init__(self):
  152. super().__init__()
  153. if not self.data:
  154. self.copy_data()
  155. class CfgFileSampleSys(CfgFileSample):
  156. desc = 'system sample configuration file'
  157. test_fn_subdir = 'usr.local.share'
  158. def __init__(self):
  159. if os.getenv('MMGEN_TEST_SUITE_CFGTEST'):
  160. self.fn = os.path.join(g.data_dir_root,self.test_fn_subdir,self.fn_base)
  161. with open(self.fn) as fp:
  162. self.data = fp.read().splitlines()
  163. else:
  164. # self.fn is used for error msgs only, so file need not exist on filesystem
  165. self.fn = os.path.join(os.path.dirname(__file__),'data',self.fn_base)
  166. self.data = g.get_mmgen_data_file(self.fn_base).splitlines()
  167. def make_metadata(self):
  168. return [f'# Version {self.cur_ver} {self.computed_chksum}']
  169. class CfgFileSampleUsr(CfgFileSample):
  170. desc = 'sample configuration file'
  171. warn_missing = False
  172. fn_base = g.proj_name.lower() + '.cfg.sample'
  173. fn_dir = g.data_dir_root
  174. write_ok = True
  175. chksum = None
  176. write_metadata = True
  177. details_confirm_prompt = 'View details?'
  178. out_of_date_fs = 'File {!r} is out of date - replacing'
  179. altered_by_user_fs = 'File {!r} was altered by user - replacing'
  180. def __init__(self):
  181. super().__init__()
  182. src = cfg_file('sys')
  183. if not src.data:
  184. return
  185. if self.data:
  186. if self.parse_metadata():
  187. if self.chksum == self.computed_chksum:
  188. diff = self.diff(self.get_lines(),src.get_lines())
  189. if not diff:
  190. return
  191. self.show_changes(diff)
  192. else:
  193. msg(self.altered_by_user_fs.format(self.fn))
  194. else:
  195. msg(self.out_of_date_fs.format(self.fn))
  196. self.copy_data()
  197. def parse_metadata(self):
  198. if self.data:
  199. m = re.match(r'# Version (\d+) ([a-f0-9]{40})$',self.data[-1])
  200. if m:
  201. self.ver = m[1]
  202. self.chksum = m[2]
  203. self.data = self.data[:-1] # remove metadata line
  204. return True
  205. def diff(self,a_tup,b_tup): # a=user, b=system
  206. a = [i.name for i in a_tup]#[3:] # Debug
  207. b = [i.name for i in b_tup]#[:-2] # Debug
  208. removed = set(a) - set(b)
  209. added = set(b) - set(a)
  210. if removed or added:
  211. return {
  212. 'removed': [i for i in a_tup if i.name in removed],
  213. 'added': [i for i in b_tup if i.name in added],
  214. }
  215. else:
  216. return None
  217. def show_changes(self,diff):
  218. ymsg('Warning: configuration file options have changed!\n')
  219. for desc in ('added','removed'):
  220. data = diff[desc]
  221. if data:
  222. opts = fmt_list([i.name for i in data],fmt='bare')
  223. msg(f' The following option{suf(data,verb="has")} been {desc}:\n {opts}\n')
  224. if desc == 'removed' and data:
  225. uc = cfg_file('usr')
  226. usr_names = [i.name for i in uc.get_lines()]
  227. rm_names = [i.name for i in data]
  228. bad = sorted(set(usr_names).intersection(rm_names))
  229. if bad:
  230. m = f"""
  231. The following removed option{suf(bad,verb='is')} set in {uc.fn!r}
  232. and must be deleted or commented out:
  233. {' ' + fmt_list(bad,fmt='bare')}
  234. """
  235. ymsg(fmt(m,indent=' ',strip_char='\t'))
  236. while True:
  237. if not keypress_confirm(self.details_confirm_prompt,no_nl=True):
  238. return
  239. def get_details():
  240. for desc,data in diff.items():
  241. sep,sep2 = ('\n ','\n\n ')
  242. if data:
  243. yield (
  244. f'{capfirst(desc)} section{suf(data)}:'
  245. + sep2
  246. + sep2.join([f'{sep.join(v.chunk)}' for v in data])
  247. )
  248. do_pager(
  249. 'CONFIGURATION FILE CHANGES\n\n'
  250. + '\n\n'.join(get_details()) + '\n'
  251. )