cli.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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) 2012 Oz Nahum <nahumoz@gmail.com>
  18. #============================================================================
  19. # Copyright (C) 2006 Ivan Kelly <ivan@ivankelly.net>
  20. #============================================================================
  21. # pylint: disable=I0011
  22. """
  23. Define the CLI interface for pwman3 and the helper functions
  24. """
  25. from __future__ import print_function
  26. import pwman
  27. from pwman.data.nodes import NewNode
  28. from pwman.data.tags import TagNew as TagN
  29. from pwman.util.crypto import CryptoEngine
  30. from pwman.util.crypto import zerome
  31. import pwman.util.config as config
  32. import sys
  33. import cmd
  34. import time
  35. import select as uselect
  36. import ast
  37. from pwman.ui import tools
  38. from pwman.ui.tools import CMDLoop
  39. from pwman.ui.tools import CliMenuItem
  40. from pwman.ui.ocli import PwmanCliOld
  41. from colorama import Fore
  42. import getpass
  43. try:
  44. import readline
  45. _readline_available = True
  46. except ImportError, e: # pragma: no cover
  47. _readline_available = False
  48. def get_pass_conf():
  49. numerics = config.get_value("Generator", "numerics").lower() == 'true'
  50. # TODO: allow custom leetifying through the config
  51. leetify = config.get_value("Generator", "leetify").lower() == 'true'
  52. special_chars = config.get_value("Generator", "special_chars"
  53. ).lower() == 'true'
  54. return numerics, leetify, special_chars
  55. class BaseCommands(PwmanCliOld):
  56. """
  57. Inherit from the old class, override
  58. all the methods related to tags, and
  59. newer Node format, so backward compatability is kept...
  60. Commands defined here, can have aliases definded in Aliases.
  61. You can define the aliases here too, but it makes
  62. the class code really long and unclear.
  63. """
  64. def do_copy(self, args):
  65. if self.hasxsel:
  66. ids = self.get_ids(args)
  67. if len(ids) > 1:
  68. print ("Can copy only 1 password at a time...")
  69. return None
  70. try:
  71. node = self._db.getnodes(ids)
  72. tools.text_to_clipboards(node[0].password)
  73. print ("copied password for {}@{} clipboard".format(
  74. node[0].username, node[0].url))
  75. print ("erasing in 10 sec...")
  76. time.sleep(10)
  77. tools.text_to_clipboards("")
  78. except Exception, e:
  79. self.error(e)
  80. else:
  81. print ("Can't copy to clipboard, no xsel found in the system!")
  82. def do_open(self, args):
  83. ids = self.get_ids(args)
  84. if not args:
  85. self.help_open()
  86. return
  87. if len(ids) > 1:
  88. print ("Can open only 1 link at a time ...")
  89. return None
  90. try:
  91. node = self._db.getnodes(ids)
  92. url = node[0].url
  93. tools.open_url(url)
  94. except Exception, e:
  95. self.error(e)
  96. def do_edit(self, arg, menu=None):
  97. ids = self.get_ids(arg)
  98. for i in ids:
  99. try:
  100. i = int(i)
  101. node = self._db.getnodes([i])[0]
  102. if not menu:
  103. menu = CMDLoop()
  104. print ("Editing node %d." % (i))
  105. menu.add(CliMenuItem("Username", self.get_username,
  106. node.username,
  107. node.username))
  108. menu.add(CliMenuItem("Password", self.get_password,
  109. node.password,
  110. node.password))
  111. menu.add(CliMenuItem("Url", self.get_url,
  112. node.url,
  113. node.url))
  114. menunotes = CliMenuItem("Notes", self.get_notes,
  115. node.notes,
  116. node.notes)
  117. menu.add(menunotes)
  118. menu.add(CliMenuItem("Tags", self.get_tags,
  119. node.tags,
  120. node.tags))
  121. menu.run(node)
  122. self._db.editnode(i, node)
  123. # when done with node erase it
  124. zerome(node._password)
  125. except Exception, e:
  126. self.error(e)
  127. def print_node(self, node):
  128. width = str(tools._defaultwidth)
  129. print ("Node %d." % (node._id))
  130. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  131. node.username))
  132. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  133. node.password))
  134. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  135. node.url))
  136. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  137. node.notes))
  138. print (tools.typeset("Tags: ", Fore.RED)),
  139. for t in node.tags:
  140. print (" %s " % t)
  141. print()
  142. def heardEnter():
  143. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  144. for s in i:
  145. if s == sys.stdin:
  146. sys.stdin.readline()
  147. return True
  148. return False
  149. def waituntil_enter(somepredicate, timeout, period=0.25):
  150. mustend = time.time() + timeout
  151. while time.time() < mustend:
  152. cond = somepredicate()
  153. if cond:
  154. break
  155. time.sleep(period)
  156. self.do_cls('')
  157. try:
  158. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  159. except ValueError:
  160. flushtimeout = 10
  161. if flushtimeout > 0:
  162. print ("Type Enter to flush screen (autoflash in "
  163. "%d sec.)" % flushtimeout)
  164. waituntil_enter(heardEnter, flushtimeout)
  165. def do_tags(self, arg):
  166. enc = CryptoEngine.get()
  167. if not enc.alive():
  168. enc._getcipher()
  169. print ("Tags: \n",)
  170. t = self._tags(enc)
  171. print ('\n'.join(t))
  172. def get_tags(self, default=None, reader=raw_input):
  173. """read tags from user"""
  174. defaultstr = ''
  175. if default:
  176. for t in default:
  177. defaultstr += "%s " % (t)
  178. else:
  179. # tags = self._db.currenttags()
  180. tags = self._db._filtertags
  181. for t in tags:
  182. defaultstr += "%s " % (t)
  183. # strings = []
  184. tags = self._db.listtags(True)
  185. # for t in tags:
  186. # strings.append(t.get_name())
  187. # strings.append(t)
  188. strings = [t for t in tags]
  189. def complete(text, state):
  190. count = 0
  191. for s in strings:
  192. if s.startswith(text):
  193. if count == state:
  194. return s
  195. else:
  196. count += 1
  197. taglist = tools.getinput("Tags: ", defaultstr, completer=complete,
  198. reader=reader)
  199. tagstrings = taglist.split()
  200. tags = [TagN(tn) for tn in tagstrings]
  201. return tags
  202. def do_list(self, args):
  203. if len(args.split()) > 0:
  204. self.do_clear('')
  205. self.do_filter(args)
  206. try:
  207. if sys.platform != 'win32':
  208. rows, cols = tools.gettermsize()
  209. else:
  210. rows, cols = 18, 80 # fix this !
  211. nodeids = self._db.listnodes()
  212. nodes = self._db.getnodes(nodeids)
  213. cols -= 8
  214. i = 0
  215. for n in nodes:
  216. tags = n.tags
  217. tags = filter(None, tags)
  218. tagstring = ''
  219. first = True
  220. for t in tags:
  221. if not first:
  222. tagstring += ", "
  223. else:
  224. first = False
  225. tagstring += t
  226. name = "%s@%s" % (n.username, n.url)
  227. name_len = cols * 2 / 3
  228. tagstring_len = cols / 3
  229. if len(name) > name_len:
  230. name = name[:name_len - 3] + "..."
  231. if len(tagstring) > tagstring_len:
  232. tagstring = tagstring[:tagstring_len - 3] + "..."
  233. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  234. formatted_entry = tools.typeset(fmt % (n._id,
  235. name, tagstring),
  236. Fore.YELLOW, False)
  237. print (formatted_entry)
  238. i += 1
  239. if i > rows - 2:
  240. i = 0
  241. c = tools.getonechar("Press <Space> for more,"
  242. " or 'Q' to cancel")
  243. if c.lower() == 'q':
  244. break
  245. except Exception, e:
  246. self.error(e)
  247. def do_filter(self, args):
  248. tagstrings = args.split()
  249. try:
  250. tags = [TagN(ts) for ts in tagstrings]
  251. self._db.filter(tags)
  252. tags = self._db.currenttags()
  253. print ("Current tags: ",)
  254. if len(tags) == 0:
  255. print ("None",)
  256. for t in tags:
  257. print ("%s " % (t.name),)
  258. print
  259. except Exception, e:
  260. self.error(e)
  261. def do_new(self, args):
  262. """
  263. can override default config settings the following way:
  264. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  265. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  266. Password (Blank to generate):
  267. """
  268. errmsg = ("could not parse config override, please input some"
  269. " kind of dictionary, e.g.: n {'leetify':False, "
  270. " numerics':True, 'special_chars':True}")
  271. try:
  272. username = self.get_username()
  273. if args:
  274. try:
  275. args = ast.literal_eval(args)
  276. except Exception:
  277. raise Exception(errmsg)
  278. if not isinstance(args, dict):
  279. raise Exception(errmsg)
  280. password = self.get_password(argsgiven=1, **args)
  281. else:
  282. numerics, leet, s_chars = get_pass_conf()
  283. password = self.get_password(argsgiven=0,
  284. numerics=numerics,
  285. symbols=leet,
  286. special_signs=s_chars)
  287. url = self.get_url()
  288. notes = self.get_notes()
  289. node = NewNode(username, password, url, notes)
  290. node.tags = self.get_tags()
  291. self._db.addnodes([node])
  292. print ("Password ID: %d" % (node._id))
  293. # when done with node erase it
  294. zerome(password)
  295. except Exception, e:
  296. self.error(e)
  297. def do_print(self, arg):
  298. for i in self.get_ids(arg):
  299. try:
  300. node = self._db.getnodes([i])
  301. self.print_node(node[0])
  302. # when done with node erase it
  303. zerome(node[0]._password)
  304. except Exception, e:
  305. self.error(e)
  306. def do_delete(self, arg):
  307. ids = self.get_ids(arg)
  308. try:
  309. nodes = self._db.getnodes(ids)
  310. for n in nodes:
  311. try:
  312. b = tools.getyesno(("Are you sure you want to"
  313. " delete '%s@%s'?"
  314. ) % (n.username, n.url), False)
  315. except NameError:
  316. pass
  317. if b is True:
  318. self._db.removenodes([n])
  319. print ("%s@%s deleted" % (n.username, n.url))
  320. except Exception, e:
  321. self.error(e)
  322. def get_password(self, argsgiven, numerics=False, leetify=False,
  323. symbols=False, special_signs=False,
  324. reader=getpass.getpass, length=None):
  325. return tools.getpassword("Password (Blank to generate): ",
  326. reader=reader, length=length, leetify=leetify)
  327. class Aliases(BaseCommands, PwmanCliOld):
  328. """
  329. Define all the alias you want here...
  330. """
  331. def do_cp(self, args):
  332. self.do_copy(args)
  333. def do_e(self, arg):
  334. self.do_edit(arg)
  335. def do_EOF(self, args):
  336. return self.do_exit(args)
  337. def do_l(self, args):
  338. self.do_list(args)
  339. def do_ls(self, args):
  340. self.do_list(args)
  341. def do_p(self, arg):
  342. self.do_print(arg)
  343. def do_rm(self, arg):
  344. self.do_delete(arg)
  345. def do_o(self, args):
  346. self.do_open(args)
  347. def do_h(self, arg):
  348. self.do_help(arg)
  349. def do_n(self, arg):
  350. self.do_new(arg)
  351. class PwmanCliNew(Aliases, BaseCommands):
  352. """
  353. Inherit from the BaseCommands and Aliases
  354. """
  355. def __init__(self, db, hasxsel, callback):
  356. """
  357. initialize CLI interface, set up the DB
  358. connecion, see if we have xsel ...
  359. """
  360. cmd.Cmd.__init__(self)
  361. self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version,
  362. pwman.website)
  363. self._historyfile = config.get_value("Readline", "history")
  364. self.hasxsel = hasxsel
  365. try:
  366. enc = CryptoEngine.get()
  367. enc._callback = callback()
  368. self._db = db
  369. self._db.open()
  370. except Exception, e: # pragma: no cover
  371. self.error(e)
  372. sys.exit(1)
  373. try:
  374. readline.read_history_file(self._historyfile)
  375. except IOError, e: # pragma: no cover
  376. pass
  377. self.prompt = "pwman> "