tools.py 11 KB

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