cli.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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):
  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. menu = CMDLoop()
  103. print ("Editing node %d." % (i))
  104. menu.add(CliMenuItem("Username", self.get_username,
  105. node.username,
  106. node.username))
  107. menu.add(CliMenuItem("Password", self.get_password,
  108. node.password,
  109. node.password))
  110. menu.add(CliMenuItem("Url", self.get_url,
  111. node.url,
  112. node.url))
  113. menunotes = CliMenuItem("Notes", self.get_notes,
  114. node.notes,
  115. node.notes)
  116. menu.add(menunotes)
  117. menu.add(CliMenuItem("Tags", self.get_tags,
  118. node.tags,
  119. node.tags))
  120. menu.run(node)
  121. self._db.editnode(i, node)
  122. # when done with node erase it
  123. zerome(node._password)
  124. except Exception, e:
  125. self.error(e)
  126. def print_node(self, node):
  127. width = str(tools._defaultwidth)
  128. print ("Node %d." % (node._id))
  129. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  130. node.username))
  131. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  132. node.password))
  133. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  134. node.url))
  135. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  136. node.notes))
  137. print (tools.typeset("Tags: ", Fore.RED)),
  138. for t in node.tags:
  139. print (" %s " % t)
  140. print()
  141. def heardEnter():
  142. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  143. for s in i:
  144. if s == sys.stdin:
  145. sys.stdin.readline()
  146. return True
  147. return False
  148. def waituntil_enter(somepredicate, timeout, period=0.25):
  149. mustend = time.time() + timeout
  150. while time.time() < mustend:
  151. cond = somepredicate()
  152. if cond:
  153. break
  154. time.sleep(period)
  155. self.do_cls('')
  156. try:
  157. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  158. except ValueError:
  159. flushtimeout = 10
  160. if flushtimeout > 0:
  161. print ("Type Enter to flush screen (autoflash in "
  162. "%d sec.)" % flushtimeout)
  163. waituntil_enter(heardEnter, flushtimeout)
  164. def do_tags(self, arg):
  165. enc = CryptoEngine.get()
  166. if not enc.alive():
  167. enc._getcipher()
  168. print ("Tags: \n",)
  169. t = self._tags(enc)
  170. print ('\n'.join(t))
  171. def get_tags(self, default=None, reader=raw_input):
  172. """read tags from user"""
  173. defaultstr = ''
  174. if default:
  175. for t in default:
  176. defaultstr += "%s " % (t)
  177. else:
  178. # tags = self._db.currenttags()
  179. tags = self._db._filtertags
  180. for t in tags:
  181. defaultstr += "%s " % (t)
  182. # strings = []
  183. tags = self._db.listtags(True)
  184. #for t in tags:
  185. # strings.append(t.get_name())
  186. # strings.append(t)
  187. strings = [t for t in tags]
  188. def complete(text, state):
  189. count = 0
  190. for s in strings:
  191. if s.startswith(text):
  192. if count == state:
  193. return s
  194. else:
  195. count += 1
  196. taglist = tools.getinput("Tags: ", defaultstr, completer=complete,
  197. reader=reader)
  198. tagstrings = taglist.split()
  199. tags = [TagN(tn) for tn in tagstrings]
  200. return tags
  201. def do_list(self, args):
  202. if len(args.split()) > 0:
  203. self.do_clear('')
  204. self.do_filter(args)
  205. try:
  206. if sys.platform != 'win32':
  207. rows, cols = tools.gettermsize()
  208. else:
  209. rows, cols = 18, 80 # fix this !
  210. nodeids = self._db.listnodes()
  211. nodes = self._db.getnodes(nodeids)
  212. cols -= 8
  213. i = 0
  214. for n in nodes:
  215. tags = n.tags
  216. tags = filter(None, tags)
  217. tagstring = ''
  218. first = True
  219. for t in tags:
  220. if not first:
  221. tagstring += ", "
  222. else:
  223. first = False
  224. tagstring += t
  225. name = "%s@%s" % (n.username, n.url)
  226. name_len = cols * 2 / 3
  227. tagstring_len = cols / 3
  228. if len(name) > name_len:
  229. name = name[:name_len - 3] + "..."
  230. if len(tagstring) > tagstring_len:
  231. tagstring = tagstring[:tagstring_len - 3] + "..."
  232. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  233. formatted_entry = tools.typeset(fmt % (n._id,
  234. name, tagstring),
  235. Fore.YELLOW, False)
  236. print (formatted_entry)
  237. i += 1
  238. if i > rows - 2:
  239. i = 0
  240. c = tools.getonechar("Press <Space> for more,"
  241. " or 'Q' to cancel")
  242. if c.lower() == 'q':
  243. break
  244. except Exception, e:
  245. self.error(e)
  246. def do_filter(self, args):
  247. tagstrings = args.split()
  248. try:
  249. tags = [TagN(ts) for ts in tagstrings]
  250. self._db.filter(tags)
  251. tags = self._db.currenttags()
  252. print ("Current tags: ",)
  253. if len(tags) == 0:
  254. print ("None",)
  255. for t in tags:
  256. print ("%s " % (t.name),)
  257. print
  258. except Exception, e:
  259. self.error(e)
  260. def do_new(self, args):
  261. """
  262. can override default config settings the following way:
  263. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  264. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  265. Password (Blank to generate):
  266. """
  267. errmsg = ("could not parse config override, please input some"
  268. " kind of dictionary, e.g.: n {'leetify':False, "
  269. " numerics':True, 'special_chars':True}")
  270. try:
  271. username = self.get_username()
  272. if args:
  273. try:
  274. args = ast.literal_eval(args)
  275. except Exception:
  276. raise Exception(errmsg)
  277. if not isinstance(args, dict):
  278. raise Exception(errmsg)
  279. password = self.get_password(argsgiven=1, **args)
  280. else:
  281. numerics, leet, s_chars = get_pass_conf()
  282. password = self.get_password(argsgiven=0,
  283. numerics=numerics,
  284. symbols=leet,
  285. special_signs=s_chars)
  286. url = self.get_url()
  287. notes = self.get_notes()
  288. node = NewNode(username, password, url, notes)
  289. node.tags = self.get_tags()
  290. self._db.addnodes([node])
  291. print ("Password ID: %d" % (node._id))
  292. # when done with node erase it
  293. zerome(password)
  294. except Exception, e:
  295. self.error(e)
  296. def do_print(self, arg):
  297. for i in self.get_ids(arg):
  298. try:
  299. node = self._db.getnodes([i])
  300. self.print_node(node[0])
  301. # when done with node erase it
  302. zerome(node[0]._password)
  303. except Exception, e:
  304. self.error(e)
  305. def do_delete(self, arg):
  306. ids = self.get_ids(arg)
  307. try:
  308. nodes = self._db.getnodes(ids)
  309. for n in nodes:
  310. try:
  311. b = tools.getyesno(("Are you sure you want to"
  312. " delete '%s@%s'?"
  313. ) % (n.username, n.url), False)
  314. except NameError:
  315. pass
  316. if b is True:
  317. self._db.removenodes([n])
  318. print ("%s@%s deleted" % (n.username, n.url))
  319. except Exception, e:
  320. self.error(e)
  321. def get_password(self, argsgiven, numerics=False, leetify=False,
  322. symbols=False, special_signs=False,
  323. reader=getpass.getpass, length=None):
  324. return tools.getpassword("Password (Blank to generate): ",
  325. reader=reader, length=length, leetify=leetify)
  326. class Aliases(BaseCommands, PwmanCliOld):
  327. """
  328. Define all the alias you want here...
  329. """
  330. def do_cp(self, args):
  331. self.do_copy(args)
  332. def do_e(self, arg):
  333. self.do_edit(arg)
  334. def do_EOF(self, args):
  335. return self.do_exit(args)
  336. def do_l(self, args):
  337. self.do_list(args)
  338. def do_ls(self, args):
  339. self.do_list(args)
  340. def do_p(self, arg):
  341. self.do_print(arg)
  342. def do_rm(self, arg):
  343. self.do_delete(arg)
  344. def do_o(self, args):
  345. self.do_open(args)
  346. def do_h(self, arg):
  347. self.do_help(arg)
  348. def do_n(self, arg):
  349. self.do_new(arg)
  350. class PwmanCliNew(Aliases, BaseCommands):
  351. """
  352. Inherit from the BaseCommands and Aliases
  353. """
  354. def __init__(self, db, hasxsel, callback):
  355. """
  356. initialize CLI interface, set up the DB
  357. connecion, see if we have xsel ...
  358. """
  359. cmd.Cmd.__init__(self)
  360. self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version,
  361. pwman.website)
  362. self._historyfile = config.get_value("Readline", "history")
  363. self.hasxsel = hasxsel
  364. try:
  365. enc = CryptoEngine.get()
  366. enc._callback = callback()
  367. self._db = db
  368. self._db.open()
  369. except Exception, e: # pragma: no cover
  370. self.error(e)
  371. sys.exit(1)
  372. try:
  373. readline.read_history_file(self._historyfile)
  374. except IOError, e: # pragma: no cover
  375. pass
  376. self.prompt = "pwman> "