cli.py 38 KB

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