cli.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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. import pwman
  26. import pwman.exchange.importer as importer
  27. import pwman.exchange.exporter as exporter
  28. import pwman.util.generator as generator
  29. from pwman.data.nodes import Node
  30. from pwman.data.nodes import NewNode
  31. from pwman.data.tags import Tag
  32. from pwman.util.crypto import CryptoEngine
  33. from pwman.util.crypto import zerome
  34. import pwman.util.config as config
  35. import re
  36. import sys
  37. import os
  38. import cmd
  39. import time
  40. import select as uselect
  41. import ast
  42. from pwman.ui import tools
  43. from pwman.ui.tools import CliMenu
  44. from pwman.ui.tools import CliMenuItem
  45. from pwman.ui.tools import CLICallback
  46. from colorama import Fore
  47. try:
  48. import readline
  49. _readline_available = True
  50. except ImportError, e:
  51. _readline_available = False
  52. # pylint: disable=R0904
  53. class PwmanCli(cmd.Cmd):
  54. """
  55. UI class for MacOSX
  56. """
  57. def error(self, exception):
  58. if (isinstance(exception, KeyboardInterrupt)):
  59. print
  60. else:
  61. # traceback.print_exc()
  62. print "Error: %s " % (exception)
  63. def do_EOF(self, args):
  64. return self.do_exit(args)
  65. def do_exit(self, args):
  66. """exit the ui"""
  67. print
  68. # try:
  69. # print "goodbye"
  70. self._db.close()
  71. # except DatabaseException, e:
  72. # self.error(e)
  73. return True
  74. def get_ids(self, args):
  75. ids = []
  76. rex = re.compile(r"^(\d+)-(\d+)$")
  77. idstrs = args.split()
  78. for i in idstrs:
  79. m = rex.match(i)
  80. if m is None:
  81. try:
  82. ids.append(int(i))
  83. except ValueError:
  84. self._db.clearfilter()
  85. self._db.filter([Tag(i)])
  86. ids += self._db.listnodes()
  87. else:
  88. ids += range(int(m.group(1)),
  89. int(m.group(2))+1)
  90. return ids
  91. def get_filesystem_path(self, default=""):
  92. return tools.getinput("Enter filename: ", default)
  93. def get_username(self, default=""):
  94. return tools.getinput("Username: ", default)
  95. def get_password(self, argsgiven, numerics=False, leetify=False,
  96. symbols=False, special_signs=False):
  97. """
  98. in the config file:
  99. numerics -> numerics
  100. leetify -> symbols
  101. special_chars -> special_signs
  102. """
  103. if argsgiven == 1:
  104. length = tools.getinput("Password length (default 7): ", "7")
  105. length = len(length)
  106. password, dumpme = generator.generate_password(length, length,
  107. True, leetify,
  108. numerics,
  109. special_signs)
  110. print "New password: %s" % (password)
  111. return password
  112. # no args given
  113. password = tools.getpassword("Password (Blank to generate): ",
  114. tools._defaultwidth, False)
  115. if len(password) == 0:
  116. length = tools.getinput("Password length (default 7): ", "7")
  117. if length:
  118. length = int(length)
  119. else:
  120. length = 7
  121. password, dumpme = generator.generate_password(length, length,
  122. True, leetify,
  123. numerics,
  124. special_signs)
  125. print "New password: %s" % (password)
  126. return password
  127. def get_url(self, default=""):
  128. return tools.getinput("Url: ", default)
  129. def get_notes(self, default=""):
  130. return tools.getinput("Notes: ", default)
  131. def get_tags(self, default=None):
  132. defaultstr = ''
  133. if default:
  134. for t in default:
  135. defaultstr += "%s " % (t.get_name())
  136. else:
  137. tags = self._db.currenttags()
  138. for t in tags:
  139. defaultstr += "%s " % (t.get_name())
  140. strings = []
  141. tags = self._db.listtags(True)
  142. for t in tags:
  143. strings.append(t.get_name())
  144. def complete(text, state):
  145. count = 0
  146. for s in strings:
  147. if s.startswith(text):
  148. if count == state:
  149. return s
  150. else:
  151. count += 1
  152. taglist = tools.getinput("Tags: ", defaultstr, complete)
  153. tagstrings = taglist.split()
  154. tags = []
  155. for tn in tagstrings:
  156. tags.append(Tag(tn))
  157. return tags
  158. def print_node(self, node):
  159. width = str(tools._defaultwidth)
  160. print "Node %d." % (node._id)
  161. print ("%"+width+"s %s") % (tools.typeset("Username:", Fore.RED),
  162. node.get_username())
  163. print ("%"+width+"s %s") % (tools.typeset("Password:", Fore.RED),
  164. node.get_password())
  165. print ("%"+width+"s %s") % (tools.typeset("Url:", Fore.RED),
  166. node.get_url())
  167. print ("%"+width+"s %s") % (tools.typeset("Notes:", Fore.RED),
  168. node.get_notes())
  169. print tools.typeset("Tags: ", Fore.RED),
  170. for t in node.get_tags():
  171. print " %s \n" % t.get_name(),
  172. def heardEnter():
  173. inpt, out, err = uselect.select([sys.stdin], [], [], 0.0001)
  174. for stream in inpt:
  175. if stream == sys.stdin:
  176. sys.stdin.readline()
  177. return True
  178. return False
  179. def waituntil_enter(somepredicate, timeout, period=0.25):
  180. mustend = time.time() + timeout
  181. while time.time() < mustend:
  182. cond = somepredicate()
  183. if cond:
  184. break
  185. time.sleep(period)
  186. self.do_cls('')
  187. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  188. if flushtimeout > 0:
  189. print "Type Enter to flush screen (autoflash in "\
  190. + "%d sec.)" % flushtimeout
  191. waituntil_enter(heardEnter, flushtimeout)
  192. def do_tags(self, arg):
  193. tags = self._db.listtags()
  194. if len(tags) > 0:
  195. tags[0].get_name() # hack to get password request before output
  196. print "Tags: ",
  197. if len(tags) == 0:
  198. print "None",
  199. for t in tags:
  200. print "%s " % (t.get_name()),
  201. print
  202. def complete_filter(self, text, line, begidx, endidx):
  203. strings = []
  204. enc = CryptoEngine.get()
  205. if not enc.alive():
  206. return strings
  207. tags = self._db.listtags()
  208. for t in tags:
  209. name = t.get_name()
  210. if name.startswith(text):
  211. strings.append(t.get_name())
  212. return strings
  213. def do_filter(self, args):
  214. tagstrings = args.split()
  215. try:
  216. tags = []
  217. for ts in tagstrings:
  218. tags.append(Tag(ts))
  219. self._db.filter(tags)
  220. tags = self._db.currenttags()
  221. print "Current tags: ",
  222. if len(tags) == 0:
  223. print "None",
  224. for t in tags:
  225. print "%s " % (t.get_name()),
  226. print
  227. except Exception, e:
  228. self.error(e)
  229. def do_clear(self, args):
  230. try:
  231. self._db.clearfilter()
  232. except Exception, e:
  233. self.error(e)
  234. def do_e(self, arg):
  235. self.do_edit(arg)
  236. def do_edit(self, arg):
  237. ids = self.get_ids(arg)
  238. for i in ids:
  239. try:
  240. i = int(i)
  241. node = self._db.getnodes([i])[0]
  242. menu = CliMenu()
  243. print "Editing node %d." % (i)
  244. menu.add(CliMenuItem("Username", self.get_username,
  245. node.get_username,
  246. node.set_username))
  247. menu.add(CliMenuItem("Password", self.get_password,
  248. node.get_password,
  249. node.set_password))
  250. menu.add(CliMenuItem("Url", self.get_url,
  251. node.get_url,
  252. node.set_url))
  253. menu.add(CliMenuItem("Notes", self.get_notes,
  254. node.get_notes,
  255. node.set_notes))
  256. menu.add(CliMenuItem("Tags", self.get_tags,
  257. node.get_tags,
  258. node.set_tags))
  259. menu.run()
  260. self._db.editnode(i, node)
  261. # when done with node erase it
  262. zerome(node._password)
  263. except Exception, e:
  264. self.error(e)
  265. def do_import(self, arg):
  266. try:
  267. args = arg.split()
  268. if len(args) == 0:
  269. types = importer.Importer.types()
  270. intype = tools.select("Select filetype:", types)
  271. imp = importer.Importer.get(intype)
  272. infile = tools.getinput("Select file:")
  273. imp.import_data(self._db, infile)
  274. else:
  275. for i in args:
  276. types = importer.Importer.types()
  277. intype = tools.select("Select filetype:", types)
  278. imp = importer.Importer.get(intype)
  279. imp.import_data(self._db, i)
  280. except Exception, e:
  281. self.error(e)
  282. def do_export(self, arg):
  283. try:
  284. nodes = self.get_ids(arg)
  285. types = exporter.Exporter.types()
  286. ftype = tools.select("Select filetype:", types)
  287. exp = exporter.Exporter.get(ftype)
  288. out_file = tools.getinput("Select output file:")
  289. if len(nodes) > 0:
  290. b = tools.getyesno("Export nodes %s?" % (nodes), True)
  291. if not b:
  292. return
  293. exp.export_data(self._db, out_file, nodes)
  294. else:
  295. nodes = self._db.listnodes()
  296. tags = self._db.currenttags()
  297. tagstr = ""
  298. if len(tags) > 0:
  299. tagstr = " for "
  300. for t in tags:
  301. tagstr += "'%s' " % (t.get_name())
  302. b = tools.getyesno("Export all nodes%s?" % (tagstr), True)
  303. if not b:
  304. return
  305. exp.export_data(self._db, out_file, nodes)
  306. print "Data exported."
  307. except Exception, e:
  308. self.error(e)
  309. def do_h(self, arg):
  310. self.do_help(arg)
  311. def do_n(self, arg):
  312. self.do_new(arg)
  313. def do_new(self, args):
  314. """
  315. can override default config settings the following way:
  316. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  317. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  318. Password (Blank to generate):
  319. """
  320. errmsg = """could not parse config override, please input some"""\
  321. + """ kind of dictionary, e.g.: n {'leetify':False, """\
  322. + """'numerics':True, 'special_chars':True}"""
  323. try:
  324. username = self.get_username()
  325. if args:
  326. try:
  327. args = ast.literal_eval(args)
  328. except Exception:
  329. raise Exception(errmsg)
  330. if not isinstance(args, dict):
  331. raise Exception(errmsg)
  332. password = self.get_password(1, **args)
  333. else:
  334. numerics = config.get_value("Generator",
  335. "numerics").lower() == 'true'
  336. # TODO: allow custom leetifying through the config
  337. leetify = config.get_value("Generator",
  338. "leetify").lower() == 'true'
  339. special_chars = config.get_value("Generator",
  340. "special_chars").lower() == \
  341. 'true'
  342. password = self.get_password(0,
  343. numerics=numerics,
  344. symbols=leetify,
  345. special_signs=special_chars)
  346. url = self.get_url()
  347. notes = self.get_notes()
  348. node = Node(username, password, url, notes)
  349. tags = self.get_tags()
  350. node.set_tags(tags)
  351. self._db.addnodes([node])
  352. print "Password ID: %d" % (node.get_id())
  353. except Exception, e:
  354. self.error(e)
  355. def do_p(self, arg):
  356. self.do_print(arg)
  357. def do_print(self, arg):
  358. for i in self.get_ids(arg):
  359. try:
  360. node = self._db.getnodes([i])
  361. self.print_node(node[0])
  362. except Exception, e:
  363. self.error(e)
  364. def do_rm(self, arg):
  365. self.do_delete(arg)
  366. def do_delete(self, arg):
  367. ids = self.get_ids(arg)
  368. try:
  369. nodes = self._db.getnodes(ids)
  370. for n in nodes:
  371. b = tools.getyesno("Are you sure you want to delete '%s@%s'?"
  372. % (n.get_username(), n.get_url()), False)
  373. if b is True:
  374. self._db.removenodes([n])
  375. print "%s@%s deleted" % (n.get_username(), n.get_url())
  376. except Exception, e:
  377. self.error(e)
  378. def do_l(self, args):
  379. self.do_list(args)
  380. def do_ls(self, args):
  381. self.do_list(args)
  382. def do_list(self, args):
  383. if len(args.split()) > 0:
  384. self.do_clear('')
  385. self.do_filter(args)
  386. try:
  387. if sys.platform != 'win32':
  388. rows, cols = tools.gettermsize()
  389. else:
  390. rows, cols = 18, 80
  391. nodeids = self._db.listnodes()
  392. nodes = self._db.getnodes(nodeids)
  393. cols -= 8
  394. i = 0
  395. for n in nodes:
  396. tags = n.get_tags()
  397. tagstring = ''
  398. first = True
  399. for t in tags:
  400. if not first:
  401. tagstring += ", "
  402. else:
  403. first = False
  404. tagstring += t.get_name()
  405. name = "%s@%s" % (n.get_username(), n.get_url())
  406. name_len = cols * 2 / 3
  407. tagstring_len = cols / 3
  408. if len(name) > name_len:
  409. name = name[:name_len-3] + "..."
  410. if len(tagstring) > tagstring_len:
  411. tagstring = tagstring[:tagstring_len-3] + "..."
  412. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  413. print tools.typeset(fmt % (n.get_id(), name, tagstring),
  414. Fore.YELLOW, False)
  415. i += 1
  416. if i > rows-2:
  417. i = 0
  418. c = tools.getonechar("Press <Space> for more, "
  419. "or 'Q' to cancel")
  420. if c == 'q':
  421. break
  422. except Exception, e:
  423. self.error(e)
  424. def do_forget(self, args):
  425. try:
  426. enc = CryptoEngine.get()
  427. enc.forget()
  428. except Exception, e:
  429. self.error(e)
  430. def do_passwd(self, args):
  431. try:
  432. self._db.changepassword()
  433. except Exception, e:
  434. self.error(e)
  435. def do_set(self, args):
  436. argstrs = args.split()
  437. try:
  438. if len(argstrs) == 0:
  439. conf = config.get_conf()
  440. for s in conf.keys():
  441. for n in conf[s].keys():
  442. print "%s.%s = %s" % (s, n, conf[s][n])
  443. elif len(argstrs) == 1:
  444. r = re.compile("(.+)\.(.+)")
  445. m = r.match(argstrs[0])
  446. if m is None or len(m.groups()) != 2:
  447. print "Invalid option format"
  448. self.help_set()
  449. return
  450. print "%s.%s = %s" % (m.group(1), m.group(2),
  451. config.get_value(m.group(1), m.group(2)))
  452. elif len(argstrs) == 2:
  453. r = re.compile("(.+)\.(.+)")
  454. m = r.match(argstrs[0])
  455. if m is None or len(m.groups()) != 2:
  456. print "Invalid option format"
  457. self.help_set()
  458. return
  459. config.set_value(m.group(1), m.group(2), argstrs[1])
  460. else:
  461. self.help_set()
  462. except Exception, e:
  463. self.error(e)
  464. def do_save(self, args):
  465. argstrs = args.split()
  466. try:
  467. if len(argstrs) > 0:
  468. config.save(argstrs[0])
  469. else:
  470. config.save()
  471. print "Config saved."
  472. except Exception, e:
  473. self.error(e)
  474. def do_cls(self, args):
  475. os.system('clear')
  476. def do_copy(self, args):
  477. if self.hasxsel:
  478. ids = self.get_ids(args)
  479. if len(ids) > 1:
  480. print "Can copy only 1 password at a time..."
  481. return None
  482. try:
  483. node = self._db.getnodes(ids)
  484. tools.text_to_clipboards(node[0].get_password())
  485. print "copied password for {}@{} clipboard".format(
  486. node[0].get_username(), node[0].get_url())
  487. print "erasing in 10 sec..."
  488. time.sleep(10)
  489. tools.text_to_clipboards("")
  490. except Exception, e:
  491. self.error(e)
  492. else:
  493. print "Can't copy to clipboard, no xsel found in the system!"
  494. def do_cp(self, args):
  495. self.do_copy(args)
  496. def do_open(self, args):
  497. ids = self.get_ids(args)
  498. if not args:
  499. self.help_open()
  500. return
  501. if len(ids) > 1:
  502. print "Can open only 1 link at a time ..."
  503. return None
  504. try:
  505. node = self._db.getnodes(ids)
  506. url = node[0].get_url()
  507. tools.open_url(url)
  508. except Exception, e:
  509. self.error(e)
  510. def do_o(self, args):
  511. self.do_open(args)
  512. ##
  513. ## Help functions
  514. ##
  515. def usage(self, string):
  516. print "Usage: %s" % (string)
  517. def help_open(self):
  518. self.usage("open <ID>")
  519. print "Launch default browser with 'xdg-open url',\n" \
  520. + "the url must contain http:// or https://."
  521. def help_o(self):
  522. self.help_open()
  523. def help_copy(self):
  524. self.usage("copy <ID>")
  525. print "Copy password to X clipboard (xsel required)"
  526. def help_cp(self):
  527. self.help_copy()
  528. def help_cls(self):
  529. self.usage("cls")
  530. print "Clear the Screen from information."
  531. def help_list(self):
  532. self.usage("list <tag> ...")
  533. print "List nodes that match current or specified filter." \
  534. + " l is an alias."
  535. def help_EOF(self):
  536. self.help_exit()
  537. def help_delete(self):
  538. self.usage("delete <ID|tag> ...")
  539. print "Deletes nodes. rm is an alias."
  540. self._mult_id_help()
  541. def help_h(self):
  542. self.help_help()
  543. def help_help(self):
  544. self.usage("help [topic]")
  545. print "Prints a help message for a command."
  546. def help_e(self):
  547. self.help_edit()
  548. def help_n(self):
  549. self.help_new()
  550. def help_p(self):
  551. self.help_print()
  552. def help_l(self):
  553. self.help_list()
  554. def help_edit(self):
  555. self.usage("edit <ID|tag> ... ")
  556. print "Edits a nodes."
  557. self._mult_id_help()
  558. def help_import(self):
  559. self.usage("import [filename] ...")
  560. print "Imports a nodes from a file."
  561. def help_export(self):
  562. self.usage("export <ID|tag> ... ")
  563. print "Exports a list of ids to an external format. If no IDs or" \
  564. + " tags are specified, then all nodes under the current" \
  565. + " filter are exported."
  566. self._mult_id_help()
  567. def help_new(self):
  568. self.usage("new")
  569. print """Creates a new node.,
  570. You can override default config settings the following way:
  571. pwman> n {'leetify':False, 'numerics':True}"""
  572. def help_rm(self):
  573. self.help_delete()
  574. def help_print(self):
  575. self.usage("print <ID|tag> ...")
  576. print "Displays a node. ",
  577. self._mult_id_help()
  578. def _mult_id_help(self):
  579. print "Multiple ids and nodes can be specified, separated by a space."\
  580. + "A range of ids can be specified in the format n-N. e.g. " \
  581. + "'10-20' would specify all nodes having ids from 10 to 20 " \
  582. + "inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar'" \
  583. + " would yield to all nodes with tag 'foo', node 2 and all "\
  584. + "nodes with tag 'bar'."
  585. def help_exit(self):
  586. self.usage("exit")
  587. print "Exits the application."
  588. def help_save(self):
  589. self.usage("save [filename]")
  590. print "Saves the current configuration to [filename]. If no filename "\
  591. + "is given, the configuration is saved to the file from which "\
  592. + "the initial configuration was loaded."
  593. def help_set(self):
  594. self.usage("set [configoption] [value]")
  595. print "Sets a configuration option. If no value is specified, the "\
  596. + "current value for [configoption] is output. If neither "\
  597. + "[configoption] nor [value] are specified, the whole current "\
  598. + "configuration is output. [configoption] must be of the "\
  599. + "format <section>.<option>"
  600. def help_passwd(self):
  601. self.usage("passwd")
  602. print "Changes the password on the database. "
  603. def help_forget(self):
  604. self.usage("forget")
  605. print "Forgets the database password. Your password will need to " \
  606. + "be reentered before accessing the database again."
  607. def help_clear(self):
  608. self.usage("clear")
  609. print "Clears the filter criteria. "
  610. def help_filter(self):
  611. self.usage("filter <tag> ...")
  612. print "Filters nodes on tag. Arguments can be zero or more tags. " \
  613. + "Displays current tags if called without arguments."
  614. def help_tags(self):
  615. self.usage("tags")
  616. print "Displays all tags in used in the database."
  617. def postloop(self):
  618. try:
  619. readline.write_history_file(self._historyfile)
  620. except Exception:
  621. pass
  622. def __init__(self, db, hasxsel):
  623. """
  624. initialize CLI interface, set up the DB
  625. connecion, see if we have xsel ...
  626. """
  627. _dbwarning = "\n*** WARNNING: You are using the old database format" \
  628. + " which is unsecure." \
  629. + " It's highly recommended to switch to the new database " \
  630. + "format." \
  631. + " Check the help (pwman3 -h) or look at the manpage which" \
  632. + " explains how to proceed. ***"
  633. cmd.Cmd.__init__(self)
  634. self.intro = "%s %s (c) visit: %s %s" % (pwman.appname, pwman.version,
  635. pwman.website, _dbwarning)
  636. self._historyfile = config.get_value("Readline", "history")
  637. self.hasxsel = hasxsel
  638. try:
  639. enc = CryptoEngine.get()
  640. enc.set_callback(CLICallback())
  641. self._db = db
  642. self._db.open()
  643. except Exception, e:
  644. self.error(e)
  645. sys.exit(1)
  646. try:
  647. readline.read_history_file(self._historyfile)
  648. except IOError, e:
  649. pass
  650. self.prompt = "!pwman> "
  651. class PwmanCliNew(PwmanCli):
  652. """
  653. inherit from the old class, override
  654. all the methods related to tags, and
  655. newer Node format, so backward compatability is kept...
  656. """
  657. def __init__(self, db, hasxsel):
  658. """
  659. initialize CLI interface, set up the DB
  660. connecion, see if we have xsel ...
  661. """
  662. cmd.Cmd.__init__(self)
  663. self.intro = "%s %s (c) visit: %s" % (pwman.appname, pwman.version,
  664. pwman.website)
  665. self._historyfile = config.get_value("Readline", "history")
  666. self.hasxsel = hasxsel
  667. try:
  668. enc = CryptoEngine.get()
  669. #enc.set_callback(CLICallback())
  670. enc._callback = CLICallback()
  671. self._db = db
  672. self._db.open()
  673. except Exception, e:
  674. self.error(e)
  675. sys.exit(1)
  676. try:
  677. readline.read_history_file(self._historyfile)
  678. except IOError, e:
  679. pass
  680. self.prompt = "pwman> "
  681. def print_node(self, node):
  682. width = str(tools._defaultwidth)
  683. print "Node %d." % (node._id)
  684. print ("%"+width+"s %s") % (tools.typeset("Username:", Fore.RED),
  685. node.username)
  686. print ("%"+width+"s %s") % (tools.typeset("Password:", Fore.RED),
  687. node.password)
  688. print ("%"+width+"s %s") % (tools.typeset("Url:", Fore.RED),
  689. node.url)
  690. print ("%"+width+"s %s") % (tools.typeset("Notes:", Fore.RED),
  691. node.notes)
  692. print tools.typeset("Tags: ", Fore.RED),
  693. for t in node.get_tags():
  694. print " %s " % t
  695. print
  696. def heardEnter():
  697. i, o, e = uselect.select([sys.stdin], [], [], 0.0001)
  698. for s in i:
  699. if s == sys.stdin:
  700. sys.stdin.readline()
  701. return True
  702. return False
  703. def waituntil_enter(somepredicate, timeout, period=0.25):
  704. mustend = time.time() + timeout
  705. while time.time() < mustend:
  706. cond = somepredicate()
  707. if cond:
  708. break
  709. time.sleep(period)
  710. self.do_cls('')
  711. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  712. if flushtimeout > 0:
  713. print "Type Enter to flush screen (autoflash in "\
  714. + "%d sec.)" % flushtimeout
  715. waituntil_enter(heardEnter, flushtimeout)
  716. def do_tags(self, arg):
  717. tags = self._db.listtags()
  718. # request password
  719. enc = CryptoEngine.get()
  720. if not enc.alive():
  721. enc._getcipher()
  722. print "Tags: ",
  723. if len(tags) == 0:
  724. print "None",
  725. for t in tags:
  726. print "%s " % t,
  727. print
  728. def get_tags(self, default=None):
  729. defaultstr = ''
  730. if default:
  731. for t in default:
  732. defaultstr += "%s " % (t)
  733. else:
  734. tags = self._db.currenttags()
  735. for t in tags:
  736. defaultstr += "%s " % (t)
  737. strings = []
  738. tags = self._db.listtags(True)
  739. for t in tags:
  740. # strings.append(t.get_name())
  741. strings.append(t)
  742. def complete(text, state):
  743. count = 0
  744. for s in strings:
  745. if s.startswith(text):
  746. if count == state:
  747. return s
  748. else:
  749. count += 1
  750. taglist = tools.getinput("Tags: ", defaultstr, complete)
  751. tagstrings = taglist.split()
  752. tags = [Tag(tn) for tn in tagstrings]
  753. return tags
  754. def do_list(self, args):
  755. if len(args.split()) > 0:
  756. self.do_clear('')
  757. self.do_filter(args)
  758. try:
  759. if sys.platform != 'win32':
  760. rows, cols = tools.gettermsize()
  761. else:
  762. rows, cols = 18, 80 # fix this !
  763. nodeids = self._db.listnodes()
  764. nodes = self._db.getnodes(nodeids)
  765. cols -= 8
  766. i = 0
  767. for n in nodes:
  768. tags = n.get_tags()
  769. tags = filter(None, tags)
  770. tagstring = ''
  771. first = True
  772. for t in tags:
  773. if not first:
  774. tagstring += ", "
  775. else:
  776. first = False
  777. tagstring += t
  778. name = "%s@%s" % (n.username, n.url)
  779. name_len = cols * 2 / 3
  780. tagstring_len = cols / 3
  781. if len(name) > name_len:
  782. name = name[:name_len-3] + "..."
  783. if len(tagstring) > tagstring_len:
  784. tagstring = tagstring[:tagstring_len-3] + "..."
  785. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  786. formatted_entry = tools.typeset(fmt % (n._id,
  787. name, tagstring),
  788. Fore.YELLOW, False)
  789. print formatted_entry
  790. i += 1
  791. if i > rows-2:
  792. i = 0
  793. c = tools.getonechar("Press <Space> for more,"
  794. " or 'Q' to cancel")
  795. if c == 'q':
  796. break
  797. except Exception, e:
  798. self.error(e)
  799. def do_filter(self, args):
  800. tagstrings = args.split()
  801. try:
  802. tags = []
  803. for ts in tagstrings:
  804. tags.append(Tag(ts))
  805. self._db.filter(tags)
  806. tags = self._db.currenttags()
  807. print "Current tags: ",
  808. if len(tags) == 0:
  809. print "None",
  810. for t in tags:
  811. print "%s " % (t.get_name()),
  812. print
  813. except Exception, e:
  814. self.error(e)
  815. def do_new(self, args):
  816. """
  817. can override default config settings the following way:
  818. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  819. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  820. Password (Blank to generate):
  821. """
  822. errmsg = """could not parse config override, please input some"""\
  823. + """ kind of dictionary, e.g.: n {'leetify':False, """\
  824. + """'numerics':True, 'special_chars':True}"""
  825. try:
  826. username = self.get_username()
  827. if args:
  828. try:
  829. args = ast.literal_eval(args)
  830. except Exception:
  831. raise Exception(errmsg)
  832. if not isinstance(args, dict):
  833. raise Exception(errmsg)
  834. password = self.get_password(1, **args)
  835. else:
  836. numerics = config.get_value(
  837. "Generator", "numerics").lower() == 'true'
  838. # TODO: allow custom leetifying through the config
  839. leetify = config.get_value(
  840. "Generator", "leetify").lower() == 'true'
  841. special_chars = config.get_value(
  842. "Generator", "special_chars").lower() == 'true'
  843. password = self.get_password(0,
  844. numerics=numerics,
  845. symbols=leetify,
  846. special_signs=special_chars)
  847. url = self.get_url()
  848. notes = self.get_notes()
  849. node = NewNode(username, password, url, notes)
  850. tags = self.get_tags()
  851. node.set_tags(tags)
  852. self._db.addnodes([node])
  853. print "Password ID: %d" % (node._id)
  854. # when done with node erase it
  855. zerome(password)
  856. except Exception, e:
  857. self.error(e)
  858. def do_print(self, arg):
  859. for i in self.get_ids(arg):
  860. try:
  861. node = self._db.getnodes([i])
  862. self.print_node(node[0])
  863. # when done with node erase it
  864. zerome(node[0]._password)
  865. except Exception, e:
  866. self.error(e)