tools.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. default_length = config.get_value(
  134. 'Generator', 'default_pw_length') or '7'
  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)
  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. s = struct.pack("HHHH", 0, 0, 0, 0)
  164. f = sys.stdout.fileno()
  165. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  166. rows, cols, width, height = struct.unpack("HHHH", x)
  167. return rows, cols
  168. def getinput(question, default="", reader=raw_input,
  169. completer=None, width=_defaultwidth): # pragma: no cover
  170. """
  171. http://stackoverflow.com/questions/2617057/\
  172. supply-inputs-to-python-unittests
  173. """
  174. if reader == raw_input:
  175. if not _readline_available:
  176. val = raw_input(question.ljust(width))
  177. if val:
  178. return val
  179. else:
  180. return default
  181. else:
  182. def defaulter():
  183. """define default behavior startup"""
  184. if _readline_available:
  185. readline.insert_text(default)
  186. readline.set_startup_hook(defaulter)
  187. readline.get_completer()
  188. readline.set_completer(completer)
  189. x = raw_input(question.ljust(width))
  190. readline.set_completer(completer)
  191. readline.set_startup_hook()
  192. if not x:
  193. return default
  194. return x
  195. else:
  196. return reader()
  197. class CMDLoop(object): # pragma: no cover
  198. """
  199. The menu that drives editing of a node
  200. """
  201. def __init__(self):
  202. self.items = []
  203. def add(self, item):
  204. if (isinstance(item, CliMenuItem)):
  205. self.items.append(item)
  206. else:
  207. print (item.__class__)
  208. def run(self, new_node=None):
  209. while True:
  210. i = 0
  211. for x in self.items:
  212. i = i + 1
  213. try:
  214. current = x.getter
  215. except AttributeError:
  216. current = x
  217. # when printing tags, we have list ...
  218. currentstr = ''
  219. if type(current) == list:
  220. for c in current:
  221. try:
  222. currentstr += ' ' + c
  223. except TypeError:
  224. currentstr += ' ' + c.name
  225. # for the case we are not dealing with
  226. # a list of tags
  227. else:
  228. currentstr = current
  229. print ("%s - %s: %s" % (i, x.name, currentstr))
  230. print("X - Finish editing")
  231. option = getonechar("Enter your choice:")
  232. try:
  233. print ("Selection, ", option)
  234. # substract 1 because array subscripts start at 0
  235. selection = int(option) - 1
  236. # new value is created by calling the editor with the
  237. # previous value as a parameter
  238. # TODO: enable overriding password policy as if new node
  239. # is created.
  240. if selection == 0:
  241. new_node.username = getinput("Username:")
  242. self.items[0].getter = new_node.username
  243. self.items[0].setter = new_node.username
  244. elif selection == 1: # for password
  245. numerics, leet, s_chars = get_pass_conf()
  246. new_node.password = getpassword(
  247. 'New Password:', numerics=numerics, leetify=leet,
  248. special_signs=s_chars)
  249. self.items[1].getter = new_node.password
  250. self.items[1].setter = new_node.password
  251. elif selection == 2:
  252. new_node.url = getinput("Url:")
  253. self.items[2].getter = new_node.url
  254. self.items[2].setter = new_node.url
  255. elif selection == 3: # for notes
  256. # new_node.notes = getinput("Notes:")
  257. new_node.notes = getinput("Notes:")
  258. self.items[3].getter = new_node.notes
  259. self.items[3].setter = new_node.notes
  260. elif selection == 4:
  261. taglist = getinput("Tags:")
  262. tagstrings = taglist.split()
  263. tags = [Tag(tn) for tn in tagstrings]
  264. new_node.tags = tags
  265. self.items[4].setter = new_node.tags
  266. self.items[4].getter = new_node.tags
  267. except (ValueError, IndexError):
  268. if (option.upper() == 'X'):
  269. break
  270. print("Invalid selection")
  271. def getonechar(question, width=_defaultwidth): # pragma: no cover
  272. question = "%s " % (question)
  273. print (question.ljust(width),)
  274. try:
  275. sys.stdout.flush()
  276. fd = sys.stdin.fileno()
  277. # tty module exists only if we are on Posix
  278. try:
  279. tty_mode = tty.tcgetattr(fd)
  280. tty.setcbreak(fd)
  281. except NameError:
  282. pass
  283. try:
  284. ch = os.read(fd, 1)
  285. finally:
  286. try:
  287. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  288. except NameError:
  289. pass
  290. except AttributeError:
  291. ch = sys.stdin.readline()[0]
  292. print(ch)
  293. return ch
  294. class CliMenuItem(object): # pragma: no cover
  295. def __init__(self, name, editor, getter, setter):
  296. self.name = name
  297. self.editor = editor
  298. self.getter = getter
  299. self.setter = setter
  300. class CLICallback(Callback): # pragma: no cover
  301. def getinput(self, question):
  302. return raw_input(question)
  303. def getsecret(self, question):
  304. return getpass.getpass(question + ":")
  305. def getnewsecret(self, question):
  306. return getpass.getpass(question + ":")