cli.py 40 KB

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