base.py 36 KB

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