fileutil.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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. die(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. die( 'FileNotFound', f'Requested {ftype} {fname!r} not found' )
  82. for t in ok_types:
  83. if t[0](mode):
  84. break
  85. else:
  86. ok_list = ' or '.join( t[1] for t in ok_types )
  87. die(1,f'Requested {ftype} {fname!r} is not a {ok_list}')
  88. if not os.access(fname,access):
  89. die(1,f'Requested {ftype} {fname!r} is not {op_desc}able by you')
  90. return True
  91. def check_infile(f,blkdev_ok=False):
  92. return _check_file_type_and_access(f,'input file',blkdev_ok=blkdev_ok)
  93. def check_outfile(f,blkdev_ok=False):
  94. return _check_file_type_and_access(f,'output file',blkdev_ok=blkdev_ok)
  95. def check_outdir(f):
  96. return _check_file_type_and_access(f,'output directory')
  97. def get_seed_file(cmd_args,nargs,invoked_as=None):
  98. from .opts import opt
  99. from .filename import find_file_in_dir
  100. from .wallet import MMGenWallet
  101. wf = find_file_in_dir(MMGenWallet,g.data_dir)
  102. wd_from_opt = bool(opt.hidden_incog_input_params or opt.in_fmt) # have wallet data from opt?
  103. import mmgen.opts as opts
  104. if len(cmd_args) + (wd_from_opt or bool(wf)) < nargs:
  105. if not wf:
  106. msg('No default wallet found, and no other seed source was specified')
  107. opts.usage()
  108. elif len(cmd_args) > nargs:
  109. opts.usage()
  110. elif len(cmd_args) == nargs and wf and invoked_as != 'gen':
  111. qmsg('Warning: overriding default wallet with user-supplied wallet')
  112. if cmd_args or wf:
  113. check_infile(cmd_args[0] if cmd_args else wf)
  114. return cmd_args[0] if cmd_args else (wf,None)[wd_from_opt]
  115. def _open_or_die(filename,mode,silent=False):
  116. try:
  117. return open(filename,mode)
  118. except:
  119. die(2,'' if silent else
  120. 'Unable to open file {!r} for {}'.format(
  121. ({0:'STDIN',1:'STDOUT',2:'STDERR'}[filename] if type(filename) == int else filename),
  122. ('reading' if 'r' in mode else 'writing')
  123. ))
  124. def write_data_to_file( outfile,data,desc='data',
  125. ask_write=False,
  126. ask_write_prompt='',
  127. ask_write_default_yes=True,
  128. ask_overwrite=True,
  129. ask_tty=True,
  130. no_tty=False,
  131. quiet=False,
  132. binary=False,
  133. ignore_opt_outdir=False,
  134. check_data=False,
  135. cmp_data=None):
  136. from .opts import opt
  137. if quiet:
  138. ask_tty = ask_overwrite = False
  139. if opt.quiet:
  140. ask_overwrite = False
  141. if ask_write_default_yes == False or ask_write_prompt:
  142. ask_write = True
  143. def do_stdout():
  144. qmsg('Output to STDOUT requested')
  145. if g.stdin_tty:
  146. if no_tty:
  147. die(2,f'Printing {desc} to screen is not allowed')
  148. if (ask_tty and not opt.quiet) or binary:
  149. confirm_or_raise('',f'output {desc} to screen')
  150. else:
  151. try: of = os.readlink(f'/proc/{os.getpid()}/fd/1') # Linux
  152. except: of = None # Windows
  153. if of:
  154. if of[:5] == 'pipe:':
  155. if no_tty:
  156. die(2,f'Writing {desc} to pipe is not allowed')
  157. if ask_tty and not opt.quiet:
  158. confirm_or_raise('',f'output {desc} to pipe')
  159. msg('')
  160. of2,pd = os.path.relpath(of),os.path.pardir
  161. msg('Redirecting output to file {!r}'.format(of if of2[:len(pd)] == pd else of2))
  162. else:
  163. msg('Redirecting output to file')
  164. if binary and g.platform == 'win':
  165. import msvcrt
  166. msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
  167. # MSWin workaround. See msg_r()
  168. try:
  169. sys.stdout.write(data.decode() if isinstance(data,bytes) else data)
  170. except:
  171. os.write(1,data if isinstance(data,bytes) else data.encode())
  172. def do_file(outfile,ask_write_prompt):
  173. if opt.outdir and not ignore_opt_outdir and not os.path.isabs(outfile):
  174. outfile = make_full_path(opt.outdir,outfile)
  175. if ask_write:
  176. if not ask_write_prompt:
  177. ask_write_prompt = f'Save {desc}?'
  178. if not keypress_confirm(ask_write_prompt,
  179. default_yes=ask_write_default_yes):
  180. die(1,f'{capfirst(desc)} not saved')
  181. hush = False
  182. if os.path.lexists(outfile) and ask_overwrite:
  183. confirm_or_raise('',f'File {outfile!r} already exists\nOverwrite?')
  184. msg(f'Overwriting file {outfile!r}')
  185. hush = True
  186. # not atomic, but better than nothing
  187. # if cmp_data is empty, file can be either empty or non-existent
  188. if check_data:
  189. try:
  190. with open(outfile,('r','rb')[bool(binary)]) as fp:
  191. d = fp.read()
  192. except:
  193. d = ''
  194. finally:
  195. if d != cmp_data:
  196. if g.test_suite:
  197. print_diff(cmp_data,d)
  198. die(3,f'{desc} in file {outfile!r} has been altered by some other program! Aborting file write')
  199. # To maintain portability, always open files in binary mode
  200. # If 'binary' option not set, encode/decode data before writing and after reading
  201. try:
  202. with _open_or_die(outfile,'wb') as fp:
  203. fp.write(data if binary else data.encode())
  204. except:
  205. die(2,f'Failed to write {desc} to file {outfile!r}')
  206. if not (hush or quiet):
  207. msg(f'{capfirst(desc)} written to file {outfile!r}')
  208. return True
  209. if opt.stdout or outfile in ('','-'):
  210. do_stdout()
  211. elif sys.stdin.isatty() and not sys.stdout.isatty():
  212. do_stdout()
  213. else:
  214. do_file(outfile,ask_write_prompt)
  215. def get_words_from_file(infile,desc,quiet=False):
  216. if not quiet:
  217. qmsg(f'Getting {desc} from file {infile!r}')
  218. with _open_or_die(infile, 'rb') as fp:
  219. data = fp.read()
  220. try:
  221. words = data.decode().split()
  222. except:
  223. die(1,f'{capfirst(desc)} data must be UTF-8 encoded.')
  224. dmsg('Sanitized input: [{}]'.format(' '.join(words)))
  225. return words
  226. def get_data_from_file(infile,desc='data',dash=False,silent=False,binary=False,quiet=False):
  227. from .opts import opt
  228. if not (opt.quiet or silent or quiet):
  229. qmsg(f'Getting {desc} from file {infile!r}')
  230. with _open_or_die(
  231. (0 if dash and infile == '-' else infile),
  232. 'rb',
  233. silent=silent) as fp:
  234. data = fp.read(g.max_input_size+1)
  235. if not binary:
  236. data = data.decode()
  237. if len(data) == g.max_input_size + 1:
  238. die( 'MaxInputSizeExceeded',
  239. f'Too much input data! Max input data size: {f.max_input_size} bytes' )
  240. return data
  241. def _mmgen_decrypt_file_maybe(fn,desc='data',quiet=False,silent=False):
  242. d = get_data_from_file(fn,desc=desc,binary=True,quiet=quiet,silent=silent)
  243. from .crypto import mmenc_ext
  244. have_enc_ext = get_extension(fn) == mmenc_ext
  245. if have_enc_ext or not is_utf8(d):
  246. m = ('Attempting to decrypt','Decrypting')[have_enc_ext]
  247. qmsg(f'{m} {desc} {fn!r}')
  248. from .crypto import mmgen_decrypt_retry
  249. d = mmgen_decrypt_retry(d,desc)
  250. return d
  251. def get_lines_from_file(fn,desc='data',trim_comments=False,quiet=False,silent=False):
  252. dec = _mmgen_decrypt_file_maybe(fn,desc=desc,quiet=quiet,silent=silent)
  253. ret = dec.decode().splitlines()
  254. if trim_comments:
  255. ret = strip_comments(ret)
  256. dmsg(f'Got {len(ret)} lines from file {fn!r}')
  257. return ret