tools.py 11 KB

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