fileutil.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. fileutil.py: Routines that read, write, execute or stat files
  20. """
  21. import sys,os
  22. from .globalvars import g
  23. from .util import (
  24. msg,
  25. qmsg,
  26. dmsg,
  27. die,
  28. confirm_or_raise,
  29. get_extension,
  30. is_utf8,
  31. capfirst,
  32. make_full_path,
  33. strip_comments,
  34. keypress_confirm,
  35. )
  36. def check_or_create_dir(path):
  37. try:
  38. os.listdir(path)
  39. except:
  40. if os.getenv('MMGEN_TEST_SUITE'):
  41. from subprocess import run
  42. try: # exception handling required for MSWin/MSYS2
  43. run(['/bin/rm','-rf',path])
  44. except:
  45. pass
  46. try:
  47. os.makedirs(path,0o700)
  48. except:
  49. die(2,f'ERROR: unable to read or create path {path!r}')
  50. def check_binary(args):
  51. from subprocess import run,DEVNULL
  52. try:
  53. run(args,stdout=DEVNULL,stderr=DEVNULL,check=True)
  54. except:
  55. rdie(2,f'{args[0]!r} binary missing, not in path, or not executable')
  56. def shred_file(fn,verbose=False):
  57. check_binary(['shred','--version'])
  58. from subprocess import run
  59. run(
  60. ['shred','--force','--iterations=30','--zero','--remove=wipesync']
  61. + (['--verbose'] if verbose else [])
  62. + [fn],
  63. check=True )
  64. def _check_file_type_and_access(fname,ftype,blkdev_ok=False):
  65. import stat
  66. access,op_desc = (
  67. (os.W_OK,'writ') if ftype in ('output file','output directory') else
  68. (os.R_OK,'read') )
  69. if ftype == 'output directory':
  70. ok_types = [(stat.S_ISDIR, 'output directory')]
  71. else:
  72. ok_types = [
  73. (stat.S_ISREG,'regular file'),
  74. (stat.S_ISLNK,'symbolic link')
  75. ]
  76. if blkdev_ok:
  77. ok_types.append((stat.S_ISBLK,'block device'))
  78. try:
  79. mode = os.stat(fname).st_mode
  80. except:
  81. from .exception import FileNotFound
  82. raise FileNotFound(f'Requested {ftype} {fname!r} not found')
  83. for t in ok_types:
  84. if t[0](mode):
  85. break
  86. else:
  87. ok_list = ' or '.join( t[1] for t in ok_types )
  88. die(1,f'Requested {ftype} {fname!r} is not a {ok_list}')
  89. if not os.access(fname,access):
  90. die(1,f'Requested {ftype} {fname!r} is not {op_desc}able by you')
  91. return True
  92. def check_infile(f,blkdev_ok=False):
  93. return _check_file_type_and_access(f,'input file',blkdev_ok=blkdev_ok)
  94. def check_outfile(f,blkdev_ok=False):
  95. return _check_file_type_and_access(f,'output file',blkdev_ok=blkdev_ok)
  96. def check_outdir(f):
  97. return _check_file_type_and_access(f,'output directory')
  98. def get_seed_file(cmd_args,nargs,invoked_as=None):
  99. from .opts import opt
  100. from .filename import find_file_in_dir
  101. from .wallet import MMGenWallet
  102. wf = find_file_in_dir(MMGenWallet,g.data_dir)
  103. wd_from_opt = bool(opt.hidden_incog_input_params or opt.in_fmt) # have wallet data from opt?
  104. import mmgen.opts as opts
  105. if len(cmd_args) + (wd_from_opt or bool(wf)) < nargs:
  106. if not wf:
  107. msg('No default wallet found, and no other seed source was specified')
  108. opts.usage()
  109. elif len(cmd_args) > nargs:
  110. opts.usage()
  111. elif len(cmd_args) == nargs and wf and invoked_as != 'gen':
  112. qmsg('Warning: overriding default wallet with user-supplied wallet')
  113. if cmd_args or wf:
  114. check_infile(cmd_args[0] if cmd_args else wf)
  115. return cmd_args[0] if cmd_args else (wf,None)[wd_from_opt]
  116. def _open_or_die(filename,mode,silent=False):
  117. try:
  118. return open(filename,mode)
  119. except:
  120. die(2,'' if silent else
  121. 'Unable to open file {!r} for {}'.format(
  122. ({0:'STDIN',1:'STDOUT',2:'STDERR'}[filename] if type(filename) == int else filename),
  123. ('reading' if 'r' in mode else 'writing')
  124. ))
  125. def write_data_to_file( outfile,data,desc='data',
  126. ask_write=False,
  127. ask_write_prompt='',
  128. ask_write_default_yes=True,
  129. ask_overwrite=True,
  130. ask_tty=True,
  131. no_tty=False,
  132. quiet=False,
  133. binary=False,
  134. ignore_opt_outdir=False,
  135. check_data=False,
  136. cmp_data=None):
  137. from .opts import opt
  138. if quiet:
  139. ask_tty = ask_overwrite = False
  140. if opt.quiet:
  141. ask_overwrite = False
  142. if ask_write_default_yes == False or ask_write_prompt:
  143. ask_write = True
  144. def do_stdout():
  145. qmsg('Output to STDOUT requested')
  146. if g.stdin_tty:
  147. if no_tty:
  148. die(2,f'Printing {desc} to screen is not allowed')
  149. if (ask_tty and not opt.quiet) or binary:
  150. confirm_or_raise('',f'output {desc} to screen')
  151. else:
  152. try: of = os.readlink(f'/proc/{os.getpid()}/fd/1') # Linux
  153. except: of = None # Windows
  154. if of:
  155. if of[:5] == 'pipe:':
  156. if no_tty:
  157. die(2,f'Writing {desc} to pipe is not allowed')
  158. if ask_tty and not opt.quiet:
  159. confirm_or_raise('',f'output {desc} to pipe')
  160. msg('')
  161. of2,pd = os.path.relpath(of),os.path.pardir
  162. msg('Redirecting output to file {!r}'.format(of if of2[:len(pd)] == pd else of2))
  163. else:
  164. msg('Redirecting output to file')
  165. if binary and g.platform == 'win':
  166. import msvcrt
  167. msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
  168. # MSWin workaround. See msg_r()
  169. try:
  170. sys.stdout.write(data.decode() if isinstance(data,bytes) else data)
  171. except:
  172. os.write(1,data if isinstance(data,bytes) else data.encode())
  173. def do_file(outfile,ask_write_prompt):
  174. if opt.outdir and not ignore_opt_outdir and not os.path.isabs(outfile):
  175. outfile = make_full_path(opt.outdir,outfile)
  176. if ask_write:
  177. if not ask_write_prompt:
  178. ask_write_prompt = f'Save {desc}?'
  179. if not keypress_confirm(ask_write_prompt,
  180. default_yes=ask_write_default_yes):
  181. die(1,f'{capfirst(desc)} not saved')
  182. hush = False
  183. if os.path.lexists(outfile) and ask_overwrite:
  184. confirm_or_raise('',f'File {outfile!r} already exists\nOverwrite?')
  185. msg(f'Overwriting file {outfile!r}')
  186. hush = True
  187. # not atomic, but better than nothing
  188. # if cmp_data is empty, file can be either empty or non-existent
  189. if check_data:
  190. try:
  191. with open(outfile,('r','rb')[bool(binary)]) as fp:
  192. d = fp.read()
  193. except:
  194. d = ''
  195. finally:
  196. if d != cmp_data:
  197. if g.test_suite:
  198. print_diff(cmp_data,d)
  199. die(3,f'{desc} in file {outfile!r} has been altered by some other program! Aborting file write')
  200. # To maintain portability, always open files in binary mode
  201. # If 'binary' option not set, encode/decode data before writing and after reading
  202. try:
  203. with _open_or_die(outfile,'wb') as fp:
  204. fp.write(data if binary else data.encode())
  205. except:
  206. die(2,f'Failed to write {desc} to file {outfile!r}')
  207. if not (hush or quiet):
  208. msg(f'{capfirst(desc)} written to file {outfile!r}')
  209. return True
  210. if opt.stdout or outfile in ('','-'):
  211. do_stdout()
  212. elif sys.stdin.isatty() and not sys.stdout.isatty():
  213. do_stdout()
  214. else:
  215. do_file(outfile,ask_write_prompt)
  216. def get_words_from_file(infile,desc,quiet=False):
  217. if not quiet:
  218. qmsg(f'Getting {desc} from file {infile!r}')
  219. with _open_or_die(infile, 'rb') as fp:
  220. data = fp.read()
  221. try:
  222. words = data.decode().split()
  223. except:
  224. die(1,f'{capfirst(desc)} data must be UTF-8 encoded.')
  225. dmsg('Sanitized input: [{}]'.format(' '.join(words)))
  226. return words
  227. def get_data_from_file(infile,desc='data',dash=False,silent=False,binary=False,quiet=False):
  228. from .opts import opt
  229. if not opt.quiet and not silent and not quiet and desc:
  230. qmsg(f'Getting {desc} from file {infile!r}')
  231. with _open_or_die(
  232. (0 if dash and infile == '-' else infile),
  233. 'rb',
  234. silent=silent) as fp:
  235. data = fp.read(g.max_input_size+1)
  236. if not binary:
  237. data = data.decode()
  238. if len(data) == g.max_input_size + 1:
  239. from .exception import MaxInputSizeExceeded
  240. raise MaxInputSizeExceeded(f'Too much input data! Max input data size: {f.max_input_size} bytes')
  241. return data
  242. def _mmgen_decrypt_file_maybe(fn,desc='',quiet=False,silent=False):
  243. d = get_data_from_file(fn,desc,binary=True,quiet=quiet,silent=silent)
  244. from .crypto import mmenc_ext
  245. have_enc_ext = get_extension(fn) == mmenc_ext
  246. if have_enc_ext or not is_utf8(d):
  247. m = ('Attempting to decrypt','Decrypting')[have_enc_ext]
  248. qmsg(f'{m} {desc} {fn!r}')
  249. from .crypto import mmgen_decrypt_retry
  250. d = mmgen_decrypt_retry(d,desc)
  251. return d
  252. def get_lines_from_file(fn,desc='',trim_comments=False,quiet=False,silent=False):
  253. dec = _mmgen_decrypt_file_maybe(fn,desc,quiet=quiet,silent=silent)
  254. ret = dec.decode().splitlines()
  255. if trim_comments:
  256. ret = strip_comments(ret)
  257. dmsg(f'Got {len(ret)} lines from file {fn!r}')
  258. return ret