fileutil.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2024 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: Routines that read, write, execute or stat files
  20. """
  21. # 09 Mar 2024: make all utils accept Path instances as arguments
  22. import sys,os
  23. from .color import set_vt100
  24. from .util import (
  25. msg,
  26. die,
  27. get_extension,
  28. is_utf8,
  29. capfirst,
  30. make_full_path,
  31. strip_comments,
  32. )
  33. def check_or_create_dir(path):
  34. try:
  35. os.listdir(path)
  36. except:
  37. if os.getenv('MMGEN_TEST_SUITE'):
  38. if os.path.exists(path): # path is a link or regular file
  39. from subprocess import run
  40. run([
  41. ('rm' if sys.platform == 'win32' else '/bin/rm'),
  42. '-rf',
  43. str(path)])
  44. set_vt100()
  45. try:
  46. os.makedirs(path,0o700)
  47. except:
  48. die(2, f'ERROR: unable to read or create path ‘{path}’')
  49. def check_binary(args):
  50. from subprocess import run,DEVNULL
  51. try:
  52. run(args,stdout=DEVNULL,stderr=DEVNULL,check=True)
  53. except:
  54. die(2,f'{args[0]!r} binary missing, not in path, or not executable')
  55. set_vt100()
  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. + [str(fn)],
  63. check=True )
  64. set_vt100()
  65. def _check_file_type_and_access(fname,ftype,blkdev_ok=False):
  66. import stat
  67. access,op_desc = (
  68. (os.W_OK,'writ') if ftype in ('output file','output directory') else
  69. (os.R_OK,'read') )
  70. if ftype == 'output directory':
  71. ok_types = [(stat.S_ISDIR, 'output directory')]
  72. else:
  73. ok_types = [
  74. (stat.S_ISREG,'regular file'),
  75. (stat.S_ISLNK,'symbolic link')
  76. ]
  77. if blkdev_ok:
  78. ok_types.append((stat.S_ISBLK,'block device'))
  79. try:
  80. mode = os.stat(fname).st_mode
  81. except:
  82. die('FileNotFound', f'Requested {ftype} ‘{fname}’ 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}’ is not a {ok_list}')
  89. if not os.access(fname,access):
  90. die(1, f'Requested {ftype} ‘{fname}’ 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(cfg,nargs,wallets=None,invoked_as=None):
  99. wallets = wallets or cfg._args
  100. from .filename import find_file_in_dir
  101. from .wallet.mmgen import wallet
  102. wf = find_file_in_dir(wallet,cfg.data_dir)
  103. wd_from_opt = bool(cfg.hidden_incog_input_params or cfg.in_fmt) # have wallet data from opt?
  104. if len(wallets) + (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. cfg._opts.usage()
  108. elif len(wallets) > nargs:
  109. cfg._opts.usage()
  110. elif len(wallets) == nargs and wf and invoked_as != 'gen':
  111. cfg._util.qmsg('Warning: overriding default wallet with user-supplied wallet')
  112. if wallets or wf:
  113. check_infile(wallets[0] if wallets else wf)
  114. return str(wallets[0]) if wallets else (wf,None)[wd_from_opt] # could be a Path instance
  115. def _open_or_die(filename,mode,silent=False):
  116. try:
  117. return open(filename,mode)
  118. except:
  119. if silent:
  120. die(2,'')
  121. else:
  122. fn = {0:'STDIN',1:'STDOUT',2:'STDERR'}[filename] if isinstance(filename,int) else f'‘{filename}’'
  123. desc = 'reading' if 'r' in mode else 'writing'
  124. die(2, f'Unable to open file {fn} for {desc}')
  125. def write_data_to_file(
  126. cfg,
  127. outfile,
  128. data,
  129. desc = 'data',
  130. ask_write = False,
  131. ask_write_prompt = '',
  132. ask_write_default_yes = True,
  133. ask_overwrite = True,
  134. ask_tty = True,
  135. no_tty = False,
  136. quiet = False,
  137. binary = False,
  138. ignore_opt_outdir = False,
  139. outdir = None,
  140. check_data = False,
  141. cmp_data = None):
  142. outfile = str(outfile) # could be a Path instance
  143. if quiet:
  144. ask_tty = ask_overwrite = False
  145. if cfg.quiet:
  146. ask_overwrite = False
  147. if ask_write_default_yes is False or ask_write_prompt:
  148. ask_write = True
  149. def do_stdout():
  150. cfg._util.qmsg('Output to STDOUT requested')
  151. if cfg.stdin_tty:
  152. if no_tty:
  153. die(2,f'Printing {desc} to screen is not allowed')
  154. if (ask_tty and not cfg.quiet) or binary:
  155. from .ui import confirm_or_raise
  156. confirm_or_raise(
  157. cfg,
  158. message = '',
  159. action = f'output {desc} to screen' )
  160. else:
  161. try:
  162. of = os.readlink(f'/proc/{os.getpid()}/fd/1') # Linux
  163. except:
  164. of = None # Windows
  165. if of:
  166. if of[:5] == 'pipe:':
  167. if no_tty:
  168. die(2,f'Writing {desc} to pipe is not allowed')
  169. if ask_tty and not cfg.quiet:
  170. from .ui import confirm_or_raise
  171. confirm_or_raise(
  172. cfg,
  173. message = '',
  174. action = f'output {desc} to pipe' )
  175. msg('')
  176. of2,pd = os.path.relpath(of),os.path.pardir
  177. msg('Redirecting output to file {!r}'.format(of if of2[:len(pd)] == pd else of2))
  178. else:
  179. msg('Redirecting output to file')
  180. if binary:
  181. if sys.platform == 'win32': # condition on separate line for pylint
  182. import msvcrt
  183. msvcrt.setmode(sys.stdout.fileno(),os.O_BINARY)
  184. # MSWin workaround. See msg_r()
  185. try:
  186. sys.stdout.write(data.decode() if isinstance(data,bytes) else data)
  187. except:
  188. os.write(1,data if isinstance(data,bytes) else data.encode())
  189. def do_file(outfile,ask_write_prompt):
  190. if (outdir or (cfg.outdir and not ignore_opt_outdir)) and not os.path.isabs(outfile):
  191. outfile = make_full_path(str(outdir or cfg.outdir), outfile) # outdir could be Path instance
  192. if ask_write:
  193. if not ask_write_prompt:
  194. ask_write_prompt = f'Save {desc}?'
  195. from .ui import keypress_confirm
  196. if not keypress_confirm(
  197. cfg,
  198. ask_write_prompt,
  199. default_yes = ask_write_default_yes ):
  200. die(1,f'{capfirst(desc)} not saved')
  201. hush = False
  202. if os.path.lexists(outfile) and ask_overwrite:
  203. from .ui import confirm_or_raise
  204. confirm_or_raise(
  205. cfg,
  206. message = '',
  207. action = f'File {outfile!r} already exists\nOverwrite?' )
  208. msg(f'Overwriting file {outfile!r}')
  209. hush = True
  210. # not atomic, but better than nothing
  211. # if cmp_data is empty, file can be either empty or non-existent
  212. if check_data:
  213. d = ''
  214. try:
  215. with open(outfile,('r','rb')[bool(binary)]) as fp:
  216. d = fp.read()
  217. except:
  218. pass
  219. if d != cmp_data:
  220. die(3,f'{desc} in file {outfile!r} has been altered by some other program! Aborting file write')
  221. # To maintain portability, always open files in binary mode
  222. # If 'binary' option not set, encode/decode data before writing and after reading
  223. try:
  224. with _open_or_die(outfile,'wb') as fp:
  225. fp.write(data if binary else data.encode())
  226. except:
  227. die(2,f'Failed to write {desc} to file {outfile!r}')
  228. if not (hush or quiet):
  229. msg(f'{capfirst(desc)} written to file {outfile!r}')
  230. return True
  231. if cfg.stdout or outfile in ('','-'):
  232. do_stdout()
  233. elif sys.stdin.isatty() and not sys.stdout.isatty():
  234. do_stdout()
  235. else:
  236. do_file(outfile,ask_write_prompt)
  237. def get_words_from_file(cfg,infile,desc,quiet=False):
  238. if not quiet:
  239. cfg._util.qmsg(f'Getting {desc} from file ‘{infile}’')
  240. with _open_or_die(infile, 'rb') as fp:
  241. data = fp.read()
  242. try:
  243. words = data.decode().split()
  244. except:
  245. die(1,f'{capfirst(desc)} data must be UTF-8 encoded.')
  246. cfg._util.dmsg('Sanitized input: [{}]'.format(' '.join(words)))
  247. return words
  248. def get_data_from_file(
  249. cfg,
  250. infile,
  251. desc = 'data',
  252. dash = False,
  253. silent = False,
  254. binary = False,
  255. quiet = False ):
  256. if not (cfg.quiet or silent or quiet):
  257. cfg._util.qmsg(f'Getting {desc} from file ‘{infile}’')
  258. with _open_or_die(
  259. (0 if dash and infile == '-' else infile),
  260. 'rb',
  261. silent=silent) as fp:
  262. data = fp.read(cfg.max_input_size+1)
  263. if not binary:
  264. data = data.decode()
  265. if len(data) == cfg.max_input_size + 1:
  266. die( 'MaxInputSizeExceeded',
  267. f'Too much input data! Max input data size: {cfg.max_input_size} bytes' )
  268. return data
  269. def get_lines_from_file(
  270. cfg,
  271. fn,
  272. desc = 'data',
  273. trim_comments = False,
  274. quiet = False,
  275. silent = False ):
  276. def decrypt_file_maybe():
  277. data = get_data_from_file( cfg, fn, desc=desc, binary=True, quiet=quiet, silent=silent )
  278. from .crypto import Crypto
  279. have_enc_ext = get_extension(fn) == Crypto.mmenc_ext
  280. if have_enc_ext or not is_utf8(data):
  281. m = ('Attempting to decrypt','Decrypting')[have_enc_ext]
  282. cfg._util.qmsg(f'{m} {desc} ‘{fn}’')
  283. data = Crypto(cfg).mmgen_decrypt_retry(data,desc)
  284. return data
  285. lines = decrypt_file_maybe().decode().splitlines()
  286. if trim_comments:
  287. lines = strip_comments(lines)
  288. cfg._util.dmsg(f'Got {len(lines)} lines from file ‘{fn}’')
  289. return lines