base.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. # pylint: disable=I0011
  20. """
  21. Define the base CLI interface for pwman3
  22. """
  23. from __future__ import print_function
  24. from pwman.util.crypto_engine import CryptoEngine, zerome
  25. import re
  26. import sys
  27. import os
  28. import time
  29. import select as uselect
  30. import ast
  31. from pwman.ui import tools
  32. from pwman.ui.tools import CliMenuItem
  33. from colorama import Fore
  34. from pwman.ui.tools import CMDLoop
  35. import getpass
  36. from pwman.data.tags import TagNew
  37. import csv
  38. if sys.version_info.major > 2:
  39. raw_input = input
  40. class HelpUI(object): # pragma: no cover
  41. """
  42. this class holds all the UI help functionality.
  43. in PwmanCliNew. The later inherits from this class
  44. and allows it to print help messages to the console.
  45. """
  46. def usage(self, string):
  47. print ("Usage: %s" % (string))
  48. def help_open(self):
  49. self.usage("open <ID>")
  50. print ("Launch default browser with 'xdg-open url',\n",
  51. "the url must contain http:// or https://.")
  52. def help_o(self):
  53. self.help_open()
  54. def help_copy(self):
  55. self.usage("copy <ID>")
  56. print ("Copy password to X clipboard (xsel required)")
  57. def help_cp(self):
  58. self.help_copy()
  59. def help_cls(self):
  60. self.usage("cls")
  61. print ("Clear the Screen from information.")
  62. def help_list(self):
  63. self.usage("list <tag> ...")
  64. print ("List nodes that match current or specified filter.",
  65. " l is an alias.")
  66. def help_EOF(self):
  67. self.help_exit()
  68. def help_delete(self):
  69. self.usage("delete <ID|tag> ...")
  70. print ("Deletes nodes. rm is an alias.")
  71. self._mult_id_help()
  72. def help_h(self):
  73. self.help_help()
  74. def help_help(self):
  75. self.usage("help [topic]")
  76. print ("Prints a help message for a command.")
  77. def help_e(self):
  78. self.help_edit()
  79. def help_n(self):
  80. self.help_new()
  81. def help_p(self):
  82. self.help_print()
  83. def help_l(self):
  84. self.help_list()
  85. def help_edit(self):
  86. self.usage("edit <ID|tag> ... ")
  87. print ("Edits a nodes.")
  88. def help_import(self):
  89. self.usage("import [filename] ...")
  90. print ("Not implemented...")
  91. def help_export(self):
  92. self.usage("export [{'filename': 'foo.csv', 'delimiter':'|'}] ")
  93. print("All nodes under the current filter are exported.")
  94. def help_new(self):
  95. self.usage("new")
  96. print ("Creates a new node.,",
  97. "You can override default config settings the following way:\n",
  98. "pwman> n {'leetify':False, 'numerics':True}")
  99. def help_rm(self):
  100. self.help_delete()
  101. def help_print(self):
  102. self.usage("print <ID|tag> ...")
  103. print ("Displays a node. ")
  104. self._mult_id_help()
  105. def _mult_id_help(self):
  106. print("Multiple ids and nodes can be specified, separated by a space.",
  107. " A range of ids can be specified in the format n-N. e.g. ",
  108. " '10-20' would specify all nodes having ids from 10 to 20 ",
  109. " inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar'",
  110. " would yield to all nodes with tag 'foo', node 2 and all ",
  111. " nodes with tag 'bar'.")
  112. def help_exit(self):
  113. self.usage("exit")
  114. print("Exits the application.")
  115. def help_passwd(self):
  116. self.usage("passwd")
  117. print("Changes the password on the database. ")
  118. def help_forget(self):
  119. self.usage("forget")
  120. print("Forgets the database password. Your password will need to ",
  121. "be reentered before accessing the database again.")
  122. def help_clear(self):
  123. self.usage("clear")
  124. print("Clears the filter criteria. ")
  125. def help_filter(self):
  126. self.usage("filter <tag> ...")
  127. print("Filters nodes on tag. Arguments can be zero or more tags. ",
  128. "Displays current tags if called without arguments.")
  129. def help_tags(self):
  130. self.usage("tags")
  131. print("Displays all tags in used in the database.")
  132. class BaseCommands(HelpUI):
  133. """
  134. Inherit from the old class, override
  135. all the methods related to tags, and
  136. newer Node format, so backward compatability is kept...
  137. Commands defined here, can have aliases definded in Aliases.
  138. You can define the aliases here too, but it makes
  139. the class code really long and unclear.
  140. """
  141. def error(self, exception):
  142. if (isinstance(exception, KeyboardInterrupt)):
  143. print('')
  144. else:
  145. print("Error: {0} ".format(exception))
  146. def do_copy(self, args):
  147. if self.hasxsel:
  148. ids = self.get_ids(args)
  149. if len(ids) > 1:
  150. print ("Can copy only 1 password at a time...")
  151. return None
  152. try:
  153. node = self._db.getnodes(ids)
  154. tools.text_to_clipboards(node[0].password)
  155. print("copied password for {}@{} clipboard".format(
  156. node[0].username, node[0].url))
  157. print("erasing in 10 sec...")
  158. time.sleep(10)
  159. tools.text_to_clipboards("")
  160. except Exception as e:
  161. self.error(e)
  162. else:
  163. print ("Can't copy to clipboard, no xsel found in the system!")
  164. def do_exit(self, args):
  165. """exit the ui"""
  166. self._db.close()
  167. return True
  168. def do_export(self, args):
  169. try:
  170. args = ast.literal_eval(args)
  171. except Exception:
  172. args = {}
  173. filename = args.get('filename', 'pwman-export.csv')
  174. delim = args.get('delimiter', ';')
  175. nodeids = self._db.listnodes()
  176. nodes = self._db.getnodes(nodeids)
  177. with open(filename, 'w') as csvfile:
  178. writer = csv.writer(csvfile, delimiter=delim)
  179. writer.writerow(['Username', 'URL', 'Password', 'Notes',
  180. 'Tags'])
  181. for n in nodes:
  182. tags = n.tags
  183. tags = filter(None, tags)
  184. tags = ','.join(t.strip() for t in tags)
  185. writer.writerow([n.username, n.url, n.password, n.notes,
  186. tags])
  187. print("Successfuly exported database to {}".format(
  188. os.path.join(os.getcwd(), filename)))
  189. def do_forget(self, args):
  190. try:
  191. enc = CryptoEngine.get()
  192. enc.forget()
  193. except Exception as e:
  194. self.error(e)
  195. def get_username(self, default="", reader=raw_input):
  196. return tools.getinput("Username: ", default, reader)
  197. def get_url(self, default="", reader=raw_input):
  198. return tools.getinput("Url: ", default, reader)
  199. def get_notes(self, default="", reader=raw_input):
  200. return tools.getinput("Notes: ", default, reader)
  201. def do_open(self, args):
  202. ids = self.get_ids(args)
  203. if not args:
  204. self.help_open()
  205. return
  206. if len(ids) > 1:
  207. print ("Can open only 1 link at a time ...")
  208. return None
  209. try:
  210. node = self._db.getnodes(ids)
  211. url = node[0].url
  212. tools.open_url(url)
  213. except Exception as e:
  214. self.error(e)
  215. def do_clear(self, args):
  216. try:
  217. self._db.clearfilter()
  218. except Exception as e:
  219. self.error(e)
  220. def do_cls(self, args):
  221. os.system('clear')
  222. def do_edit(self, arg, menu=None):
  223. ids = self.get_ids(arg)
  224. for i in ids:
  225. try:
  226. i = int(i)
  227. node = self._db.getnodes([i])[0]
  228. if not menu:
  229. menu = CMDLoop()
  230. print ("Editing node %d." % (i))
  231. menu.add(CliMenuItem("Username", self.get_username,
  232. node.username,
  233. node.username))
  234. menu.add(CliMenuItem("Password", self.get_password,
  235. node.password,
  236. node.password))
  237. menu.add(CliMenuItem("Url", self.get_url,
  238. node.url,
  239. node.url))
  240. menunotes = CliMenuItem("Notes", self.get_notes,
  241. node.notes,
  242. node.notes)
  243. menu.add(menunotes)
  244. menu.add(CliMenuItem("Tags", self.get_tags,
  245. node.tags,
  246. node.tags))
  247. menu.run(node)
  248. self._db.editnode(i, node)
  249. # when done with node erase it
  250. zerome(node._password)
  251. except Exception as e:
  252. self.error(e)
  253. def print_node(self, node):
  254. width = str(tools._defaultwidth)
  255. print ("Node %d." % (node._id))
  256. print (("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  257. node.username))
  258. print (("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  259. node.password))
  260. print (("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  261. node.url))
  262. print (("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  263. node.notes))
  264. print (tools.typeset("Tags: ", Fore.RED)),
  265. for t in node.tags:
  266. print (" %s " % t)
  267. print()
  268. def heardEnter():
  269. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  270. for s in i:
  271. if s == sys.stdin:
  272. sys.stdin.readline()
  273. return True
  274. return False
  275. def waituntil_enter(somepredicate, timeout, period=0.25):
  276. mustend = time.time() + timeout
  277. while time.time() < mustend:
  278. cond = somepredicate()
  279. if cond:
  280. break
  281. time.sleep(period)
  282. self.do_cls('')
  283. try:
  284. flushtimeout = int(self.config.get_value("Global", "cls_timeout"))
  285. except ValueError:
  286. flushtimeout = 10
  287. if flushtimeout > 0:
  288. print ("Type Enter to flush screen (autoflash in "
  289. "%d sec.)" % flushtimeout)
  290. waituntil_enter(heardEnter, flushtimeout)
  291. def do_passwd(self, args):
  292. raise Exception("Not Implemented ...")
  293. #try:
  294. # key = self._db.changepassword()
  295. # self._db.savekey(key)
  296. #except Exception as e:
  297. # self.error(e)
  298. def get_tags(self, default=None, reader=raw_input):
  299. """read tags from user"""
  300. defaultstr = ''
  301. if default:
  302. for t in default:
  303. defaultstr += "%s " % (t)
  304. else:
  305. # tags = self._db.currenttags()
  306. tags = self._db._filtertags
  307. for t in tags:
  308. defaultstr += "%s " % (t)
  309. # strings = []
  310. tags = self._db.listtags(True)
  311. # for t in tags:
  312. # strings.append(t.get_name())
  313. # strings.append(t)
  314. strings = [t for t in tags]
  315. def complete(text, state):
  316. count = 0
  317. for s in strings:
  318. if s.startswith(text):
  319. if count == state:
  320. return s
  321. else:
  322. count += 1
  323. taglist = tools.getinput("Tags: ", defaultstr, completer=complete,
  324. reader=reader)
  325. tagstrings = taglist.split()
  326. tags = [TagNew(tn) for tn in tagstrings]
  327. return tags
  328. def do_filter(self, args):
  329. tagstrings = args.split()
  330. try:
  331. tags = [TagNew(ts) for ts in tagstrings]
  332. self._db.filter(tags)
  333. tags = self._db.currenttags()
  334. print ("Current tags: ",)
  335. if len(tags) == 0:
  336. print ("None",)
  337. for t in tags:
  338. print ("%s " % t.name.decode())
  339. print
  340. except Exception as e:
  341. self.error(e)
  342. def do_print(self, arg):
  343. for i in self.get_ids(arg):
  344. try:
  345. node = self._db.getnodes([i])
  346. self.print_node(node[0])
  347. # when done with node erase it
  348. zerome(node[0]._password)
  349. except Exception as e:
  350. self.error(e)
  351. def do_delete(self, arg):
  352. ids = self.get_ids(arg)
  353. try:
  354. nodes = self._db.getnodes(ids)
  355. for n in nodes:
  356. ans = ''
  357. while True:
  358. ans = tools.getinput(("Are you sure you want to"
  359. " delete '%s@%s' ([y/N])?"
  360. ) % (n.username, n.url)
  361. ).lower().strip('\n')
  362. if ans == '' or ans == 'y' or ans == 'n':
  363. break
  364. if ans == 'y':
  365. self._db.removenodes([n])
  366. print ("%s@%s deleted" % (n.username, n.url))
  367. except Exception as e:
  368. self.error(e)
  369. def get_ids(self, args):
  370. """
  371. Command can get a single ID or
  372. a range of IDs, with begin-end.
  373. e.g. 1-3 , will get 1 to 3.
  374. """
  375. ids = []
  376. rex = re.compile("^(?P<begin>\d+)(?:-(?P<end>\d+))?$")
  377. rex = rex.match(args)
  378. if hasattr(rex, 'groupdict'):
  379. try:
  380. begin = int(rex.groupdict()['begin'])
  381. end = int(rex.groupdict()['end'])
  382. if not end > begin:
  383. print("Start node should be smaller than end node")
  384. return ids
  385. ids += range(begin, end+1)
  386. return ids
  387. except TypeError:
  388. ids.append(int(begin))
  389. else:
  390. print("Could not understand your input...")
  391. return ids
  392. def get_password(self, argsgiven, numerics=False, leetify=False,
  393. symbols=False, special_signs=False,
  394. reader=getpass.getpass, length=None):
  395. return tools.getpassword("Password (Blank to generate): ",
  396. reader=reader, length=length, leetify=leetify,
  397. special_signs=special_signs, symbols=symbols,
  398. numerics=numerics, config=self.config)
  399. class Aliases(BaseCommands): # pragma: no cover
  400. """
  401. Define all the alias you want here...
  402. """
  403. def do_cp(self, args):
  404. self.do_copy(args)
  405. def do_e(self, arg):
  406. self.do_edit(arg)
  407. def do_EOF(self, args):
  408. return self.do_exit(args)
  409. def do_l(self, args):
  410. self.do_list(args)
  411. def do_ls(self, args):
  412. self.do_list(args)
  413. def do_p(self, arg):
  414. self.do_print(arg)
  415. def do_rm(self, arg):
  416. self.do_delete(arg)
  417. def do_o(self, args):
  418. self.do_open(args)
  419. def do_h(self, arg):
  420. self.do_help(arg)
  421. def do_n(self, arg):
  422. self.do_new(arg)