tools.py 11 KB

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