bindcmd.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  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 BindCmdParse
  24. from xml.dom import minidom
  25. import isc
  26. import isc.cc.data
  27. import http.client
  28. import json
  29. import inspect
  30. import pprint
  31. import ssl, socket
  32. import os, time, random, re
  33. import getpass
  34. from hashlib import sha1
  35. import csv
  36. import pwd
  37. import getpass
  38. try:
  39. from collections import OrderedDict
  40. except ImportError:
  41. from bindctl.mycollections import OrderedDict
  42. # if we have readline support, use that, otherwise use normal stdio
  43. try:
  44. import readline
  45. my_readline = readline.get_line_buffer
  46. except ImportError:
  47. my_readline = sys.stdin.readline
  48. CSV_FILE_NAME = 'default_user.csv'
  49. FAIL_TO_CONNECT_WITH_CMDCTL = "Fail to connect with b10-cmdctl module, is it running?"
  50. CONFIG_MODULE_NAME = 'config'
  51. CONST_BINDCTL_HELP = """
  52. usage: <module name> <command name> [param1 = value1 [, param2 = value2]]
  53. Type Tab character to get the hint of module/command/parameters.
  54. Type \"help(? h)\" for help on bindctl.
  55. Type \"<module_name> help\" for help on the specific module.
  56. Type \"<module_name> <command_name> help\" for help on the specific command.
  57. \nAvailable module names: """
  58. class ValidatedHTTPSConnection(http.client.HTTPSConnection):
  59. '''Overrides HTTPSConnection to support certification
  60. validation. '''
  61. def __init__(self, host, ca_certs):
  62. http.client.HTTPSConnection.__init__(self, host)
  63. self.ca_certs = ca_certs
  64. def connect(self):
  65. ''' Overrides the connect() so that we do
  66. certificate validation. '''
  67. sock = socket.create_connection((self.host, self.port),
  68. self.timeout)
  69. if self._tunnel_host:
  70. self.sock = sock
  71. self._tunnel()
  72. req_cert = ssl.CERT_NONE
  73. if self.ca_certs:
  74. req_cert = ssl.CERT_REQUIRED
  75. self.sock = ssl.wrap_socket(sock, self.key_file,
  76. self.cert_file,
  77. cert_reqs=req_cert,
  78. ca_certs=self.ca_certs)
  79. class BindCmdInterpreter(Cmd):
  80. """simple bindctl example."""
  81. def __init__(self, server_port = 'localhost:8080', pem_file = None):
  82. Cmd.__init__(self)
  83. self.location = ""
  84. self.prompt_end = '> '
  85. self.prompt = self.prompt_end
  86. self.ruler = '-'
  87. self.modules = OrderedDict()
  88. self.add_module_info(ModuleInfo("help", desc = "Get help for bindctl"))
  89. self.server_port = server_port
  90. self.conn = ValidatedHTTPSConnection(self.server_port,
  91. ca_certs=pem_file)
  92. self.session_id = self._get_session_id()
  93. self.config_data = None
  94. def _get_session_id(self):
  95. '''Generate one session id for the connection. '''
  96. rand = os.urandom(16)
  97. now = time.time()
  98. session_id = sha1(("%s%s%s" %(rand, now,
  99. socket.gethostname())).encode())
  100. digest = session_id.hexdigest()
  101. return digest
  102. def run(self):
  103. '''Parse commands from user and send them to cmdctl. '''
  104. try:
  105. if not self.login_to_cmdctl():
  106. return
  107. self.cmdloop()
  108. except FailToLogin as err:
  109. print(err)
  110. print(FAIL_TO_CONNECT_WITH_CMDCTL)
  111. except KeyboardInterrupt:
  112. print('\nExit from bindctl')
  113. def _get_saved_user_info(self, dir, file_name):
  114. ''' Read all the available username and password pairs saved in
  115. file(path is "dir + file_name"), Return value is one list of elements
  116. ['name', 'password'], If get information failed, empty list will be
  117. returned.'''
  118. if (not dir) or (not os.path.exists(dir)):
  119. return []
  120. try:
  121. csvfile = None
  122. users = []
  123. csvfile = open(dir + file_name)
  124. users_info = csv.reader(csvfile)
  125. for row in users_info:
  126. users.append([row[0], row[1]])
  127. except (IOError, IndexError) as err:
  128. print("Error reading saved username and password from %s%s: %s" % (dir, file_name, err))
  129. finally:
  130. if csvfile:
  131. csvfile.close()
  132. return users
  133. def _save_user_info(self, username, passwd, dir, file_name):
  134. ''' Save username and password in file "dir + file_name"
  135. If it's saved properly, return True, or else return False. '''
  136. try:
  137. if not os.path.exists(dir):
  138. os.mkdir(dir, 0o700)
  139. csvfilepath = dir + file_name
  140. csvfile = open(csvfilepath, 'w')
  141. os.chmod(csvfilepath, 0o600)
  142. writer = csv.writer(csvfile)
  143. writer.writerow([username, passwd])
  144. csvfile.close()
  145. except IOError as err:
  146. print("Error saving user information:", err)
  147. print("user info file name: %s%s" % (dir, file_name))
  148. return False
  149. return True
  150. def login_to_cmdctl(self):
  151. '''Login to cmdctl with the username and password inputted
  152. from user. After the login is sucessful, the username and
  153. password will be saved in 'default_user.csv', when run the next
  154. time, username and password saved in 'default_user.csv' will be
  155. used first.
  156. '''
  157. csv_file_dir = pwd.getpwnam(getpass.getuser()).pw_dir
  158. csv_file_dir += os.sep + '.bind10' + os.sep
  159. users = self._get_saved_user_info(csv_file_dir, CSV_FILE_NAME)
  160. for row in users:
  161. param = {'username': row[0], 'password' : row[1]}
  162. try:
  163. response = self.send_POST('/login', param)
  164. data = response.read().decode()
  165. except socket.error as err:
  166. print("Socket error while sending login information:", err)
  167. raise FailToLogin()
  168. if response.status == http.client.OK:
  169. print(data + ' login as ' + row[0] )
  170. return True
  171. count = 0
  172. print("[TEMP MESSAGE]: username :root password :bind10")
  173. while True:
  174. count = count + 1
  175. if count > 3:
  176. print("Too many authentication failures")
  177. return False
  178. username = input("Username:")
  179. passwd = getpass.getpass()
  180. param = {'username': username, 'password' : passwd}
  181. try:
  182. response = self.send_POST('/login', param)
  183. data = response.read().decode()
  184. print(data)
  185. except socket.error as err:
  186. print("Socket error while sending login information:", err)
  187. raise FailToLogin()
  188. if response.status == http.client.OK:
  189. self._save_user_info(username, passwd, csv_file_dir, CSV_FILE_NAME)
  190. return True
  191. def _update_commands(self):
  192. '''Update the commands of all modules. '''
  193. for module_name in self.config_data.get_config_item_list():
  194. self._prepare_module_commands(self.config_data.get_module_spec(module_name))
  195. def send_GET(self, url, body = None):
  196. '''Send GET request to cmdctl, session id is send with the name
  197. 'cookie' in header.
  198. '''
  199. headers = {"cookie" : self.session_id}
  200. self.conn.request('GET', url, body, headers)
  201. res = self.conn.getresponse()
  202. reply_msg = res.read()
  203. if reply_msg:
  204. return json.loads(reply_msg.decode())
  205. else:
  206. return {}
  207. def send_POST(self, url, post_param = None):
  208. '''Send POST request to cmdctl, session id is send with the name
  209. 'cookie' in header.
  210. Format: /module_name/command_name
  211. parameters of command is encoded as a map
  212. '''
  213. param = None
  214. if (len(post_param) != 0):
  215. param = json.dumps(post_param)
  216. headers = {"cookie" : self.session_id}
  217. self.conn.request('POST', url, param, headers)
  218. return self.conn.getresponse()
  219. def _update_all_modules_info(self):
  220. ''' Get all modules' information from cmdctl, including
  221. specification file and configuration data. This function
  222. should be called before interpreting command line or complete-key
  223. is entered. This may not be the best way to keep bindctl
  224. and cmdctl share same modules information, but it works.'''
  225. if self.config_data is not None:
  226. self.config_data.update_specs_and_config()
  227. else:
  228. self.config_data = isc.config.UIModuleCCSession(self)
  229. self._update_commands()
  230. def precmd(self, line):
  231. self._update_all_modules_info()
  232. return line
  233. def postcmd(self, stop, line):
  234. '''Update the prompt after every command'''
  235. self.prompt = self.location + self.prompt_end
  236. return stop
  237. def _prepare_module_commands(self, module_spec):
  238. '''Prepare the module commands'''
  239. module = ModuleInfo(name = module_spec.get_module_name(),
  240. desc = module_spec.get_module_description())
  241. for command in module_spec.get_commands_spec():
  242. cmd = CommandInfo(name = command["command_name"],
  243. desc = command["command_description"])
  244. for arg in command["command_args"]:
  245. param = ParamInfo(name = arg["item_name"],
  246. type = arg["item_type"],
  247. optional = bool(arg["item_optional"]),
  248. param_spec = arg)
  249. if ("item_default" in arg):
  250. param.default = arg["item_default"]
  251. cmd.add_param(param)
  252. module.add_command(cmd)
  253. self.add_module_info(module)
  254. def _validate_cmd(self, cmd):
  255. '''validate the parameters and merge some parameters together,
  256. merge algorithm is based on the command line syntax, later, if
  257. a better command line syntax come out, this function should be
  258. updated first.
  259. '''
  260. if not cmd.module in self.modules:
  261. raise CmdUnknownModuleSyntaxError(cmd.module)
  262. module_info = self.modules[cmd.module]
  263. if not module_info.has_command_with_name(cmd.command):
  264. raise CmdUnknownCmdSyntaxError(cmd.module, cmd.command)
  265. command_info = module_info.get_command_with_name(cmd.command)
  266. manda_params = command_info.get_mandatory_param_names()
  267. all_params = command_info.get_param_names()
  268. # If help is entered, don't do further parameter validation.
  269. for val in cmd.params.keys():
  270. if val == "help":
  271. return
  272. params = cmd.params.copy()
  273. if not params and manda_params:
  274. raise CmdMissParamSyntaxError(cmd.module, cmd.command, manda_params[0])
  275. elif params and not all_params:
  276. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command,
  277. list(params.keys())[0])
  278. elif params:
  279. param_name = None
  280. param_count = len(params)
  281. for name in params:
  282. # either the name of the parameter must be known, or
  283. # the 'name' must be an integer (ie. the position of
  284. # an unnamed argument
  285. if type(name) == int:
  286. # lump all extraneous arguments together as one big final one
  287. # todo: check if last param type is a string?
  288. if (param_count > 2):
  289. while (param_count > len(command_info.params) - 1):
  290. params[param_count - 2] += params[param_count - 1]
  291. del(params[param_count - 1])
  292. param_count = len(params)
  293. cmd.params = params.copy()
  294. # (-1, help is always in the all_params list)
  295. if name >= len(all_params) - 1:
  296. # add to last known param
  297. if param_name:
  298. cmd.params[param_name] += cmd.params[name]
  299. else:
  300. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command, cmd.params[name])
  301. else:
  302. # replace the numbered items by named items
  303. param_name = command_info.get_param_name_by_position(name, param_count)
  304. cmd.params[param_name] = cmd.params[name]
  305. del cmd.params[name]
  306. elif not name in all_params:
  307. raise CmdUnknownParamSyntaxError(cmd.module, cmd.command, name)
  308. param_nr = 0
  309. for name in manda_params:
  310. if not name in params and not param_nr in params:
  311. raise CmdMissParamSyntaxError(cmd.module, cmd.command, name)
  312. param_nr += 1
  313. # Convert parameter value according parameter spec file.
  314. # Ignore check for commands belongs to module 'config'
  315. if cmd.module != CONFIG_MODULE_NAME:
  316. for param_name in cmd.params:
  317. param_spec = command_info.get_param_with_name(param_name).param_spec
  318. try:
  319. cmd.params[param_name] = isc.config.config_data.convert_type(param_spec, cmd.params[param_name])
  320. except isc.cc.data.DataTypeError as e:
  321. raise isc.cc.data.DataTypeError('Invalid parameter value for \"%s\", the type should be \"%s\" \n'
  322. % (param_name, param_spec['item_type']) + str(e))
  323. def _handle_cmd(self, cmd):
  324. '''Handle a command entered by the user'''
  325. if cmd.command == "help" or ("help" in cmd.params.keys()):
  326. self._handle_help(cmd)
  327. elif cmd.module == CONFIG_MODULE_NAME:
  328. self.apply_config_cmd(cmd)
  329. else:
  330. self.apply_cmd(cmd)
  331. def add_module_info(self, module_info):
  332. '''Add the information about one module'''
  333. self.modules[module_info.name] = module_info
  334. def get_module_names(self):
  335. '''Return the names of all known modules'''
  336. return list(self.modules.keys())
  337. #override methods in cmd
  338. def default(self, line):
  339. self._parse_cmd(line)
  340. def emptyline(self):
  341. pass
  342. def do_help(self, name):
  343. print(CONST_BINDCTL_HELP)
  344. for k in self.modules.keys():
  345. print("\t", self.modules[k])
  346. def onecmd(self, line):
  347. if line == 'EOF' or line.lower() == "quit":
  348. self.conn.close()
  349. return True
  350. if line == 'h':
  351. line = 'help'
  352. Cmd.onecmd(self, line)
  353. def remove_prefix(self, list, prefix):
  354. return [(val[len(prefix):]) for val in list]
  355. def complete(self, text, state):
  356. if 0 == state:
  357. self._update_all_modules_info()
  358. text = text.strip()
  359. hints = []
  360. cur_line = my_readline()
  361. try:
  362. cmd = BindCmdParse(cur_line)
  363. if not cmd.params and text:
  364. hints = self._get_command_startswith(cmd.module, text)
  365. else:
  366. hints = self._get_param_startswith(cmd.module, cmd.command,
  367. text)
  368. if cmd.module == CONFIG_MODULE_NAME:
  369. # grm text has been stripped of slashes...
  370. my_text = self.location + "/" + cur_line.rpartition(" ")[2]
  371. list = self.config_data.get_config_item_list(my_text.rpartition("/")[0], True)
  372. hints.extend([val for val in list if val.startswith(my_text[1:])])
  373. # remove the common prefix from the hints so we don't get it twice
  374. hints = self.remove_prefix(hints, my_text.rpartition("/")[0])
  375. except CmdModuleNameFormatError:
  376. if not text:
  377. hints = self.get_module_names()
  378. except CmdMissCommandNameFormatError as e:
  379. if not text.strip(): # command name is empty
  380. hints = self.modules[e.module].get_command_names()
  381. else:
  382. hints = self._get_module_startswith(text)
  383. except CmdCommandNameFormatError as e:
  384. if e.module in self.modules:
  385. hints = self._get_command_startswith(e.module, text)
  386. except CmdParamFormatError as e:
  387. hints = self._get_param_startswith(e.module, e.command, text)
  388. except BindCtlException:
  389. hints = []
  390. self.hint = hints
  391. #self._append_space_to_hint()
  392. if state < len(self.hint):
  393. return self.hint[state]
  394. else:
  395. return None
  396. def _get_module_startswith(self, text):
  397. return [module
  398. for module in self.modules
  399. if module.startswith(text)]
  400. def _get_command_startswith(self, module, text):
  401. if module in self.modules:
  402. return [command
  403. for command in self.modules[module].get_command_names()
  404. if command.startswith(text)]
  405. return []
  406. def _get_param_startswith(self, module, command, text):
  407. if module in self.modules:
  408. module_info = self.modules[module]
  409. if command in module_info.get_command_names():
  410. cmd_info = module_info.get_command_with_name(command)
  411. params = cmd_info.get_param_names()
  412. hint = []
  413. if text:
  414. hint = [val for val in params if val.startswith(text)]
  415. else:
  416. hint = list(params)
  417. if len(hint) == 1 and hint[0] != "help":
  418. hint[0] = hint[0] + " ="
  419. return hint
  420. return []
  421. def _parse_cmd(self, line):
  422. try:
  423. cmd = BindCmdParse(line)
  424. self._validate_cmd(cmd)
  425. self._handle_cmd(cmd)
  426. except (IOError, http.client.HTTPException) as err:
  427. print('Error!', err)
  428. print(FAIL_TO_CONNECT_WITH_CMDCTL)
  429. except BindCtlException as err:
  430. print("Error! ", err)
  431. self._print_correct_usage(err)
  432. except isc.cc.data.DataTypeError as err:
  433. print("Error! ", err)
  434. def _print_correct_usage(self, ept):
  435. if isinstance(ept, CmdUnknownModuleSyntaxError):
  436. self.do_help(None)
  437. elif isinstance(ept, CmdUnknownCmdSyntaxError):
  438. self.modules[ept.module].module_help()
  439. elif isinstance(ept, CmdMissParamSyntaxError) or \
  440. isinstance(ept, CmdUnknownParamSyntaxError):
  441. self.modules[ept.module].command_help(ept.command)
  442. def _append_space_to_hint(self):
  443. """Append one space at the end of complete hint."""
  444. self.hint = [(val + " ") for val in self.hint]
  445. def _handle_help(self, cmd):
  446. if cmd.command == "help":
  447. self.modules[cmd.module].module_help()
  448. else:
  449. self.modules[cmd.module].command_help(cmd.command)
  450. def apply_config_cmd(self, cmd):
  451. '''Handles a configuration command.
  452. Raises a DataTypeError if a wrong value is set.
  453. Raises a DataNotFoundError if a wrong identifier is used.
  454. Raises a KeyError if the command was not complete
  455. '''
  456. identifier = self.location
  457. try:
  458. if 'identifier' in cmd.params:
  459. if not identifier.endswith("/"):
  460. identifier += "/"
  461. if cmd.params['identifier'].startswith("/"):
  462. identifier = cmd.params['identifier']
  463. else:
  464. identifier += cmd.params['identifier']
  465. # Check if the module is known; for unknown modules
  466. # we currently deny setting preferences, as we have
  467. # no way yet to determine if they are ok.
  468. module_name = identifier.split('/')[1]
  469. if self.config_data is None or \
  470. not self.config_data.have_specification(module_name):
  471. print("Error: Module '" + module_name + "' unknown or not running")
  472. return
  473. if cmd.command == "show":
  474. values = self.config_data.get_value_maps(identifier)
  475. for value_map in values:
  476. line = value_map['name']
  477. if value_map['type'] in [ 'module', 'map', 'list' ]:
  478. line += "/"
  479. else:
  480. line += ":\t" + str(value_map['value'])
  481. line += "\t" + value_map['type']
  482. line += "\t"
  483. if value_map['default']:
  484. line += "(default)"
  485. if value_map['modified']:
  486. line += "(modified)"
  487. print(line)
  488. elif cmd.command == "add":
  489. self.config_data.add_value(identifier, cmd.params['value'])
  490. elif cmd.command == "remove":
  491. self.config_data.remove_value(identifier, cmd.params['value'])
  492. elif cmd.command == "set":
  493. if 'identifier' not in cmd.params:
  494. print("Error: missing identifier or value")
  495. else:
  496. parsed_value = None
  497. try:
  498. parsed_value = json.loads(cmd.params['value'])
  499. except Exception as exc:
  500. # ok could be an unquoted string, interpret as such
  501. parsed_value = cmd.params['value']
  502. self.config_data.set_value(identifier, parsed_value)
  503. elif cmd.command == "unset":
  504. self.config_data.unset(identifier)
  505. elif cmd.command == "revert":
  506. self.config_data.clear_local_changes()
  507. elif cmd.command == "commit":
  508. self.config_data.commit()
  509. elif cmd.command == "diff":
  510. print(self.config_data.get_local_changes());
  511. elif cmd.command == "go":
  512. self.go(identifier)
  513. except isc.cc.data.DataTypeError as dte:
  514. print("Error: " + str(dte))
  515. except isc.cc.data.DataNotFoundError as dnfe:
  516. print("Error: " + identifier + " not found")
  517. except KeyError as ke:
  518. print("Error: missing " + str(ke))
  519. raise ke
  520. def go(self, identifier):
  521. '''Handles the config go command, change the 'current' location
  522. within the configuration tree'''
  523. # this is just to see if it exists
  524. self.config_data.get_value(identifier)
  525. # some sanitizing
  526. identifier = identifier.replace("//", "/")
  527. if not identifier.startswith("/"):
  528. identifier = "/" + identifier
  529. if identifier.endswith("/"):
  530. identifier = identifier[:-1]
  531. self.location = identifier
  532. def apply_cmd(self, cmd):
  533. '''Handles a general module command'''
  534. url = '/' + cmd.module + '/' + cmd.command
  535. cmd_params = None
  536. if (len(cmd.params) != 0):
  537. cmd_params = json.dumps(cmd.params)
  538. print("send the command to cmd-ctrld")
  539. reply = self.send_POST(url, cmd.params)
  540. data = reply.read().decode()
  541. print("received reply:", data)