cli.py 33 KB

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