/*
 *	BIRD Internet Routing Daemon -- Configuration File Handling
 *
 *	(c) 1998--2000 Martin Mares <mj@ucw.cz>
 *
 *	Can be freely distributed and used under the terms of the GNU GPL.
 */

/**
 * DOC: Configuration manager
 *
 * Configuration of BIRD is complex, yet straightforward. There are three
 * modules taking care of the configuration: config manager (which takes care
 * of storage of the config information and controls switching between configs),
 * lexical analyzer and parser.
 *
 * The configuration manager stores each config as a &config structure
 * accompanied by a linear pool from which all information associated
 * with the config and pointed to by the &config structure is allocated.
 *
 * There can exist up to four different configurations at one time: an active
 * one (pointed to by @config), configuration we are just switching from
 * (@old_config), one queued for the next reconfiguration (@future_config; if
 * there is one and the user wants to reconfigure once again, we just free the
 * previous queued config and replace it with the new one) and finally a config
 * being parsed (@new_config). The stored @old_config is also used for undo
 * reconfiguration, which works in a similar way. Reconfiguration could also
 * have timeout (using @config_timer) and undo is automatically called if the
 * new configuration is not confirmed later. The new config (@new_config) and
 * associated linear pool (@cfg_mem) is non-NULL only during parsing.
 *
 * Loading of new configuration is very simple: just call config_alloc() to get
 * a new &config structure, then use config_parse() to parse a configuration
 * file and fill all fields of the structure and finally ask the config manager
 * to switch to the new config by calling config_commit().
 *
 * CLI commands are parsed in a very similar way -- there is also a stripped-down
 * &config structure associated with them and they are lex-ed and parsed by the
 * same functions, only a special fake token is prepended before the command
 * text to make the parser recognize only the rules corresponding to CLI commands.
 */

#include <stdarg.h>

#undef LOCAL_DEBUG

#include "nest/bird.h"
#include "nest/route.h"
#include "nest/protocol.h"
#include "nest/iface.h"
#include "nest/mpls.h"
#include "lib/resource.h"
#include "lib/string.h"
#include "lib/event.h"
#include "lib/timer.h"
#include "conf/conf.h"
#include "filter/filter.h"
#include "sysdep/unix/unix.h"


static jmp_buf conf_jmpbuf;

config_ref config;
_Thread_local struct config *new_config;
pool *config_pool;

struct config *old_config;		/* Old configuration */
static config_ref future_config;	/* New config held here if recon requested during recon */
static int old_cftype;			/* Type of transition old_config -> config (RECONFIG_SOFT/HARD) */
static int future_cftype;		/* Type of scheduled transition, may also be RECONFIG_UNDO */
/* Note that when future_cftype is RECONFIG_UNDO, then future_config is NULL,
   therefore proper check for future scheduled config checks future_cftype */

static void config_done(void);
static timer *config_timer;		/* Timer for scheduled configuration rollback */

/* These are public just for cmd_show_status(), should not be accessed elsewhere */
int shutting_down;			/* Shutdown requested, do not accept new config changes */
int configuring;			/* Reconfiguration is running */
int undo_available;			/* Undo was not requested from last reconfiguration */
/* Note that both shutting_down and undo_available are related to requests, not processing */

static void
config_obstacles_cleared(struct callback *_ UNUSED)
{
  ASSERT_DIE(birdloop_inside(&main_birdloop));
  ASSERT_DIE(configuring);
  config_done();
}

/**
 * config_alloc - allocate a new configuration
 * @name: name of the config
 *
 * This function creates new &config structure, attaches a resource
 * pool and a linear memory pool to it and makes it available for
 * further use. Returns a pointer to the structure.
 */
struct config *
config_alloc(const char *name)
{
  pool *p = rp_new(config_pool, the_bird_domain.the_bird, "Config");
  linpool *l = lp_new_default(p);
  struct config *c = lp_allocz(l, sizeof(struct config));

  /* Duplication of name string in local linear pool */
  uint nlen = strlen(name) + 1;
  char *ndup = lp_allocu(l, nlen);
  memcpy(ndup, name, nlen);

  init_list(&c->tests);
  init_list(&c->symbols);
  c->pool = p;
  c->mem = l;
  c->file_name = ndup;
  c->tf_route = c->tf_proto = TM_ISO_SHORT_MS;
  c->tf_base = c->tf_log = TM_ISO_LONG_MS;
  c->gr_wait = DEFAULT_GR_WAIT;

  callback_init(&c->obstacles_cleared, config_obstacles_cleared, &main_birdloop);
  obstacle_target_init(&c->obstacles, &c->obstacles_cleared, p, "Config");

  return c;
}

