tools.py 11 KB

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