bindcmd.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. # Copyright (C) 2009 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. """This module holds the BindCmdInterpreter class. This provides the
  16. core functionality for bindctl. It maintains a session with
  17. b10-cmdctl, holds local configuration and module information, and
  18. handles command line interface commands"""
  19. import sys
  20. from cmd import Cmd
  21. from bindctl.exception import *
  22. from bindctl.moduleinfo import *
  23. from bindctl.cmdparse import BindCmdParser
  24. from bindctl import command_sets
  25. from xml.dom import minidom
  26. import isc.config
  27. import isc.cc.data
  28. import http.client
  29. import json
  30. import inspect
  31. import pprint
  32. import ssl, socket
  33. import os, time, random, re
  34. import os.path
  35. import getpass
  36. from hashlib import sha1
  37. import csv
  38. import pwd
  39. import getpass
  40. import copy
  41. import errno
  42. try:
  43. from collections import OrderedDict
  44. except ImportError:
  45. from bindctl.mycollections import OrderedDict
  46. # if we have readline support, use that, otherwise use normal stdio
  47. try:
  48. import readline
  49. # Only consider spaces as word boundaries; identifiers can contain
  50. # '/' and '[]', and configuration item names can in theory use any
  51. # printable character. See the discussion in tickets #1345 and
  52. # #2254 for more information.
  53. readline.set_completer_delims(' ')
  54. my_readline = readline.get_line_buffer
  55. except ImportError:
  56. my_readline = sys.stdin.readline
  57. # Used for tab-completion of 'identifiers' (i.e. config values)
  58. # If a command parameter has this name, the tab completion hints
  59. # are derived from config data
  60. CFGITEM_IDENTIFIER_PARAM = 'identifier'
  61. CSV_FILE_NAME = 'default_user.csv'
  62. CONFIG_MODULE_NAME = 'config'
  63. CONST_BINDCTL_HELP = """
  64. usage: <module name> <command name> [param1 = value1 [, param2 = value2]]
  65. Type Tab character to get the hint of module/command/parameters.
  66. Type \"help(? h)\" for help on bindctl.
  67. Type \"<module_name> help\" for help on the specific module.
  68. Type \"<module_name> <command_name> help\" for help on the specific command.
  69. \nAvailable module names: """
  70. class ValidatedHTTPSConnection(http.client.HTTPSConnection):
  71. '''Overrides HTTPSConnection to support certification
  72. validation. '''
  73. def __init__(self, host, ca_certs):
  74. http.client.HTTPSConnection.__init__(self, host)
  75. self.ca_certs = ca_certs
  76. def connect(self):
  77. ''' Overrides the connect() so that we do
  78. certificate validation. '''
  79. sock = socket.create_connection((self.host, self.port),
  80. self.timeout)
  81. if self._tunnel_host:
  82. self.sock = sock
  83. self._tunnel()
  84. req_cert = ssl.CERT_NONE
  85. if self.ca_certs:
  86. req_cert = ssl.CERT_REQUIRED
  87. self.sock = ssl.wrap_socket(sock, self.key_file,
  88. self.cert_file,
  89. cert_reqs=req_cert,
  90. ca_certs=self.ca_certs)
  91. class BindCmdInterpreter(Cmd):
  92. """simple bindctl example."""
  93. def __init__(self, server_port='localhost:8080', pem_file=None,
  94. csv_file_dir=None):
  95. Cmd.__init__(self)
  96. self.location = ""
  97. self.prompt_end = '> '
  98. if sys.stdin.isatty():
  99. self.prompt = self.prompt_end
  100. else:
  101. self.prompt = ""
  102. self.ruler = '-'
  103. self.modules = OrderedDict()
  104. self.add_module_info(ModuleInfo("help", desc = "Get help for bindctl."))
  105. self.server_port = server_port
  106. self.conn = ValidatedHTTPSConnection(self.server_port,
  107. ca_certs=pem_file)
  108. self.session_id = self._get_session_id()
  109. self.config_data = None
  110. if csv_file_dir is not None:
  111. self.csv_file_dir = csv_file_dir
  112. else:
  113. self.csv_file_dir = pwd.getpwnam(getpass.getuser()).pw_dir + \
  114. os.sep + '.bind10' + os.sep
  115. def _print(self, *args):
  116. '''Simple wrapper around calls to print that can be overridden in
  117. unit tests.'''
  118. print(*args)
  119. def _get_session_id(self):
  120. '''Generate one session id for the connection. '''
  121. rand = os.urandom(16)
  122. now = time.time()
  123. session_id = sha1(("%s%s%s" %(rand, now,
  124. socket.gethostname())).encode())
  125. digest = session_id.hexdigest()
  126. return digest
  127. def run(self):
  128. '''Parse commands from user and send them to cmdctl.'''
  129. # Show helper warning about a well known issue. We only do this
  130. # when stdin is attached to a terminal, because otherwise it doesn't
  131. # matter and is just noisy, and could even be harmful if the output
  132. # is processed by a script that expects a specific format.
  133. if my_readline == sys.stdin.readline and sys.stdin.isatty():
  134. sys.stdout.write("""\
  135. WARNING: The Python readline module isn't available, so some command line
  136. editing features (including command history management) will not
  137. work. See the BIND 10 guide for more details.\n\n""")
  138. try:
  139. if not self.login_to_cmdctl():
  140. return 1
  141. self.cmdloop()
  142. self._print('\nExit from bindctl')
  143. return 0
  144. except FailToLogin as err:
  145. # error already printed when this was raised, ignoring
  146. return 1
  147. except KeyboardInterrupt:
  148. self._print('\nExit from bindctl')
  149. return 0
  150. except socket.error as err:
  151. self._print('Failed to send request, the connection is closed')
  152. return 1
  153. except http.client.CannotSendRequest:
  154. self._print('Can not send request, the connection is busy')
  155. return 1
  156. def _get_saved_user_info(self, dir, file_name):
  157. ''' Read all the available username and password pairs saved in
  158. file(path is "dir + file_name"), Return value is one list of elements
  159. ['name', 'password'], If get information failed, empty list will be
  160. returned.'''
  161. if (not dir) or (not os.path.exists(dir)):
  162. return []
  163. try:
  164. csvfile = None
  165. users = []
  166. csvfile = open(dir + file_name)
  167. users_info = csv.reader(csvfile)
  168. for row in users_info:
  169. users.append([row[0], row[1]])
  170. except (IOError, IndexError) as err:
  171. self._print("Error reading saved username and password "
  172. "from %s%s: %s" % (dir, file_name, err))
  173. finally:
  174. if csvfile:
  175. csvfile.close()
  176. return users
  177. def _save_user_info(self, username, passwd, dir, file_name):
  178. ''' Save username and password in file "dir + file_name"
  179. If it's saved properly, return True, or else return False. '''
  180. try:
  181. if not os.path.exists(dir):
  182. os.mkdir(dir, 0o700)
  183. csvfilepath = dir + file_name
  184. csvfile = open(csvfilepath, 'w')
  185. os.chmod(csvfilepath, 0o600)
  186. writer = csv.writer(csvfile)
  187. writer.writerow([username, passwd])
  188. csvfile.close()
  189. except IOError as err:
  190. self._print("Error saving user information:", err)
  191. self._print("user info file name: %s%s" % (dir, file_name))
  192. return False
  193. return True
  194. def _try_login(self, username, password):
  195. '''
  196. Attempts to log into cmdctl by sending a POST with the given
  197. username and password. On success of the POST (not the login,
  198. but the network operation), it returns a tuple (response, data).
  199. We check for some failures such as SSL errors and socket errors
  200. which could happen due to the environment in which BIND 10 runs.
  201. On failure, it raises a FailToLogin exception and prints some
  202. information on the failure. This call is essentially 'private',
  203. but made 'protected' for easier testing.
  204. '''
  205. param = {'username': username, 'password' : password}
  206. try:
  207. response = self.send_POST('/login', param)
  208. data = response.read().decode()
  209. # return here (will raise error after try block)
  210. return (response, data)
  211. except (ssl.SSLError, socket.error) as err:
  212. self._print('Error while sending login information:', err)
  213. pass
  214. raise FailToLogin()
  215. def login_to_cmdctl(self):
  216. '''Login to cmdctl with the username and password given by
  217. the user. After the login is sucessful, the username and
  218. password will be saved in 'default_user.csv', when run the next
  219. time, username and password saved in 'default_user.csv' will be
  220. used first.
  221. '''
  222. # Look at existing username/password combinations and try to log in
  223. users = self._get_saved_user_info(self.csv_file_dir, CSV_FILE_NAME)
  224. for row in users:
  225. response, data = self._try_login(row[0], row[1])
  226. if response.status == http.client.OK:
  227. # Is interactive?
  228. if sys.stdin.isatty():
  229. self._print(data + ' login as ' + row[0])
  230. return True
  231. # No valid logins were found, prompt the user for a username/password
  232. count = 0
  233. if not os.path.exists(self.csv_file_dir + CSV_FILE_NAME):
  234. self._print('\nNo stored password file found.\n\n'
  235. 'When the system is first set up you need to create '
  236. 'at least one user account.\n'
  237. 'For information on how to set up a BIND 10 system, '
  238. 'please check see the\n'
  239. 'BIND 10 Guide: \n\n'
  240. 'http://bind10.isc.org/docs/bind10-guide.html#quick-start-auth-dns\n\n'
  241. 'If a user account has been set up, please check the '
  242. 'b10-cmdctl log for other\n'
  243. 'information.\n')
  244. else:
  245. self._print('Login failed: either the user name or password is '
  246. 'invalid.\n')
  247. # If this was not an interactive session do not prompt for login info.
  248. if not sys.stdin.isatty():
  249. return False
  250. while True:
  251. count = count + 1
  252. if count > 3:
  253. self._print("Too many authentication failures")
  254. return False
  255. username = input("Username: ")
  256. passwd = getpass.getpass()
  257. response, data = self._try_login(username, passwd)
  258. self._print(data)
  259. if response.status == http.client.OK:
  260. self._save_user_info(username, passwd, self.csv_file_dir,
  261. CSV_FILE_NAME)
  262. return True
  263. def _update_commands(self):
  264. '''Update the commands of all modules. '''
  265. for module_name in self.config_data.get_config_item_list():
  266. self._prepare_module_commands(self.config_data.get_module_spec(module_name))
  267. def _send_message(self, url, body):
  268. headers = {"cookie" : self.session_id}
  269. self.conn.request('GET', url, body, headers)
  270. res = self.conn.getresponse()
  271. return res.status, res.read()
  272. def send_GET(self, url, body = None):
  273. '''Send GET request to cmdctl, session id is send with the name
  274. 'cookie' in header.
  275. '''
  276. status, reply_msg = self._send_message(url, body)
  277. if status == http.client.UNAUTHORIZED:
  278. if self.login_to_cmdctl():
  279. # successful, so try send again
  280. status, reply_msg = self._send_message(url, body)
  281. if reply_msg:
  282. return json.loads(reply_msg.decode())
  283. else:
  284. return {}
  285. def send_POST(self, url, post_param=None):
  286. '''Send POST request to cmdctl, session id is send with the name
  287. 'cookie' in header.
  288. Format: /module_name/command_name
  289. parameters of command is encoded as a map
  290. '''
  291. param = None
  292. if post_param is not None and len(post_param) != 0:
  293. param = json.dumps(post_param)
  294. headers = {"cookie" : self.session_id}
  295. self.conn.request('POST', url, param, headers)
  296. return self.conn.getresponse()
  297. def _update_all_modules_info(self):
  298. ''' Get all modules' information from cmdctl, including
  299. specification file and configuration data. This function
  300. should be called before interpreting command line or complete-key
  301. is entered. This may not be the best way to keep bindctl
  302. and cmdctl share same modules information, but it works.'''
  303. if self.config_data is not None:
  304. self.config_data.update_specs_and_config()
  305. else:
  306. self.config_data = isc.config.UIModuleCCSession(self)
  307. self._update_commands()
  308. def precmd(self, line):
  309. if line != 'EOF':
  310. self._update_all_modules_info()
  311. return line
  312. def postcmd(self, stop, line):
  313. '''Update the prompt after every command, but only if we
  314. have a tty as output'''
  315. if sys.stdin.isatty():
  316. self.prompt = self.location + self.prompt_end
  317. return stop
  318. def _prepare_module_commands(self, module_spec):
  319. '''Prepare the module commands'''
  320. module = ModuleInfo(name = module_spec.get_module_name(),
  321. desc = module_spec.get_module_description())
  322. for command in module_spec.get_commands_spec():
  323. cmd = CommandInfo(name = command["command_name"],
  324. desc = command["command_description"])
  325. for arg in command["command_args"]:
  326. param = ParamInfo(name = arg["item_name"],
  327. type = arg["item_type"],
  328. optional = bool(arg["item_optional"]),
  329. param_spec = arg)
  330. if ("item_default" in arg):
  331. param.default = arg["item_default"]
  332. if ("item_description" in arg):
  333. param.desc = arg["item_description"]
  334. cmd.add_param(param)
  335. module.add_command(cmd)
  336. self.add_module_info(module)
  337. def _validate_cmd(self, cmd):
  338. '''validate the parameters and merge some parameters together,
  339. merge algorithm is based on the command line syntax, later, if
  340. a better command line syntax come out, this function should be
  341. updated first.
  342. '''
  343. if not cmd.module in self.modules:
  344. raise CmdUnknownModuleSyntaxError(cmd.module)
  345. module_info = self.modules[cmd.module]
  346. if not module_info.has_command_with_name(cmd.command):
  347. raise CmdUnknownCmdSyntaxError(cmd.module, cmd.command)
  348. command_info = module_info.get_command_with_name(cmd.command)
  349. manda_params = command_info.get_mandatory_param_names()
  350. all_params = command_info.get_param_names()
  351. # If help is entered, don't do further parameter validation.
  352. for val in cmd.params.keys():
  353. if val == "help":
  354. return
  355. params = cmd.params.copy()
  356. if not params and manda_params:
  357. raise CmdMissParamSyntaxError(cmd.module, cmd.command, manda_params[0])
  358. elif params and not all_params:
  359. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command,
  360. list(params.keys())[0])
  361. elif params:
  362. param_name = None
  363. param_count = len(params)
  364. for name in params:
  365. # either the name of the parameter must be known, or
  366. # the 'name' must be an integer (ie. the position of
  367. # an unnamed argument
  368. if type(name) == int:
  369. # lump all extraneous arguments together as one big final one
  370. # todo: check if last param type is a string?
  371. while (param_count > 2 and
  372. param_count > len(command_info.params) - 1):
  373. params[param_count - 2] += " " + params[param_count - 1]
  374. del(params[param_count - 1])
  375. param_count = len(params)
  376. cmd.params = params.copy()
  377. # (-1, help is always in the all_params list)
  378. if name >= len(all_params) - 1:
  379. # add to last known param
  380. if param_name:
  381. cmd.params[param_name] += cmd.params[name]
  382. else:
  383. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command, cmd.params[name])
  384. else:
  385. # replace the numbered items by named items
  386. param_name = command_info.get_param_name_by_position(name, param_count)
  387. cmd.params[param_name] = cmd.params[name]
  388. del cmd.params[name]
  389. elif not name in all_params:
  390. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command, name)
  391. param_nr = 0
  392. for name in manda_params:
  393. if not name in params and not param_nr in params:
  394. raise CmdMissParamSyntaxError(cmd.module, cmd.command, name)
  395. param_nr += 1
  396. # Convert parameter value according parameter spec file.
  397. # Ignore check for commands belongs to module 'config' or 'execute
  398. if cmd.module != CONFIG_MODULE_NAME and\
  399. cmd.module != command_sets.EXECUTE_MODULE_NAME:
  400. for param_name in cmd.params:
  401. param_spec = command_info.get_param_with_name(param_name).param_spec
  402. try:
  403. cmd.params[param_name] = isc.config.config_data.convert_type(param_spec, cmd.params[param_name])
  404. except isc.cc.data.DataTypeError as e:
  405. raise isc.cc.data.DataTypeError('Invalid parameter value for \"%s\", the type should be \"%s\" \n'
  406. % (param_name, param_spec['item_type']) + str(e))
  407. def _handle_cmd(self, cmd):
  408. '''Handle a command entered by the user'''
  409. if cmd.command == "help" or ("help" in cmd.params.keys()):
  410. self._handle_help(cmd)
  411. elif cmd.module == CONFIG_MODULE_NAME:
  412. self.apply_config_cmd(cmd)
  413. elif cmd.module == command_sets.EXECUTE_MODULE_NAME:
  414. self.apply_execute_cmd(cmd)
  415. else:
  416. self.apply_cmd(cmd)
  417. def add_module_info(self, module_info):
  418. '''Add the information about one module'''
  419. self.modules[module_info.name] = module_info
  420. def get_module_names(self):
  421. '''Return the names of all known modules'''
  422. return list(self.modules.keys())
  423. #override methods in cmd
  424. def default(self, line):
  425. self._parse_cmd(line)
  426. def emptyline(self):
  427. pass
  428. def do_help(self, name):
  429. self._print(CONST_BINDCTL_HELP)
  430. for k in self.modules.values():
  431. n = k.get_name()
  432. if len(n) >= CONST_BINDCTL_HELP_INDENT_WIDTH:
  433. self._print(" %s" % n)
  434. self._print(textwrap.fill(k.get_desc(),
  435. initial_indent=" ",
  436. subsequent_indent=" " +
  437. " " * CONST_BINDCTL_HELP_INDENT_WIDTH,
  438. width=70))
  439. else:
  440. self._print(textwrap.fill("%s%s%s" %
  441. (k.get_name(),
  442. " "*(CONST_BINDCTL_HELP_INDENT_WIDTH -
  443. len(k.get_name())),
  444. k.get_desc()),
  445. initial_indent=" ",
  446. subsequent_indent=" " +
  447. " " * CONST_BINDCTL_HELP_INDENT_WIDTH,
  448. width=70))
  449. def onecmd(self, line):
  450. if line == 'EOF' or line.lower() == "quit":
  451. self.conn.close()
  452. return True
  453. if line == 'h':
  454. line = 'help'
  455. Cmd.onecmd(self, line)
  456. def _get_identifier_startswith(self, id_text):
  457. """Return the tab-completion hints for identifiers starting with
  458. id_text.
  459. Parameters:
  460. id_text (string): the currently entered identifier part, which
  461. is to be completed.
  462. """
  463. # Strip starting "/" from id_text
  464. if id_text.startswith('/'):
  465. id_text = id_text[1:]
  466. # Get all items from the given module (up to the first /)
  467. list = self.config_data.get_config_item_list(
  468. id_text.rpartition("/")[0], recurse=True)
  469. # filter out all possibilities that don't match currently entered
  470. # text part
  471. hints = [val for val in list if val.startswith(id_text)]
  472. return hints
  473. def _cmd_has_identifier_param(self, cmd):
  474. """
  475. Returns True if the given (parsed) command is known and has a
  476. parameter which points to a config data identifier
  477. Parameters:
  478. cmd (cmdparse.BindCmdParser): command context, including given params
  479. """
  480. if cmd.module not in self.modules:
  481. return False
  482. command = self.modules[cmd.module].get_command_with_name(cmd.command)
  483. return command.has_param_with_name(CFGITEM_IDENTIFIER_PARAM)
  484. def complete(self, text, state):
  485. """
  486. Returns tab-completion hints. See the python documentation of the
  487. readline and Cmd modules for more information.
  488. The first time this is called (within one 'completer' action), it
  489. has state 0, and a list of possible completions is made. This list
  490. is stored; complete() will then be called with increasing values of
  491. state, until it returns None. For each call it returns the state'th
  492. element of the hints it collected in the first call.
  493. The hints list contents depend on which part of the full command
  494. line; if no module is given yet, it will list all modules. If a
  495. module is given, but no command, it will complete with module
  496. commands. If both have been given, it will create the hints based on
  497. the command parameters.
  498. If module and command have already been specified, and the command
  499. has a parameter 'identifier', the configuration data is used to
  500. create the hints list.
  501. Parameters:
  502. text (string): The text entered so far in the 'current' part of
  503. the command (module, command, parameters)
  504. state (int): state used in the readline tab-completion logic;
  505. 0 on first call, increasing by one until there are
  506. no (more) hints to return.
  507. Returns the string value of the hints list with index 'state',
  508. or None if no (more) hints are available.
  509. """
  510. if state == 0:
  511. self._update_all_modules_info()
  512. text = text.strip()
  513. hints = []
  514. cur_line = my_readline()
  515. try:
  516. cmd = BindCmdParser(cur_line)
  517. if not cmd.params and text:
  518. hints = self._get_command_startswith(cmd.module, text)
  519. elif self._cmd_has_identifier_param(cmd):
  520. # If the command has an argument that is a configuration
  521. # identifier (currently, this is only a subset of
  522. # the config commands), then don't tab-complete with
  523. # hints derived from command parameters, but from
  524. # possible configuration identifiers.
  525. #
  526. # This solves the issue reported in #2254, where
  527. # there were hints such as 'argument' and 'identifier'.
  528. #
  529. # Since they are replaced, the tab-completion no longer
  530. # adds 'help' as an option (but it still works)
  531. #
  532. # Also, currently, tab-completion does not work
  533. # together with 'config go' (it does not take 'current
  534. # position' into account). But config go currently has
  535. # problems by itself, unrelated to completion.
  536. hints = self._get_identifier_startswith(text)
  537. else:
  538. hints = self._get_param_startswith(cmd.module, cmd.command,
  539. text)
  540. except CmdModuleNameFormatError:
  541. if not text:
  542. hints = self.get_module_names()
  543. except CmdMissCommandNameFormatError as e:
  544. if not text.strip(): # command name is empty
  545. hints = self.modules[e.module].get_command_names()
  546. else:
  547. hints = self._get_module_startswith(text)
  548. except CmdCommandNameFormatError as e:
  549. if e.module in self.modules:
  550. hints = self._get_command_startswith(e.module, text)
  551. except CmdParamFormatError as e:
  552. hints = self._get_param_startswith(e.module, e.command, text)
  553. except BindCtlException:
  554. hints = []
  555. self.hint = hints
  556. if state < len(self.hint):
  557. return self.hint[state]
  558. else:
  559. return None
  560. def _get_module_startswith(self, text):
  561. return [module
  562. for module in self.modules
  563. if module.startswith(text)]
  564. def _get_command_startswith(self, module, text):
  565. if module in self.modules:
  566. return [command
  567. for command in self.modules[module].get_command_names()
  568. if command.startswith(text)]
  569. return []
  570. def _get_param_startswith(self, module, command, text):
  571. if module in self.modules:
  572. module_info = self.modules[module]
  573. if command in module_info.get_command_names():
  574. cmd_info = module_info.get_command_with_name(command)
  575. params = cmd_info.get_param_names()
  576. hint = []
  577. if text:
  578. hint = [val for val in params if val.startswith(text)]
  579. else:
  580. hint = list(params)
  581. if len(hint) == 1 and hint[0] != "help":
  582. hint[0] = hint[0] + " ="
  583. return hint
  584. return []
  585. def _parse_cmd(self, line):
  586. try:
  587. cmd = BindCmdParser(line)
  588. self._validate_cmd(cmd)
  589. self._handle_cmd(cmd)
  590. except (IOError, http.client.HTTPException) as err:
  591. self._print('Error: ', err)
  592. except BindCtlException as err:
  593. self._print("Error! ", err)
  594. self._print_correct_usage(err)
  595. except isc.cc.data.DataTypeError as err:
  596. self._print("Error! ", err)
  597. except isc.cc.data.DataTypeError as dte:
  598. self._print("Error: " + str(dte))
  599. except isc.cc.data.DataNotFoundError as dnfe:
  600. self._print("Error: " + str(dnfe))
  601. except isc.cc.data.DataAlreadyPresentError as dape:
  602. self._print("Error: " + str(dape))
  603. except KeyError as ke:
  604. self._print("Error: missing " + str(ke))
  605. def _print_correct_usage(self, ept):
  606. if isinstance(ept, CmdUnknownModuleSyntaxError):
  607. self.do_help(None)
  608. elif isinstance(ept, CmdUnknownCmdSyntaxError):
  609. self.modules[ept.module].module_help()
  610. elif isinstance(ept, CmdMissParamSyntaxError) or \
  611. isinstance(ept, CmdUnknownParamSyntaxError):
  612. self.modules[ept.module].command_help(ept.command)
  613. def _append_space_to_hint(self):
  614. """Append one space at the end of complete hint."""
  615. self.hint = [(val + " ") for val in self.hint]
  616. def _handle_help(self, cmd):
  617. if cmd.command == "help":
  618. self.modules[cmd.module].module_help()
  619. else:
  620. self.modules[cmd.module].command_help(cmd.command)
  621. def apply_config_cmd(self, cmd):
  622. '''Handles a configuration command.
  623. Raises a DataTypeError if a wrong value is set.
  624. Raises a DataNotFoundError if a wrong identifier is used.
  625. Raises a KeyError if the command was not complete
  626. '''
  627. identifier = self.location
  628. if 'identifier' in cmd.params:
  629. if not identifier.endswith("/"):
  630. identifier += "/"
  631. if cmd.params['identifier'].startswith("/"):
  632. identifier = cmd.params['identifier']
  633. else:
  634. if cmd.params['identifier'].startswith('['):
  635. identifier = identifier[:-1]
  636. identifier += cmd.params['identifier']
  637. # Check if the module is known; for unknown modules
  638. # we currently deny setting preferences, as we have
  639. # no way yet to determine if they are ok.
  640. module_name = identifier.split('/')[1]
  641. if module_name != "" and (self.config_data is None or \
  642. not self.config_data.have_specification(module_name)):
  643. self._print("Error: Module '" + module_name +
  644. "' unknown or not running")
  645. return
  646. if cmd.command == "show":
  647. # check if we have the 'all' argument
  648. show_all = False
  649. if 'argument' in cmd.params:
  650. if cmd.params['argument'] == 'all':
  651. show_all = True
  652. elif 'identifier' not in cmd.params:
  653. # no 'all', no identifier, assume this is the
  654. #identifier
  655. identifier += cmd.params['argument']
  656. else:
  657. self._print("Error: unknown argument " +
  658. cmd.params['argument'] +
  659. ", or multiple identifiers given")
  660. return
  661. values = self.config_data.get_value_maps(identifier, show_all)
  662. for value_map in values:
  663. line = value_map['name']
  664. if value_map['type'] in [ 'module', 'map' ]:
  665. line += "/"
  666. elif value_map['type'] == 'list' \
  667. and value_map['value'] != []:
  668. # do not print content of non-empty lists if
  669. # we have more data to show
  670. line += "/"
  671. else:
  672. # if type is named_set, don't print value if None
  673. # (it is either {} meaning empty, or None, meaning
  674. # there actually is data, but not to be shown with
  675. # the current command
  676. if value_map['type'] == 'named_set' and\
  677. value_map['value'] is None:
  678. line += "/\t"
  679. else:
  680. line += "\t" + json.dumps(value_map['value'])
  681. line += "\t" + value_map['type']
  682. line += "\t"
  683. if value_map['default']:
  684. line += "(default)"
  685. if value_map['modified']:
  686. line += "(modified)"
  687. self._print(line)
  688. elif cmd.command == "show_json":
  689. if identifier == "":
  690. self._print("Need at least the module to show the "
  691. "configuration in JSON format")
  692. else:
  693. data, default = self.config_data.get_value(identifier)
  694. self._print(json.dumps(data))
  695. elif cmd.command == "add":
  696. self.config_data.add_value(identifier,
  697. cmd.params.get('value_or_name'),
  698. cmd.params.get('value_for_set'))
  699. elif cmd.command == "remove":
  700. if 'value' in cmd.params:
  701. self.config_data.remove_value(identifier, cmd.params['value'])
  702. else:
  703. self.config_data.remove_value(identifier, None)
  704. elif cmd.command == "set":
  705. if 'identifier' not in cmd.params:
  706. self._print("Error: missing identifier or value")
  707. else:
  708. parsed_value = None
  709. try:
  710. parsed_value = json.loads(cmd.params['value'])
  711. except Exception as exc:
  712. # ok could be an unquoted string, interpret as such
  713. parsed_value = cmd.params['value']
  714. self.config_data.set_value(identifier, parsed_value)
  715. elif cmd.command == "unset":
  716. self.config_data.unset(identifier)
  717. elif cmd.command == "revert":
  718. self.config_data.clear_local_changes()
  719. elif cmd.command == "commit":
  720. try:
  721. self.config_data.commit()
  722. except isc.config.ModuleCCSessionError as mcse:
  723. self._print(str(mcse))
  724. elif cmd.command == "diff":
  725. self._print(self.config_data.get_local_changes())
  726. elif cmd.command == "go":
  727. self.go(identifier)
  728. def go(self, identifier):
  729. '''Handles the config go command, change the 'current' location
  730. within the configuration tree. '..' will be interpreted as
  731. 'up one level'.'''
  732. id_parts = isc.cc.data.split_identifier(identifier)
  733. new_location = ""
  734. for id_part in id_parts:
  735. if (id_part == ".."):
  736. # go 'up' one level
  737. new_location, a, b = new_location.rpartition("/")
  738. else:
  739. new_location += "/" + id_part
  740. # check if exists, if not, revert and error
  741. v,d = self.config_data.get_value(new_location)
  742. if v is None:
  743. self._print("Error: " + identifier + " not found")
  744. return
  745. self.location = new_location
  746. def apply_execute_cmd(self, command):
  747. '''Handles the 'execute' command, which executes a number of
  748. (preset) statements. The command set to execute is either
  749. read from a file (e.g. 'execute file <file>'.) or one
  750. of the sets as defined in command_sets.py'''
  751. if command.command == 'file':
  752. try:
  753. with open(command.params['filename']) as command_file:
  754. commands = command_file.readlines()
  755. except IOError as ioe:
  756. self._print("Error: " + str(ioe))
  757. return
  758. elif command_sets.has_command_set(command.command):
  759. commands = command_sets.get_commands(command.command)
  760. else:
  761. # Should not be reachable; parser should've caught this
  762. raise Exception("Unknown execute command type " + command.command)
  763. # We have our set of commands now, depending on whether 'show' was
  764. # specified, show or execute them
  765. if 'show' in command.params and command.params['show'] == 'show':
  766. self.__show_execute_commands(commands)
  767. else:
  768. self.__apply_execute_commands(commands)
  769. def __show_execute_commands(self, commands):
  770. '''Prints the command list without executing them'''
  771. for line in commands:
  772. self._print(line.strip())
  773. def __apply_execute_commands(self, commands):
  774. '''Applies the configuration commands from the given iterator.
  775. This is the method that catches, comments, echo statements, and
  776. other directives. All commands not filtered by this method are
  777. interpreted as if they are directly entered in an active session.
  778. Lines starting with any of the following characters are not
  779. passed directly:
  780. # - These are comments
  781. ! - These are directives
  782. !echo: print the rest of the line
  783. !verbose on/off: print the commands themselves too
  784. Unknown directives are ignored (with a warning)
  785. The execution is stopped if there are any errors.
  786. '''
  787. verbose = False
  788. try:
  789. for line in commands:
  790. line = line.strip()
  791. if verbose:
  792. self._print(line)
  793. if line.startswith('#') or len(line) == 0:
  794. continue
  795. elif line.startswith('!'):
  796. if re.match('^!echo ', line, re.I) and len(line) > 6:
  797. self._print(line[6:])
  798. elif re.match('^!verbose\s+on\s*$', line, re.I):
  799. verbose = True
  800. elif re.match('^!verbose\s+off$', line, re.I):
  801. verbose = False
  802. else:
  803. self._print("Warning: ignoring unknown directive: " +
  804. line)
  805. else:
  806. cmd = BindCmdParser(line)
  807. self._validate_cmd(cmd)
  808. self._handle_cmd(cmd)
  809. except (isc.config.ModuleCCSessionError,
  810. IOError, http.client.HTTPException,
  811. BindCtlException, isc.cc.data.DataTypeError,
  812. isc.cc.data.DataNotFoundError,
  813. isc.cc.data.DataAlreadyPresentError,
  814. KeyError) as err:
  815. self._print('Error: ', err)
  816. self._print()
  817. self._print('Depending on the contents of the script, and which')
  818. self._print('commands it has called, there can be committed and')
  819. self._print('local changes. It is advised to check your settings')
  820. self._print(', and revert local changes with "config revert".')
  821. def apply_cmd(self, cmd):
  822. '''Handles a general module command'''
  823. url = '/' + cmd.module + '/' + cmd.command
  824. cmd_params = None
  825. if (len(cmd.params) != 0):
  826. cmd_params = json.dumps(cmd.params)
  827. reply = self.send_POST(url, cmd.params)
  828. data = reply.read().decode()
  829. # The reply is a string containing JSON data,
  830. # parse it, then prettyprint
  831. if data != "" and data != "{}":
  832. self._print(json.dumps(json.loads(data), sort_keys=True,
  833. indent=4))