/**
 * config_parse - parse a configuration
 * @c: configuration
 *
 * config_parse() reads input by calling a hook function pointed to
 * by @cf_read_hook and parses it according to the configuration
 * grammar. It also calls all the preconfig and postconfig hooks
 * before, resp. after parsing.
 *
 * Result: 1 if the config has been parsed successfully, 0 if any
 * error has occurred (such as anybody calling cf_error()) and
 * the @err_msg field has been set to the error message.
 */
int
config_parse(struct config *c)
{
  int done = 0;
  DBG("Parsing configuration file `%s'\n", c->file_name);
  new_config = c;
  cfg_mem = c->mem;
  if (setjmp(conf_jmpbuf))
    goto cleanup;

  cf_lex_init(NULL, c);
  filter_preconfig(c);
  sysdep_preconfig(c);
  protos_preconfig(c);
  mpls_preconfig(c);
  rt_preconfig(c);
  cf_parse();
  rt_postconfig(c);

  if (EMPTY_LIST(c->protos))
    cf_error("No protocol is specified in the config file");

  done = 1;

cleanup:
  new_config = NULL;
  cfg_mem = NULL;
  return done;
}

/**
 * cli_parse - parse a CLI command
 * @c: temporary config structure
 *
 * cli_parse() is similar to config_parse(), but instead of a configuration,
 * it parses a CLI command. See the CLI module for more information.
 */
int
cli_parse(struct config *main_config, struct config *c)
{
  int done = 0;
  new_config = c;
  cfg_mem = c->mem;
  if (setjmp(conf_jmpbuf))
    goto cleanup;

  cf_lex_init(main_config, c);
  cf_parse();
  done = 1;

cleanup:
  new_config = NULL;
  cfg_mem = NULL;
  return done;
}

/**
 * config_free - free a configuration
 * @c: configuration to be freed
 *
 * This function takes a &config structure and frees all resources
 * associated with it.
 */
void
config_free(struct config *c)
{
  if (!c)
    return;

  synchronize_rcu();
  ASSERT_DIE(!obstacle_target_count(&c->obstacles));

  rp_free(c->pool);
}

/**
 * config_free_old - free stored old configuration
 *
 * This function frees the old configuration (%old_config) that is saved for the
 * purpose of undo. It is useful before parsing a new config when reconfig is
 * requested, to avoid keeping three (perhaps memory-heavy) configs together.
 * Configuration is not freed when it is still active during reconfiguration.
 */
void
config_free_old(void)
{
  tm_stop(config_timer);
  undo_available = 0;

  config_free(old_config);
  old_config = NULL;
}

struct global_runtime global_runtime_internal[2] = {{
  .tf_log = {
    .fmt1 = "%F %T.%3f",
  },
}};
struct global_runtime * _Atomic global_runtime = &global_runtime_internal[0];

static void
global_commit(struct config *new, struct config *old)
{
  /* Updating the global runtime. */
  struct global_runtime *og = atomic_load_explicit(&global_runtime, memory_order_relaxed);
  struct global_runtime *ng = &global_runtime_internal[og == &global_runtime_internal[0]];
  ASSERT_DIE(ng != og);

#define COPY(x)	ng->x = new->x;
  MACRO_FOREACH(COPY,
      tf_route,
      tf_proto,
      tf_log,
      tf_base,
      cli_debug,
      latency_debug,
      latency_limit,
      watchdog_warning,
      watchdog_timeout,
      gr_wait,
      hostname
      );
#undef COPY

  ng->load_time = current_time();

  if (new->router_id)
    ng->router_id = new->router_id;
  else if (old)
  {
    /* The startup router ID must be determined after start of device protocol,
     * thus if old == NULL then we do nothing */
    ng->router_id = og->router_id;

    if (new->router_id_from)
    {
      u32 id = if_choose_router_id(new->router_id_from, og->router_id);
      if (!id)
	log(L_WARN "Cannot determine router ID, using old one");
      else
	ng->router_id = id;
    }
  }

  atomic_store_explicit(&global_runtime, ng, memory_order_release);

  /* We have to wait until every reader surely doesn't read the old values */
  synchronize_rcu();
}

static int
config_do_commit(config_ref *cr, int type)
{
  if (type == RECONFIG_UNDO)
    {
      OBSREF_SET(*cr, old_config);
      type = old_cftype;
    }
  else
    config_free(old_config);

  old_config = NULL;
  old_cftype = type;

  struct config *c = OBSREF_GET(*cr);
  old_config = OBSREF_GET(config);

  OBSREF_CLEAR(config);
  OBSREF_SET(config, OBSREF_GET(*cr));

  if (!c->hostname)
    {
      c->hostname = get_hostname(c->mem);

      if (!c->hostname)
        log(L_WARN "Cannot determine hostname");
    }

  configuring = 1;
  if (old_config && !c->shutdown)
    log(L_INFO "Reconfiguring");

  DBG("filter_commit\n");
  filter_commit(c, old_config);
  DBG("sysdep_commit\n");
  sysdep_commit(c, old_config);
  DBG("global_commit\n");
  global_commit(c, old_config);
  mpls_commit(c, old_config);
  DBG("rt_commit\n");
  rt_commit(c, old_config);
  DBG("protos_commit\n");
  protos_commit(c, old_config, type);

  /* Can be cleared directly? */
  if (!old_config)
    return 1;

  if (!callback_is_active(&old_config->obstacles_cleared))
    return 0;

  callback_cancel(&old_config->obstacles_cleared);
  return 1;
}

