cli.py 37 KB

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