tools.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. #============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. #============================================================================
  17. # Copyright (C) 2013 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. """
  20. Define the CLI interface for pwman3 and the helper functions
  21. """
  22. from __future__ import print_function
  23. from pwman.util.callback import Callback
  24. import subprocess as sp
  25. import getpass
  26. import sys
  27. import struct
  28. import os
  29. import colorama
  30. from pwman.data.tags import TagNew as Tag
  31. from pwman.util.config import get_pass_conf
  32. import pwman.util.generator as generator
  33. if sys.version_info.major > 2:
  34. raw_input = input
  35. if sys.platform != 'win32':
  36. import termios
  37. import fcntl
  38. import tty
  39. import readline
  40. _readline_available = True
  41. else: # pragma: no cover
  42. try:
  43. #import pyreadline as readline
  44. import readline
  45. _readline_available = True
  46. except ImportError as e:
  47. _readline_available = False
  48. _defaultwidth = 10
  49. class ANSI(object):
  50. """
  51. ANSI Colors
  52. """
  53. Reset = 0
  54. Bold = 1
  55. Underscore = 2
  56. Black = 30
  57. Red = 31
  58. Green = 32
  59. Yellow = 33
  60. Blue = 34
  61. Magenta = 35
  62. Cyan = 36
  63. White = 37
  64. def typeset(text, color, bold=False, underline=False,
  65. has_colorama=True): # pragma: no cover
  66. """
  67. print colored strings using colorama
  68. """
  69. if not has_colorama:
  70. return text
  71. if bold:
  72. text = colorama.Style.BRIGHT + text
  73. if underline and not 'win32' in sys.platform:
  74. text = ANSI.Underscore + text
  75. return color + text + colorama.Style.RESET_ALL
  76. def select(question, possible): # pragma: no cover
  77. """
  78. select input from user
  79. """
  80. for i in range(0, len(possible)):
  81. print ("%d - %-" + str(_defaultwidth) + "s") % (i + 1, possible[i])
  82. while 1:
  83. uinput = getonechar(question)
  84. if uinput.isdigit() and int(uinput) in range(1, len(possible) + 1):
  85. return possible[int(uinput) - 1]
  86. def text_to_clipboards(text): # pragma: no cover
  87. """
  88. copy text to clipboard
  89. credit:
  90. https://pythonadventures.wordpress.com/tag/xclip/
  91. """
  92. # "primary":
  93. try:
  94. xsel_proc = sp.Popen(['xsel', '-pi'], stdin=sp.PIPE)
  95. xsel_proc.communicate(text)
  96. # "clipboard":
  97. xsel_proc = sp.Popen(['xsel', '-bi'], stdin=sp.PIPE)
  98. xsel_proc.communicate(text)
  99. except OSError as e:
  100. print (e, "\nExecuting xsel failed, is it installed ?\n \
  101. please check your configuration file ... ")
  102. def text_to_mcclipboard(text): # pragma: no cover
  103. """
  104. copy text to mac os x clip board
  105. credit:
  106. https://pythonadventures.wordpress.com/tag/xclip/
  107. """
  108. # "primary":
  109. try:
  110. pbcopy_proc = sp.Popen(['pbcopy'], stdin=sp.PIPE)
  111. pbcopy_proc.communicate(text)
  112. except OSError as e:
  113. print (e, "\nExecuting pbcoy failed...")
  114. def open_url(link, macosx=False): # pragma: no cover
  115. """
  116. launch xdg-open or open in MacOSX with url
  117. """
  118. uopen = "xdg-open"
  119. if macosx:
  120. uopen = "open"
  121. try:
  122. sp.Popen([uopen, link], stdin=sp.PIPE)
  123. except OSError as e:
  124. print ("Executing open_url failed with:\n", e)
  125. def getpassword(question, argsgiven=None,
  126. width=_defaultwidth, echo=False,
  127. reader=getpass.getpass, numerics=False, leetify=False,
  128. symbols=False, special_signs=False,
  129. length=None, config=None): # pragma: no cover
  130. if argsgiven == 1 or length:
  131. while not length:
  132. try:
  133. default_length = config.get_value(
  134. 'Generator', 'default_pw_length') or '8'
  135. length = getinput(
  136. "Password length (default %s): " % default_length,
  137. default=default_length)
  138. length = int(length)
  139. except ValueError:
  140. print("please enter a proper integer")
  141. password, dumpme = generator.generate_password(
  142. length, length, True, symbols=leetify, numerics=numerics,
  143. special_chars=special_signs)
  144. print ("New password: %s" % (password))
  145. return password
  146. # no args given
  147. while True:
  148. a1 = reader(question.ljust(width))
  149. if not a1:
  150. return getpassword(
  151. '', argsgiven=1, width=width, echo=echo, reader=reader,
  152. numerics=numerics, leetify=leetify, symbols=symbols,
  153. special_signs=special_signs, length=length, config=config)
  154. a2 = reader("[Repeat] %s" % (question.ljust(width)))
  155. if a1 == a2:
  156. if leetify:
  157. return generator.leetify(a1)
  158. else:
  159. return a1
  160. else:
  161. print ("Passwords don't match. Try again.")
  162. def gettermsize(): # pragma: no cover
  163. if sys.stdout.isatty():
  164. s = struct.pack("HHHH", 0, 0, 0, 0)
  165. f = sys.stdout.fileno()
  166. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  167. rows, cols, width, height = struct.unpack("HHHH", x)
  168. return rows, cols
  169. else:
  170. return 40, 80
  171. def getinput(question, default="", reader=raw_input,
  172. completer=None, width=_defaultwidth): # pragma: no cover
  173. """
  174. http://stackoverflow.com/questions/2617057/\
  175. supply-inputs-to-python-unittests
  176. """
  177. if reader == raw_input:
  178. if not _readline_available:
  179. val = raw_input(question.ljust(width))
  180. if val:
  181. return val
  182. else:
  183. return default
  184. else:
  185. def defaulter():
  186. """define default behavior startup"""
  187. if _readline_available:
  188. readline.insert_text(default)
  189. readline.set_startup_hook(defaulter)
  190. readline.get_completer()
  191. readline.set_completer(completer)
  192. x = raw_input(question.ljust(width))
  193. readline.set_completer(completer)
  194. readline.set_startup_hook()
  195. if not x:
  196. return default
  197. return x
  198. else:
  199. return reader()
  200. class CMDLoop(object): # pragma: no cover
  201. """
  202. The menu that drives editing of a node
  203. """
  204. def __init__(self):
  205. self.items = []
  206. def add(self, item):
  207. if (isinstance(item, CliMenuItem)):
  208. self.items.append(item)
  209. else:
  210. print (item.__class__)
  211. def run(self, new_node=None, reader=raw_input):
  212. while True:
  213. i = 0
  214. for x in self.items:
  215. i = i + 1
  216. try:
  217. current = x.getter
  218. except AttributeError:
  219. current = x
  220. # when printing tags, we have list ...
  221. currentstr = b''
  222. if type(current) == list:
  223. for c in current:
  224. print(c, type(c))
  225. try:
  226. currentstr += b' ' + c
  227. except TypeError:
  228. currentstr += b' ' + c.name
  229. # for the case we are not dealing with
  230. # a list of tags
  231. else:
  232. currentstr = current
  233. print ("%s - %s: %s" % (i, x.name, currentstr))
  234. print("X - Finish editing")
  235. option = reader("Enter your choice:")[0]
  236. try:
  237. print ("Selection, ", option)
  238. # substract 1 because array subscripts start at 0
  239. selection = int(option) - 1
  240. # new value is created by calling the editor with the
  241. # previous value as a parameter
  242. # TODO: enable overriding password policy as if new node
  243. # is created.
  244. if selection == 0:
  245. new_node.username = getinput("Username:")
  246. self.items[0].getter = new_node.username
  247. self.items[0].setter = new_node.username
  248. elif selection == 1: # for password
  249. numerics, leet, s_chars = get_pass_conf()
  250. new_node.password = getpassword(
  251. 'New Password:', numerics=numerics, leetify=leet,
  252. special_signs=s_chars)
  253. self.items[1].getter = new_node.password
  254. self.items[1].setter = new_node.password
  255. elif selection == 2:
  256. new_node.url = getinput("Url:")
  257. self.items[2].getter = new_node.url
  258. self.items[2].setter = new_node.url
  259. elif selection == 3: # for notes
  260. # new_node.notes = getinput("Notes:")
  261. new_node.notes = reader("Notes:")
  262. self.items[3].getter = new_node.notes
  263. self.items[3].setter = new_node.notes
  264. elif selection == 4:
  265. taglist = getinput("Tags:")
  266. tagstrings = taglist.split()
  267. tags = [Tag(tn) for tn in tagstrings]
  268. new_node.tags = tags
  269. self.items[4].setter = new_node.tags
  270. self.items[4].getter = new_node.tags
  271. except (ValueError, IndexError):
  272. if (option.upper() == 'X'):
  273. break
  274. print("Invalid selection")
  275. def getonechar(question, width=_defaultwidth): # pragma: no cover
  276. question = "%s " % (question)
  277. print (question.ljust(width),)
  278. try:
  279. sys.stdout.flush()
  280. fd = sys.stdin.fileno()
  281. # tty module exists only if we are on Posix
  282. try:
  283. tty_mode = tty.tcgetattr(fd)
  284. tty.setcbreak(fd)
  285. except NameError:
  286. pass
  287. try:
  288. ch = os.read(fd, 1)
  289. finally:
  290. try:
  291. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  292. except NameError:
  293. pass
  294. except AttributeError:
  295. ch = sys.stdin.readline()[0]
  296. print(ch)
  297. return ch
  298. class CliMenuItem(object): # pragma: no cover
  299. def __init__(self, name, editor, getter, setter):
  300. self.name = name
  301. self.editor = editor
  302. self.getter = getter
  303. self.setter = setter
  304. class CLICallback(Callback): # pragma: no cover
  305. def getinput(self, question):
  306. return raw_input(question)
  307. def getsecret(self, question):
  308. return getpass.getpass(question + ":")
  309. def getnewsecret(self, question):
  310. return getpass.getpass(question + ":")