cli.py 39 KB

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