cli.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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) 2006 Ivan Kelly <ivan@ivankelly.net>
  18. #============================================================================
  19. import pwman
  20. import pwman.exchange.importer as importer
  21. import pwman.exchange.exporter as exporter
  22. import pwman.util.generator as generator
  23. from pwman.data.nodes import Node
  24. from pwman.data.tags import Tag
  25. from pwman.util.crypto import CryptoEngine, CryptoBadKeyException, \
  26. CryptoPasswordMismatchException
  27. from pwman.util.callback import Callback
  28. import pwman.util.config as config
  29. import re
  30. import sys
  31. import tty
  32. import os
  33. import struct
  34. import termios
  35. import fcntl
  36. import getpass
  37. import cmd
  38. import traceback
  39. import time
  40. import select as uselect
  41. try:
  42. import readline
  43. _readline_available = True
  44. except ImportError, e:
  45. _readline_available = False
  46. class CLICallback(Callback):
  47. def getinput(self, question):
  48. return raw_input(question)
  49. def getsecret(self, question):
  50. return getpass.getpass(question + ":")
  51. class ANSI(object):
  52. Reset = 0
  53. Bold = 1
  54. Underscore = 2
  55. Black = 30
  56. Red = 31
  57. Green = 32
  58. Yellow = 33
  59. Blue = 34
  60. Magenta = 35
  61. Cyan = 36
  62. White = 37
  63. class PwmanCli(cmd.Cmd):
  64. def error(self, exception):
  65. if (isinstance(exception, KeyboardInterrupt)):
  66. print
  67. else:
  68. # traceback.print_exc()
  69. print "Error: %s " % (exception)
  70. def do_EOF(self, args):
  71. return self.do_exit(args)
  72. def do_exit(self, args):
  73. print
  74. try:
  75. self._db.close()
  76. except Exception, e:
  77. self.error(e)
  78. return True
  79. def get_ids(self, args):
  80. ids = []
  81. rx =re.compile(r"^(\d+)-(\d+)$")
  82. idstrs = args.split()
  83. for i in idstrs:
  84. m = rx.match(i)
  85. if m == None:
  86. try:
  87. ids.append(int(i))
  88. except ValueError, e:
  89. self._db.clearfilter()
  90. self._db.filter([Tag(i)])
  91. ids += self._db.listnodes()
  92. else:
  93. ids += range(int(m.group(1)),
  94. int(m.group(2))+1)
  95. return ids
  96. def get_filesystem_path(self, default=""):
  97. return getinput("Enter filename: ", default)
  98. def get_username(self, default=""):
  99. return getinput("Username: ", default)
  100. def get_password(self, default=""):
  101. password = getpassword("Password (Blank to generate): ", _defaultwidth, False)
  102. if len(password) == 0:
  103. length = getinput("Password length (default 7): ", "7")
  104. length = int(length)
  105. numerics = config.get_value("Generator", "numerics") == 'true';
  106. leetify = config.get_value("Generator", "leetify") == 'true';
  107. (password, dumpme) = generator.generate_password(length, length, True, leetify, numerics)
  108. print "New password: %s" % (password)
  109. return password
  110. else:
  111. return password
  112. def get_url(self, default=""):
  113. return getinput("Url: ", default)
  114. def get_notes(self, default=""):
  115. return getinput("Notes: ", default)
  116. def get_tags(self, default=[]):
  117. defaultstr = ''
  118. if len(default) > 0:
  119. for t in default:
  120. defaultstr += "%s " % (t.get_name())
  121. else:
  122. tags = self._db.currenttags()
  123. for t in tags:
  124. defaultstr += "%s " % (t.get_name())
  125. strings = []
  126. tags = self._db.listtags(True)
  127. for t in tags:
  128. strings.append(t.get_name())
  129. def complete(text, state):
  130. count = 0
  131. for s in strings:
  132. if s.startswith(text):
  133. if count == state:
  134. return s
  135. else:
  136. count += 1
  137. taglist = getinput("Tags: ", defaultstr, complete)
  138. tagstrings = taglist.split()
  139. tags = []
  140. for tn in tagstrings:
  141. tags.append(Tag(tn))
  142. return tags
  143. def print_node(self, node):
  144. width = str(_defaultwidth)
  145. print "Node %d." % (node.get_id())
  146. print ("%"+width+"s %s") % (typeset("Username:", ANSI.Red),
  147. node.get_username())
  148. print ("%"+width+"s %s") % (typeset("Password:", ANSI.Red),
  149. node.get_password())
  150. print ("%"+width+"s %s") % (typeset("Url:", ANSI.Red),
  151. node.get_url())
  152. print ("%"+width+"s %s") % (typeset("Notes:", ANSI.Red),
  153. node.get_notes())
  154. print typeset("Tags: ", ANSI.Red),
  155. for t in node.get_tags():
  156. print "%s " % t.get_name(),
  157. print
  158. def heardEnter():
  159. i,o,e = uselect.select([sys.stdin],[],[],0.0001)
  160. for s in i:
  161. if s == sys.stdin:
  162. input = sys.stdin.readline()
  163. return True
  164. return False
  165. def waituntil_enter(somepredicate,timeout, period=0.25):
  166. mustend = time.time() + timeout
  167. while time.time() < mustend:
  168. if somepredicate():
  169. break
  170. time.sleep(period)
  171. self.do_cls('')
  172. print "Type Enter to flush screen (autoflash in 5 sec.)"
  173. waituntil_enter(heardEnter(), 5)
  174. def do_tags(self, arg):
  175. tags = self._db.listtags()
  176. if len(tags) > 0:
  177. tags[0].get_name() # hack to get password request before output
  178. print "Tags: ",
  179. if len(tags) == 0:
  180. print "None",
  181. for t in tags:
  182. print "%s " % (t.get_name()),
  183. print
  184. def complete_filter(self, text, line, begidx, endidx):
  185. strings = []
  186. enc = CryptoEngine.get()
  187. if not enc.alive():
  188. return strings
  189. tags = self._db.listtags()
  190. for t in tags:
  191. name = t.get_name()
  192. if name.startswith(text):
  193. strings.append(t.get_name())
  194. return strings
  195. def do_filter(self, args):
  196. tagstrings = args.split()
  197. try:
  198. tags = []
  199. for ts in tagstrings:
  200. tags.append(Tag(ts))
  201. self._db.filter(tags)
  202. tags = self._db.currenttags()
  203. print "Current tags: ",
  204. if len(tags) == 0:
  205. print "None",
  206. for t in tags:
  207. print "%s " % (t.get_name()),
  208. print
  209. except Exception, e:
  210. self.error(e)
  211. def do_clear(self, args):
  212. try:
  213. self._db.clearfilter()
  214. except Exception, e:
  215. self.error(e)
  216. def do_e(self, arg):
  217. self.do_edit(arg)
  218. def do_edit(self, arg):
  219. ids = self.get_ids(arg)
  220. for i in ids:
  221. try:
  222. i = int(i)
  223. node = self._db.getnodes([i])[0]
  224. menu = CliMenu()
  225. print "Editing node %d." % (i)
  226. menu.add(CliMenuItem("Username", self.get_username,
  227. node.get_username,
  228. node.set_username))
  229. menu.add(CliMenuItem("Password", self.get_password,
  230. node.get_password,
  231. node.set_password))
  232. menu.add(CliMenuItem("Url", self.get_url,
  233. node.get_url,
  234. node.set_url))
  235. menu.add(CliMenuItem("Notes", self.get_notes,
  236. node.get_notes,
  237. node.set_notes))
  238. menu.add(CliMenuItem("Tags", self.get_tags,
  239. node.get_tags,
  240. node.set_tags))
  241. menu.run()
  242. self._db.editnode(i, node)
  243. except Exception, e:
  244. self.error(e)
  245. def do_import(self, arg):
  246. try:
  247. args = arg.split()
  248. if len(args) == 0:
  249. types = importer.Importer.types()
  250. type = select("Select filetype:", types)
  251. imp = importer.Importer.get(type)
  252. file = getinput("Select file:")
  253. imp.import_data(self._db, file)
  254. else:
  255. for i in args:
  256. types = importer.Importer.types()
  257. type = select("Select filetype:", types)
  258. imp = importer.Importer.get(type)
  259. imp.import_data(self._db, i)
  260. except Exception, e:
  261. self.error(e)
  262. def do_export(self, arg):
  263. try:
  264. nodes = self.get_ids(arg)
  265. types = exporter.Exporter.types()
  266. type = select("Select filetype:", types)
  267. exp = exporter.Exporter.get(type)
  268. file = getinput("Select output file:")
  269. if len(nodes) > 0:
  270. b = getyesno("Export nodes %s?" % (nodes), True)
  271. if not b:
  272. return
  273. exp.export_data(self._db, file, nodes)
  274. else:
  275. nodes = self._db.listnodes()
  276. tags = self._db.currenttags()
  277. tagstr = ""
  278. if len(tags) > 0:
  279. tagstr = " for "
  280. for t in tags:
  281. tagstr += "'%s' " % (t.get_name())
  282. b = getyesno("Export all nodes%s?" % (tagstr), True)
  283. if not b:
  284. return
  285. exp.export_data(self._db, file, nodes)
  286. print "Data exported."
  287. except Exception, e:
  288. self.error(e)
  289. def do_h(self, arg):
  290. self.do_help(arg)
  291. def do_n(self, arg):
  292. self.do_new(arg)
  293. def do_new(self, arg):
  294. try:
  295. username = self.get_username()
  296. password = self.get_password()
  297. url = self.get_url()
  298. notes = self.get_notes()
  299. node = Node(username, password, url, notes)
  300. tags = self.get_tags()
  301. node.set_tags(tags)
  302. self._db.addnodes([node])
  303. print "Password ID: %d" % (node.get_id())
  304. except Exception, e:
  305. self.error(e)
  306. def do_p(self, arg):
  307. self.do_print(arg)
  308. def do_print(self, arg):
  309. for i in self.get_ids(arg):
  310. try:
  311. node = self._db.getnodes([i])
  312. self.print_node(node[0])
  313. except Exception, e:
  314. self.error(e)
  315. def do_rm(self, arg):
  316. self.do_delete(arg)
  317. def do_delete(self, arg):
  318. ids = self.get_ids(arg)
  319. try:
  320. nodes = self._db.getnodes(ids)
  321. for n in nodes:
  322. b = getyesno("Are you sure you want to delete '%s@%s'?"
  323. % (n.get_username(), n.get_url()), False)
  324. if b == True:
  325. self._db.removenodes([n])
  326. print "%s@%s deleted" % (n.get_username(), n.get_url())
  327. except Exception, e:
  328. self.error(e)
  329. def do_l(self, args):
  330. self.do_list(args)
  331. def do_ls(self, args):
  332. self.do_list(args)
  333. def do_list(self, args):
  334. if len(args.split()) > 0:
  335. self.do_clear('')
  336. self.do_filter(args)
  337. try:
  338. rows, cols = gettermsize()
  339. nodeids = self._db.listnodes()
  340. nodes = self._db.getnodes(nodeids)
  341. cols -= 8
  342. i = 0
  343. for n in nodes:
  344. tags=n.get_tags()
  345. tagstring = ''
  346. first = True
  347. for t in tags:
  348. if not first:
  349. tagstring += ", "
  350. else:
  351. first=False
  352. tagstring += t.get_name()
  353. name = "%s@%s" % (n.get_username(), n.get_url())
  354. name_len = cols * 2 / 3
  355. tagstring_len = cols / 3
  356. if len(name) > name_len:
  357. name = name[:name_len-3] + "..."
  358. if len(tagstring) > tagstring_len:
  359. tagstring = tagstring[:tagstring_len-3] + "..."
  360. fmt = "%%5d. %%-%ds %%-%ds" % (name_len, tagstring_len)
  361. print typeset(fmt % (n.get_id(), name, tagstring),
  362. ANSI.Yellow, False)
  363. i += 1
  364. if i > rows-2:
  365. i = 0
  366. c = getonechar("Press <Space> for more, or 'Q' to cancel")
  367. if c == 'q':
  368. break
  369. except Exception, e:
  370. self.error(e)
  371. def do_forget(self, args):
  372. try:
  373. enc = CryptoEngine.get()
  374. enc.forget()
  375. except Exception,e:
  376. self.error(e)
  377. def do_passwd(self, args):
  378. try:
  379. self._db.changepassword()
  380. except Exception, e:
  381. self.error(e)
  382. def do_set(self, args):
  383. argstrs = args.split()
  384. try:
  385. if len(argstrs) == 0:
  386. conf = config.get_conf()
  387. for s in conf.keys():
  388. for n in conf[s].keys():
  389. print "%s.%s = %s" % (s, n, conf[s][n])
  390. elif len(argstrs) == 1:
  391. r = re.compile("(.+)\.(.+)")
  392. m = r.match(argstrs[0])
  393. if m is None or len(m.groups()) != 2:
  394. print "Invalid option format"
  395. self.help_set()
  396. return
  397. print "%s.%s = %s" % (m.group(1), m.group(2),
  398. config.get_value(m.group(1), m.group(2)))
  399. elif len(argstrs) == 2:
  400. r = re.compile("(.+)\.(.+)")
  401. m = r.match(argstrs[0])
  402. if m is None or len(m.groups()) != 2:
  403. print "Invalid option format"
  404. self.help_set()
  405. return
  406. config.set_value(m.group(1), m.group(2), argstrs[1])
  407. else:
  408. self.help_set()
  409. except Exception, e:
  410. self.error(e)
  411. def do_save(self, args):
  412. argstrs = args.split()
  413. try:
  414. if len(argstrs) > 0:
  415. config.save(argstrs[0])
  416. else:
  417. config.save()
  418. print "Config saved."
  419. except Exception, e:
  420. self.error(e)
  421. def do_cls(self,args):
  422. os.system('clear')
  423. ##
  424. ## Help functions
  425. ##
  426. def usage(self, string):
  427. print "Usage: %s" % (string)
  428. def help_cls(self):
  429. self.usage("cls")
  430. print "Clear the Screen from information."
  431. def help_ls(self):
  432. self.help_list()
  433. def help_list(self):
  434. self.usage("list <tag> ...")
  435. print "List nodes that match current or specified filter. ls is an alias."
  436. def help_EOF(self):
  437. self.help_exit()
  438. def help_delete(self):
  439. self.usage("delete <ID|tag> ...")
  440. print "Deletes nodes. rm is an alias."
  441. self._mult_id_help()
  442. def help_h(self):
  443. self.help_help()
  444. def help_help(self):
  445. self.usage("help [topic]")
  446. print "Prints a help message for a command."
  447. def help_e(self):
  448. self.help_edit()
  449. def help_n(self):
  450. self.help_new()
  451. def help_p(self):
  452. self.help_print()
  453. def help_l(self):
  454. self.help_list()
  455. def help_edit(self):
  456. self.usage("edit <ID|tag> ... ")
  457. print "Edits a nodes."
  458. self._mult_id_help()
  459. def help_import(self):
  460. self.usage("import [filename] ...")
  461. print "Imports a nodes from a file."
  462. def help_export(self):
  463. self.usage("export <ID|tag> ... ")
  464. print "Exports a list of ids to an external format. If no IDs or tags are specified, then all nodes under the current filter are exported."
  465. self._mult_id_help()
  466. def help_new(self):
  467. self.usage("new")
  468. print "Creates a new node."
  469. def help_rm(self):
  470. self.help_delete()
  471. def help_print(self):
  472. self.usage("print <ID|tag> ...")
  473. print "Displays a node. ",
  474. self._mult_id_help()
  475. def _mult_id_help(self):
  476. print "Multiple ids and nodes can be specified, separated by a space. A range of ids can be specified in the format n-N. e.g. '10-20' would specify all nodes having ids from 10 to 20 inclusive. Tags are considered one-by-one. e.g. 'foo 2 bar' would yield to all nodes with tag 'foo', node 2 and all nodes with tag 'bar'."
  477. def help_exit(self):
  478. self.usage("exit")
  479. print "Exits the application."
  480. def help_save(self):
  481. self.usage("save [filename]")
  482. print "Saves the current configuration to [filename]. If no filename is given, the configuration is saved to the file from which the initial configuration was loaded."
  483. def help_set(self):
  484. self.usage("set [configoption] [value]")
  485. print "Sets a configuration option. If no value is specified, the current value for [configoption] is output. If neither [configoption] nor [value] are specified, the whole current configuration is output. [configoption] must be of the format <section>.<option>"
  486. def help_ls(self):
  487. self.help_list()
  488. def help_passwd(self):
  489. self.usage("passwd")
  490. print "Changes the password on the database. "
  491. def help_forget(self):
  492. self.usage("forget")
  493. print "Forgets the database password. Your password will need to be reentered before accessing the database again."
  494. def help_clear(self):
  495. self.usage("clear")
  496. print "Clears the filter criteria. "
  497. def help_filter(self):
  498. self.usage("filter <tag> ...")
  499. print "Filters nodes on tag. Arguments can be zero or more tags. Displays current tags if called without arguments."
  500. def help_tags(self):
  501. self.usage("tags")
  502. print "Displays all tags in used in the database."
  503. def postloop(self):
  504. try:
  505. readline.write_history_file(self._historyfile)
  506. except Exception, e:
  507. pass
  508. def __init__(self, db):
  509. cmd.Cmd.__init__(self)
  510. self.intro = "%s %s (c) %s <%s>" % (pwman.appname, pwman.version,
  511. pwman.author, pwman.authoremail)
  512. self._historyfile = config.get_value("Readline", "history")
  513. try:
  514. enc = CryptoEngine.get()
  515. enc.set_callback(CLICallback())
  516. self._db = db
  517. self._db.open()
  518. except Exception, e:
  519. self.error(e)
  520. sys.exit(1)
  521. try:
  522. readline.read_history_file(self._historyfile)
  523. except Exception, e:
  524. pass
  525. self.prompt = "pwman> "
  526. _defaultwidth = 10
  527. def getonechar(question, width=_defaultwidth):
  528. question = "%s " % (question)
  529. print question.ljust(width),
  530. sys.stdout.flush()
  531. fd = sys.stdin.fileno()
  532. tty_mode = tty.tcgetattr(fd)
  533. tty.setcbreak(fd)
  534. try:
  535. ch = os.read(fd, 1)
  536. finally:
  537. tty.tcsetattr(fd, tty.TCSAFLUSH, tty_mode)
  538. print ch
  539. return ch
  540. def getyesno(question, defaultyes=False, width=_defaultwidth):
  541. if (defaultyes):
  542. default = "[Y/n]"
  543. else:
  544. default = "[y/N]"
  545. ch = getonechar("%s %s" % (question, default), width)
  546. if (ch == '\n'):
  547. if (defaultyes):
  548. return True
  549. else:
  550. return False
  551. elif (ch == 'y' or ch == 'Y'):
  552. return True
  553. elif (ch == 'n' or ch == 'N'):
  554. return False
  555. else:
  556. return getyesno(question, defaultyes, width)
  557. def gettermsize():
  558. s = struct.pack("HHHH", 0, 0, 0, 0)
  559. f = sys.stdout.fileno()
  560. x = fcntl.ioctl(f, termios.TIOCGWINSZ, s)
  561. rows, cols, width, height = struct.unpack("HHHH", x)
  562. return rows, cols
  563. def getinput(question, default="", completer=None, width=_defaultwidth):
  564. if (not _readline_available):
  565. return raw_input(question.ljust(width))
  566. else:
  567. def defaulter(): readline.insert_text(default)
  568. readline.set_startup_hook(defaulter)
  569. oldcompleter = readline.get_completer()
  570. readline.set_completer(completer)
  571. x = raw_input(question.ljust(width))
  572. readline.set_completer(oldcompleter)
  573. readline.set_startup_hook()
  574. return x
  575. def getpassword(question, width=_defaultwidth, echo=False):
  576. if echo:
  577. print question.ljust(width),
  578. return sys.stdin.readline().rstrip()
  579. else:
  580. while 1:
  581. a1 = getpass.getpass(question.ljust(width))
  582. if len(a1) == 0:
  583. return a1;
  584. a2 = getpass.getpass("[Repeat] %s" % (question.ljust(width)))
  585. if a1 == a2:
  586. return a1
  587. else:
  588. print "Passwords don't match. Try again."
  589. def typeset(text, color, bold=False, underline=False):
  590. if not config.get_value("Global", "colors") == 'yes':
  591. return text
  592. if (bold):
  593. bold = "%d;" %(ANSI.Bold)
  594. else:
  595. bold = ""
  596. if (underline):
  597. underline = "%d;" % (ANSI.Underline)
  598. else:
  599. underline = ""
  600. return "\033[%s%s%sm%s\033[%sm" % (bold, underline, color,
  601. text, ANSI.Reset)
  602. def select(question, possible):
  603. for i in range(0, len(possible)):
  604. print ("%d - %-"+str(_defaultwidth)+"s") % (i+1, possible[i])
  605. while 1:
  606. input = getonechar(question)
  607. if input.isdigit() and int(input) in range(1, len(possible)+1):
  608. return possible[int(input)-1]
  609. class CliMenu(object):
  610. def __init__(self):
  611. self.items = []
  612. def add(self, item):
  613. if (isinstance(item, CliMenuItem)):
  614. self.items.append(item)
  615. else:
  616. print item.__class__
  617. def run(self):
  618. while True:
  619. i = 0
  620. for x in self.items:
  621. i = i + 1
  622. current = x.getter()
  623. currentstr = ''
  624. if type(current) == list:
  625. for c in current:
  626. currentstr += ("%s " % (c))
  627. else:
  628. currentstr = current
  629. print ("%d - %-"+str(_defaultwidth)+"s %s") % (i, x.name+":",
  630. currentstr)
  631. print "%c - Finish editing" % ('X')
  632. option = getonechar("Enter your choice:")
  633. try:
  634. # substract 1 because array subscripts start at 1
  635. selection = int(option) - 1
  636. value = self.items[selection].editor(self.items[selection].getter())
  637. self.items[selection].setter(value)
  638. except (ValueError,IndexError):
  639. if (option.upper() == 'X'):
  640. break
  641. print "Invalid selection"
  642. class CliMenuItem(object):
  643. def __init__(self, name, editor, getter, setter):
  644. self.name = name
  645. self.editor = editor
  646. self.getter = getter
  647. self.setter = setter