cli.py 39 KB

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