static void
config_done(void)
{
  struct config *c = OBSREF_GET(config);
  ASSERT_DIE(c);

  if (c->shutdown)
    sysdep_shutdown_done();

  configuring = 0;

  if (old_config)
    log(L_INFO "Reconfigured");

  if (future_cftype)
    {
      int type = future_cftype;
      struct config *fc = OBSREF_GET(future_config);

      if (type == RECONFIG_UNDO)
      {
	ASSERT_DIE(!fc);
	ASSERT_DIE(old_config);
	fc = old_config;
      }

      CONFIG_REF_LOCAL(conf, fc);

      future_cftype = RECONFIG_NONE;
      OBSREF_CLEAR(future_config);

      log(L_INFO "Reconfiguring to queued configuration");
      if (config_do_commit(&conf, type))
	config_done();
    }
}

/**
 * config_commit - commit a configuration
 * @c: new configuration
 * @type: type of reconfiguration (RECONFIG_SOFT or RECONFIG_HARD)
 * @timeout: timeout for undo (in seconds; or 0 for no timeout)
 *
 * When a configuration is parsed and prepared for use, the
 * config_commit() function starts the process of reconfiguration.
 * It checks whether there is already a reconfiguration in progress
 * in which case it just queues the new config for later processing.
 * Else it notifies all modules about the new configuration by calling
 * their commit() functions which can either accept it immediately
 * or call config_add_obstacle() to report that they need some time
 * to complete the reconfiguration. After all such obstacles are removed
 * using config_del_obstacle(), the old configuration is freed and
 * everything runs according to the new one.
 *
 * When @timeout is nonzero, the undo timer is activated with given
 * timeout. The timer is deactivated when config_commit(),
 * config_confirm() or config_undo() is called.
 *
 * Result: %CONF_DONE if the configuration has been accepted immediately,
 * %CONF_PROGRESS if it will take some time to switch to it, %CONF_QUEUED
 * if it's been queued due to another reconfiguration being in progress now
 * or %CONF_SHUTDOWN if BIRD is in shutdown mode and no new configurations
 * are accepted.
 */
int
config_commit(config_ref *cr, int type, uint timeout)
{
  if (shutting_down)
    {
      OBSREF_CLEAR(*cr);
      return CONF_SHUTDOWN;
    }

  undo_available = 1;
  if (timeout)
    tm_start(config_timer, timeout S);
  else
    tm_stop(config_timer);

  if (configuring)
    {
      if (future_cftype)
	{
	  log(L_INFO "Queueing new configuration, ignoring the one already queued");
	  OBSREF_CLEAR(future_config);
	}
      else
	log(L_INFO "Queueing new configuration");

      future_cftype = type;
      OBSREF_SET(future_config, OBSREF_GET(*cr));
      return CONF_QUEUED;
    }

  if (config_do_commit(cr, type))
    {
      config_done();
      return CONF_DONE;
    }
  return CONF_PROGRESS;
}

/**
 * config_confirm - confirm a commited configuration
 *
 * When the undo timer is activated by config_commit() with nonzero timeout,
 * this function can be used to deactivate it and therefore confirm
 * the current configuration.
 *
 * Result: %CONF_CONFIRM when the current configuration is confirmed,
 * %CONF_NONE when there is nothing to confirm (i.e. undo timer is not active).
 */
int
config_confirm(void)
{
  if (config_timer->expires == 0)
    return CONF_NOTHING;

  tm_stop(config_timer);

  return CONF_CONFIRM;
}

/**
 * config_undo - undo a configuration
 *
 * Function config_undo() can be used to change the current
 * configuration back to stored %old_config. If no reconfiguration is
 * running, this stored configuration is commited in the same way as a
 * new configuration in config_commit(). If there is already a
 * reconfiguration in progress and no next reconfiguration is
 * scheduled, then the undo is scheduled for later processing as
 * usual, but if another reconfiguration is already scheduled, then
 * such reconfiguration is removed instead (i.e. undo is applied on
 * the last commit that scheduled it).
 *
 * Result: %CONF_DONE if the configuration has been accepted immediately,
 * %CONF_PROGRESS if it will take some time to switch to it, %CONF_QUEUED
 * if it's been queued due to another reconfiguration being in progress now,
 * %CONF_UNQUEUED if a scheduled reconfiguration is removed, %CONF_NOTHING
 * if there is no relevant configuration to undo (the previous config request
 * was config_undo() too)  or %CONF_SHUTDOWN if BIRD is in shutdown mode and
 * no new configuration changes  are accepted.
 */
