ocli.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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. Base Class and Old UI classes, should be removed in next pwman release
  24. """
  25. from __future__ import print_function
  26. import pwman
  27. import pwman.exchange.importer as importer
  28. import pwman.exchange.exporter as exporter
  29. import pwman.util.generator as generator
  30. from pwman.data.nodes import Node
  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 colorama import Fore
  46. from pwman.ui.base import HelpUI, BaseUI
  47. from pwman.ui.tools import CLICallback
  48. try:
  49. import readline
  50. _readline_available = True
  51. except ImportError, e: # pragma: no cover
  52. _readline_available = False
  53. def get_pass_conf():
  54. numerics = config.get_value("Generator", "numerics").lower() == 'true'
  55. # TODO: allow custom leetifying through the config
  56. leetify = config.get_value("Generator", "leetify").lower() == 'true'
  57. special_chars = config.get_value("Generator", "special_chars"
  58. ).lower() == 'true'
  59. return numerics, leetify, special_chars
  60. # pylint: disable=R0904
  61. class PwmanCliOld(cmd.Cmd, HelpUI, BaseUI):
  62. """
  63. UI class for MacOSX
  64. """
  65. def error(self, exception):
  66. if (isinstance(exception, KeyboardInterrupt)):
  67. print('')
  68. else:
  69. print("Error: {0} ".format(exception))
  70. def do_exit(self, args):
  71. """exit the ui"""
  72. self._db.close()
  73. return True
  74. def get_ids(self, args):
  75. """
  76. Command can get a single ID or
  77. a range of IDs, with begin-end.
  78. e.g. 1-3 , will get 1 to 3.
  79. """
  80. ids = []
  81. rex = re.compile("^(?P<begin>\d+)(?:-(?P<end>\d+))?$")
  82. rex = rex.match(args)
  83. if hasattr(rex, 'groupdict'):
  84. try:
  85. begin = int(rex.groupdict()['begin'])
  86. end = int(rex.groupdict()['end'])
  87. if not end > begin:
  88. print("Start node should be smaller than end node")
  89. return ids
  90. ids += range(begin, end+1)
  91. return ids
  92. except TypeError:
  93. ids.append(int(begin))
  94. else:
  95. print("Could not understand your input...")
  96. return ids
  97. def get_filesystem_path(self, default="", reader=raw_input):
  98. return tools.getinput("Enter filename: ", default, reader=reader)
  99. def get_username(self, default="", reader=raw_input):
  100. return tools.getinput("Username: ", default, reader)
  101. def get_password(self, argsgiven, numerics=False, leetify=False,
  102. symbols=False, special_signs=False, reader=raw_input):
  103. """
  104. in the config file:
  105. numerics -> numerics
  106. leetify -> symbols
  107. special_chars -> special_signs
  108. """
  109. # TODO: replace this code with tools.getpassword
  110. if argsgiven == 1:
  111. length = tools.getinput("Password length (default 7): ", "7")
  112. length = len(length)
  113. password, dumpme = generator.generate_password(length, length,
  114. True, leetify,
  115. numerics,
  116. special_signs)
  117. print ("New password: %s" % (password))
  118. return password
  119. # no args given
  120. password = tools.getpassword("Password (Blank to generate): ",
  121. tools._defaultwidth, False, reader)
  122. if not password:
  123. length = tools.getinput("Password length (default 7): ", "7")
  124. if length:
  125. length = int(length)
  126. else:
  127. length = 7
  128. password, dumpme = generator.generate_password(length, length,
  129. True, leetify,
  130. numerics,
  131. special_signs)
  132. print ("New password: %s" % (password))
  133. return password
  134. def get_url(self, default="", reader=raw_input):
  135. return tools.getinput("Url: ", default, reader)
  136. def get_notes(self, default="", reader=raw_input):
  137. return tools.getinput("Notes: ", default, reader)
  138. def get_tags(self, default=None):
  139. """read node tags from user"""
  140. defaultstr = ''
  141. if default:
  142. for t in default:
  143. defaultstr += "%s " % (t.get_name())
  144. else:
  145. tags = self._db.currenttags()
  146. for t in tags:
  147. defaultstr += "%s " % (t.get_name())
  148. strings = []
  149. tags = self._db.listtags(True)
  150. for t in tags:
  151. strings.append(t.get_name())
  152. def complete(text, state):
  153. count = 0
  154. for s in strings:
  155. if s.startswith(text):
  156. if count == state:
  157. return s
  158. else:
  159. count += 1
  160. taglist = tools.getinput("Tags: ", defaultstr, complete)
  161. tagstrings = taglist.split()
  162. tags = []
  163. for tn in tagstrings:
  164. tags.append(Tag(tn))
  165. return tags
  166. def print_node(self, node):
  167. width = str(tools._defaultwidth)
  168. print ("Node %d." % (node._id))
  169. print ("%" + width + "s %s") % (tools.typeset("Username:", Fore.RED),
  170. node.get_username())
  171. print ("%" + width + "s %s") % (tools.typeset("Password:", Fore.RED),
  172. node.get_password())
  173. print ("%" + width + "s %s") % (tools.typeset("Url:", Fore.RED),
  174. node.get_url())
  175. print ("%" + width + "s %s") % (tools.typeset("Notes:", Fore.RED),
  176. node.get_notes())
  177. print (tools.typeset("Tags: ", Fore.RED)),
  178. for t in node.get_tags():
  179. print (" %s \n" % t.get_name()),
  180. def heardEnter():
  181. inpt, out, err = uselect.select([sys.stdin], [], [], 0.0001)
  182. for stream in inpt:
  183. if stream == sys.stdin:
  184. sys.stdin.readline()
  185. return True
  186. return False
  187. def waituntil_enter(somepredicate, timeout, period=0.25):
  188. mustend = time.time() + timeout
  189. while time.time() < mustend:
  190. cond = somepredicate()
  191. if cond:
  192. break
  193. time.sleep(period)
  194. self.do_cls('')
  195. flushtimeout = int(config.get_value("Global", "cls_timeout"))
  196. if flushtimeout > 0:
  197. print ("Type Enter to flush screen (autoflash in "
  198. "%d sec.)" % flushtimeout)
  199. waituntil_enter(heardEnter, flushtimeout)
  200. def do_tags(self, arg):
  201. tags = self._db.listtags()
  202. if len(tags) > 0:
  203. tags[0].get_name() # hack to get password request before output
  204. print ("Tags: "),
  205. if len(tags) == 0:
  206. print ("None"),
  207. for t in tags:
  208. print ("%s " % (t.get_name())),
  209. print
  210. def complete_filter(self, text, line, begidx, endidx):
  211. strings = []
  212. enc = CryptoEngine.get()
  213. if not enc.alive():
  214. return strings
  215. tags = self._db.listtags()
  216. for t in tags:
  217. name = t.get_name()
  218. if name.startswith(text):
  219. strings.append(t.get_name())
  220. return strings
  221. def do_filter(self, args):
  222. tagstrings = args.split()
  223. try:
  224. tags = []
  225. for ts in tagstrings:
  226. tags.append(Tag(ts))
  227. self._db.filter(tags)
  228. tags = self._db.currenttags()
  229. print ("Current tags: "),
  230. if len(tags) == 0:
  231. print ("None"),
  232. for t in tags:
  233. print ("%s " % (t.get_name())),
  234. print
  235. except Exception, e:
  236. self.error(e)
  237. def do_clear(self, args):
  238. try:
  239. self._db.clearfilter()
  240. except Exception, e:
  241. self.error(e)
  242. def do_edit(self, arg):
  243. ids = self.get_ids(arg)
  244. for i in ids:
  245. try:
  246. i = int(i)
  247. node = self._db.getnodes([i])[0]
  248. menu = CliMenu()
  249. print ("Editing node %d." % (i))
  250. menu.add(CliMenuItem("Username", self.get_username,
  251. node.get_username,
  252. node.set_username))
  253. menu.add(CliMenuItem("Password", self.get_password,
  254. node.get_password,
  255. node.set_password))
  256. menu.add(CliMenuItem("Url", self.get_url,
  257. node.get_url,
  258. node.set_url))
  259. menu.add(CliMenuItem("Notes", self.get_notes,
  260. node.get_notes,
  261. node.set_notes))
  262. menu.add(CliMenuItem("Tags", self.get_tags,
  263. node.get_tags,
  264. node.set_tags))
  265. menu.run()
  266. self._db.editnode(i, node)
  267. # when done with node erase it
  268. zerome(node._password)
  269. except Exception, e:
  270. self.error(e)
  271. def do_import(self, arg):
  272. try:
  273. args = arg.split()
  274. if len(args) == 0:
  275. types = importer.Importer.types()
  276. intype = tools.select("Select filetype:", types)
  277. imp = importer.Importer.get(intype)
  278. infile = tools.getinput("Select file:")
  279. imp.import_data(self._db, infile)
  280. else:
  281. for i in args:
  282. types = importer.Importer.types()
  283. intype = tools.select("Select filetype:", types)
  284. imp = importer.Importer.get(intype)
  285. imp.import_data(self._db, i)
  286. except Exception, e:
  287. self.error(e)
  288. def do_export(self, arg):
  289. try:
  290. nodes = self.get_ids(arg)
  291. types = exporter.Exporter.types()
  292. ftype = tools.select("Select filetype:", types)
  293. exp = exporter.Exporter.get(ftype)
  294. out_file = tools.getinput("Select output file:")
  295. if len(nodes) > 0:
  296. b = tools.getyesno("Export nodes %s?" % (nodes), True)
  297. if not b:
  298. return
  299. exp.export_data(self._db, out_file, nodes)
  300. else:
  301. nodes = self._db.listnodes()
  302. tags = self._db.currenttags()
  303. tagstr = ""
  304. if len(tags) > 0:
  305. tagstr = " for "
  306. for t in tags:
  307. tagstr += "'%s' " % (t.get_name())
  308. b = tools.getyesno("Export all nodes%s?" % (tagstr), True)
  309. if not b:
  310. return
  311. exp.export_data(self._db, out_file, nodes)
  312. print ("Data exported.")
  313. except Exception, e:
  314. self.error(e)
  315. def do_new(self, args):
  316. """
  317. can override default config settings the following way:
  318. Pwman3 0.2.1 (c) visit: http://github.com/pwman3/pwman3
  319. pwman> n {'leetify':False, 'numerics':True, 'special_chars':True}
  320. Password (Blank to generate):
  321. """
  322. errmsg = ("could not parse config override, please input some"
  323. " kind of dictionary, e.g.: n {'leetify':False, "
  324. " numerics':True, 'special_chars':True}")
  325. try:
  326. username = self.get_username()
  327. if args:
  328. try:
  329. args = ast.literal_eval(args)
  330. except Exception:
  331. raise Exception(errmsg)
  332. if not isinstance(args, dict):
  333. raise Exception(errmsg)
  334. password = self.get_password(1, **args)
  335. else:
  336. numerics = config.get_value("Generator",
  337. "numerics").lower() == 'true'
  338. # TODO: allow custom leetifying through the config
  339. leetify = config.get_value("Generator",
  340. "leetify").lower() == 'true'
  341. special_chars = config.get_value("Generator",
  342. "special_chars").lower() == \
  343. 'true'
  344. password = self.get_password(0,
  345. numerics=numerics,
  346. symbols=leetify,
  347. special_signs=special_chars)
  348. url = self.get_url()
  349. notes = self.get_notes()
  350. node = Node(username, password, url, notes)
  351. tags = self.get_tags()
  352. node.set_tags(tags)
  353. self._db.addnodes([node])
  354. print ("Password ID: %d" % (node.get_id()))
  355. except Exception, e:
  356. self.error(e)
  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: # pragma: no cover
  363. self.error(e)
  364. def do_delete(self, arg):
  365. ids = self.get_ids(arg)
  366. try:
  367. nodes = self._db.getnodes(ids)
  368. for n in nodes:
  369. b = tools.getyesno("Are you sure you want to delete '%s@%s'?"
  370. % (n.get_username(), n.get_url()), False)
  371. if b is True:
  372. self._db.removenodes([n])
  373. print ("%s@%s deleted" % (n.get_username(), n.get_url()))
  374. except Exception, e:
  375. self.error(e)
  376. def do_list(self, args):
  377. """
  378. TODO: in order to make this code testable
  379. The functionality in this method should
  380. go to a method that returns a string.
  381. This method should only do the printing.
  382. """
  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),
  452. m.group(2))))
  453. elif len(argstrs) == 2:
  454. r = re.compile("(.+)\.(.+)")
  455. m = r.match(argstrs[0])
  456. if m is None or len(m.groups()) != 2:
  457. print ("Invalid option format")
  458. self.help_set()
  459. return
  460. config.set_value(m.group(1), m.group(2), argstrs[1])
  461. else:
  462. self.help_set()
  463. except Exception, e:
  464. self.error(e)
  465. def do_save(self, args):
  466. argstrs = args.split()
  467. try:
  468. if len(argstrs) > 0:
  469. config.save(argstrs[0])
  470. else:
  471. config.save()
  472. print ("Config saved.")
  473. except Exception, e:
  474. self.error(e)
  475. def do_cls(self, args):
  476. os.system('clear')
  477. def do_copy(self, args):
  478. if self.hasxsel:
  479. ids = self.get_ids(args)
  480. if len(ids) > 1:
  481. print ("Can copy only 1 password at a time...")
  482. return None
  483. try:
  484. node = self._db.getnodes(ids)
  485. tools.text_to_clipboards(node[0].get_password())
  486. print ("copied password for {}@{} clipboard".format(
  487. node[0].get_username(), node[0].get_url()))
  488. print ("erasing in 10 sec...")
  489. time.sleep(10)
  490. tools.text_to_clipboards("")
  491. except Exception, e:
  492. self.error(e)
  493. else:
  494. print ("Can't copy to clipboard, no xsel found in the system!")
  495. def do_open(self, args):
  496. ids = self.get_ids(args)
  497. if not args:
  498. self.help_open()
  499. return
  500. if len(ids) > 1:
  501. print ("Can open only 1 link at a time ...")
  502. return None
  503. try:
  504. node = self._db.getnodes(ids)
  505. url = node[0].get_url()
  506. tools.open_url(url)
  507. except Exception, e:
  508. self.error(e)
  509. def postloop(self):
  510. try:
  511. readline.write_history_file(self._historyfile)
  512. except Exception:
  513. pass
  514. def __init__(self, db, hasxsel):
  515. """
  516. initialize CLI interface, set up the DB
  517. connecion, see if we have xsel ...
  518. """
  519. _dbwarning = "\n*** WARNNING: You are using the old database format" \
  520. + " which is unsecure." \
  521. + " It's highly recommended to switch to the new database " \
  522. + "format. Do note: support for this DB format will be dropped in"\
  523. + " v0.5." \
  524. + " Check the help (pwman3 -h) or look at the manpage which" \
  525. + " explains how to proceed. ***"
  526. cmd.Cmd.__init__(self)
  527. self.intro = "%s %s (c) visit: %s %s" % (pwman.appname, pwman.version,
  528. pwman.website, _dbwarning)
  529. self._historyfile = config.get_value("Readline", "history")
  530. self.hasxsel = hasxsel
  531. try:
  532. enc = CryptoEngine.get()
  533. enc.set_callback(CLICallback())
  534. self._db = db
  535. self._db.open()
  536. except Exception, e:
  537. self.error(e)
  538. sys.exit(1)
  539. try:
  540. readline.read_history_file(self._historyfile)
  541. except IOError, e:
  542. pass
  543. self.prompt = "!pwman> "