bindcmd.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  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. while True:
  248. count = count + 1
  249. if count > 3:
  250. self._print("Too many authentication failures")
  251. return False
  252. username = input("Username: ")
  253. passwd = getpass.getpass()
  254. response, data = self._try_login(username, passwd)
  255. self._print(data)
  256. if response.status == http.client.OK:
  257. self._save_user_info(username, passwd, self.csv_file_dir,
  258. CSV_FILE_NAME)
  259. return True
  260. def _update_commands(self):
  261. '''Update the commands of all modules. '''
  262. for module_name in self.config_data.get_config_item_list():
  263. self._prepare_module_commands(self.config_data.get_module_spec(module_name))
  264. def _send_message(self, url, body):
  265. headers = {"cookie" : self.session_id}
  266. self.conn.request('GET', url, body, headers)
  267. res = self.conn.getresponse()
  268. return res.status, res.read()
  269. def send_GET(self, url, body = None):
  270. '''Send GET request to cmdctl, session id is send with the name
  271. 'cookie' in header.
  272. '''
  273. status, reply_msg = self._send_message(url, body)
  274. if status == http.client.UNAUTHORIZED:
  275. if self.login_to_cmdctl():
  276. # successful, so try send again
  277. status, reply_msg = self._send_message(url, body)
  278. if reply_msg:
  279. return json.loads(reply_msg.decode())
  280. else:
  281. return {}
  282. def send_POST(self, url, post_param=None):
  283. '''Send POST request to cmdctl, session id is send with the name
  284. 'cookie' in header.
  285. Format: /module_name/command_name
  286. parameters of command is encoded as a map
  287. '''
  288. param = None
  289. if post_param is not None and len(post_param) != 0:
  290. param = json.dumps(post_param)
  291. headers = {"cookie" : self.session_id}
  292. self.conn.request('POST', url, param, headers)
  293. return self.conn.getresponse()
  294. def _update_all_modules_info(self):
  295. ''' Get all modules' information from cmdctl, including
  296. specification file and configuration data. This function
  297. should be called before interpreting command line or complete-key
  298. is entered. This may not be the best way to keep bindctl
  299. and cmdctl share same modules information, but it works.'''
  300. if self.config_data is not None:
  301. self.config_data.update_specs_and_config()
  302. else:
  303. self.config_data = isc.config.UIModuleCCSession(self)
  304. self._update_commands()
  305. def precmd(self, line):
  306. if line != 'EOF':
  307. self._update_all_modules_info()
  308. return line
  309. def postcmd(self, stop, line):
  310. '''Update the prompt after every command, but only if we
  311. have a tty as output'''
  312. if sys.stdin.isatty():
  313. self.prompt = self.location + self.prompt_end
  314. return stop
  315. def _prepare_module_commands(self, module_spec):
  316. '''Prepare the module commands'''
  317. module = ModuleInfo(name = module_spec.get_module_name(),
  318. desc = module_spec.get_module_description())
  319. for command in module_spec.get_commands_spec():
  320. cmd = CommandInfo(name = command["command_name"],
  321. desc = command["command_description"])
  322. for arg in command["command_args"]:
  323. param = ParamInfo(name = arg["item_name"],
  324. type = arg["item_type"],
  325. optional = bool(arg["item_optional"]),
  326. param_spec = arg)
  327. if ("item_default" in arg):
  328. param.default = arg["item_default"]
  329. if ("item_description" in arg):
  330. param.desc = arg["item_description"]
  331. cmd.add_param(param)
  332. module.add_command(cmd)
  333. self.add_module_info(module)
  334. def _validate_cmd(self, cmd):
  335. '''validate the parameters and merge some parameters together,
  336. merge algorithm is based on the command line syntax, later, if
  337. a better command line syntax come out, this function should be
  338. updated first.
  339. '''
  340. if not cmd.module in self.modules:
  341. raise CmdUnknownModuleSyntaxError(cmd.module)
  342. module_info = self.modules[cmd.module]
  343. if not module_info.has_command_with_name(cmd.command):
  344. raise CmdUnknownCmdSyntaxError(cmd.module, cmd.command)
  345. command_info = module_info.get_command_with_name(cmd.command)
  346. manda_params = command_info.get_mandatory_param_names()
  347. all_params = command_info.get_param_names()
  348. # If help is entered, don't do further parameter validation.
  349. for val in cmd.params.keys():
  350. if val == "help":
  351. return
  352. params = cmd.params.copy()
  353. if not params and manda_params:
  354. raise CmdMissParamSyntaxError(cmd.module, cmd.command, manda_params[0])
  355. elif params and not all_params:
  356. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command,
  357. list(params.keys())[0])
  358. elif params:
  359. param_name = None
  360. param_count = len(params)
  361. for name in params:
  362. # either the name of the parameter must be known, or
  363. # the 'name' must be an integer (ie. the position of
  364. # an unnamed argument
  365. if type(name) == int:
  366. # lump all extraneous arguments together as one big final one
  367. # todo: check if last param type is a string?
  368. while (param_count > 2 and
  369. param_count > len(command_info.params) - 1):
  370. params[param_count - 2] += " " + params[param_count - 1]
  371. del(params[param_count - 1])
  372. param_count = len(params)
  373. cmd.params = params.copy()
  374. # (-1, help is always in the all_params list)
  375. if name >= len(all_params) - 1:
  376. # add to last known param
  377. if param_name:
  378. cmd.params[param_name] += cmd.params[name]
  379. else:
  380. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command, cmd.params[name])
  381. else:
  382. # replace the numbered items by named items
  383. param_name = command_info.get_param_name_by_position(name, param_count)
  384. cmd.params[param_name] = cmd.params[name]
  385. del cmd.params[name]
  386. elif not name in all_params:
  387. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command, name)
  388. param_nr = 0
  389. for name in manda_params:
  390. if not name in params and not param_nr in params:
  391. raise CmdMissParamSyntaxError(cmd.module, cmd.command, name)
  392. param_nr += 1
  393. # Convert parameter value according parameter spec file.
  394. # Ignore check for commands belongs to module 'config' or 'execute
  395. if cmd.module != CONFIG_MODULE_NAME and\
  396. cmd.module != command_sets.EXECUTE_MODULE_NAME:
  397. for param_name in cmd.params:
  398. param_spec = command_info.get_param_with_name(param_name).param_spec
  399. try:
  400. cmd.params[param_name] = isc.config.config_data.convert_type(param_spec, cmd.params[param_name])
  401. except isc.cc.data.DataTypeError as e:
  402. raise isc.cc.data.DataTypeError('Invalid parameter value for \"%s\", the type should be \"%s\" \n'
  403. % (param_name, param_spec['item_type']) + str(e))
  404. def _handle_cmd(self, cmd):
  405. '''Handle a command entered by the user'''
  406. if cmd.command == "help" or ("help" in cmd.params.keys()):
  407. self._handle_help(cmd)
  408. elif cmd.module == CONFIG_MODULE_NAME:
  409. self.apply_config_cmd(cmd)
  410. elif cmd.module == command_sets.EXECUTE_MODULE_NAME:
  411. self.apply_execute_cmd(cmd)
  412. else:
  413. self.apply_cmd(cmd)
  414. def add_module_info(self, module_info):
  415. '''Add the information about one module'''
  416. self.modules[module_info.name] = module_info
  417. def get_module_names(self):
  418. '''Return the names of all known modules'''
  419. return list(self.modules.keys())
  420. #override methods in cmd
  421. def default(self, line):
  422. self._parse_cmd(line)
  423. def emptyline(self):
  424. pass
  425. def do_help(self, name):
  426. self._print(CONST_BINDCTL_HELP)
  427. for k in self.modules.values():
  428. n = k.get_name()
  429. if len(n) >= CONST_BINDCTL_HELP_INDENT_WIDTH:
  430. self._print(" %s" % n)
  431. self._print(textwrap.fill(k.get_desc(),
  432. initial_indent=" ",
  433. subsequent_indent=" " +
  434. " " * CONST_BINDCTL_HELP_INDENT_WIDTH,
  435. width=70))
  436. else:
  437. self._print(textwrap.fill("%s%s%s" %
  438. (k.get_name(),
  439. " "*(CONST_BINDCTL_HELP_INDENT_WIDTH -
  440. len(k.get_name())),
  441. k.get_desc()),
  442. initial_indent=" ",
  443. subsequent_indent=" " +
  444. " " * CONST_BINDCTL_HELP_INDENT_WIDTH,
  445. width=70))
  446. def onecmd(self, line):
  447. if line == 'EOF' or line.lower() == "quit":
  448. self.conn.close()
  449. return True
  450. if line == 'h':
  451. line = 'help'
  452. Cmd.onecmd(self, line)
  453. def _get_identifier_startswith(self, id_text):
  454. """Return the tab-completion hints for identifiers starting with
  455. id_text.
  456. Parameters:
  457. id_text (string): the currently entered identifier part, which
  458. is to be completed.
  459. """
  460. # Strip starting "/" from id_text
  461. if id_text.startswith('/'):
  462. id_text = id_text[1:]
  463. # Get all items from the given module (up to the first /)
  464. list = self.config_data.get_config_item_list(
  465. id_text.rpartition("/")[0], recurse=True)
  466. # filter out all possibilities that don't match currently entered
  467. # text part
  468. hints = [val for val in list if val.startswith(id_text)]
  469. return hints
  470. def _cmd_has_identifier_param(self, cmd):
  471. """
  472. Returns True if the given (parsed) command is known and has a
  473. parameter which points to a config data identifier
  474. Parameters:
  475. cmd (cmdparse.BindCmdParser): command context, including given params
  476. """
  477. if cmd.module not in self.modules:
  478. return False
  479. command = self.modules[cmd.module].get_command_with_name(cmd.command)
  480. return command.has_param_with_name(CFGITEM_IDENTIFIER_PARAM)
  481. def complete(self, text, state):
  482. """
  483. Returns tab-completion hints. See the python documentation of the
  484. readline and Cmd modules for more information.
  485. The first time this is called (within one 'completer' action), it
  486. has state 0, and a list of possible completions is made. This list
  487. is stored; complete() will then be called with increasing values of
  488. state, until it returns None. For each call it returns the state'th
  489. element of the hints it collected in the first call.
  490. The hints list contents depend on which part of the full command
  491. line; if no module is given yet, it will list all modules. If a
  492. module is given, but no command, it will complete with module
  493. commands. If both have been given, it will create the hints based on
  494. the command parameters.
  495. If module and command have already been specified, and the command
  496. has a parameter 'identifier', the configuration data is used to
  497. create the hints list.
  498. Parameters:
  499. text (string): The text entered so far in the 'current' part of
  500. the command (module, command, parameters)
  501. state (int): state used in the readline tab-completion logic;
  502. 0 on first call, increasing by one until there are
  503. no (more) hints to return.
  504. Returns the string value of the hints list with index 'state',
  505. or None if no (more) hints are available.
  506. """
  507. if state == 0:
  508. self._update_all_modules_info()
  509. text = text.strip()
  510. hints = []
  511. cur_line = my_readline()
  512. try:
  513. cmd = BindCmdParser(cur_line)
  514. if not cmd.params and text:
  515. hints = self._get_command_startswith(cmd.module, text)
  516. elif self._cmd_has_identifier_param(cmd):
  517. # If the command has an argument that is a configuration
  518. # identifier (currently, this is only a subset of
  519. # the config commands), then don't tab-complete with
  520. # hints derived from command parameters, but from
  521. # possible configuration identifiers.
  522. #
  523. # This solves the issue reported in #2254, where
  524. # there were hints such as 'argument' and 'identifier'.
  525. #
  526. # Since they are replaced, the tab-completion no longer
  527. # adds 'help' as an option (but it still works)
  528. #
  529. # Also, currently, tab-completion does not work
  530. # together with 'config go' (it does not take 'current
  531. # position' into account). But config go currently has
  532. # problems by itself, unrelated to completion.
  533. hints = self._get_identifier_startswith(text)
  534. else:
  535. hints = self._get_param_startswith(cmd.module, cmd.command,
  536. text)
  537. except CmdModuleNameFormatError:
  538. if not text:
  539. hints = self.get_module_names()
  540. except CmdMissCommandNameFormatError as e:
  541. if not text.strip(): # command name is empty
  542. hints = self.modules[e.module].get_command_names()
  543. else:
  544. hints = self._get_module_startswith(text)
  545. except CmdCommandNameFormatError as e:
  546. if e.module in self.modules:
  547. hints = self._get_command_startswith(e.module, text)
  548. except CmdParamFormatError as e:
  549. hints = self._get_param_startswith(e.module, e.command, text)
  550. except BindCtlException:
  551. hints = []
  552. self.hint = hints
  553. if state < len(self.hint):
  554. return self.hint[state]
  555. else:
  556. return None
  557. def _get_module_startswith(self, text):
  558. return [module
  559. for module in self.modules
  560. if module.startswith(text)]
  561. def _get_command_startswith(self, module, text):
  562. if module in self.modules:
  563. return [command
  564. for command in self.modules[module].get_command_names()
  565. if command.startswith(text)]
  566. return []
  567. def _get_param_startswith(self, module, command, text):
  568. if module in self.modules:
  569. module_info = self.modules[module]
  570. if command in module_info.get_command_names():
  571. cmd_info = module_info.get_command_with_name(command)
  572. params = cmd_info.get_param_names()
  573. hint = []
  574. if text:
  575. hint = [val for val in params if val.startswith(text)]
  576. else:
  577. hint = list(params)
  578. if len(hint) == 1 and hint[0] != "help":
  579. hint[0] = hint[0] + " ="
  580. return hint
  581. return []
  582. def _parse_cmd(self, line):
  583. try:
  584. cmd = BindCmdParser(line)
  585. self._validate_cmd(cmd)
  586. self._handle_cmd(cmd)
  587. except (IOError, http.client.HTTPException) as err:
  588. self._print('Error: ', err)
  589. except BindCtlException as err:
  590. self._print("Error! ", err)
  591. self._print_correct_usage(err)
  592. except isc.cc.data.DataTypeError as err:
  593. self._print("Error! ", err)
  594. except isc.cc.data.DataTypeError as dte:
  595. self._print("Error: " + str(dte))
  596. except isc.cc.data.DataNotFoundError as dnfe:
  597. self._print("Error: " + str(dnfe))
  598. except isc.cc.data.DataAlreadyPresentError as dape:
  599. self._print("Error: " + str(dape))
  600. except KeyError as ke:
  601. self._print("Error: missing " + str(ke))
  602. def _print_correct_usage(self, ept):
  603. if isinstance(ept, CmdUnknownModuleSyntaxError):
  604. self.do_help(None)
  605. elif isinstance(ept, CmdUnknownCmdSyntaxError):
  606. self.modules[ept.module].module_help()
  607. elif isinstance(ept, CmdMissParamSyntaxError) or \
  608. isinstance(ept, CmdUnknownParamSyntaxError):
  609. self.modules[ept.module].command_help(ept.command)
  610. def _append_space_to_hint(self):
  611. """Append one space at the end of complete hint."""
  612. self.hint = [(val + " ") for val in self.hint]
  613. def _handle_help(self, cmd):
  614. if cmd.command == "help":
  615. self.modules[cmd.module].module_help()
  616. else:
  617. self.modules[cmd.module].command_help(cmd.command)
  618. def apply_config_cmd(self, cmd):
  619. '''Handles a configuration command.
  620. Raises a DataTypeError if a wrong value is set.
  621. Raises a DataNotFoundError if a wrong identifier is used.
  622. Raises a KeyError if the command was not complete
  623. '''
  624. identifier = self.location
  625. if 'identifier' in cmd.params:
  626. if not identifier.endswith("/"):
  627. identifier += "/"
  628. if cmd.params['identifier'].startswith("/"):
  629. identifier = cmd.params['identifier']
  630. else:
  631. if cmd.params['identifier'].startswith('['):
  632. identifier = identifier[:-1]
  633. identifier += cmd.params['identifier']
  634. # Check if the module is known; for unknown modules
  635. # we currently deny setting preferences, as we have
  636. # no way yet to determine if they are ok.
  637. module_name = identifier.split('/')[1]
  638. if module_name != "" and (self.config_data is None or \
  639. not self.config_data.have_specification(module_name)):
  640. self._print("Error: Module '" + module_name +
  641. "' unknown or not running")
  642. return
  643. if cmd.command == "show":
  644. # check if we have the 'all' argument
  645. show_all = False
  646. if 'argument' in cmd.params:
  647. if cmd.params['argument'] == 'all':
  648. show_all = True
  649. elif 'identifier' not in cmd.params:
  650. # no 'all', no identifier, assume this is the
  651. #identifier
  652. identifier += cmd.params['argument']
  653. else:
  654. self._print("Error: unknown argument " +
  655. cmd.params['argument'] +
  656. ", or multiple identifiers given")
  657. return
  658. values = self.config_data.get_value_maps(identifier, show_all)
  659. for value_map in values:
  660. line = value_map['name']
  661. if value_map['type'] in [ 'module', 'map' ]:
  662. line += "/"
  663. elif value_map['type'] == 'list' \
  664. and value_map['value'] != []:
  665. # do not print content of non-empty lists if
  666. # we have more data to show
  667. line += "/"
  668. else:
  669. # if type is named_set, don't print value if None
  670. # (it is either {} meaning empty, or None, meaning
  671. # there actually is data, but not to be shown with
  672. # the current command
  673. if value_map['type'] == 'named_set' and\
  674. value_map['value'] is None:
  675. line += "/\t"
  676. else:
  677. line += "\t" + json.dumps(value_map['value'])
  678. line += "\t" + value_map['type']
  679. line += "\t"
  680. if value_map['default']:
  681. line += "(default)"
  682. if value_map['modified']:
  683. line += "(modified)"
  684. self._print(line)
  685. elif cmd.command == "show_json":
  686. if identifier == "":
  687. self._print("Need at least the module to show the "
  688. "configuration in JSON format")
  689. else:
  690. data, default = self.config_data.get_value(identifier)
  691. self._print(json.dumps(data))
  692. elif cmd.command == "add":
  693. self.config_data.add_value(identifier,
  694. cmd.params.get('value_or_name'),
  695. cmd.params.get('value_for_set'))
  696. elif cmd.command == "remove":
  697. if 'value' in cmd.params:
  698. self.config_data.remove_value(identifier, cmd.params['value'])
  699. else:
  700. self.config_data.remove_value(identifier, None)
  701. elif cmd.command == "set":
  702. if 'identifier' not in cmd.params:
  703. self._print("Error: missing identifier or value")
  704. else:
  705. parsed_value = None
  706. try:
  707. parsed_value = json.loads(cmd.params['value'])
  708. except Exception as exc:
  709. # ok could be an unquoted string, interpret as such
  710. parsed_value = cmd.params['value']
  711. self.config_data.set_value(identifier, parsed_value)
  712. elif cmd.command == "unset":
  713. self.config_data.unset(identifier)
  714. elif cmd.command == "revert":
  715. self.config_data.clear_local_changes()
  716. elif cmd.command == "commit":
  717. try:
  718. self.config_data.commit()
  719. except isc.config.ModuleCCSessionError as mcse:
  720. self._print(str(mcse))
  721. elif cmd.command == "diff":
  722. self._print(self.config_data.get_local_changes())
  723. elif cmd.command == "go":
  724. self.go(identifier)
  725. def go(self, identifier):
  726. '''Handles the config go command, change the 'current' location
  727. within the configuration tree. '..' will be interpreted as
  728. 'up one level'.'''
  729. id_parts = isc.cc.data.split_identifier(identifier)
  730. new_location = ""
  731. for id_part in id_parts:
  732. if (id_part == ".."):
  733. # go 'up' one level
  734. new_location, a, b = new_location.rpartition("/")
  735. else:
  736. new_location += "/" + id_part
  737. # check if exists, if not, revert and error
  738. v,d = self.config_data.get_value(new_location)
  739. if v is None:
  740. self._print("Error: " + identifier + " not found")
  741. return
  742. self.location = new_location
  743. def apply_execute_cmd(self, command):
  744. '''Handles the 'execute' command, which executes a number of
  745. (preset) statements. The command set to execute is either
  746. read from a file (e.g. 'execute file <file>'.) or one
  747. of the sets as defined in command_sets.py'''
  748. if command.command == 'file':
  749. try:
  750. with open(command.params['filename']) as command_file:
  751. commands = command_file.readlines()
  752. except IOError as ioe:
  753. self._print("Error: " + str(ioe))
  754. return
  755. elif command_sets.has_command_set(command.command):
  756. commands = command_sets.get_commands(command.command)
  757. else:
  758. # Should not be reachable; parser should've caught this
  759. raise Exception("Unknown execute command type " + command.command)
  760. # We have our set of commands now, depending on whether 'show' was
  761. # specified, show or execute them
  762. if 'show' in command.params and command.params['show'] == 'show':
  763. self.__show_execute_commands(commands)
  764. else:
  765. self.__apply_execute_commands(commands)
  766. def __show_execute_commands(self, commands):
  767. '''Prints the command list without executing them'''
  768. for line in commands:
  769. self._print(line.strip())
  770. def __apply_execute_commands(self, commands):
  771. '''Applies the configuration commands from the given iterator.
  772. This is the method that catches, comments, echo statements, and
  773. other directives. All commands not filtered by this method are
  774. interpreted as if they are directly entered in an active session.
  775. Lines starting with any of the following characters are not
  776. passed directly:
  777. # - These are comments
  778. ! - These are directives
  779. !echo: print the rest of the line
  780. !verbose on/off: print the commands themselves too
  781. Unknown directives are ignored (with a warning)
  782. The execution is stopped if there are any errors.
  783. '''
  784. verbose = False
  785. try:
  786. for line in commands:
  787. line = line.strip()
  788. if verbose:
  789. self._print(line)
  790. if line.startswith('#') or len(line) == 0:
  791. continue
  792. elif line.startswith('!'):
  793. if re.match('^!echo ', line, re.I) and len(line) > 6:
  794. self._print(line[6:])
  795. elif re.match('^!verbose\s+on\s*$', line, re.I):
  796. verbose = True
  797. elif re.match('^!verbose\s+off$', line, re.I):
  798. verbose = False
  799. else:
  800. self._print("Warning: ignoring unknown directive: " +
  801. line)
  802. else:
  803. cmd = BindCmdParser(line)
  804. self._validate_cmd(cmd)
  805. self._handle_cmd(cmd)
  806. except (isc.config.ModuleCCSessionError,
  807. IOError, http.client.HTTPException,
  808. BindCtlException, isc.cc.data.DataTypeError,
  809. isc.cc.data.DataNotFoundError,
  810. isc.cc.data.DataAlreadyPresentError,
  811. KeyError) as err:
  812. self._print('Error: ', err)
  813. self._print()
  814. self._print('Depending on the contents of the script, and which')
  815. self._print('commands it has called, there can be committed and')
  816. self._print('local changes. It is advised to check your settings')
  817. self._print(', and revert local changes with "config revert".')
  818. def apply_cmd(self, cmd):
  819. '''Handles a general module command'''
  820. url = '/' + cmd.module + '/' + cmd.command
  821. cmd_params = None
  822. if (len(cmd.params) != 0):
  823. cmd_params = json.dumps(cmd.params)
  824. reply = self.send_POST(url, cmd.params)
  825. data = reply.read().decode()
  826. # The reply is a string containing JSON data,
  827. # parse it, then prettyprint
  828. if data != "" and data != "{}":
  829. self._print(json.dumps(json.loads(data), sort_keys=True,
  830. indent=4))