int
config_undo(void)
{
  if (shutting_down)
    return CONF_SHUTDOWN;

  if (!undo_available || !old_config)
    return CONF_NOTHING;

  undo_available = 0;
  tm_stop(config_timer);

  if (configuring)
    {
      if (future_cftype)
	{
	  OBSREF_CLEAR(future_config);

	  log(L_INFO "Removing queued configuration");
	  future_cftype = RECONFIG_NONE;
	  return CONF_UNQUEUED;
	}
      else
	{
	  log(L_INFO "Queueing undo configuration");
	  future_cftype = RECONFIG_UNDO;
	  return CONF_QUEUED;
	}
    }

  CONFIG_REF_LOCAL_EMPTY(undo_conf);
  if (config_do_commit(&undo_conf, RECONFIG_UNDO))
    {
      OBSREF_CLEAR(undo_conf);
      config_done();
      return CONF_DONE;
    }
  return CONF_PROGRESS;
}

int
config_status(void)
{
  if (shutting_down)
    return CONF_SHUTDOWN;

  if (configuring)
    return future_cftype ? CONF_QUEUED : CONF_PROGRESS;

  return CONF_DONE;
}

btime
config_timer_status(void)
{
  return tm_active(config_timer) ? tm_remains(config_timer) : -1;
}

extern void cmd_reconfig_undo_notify(void);

static void
config_timeout(timer *t UNUSED)
{
  log(L_INFO "Config timeout expired, starting undo");
  cmd_reconfig_undo_notify();

  int r = config_undo();
  if (r < 0)
    log(L_ERR "Undo request failed");
}

void
config_init(void)
{
  config_pool = rp_new(&root_pool, the_bird_domain.the_bird, "Configurations");

  config_timer = tm_new(config_pool);
  config_timer->hook = config_timeout;
}

/**
 * order_shutdown - order BIRD shutdown
 *
 * This function initiates shutdown of BIRD. It's accomplished by asking
 * for switching to an empty configuration.
 */
void
order_shutdown(int gr)
{
  if (shutting_down)
    return;

  if (!gr)
    log(L_INFO "Shutting down");
  else
    log(L_INFO "Shutting down for graceful restart");

  struct config *c = lp_alloc(OBSREF_GET(config)->mem, sizeof(struct config));
  memcpy(c, OBSREF_GET(config), sizeof(struct config));
  init_list(&c->protos);
  init_list(&c->tables);
  init_list(&c->mpls_domains);
  init_list(&c->symbols);
  obstacle_target_init(&c->obstacles, &c->obstacles_cleared, c->pool, "Config");
  c->cli = (struct cli_config_list) {};
  memset(c->def_tables, 0, sizeof(c->def_tables));
  c->shutdown = 1;
  c->gr_down = gr;

  CONFIG_REF_LOCAL(cr, c);
  config_commit(&cr, RECONFIG_HARD, 0);
  shutting_down = 1;
}

/**
 * cf_error - report a configuration error
 * @msg: printf-like format string
 *
 * cf_error() can be called during execution of config_parse(), that is
 * from the parser, a preconfig hook or a postconfig hook, to report an
 * error in the configuration.
 */
void
cf_error(const char *msg, ...)
{
  char buf[1024];
  va_list args;

  va_start(args, msg);
  if (bvsnprintf(buf, sizeof(buf), msg, args) < 0)
    strcpy(buf, "<bug: error message too long>");
  va_end(args);
  new_config->err_msg = cfg_strdup(buf);
  new_config->err_lino = ifs->lino;
  new_config->err_chno = ifs->chno - ifs->toklen + 1;
  new_config->err_file_name = ifs->file_name;
  cf_lex_unwind();
  longjmp(conf_jmpbuf, 1);
}

/**
 * cfg_strdup - copy a string to config memory
 * @c: string to copy
 *
 * cfg_strdup() creates a new copy of the string in the memory
 * pool associated with the configuration being currently parsed.
 * It's often used when a string literal occurs in the configuration
 * and we want to preserve it for further use.
 */
char *
cfg_strdup(const char *c)
{
  int l = strlen(c) + 1;
  char *z = cfg_allocu(l);
  memcpy(z, c, l);
  return z;
}


void
cfg_copy_list(list *dest, list *src, unsigned node_size)
{
  node *dn, *sn;

  init_list(dest);
  WALK_LIST(sn, *src)
  {
    dn = cfg_alloc(node_size);
    memcpy(dn, sn, node_size);
    memset(dn, 0, sizeof(node));
    add_tail(dest, dn);
  }
}