diff options
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/agentx.c | 447 | ||||
| -rw-r--r-- | lib/bfd.c | 715 | ||||
| -rw-r--r-- | lib/bfd.h | 90 | ||||
| -rw-r--r-- | lib/bitfield.h | 84 | ||||
| -rw-r--r-- | lib/buffer.c | 681 | ||||
| -rw-r--r-- | lib/buffer.h | 59 | ||||
| -rw-r--r-- | lib/checksum.c | 148 | ||||
| -rw-r--r-- | lib/checksum.h | 3 | ||||
| -rw-r--r-- | lib/command.c | 3781 | ||||
| -rw-r--r-- | lib/command.h | 508 | ||||
| -rw-r--r-- | lib/command_match.c | 1452 | ||||
| -rw-r--r-- | lib/command_match.h | 51 | ||||
| -rw-r--r-- | lib/csv.c | 1155 | ||||
| -rw-r--r-- | lib/csv.h | 14 | ||||
| -rw-r--r-- | lib/distribute.c | 744 | ||||
| -rw-r--r-- | lib/distribute.h | 50 | ||||
| -rw-r--r-- | lib/event_counter.c | 37 | ||||
| -rw-r--r-- | lib/event_counter.h | 11 | ||||
| -rw-r--r-- | lib/fifo.h | 66 | ||||
| -rw-r--r-- | lib/filter.c | 2395 | ||||
| -rw-r--r-- | lib/filter.h | 46 | ||||
| -rw-r--r-- | lib/getopt.c | 1339 | ||||
| -rw-r--r-- | lib/getopt.h | 55 | ||||
| -rw-r--r-- | lib/getopt1.c | 189 | ||||
| -rw-r--r-- | lib/grammar_sandbox.c | 977 | ||||
| -rw-r--r-- | lib/grammar_sandbox_main.c | 40 | ||||
| -rw-r--r-- | lib/graph.c | 181 | ||||
| -rw-r--r-- | lib/graph.h | 36 | ||||
| -rw-r--r-- | lib/hash.c | 377 | ||||
| -rw-r--r-- | lib/hash.h | 74 | ||||
| -rw-r--r-- | lib/hook.c | 7 | ||||
| -rw-r--r-- | lib/hook.h | 100 | ||||
| -rw-r--r-- | lib/if.c | 1451 | ||||
| -rw-r--r-- | lib/if.h | 505 | ||||
| -rw-r--r-- | lib/if_rmap.c | 404 | ||||
| -rw-r--r-- | lib/if_rmap.h | 30 | ||||
| -rw-r--r-- | lib/imsg-buffer.c | 105 | ||||
| -rw-r--r-- | lib/imsg.c | 117 | ||||
| -rw-r--r-- | lib/imsg.h | 110 | ||||
| -rw-r--r-- | lib/jhash.c | 232 | ||||
| -rw-r--r-- | lib/jhash.h | 6 | ||||
| -rw-r--r-- | lib/json.c | 66 | ||||
| -rw-r--r-- | lib/json.h | 27 | ||||
| -rw-r--r-- | lib/keychain.c | 1310 | ||||
| -rw-r--r-- | lib/keychain.h | 41 | ||||
| -rw-r--r-- | lib/libfrr.c | 142 | ||||
| -rw-r--r-- | lib/libfrr.h | 35 | ||||
| -rw-r--r-- | lib/linklist.c | 404 | ||||
| -rw-r--r-- | lib/linklist.h | 147 | ||||
| -rw-r--r-- | lib/log.c | 1651 | ||||
| -rw-r--r-- | lib/log.h | 127 | ||||
| -rw-r--r-- | lib/log_int.h | 36 | ||||
| -rw-r--r-- | lib/md5.c | 502 | ||||
| -rw-r--r-- | lib/md5.h | 34 | ||||
| -rw-r--r-- | lib/memory.c | 146 | ||||
| -rw-r--r-- | lib/memory.h | 184 | ||||
| -rw-r--r-- | lib/memory_vty.c | 231 | ||||
| -rw-r--r-- | lib/memory_vty.h | 4 | ||||
| -rw-r--r-- | lib/module.c | 28 | ||||
| -rw-r--r-- | lib/module.h | 20 | ||||
| -rw-r--r-- | lib/monotime.h | 58 | ||||
| -rw-r--r-- | lib/mpls.h | 134 | ||||
| -rw-r--r-- | lib/network.c | 147 | ||||
| -rw-r--r-- | lib/network.h | 12 | ||||
| -rw-r--r-- | lib/nexthop.c | 278 | ||||
| -rw-r--r-- | lib/nexthop.h | 108 | ||||
| -rw-r--r-- | lib/ns.c | 578 | ||||
| -rw-r--r-- | lib/ns.h | 38 | ||||
| -rw-r--r-- | lib/openbsd-queue.h | 740 | ||||
| -rw-r--r-- | lib/openbsd-tree.h | 1308 | ||||
| -rw-r--r-- | lib/pid_output.c | 81 | ||||
| -rw-r--r-- | lib/plist.c | 3839 | ||||
| -rw-r--r-- | lib/plist.h | 50 | ||||
| -rw-r--r-- | lib/plist_int.h | 58 | ||||
| -rw-r--r-- | lib/pqueue.c | 218 | ||||
| -rw-r--r-- | lib/pqueue.h | 29 | ||||
| -rw-r--r-- | lib/prefix.c | 1829 | ||||
| -rw-r--r-- | lib/prefix.h | 311 | ||||
| -rw-r--r-- | lib/privs.c | 1409 | ||||
| -rw-r--r-- | lib/privs.h | 98 | ||||
| -rw-r--r-- | lib/ptm_lib.c | 800 | ||||
| -rw-r--r-- | lib/ptm_lib.h | 31 | ||||
| -rw-r--r-- | lib/pw.h | 19 | ||||
| -rw-r--r-- | lib/qobj.c | 53 | ||||
| -rw-r--r-- | lib/qobj.h | 63 | ||||
| -rw-r--r-- | lib/queue.h | 892 | ||||
| -rw-r--r-- | lib/routemap.c | 4008 | ||||
| -rw-r--r-- | lib/routemap.h | 505 | ||||
| -rw-r--r-- | lib/sigevent.c | 434 | ||||
| -rw-r--r-- | lib/sigevent.h | 19 | ||||
| -rw-r--r-- | lib/skiplist.c | 883 | ||||
| -rw-r--r-- | lib/skiplist.h | 178 | ||||
| -rw-r--r-- | lib/smux.c | 2320 | ||||
| -rw-r--r-- | lib/smux.h | 83 | ||||
| -rw-r--r-- | lib/snmp.c | 144 | ||||
| -rw-r--r-- | lib/sockopt.c | 910 | ||||
| -rw-r--r-- | lib/sockopt.h | 60 | ||||
| -rw-r--r-- | lib/sockunion.c | 1007 | ||||
| -rw-r--r-- | lib/sockunion.h | 84 | ||||
| -rw-r--r-- | lib/spf_backoff.c | 418 | ||||
| -rw-r--r-- | lib/spf_backoff.h | 16 | ||||
| -rw-r--r-- | lib/srcdest_table.c | 412 | ||||
| -rw-r--r-- | lib/srcdest_table.h | 48 | ||||
| -rw-r--r-- | lib/stream.c | 1661 | ||||
| -rw-r--r-- | lib/stream.h | 180 | ||||
| -rw-r--r-- | lib/strlcat.c | 61 | ||||
| -rw-r--r-- | lib/strlcpy.c | 44 | ||||
| -rw-r--r-- | lib/systemd.c | 106 | ||||
| -rw-r--r-- | lib/systemd.h | 7 | ||||
| -rw-r--r-- | lib/table.c | 1138 | ||||
| -rw-r--r-- | lib/table.h | 282 | ||||
| -rw-r--r-- | lib/thread.c | 1840 | ||||
| -rw-r--r-- | lib/thread.h | 266 | ||||
| -rw-r--r-- | lib/vector.c | 198 | ||||
| -rw-r--r-- | lib/vector.h | 37 | ||||
| -rw-r--r-- | lib/vrf.c | 629 | ||||
| -rw-r--r-- | lib/vrf.h | 124 | ||||
| -rw-r--r-- | lib/vty.c | 4627 | ||||
| -rw-r--r-- | lib/vty.h | 432 | ||||
| -rw-r--r-- | lib/wheel.c | 169 | ||||
| -rw-r--r-- | lib/wheel.h | 45 | ||||
| -rw-r--r-- | lib/workqueue.c | 576 | ||||
| -rw-r--r-- | lib/workqueue.h | 155 | ||||
| -rw-r--r-- | lib/zassert.h | 15 | ||||
| -rw-r--r-- | lib/zclient.c | 3228 | ||||
| -rw-r--r-- | lib/zclient.h | 487 | ||||
| -rw-r--r-- | lib/zebra.h | 184 | 
127 files changed, 31870 insertions, 33338 deletions
diff --git a/lib/agentx.c b/lib/agentx.c index 11d5c9385d..c36e642c89 100644 --- a/lib/agentx.c +++ b/lib/agentx.c @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -41,131 +41,137 @@ static struct list *events = NULL;  static void agentx_events_update(void); -static int -agentx_timeout(struct thread *t) +static int agentx_timeout(struct thread *t)  { -  timeout_thr = NULL; +	timeout_thr = NULL; -  snmp_timeout (); -  run_alarms (); -  netsnmp_check_outstanding_agent_requests (); -  agentx_events_update (); -  return 0; +	snmp_timeout(); +	run_alarms(); +	netsnmp_check_outstanding_agent_requests(); +	agentx_events_update(); +	return 0;  } -static int -agentx_read(struct thread *t) +static int agentx_read(struct thread *t)  { -  fd_set fds; -  struct listnode *ln = THREAD_ARG (t); -  list_delete_node (events, ln); +	fd_set fds; +	struct listnode *ln = THREAD_ARG(t); +	list_delete_node(events, ln); -  FD_ZERO (&fds); -  FD_SET (THREAD_FD (t), &fds); -  snmp_read (&fds); +	FD_ZERO(&fds); +	FD_SET(THREAD_FD(t), &fds); +	snmp_read(&fds); -  netsnmp_check_outstanding_agent_requests (); -  agentx_events_update (); -  return 0; +	netsnmp_check_outstanding_agent_requests(); +	agentx_events_update(); +	return 0;  } -static void -agentx_events_update(void) +static void agentx_events_update(void)  { -  int maxfd = 0; -  int block = 1; -  struct timeval timeout = { .tv_sec = 0, .tv_usec = 0 }; -  fd_set fds; -  struct listnode *ln; -  struct thread *thr; -  int fd, thr_fd; - -  THREAD_OFF (timeout_thr); - -  FD_ZERO (&fds); -  snmp_select_info (&maxfd, &fds, &timeout, &block); - -  if (!block) -    timeout_thr = thread_add_timer_tv (agentx_tm, agentx_timeout, NULL, &timeout); - -  ln = listhead (events); -  thr = ln ? listgetdata (ln) : NULL; -  thr_fd = thr ? THREAD_FD (thr) : -1; - -  /* "two-pointer" / two-list simultaneous iteration -   * ln/thr/thr_fd point to the next existing event listener to hit while -   * fd counts to catch up */ -  for (fd = 0; fd < maxfd; fd++) -    { -      /* caught up */ -      if (thr_fd == fd) -        { -          struct listnode *nextln = listnextnode (ln); -          if (!FD_ISSET (fd, &fds)) -            { -              thread_cancel (thr); -              list_delete_node (events, ln); -            } -          ln = nextln; -          thr = ln ? listgetdata (ln) : NULL; -          thr_fd = thr ? THREAD_FD (thr) : -1; -        } -      /* need listener, but haven't hit one where it would be */ -      else if (FD_ISSET (fd, &fds)) -        { -          struct listnode *newln; -          thr = thread_add_read (agentx_tm, agentx_read, NULL, fd); -          newln = listnode_add_before (events, ln, thr); -          thr->arg = newln; -        } -    } - -  /* leftover event listeners at this point have fd > maxfd, delete them */ -  while (ln) -    { -      struct listnode *nextln = listnextnode (ln); -      thread_cancel (listgetdata (ln)); -      list_delete_node (events, ln); -      ln = nextln; -    } +	int maxfd = 0; +	int block = 1; +	struct timeval timeout = {.tv_sec = 0, .tv_usec = 0}; +	fd_set fds; +	struct listnode *ln; +	struct thread *thr; +	int fd, thr_fd; + +	THREAD_OFF(timeout_thr); + +	FD_ZERO(&fds); +	snmp_select_info(&maxfd, &fds, &timeout, &block); + +	if (!block) +		timeout_thr = thread_add_timer_tv(agentx_tm, agentx_timeout, +						  NULL, &timeout); + +	ln = listhead(events); +	thr = ln ? listgetdata(ln) : NULL; +	thr_fd = thr ? THREAD_FD(thr) : -1; + +	/* "two-pointer" / two-list simultaneous iteration +	 * ln/thr/thr_fd point to the next existing event listener to hit while +	 * fd counts to catch up */ +	for (fd = 0; fd < maxfd; fd++) { +		/* caught up */ +		if (thr_fd == fd) { +			struct listnode *nextln = listnextnode(ln); +			if (!FD_ISSET(fd, &fds)) { +				thread_cancel(thr); +				list_delete_node(events, ln); +			} +			ln = nextln; +			thr = ln ? listgetdata(ln) : NULL; +			thr_fd = thr ? THREAD_FD(thr) : -1; +		} +		/* need listener, but haven't hit one where it would be */ +		else if (FD_ISSET(fd, &fds)) { +			struct listnode *newln; +			thr = thread_add_read(agentx_tm, agentx_read, NULL, fd); +			newln = listnode_add_before(events, ln, thr); +			thr->arg = newln; +		} +	} + +	/* leftover event listeners at this point have fd > maxfd, delete them +	 */ +	while (ln) { +		struct listnode *nextln = listnextnode(ln); +		thread_cancel(listgetdata(ln)); +		list_delete_node(events, ln); +		ln = nextln; +	}  }  /* AgentX node. */ -static struct cmd_node agentx_node = -{ -  SMUX_NODE, -  ""                            /* AgentX has no interface. */ +static struct cmd_node agentx_node = { +	SMUX_NODE, "" /* AgentX has no interface. */  };  /* Logging NetSNMP messages */ -static int -agentx_log_callback(int major, int minor, -		    void *serverarg, void *clientarg) +static int agentx_log_callback(int major, int minor, void *serverarg, +			       void *clientarg)  { -  struct snmp_log_message *slm = (struct snmp_log_message *)serverarg; -  char *msg = XSTRDUP(MTYPE_TMP, slm->msg); -  if (msg) msg[strlen(msg)-1] = '\0'; -  switch (slm->priority) -    { -    case LOG_EMERG:   zlog_err   ("snmp[emerg]: %s",   msg?msg:slm->msg); break; -    case LOG_ALERT:   zlog_err   ("snmp[alert]: %s",   msg?msg:slm->msg); break; -    case LOG_CRIT:    zlog_err   ("snmp[crit]: %s",    msg?msg:slm->msg); break; -    case LOG_ERR:     zlog_err   ("snmp[err]: %s",     msg?msg:slm->msg); break; -    case LOG_WARNING: zlog_warn  ("snmp[warning]: %s", msg?msg:slm->msg); break; -    case LOG_NOTICE:  zlog_notice("snmp[notice]: %s",  msg?msg:slm->msg); break; -    case LOG_INFO:    zlog_info  ("snmp[info]: %s",    msg?msg:slm->msg); break; -    case LOG_DEBUG:   zlog_debug ("snmp[debug]: %s",   msg?msg:slm->msg); break; -    } -  XFREE(MTYPE_TMP, msg); -  return SNMP_ERR_NOERROR; +	struct snmp_log_message *slm = (struct snmp_log_message *)serverarg; +	char *msg = XSTRDUP(MTYPE_TMP, slm->msg); +	if (msg) +		msg[strlen(msg) - 1] = '\0'; +	switch (slm->priority) { +	case LOG_EMERG: +		zlog_err("snmp[emerg]: %s", msg ? msg : slm->msg); +		break; +	case LOG_ALERT: +		zlog_err("snmp[alert]: %s", msg ? msg : slm->msg); +		break; +	case LOG_CRIT: +		zlog_err("snmp[crit]: %s", msg ? msg : slm->msg); +		break; +	case LOG_ERR: +		zlog_err("snmp[err]: %s", msg ? msg : slm->msg); +		break; +	case LOG_WARNING: +		zlog_warn("snmp[warning]: %s", msg ? msg : slm->msg); +		break; +	case LOG_NOTICE: +		zlog_notice("snmp[notice]: %s", msg ? msg : slm->msg); +		break; +	case LOG_INFO: +		zlog_info("snmp[info]: %s", msg ? msg : slm->msg); +		break; +	case LOG_DEBUG: +		zlog_debug("snmp[debug]: %s", msg ? msg : slm->msg); +		break; +	} +	XFREE(MTYPE_TMP, msg); +	return SNMP_ERR_NOERROR;  } -static int -config_write_agentx (struct vty *vty) +static int config_write_agentx(struct vty *vty)  { -  if (agentx_enabled) -      vty_out (vty, "agentx%s", VTY_NEWLINE); -  return 0; +	if (agentx_enabled) +		vty_out(vty, "agentx%s", VTY_NEWLINE); +	return 0;  }  DEFUN (agentx_enable, @@ -174,16 +180,15 @@ DEFUN (agentx_enable,         "SNMP AgentX protocol settings\n"         "SNMP AgentX settings\n")  { -  if (!agentx_enabled) -    { -      init_snmp(FRR_SMUX_NAME); -      events = list_new(); -      agentx_events_update (); -      agentx_enabled = 1; -      return CMD_SUCCESS; -    } -  vty_out (vty, "SNMP AgentX already enabled%s", VTY_NEWLINE); -  return CMD_WARNING; +	if (!agentx_enabled) { +		init_snmp(FRR_SMUX_NAME); +		events = list_new(); +		agentx_events_update(); +		agentx_enabled = 1; +		return CMD_SUCCESS; +	} +	vty_out(vty, "SNMP AgentX already enabled%s", VTY_NEWLINE); +	return CMD_WARNING;  }  DEFUN (no_agentx, @@ -193,126 +198,120 @@ DEFUN (no_agentx,         "SNMP AgentX protocol settings\n"         "SNMP AgentX settings\n")  { -  if (!agentx_enabled) return CMD_SUCCESS; -  vty_out (vty, "SNMP AgentX support cannot be disabled once enabled%s", VTY_NEWLINE); -  return CMD_WARNING; +	if (!agentx_enabled) +		return CMD_SUCCESS; +	vty_out(vty, "SNMP AgentX support cannot be disabled once enabled%s", +		VTY_NEWLINE); +	return CMD_WARNING;  } -void -smux_init (struct thread_master *tm) +void smux_init(struct thread_master *tm)  { -  agentx_tm = tm; - -  netsnmp_enable_subagent (); -  snmp_disable_log (); -  snmp_enable_calllog (); -  snmp_register_callback (SNMP_CALLBACK_LIBRARY, -			  SNMP_CALLBACK_LOGGING, -			  agentx_log_callback, -			  NULL); -  init_agent (FRR_SMUX_NAME); - -  install_node (&agentx_node, config_write_agentx); -  install_element (CONFIG_NODE, &agentx_enable_cmd); -  install_element (CONFIG_NODE, &no_agentx_cmd); +	agentx_tm = tm; + +	netsnmp_enable_subagent(); +	snmp_disable_log(); +	snmp_enable_calllog(); +	snmp_register_callback(SNMP_CALLBACK_LIBRARY, SNMP_CALLBACK_LOGGING, +			       agentx_log_callback, NULL); +	init_agent(FRR_SMUX_NAME); + +	install_node(&agentx_node, config_write_agentx); +	install_element(CONFIG_NODE, &agentx_enable_cmd); +	install_element(CONFIG_NODE, &no_agentx_cmd);  } -void -smux_register_mib (const char *descr, struct variable *var,  -		   size_t width, int num, -		   oid name[], size_t namelen) +void smux_register_mib(const char *descr, struct variable *var, size_t width, +		       int num, oid name[], size_t namelen)  { -  register_mib (descr, var, width, num, name, namelen); +	register_mib(descr, var, width, num, name, namelen);  } -int -smux_trap (struct variable *vp, size_t vp_len, -	   const oid *ename, size_t enamelen, -	   const oid *name, size_t namelen, -	   const oid *iname, size_t inamelen, -	   const struct trap_object *trapobj, size_t trapobjlen, -	   u_char sptrap) +int smux_trap(struct variable *vp, size_t vp_len, const oid *ename, +	      size_t enamelen, const oid *name, size_t namelen, +	      const oid *iname, size_t inamelen, +	      const struct trap_object *trapobj, size_t trapobjlen, +	      u_char sptrap)  { -  oid objid_snmptrap[] = { 1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0 }; -  size_t objid_snmptrap_len = sizeof objid_snmptrap / sizeof (oid); -  oid notification_oid[MAX_OID_LEN]; -  size_t notification_oid_len; -  unsigned int i; - -  netsnmp_variable_list *notification_vars = NULL; -  if (!agentx_enabled) return 0; - -  /* snmpTrapOID */ -  oid_copy (notification_oid, ename, enamelen); -  notification_oid[enamelen] = sptrap; -  notification_oid_len = enamelen + 1; -  snmp_varlist_add_variable (¬ification_vars, -			     objid_snmptrap, objid_snmptrap_len, -			     ASN_OBJECT_ID, -			     (u_char *) notification_oid, -			     notification_oid_len * sizeof(oid)); - -  /* Provided bindings */ -  for (i = 0; i < trapobjlen; i++) -    { -      unsigned int j; -      oid oid[MAX_OID_LEN]; -      size_t oid_len, onamelen; -      u_char *val; -      size_t val_len; -      WriteMethod *wm = NULL; -      struct variable cvp; - -      /* Make OID. */ -      if (trapobj[i].namelen > 0) -        { -	  /* Columnar object */ -	  onamelen = trapobj[i].namelen; -	  oid_copy (oid, name, namelen); -	  oid_copy (oid + namelen, trapobj[i].name, onamelen); -	  oid_copy (oid + namelen + onamelen, iname, inamelen); -	  oid_len = namelen + onamelen + inamelen; -        } -      else -        { -	  /* Scalar object */ -	  onamelen = trapobj[i].namelen * (-1); -	  oid_copy (oid, name, namelen); -	  oid_copy (oid + namelen, trapobj[i].name, onamelen); -	  oid[onamelen + namelen] = 0; -	  oid_len = namelen + onamelen + 1; -        } - -      /* Locate the appropriate function and type in the MIB registry. */ -      for (j = 0; j < vp_len; j++) -	{ -	  if (oid_compare (trapobj[i].name, onamelen, vp[j].name, vp[j].namelen) != 0) -	    continue; -	  /* We found the appropriate variable in the MIB registry. */ -	  oid_copy(cvp.name, name, namelen); -	  oid_copy(cvp.name + namelen, vp[j].name, vp[j].namelen); -	  cvp.namelen = namelen + vp[j].namelen; -	  cvp.type = vp[j].type; -	  cvp.magic = vp[j].magic; -	  cvp.acl = vp[j].acl; -	  cvp.findVar = vp[j].findVar; -	  /* Grab the result. */ -	  val = cvp.findVar (&cvp, oid, &oid_len, 1, &val_len, &wm); -	  if (!val) break; -	  snmp_varlist_add_variable (¬ification_vars, -				     oid, oid_len, -				     vp[j].type, -				     val, -				     val_len); -	  break; +	oid objid_snmptrap[] = {1, 3, 6, 1, 6, 3, 1, 1, 4, 1, 0}; +	size_t objid_snmptrap_len = sizeof objid_snmptrap / sizeof(oid); +	oid notification_oid[MAX_OID_LEN]; +	size_t notification_oid_len; +	unsigned int i; + +	netsnmp_variable_list *notification_vars = NULL; +	if (!agentx_enabled) +		return 0; + +	/* snmpTrapOID */ +	oid_copy(notification_oid, ename, enamelen); +	notification_oid[enamelen] = sptrap; +	notification_oid_len = enamelen + 1; +	snmp_varlist_add_variable(¬ification_vars, objid_snmptrap, +				  objid_snmptrap_len, ASN_OBJECT_ID, +				  (u_char *)notification_oid, +				  notification_oid_len * sizeof(oid)); + +	/* Provided bindings */ +	for (i = 0; i < trapobjlen; i++) { +		unsigned int j; +		oid oid[MAX_OID_LEN]; +		size_t oid_len, onamelen; +		u_char *val; +		size_t val_len; +		WriteMethod *wm = NULL; +		struct variable cvp; + +		/* Make OID. */ +		if (trapobj[i].namelen > 0) { +			/* Columnar object */ +			onamelen = trapobj[i].namelen; +			oid_copy(oid, name, namelen); +			oid_copy(oid + namelen, trapobj[i].name, onamelen); +			oid_copy(oid + namelen + onamelen, iname, inamelen); +			oid_len = namelen + onamelen + inamelen; +		} else { +			/* Scalar object */ +			onamelen = trapobj[i].namelen * (-1); +			oid_copy(oid, name, namelen); +			oid_copy(oid + namelen, trapobj[i].name, onamelen); +			oid[onamelen + namelen] = 0; +			oid_len = namelen + onamelen + 1; +		} + +		/* Locate the appropriate function and type in the MIB registry. +		 */ +		for (j = 0; j < vp_len; j++) { +			if (oid_compare(trapobj[i].name, onamelen, vp[j].name, +					vp[j].namelen) +			    != 0) +				continue; +			/* We found the appropriate variable in the MIB +			 * registry. */ +			oid_copy(cvp.name, name, namelen); +			oid_copy(cvp.name + namelen, vp[j].name, vp[j].namelen); +			cvp.namelen = namelen + vp[j].namelen; +			cvp.type = vp[j].type; +			cvp.magic = vp[j].magic; +			cvp.acl = vp[j].acl; +			cvp.findVar = vp[j].findVar; +			/* Grab the result. */ +			val = cvp.findVar(&cvp, oid, &oid_len, 1, &val_len, +					  &wm); +			if (!val) +				break; +			snmp_varlist_add_variable(¬ification_vars, oid, +						  oid_len, vp[j].type, val, +						  val_len); +			break; +		}  	} -    } -  send_v2trap (notification_vars); -  snmp_free_varbind (notification_vars); -  agentx_events_update (); -  return 1; +	send_v2trap(notification_vars); +	snmp_free_varbind(notification_vars); +	agentx_events_update(); +	return 1;  }  #endif /* SNMP_AGENTX */ @@ -41,469 +41,436 @@ struct bfd_gbl bfd_gbl;  /*   * bfd_gbl_init - Initialize the BFD global structure   */ -void -bfd_gbl_init(void) +void bfd_gbl_init(void)  { -  memset(&bfd_gbl, 0, sizeof (struct bfd_gbl)); +	memset(&bfd_gbl, 0, sizeof(struct bfd_gbl));  }  /*   * bfd_gbl_exit - Called when daemon exits   */ -void -bfd_gbl_exit(void) +void bfd_gbl_exit(void)  { -  SET_FLAG (bfd_gbl.flags, BFD_GBL_FLAG_IN_SHUTDOWN); +	SET_FLAG(bfd_gbl.flags, BFD_GBL_FLAG_IN_SHUTDOWN);  }  /*   * bfd_info_create - Allocate the BFD information   */ -struct bfd_info * -bfd_info_create(void) +struct bfd_info *bfd_info_create(void)  { -  struct bfd_info *bfd_info; +	struct bfd_info *bfd_info; -  bfd_info = XCALLOC (MTYPE_BFD_INFO, sizeof (struct bfd_info)); -  assert(bfd_info); +	bfd_info = XCALLOC(MTYPE_BFD_INFO, sizeof(struct bfd_info)); +	assert(bfd_info); -  bfd_info->status = BFD_STATUS_UNKNOWN; -  bfd_info->type = BFD_TYPE_NOT_CONFIGURED; -  bfd_info->last_update = 0; -  return bfd_info; +	bfd_info->status = BFD_STATUS_UNKNOWN; +	bfd_info->type = BFD_TYPE_NOT_CONFIGURED; +	bfd_info->last_update = 0; +	return bfd_info;  }  /*   * bfd_info_free - Free the BFD information.   */ -void -bfd_info_free(struct bfd_info **bfd_info) +void bfd_info_free(struct bfd_info **bfd_info)  { -  if (*bfd_info) -    { -      XFREE (MTYPE_BFD_INFO, *bfd_info); -      *bfd_info = NULL; -    } +	if (*bfd_info) { +		XFREE(MTYPE_BFD_INFO, *bfd_info); +		*bfd_info = NULL; +	}  }  /*   * bfd_validate_param - Validate the BFD paramter information.   */ -int -bfd_validate_param(struct vty *vty, const char *dm_str, const char *rx_str, -                    const char *tx_str, u_int8_t *dm_val, u_int32_t *rx_val, -                    u_int32_t *tx_val) +int bfd_validate_param(struct vty *vty, const char *dm_str, const char *rx_str, +		       const char *tx_str, u_int8_t *dm_val, u_int32_t *rx_val, +		       u_int32_t *tx_val)  { -  VTY_GET_INTEGER_RANGE ("detect-mul", *dm_val, dm_str, -                         BFD_MIN_DETECT_MULT, BFD_MAX_DETECT_MULT); -  VTY_GET_INTEGER_RANGE ("min-rx", *rx_val, rx_str, -                         BFD_MIN_MIN_RX, BFD_MAX_MIN_RX); -  VTY_GET_INTEGER_RANGE ("min-tx", *tx_val, tx_str, -                         BFD_MIN_MIN_TX, BFD_MAX_MIN_TX); -  return CMD_SUCCESS; +	VTY_GET_INTEGER_RANGE("detect-mul", *dm_val, dm_str, +			      BFD_MIN_DETECT_MULT, BFD_MAX_DETECT_MULT); +	VTY_GET_INTEGER_RANGE("min-rx", *rx_val, rx_str, BFD_MIN_MIN_RX, +			      BFD_MAX_MIN_RX); +	VTY_GET_INTEGER_RANGE("min-tx", *tx_val, tx_str, BFD_MIN_MIN_TX, +			      BFD_MAX_MIN_TX); +	return CMD_SUCCESS;  }  /*   * bfd_set_param - Set the configured BFD paramter values   */ -void -bfd_set_param (struct bfd_info **bfd_info, u_int32_t min_rx, u_int32_t min_tx, -               u_int8_t detect_mult, int defaults, int *command) +void bfd_set_param(struct bfd_info **bfd_info, u_int32_t min_rx, +		   u_int32_t min_tx, u_int8_t detect_mult, int defaults, +		   int *command)  { -  if (!*bfd_info) -    { -      *bfd_info = bfd_info_create(); -      *command = ZEBRA_BFD_DEST_REGISTER; -    } -  else -    { -      if (((*bfd_info)->required_min_rx != min_rx) || -          ((*bfd_info)->desired_min_tx != min_tx) || -          ((*bfd_info)->detect_mult != detect_mult)) -        *command = ZEBRA_BFD_DEST_UPDATE; -    } - -  if (*command) -    { -      (*bfd_info)->required_min_rx = min_rx; -      (*bfd_info)->desired_min_tx = min_tx; -      (*bfd_info)->detect_mult = detect_mult; -    } - -  if (!defaults) -    SET_FLAG ((*bfd_info)->flags, BFD_FLAG_PARAM_CFG); -  else -    UNSET_FLAG ((*bfd_info)->flags, BFD_FLAG_PARAM_CFG); +	if (!*bfd_info) { +		*bfd_info = bfd_info_create(); +		*command = ZEBRA_BFD_DEST_REGISTER; +	} else { +		if (((*bfd_info)->required_min_rx != min_rx) +		    || ((*bfd_info)->desired_min_tx != min_tx) +		    || ((*bfd_info)->detect_mult != detect_mult)) +			*command = ZEBRA_BFD_DEST_UPDATE; +	} + +	if (*command) { +		(*bfd_info)->required_min_rx = min_rx; +		(*bfd_info)->desired_min_tx = min_tx; +		(*bfd_info)->detect_mult = detect_mult; +	} + +	if (!defaults) +		SET_FLAG((*bfd_info)->flags, BFD_FLAG_PARAM_CFG); +	else +		UNSET_FLAG((*bfd_info)->flags, BFD_FLAG_PARAM_CFG);  }  /*   * bfd_peer_sendmsg - Format and send a peer register/Unregister   *                    command to Zebra to be forwarded to BFD   */ -void -bfd_peer_sendmsg (struct zclient *zclient, struct bfd_info *bfd_info, -                  int family, void *dst_ip, void *src_ip, char *if_name, -                  int ttl, int multihop, int command, int set_flag, -                  vrf_id_t vrf_id) +void bfd_peer_sendmsg(struct zclient *zclient, struct bfd_info *bfd_info, +		      int family, void *dst_ip, void *src_ip, char *if_name, +		      int ttl, int multihop, int command, int set_flag, +		      vrf_id_t vrf_id)  { -  struct stream *s; -  int ret; -  int len; - -  /* Individual reg/dereg messages are supressed during shutdown. */ -  if (CHECK_FLAG (bfd_gbl.flags, BFD_GBL_FLAG_IN_SHUTDOWN)) -    { -      if (bfd_debug) -	zlog_debug("%s: Suppressing BFD peer reg/dereg messages", __FUNCTION__); -      return; -    } - -  /* Check socket. */ -  if (!zclient || zclient->sock < 0) -    { -      if (bfd_debug) -	zlog_debug("%s: Can't send BFD peer register, Zebra client not " -		   "established", __FUNCTION__); -      return; -    } - -  s = zclient->obuf; -  stream_reset (s); -  zclient_create_header (s, command, vrf_id); - -  stream_putl(s, getpid()); - -  stream_putw(s, family); -  switch (family) -    { -    case AF_INET: -      stream_put_in_addr (s, (struct in_addr *)dst_ip); -      break; -    case AF_INET6: -      stream_put(s, dst_ip, 16); -      break; -    default: -      break; -    } - -  if (command != ZEBRA_BFD_DEST_DEREGISTER) -    { -      stream_putl(s, bfd_info->required_min_rx); -      stream_putl(s, bfd_info->desired_min_tx); -      stream_putc(s, bfd_info->detect_mult); -    } - -  if (multihop) -    { -      stream_putc(s, 1); -      /* Multi-hop destination send the source IP address to BFD */ -      if (src_ip) -        { -          stream_putw(s, family); -          switch (family) -            { -            case AF_INET: -              stream_put_in_addr (s, (struct in_addr *) src_ip); -              break; -            case AF_INET6: -              stream_put(s, src_ip, 16); -              break; -            default: -              break; -            } -        } -      stream_putc(s, ttl); -    } -  else -    { -      stream_putc(s, 0); -      if ((family == AF_INET6) && (src_ip)) -        { -          stream_putw(s, family); -          stream_put(s, src_ip, 16); -        } -      if (if_name) -        { -          len = strlen(if_name); -          stream_putc(s, len); -          stream_put(s, if_name, len); -        } -      else -        { -          stream_putc(s, 0); -        } -    } - -  stream_putw_at (s, 0, stream_get_endp (s)); - -  ret = zclient_send_message(zclient); - -  if (ret < 0) -    { -      if (bfd_debug) -	zlog_debug("bfd_peer_sendmsg: zclient_send_message() failed"); -      return; -    } - -  if (set_flag) -    { -      if (command == ZEBRA_BFD_DEST_REGISTER) -        SET_FLAG(bfd_info->flags, BFD_FLAG_BFD_REG); -      else if (command == ZEBRA_BFD_DEST_DEREGISTER) -        UNSET_FLAG(bfd_info->flags, BFD_FLAG_BFD_REG); -    } - -  return; +	struct stream *s; +	int ret; +	int len; + +	/* Individual reg/dereg messages are supressed during shutdown. */ +	if (CHECK_FLAG(bfd_gbl.flags, BFD_GBL_FLAG_IN_SHUTDOWN)) { +		if (bfd_debug) +			zlog_debug( +				"%s: Suppressing BFD peer reg/dereg messages", +				__FUNCTION__); +		return; +	} + +	/* Check socket. */ +	if (!zclient || zclient->sock < 0) { +		if (bfd_debug) +			zlog_debug( +				"%s: Can't send BFD peer register, Zebra client not " +				"established", +				__FUNCTION__); +		return; +	} + +	s = zclient->obuf; +	stream_reset(s); +	zclient_create_header(s, command, vrf_id); + +	stream_putl(s, getpid()); + +	stream_putw(s, family); +	switch (family) { +	case AF_INET: +		stream_put_in_addr(s, (struct in_addr *)dst_ip); +		break; +	case AF_INET6: +		stream_put(s, dst_ip, 16); +		break; +	default: +		break; +	} + +	if (command != ZEBRA_BFD_DEST_DEREGISTER) { +		stream_putl(s, bfd_info->required_min_rx); +		stream_putl(s, bfd_info->desired_min_tx); +		stream_putc(s, bfd_info->detect_mult); +	} + +	if (multihop) { +		stream_putc(s, 1); +		/* Multi-hop destination send the source IP address to BFD */ +		if (src_ip) { +			stream_putw(s, family); +			switch (family) { +			case AF_INET: +				stream_put_in_addr(s, (struct in_addr *)src_ip); +				break; +			case AF_INET6: +				stream_put(s, src_ip, 16); +				break; +			default: +				break; +			} +		} +		stream_putc(s, ttl); +	} else { +		stream_putc(s, 0); +		if ((family == AF_INET6) && (src_ip)) { +			stream_putw(s, family); +			stream_put(s, src_ip, 16); +		} +		if (if_name) { +			len = strlen(if_name); +			stream_putc(s, len); +			stream_put(s, if_name, len); +		} else { +			stream_putc(s, 0); +		} +	} + +	stream_putw_at(s, 0, stream_get_endp(s)); + +	ret = zclient_send_message(zclient); + +	if (ret < 0) { +		if (bfd_debug) +			zlog_debug( +				"bfd_peer_sendmsg: zclient_send_message() failed"); +		return; +	} + +	if (set_flag) { +		if (command == ZEBRA_BFD_DEST_REGISTER) +			SET_FLAG(bfd_info->flags, BFD_FLAG_BFD_REG); +		else if (command == ZEBRA_BFD_DEST_DEREGISTER) +			UNSET_FLAG(bfd_info->flags, BFD_FLAG_BFD_REG); +	} + +	return;  }  /*   * bfd_get_command_dbg_str - Convert command to a debug string.   */ -const char * -bfd_get_command_dbg_str(int command) +const char *bfd_get_command_dbg_str(int command)  { -  switch (command) -  { -    case ZEBRA_BFD_DEST_REGISTER: -      return "Register"; -    case ZEBRA_BFD_DEST_DEREGISTER: -      return "Deregister"; -    case ZEBRA_BFD_DEST_UPDATE: -      return "Update"; -    default: -      return "Unknown"; -  } +	switch (command) { +	case ZEBRA_BFD_DEST_REGISTER: +		return "Register"; +	case ZEBRA_BFD_DEST_DEREGISTER: +		return "Deregister"; +	case ZEBRA_BFD_DEST_UPDATE: +		return "Update"; +	default: +		return "Unknown"; +	}  }  /*   * bfd_get_peer_info - Extract the Peer information for which the BFD session   *                     went down from the message sent from Zebra to clients.   */ -struct interface * -bfd_get_peer_info (struct stream *s, struct prefix *dp, struct prefix *sp, -                    int *status, vrf_id_t vrf_id) +struct interface *bfd_get_peer_info(struct stream *s, struct prefix *dp, +				    struct prefix *sp, int *status, +				    vrf_id_t vrf_id)  { -  unsigned int ifindex; -  struct interface *ifp = NULL; -  int plen; - -  /* Get interface index. */ -  ifindex = stream_getl (s); - -  /* Lookup index. */ -  if (ifindex != 0) -    { -      ifp = if_lookup_by_index (ifindex, vrf_id); -      if (ifp == NULL) -        { -	  if (bfd_debug) -	    zlog_debug ("zebra_interface_bfd_read: " -			"Can't find interface by ifindex: %d ", ifindex); -          return NULL; -        } -    } - -  /* Fetch destination address. */ -  dp->family = stream_getc (s); - -  plen = prefix_blen (dp); -  stream_get (&dp->u.prefix, s, plen); -  dp->prefixlen = stream_getc (s); - -  /* Get BFD status. */ -  *status = stream_getl (s); - -  if (sp) -    { -      sp->family = stream_getc (s); - -      plen = prefix_blen (sp); -      stream_get (&sp->u.prefix, s, plen); -      sp->prefixlen = stream_getc (s); -    } -  return ifp; +	unsigned int ifindex; +	struct interface *ifp = NULL; +	int plen; + +	/* Get interface index. */ +	ifindex = stream_getl(s); + +	/* Lookup index. */ +	if (ifindex != 0) { +		ifp = if_lookup_by_index(ifindex, vrf_id); +		if (ifp == NULL) { +			if (bfd_debug) +				zlog_debug( +					"zebra_interface_bfd_read: " +					"Can't find interface by ifindex: %d ", +					ifindex); +			return NULL; +		} +	} + +	/* Fetch destination address. */ +	dp->family = stream_getc(s); + +	plen = prefix_blen(dp); +	stream_get(&dp->u.prefix, s, plen); +	dp->prefixlen = stream_getc(s); + +	/* Get BFD status. */ +	*status = stream_getl(s); + +	if (sp) { +		sp->family = stream_getc(s); + +		plen = prefix_blen(sp); +		stream_get(&sp->u.prefix, s, plen); +		sp->prefixlen = stream_getc(s); +	} +	return ifp;  }  /*   * bfd_get_status_str - Convert BFD status to a display string.   */ -const char * -bfd_get_status_str(int status) +const char *bfd_get_status_str(int status)  { -  switch (status) -  { -    case BFD_STATUS_DOWN: -      return "Down"; -    case BFD_STATUS_UP: -      return "Up"; -    case BFD_STATUS_UNKNOWN: -    default: -      return "Unknown"; -  } +	switch (status) { +	case BFD_STATUS_DOWN: +		return "Down"; +	case BFD_STATUS_UP: +		return "Up"; +	case BFD_STATUS_UNKNOWN: +	default: +		return "Unknown"; +	}  }  /*   * bfd_last_update - Calculate the last BFD update time and convert it   *                   into a dd:hh:mm:ss display format.   */ -static void -bfd_last_update (time_t last_update, char *buf, size_t len) +static void bfd_last_update(time_t last_update, char *buf, size_t len)  { -  time_t curr; -  time_t diff; -  struct tm *tm; -  struct timeval tv; - -  /* If no BFD satatus update has ever been received, print `never'. */ -  if (last_update == 0) -    { -      snprintf (buf, len, "never"); -      return; -    } - -  /* Get current time. */ -  monotime(&tv); -  curr = tv.tv_sec; -  diff = curr - last_update; -  tm = gmtime (&diff); - -  snprintf (buf, len, "%d:%02d:%02d:%02d", -            tm->tm_yday, tm->tm_hour, tm->tm_min, tm->tm_sec); +	time_t curr; +	time_t diff; +	struct tm *tm; +	struct timeval tv; + +	/* If no BFD satatus update has ever been received, print `never'. */ +	if (last_update == 0) { +		snprintf(buf, len, "never"); +		return; +	} + +	/* Get current time. */ +	monotime(&tv); +	curr = tv.tv_sec; +	diff = curr - last_update; +	tm = gmtime(&diff); + +	snprintf(buf, len, "%d:%02d:%02d:%02d", tm->tm_yday, tm->tm_hour, +		 tm->tm_min, tm->tm_sec);  }  /*   * bfd_show_param - Show the BFD parameter information.   */ -void -bfd_show_param(struct vty *vty, struct bfd_info *bfd_info, int bfd_tag, -                int extra_space, u_char use_json, json_object *json_obj) +void bfd_show_param(struct vty *vty, struct bfd_info *bfd_info, int bfd_tag, +		    int extra_space, u_char use_json, json_object *json_obj)  { -  json_object *json_bfd = NULL; - -  if (!bfd_info) -    return; - -  if (use_json) -    { -      if (bfd_tag) -        json_bfd = json_object_new_object(); -      else -        json_bfd = json_obj; - -      json_object_int_add(json_bfd, "detectMultiplier", bfd_info->detect_mult); -      json_object_int_add(json_bfd, "rxMinInterval", bfd_info->required_min_rx); -      json_object_int_add(json_bfd, "txMinInterval", bfd_info->desired_min_tx); -      if (bfd_tag) -        json_object_object_add(json_obj, "peerBfdInfo", json_bfd); -    } -  else -    { -      vty_out (vty, "  %s%sDetect Mul: %d, Min Rx interval: %d," -                " Min Tx interval: %d%s", -                    (extra_space) ? "  ": "", (bfd_tag) ? "BFD: " : "  ", -                    bfd_info->detect_mult, bfd_info->required_min_rx, -                    bfd_info->desired_min_tx, VTY_NEWLINE); -    } +	json_object *json_bfd = NULL; + +	if (!bfd_info) +		return; + +	if (use_json) { +		if (bfd_tag) +			json_bfd = json_object_new_object(); +		else +			json_bfd = json_obj; + +		json_object_int_add(json_bfd, "detectMultiplier", +				    bfd_info->detect_mult); +		json_object_int_add(json_bfd, "rxMinInterval", +				    bfd_info->required_min_rx); +		json_object_int_add(json_bfd, "txMinInterval", +				    bfd_info->desired_min_tx); +		if (bfd_tag) +			json_object_object_add(json_obj, "peerBfdInfo", +					       json_bfd); +	} else { +		vty_out(vty, +			"  %s%sDetect Mul: %d, Min Rx interval: %d," +			" Min Tx interval: %d%s", +			(extra_space) ? "  " : "", (bfd_tag) ? "BFD: " : "  ", +			bfd_info->detect_mult, bfd_info->required_min_rx, +			bfd_info->desired_min_tx, VTY_NEWLINE); +	}  }  /*   * bfd_show_status - Show the BFD status information.   */ -static void -bfd_show_status(struct vty *vty, struct bfd_info *bfd_info, int bfd_tag, -                int extra_space, u_char use_json, json_object *json_bfd) +static void bfd_show_status(struct vty *vty, struct bfd_info *bfd_info, +			    int bfd_tag, int extra_space, u_char use_json, +			    json_object *json_bfd)  { -  char time_buf[32]; - -  if (!bfd_info) -    return; - -  bfd_last_update(bfd_info->last_update, time_buf, 32); -  if (use_json) -    { -      json_object_string_add(json_bfd, "status", -                              bfd_get_status_str(bfd_info->status)); -      json_object_string_add(json_bfd, "lastUpdate", time_buf); -    } -  else -    { -      vty_out (vty, "  %s%sStatus: %s, Last update: %s%s", -                  (extra_space) ? "  ": "", (bfd_tag) ? "BFD: " : "  ", -                  bfd_get_status_str(bfd_info->status), time_buf, VTY_NEWLINE); -    } +	char time_buf[32]; + +	if (!bfd_info) +		return; + +	bfd_last_update(bfd_info->last_update, time_buf, 32); +	if (use_json) { +		json_object_string_add(json_bfd, "status", +				       bfd_get_status_str(bfd_info->status)); +		json_object_string_add(json_bfd, "lastUpdate", time_buf); +	} else { +		vty_out(vty, "  %s%sStatus: %s, Last update: %s%s", +			(extra_space) ? "  " : "", (bfd_tag) ? "BFD: " : "  ", +			bfd_get_status_str(bfd_info->status), time_buf, +			VTY_NEWLINE); +	}  }  /*   * bfd_show_info - Show the BFD information.   */ -void -bfd_show_info(struct vty *vty, struct bfd_info *bfd_info, int multihop, -              int extra_space, u_char use_json, json_object *json_obj) +void bfd_show_info(struct vty *vty, struct bfd_info *bfd_info, int multihop, +		   int extra_space, u_char use_json, json_object *json_obj)  { -  json_object *json_bfd = NULL; - -  if (!bfd_info) -    return; - -  if (use_json) -    { -      json_bfd = json_object_new_object(); -      if (multihop) -        json_object_string_add(json_bfd, "type", "multi hop"); -      else -        json_object_string_add(json_bfd, "type", "single hop"); -    } -  else -    { -      vty_out (vty, "  %sBFD: Type: %s%s", (extra_space) ? "  " : "", -              (multihop) ? "multi hop" : "single hop", VTY_NEWLINE); -    } - -  bfd_show_param(vty, bfd_info, 0, extra_space, use_json, json_bfd); -  bfd_show_status(vty, bfd_info, 0, extra_space, use_json, json_bfd); - -  if (use_json) -    json_object_object_add(json_obj, "peerBfdInfo", json_bfd); -  else -    vty_out (vty, "%s", VTY_NEWLINE); +	json_object *json_bfd = NULL; + +	if (!bfd_info) +		return; + +	if (use_json) { +		json_bfd = json_object_new_object(); +		if (multihop) +			json_object_string_add(json_bfd, "type", "multi hop"); +		else +			json_object_string_add(json_bfd, "type", "single hop"); +	} else { +		vty_out(vty, "  %sBFD: Type: %s%s", (extra_space) ? "  " : "", +			(multihop) ? "multi hop" : "single hop", VTY_NEWLINE); +	} + +	bfd_show_param(vty, bfd_info, 0, extra_space, use_json, json_bfd); +	bfd_show_status(vty, bfd_info, 0, extra_space, use_json, json_bfd); + +	if (use_json) +		json_object_object_add(json_obj, "peerBfdInfo", json_bfd); +	else +		vty_out(vty, "%s", VTY_NEWLINE);  }  /*   * bfd_client_sendmsg - Format and send a client register   *                    command to Zebra to be forwarded to BFD   */ -void -bfd_client_sendmsg (struct zclient *zclient, int command) +void bfd_client_sendmsg(struct zclient *zclient, int command)  { -  struct stream *s; -  int ret; - -  /* Check socket. */ -  if (!zclient || zclient->sock < 0) -    { -      if (bfd_debug) -	zlog_debug ("%s: Can't send BFD client register, Zebra client not " -		   "established", __FUNCTION__); -      return; -    } - -  s = zclient->obuf; -  stream_reset (s); -  zclient_create_header (s, command, VRF_DEFAULT); - -  stream_putl(s, getpid()); - -  stream_putw_at (s, 0, stream_get_endp (s)); - -  ret = zclient_send_message(zclient); - -  if (ret < 0) -    { -      if (bfd_debug) -	zlog_debug ("bfd_client_sendmsg %ld: zclient_send_message() failed", -		   (long) getpid()); -      return; -    } - -  return; +	struct stream *s; +	int ret; + +	/* Check socket. */ +	if (!zclient || zclient->sock < 0) { +		if (bfd_debug) +			zlog_debug( +				"%s: Can't send BFD client register, Zebra client not " +				"established", +				__FUNCTION__); +		return; +	} + +	s = zclient->obuf; +	stream_reset(s); +	zclient_create_header(s, command, VRF_DEFAULT); + +	stream_putl(s, getpid()); + +	stream_putw_at(s, 0, stream_get_endp(s)); + +	ret = zclient_send_message(zclient); + +	if (ret < 0) { +		if (bfd_debug) +			zlog_debug( +				"bfd_client_sendmsg %ld: zclient_send_message() failed", +				(long)getpid()); +		return; +	} + +	return;  } @@ -37,9 +37,8 @@  #define BFD_MAX_DETECT_MULT 255  #define BFD_GBL_FLAG_IN_SHUTDOWN (1 << 0) /* The daemon in shutdown */ -struct bfd_gbl -{ -  u_int16_t           flags; +struct bfd_gbl { +	u_int16_t flags;  };  #define BFD_FLAG_PARAM_CFG (1 << 0) /* parameters have been configured */ @@ -51,67 +50,58 @@ struct bfd_gbl  #define BFD_STATUS_UP      (1 << 2) /* BFD session status is up */  enum bfd_sess_type { -  BFD_TYPE_NOT_CONFIGURED, -  BFD_TYPE_SINGLEHOP, -  BFD_TYPE_MULTIHOP +	BFD_TYPE_NOT_CONFIGURED, +	BFD_TYPE_SINGLEHOP, +	BFD_TYPE_MULTIHOP  }; -struct bfd_info -{ -  u_int16_t           flags; -  u_int8_t            detect_mult; -  u_int32_t           desired_min_tx; -  u_int32_t           required_min_rx; -  time_t              last_update; -  u_int8_t            status; -  enum bfd_sess_type  type; +struct bfd_info { +	u_int16_t flags; +	u_int8_t detect_mult; +	u_int32_t desired_min_tx; +	u_int32_t required_min_rx; +	time_t last_update; +	u_int8_t status; +	enum bfd_sess_type type;  }; -extern struct bfd_info * -bfd_info_create(void); +extern struct bfd_info *bfd_info_create(void); -extern void -bfd_info_free(struct bfd_info **bfd_info); +extern void bfd_info_free(struct bfd_info **bfd_info); -extern int -bfd_validate_param(struct vty *vty, const char *dm_str, const char *rx_str, -                   const char *tx_str, u_int8_t *dm_val, u_int32_t *rx_val, -                   u_int32_t *tx_val); +extern int bfd_validate_param(struct vty *vty, const char *dm_str, +			      const char *rx_str, const char *tx_str, +			      u_int8_t *dm_val, u_int32_t *rx_val, +			      u_int32_t *tx_val); -extern void -bfd_set_param (struct bfd_info **bfd_info, u_int32_t min_rx, u_int32_t min_tx, -               u_int8_t detect_mult, int defaults, int *command); -extern void -bfd_peer_sendmsg (struct zclient *zclient, struct bfd_info *bfd_info, -                  int family, void *dst_ip, void *src_ip, char *if_name, -                  int ttl, int multihop, int command, int set_flag, -                  vrf_id_t vrf_id); +extern void bfd_set_param(struct bfd_info **bfd_info, u_int32_t min_rx, +			  u_int32_t min_tx, u_int8_t detect_mult, int defaults, +			  int *command); +extern void bfd_peer_sendmsg(struct zclient *zclient, struct bfd_info *bfd_info, +			     int family, void *dst_ip, void *src_ip, +			     char *if_name, int ttl, int multihop, int command, +			     int set_flag, vrf_id_t vrf_id); -extern const char * -bfd_get_command_dbg_str(int command); +extern const char *bfd_get_command_dbg_str(int command); -extern struct interface * -bfd_get_peer_info (struct stream *s, struct prefix *dp, struct prefix *sp, -                   int *status, vrf_id_t vrf_id); +extern struct interface *bfd_get_peer_info(struct stream *s, struct prefix *dp, +					   struct prefix *sp, int *status, +					   vrf_id_t vrf_id); -const char * -bfd_get_status_str(int status); +const char *bfd_get_status_str(int status); -extern void -bfd_show_param(struct vty *vty, struct bfd_info *bfd_info, int bfd_tag, -                int extra_space, u_char use_json, json_object *json_obj); +extern void bfd_show_param(struct vty *vty, struct bfd_info *bfd_info, +			   int bfd_tag, int extra_space, u_char use_json, +			   json_object *json_obj); -extern void -bfd_show_info(struct vty *vty, struct bfd_info *bfd_info, int multihop, -              int extra_space, u_char use_json, json_object *json_obj); +extern void bfd_show_info(struct vty *vty, struct bfd_info *bfd_info, +			  int multihop, int extra_space, u_char use_json, +			  json_object *json_obj); -extern void -bfd_client_sendmsg (struct zclient *zclient, int command); +extern void bfd_client_sendmsg(struct zclient *zclient, int command); -extern void -bfd_gbl_init(void); +extern void bfd_gbl_init(void); -extern void -bfd_gbl_exit(void); +extern void bfd_gbl_exit(void);  #endif /* _ZEBRA_BFD_H */ diff --git a/lib/bitfield.h b/lib/bitfield.h index 7062796a99..e6020f0238 100644 --- a/lib/bitfield.h +++ b/lib/bitfield.h @@ -63,27 +63,27 @@ typedef unsigned int word_t;   * @N: number of bits to start with, which equates to how many   *     IDs can be allocated.   */ -#define bf_init(v, N)				    \ -  do {						    \ -    (v).n = 0;					    \ -    (v).m = ((N) / WORD_SIZE + 1);		    \ -    (v).data = calloc(1, ((v).m * sizeof(word_t))); \ -  } while (0) +#define bf_init(v, N)                                                          \ +	do {                                                                   \ +		(v).n = 0;                                                     \ +		(v).m = ((N) / WORD_SIZE + 1);                                 \ +		(v).data = calloc(1, ((v).m * sizeof(word_t)));                \ +	} while (0)  /**   * allocate and assign an id from bitfield v.   */ -#define bf_assign_index(v, id)				\ -  do {							\ -    bf_find_bit(v, id);					\ -    bf_set_bit(v, id);					\ -  } while (0) +#define bf_assign_index(v, id)                                                 \ +	do {                                                                   \ +		bf_find_bit(v, id);                                            \ +		bf_set_bit(v, id);                                             \ +	} while (0)  /**   * return an id to bitfield v   */ -#define bf_release_index(v, id)			\ -  (v).data[bf_index(id)] &= ~(1 << (bf_offset(id))) +#define bf_release_index(v, id)                                                \ +	(v).data[bf_index(id)] &= ~(1 << (bf_offset(id)))  #define bf_index(b) ((b) / WORD_SIZE)  #define bf_offset(b) ((b) % WORD_SIZE) @@ -92,31 +92,41 @@ typedef unsigned int word_t;   * Set a bit in the array. If it fills up that word and we are   * out of words, extend it by one more word.   */ -#define bf_set_bit(v, b)					\ -  do {								\ -    size_t w = bf_index(b);					\ -    (v).data[w] |= 1 << (bf_offset(b));				\ -    (v).n += ((v).data[w] == WORD_MAX);				\ -    if ((v).n == (v).m) {					\ -      (v).m = (v).m + 1;					\ -      (v).data = realloc((v).data, (v).m * sizeof(word_t));	\ -    }								\ -  } while (0) +#define bf_set_bit(v, b)                                                       \ +	do {                                                                   \ +		size_t w = bf_index(b);                                        \ +		(v).data[w] |= 1 << (bf_offset(b));                            \ +		(v).n += ((v).data[w] == WORD_MAX);                            \ +		if ((v).n == (v).m) {                                          \ +			(v).m = (v).m + 1;                                     \ +			(v).data = realloc((v).data, (v).m * sizeof(word_t));  \ +		}                                                              \ +	} while (0)  /* Find a clear bit in v and assign it to b. */ -#define bf_find_bit(v, b)					\ -  do {								\ -    word_t word = 0;						\ -    unsigned int w, sh;						\ -    for (w = 0; w <= (v).n; w++) {				\ -      if ((word = (v).data[w]) != WORD_MAX) break;		\ -    }								\ -    (b) = ((word & 0xFFFF) == 0xFFFF) << 4; word >>= (b);	\ -    sh = ((word & 0xFF) == 0xFF) << 3; word >>= sh; (b) |= sh;	\ -    sh = ((word & 0xF) == 0xF) << 2; word >>= sh; (b) |= sh;	\ -    sh = ((word & 0x3) == 0x3) << 1; word >>= sh; (b) |= sh;	\ -    sh = ((word & 0x1) == 0x1) << 0; word >>= sh; (b) |= sh;	\ -    (b) += (w * WORD_SIZE);					\ -  } while (0) +#define bf_find_bit(v, b)                                                      \ +	do {                                                                   \ +		word_t word = 0;                                               \ +		unsigned int w, sh;                                            \ +		for (w = 0; w <= (v).n; w++) {                                 \ +			if ((word = (v).data[w]) != WORD_MAX)                  \ +				break;                                         \ +		}                                                              \ +		(b) = ((word & 0xFFFF) == 0xFFFF) << 4;                        \ +		word >>= (b);                                                  \ +		sh = ((word & 0xFF) == 0xFF) << 3;                             \ +		word >>= sh;                                                   \ +		(b) |= sh;                                                     \ +		sh = ((word & 0xF) == 0xF) << 2;                               \ +		word >>= sh;                                                   \ +		(b) |= sh;                                                     \ +		sh = ((word & 0x3) == 0x3) << 1;                               \ +		word >>= sh;                                                   \ +		(b) |= sh;                                                     \ +		sh = ((word & 0x1) == 0x1) << 0;                               \ +		word >>= sh;                                                   \ +		(b) |= sh;                                                     \ +		(b) += (w * WORD_SIZE);                                        \ +	} while (0)  #endif diff --git a/lib/buffer.c b/lib/buffer.c index 1dfcdb4732..192a647eca 100644 --- a/lib/buffer.c +++ b/lib/buffer.c @@ -1,5 +1,5 @@  /* - * Buffering of output and input.  + * Buffering of output and input.   * Copyright (C) 1998 Kunihiro Ishiguro   *   * This file is part of GNU Zebra. @@ -8,7 +8,7 @@   * it under the terms of the GNU General Public License as published   * by the Free Software Foundation; either version 2, or (at your   * option) any later version. - *  + *   * GNU Zebra is distributed in the hope that it will be useful, but   * WITHOUT ANY WARRANTY; without even the implied warranty of   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the   * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA.  + * Boston, MA 02111-1307, USA.   */  #include <zebra.h> @@ -28,33 +28,31 @@  #include "network.h"  #include <stddef.h> -DEFINE_MTYPE_STATIC(LIB, BUFFER,      "Buffer") +DEFINE_MTYPE_STATIC(LIB, BUFFER, "Buffer")  DEFINE_MTYPE_STATIC(LIB, BUFFER_DATA, "Buffer data")  /* Buffer master. */ -struct buffer -{ -  /* Data list. */ -  struct buffer_data *head; -  struct buffer_data *tail; -   -  /* Size of each buffer_data chunk. */ -  size_t size; +struct buffer { +	/* Data list. */ +	struct buffer_data *head; +	struct buffer_data *tail; + +	/* Size of each buffer_data chunk. */ +	size_t size;  };  /* Data container. */ -struct buffer_data -{ -  struct buffer_data *next; +struct buffer_data { +	struct buffer_data *next; -  /* Location to add new data. */ -  size_t cp; +	/* Location to add new data. */ +	size_t cp; -  /* Pointer to data not yet flushed. */ -  size_t sp; +	/* Pointer to data not yet flushed. */ +	size_t sp; -  /* Actual data stream (variable length). */ -  unsigned char data[];  /* real dimension is buffer->size */ +	/* Actual data stream (variable length). */ +	unsigned char data[]; /* real dimension is buffer->size */  };  /* It should always be true that: 0 <= sp <= cp <= size */ @@ -63,327 +61,308 @@ struct buffer_data     next page boundery. */  #define BUFFER_SIZE_DEFAULT		4096 -  #define BUFFER_DATA_FREE(D) XFREE(MTYPE_BUFFER_DATA, (D))  /* Make new buffer. */ -struct buffer * -buffer_new (size_t size) +struct buffer *buffer_new(size_t size)  { -  struct buffer *b; - -  b = XCALLOC (MTYPE_BUFFER, sizeof (struct buffer)); - -  if (size) -    b->size = size; -  else -    { -      static size_t default_size; -      if (!default_size) -        { -	  long pgsz = sysconf(_SC_PAGESIZE); -	  default_size = ((((BUFFER_SIZE_DEFAULT-1)/pgsz)+1)*pgsz); +	struct buffer *b; + +	b = XCALLOC(MTYPE_BUFFER, sizeof(struct buffer)); + +	if (size) +		b->size = size; +	else { +		static size_t default_size; +		if (!default_size) { +			long pgsz = sysconf(_SC_PAGESIZE); +			default_size = ((((BUFFER_SIZE_DEFAULT - 1) / pgsz) + 1) +					* pgsz); +		} +		b->size = default_size;  	} -      b->size = default_size; -    } -  return b; +	return b;  }  /* Free buffer. */ -void -buffer_free (struct buffer *b) +void buffer_free(struct buffer *b)  { -  buffer_reset(b); -  XFREE (MTYPE_BUFFER, b); +	buffer_reset(b); +	XFREE(MTYPE_BUFFER, b);  }  /* Make string clone. */ -char * -buffer_getstr (struct buffer *b) +char *buffer_getstr(struct buffer *b)  { -  size_t totlen = 0; -  struct buffer_data *data; -  char *s; -  char *p; - -  for (data = b->head; data; data = data->next) -    totlen += data->cp - data->sp; -  if (!(s = XMALLOC(MTYPE_TMP, totlen+1))) -    return NULL; -  p = s; -  for (data = b->head; data; data = data->next) -    { -      memcpy(p, data->data + data->sp, data->cp - data->sp); -      p += data->cp - data->sp; -    } -  *p = '\0'; -  return s; +	size_t totlen = 0; +	struct buffer_data *data; +	char *s; +	char *p; + +	for (data = b->head; data; data = data->next) +		totlen += data->cp - data->sp; +	if (!(s = XMALLOC(MTYPE_TMP, totlen + 1))) +		return NULL; +	p = s; +	for (data = b->head; data; data = data->next) { +		memcpy(p, data->data + data->sp, data->cp - data->sp); +		p += data->cp - data->sp; +	} +	*p = '\0'; +	return s;  }  /* Return 1 if buffer is empty. */ -int -buffer_empty (struct buffer *b) +int buffer_empty(struct buffer *b)  { -  return (b->head == NULL); +	return (b->head == NULL);  }  /* Clear and free all allocated data. */ -void -buffer_reset (struct buffer *b) +void buffer_reset(struct buffer *b)  { -  struct buffer_data *data; -  struct buffer_data *next; -   -  for (data = b->head; data; data = next) -    { -      next = data->next; -      BUFFER_DATA_FREE(data); -    } -  b->head = b->tail = NULL; +	struct buffer_data *data; +	struct buffer_data *next; + +	for (data = b->head; data; data = next) { +		next = data->next; +		BUFFER_DATA_FREE(data); +	} +	b->head = b->tail = NULL;  }  /* Add buffer_data to the end of buffer. */ -static struct buffer_data * -buffer_add (struct buffer *b) +static struct buffer_data *buffer_add(struct buffer *b)  { -  struct buffer_data *d; +	struct buffer_data *d; -  d = XMALLOC(MTYPE_BUFFER_DATA, offsetof(struct buffer_data, data) + b->size); -  d->cp = d->sp = 0; -  d->next = NULL; +	d = XMALLOC(MTYPE_BUFFER_DATA, +		    offsetof(struct buffer_data, data) + b->size); +	d->cp = d->sp = 0; +	d->next = NULL; -  if (b->tail) -    b->tail->next = d; -  else -    b->head = d; -  b->tail = d; +	if (b->tail) +		b->tail->next = d; +	else +		b->head = d; +	b->tail = d; -  return d; +	return d;  }  /* Write data to buffer. */ -void -buffer_put(struct buffer *b, const void *p, size_t size) +void buffer_put(struct buffer *b, const void *p, size_t size)  { -  struct buffer_data *data = b->tail; -  const char *ptr = p; - -  /* We use even last one byte of data buffer. */ -  while (size)     -    { -      size_t chunk; - -      /* If there is no data buffer add it. */ -      if (data == NULL || data->cp == b->size) -	data = buffer_add (b); - -      chunk = ((size <= (b->size - data->cp)) ? size : (b->size - data->cp)); -      memcpy ((data->data + data->cp), ptr, chunk); -      size -= chunk; -      ptr += chunk; -      data->cp += chunk; -    } +	struct buffer_data *data = b->tail; +	const char *ptr = p; + +	/* We use even last one byte of data buffer. */ +	while (size) { +		size_t chunk; + +		/* If there is no data buffer add it. */ +		if (data == NULL || data->cp == b->size) +			data = buffer_add(b); + +		chunk = ((size <= (b->size - data->cp)) ? size +							: (b->size - data->cp)); +		memcpy((data->data + data->cp), ptr, chunk); +		size -= chunk; +		ptr += chunk; +		data->cp += chunk; +	}  }  /* Insert character into the buffer. */ -void -buffer_putc (struct buffer *b, u_char c) +void buffer_putc(struct buffer *b, u_char c)  { -  buffer_put(b, &c, 1); +	buffer_put(b, &c, 1);  }  /* Put string to the buffer. */ -void -buffer_putstr (struct buffer *b, const char *c) +void buffer_putstr(struct buffer *b, const char *c)  { -  buffer_put(b, c, strlen(c)); +	buffer_put(b, c, strlen(c));  }  /* Keep flushing data to the fd until the buffer is empty or an error is     encountered or the operation would block. */ -buffer_status_t -buffer_flush_all (struct buffer *b, int fd) +buffer_status_t buffer_flush_all(struct buffer *b, int fd)  { -  buffer_status_t ret; -  struct buffer_data *head; -  size_t head_sp; - -  if (!b->head) -    return BUFFER_EMPTY; -  head_sp = (head = b->head)->sp; -  /* Flush all data. */ -  while ((ret = buffer_flush_available(b, fd)) == BUFFER_PENDING) -    { -      if ((b->head == head) && (head_sp == head->sp) && (errno != EINTR)) -        /* No data was flushed, so kernel buffer must be full. */ -	return ret; -      head_sp = (head = b->head)->sp; -    } +	buffer_status_t ret; +	struct buffer_data *head; +	size_t head_sp; + +	if (!b->head) +		return BUFFER_EMPTY; +	head_sp = (head = b->head)->sp; +	/* Flush all data. */ +	while ((ret = buffer_flush_available(b, fd)) == BUFFER_PENDING) { +		if ((b->head == head) && (head_sp == head->sp) +		    && (errno != EINTR)) +			/* No data was flushed, so kernel buffer must be full. +			 */ +			return ret; +		head_sp = (head = b->head)->sp; +	} -  return ret; +	return ret;  }  /* Flush enough data to fill a terminal window of the given scene (used only     by vty telnet interface). */ -buffer_status_t -buffer_flush_window (struct buffer *b, int fd, int width, int height,  -		     int erase_flag, int no_more_flag) +buffer_status_t buffer_flush_window(struct buffer *b, int fd, int width, +				    int height, int erase_flag, +				    int no_more_flag)  { -  int nbytes; -  int iov_alloc; -  int iov_index; -  struct iovec *iov; -  struct iovec small_iov[3]; -  char more[] = " --More-- "; -  char erase[] = { 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, -		   ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', -		   0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08}; -  struct buffer_data *data; -  int column; - -  if (!b->head) -    return BUFFER_EMPTY; - -  if (height < 1) -    { -      zlog_warn("%s called with non-positive window height %d, forcing to 1", -      		__func__, height); -      height = 1; -    } -  else if (height >= 2) -    height--; -  if (width < 1) -    { -      zlog_warn("%s called with non-positive window width %d, forcing to 1", -      		__func__, width); -      width = 1; -    } - -  /* For erase and more data add two to b's buffer_data count.*/ -  if (b->head->next == NULL) -    { -      iov_alloc = array_size(small_iov); -      iov = small_iov; -    } -  else -    { -      iov_alloc = ((height*(width+2))/b->size)+10; -      iov = XMALLOC(MTYPE_TMP, iov_alloc*sizeof(*iov)); -    } -  iov_index = 0; - -  /* Previously print out is performed. */ -  if (erase_flag) -    { -      iov[iov_index].iov_base = erase; -      iov[iov_index].iov_len = sizeof erase; -      iov_index++; -    } - -  /* Output data. */ -  column = 1;  /* Column position of next character displayed. */ -  for (data = b->head; data && (height > 0); data = data->next) -    { -      size_t cp; - -      cp = data->sp; -      while ((cp < data->cp) && (height > 0)) -        { -	  /* Calculate lines remaining and column position after displaying -	     this character. */ -	  if (data->data[cp] == '\r') -	    column = 1; -	  else if ((data->data[cp] == '\n') || (column == width)) -	    { -	      column = 1; -	      height--; -	    } -	  else -	    column++; -	  cp++; -        } -      iov[iov_index].iov_base = (char *)(data->data + data->sp); -      iov[iov_index++].iov_len = cp-data->sp; -      data->sp = cp; - -      if (iov_index == iov_alloc) -	/* This should not ordinarily happen. */ -        { -	  iov_alloc *= 2; -	  if (iov != small_iov) -	    { -	      zlog_warn("%s: growing iov array to %d; " -			"width %d, height %d, size %lu", -			__func__, iov_alloc, width, height, (u_long)b->size); -	      iov = XREALLOC(MTYPE_TMP, iov, iov_alloc*sizeof(*iov)); -	    } -	  else -	    { -	      /* This should absolutely never occur. */ -	      zlog_err("%s: corruption detected: iov_small overflowed; " -		       "head %p, tail %p, head->next %p", -		       __func__, (void *)b->head, (void *)b->tail, -		       (void *)b->head->next); -	      iov = XMALLOC(MTYPE_TMP, iov_alloc*sizeof(*iov)); -	      memcpy(iov, small_iov, sizeof(small_iov)); -	    } +	int nbytes; +	int iov_alloc; +	int iov_index; +	struct iovec *iov; +	struct iovec small_iov[3]; +	char more[] = " --More-- "; +	char erase[] = {0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, +			0x08, 0x08, ' ',  ' ',  ' ',  ' ',  ' ',  ' ', +			' ',  ' ',  ' ',  ' ',  0x08, 0x08, 0x08, 0x08, +			0x08, 0x08, 0x08, 0x08, 0x08, 0x08}; +	struct buffer_data *data; +	int column; + +	if (!b->head) +		return BUFFER_EMPTY; + +	if (height < 1) { +		zlog_warn( +			"%s called with non-positive window height %d, forcing to 1", +			__func__, height); +		height = 1; +	} else if (height >= 2) +		height--; +	if (width < 1) { +		zlog_warn( +			"%s called with non-positive window width %d, forcing to 1", +			__func__, width); +		width = 1; +	} + +	/* For erase and more data add two to b's buffer_data count.*/ +	if (b->head->next == NULL) { +		iov_alloc = array_size(small_iov); +		iov = small_iov; +	} else { +		iov_alloc = ((height * (width + 2)) / b->size) + 10; +		iov = XMALLOC(MTYPE_TMP, iov_alloc * sizeof(*iov));  	} -    } +	iov_index = 0; -  /* In case of `more' display need. */ -  if (b->tail && (b->tail->sp < b->tail->cp) && !no_more_flag) -    { -      iov[iov_index].iov_base = more; -      iov[iov_index].iov_len = sizeof more; -      iov_index++; -    } +	/* Previously print out is performed. */ +	if (erase_flag) { +		iov[iov_index].iov_base = erase; +		iov[iov_index].iov_len = sizeof erase; +		iov_index++; +	} + +	/* Output data. */ +	column = 1; /* Column position of next character displayed. */ +	for (data = b->head; data && (height > 0); data = data->next) { +		size_t cp; + +		cp = data->sp; +		while ((cp < data->cp) && (height > 0)) { +			/* Calculate lines remaining and column position after +			   displaying +			   this character. */ +			if (data->data[cp] == '\r') +				column = 1; +			else if ((data->data[cp] == '\n') +				 || (column == width)) { +				column = 1; +				height--; +			} else +				column++; +			cp++; +		} +		iov[iov_index].iov_base = (char *)(data->data + data->sp); +		iov[iov_index++].iov_len = cp - data->sp; +		data->sp = cp; + +		if (iov_index == iov_alloc) +		/* This should not ordinarily happen. */ +		{ +			iov_alloc *= 2; +			if (iov != small_iov) { +				zlog_warn( +					"%s: growing iov array to %d; " +					"width %d, height %d, size %lu", +					__func__, iov_alloc, width, height, +					(u_long)b->size); +				iov = XREALLOC(MTYPE_TMP, iov, +					       iov_alloc * sizeof(*iov)); +			} else { +				/* This should absolutely never occur. */ +				zlog_err( +					"%s: corruption detected: iov_small overflowed; " +					"head %p, tail %p, head->next %p", +					__func__, (void *)b->head, +					(void *)b->tail, (void *)b->head->next); +				iov = XMALLOC(MTYPE_TMP, +					      iov_alloc * sizeof(*iov)); +				memcpy(iov, small_iov, sizeof(small_iov)); +			} +		} +	} + +	/* In case of `more' display need. */ +	if (b->tail && (b->tail->sp < b->tail->cp) && !no_more_flag) { +		iov[iov_index].iov_base = more; +		iov[iov_index].iov_len = sizeof more; +		iov_index++; +	}  #ifdef IOV_MAX -  /* IOV_MAX are normally defined in <sys/uio.h> , Posix.1g. -     example: Solaris2.6 are defined IOV_MAX size at 16.     */ -  { -    struct iovec *c_iov = iov; -    nbytes = 0; /* Make sure it's initialized. */ - -    while (iov_index > 0) -      { -	 int iov_size; - -	 iov_size = ((iov_index > IOV_MAX) ? IOV_MAX : iov_index); -	 if ((nbytes = writev(fd, c_iov, iov_size)) < 0) -	   { -	     zlog_warn("%s: writev to fd %d failed: %s", -		       __func__, fd, safe_strerror(errno)); -	     break; -	   } - -	 /* move pointer io-vector */ -	 c_iov += iov_size; -	 iov_index -= iov_size; -      } -  } +	/* IOV_MAX are normally defined in <sys/uio.h> , Posix.1g. +	   example: Solaris2.6 are defined IOV_MAX size at 16.     */ +	{ +		struct iovec *c_iov = iov; +		nbytes = 0; /* Make sure it's initialized. */ + +		while (iov_index > 0) { +			int iov_size; + +			iov_size = +				((iov_index > IOV_MAX) ? IOV_MAX : iov_index); +			if ((nbytes = writev(fd, c_iov, iov_size)) < 0) { +				zlog_warn("%s: writev to fd %d failed: %s", +					  __func__, fd, safe_strerror(errno)); +				break; +			} + +			/* move pointer io-vector */ +			c_iov += iov_size; +			iov_index -= iov_size; +		} +	}  #else  /* IOV_MAX */ -   if ((nbytes = writev (fd, iov, iov_index)) < 0) -     zlog_warn("%s: writev to fd %d failed: %s", -	       __func__, fd, safe_strerror(errno)); +	if ((nbytes = writev(fd, iov, iov_index)) < 0) +		zlog_warn("%s: writev to fd %d failed: %s", __func__, fd, +			  safe_strerror(errno));  #endif /* IOV_MAX */ -  /* Free printed buffer data. */ -  while (b->head && (b->head->sp == b->head->cp)) -    { -      struct buffer_data *del; -      if (!(b->head = (del = b->head)->next)) -        b->tail = NULL; -      BUFFER_DATA_FREE(del); -    } +	/* Free printed buffer data. */ +	while (b->head && (b->head->sp == b->head->cp)) { +		struct buffer_data *del; +		if (!(b->head = (del = b->head)->next)) +			b->tail = NULL; +		BUFFER_DATA_FREE(del); +	} -  if (iov != small_iov) -    XFREE (MTYPE_TMP, iov); +	if (iov != small_iov) +		XFREE(MTYPE_TMP, iov); -  return (nbytes < 0) ? BUFFER_ERROR : -  			(b->head ? BUFFER_PENDING : BUFFER_EMPTY); +	return (nbytes < 0) ? BUFFER_ERROR +			    : (b->head ? BUFFER_PENDING : BUFFER_EMPTY);  }  /* This function (unlike other buffer_flush* functions above) is designed @@ -391,8 +370,7 @@ to work with non-blocking sockets.  It does not attempt to write out  all of the queued data, just a "big" chunk.  It returns 0 if it was  able to empty out the buffers completely, 1 if more flushing is  required later, or -1 on a fatal write error. */ -buffer_status_t -buffer_flush_available(struct buffer *b, int fd) +buffer_status_t buffer_flush_available(struct buffer *b, int fd)  {  /* These are just reasonable values to make sure a significant amount of @@ -405,66 +383,63 @@ in one shot. */  #endif  #define MAX_FLUSH 131072 -  struct buffer_data *d; -  size_t written; -  struct iovec iov[MAX_CHUNKS]; -  size_t iovcnt = 0; -  size_t nbyte = 0; - -  for (d = b->head; d && (iovcnt < MAX_CHUNKS) && (nbyte < MAX_FLUSH); -       d = d->next, iovcnt++) -    { -      iov[iovcnt].iov_base = d->data+d->sp; -      nbyte += (iov[iovcnt].iov_len = d->cp-d->sp); -    } - -  if (!nbyte) -    /* No data to flush: should we issue a warning message? */ -    return BUFFER_EMPTY; - -  /* only place where written should be sign compared */ -  if ((ssize_t)(written = writev(fd,iov,iovcnt)) < 0) -    { -      if (ERRNO_IO_RETRY(errno)) -	/* Calling code should try again later. */ -        return BUFFER_PENDING; -      zlog_warn("%s: write error on fd %d: %s", -		__func__, fd, safe_strerror(errno)); -      return BUFFER_ERROR; -    } - -  /* Free printed buffer data. */ -  while (written > 0) -    { -      struct buffer_data *d; -      if (!(d = b->head)) -        { -          zlog_err("%s: corruption detected: buffer queue empty, " -		   "but written is %lu", __func__, (u_long)written); -	  break; -        } -      if (written < d->cp-d->sp) -        { -	  d->sp += written; -	  return BUFFER_PENDING; +	struct buffer_data *d; +	size_t written; +	struct iovec iov[MAX_CHUNKS]; +	size_t iovcnt = 0; +	size_t nbyte = 0; + +	for (d = b->head; d && (iovcnt < MAX_CHUNKS) && (nbyte < MAX_FLUSH); +	     d = d->next, iovcnt++) { +		iov[iovcnt].iov_base = d->data + d->sp; +		nbyte += (iov[iovcnt].iov_len = d->cp - d->sp); +	} + +	if (!nbyte) +		/* No data to flush: should we issue a warning message? */ +		return BUFFER_EMPTY; + +	/* only place where written should be sign compared */ +	if ((ssize_t)(written = writev(fd, iov, iovcnt)) < 0) { +		if (ERRNO_IO_RETRY(errno)) +			/* Calling code should try again later. */ +			return BUFFER_PENDING; +		zlog_warn("%s: write error on fd %d: %s", __func__, fd, +			  safe_strerror(errno)); +		return BUFFER_ERROR;  	} -      written -= (d->cp-d->sp); -      if (!(b->head = d->next)) -        b->tail = NULL; -      BUFFER_DATA_FREE(d); -    } +	/* Free printed buffer data. */ +	while (written > 0) { +		struct buffer_data *d; +		if (!(d = b->head)) { +			zlog_err( +				"%s: corruption detected: buffer queue empty, " +				"but written is %lu", +				__func__, (u_long)written); +			break; +		} +		if (written < d->cp - d->sp) { +			d->sp += written; +			return BUFFER_PENDING; +		} + +		written -= (d->cp - d->sp); +		if (!(b->head = d->next)) +			b->tail = NULL; +		BUFFER_DATA_FREE(d); +	} -  return b->head ? BUFFER_PENDING : BUFFER_EMPTY; +	return b->head ? BUFFER_PENDING : BUFFER_EMPTY;  #undef MAX_CHUNKS  #undef MAX_FLUSH  } -buffer_status_t -buffer_write(struct buffer *b, int fd, const void *p, size_t size) +buffer_status_t buffer_write(struct buffer *b, int fd, const void *p, +			     size_t size)  { -  ssize_t nbytes; +	ssize_t nbytes;  #if 0    /* Should we attempt to drain any previously buffered data?  This could help @@ -474,25 +449,25 @@ buffer_write(struct buffer *b, int fd, const void *p, size_t size)    if (b->head && (buffer_flush_available(b, fd) == BUFFER_ERROR))      return BUFFER_ERROR;  #endif -  if (b->head) -    /* Buffer is not empty, so do not attempt to write the new data. */ -    nbytes = 0; -  else if ((nbytes = write(fd, p, size)) < 0) -    { -      if (ERRNO_IO_RETRY(errno)) -        nbytes = 0; -      else -        { -	  zlog_warn("%s: write error on fd %d: %s", -		    __func__, fd, safe_strerror(errno)); -	  return BUFFER_ERROR; +	if (b->head) +		/* Buffer is not empty, so do not attempt to write the new data. +		 */ +		nbytes = 0; +	else if ((nbytes = write(fd, p, size)) < 0) { +		if (ERRNO_IO_RETRY(errno)) +			nbytes = 0; +		else { +			zlog_warn("%s: write error on fd %d: %s", __func__, fd, +				  safe_strerror(errno)); +			return BUFFER_ERROR; +		} +	} +	/* Add any remaining data to the buffer. */ +	{ +		size_t written = nbytes; +		if (written < size) +			buffer_put(b, ((const char *)p) + written, +				   size - written);  	} -    } -  /* Add any remaining data to the buffer. */ -  { -    size_t written = nbytes; -    if (written < size) -      buffer_put(b, ((const char *)p)+written, size-written); -  } -  return b->head ? BUFFER_PENDING : BUFFER_EMPTY; +	return b->head ? BUFFER_PENDING : BUFFER_EMPTY;  } diff --git a/lib/buffer.h b/lib/buffer.h index 6c3dc76a1b..0164a4baf3 100644 --- a/lib/buffer.h +++ b/lib/buffer.h @@ -1,5 +1,5 @@  /* - * Buffering to output and input.  + * Buffering to output and input.   * Copyright (C) 1998 Kunihiro Ishiguro   *   * This file is part of GNU Zebra. @@ -23,57 +23,56 @@  #ifndef _ZEBRA_BUFFER_H  #define _ZEBRA_BUFFER_H -  /* Create a new buffer.  Memory will be allocated in chunks of the given     size.  If the argument is 0, the library will supply a reasonable     default size suitable for buffering socket I/O. */ -extern struct buffer *buffer_new (size_t); +extern struct buffer *buffer_new(size_t);  /* Free all data in the buffer. */ -extern void buffer_reset (struct buffer *); +extern void buffer_reset(struct buffer *);  /* This function first calls buffer_reset to release all buffered data.     Then it frees the struct buffer itself. */ -extern void buffer_free (struct buffer *); +extern void buffer_free(struct buffer *);  /* Add the given data to the end of the buffer. */ -extern void buffer_put (struct buffer *, const void *, size_t); +extern void buffer_put(struct buffer *, const void *, size_t);  /* Add a single character to the end of the buffer. */ -extern void buffer_putc (struct buffer *, u_char); +extern void buffer_putc(struct buffer *, u_char);  /* Add a NUL-terminated string to the end of the buffer. */ -extern void buffer_putstr (struct buffer *, const char *); +extern void buffer_putstr(struct buffer *, const char *);  /* Combine all accumulated (and unflushed) data inside the buffer into a     single NUL-terminated string allocated using XMALLOC(MTYPE_TMP).  Note     that this function does not alter the state of the buffer, so the data     is still inside waiting to be flushed. */ -char *buffer_getstr (struct buffer *); +char *buffer_getstr(struct buffer *);  /* Returns 1 if there is no pending data in the buffer.  Otherwise returns 0. */ -int buffer_empty (struct buffer *); +int buffer_empty(struct buffer *); -typedef enum -  { -    /* An I/O error occurred.  The buffer should be destroyed and the -       file descriptor should be closed. */ -    BUFFER_ERROR = -1, +typedef enum { +	/* An I/O error occurred.  The buffer should be destroyed and the +	   file descriptor should be closed. */ +	BUFFER_ERROR = -1, -    /* The data was written successfully, and the buffer is now empty -       (there is no pending data waiting to be flushed). */ -    BUFFER_EMPTY = 0, +	/* The data was written successfully, and the buffer is now empty +	   (there is no pending data waiting to be flushed). */ +	BUFFER_EMPTY = 0, -    /* There is pending data in the buffer waiting to be flushed.  Please -       try flushing the buffer when select indicates that the file descriptor -       is writeable. */ -    BUFFER_PENDING = 1 -  } buffer_status_t; +	/* There is pending data in the buffer waiting to be flushed.  Please +	   try flushing the buffer when select indicates that the file +	   descriptor +	   is writeable. */ +	BUFFER_PENDING = 1 +} buffer_status_t;  /* Try to write this data to the file descriptor.  Any data that cannot     be written immediately is added to the buffer queue. */ -extern buffer_status_t buffer_write(struct buffer *, int fd, -				    const void *, size_t); +extern buffer_status_t buffer_write(struct buffer *, int fd, const void *, +				    size_t); -/* This function attempts to flush some (but perhaps not all) of  +/* This function attempts to flush some (but perhaps not all) of     the queued data to the given file descriptor. */  extern buffer_status_t buffer_flush_available(struct buffer *, int fd); @@ -83,12 +82,12 @@ extern buffer_status_t buffer_flush_available(struct buffer *, int fd);  /* Call buffer_flush_available repeatedly until either all data has been     flushed, or an I/O error has been encountered, or the operation would     block. */ -extern buffer_status_t buffer_flush_all (struct buffer *, int fd); +extern buffer_status_t buffer_flush_all(struct buffer *, int fd);  /* Attempt to write enough data to the given fd to fill a window of the     given width and height (and remove the data written from the buffer). -   If !no_more, then a message saying " --More-- " is appended.  +   If !no_more, then a message saying " --More-- " is appended.     If erase is true, then first overwrite the previous " --More-- " message     with spaces. @@ -96,7 +95,7 @@ extern buffer_status_t buffer_flush_all (struct buffer *, int fd);     to return -1 (because the logic for handling the erase and more features     is too complicated to retry the write later).  */ -extern buffer_status_t buffer_flush_window (struct buffer *, int fd, int width, -					    int height, int erase, int no_more); +extern buffer_status_t buffer_flush_window(struct buffer *, int fd, int width, +					   int height, int erase, int no_more);  #endif /* _ZEBRA_BUFFER_H */ diff --git a/lib/checksum.c b/lib/checksum.c index 3d6cd45791..8eef73e243 100644 --- a/lib/checksum.c +++ b/lib/checksum.c @@ -9,13 +9,13 @@  #include <zebra.h>  #include "checksum.h" -int			/* return checksum in low-order 16 bits */ -in_cksum(void *parg, int nbytes) +int /* return checksum in low-order 16 bits */ +	in_cksum(void *parg, int nbytes)  {  	u_short *ptr = parg; -	register long		sum;		/* assumes long == 32 bits */ -	u_short			oddbyte; -	register u_short	answer;		/* assumes u_short == 16 bits */ +	register long sum; /* assumes long == 32 bits */ +	u_short oddbyte; +	register u_short answer; /* assumes u_short == 16 bits */  	/*  	 * Our algorithm is simple, using a 32-bit accumulator (sum), @@ -24,15 +24,15 @@ in_cksum(void *parg, int nbytes)  	 */  	sum = 0; -	while (nbytes > 1)  { +	while (nbytes > 1) {  		sum += *ptr++;  		nbytes -= 2;  	} -				/* mop up an odd byte, if necessary */ +	/* mop up an odd byte, if necessary */  	if (nbytes == 1) { -		oddbyte = 0;		/* make sure top half is zero */ -		*((u_char *) &oddbyte) = *(u_char *)ptr;   /* one byte only */ +		oddbyte = 0; /* make sure top half is zero */ +		*((u_char *)&oddbyte) = *(u_char *)ptr; /* one byte only */  		sum += oddbyte;  	} @@ -40,82 +40,80 @@ in_cksum(void *parg, int nbytes)  	 * Add back carry outs from top 16 bits to low 16 bits.  	 */ -	sum  = (sum >> 16) + (sum & 0xffff);	/* add high-16 to low-16 */ -	sum += (sum >> 16);			/* add carry */ -	answer = ~sum;		/* ones-complement, then truncate to 16 bits */ -	return(answer); +	sum = (sum >> 16) + (sum & 0xffff); /* add high-16 to low-16 */ +	sum += (sum >> 16);		    /* add carry */ +	answer = ~sum; /* ones-complement, then truncate to 16 bits */ +	return (answer);  }  /* Fletcher Checksum -- Refer to RFC1008. */  #define MODX                 4102U   /* 5802 should be fine */ -/* To be consistent, offset is 0-based index, rather than the 1-based  +/* To be consistent, offset is 0-based index, rather than the 1-based     index required in the specification ISO 8473, Annex C.1 */  /* calling with offset == FLETCHER_CHECKSUM_VALIDATE will validate the checksum     without modifying the buffer; a valid checksum returns 0 */ -u_int16_t -fletcher_checksum(u_char * buffer, const size_t len, const uint16_t offset) +u_int16_t fletcher_checksum(u_char *buffer, const size_t len, +			    const uint16_t offset)  { -  u_int8_t *p; -  int x, y, c0, c1; -  u_int16_t checksum = 0; -  u_int16_t *csum; -  size_t partial_len, i, left = len; -   -  if (offset != FLETCHER_CHECKSUM_VALIDATE) -    /* Zero the csum in the packet. */ -    { -      assert (offset < (len - 1)); /* account for two bytes of checksum */ -      csum = (u_int16_t *) (buffer + offset); -      *(csum) = 0; -    } - -  p = buffer; -  c0 = 0; -  c1 = 0; - -  while (left != 0) -    { -      partial_len = MIN(left, MODX); - -      for (i = 0; i < partial_len; i++) +	u_int8_t *p; +	int x, y, c0, c1; +	u_int16_t checksum = 0; +	u_int16_t *csum; +	size_t partial_len, i, left = len; + +	if (offset != FLETCHER_CHECKSUM_VALIDATE) +	/* Zero the csum in the packet. */  	{ -	  c0 = c0 + *(p++); -	  c1 += c0; +		assert(offset +		       < (len - 1)); /* account for two bytes of checksum */ +		csum = (u_int16_t *)(buffer + offset); +		*(csum) = 0;  	} -      c0 = c0 % 255; -      c1 = c1 % 255; - -      left -= partial_len; -    } - -  /* The cast is important, to ensure the mod is taken as a signed value. */ -  x = (int)((len - offset - 1) * c0 - c1) % 255; - -  if (x <= 0) -    x += 255; -  y = 510 - c0 - x; -  if (y > 255)   -    y -= 255; - -  if (offset == FLETCHER_CHECKSUM_VALIDATE) -    { -      checksum = (c1 << 8) + c0; -    } -  else -    { -      /* -       * Now we write this to the packet. -       * We could skip this step too, since the checksum returned would -       * be stored into the checksum field by the caller. -       */ -      buffer[offset] = x; -      buffer[offset + 1] = y; - -      /* Take care of the endian issue */ -      checksum = htons((x << 8) | (y & 0xFF)); -    } - -  return checksum; +	p = buffer; +	c0 = 0; +	c1 = 0; + +	while (left != 0) { +		partial_len = MIN(left, MODX); + +		for (i = 0; i < partial_len; i++) { +			c0 = c0 + *(p++); +			c1 += c0; +		} + +		c0 = c0 % 255; +		c1 = c1 % 255; + +		left -= partial_len; +	} + +	/* The cast is important, to ensure the mod is taken as a signed value. +	 */ +	x = (int)((len - offset - 1) * c0 - c1) % 255; + +	if (x <= 0) +		x += 255; +	y = 510 - c0 - x; +	if (y > 255) +		y -= 255; + +	if (offset == FLETCHER_CHECKSUM_VALIDATE) { +		checksum = (c1 << 8) + c0; +	} else { +		/* +		 * Now we write this to the packet. +		 * We could skip this step too, since the checksum returned +		 * would +		 * be stored into the checksum field by the caller. +		 */ +		buffer[offset] = x; +		buffer[offset + 1] = y; + +		/* Take care of the endian issue */ +		checksum = htons((x << 8) | (y & 0xFF)); +	} + +	return checksum;  } diff --git a/lib/checksum.h b/lib/checksum.h index b310f744c9..aecaaf6bcc 100644 --- a/lib/checksum.h +++ b/lib/checksum.h @@ -1,3 +1,4 @@  extern int in_cksum(void *, int);  #define FLETCHER_CHECKSUM_VALIDATE 0xffff -extern u_int16_t fletcher_checksum(u_char *, const size_t len, const uint16_t offset); +extern u_int16_t fletcher_checksum(u_char *, const size_t len, +				   const uint16_t offset); diff --git a/lib/command.c b/lib/command.c index c2ee79035a..cc52224523 100644 --- a/lib/command.c +++ b/lib/command.c @@ -43,12 +43,12 @@  #include "qobj.h"  #include "defaults.h" -DEFINE_MTYPE(       LIB, HOST,       "Host config") -DEFINE_MTYPE(       LIB, STRVEC,     "String vector") +DEFINE_MTYPE(LIB, HOST, "Host config") +DEFINE_MTYPE(LIB, STRVEC, "String vector")  DEFINE_MTYPE_STATIC(LIB, CMD_TOKENS, "Command Tokens") -DEFINE_MTYPE_STATIC(LIB, CMD_DESC,   "Command Token Text") -DEFINE_MTYPE_STATIC(LIB, CMD_TEXT,   "Command Token Help") -DEFINE_MTYPE(       LIB, CMD_ARG,    "Command Argument") +DEFINE_MTYPE_STATIC(LIB, CMD_DESC, "Command Token Text") +DEFINE_MTYPE_STATIC(LIB, CMD_TEXT, "Command Token Help") +DEFINE_MTYPE(LIB, CMD_ARG, "Command Argument")  /* Command vector which includes some level of command lists. Normally     each daemon maintains each own cmdvec. */ @@ -58,138 +58,118 @@ vector cmdvec = NULL;  struct host host;  /* Standard command node structures. */ -static struct cmd_node auth_node = -{ -  AUTH_NODE, -  "Password: ", +static struct cmd_node auth_node = { +	AUTH_NODE, "Password: ",  }; -static struct cmd_node view_node = -{ -  VIEW_NODE, -  "%s> ", +static struct cmd_node view_node = { +	VIEW_NODE, "%s> ",  }; -static struct cmd_node auth_enable_node = -{ -  AUTH_ENABLE_NODE, -  "Password: ", +static struct cmd_node auth_enable_node = { +	AUTH_ENABLE_NODE, "Password: ",  }; -static struct cmd_node enable_node = -{ -  ENABLE_NODE, -  "%s# ", +static struct cmd_node enable_node = { +	ENABLE_NODE, "%s# ",  }; -static struct cmd_node config_node = -{ -  CONFIG_NODE, -  "%s(config)# ", -  1 -}; +static struct cmd_node config_node = {CONFIG_NODE, "%s(config)# ", 1};  /* Default motd string. */  static const char *default_motd = FRR_DEFAULT_MOTD;  static const struct facility_map { -  int facility; -  const char *name; -  size_t match; -} syslog_facilities[] = -  { -    { LOG_KERN, "kern", 1 }, -    { LOG_USER, "user", 2 }, -    { LOG_MAIL, "mail", 1 }, -    { LOG_DAEMON, "daemon", 1 }, -    { LOG_AUTH, "auth", 1 }, -    { LOG_SYSLOG, "syslog", 1 }, -    { LOG_LPR, "lpr", 2 }, -    { LOG_NEWS, "news", 1 }, -    { LOG_UUCP, "uucp", 2 }, -    { LOG_CRON, "cron", 1 }, +	int facility; +	const char *name; +	size_t match; +} syslog_facilities[] = { +	{LOG_KERN, "kern", 1}, +	{LOG_USER, "user", 2}, +	{LOG_MAIL, "mail", 1}, +	{LOG_DAEMON, "daemon", 1}, +	{LOG_AUTH, "auth", 1}, +	{LOG_SYSLOG, "syslog", 1}, +	{LOG_LPR, "lpr", 2}, +	{LOG_NEWS, "news", 1}, +	{LOG_UUCP, "uucp", 2}, +	{LOG_CRON, "cron", 1},  #ifdef LOG_FTP -    { LOG_FTP, "ftp", 1 }, +	{LOG_FTP, "ftp", 1},  #endif -    { LOG_LOCAL0, "local0", 6 }, -    { LOG_LOCAL1, "local1", 6 }, -    { LOG_LOCAL2, "local2", 6 }, -    { LOG_LOCAL3, "local3", 6 }, -    { LOG_LOCAL4, "local4", 6 }, -    { LOG_LOCAL5, "local5", 6 }, -    { LOG_LOCAL6, "local6", 6 }, -    { LOG_LOCAL7, "local7", 6 }, -    { 0, NULL, 0 }, -  }; +	{LOG_LOCAL0, "local0", 6}, +	{LOG_LOCAL1, "local1", 6}, +	{LOG_LOCAL2, "local2", 6}, +	{LOG_LOCAL3, "local3", 6}, +	{LOG_LOCAL4, "local4", 6}, +	{LOG_LOCAL5, "local5", 6}, +	{LOG_LOCAL6, "local6", 6}, +	{LOG_LOCAL7, "local7", 6}, +	{0, NULL, 0}, +}; -static const char * -facility_name(int facility) +static const char *facility_name(int facility)  { -  const struct facility_map *fm; +	const struct facility_map *fm; -  for (fm = syslog_facilities; fm->name; fm++) -    if (fm->facility == facility) -      return fm->name; -  return ""; +	for (fm = syslog_facilities; fm->name; fm++) +		if (fm->facility == facility) +			return fm->name; +	return "";  } -static int -facility_match(const char *str) +static int facility_match(const char *str)  { -  const struct facility_map *fm; +	const struct facility_map *fm; -  for (fm = syslog_facilities; fm->name; fm++) -    if (!strncmp(str,fm->name,fm->match)) -      return fm->facility; -  return -1; +	for (fm = syslog_facilities; fm->name; fm++) +		if (!strncmp(str, fm->name, fm->match)) +			return fm->facility; +	return -1;  } -static int -level_match(const char *s) +static int level_match(const char *s)  { -  int level ; +	int level; -  for ( level = 0 ; zlog_priority [level] != NULL ; level ++ ) -    if (!strncmp (s, zlog_priority[level], 2)) -      return level; -  return ZLOG_DISABLED; +	for (level = 0; zlog_priority[level] != NULL; level++) +		if (!strncmp(s, zlog_priority[level], 2)) +			return level; +	return ZLOG_DISABLED;  }  /* This is called from main when a daemon is invoked with -v or --version. */ -void -print_version (const char *progname) +void print_version(const char *progname)  { -  printf ("%s version %s\n", progname, FRR_VERSION); -  printf ("%s\n", FRR_COPYRIGHT); -  printf ("configured with:\n\t%s\n", FRR_CONFIG_ARGS); +	printf("%s version %s\n", progname, FRR_VERSION); +	printf("%s\n", FRR_COPYRIGHT); +	printf("configured with:\n\t%s\n", FRR_CONFIG_ARGS);  }  /* Utility function to concatenate argv argument into a single string     with inserting ' ' character between each argument.  */ -char * -argv_concat (struct cmd_token **argv, int argc, int shift) -{ -  int i; -  size_t len; -  char *str; -  char *p; - -  len = 0; -  for (i = shift; i < argc; i++) -    len += strlen(argv[i]->arg)+1; -  if (!len) -    return NULL; -  p = str = XMALLOC(MTYPE_TMP, len); -  for (i = shift; i < argc; i++) -    { -      size_t arglen; -      memcpy(p, argv[i]->arg, (arglen = strlen(argv[i]->arg))); -      p += arglen; -      *p++ = ' '; -    } -  *(p-1) = '\0'; -  return str; +char *argv_concat(struct cmd_token **argv, int argc, int shift) +{ +	int i; +	size_t len; +	char *str; +	char *p; + +	len = 0; +	for (i = shift; i < argc; i++) +		len += strlen(argv[i]->arg) + 1; +	if (!len) +		return NULL; +	p = str = XMALLOC(MTYPE_TMP, len); +	for (i = shift; i < argc; i++) { +		size_t arglen; +		memcpy(p, argv[i]->arg, (arglen = strlen(argv[i]->arg))); +		p += arglen; +		*p++ = ' '; +	} +	*(p - 1) = '\0'; +	return str;  }  /** @@ -202,41 +182,38 @@ argv_concat (struct cmd_token **argv, int argc, int shift)   *        index of the found token if it exists   * @return 1 if found, 0 otherwise   */ -int -argv_find (struct cmd_token **argv, int argc, const char *text, int *index) +int argv_find(struct cmd_token **argv, int argc, const char *text, int *index)  { -  int found = 0; -  for (int i = *index; i < argc && found == 0; i++) -    if ((found = strmatch (text, argv[i]->text))) -      *index = i; -  return found; +	int found = 0; +	for (int i = *index; i < argc && found == 0; i++) +		if ((found = strmatch(text, argv[i]->text))) +			*index = i; +	return found;  } -static unsigned int -cmd_hash_key (void *p) +static unsigned int cmd_hash_key(void *p)  { -  return (uintptr_t) p; +	return (uintptr_t)p;  } -static int -cmd_hash_cmp (const void *a, const void *b) +static int cmd_hash_cmp(const void *a, const void *b)  { -  return a == b; +	return a == b;  }  /* Install top node of command vector. */ -void -install_node (struct cmd_node *node, -              int (*func) (struct vty *)) +void install_node(struct cmd_node *node, int (*func)(struct vty *))  { -  vector_set_index (cmdvec, node->node, node); -  node->func = func; -  node->cmdgraph = graph_new (); -  node->cmd_vector = vector_init (VECTOR_MIN_SIZE); -  // add start node -  struct cmd_token *token = new_cmd_token (START_TKN, CMD_ATTR_NORMAL, NULL, NULL); -  graph_new_node (node->cmdgraph, token, (void (*)(void *)) &del_cmd_token); -  node->cmd_hash = hash_create (cmd_hash_key, cmd_hash_cmp); +	vector_set_index(cmdvec, node->node, node); +	node->func = func; +	node->cmdgraph = graph_new(); +	node->cmd_vector = vector_init(VECTOR_MIN_SIZE); +	// add start node +	struct cmd_token *token = +		new_cmd_token(START_TKN, CMD_ATTR_NORMAL, NULL, NULL); +	graph_new_node(node->cmdgraph, token, +		       (void (*)(void *)) & del_cmd_token); +	node->cmd_hash = hash_create(cmd_hash_key, cmd_hash_cmp);  }  /** @@ -248,177 +225,166 @@ install_node (struct cmd_node *node,   * @param string to tokenize   * @return tokenized string   */ -vector -cmd_make_strvec (const char *string) +vector cmd_make_strvec(const char *string)  { -  if (!string) return NULL; +	if (!string) +		return NULL; -  char *copy, *copystart; -  copystart = copy = XSTRDUP (MTYPE_TMP, string); +	char *copy, *copystart; +	copystart = copy = XSTRDUP(MTYPE_TMP, string); -  // skip leading whitespace -  while (isspace ((int) *copy) && *copy != '\0') copy++; +	// skip leading whitespace +	while (isspace((int)*copy) && *copy != '\0') +		copy++; -  // if the entire string was whitespace or a comment, return -  if (*copy == '\0' || *copy == '!' || *copy == '#') -  { -    XFREE (MTYPE_TMP, copystart); -    return NULL; -  } +	// if the entire string was whitespace or a comment, return +	if (*copy == '\0' || *copy == '!' || *copy == '#') { +		XFREE(MTYPE_TMP, copystart); +		return NULL; +	} -  vector strvec = vector_init (VECTOR_MIN_SIZE); -  const char *delim = " \n\r\t", *tok = NULL; -  while (copy) -  { -    tok = strsep (©, delim); -    if (*tok != '\0') -      vector_set (strvec, XSTRDUP (MTYPE_STRVEC, tok)); -  } +	vector strvec = vector_init(VECTOR_MIN_SIZE); +	const char *delim = " \n\r\t", *tok = NULL; +	while (copy) { +		tok = strsep(©, delim); +		if (*tok != '\0') +			vector_set(strvec, XSTRDUP(MTYPE_STRVEC, tok)); +	} -  XFREE (MTYPE_TMP, copystart); -  return strvec; +	XFREE(MTYPE_TMP, copystart); +	return strvec;  }  /* Free allocated string vector. */ -void -cmd_free_strvec (vector v) +void cmd_free_strvec(vector v)  { -  unsigned int i; -  char *cp; +	unsigned int i; +	char *cp; -  if (!v) -    return; +	if (!v) +		return; -  for (i = 0; i < vector_active (v); i++) -    if ((cp = vector_slot (v, i)) != NULL) -      XFREE (MTYPE_STRVEC, cp); +	for (i = 0; i < vector_active(v); i++) +		if ((cp = vector_slot(v, i)) != NULL) +			XFREE(MTYPE_STRVEC, cp); -  vector_free (v); +	vector_free(v);  }  /* Return prompt character of specified node. */ -const char * -cmd_prompt (enum node_type node) +const char *cmd_prompt(enum node_type node)  { -  struct cmd_node *cnode; +	struct cmd_node *cnode; -  cnode = vector_slot (cmdvec, node); -  return cnode->prompt; +	cnode = vector_slot(cmdvec, node); +	return cnode->prompt;  } -static bool -cmd_nodes_link (struct graph_node *from, struct graph_node *to) +static bool cmd_nodes_link(struct graph_node *from, struct graph_node *to)  { -  for (size_t i = 0; i < vector_active (from->to); i++) -    if (vector_slot (from->to, i) == to) -      return true; -  return false; +	for (size_t i = 0; i < vector_active(from->to); i++) +		if (vector_slot(from->to, i) == to) +			return true; +	return false;  } -static bool cmd_nodes_equal (struct graph_node *ga, struct graph_node *gb); +static bool cmd_nodes_equal(struct graph_node *ga, struct graph_node *gb);  /* returns a single node to be excluded as "next" from iteration   * - for JOIN_TKN, never continue back to the FORK_TKN   * - in all other cases, don't try the node itself (in case of "...")   */ -static inline struct graph_node * -cmd_loopstop(struct graph_node *gn) -{ -  struct cmd_token *tok = gn->data; -  if (tok->type == JOIN_TKN) -    return tok->forkjoin; -  else -    return gn; -} - -static bool -cmd_subgraph_equal (struct graph_node *ga, struct graph_node *gb, -                    struct graph_node *a_join) -{ -  size_t i, j; -  struct graph_node *a_fork, *b_fork; -  a_fork = cmd_loopstop (ga); -  b_fork = cmd_loopstop (gb); - -  if (vector_active (ga->to) != vector_active (gb->to)) -    return false; -  for (i = 0; i < vector_active (ga->to); i++) -    { -      struct graph_node *cga = vector_slot (ga->to, i); - -      for (j = 0; j < vector_active (gb->to); j++) -        { -          struct graph_node *cgb = vector_slot (gb->to, i); - -          if (cga == a_fork && cgb != b_fork) -            continue; -          if (cga == a_fork && cgb == b_fork) -            break; - -          if (cmd_nodes_equal (cga, cgb)) -            { -              if (cga == a_join) -                break; -              if (cmd_subgraph_equal (cga, cgb, a_join)) -                break; -            } -        } -      if (j == vector_active (gb->to)) -        return false; -    } -  return true; +static inline struct graph_node *cmd_loopstop(struct graph_node *gn) +{ +	struct cmd_token *tok = gn->data; +	if (tok->type == JOIN_TKN) +		return tok->forkjoin; +	else +		return gn; +} + +static bool cmd_subgraph_equal(struct graph_node *ga, struct graph_node *gb, +			       struct graph_node *a_join) +{ +	size_t i, j; +	struct graph_node *a_fork, *b_fork; +	a_fork = cmd_loopstop(ga); +	b_fork = cmd_loopstop(gb); + +	if (vector_active(ga->to) != vector_active(gb->to)) +		return false; +	for (i = 0; i < vector_active(ga->to); i++) { +		struct graph_node *cga = vector_slot(ga->to, i); + +		for (j = 0; j < vector_active(gb->to); j++) { +			struct graph_node *cgb = vector_slot(gb->to, i); + +			if (cga == a_fork && cgb != b_fork) +				continue; +			if (cga == a_fork && cgb == b_fork) +				break; + +			if (cmd_nodes_equal(cga, cgb)) { +				if (cga == a_join) +					break; +				if (cmd_subgraph_equal(cga, cgb, a_join)) +					break; +			} +		} +		if (j == vector_active(gb->to)) +			return false; +	} +	return true;  }  /* deep compare -- for FORK_TKN, the entire subgraph is compared.   * this is what's needed since we're not currently trying to partially   * merge subgraphs */ -static bool -cmd_nodes_equal (struct graph_node *ga, struct graph_node *gb) -{ -  struct cmd_token *a = ga->data, *b = gb->data; - -  if (a->type != b->type || a->allowrepeat != b->allowrepeat) -    return false; -  if (a->type < SPECIAL_TKN && strcmp (a->text, b->text)) -    return false; -  /* one a ..., the other not. */ -  if (cmd_nodes_link (ga, ga) != cmd_nodes_link (gb, gb)) -    return false; - -  switch (a->type) -    { -    case RANGE_TKN: -      return a->min == b->min && a->max == b->max; - -    case FORK_TKN: -      /* one is keywords, the other just option or selector ... */ -      if (cmd_nodes_link (a->forkjoin, ga) != cmd_nodes_link (b->forkjoin, gb)) -        return false; -      if (cmd_nodes_link (ga, a->forkjoin) != cmd_nodes_link (gb, b->forkjoin)) -        return false; -      return cmd_subgraph_equal (ga, gb, a->forkjoin); - -    default: -      return true; -    } -} - -static void -cmd_fork_bump_attr (struct graph_node *gn, struct graph_node *join, -                    u_char attr) -{ -  size_t i; -  struct cmd_token *tok = gn->data; -  struct graph_node *stop = cmd_loopstop (gn); - -  tok->attr = attr; -  for (i = 0; i < vector_active (gn->to); i++) -    { -      struct graph_node *next = vector_slot (gn->to, i); -      if (next == stop || next == join) -        continue; -      cmd_fork_bump_attr (next, join, attr); -    } +static bool cmd_nodes_equal(struct graph_node *ga, struct graph_node *gb) +{ +	struct cmd_token *a = ga->data, *b = gb->data; + +	if (a->type != b->type || a->allowrepeat != b->allowrepeat) +		return false; +	if (a->type < SPECIAL_TKN && strcmp(a->text, b->text)) +		return false; +	/* one a ..., the other not. */ +	if (cmd_nodes_link(ga, ga) != cmd_nodes_link(gb, gb)) +		return false; + +	switch (a->type) { +	case RANGE_TKN: +		return a->min == b->min && a->max == b->max; + +	case FORK_TKN: +		/* one is keywords, the other just option or selector ... */ +		if (cmd_nodes_link(a->forkjoin, ga) +		    != cmd_nodes_link(b->forkjoin, gb)) +			return false; +		if (cmd_nodes_link(ga, a->forkjoin) +		    != cmd_nodes_link(gb, b->forkjoin)) +			return false; +		return cmd_subgraph_equal(ga, gb, a->forkjoin); + +	default: +		return true; +	} +} + +static void cmd_fork_bump_attr(struct graph_node *gn, struct graph_node *join, +			       u_char attr) +{ +	size_t i; +	struct cmd_token *tok = gn->data; +	struct graph_node *stop = cmd_loopstop(gn); + +	tok->attr = attr; +	for (i = 0; i < vector_active(gn->to); i++) { +		struct graph_node *next = vector_slot(gn->to, i); +		if (next == stop || next == join) +			continue; +		cmd_fork_bump_attr(next, join, attr); +	}  }  /* move an entire subtree from the temporary graph resulting from @@ -426,395 +392,386 @@ cmd_fork_bump_attr (struct graph_node *gn, struct graph_node *join,   *   * this touches rather deeply into the graph code unfortunately.   */ -static void -cmd_reparent_tree (struct graph *fromgraph, struct graph *tograph, -                   struct graph_node *node) -{ -  struct graph_node *stop = cmd_loopstop (node); -  size_t i; - -  for (i = 0; i < vector_active (fromgraph->nodes); i++) -    if (vector_slot (fromgraph->nodes, i) == node) -      { -        /* agressive iteration punching through subgraphs - may hit some -         * nodes twice.  reparent only if found on old graph */ -        vector_unset (fromgraph->nodes, i); -        vector_set (tograph->nodes, node); -        break; -      } - -  for (i = 0; i < vector_active (node->to); i++) -    { -      struct graph_node *next = vector_slot (node->to, i); -      if (next != stop) -        cmd_reparent_tree (fromgraph, tograph, next); -    } -} - -static void -cmd_free_recur (struct graph *graph, struct graph_node *node, -                struct graph_node *stop) -{ -  struct graph_node *next, *nstop; - -  for (size_t i = vector_active (node->to); i; i--) -    { -      next = vector_slot (node->to, i - 1); -      if (next == stop) -        continue; -      nstop = cmd_loopstop (next); -      if (nstop != next) -        cmd_free_recur (graph, next, nstop); -      cmd_free_recur (graph, nstop, stop); -    } -  graph_delete_node (graph, node); -} - -static void -cmd_free_node (struct graph *graph, struct graph_node *node) -{ -  struct cmd_token *tok = node->data; -  if (tok->type == JOIN_TKN) -    cmd_free_recur (graph, tok->forkjoin, node); -  graph_delete_node (graph, node); +static void cmd_reparent_tree(struct graph *fromgraph, struct graph *tograph, +			      struct graph_node *node) +{ +	struct graph_node *stop = cmd_loopstop(node); +	size_t i; + +	for (i = 0; i < vector_active(fromgraph->nodes); i++) +		if (vector_slot(fromgraph->nodes, i) == node) { +			/* agressive iteration punching through subgraphs - may +			 * hit some +			 * nodes twice.  reparent only if found on old graph */ +			vector_unset(fromgraph->nodes, i); +			vector_set(tograph->nodes, node); +			break; +		} + +	for (i = 0; i < vector_active(node->to); i++) { +		struct graph_node *next = vector_slot(node->to, i); +		if (next != stop) +			cmd_reparent_tree(fromgraph, tograph, next); +	} +} + +static void cmd_free_recur(struct graph *graph, struct graph_node *node, +			   struct graph_node *stop) +{ +	struct graph_node *next, *nstop; + +	for (size_t i = vector_active(node->to); i; i--) { +		next = vector_slot(node->to, i - 1); +		if (next == stop) +			continue; +		nstop = cmd_loopstop(next); +		if (nstop != next) +			cmd_free_recur(graph, next, nstop); +		cmd_free_recur(graph, nstop, stop); +	} +	graph_delete_node(graph, node); +} + +static void cmd_free_node(struct graph *graph, struct graph_node *node) +{ +	struct cmd_token *tok = node->data; +	if (tok->type == JOIN_TKN) +		cmd_free_recur(graph, tok->forkjoin, node); +	graph_delete_node(graph, node);  }  /* recursive graph merge.  call with   *   old ~= new   * (which holds true for old == START_TKN, new == START_TKN)   */ -static void -cmd_merge_nodes (struct graph *oldgraph, struct graph *newgraph, -                 struct graph_node *old, struct graph_node *new, -                 int direction) -{ -  struct cmd_token *tok; -  struct graph_node *old_skip, *new_skip; -  old_skip = cmd_loopstop (old); -  new_skip = cmd_loopstop (new); - -  assert (direction == 1 || direction == -1); - -  tok = old->data; -  tok->refcnt += direction; - -  size_t j, i; -  for (j = 0; j < vector_active (new->to); j++) -    { -      struct graph_node *cnew = vector_slot (new->to, j); -      if (cnew == new_skip) -        continue; - -      for (i = 0; i < vector_active (old->to); i++) -        { -          struct graph_node *cold = vector_slot (old->to, i); -          if (cold == old_skip) -            continue; - -          if (cmd_nodes_equal (cold, cnew)) -            { -              struct cmd_token *told = cold->data, *tnew = cnew->data; - -              if (told->type == END_TKN) -                { -                  if (direction < 0) -                    { -                      graph_delete_node (oldgraph, vector_slot (cold->to, 0)); -                      graph_delete_node (oldgraph, cold); -                    } -                  else -                    /* force no-match handling to install END_TKN */ -                    i = vector_active (old->to); -                  break; -                } - -              /* the entire fork compared as equal, we continue after it. */ -              if (told->type == FORK_TKN) -                { -                  if (tnew->attr < told->attr && direction > 0) -                    cmd_fork_bump_attr (cold, told->forkjoin, tnew->attr); -                  /* XXX: no reverse bump on uninstall */ -                  told = (cold = told->forkjoin)->data; -                  tnew = (cnew = tnew->forkjoin)->data; -                } -              if (tnew->attr < told->attr) -                told->attr = tnew->attr; - -              cmd_merge_nodes (oldgraph, newgraph, cold, cnew, direction); -              break; -            } -        } -      /* nothing found => add new to old */ -      if (i == vector_active (old->to) && direction > 0) -        { -          assert (vector_count (cnew->from) == -                          cmd_nodes_link (cnew, cnew) ? 2 : 1); -          graph_remove_edge (new, cnew); - -          cmd_reparent_tree (newgraph, oldgraph, cnew); - -          graph_add_edge (old, cnew); -        } -    } - -  if (!tok->refcnt) -    cmd_free_node (oldgraph, old); -} - -void -cmd_merge_graphs (struct graph *old, struct graph *new, int direction) -{ -  assert (vector_active (old->nodes) >= 1); -  assert (vector_active (new->nodes) >= 1); - -  cmd_merge_nodes (old, new, -                   vector_slot (old->nodes, 0), vector_slot (new->nodes, 0), -                   direction); +static void cmd_merge_nodes(struct graph *oldgraph, struct graph *newgraph, +			    struct graph_node *old, struct graph_node *new, +			    int direction) +{ +	struct cmd_token *tok; +	struct graph_node *old_skip, *new_skip; +	old_skip = cmd_loopstop(old); +	new_skip = cmd_loopstop(new); + +	assert(direction == 1 || direction == -1); + +	tok = old->data; +	tok->refcnt += direction; + +	size_t j, i; +	for (j = 0; j < vector_active(new->to); j++) { +		struct graph_node *cnew = vector_slot(new->to, j); +		if (cnew == new_skip) +			continue; + +		for (i = 0; i < vector_active(old->to); i++) { +			struct graph_node *cold = vector_slot(old->to, i); +			if (cold == old_skip) +				continue; + +			if (cmd_nodes_equal(cold, cnew)) { +				struct cmd_token *told = cold->data, +						 *tnew = cnew->data; + +				if (told->type == END_TKN) { +					if (direction < 0) { +						graph_delete_node( +							oldgraph, +							vector_slot(cold->to, +								    0)); +						graph_delete_node(oldgraph, +								  cold); +					} else +						/* force no-match handling to +						 * install END_TKN */ +						i = vector_active(old->to); +					break; +				} + +				/* the entire fork compared as equal, we +				 * continue after it. */ +				if (told->type == FORK_TKN) { +					if (tnew->attr < told->attr +					    && direction > 0) +						cmd_fork_bump_attr( +							cold, told->forkjoin, +							tnew->attr); +					/* XXX: no reverse bump on uninstall */ +					told = (cold = told->forkjoin)->data; +					tnew = (cnew = tnew->forkjoin)->data; +				} +				if (tnew->attr < told->attr) +					told->attr = tnew->attr; + +				cmd_merge_nodes(oldgraph, newgraph, cold, cnew, +						direction); +				break; +			} +		} +		/* nothing found => add new to old */ +		if (i == vector_active(old->to) && direction > 0) { +			assert(vector_count(cnew->from) +					       == cmd_nodes_link(cnew, cnew) +				       ? 2 +				       : 1); +			graph_remove_edge(new, cnew); + +			cmd_reparent_tree(newgraph, oldgraph, cnew); + +			graph_add_edge(old, cnew); +		} +	} + +	if (!tok->refcnt) +		cmd_free_node(oldgraph, old); +} + +void cmd_merge_graphs(struct graph *old, struct graph *new, int direction) +{ +	assert(vector_active(old->nodes) >= 1); +	assert(vector_active(new->nodes) >= 1); + +	cmd_merge_nodes(old, new, vector_slot(old->nodes, 0), +			vector_slot(new->nodes, 0), direction);  }  /* Install a command into a node. */ -void -install_element (enum node_type ntype, struct cmd_element *cmd) +void install_element(enum node_type ntype, struct cmd_element *cmd)  { -  struct cmd_node *cnode; +	struct cmd_node *cnode; -  /* cmd_init hasn't been called */ -  if (!cmdvec) -    { -      fprintf (stderr, "%s called before cmd_init, breakage likely\n", -               __func__); -      return; -    } +	/* cmd_init hasn't been called */ +	if (!cmdvec) { +		fprintf(stderr, "%s called before cmd_init, breakage likely\n", +			__func__); +		return; +	} -  cnode = vector_slot (cmdvec, ntype); +	cnode = vector_slot(cmdvec, ntype); -  if (cnode == NULL) -    { -      fprintf (stderr, "Command node %d doesn't exist, please check it\n", -               ntype); -      exit (EXIT_FAILURE); -    } +	if (cnode == NULL) { +		fprintf(stderr, +			"Command node %d doesn't exist, please check it\n", +			ntype); +		exit(EXIT_FAILURE); +	} -  if (hash_lookup (cnode->cmd_hash, cmd) != NULL) -    { -      fprintf (stderr, -               "Multiple command installs to node %d of command:\n%s\n", -               ntype, cmd->string); -      return; -    } +	if (hash_lookup(cnode->cmd_hash, cmd) != NULL) { +		fprintf(stderr, +			"Multiple command installs to node %d of command:\n%s\n", +			ntype, cmd->string); +		return; +	} -  assert (hash_get (cnode->cmd_hash, cmd, hash_alloc_intern)); +	assert(hash_get(cnode->cmd_hash, cmd, hash_alloc_intern)); -  struct graph *graph = graph_new(); -  struct cmd_token *token = new_cmd_token (START_TKN, CMD_ATTR_NORMAL, NULL, NULL); -  graph_new_node (graph, token, (void (*)(void *)) &del_cmd_token); +	struct graph *graph = graph_new(); +	struct cmd_token *token = +		new_cmd_token(START_TKN, CMD_ATTR_NORMAL, NULL, NULL); +	graph_new_node(graph, token, (void (*)(void *)) & del_cmd_token); -  command_parse_format (graph, cmd); -  cmd_merge_graphs (cnode->cmdgraph, graph, +1); -  graph_delete_graph (graph); +	command_parse_format(graph, cmd); +	cmd_merge_graphs(cnode->cmdgraph, graph, +1); +	graph_delete_graph(graph); -  vector_set (cnode->cmd_vector, cmd); +	vector_set(cnode->cmd_vector, cmd); -  if (ntype == VIEW_NODE) -    install_element (ENABLE_NODE, cmd); +	if (ntype == VIEW_NODE) +		install_element(ENABLE_NODE, cmd);  } -void -uninstall_element (enum node_type ntype, struct cmd_element *cmd) +void uninstall_element(enum node_type ntype, struct cmd_element *cmd)  { -  struct cmd_node *cnode; +	struct cmd_node *cnode; -  /* cmd_init hasn't been called */ -  if (!cmdvec) -    { -      fprintf (stderr, "%s called before cmd_init, breakage likely\n", -               __func__); -      return; -    } +	/* cmd_init hasn't been called */ +	if (!cmdvec) { +		fprintf(stderr, "%s called before cmd_init, breakage likely\n", +			__func__); +		return; +	} -  cnode = vector_slot (cmdvec, ntype); +	cnode = vector_slot(cmdvec, ntype); -  if (cnode == NULL) -    { -      fprintf (stderr, "Command node %d doesn't exist, please check it\n", -               ntype); -      exit (EXIT_FAILURE); -    } +	if (cnode == NULL) { +		fprintf(stderr, +			"Command node %d doesn't exist, please check it\n", +			ntype); +		exit(EXIT_FAILURE); +	} -  if (hash_release (cnode->cmd_hash, cmd) == NULL) -    { -      fprintf (stderr, -               "Trying to uninstall non-installed command (node %d):\n%s\n", -               ntype, cmd->string); -      return; -    } +	if (hash_release(cnode->cmd_hash, cmd) == NULL) { +		fprintf(stderr, +			"Trying to uninstall non-installed command (node %d):\n%s\n", +			ntype, cmd->string); +		return; +	} -  vector_unset_value (cnode->cmd_vector, cmd); +	vector_unset_value(cnode->cmd_vector, cmd); -  struct graph *graph = graph_new(); -  struct cmd_token *token = new_cmd_token (START_TKN, CMD_ATTR_NORMAL, NULL, NULL); -  graph_new_node (graph, token, (void (*)(void *)) &del_cmd_token); +	struct graph *graph = graph_new(); +	struct cmd_token *token = +		new_cmd_token(START_TKN, CMD_ATTR_NORMAL, NULL, NULL); +	graph_new_node(graph, token, (void (*)(void *)) & del_cmd_token); -  command_parse_format (graph, cmd); -  cmd_merge_graphs (cnode->cmdgraph, graph, -1); -  graph_delete_graph (graph); +	command_parse_format(graph, cmd); +	cmd_merge_graphs(cnode->cmdgraph, graph, -1); +	graph_delete_graph(graph); -  if (ntype == VIEW_NODE) -    uninstall_element (ENABLE_NODE, cmd); +	if (ntype == VIEW_NODE) +		uninstall_element(ENABLE_NODE, cmd);  }  static const unsigned char itoa64[] = -"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; +	"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; -static void -to64(char *s, long v, int n) +static void to64(char *s, long v, int n)  { -  while (--n >= 0) -    { -      *s++ = itoa64[v&0x3f]; -      v >>= 6; -    } +	while (--n >= 0) { +		*s++ = itoa64[v & 0x3f]; +		v >>= 6; +	}  } -static char * -zencrypt (const char *passwd) +static char *zencrypt(const char *passwd)  { -  char salt[6]; -  struct timeval tv; -  char *crypt (const char *, const char *); +	char salt[6]; +	struct timeval tv; +	char *crypt(const char *, const char *); -  gettimeofday(&tv,0); +	gettimeofday(&tv, 0); -  to64(&salt[0], random(), 3); -  to64(&salt[3], tv.tv_usec, 3); -  salt[5] = '\0'; +	to64(&salt[0], random(), 3); +	to64(&salt[3], tv.tv_usec, 3); +	salt[5] = '\0'; -  return crypt (passwd, salt); +	return crypt(passwd, salt);  }  /* This function write configuration of this host. */ -static int -config_write_host (struct vty *vty) -{ -  if (host.name) -    vty_out (vty, "hostname %s%s", host.name, VTY_NEWLINE); - -  if (host.encrypt) -    { -      if (host.password_encrypt) -        vty_out (vty, "password 8 %s%s", host.password_encrypt, VTY_NEWLINE); -      if (host.enable_encrypt) -        vty_out (vty, "enable password 8 %s%s", host.enable_encrypt, VTY_NEWLINE); -    } -  else -    { -      if (host.password) -        vty_out (vty, "password %s%s", host.password, VTY_NEWLINE); -      if (host.enable) -        vty_out (vty, "enable password %s%s", host.enable, VTY_NEWLINE); -    } - -  if (zlog_default->default_lvl != LOG_DEBUG) -    { -      vty_out (vty, "! N.B. The 'log trap' command is deprecated.%s", -               VTY_NEWLINE); -      vty_out (vty, "log trap %s%s", -               zlog_priority[zlog_default->default_lvl], VTY_NEWLINE); -    } - -  if (host.logfile && (zlog_default->maxlvl[ZLOG_DEST_FILE] != ZLOG_DISABLED)) -    { -      vty_out (vty, "log file %s", host.logfile); -      if (zlog_default->maxlvl[ZLOG_DEST_FILE] != zlog_default->default_lvl) -        vty_out (vty, " %s", -                 zlog_priority[zlog_default->maxlvl[ZLOG_DEST_FILE]]); -      vty_out (vty, "%s", VTY_NEWLINE); -    } - -  if (zlog_default->maxlvl[ZLOG_DEST_STDOUT] != ZLOG_DISABLED) -    { -      vty_out (vty, "log stdout"); -      if (zlog_default->maxlvl[ZLOG_DEST_STDOUT] != zlog_default->default_lvl) -        vty_out (vty, " %s", -                 zlog_priority[zlog_default->maxlvl[ZLOG_DEST_STDOUT]]); -      vty_out (vty, "%s", VTY_NEWLINE); -    } - -  if (zlog_default->maxlvl[ZLOG_DEST_MONITOR] == ZLOG_DISABLED) -    vty_out(vty,"no log monitor%s",VTY_NEWLINE); -  else if (zlog_default->maxlvl[ZLOG_DEST_MONITOR] != zlog_default->default_lvl) -    vty_out(vty,"log monitor %s%s", -            zlog_priority[zlog_default->maxlvl[ZLOG_DEST_MONITOR]],VTY_NEWLINE); - -  if (zlog_default->maxlvl[ZLOG_DEST_SYSLOG] != ZLOG_DISABLED) -    { -      vty_out (vty, "log syslog"); -      if (zlog_default->maxlvl[ZLOG_DEST_SYSLOG] != zlog_default->default_lvl) -        vty_out (vty, " %s", -                 zlog_priority[zlog_default->maxlvl[ZLOG_DEST_SYSLOG]]); -      vty_out (vty, "%s", VTY_NEWLINE); -    } - -  if (zlog_default->facility != LOG_DAEMON) -    vty_out (vty, "log facility %s%s", -             facility_name(zlog_default->facility), VTY_NEWLINE); - -  if (zlog_default->record_priority == 1) -    vty_out (vty, "log record-priority%s", VTY_NEWLINE); - -  if (zlog_default->timestamp_precision > 0) -    vty_out (vty, "log timestamp precision %d%s", -             zlog_default->timestamp_precision, VTY_NEWLINE); - -  if (host.advanced) -    vty_out (vty, "service advanced-vty%s", VTY_NEWLINE); - -  if (host.encrypt) -    vty_out (vty, "service password-encryption%s", VTY_NEWLINE); - -  if (host.lines >= 0) -    vty_out (vty, "service terminal-length %d%s", host.lines, -             VTY_NEWLINE); - -  if (host.motdfile) -    vty_out (vty, "banner motd file %s%s", host.motdfile, VTY_NEWLINE); -  else if (! host.motd) -    vty_out (vty, "no banner motd%s", VTY_NEWLINE); - -  return 1; +static int config_write_host(struct vty *vty) +{ +	if (host.name) +		vty_out(vty, "hostname %s%s", host.name, VTY_NEWLINE); + +	if (host.encrypt) { +		if (host.password_encrypt) +			vty_out(vty, "password 8 %s%s", host.password_encrypt, +				VTY_NEWLINE); +		if (host.enable_encrypt) +			vty_out(vty, "enable password 8 %s%s", +				host.enable_encrypt, VTY_NEWLINE); +	} else { +		if (host.password) +			vty_out(vty, "password %s%s", host.password, +				VTY_NEWLINE); +		if (host.enable) +			vty_out(vty, "enable password %s%s", host.enable, +				VTY_NEWLINE); +	} + +	if (zlog_default->default_lvl != LOG_DEBUG) { +		vty_out(vty, "! N.B. The 'log trap' command is deprecated.%s", +			VTY_NEWLINE); +		vty_out(vty, "log trap %s%s", +			zlog_priority[zlog_default->default_lvl], VTY_NEWLINE); +	} + +	if (host.logfile +	    && (zlog_default->maxlvl[ZLOG_DEST_FILE] != ZLOG_DISABLED)) { +		vty_out(vty, "log file %s", host.logfile); +		if (zlog_default->maxlvl[ZLOG_DEST_FILE] +		    != zlog_default->default_lvl) +			vty_out(vty, " %s", +				zlog_priority +					[zlog_default->maxlvl[ZLOG_DEST_FILE]]); +		vty_out(vty, "%s", VTY_NEWLINE); +	} + +	if (zlog_default->maxlvl[ZLOG_DEST_STDOUT] != ZLOG_DISABLED) { +		vty_out(vty, "log stdout"); +		if (zlog_default->maxlvl[ZLOG_DEST_STDOUT] +		    != zlog_default->default_lvl) +			vty_out(vty, " %s", +				zlog_priority[zlog_default->maxlvl +						      [ZLOG_DEST_STDOUT]]); +		vty_out(vty, "%s", VTY_NEWLINE); +	} + +	if (zlog_default->maxlvl[ZLOG_DEST_MONITOR] == ZLOG_DISABLED) +		vty_out(vty, "no log monitor%s", VTY_NEWLINE); +	else if (zlog_default->maxlvl[ZLOG_DEST_MONITOR] +		 != zlog_default->default_lvl) +		vty_out(vty, "log monitor %s%s", +			zlog_priority[zlog_default->maxlvl[ZLOG_DEST_MONITOR]], +			VTY_NEWLINE); + +	if (zlog_default->maxlvl[ZLOG_DEST_SYSLOG] != ZLOG_DISABLED) { +		vty_out(vty, "log syslog"); +		if (zlog_default->maxlvl[ZLOG_DEST_SYSLOG] +		    != zlog_default->default_lvl) +			vty_out(vty, " %s", +				zlog_priority[zlog_default->maxlvl +						      [ZLOG_DEST_SYSLOG]]); +		vty_out(vty, "%s", VTY_NEWLINE); +	} + +	if (zlog_default->facility != LOG_DAEMON) +		vty_out(vty, "log facility %s%s", +			facility_name(zlog_default->facility), VTY_NEWLINE); + +	if (zlog_default->record_priority == 1) +		vty_out(vty, "log record-priority%s", VTY_NEWLINE); + +	if (zlog_default->timestamp_precision > 0) +		vty_out(vty, "log timestamp precision %d%s", +			zlog_default->timestamp_precision, VTY_NEWLINE); + +	if (host.advanced) +		vty_out(vty, "service advanced-vty%s", VTY_NEWLINE); + +	if (host.encrypt) +		vty_out(vty, "service password-encryption%s", VTY_NEWLINE); + +	if (host.lines >= 0) +		vty_out(vty, "service terminal-length %d%s", host.lines, +			VTY_NEWLINE); + +	if (host.motdfile) +		vty_out(vty, "banner motd file %s%s", host.motdfile, +			VTY_NEWLINE); +	else if (!host.motd) +		vty_out(vty, "no banner motd%s", VTY_NEWLINE); + +	return 1;  }  /* Utility function for getting command graph. */ -static struct graph * -cmd_node_graph (vector v, enum node_type ntype) +static struct graph *cmd_node_graph(vector v, enum node_type ntype)  { -  struct cmd_node *cnode = vector_slot (v, ntype); -  return cnode->cmdgraph; +	struct cmd_node *cnode = vector_slot(v, ntype); +	return cnode->cmdgraph;  } -static int -cmd_try_do_shortcut (enum node_type node, char* first_word) { -  if ( first_word != NULL && -       node != AUTH_NODE && -       node != VIEW_NODE && -       node != AUTH_ENABLE_NODE && -       node != ENABLE_NODE && -       0 == strcmp( "do", first_word ) ) -    return 1; -  return 0; +static int cmd_try_do_shortcut(enum node_type node, char *first_word) +{ +	if (first_word != NULL && node != AUTH_NODE && node != VIEW_NODE +	    && node != AUTH_ENABLE_NODE && node != ENABLE_NODE +	    && 0 == strcmp("do", first_word)) +		return 1; +	return 0;  }  /**   * Compare function for cmd_token.   * Used with qsort to sort command completions.   */ -static int -compare_completions (const void *fst, const void *snd) +static int compare_completions(const void *fst, const void *snd)  { -  struct cmd_token *first = *(struct cmd_token **) fst, -                     *secnd = *(struct cmd_token **) snd; -  return strcmp (first->text, secnd->text); +	struct cmd_token *first = *(struct cmd_token **)fst, +			 *secnd = *(struct cmd_token **)snd; +	return strcmp(first->text, secnd->text);  }  /** @@ -825,51 +782,46 @@ compare_completions (const void *fst, const void *snd)   * @param completions linked list of cmd_token   * @return deduplicated and sorted vector with   */ -vector -completions_to_vec (struct list *completions) -{ -  vector comps = vector_init (VECTOR_MIN_SIZE); - -  struct listnode *ln; -  struct cmd_token *token, *cr = NULL; -  unsigned int i, exists; -  for (ALL_LIST_ELEMENTS_RO(completions,ln,token)) -  { -    if (token->type == END_TKN && (cr = token)) -      continue; - -    // linear search for token in completions vector -    exists = 0; -    for (i = 0; i < vector_active (comps) && !exists; i++) -    { -      struct cmd_token *curr = vector_slot (comps, i); +vector completions_to_vec(struct list *completions) +{ +	vector comps = vector_init(VECTOR_MIN_SIZE); + +	struct listnode *ln; +	struct cmd_token *token, *cr = NULL; +	unsigned int i, exists; +	for (ALL_LIST_ELEMENTS_RO(completions, ln, token)) { +		if (token->type == END_TKN && (cr = token)) +			continue; + +		// linear search for token in completions vector +		exists = 0; +		for (i = 0; i < vector_active(comps) && !exists; i++) { +			struct cmd_token *curr = vector_slot(comps, i);  #ifdef VTYSH_DEBUG -      exists = !strcmp (curr->text, token->text) && -               !strcmp (curr->desc, token->desc); +			exists = !strcmp(curr->text, token->text) +				 && !strcmp(curr->desc, token->desc);  #else -      exists = !strcmp (curr->text, token->text); +			exists = !strcmp(curr->text, token->text);  #endif /* VTYSH_DEBUG */ -    } +		} -    if (!exists) -      vector_set (comps, token); -  } +		if (!exists) +			vector_set(comps, token); +	} -  // sort completions -  qsort (comps->index, -         vector_active (comps), -         sizeof (void *), -         &compare_completions); +	// sort completions +	qsort(comps->index, vector_active(comps), sizeof(void *), +	      &compare_completions); -  // make <cr> the first element, if it is present -  if (cr) -  { -    vector_set_index (comps, vector_active (comps), NULL); -    memmove (comps->index + 1, comps->index, (comps->alloced - 1) * sizeof (void *)); -    vector_set_index (comps, 0, cr); -  } +	// make <cr> the first element, if it is present +	if (cr) { +		vector_set_index(comps, vector_active(comps), NULL); +		memmove(comps->index + 1, comps->index, +			(comps->alloced - 1) * sizeof(void *)); +		vector_set_index(comps, 0, cr); +	} -  return comps; +	return comps;  }  /**   * Generates a vector of cmd_token representing possible completions @@ -880,69 +832,66 @@ completions_to_vec (struct list *completions)   * @param status pointer to matcher status code   * @return vector of struct cmd_token * with possible completions   */ -static vector -cmd_complete_command_real (vector vline, struct vty *vty, int *status) +static vector cmd_complete_command_real(vector vline, struct vty *vty, +					int *status)  { -  struct list *completions; -  struct graph *cmdgraph = cmd_node_graph (cmdvec, vty->node); +	struct list *completions; +	struct graph *cmdgraph = cmd_node_graph(cmdvec, vty->node); -  enum matcher_rv rv = command_complete (cmdgraph, vline, &completions); +	enum matcher_rv rv = command_complete(cmdgraph, vline, &completions); -  if (MATCHER_ERROR(rv)) -  { -    *status = CMD_ERR_NO_MATCH; -    return NULL; -  } +	if (MATCHER_ERROR(rv)) { +		*status = CMD_ERR_NO_MATCH; +		return NULL; +	} -  vector comps = completions_to_vec (completions); -  list_delete (completions); +	vector comps = completions_to_vec(completions); +	list_delete(completions); -  // set status code appropriately -  switch (vector_active (comps)) -  { -    case 0: -      *status = CMD_ERR_NO_MATCH; -      break; -    case 1: -      *status = CMD_COMPLETE_FULL_MATCH; -      break; -    default: -      *status = CMD_COMPLETE_LIST_MATCH; -  } +	// set status code appropriately +	switch (vector_active(comps)) { +	case 0: +		*status = CMD_ERR_NO_MATCH; +		break; +	case 1: +		*status = CMD_COMPLETE_FULL_MATCH; +		break; +	default: +		*status = CMD_COMPLETE_LIST_MATCH; +	} -  return comps; +	return comps;  } -vector -cmd_describe_command (vector vline, struct vty *vty, int *status) +vector cmd_describe_command(vector vline, struct vty *vty, int *status)  { -  vector ret; +	vector ret; -  if ( cmd_try_do_shortcut(vty->node, vector_slot(vline, 0) ) ) -    { -      enum node_type onode; -      vector shifted_vline; -      unsigned int index; +	if (cmd_try_do_shortcut(vty->node, vector_slot(vline, 0))) { +		enum node_type onode; +		vector shifted_vline; +		unsigned int index; -      onode = vty->node; -      vty->node = ENABLE_NODE; -      /* We can try it on enable node, cos' the vty is authenticated */ +		onode = vty->node; +		vty->node = ENABLE_NODE; +		/* We can try it on enable node, cos' the vty is authenticated +		 */ -      shifted_vline = vector_init (vector_count(vline)); -      /* use memcpy? */ -      for (index = 1; index < vector_active (vline); index++) -        { -          vector_set_index (shifted_vline, index-1, vector_lookup(vline, index)); -        } +		shifted_vline = vector_init(vector_count(vline)); +		/* use memcpy? */ +		for (index = 1; index < vector_active(vline); index++) { +			vector_set_index(shifted_vline, index - 1, +					 vector_lookup(vline, index)); +		} -      ret = cmd_complete_command_real (shifted_vline, vty, status); +		ret = cmd_complete_command_real(shifted_vline, vty, status); -      vector_free(shifted_vline); -      vty->node = onode; -      return ret; -  } +		vector_free(shifted_vline); +		vty->node = onode; +		return ret; +	} -  return cmd_complete_command_real (vline, vty, status); +	return cmd_complete_command_real(vline, vty, status);  }  /** @@ -957,188 +906,182 @@ cmd_describe_command (vector vline, struct vty *vty, int *status)   * @return set of valid strings for use with Readline as tab-completions.   */ -char ** -cmd_complete_command (vector vline, struct vty *vty, int *status) -{ -  char **ret = NULL; -  int original_node = vty->node; -  vector input_line = vector_init (vector_count (vline)); - -  // if the first token is 'do' we'll want to execute the command in the enable node -  int do_shortcut = cmd_try_do_shortcut (vty->node, vector_slot (vline, 0)); -  vty->node = do_shortcut ? ENABLE_NODE : original_node; - -  // construct the input line we'll be matching on -  unsigned int offset = (do_shortcut) ? 1 : 0; -  for (unsigned index = 0; index + offset < vector_active (vline); index++) -    vector_set_index (input_line, index, vector_lookup (vline, index + offset)); - -  // get token completions -- this is a copying operation -  vector comps = NULL, initial_comps; -  initial_comps = cmd_complete_command_real (input_line, vty, status); - -  if (!MATCHER_ERROR (*status)) -  { -    assert (initial_comps); -    // filter out everything that is not suitable for a tab-completion -    comps = vector_init (VECTOR_MIN_SIZE); -    for (unsigned int i = 0; i < vector_active(initial_comps); i++) -    { -      struct cmd_token *token = vector_slot (initial_comps, i); -      if (token->type == WORD_TKN) -        vector_set (comps, token); -    } -    vector_free (initial_comps); - -    // since we filtered results, we need to re-set status code -    switch (vector_active (comps)) -    { -      case 0: -        *status = CMD_ERR_NO_MATCH; -        break; -      case 1: -        *status = CMD_COMPLETE_FULL_MATCH; -        break; -      default: -        *status = CMD_COMPLETE_LIST_MATCH; -    } - -    // copy completions text into an array of char* -    ret = XMALLOC (MTYPE_TMP, (vector_active (comps)+1) * sizeof (char *)); -    unsigned int i; -    for (i = 0; i < vector_active (comps); i++) -      { -        struct cmd_token *token = vector_slot (comps, i); -        ret[i] = XSTRDUP (MTYPE_TMP, token->text); -        vector_unset (comps, i); -      } -    // set the last element to NULL, because this array is used in -    // a Readline completion_generator function which expects NULL -    // as a sentinel value -    ret[i] = NULL; -    vector_free (comps); -    comps = NULL; -  } -  else if (initial_comps) -    vector_free (initial_comps); - -  // comps should always be null here -  assert (!comps); - -  // free the adjusted input line -  vector_free (input_line); - -  // reset vty->node to its original value -  vty->node = original_node; - -  return ret; +char **cmd_complete_command(vector vline, struct vty *vty, int *status) +{ +	char **ret = NULL; +	int original_node = vty->node; +	vector input_line = vector_init(vector_count(vline)); + +	// if the first token is 'do' we'll want to execute the command in the +	// enable node +	int do_shortcut = cmd_try_do_shortcut(vty->node, vector_slot(vline, 0)); +	vty->node = do_shortcut ? ENABLE_NODE : original_node; + +	// construct the input line we'll be matching on +	unsigned int offset = (do_shortcut) ? 1 : 0; +	for (unsigned index = 0; index + offset < vector_active(vline); index++) +		vector_set_index(input_line, index, +				 vector_lookup(vline, index + offset)); + +	// get token completions -- this is a copying operation +	vector comps = NULL, initial_comps; +	initial_comps = cmd_complete_command_real(input_line, vty, status); + +	if (!MATCHER_ERROR(*status)) { +		assert(initial_comps); +		// filter out everything that is not suitable for a +		// tab-completion +		comps = vector_init(VECTOR_MIN_SIZE); +		for (unsigned int i = 0; i < vector_active(initial_comps); +		     i++) { +			struct cmd_token *token = vector_slot(initial_comps, i); +			if (token->type == WORD_TKN) +				vector_set(comps, token); +		} +		vector_free(initial_comps); + +		// since we filtered results, we need to re-set status code +		switch (vector_active(comps)) { +		case 0: +			*status = CMD_ERR_NO_MATCH; +			break; +		case 1: +			*status = CMD_COMPLETE_FULL_MATCH; +			break; +		default: +			*status = CMD_COMPLETE_LIST_MATCH; +		} + +		// copy completions text into an array of char* +		ret = XMALLOC(MTYPE_TMP, +			      (vector_active(comps) + 1) * sizeof(char *)); +		unsigned int i; +		for (i = 0; i < vector_active(comps); i++) { +			struct cmd_token *token = vector_slot(comps, i); +			ret[i] = XSTRDUP(MTYPE_TMP, token->text); +			vector_unset(comps, i); +		} +		// set the last element to NULL, because this array is used in +		// a Readline completion_generator function which expects NULL +		// as a sentinel value +		ret[i] = NULL; +		vector_free(comps); +		comps = NULL; +	} else if (initial_comps) +		vector_free(initial_comps); + +	// comps should always be null here +	assert(!comps); + +	// free the adjusted input line +	vector_free(input_line); + +	// reset vty->node to its original value +	vty->node = original_node; + +	return ret;  }  /* return parent node */  /* MUST eventually converge on CONFIG_NODE */ -enum node_type -node_parent ( enum node_type node ) -{ -  enum node_type ret; - -  assert (node > CONFIG_NODE); - -  switch (node) -    { -    case BGP_VPNV4_NODE: -    case BGP_VPNV6_NODE: -    case BGP_VRF_POLICY_NODE: -    case BGP_VNC_DEFAULTS_NODE: -    case BGP_VNC_NVE_GROUP_NODE: -    case BGP_VNC_L2_GROUP_NODE: -    case BGP_IPV4_NODE: -    case BGP_IPV4M_NODE: -    case BGP_IPV6_NODE: -    case BGP_IPV6M_NODE: -    case BGP_EVPN_NODE: -      ret = BGP_NODE; -      break; -    case KEYCHAIN_KEY_NODE: -      ret = KEYCHAIN_NODE; -      break; -    case LINK_PARAMS_NODE: -      ret = INTERFACE_NODE; -      break; -    case LDP_IPV4_NODE: -    case LDP_IPV6_NODE: -      ret = LDP_NODE; -      break; -    case LDP_IPV4_IFACE_NODE: -      ret = LDP_IPV4_NODE; -      break; -    case LDP_IPV6_IFACE_NODE: -      ret = LDP_IPV6_NODE; -      break; -    case LDP_PSEUDOWIRE_NODE: -      ret = LDP_L2VPN_NODE; -      break; -    default: -      ret = CONFIG_NODE; -      break; -    } - -  return ret; +enum node_type node_parent(enum node_type node) +{ +	enum node_type ret; + +	assert(node > CONFIG_NODE); + +	switch (node) { +	case BGP_VPNV4_NODE: +	case BGP_VPNV6_NODE: +	case BGP_VRF_POLICY_NODE: +	case BGP_VNC_DEFAULTS_NODE: +	case BGP_VNC_NVE_GROUP_NODE: +	case BGP_VNC_L2_GROUP_NODE: +	case BGP_IPV4_NODE: +	case BGP_IPV4M_NODE: +	case BGP_IPV6_NODE: +	case BGP_IPV6M_NODE: +	case BGP_EVPN_NODE: +		ret = BGP_NODE; +		break; +	case KEYCHAIN_KEY_NODE: +		ret = KEYCHAIN_NODE; +		break; +	case LINK_PARAMS_NODE: +		ret = INTERFACE_NODE; +		break; +	case LDP_IPV4_NODE: +	case LDP_IPV6_NODE: +		ret = LDP_NODE; +		break; +	case LDP_IPV4_IFACE_NODE: +		ret = LDP_IPV4_NODE; +		break; +	case LDP_IPV6_IFACE_NODE: +		ret = LDP_IPV6_NODE; +		break; +	case LDP_PSEUDOWIRE_NODE: +		ret = LDP_L2VPN_NODE; +		break; +	default: +		ret = CONFIG_NODE; +		break; +	} + +	return ret;  }  /* Execute command by argument vline vector. */ -static int -cmd_execute_command_real (vector vline, -                          enum filter_type filter, -                          struct vty *vty, -                          const struct cmd_element **cmd) -{ -  struct list *argv_list; -  enum matcher_rv status; -  const struct cmd_element *matched_element = NULL; - -  struct graph *cmdgraph = cmd_node_graph (cmdvec, vty->node); -  status = command_match (cmdgraph, vline, &argv_list, &matched_element); - -  if (cmd) -    *cmd = matched_element; - -  // if matcher error, return corresponding CMD_ERR -  if (MATCHER_ERROR(status)) -  { -    if (argv_list) -      list_delete (argv_list); -    switch (status) -    { -      case MATCHER_INCOMPLETE: -        return CMD_ERR_INCOMPLETE; -      case MATCHER_AMBIGUOUS: -        return CMD_ERR_AMBIGUOUS; -      default: -        return CMD_ERR_NO_MATCH; -    } -  } - -  // build argv array from argv list -  struct cmd_token **argv = XMALLOC (MTYPE_TMP, argv_list->count * sizeof (struct cmd_token *)); -  struct listnode *ln; -  struct cmd_token *token; -  unsigned int i = 0; -  for (ALL_LIST_ELEMENTS_RO(argv_list,ln,token)) -    argv[i++] = token; - -  int argc = argv_list->count; - -  int ret; -  if (matched_element->daemon) -    ret = CMD_SUCCESS_DAEMON; -  else -    ret = matched_element->func (matched_element, vty, argc, argv); - -  // delete list and cmd_token's in it -  list_delete (argv_list); -  XFREE (MTYPE_TMP, argv); - -  return ret; +static int cmd_execute_command_real(vector vline, enum filter_type filter, +				    struct vty *vty, +				    const struct cmd_element **cmd) +{ +	struct list *argv_list; +	enum matcher_rv status; +	const struct cmd_element *matched_element = NULL; + +	struct graph *cmdgraph = cmd_node_graph(cmdvec, vty->node); +	status = command_match(cmdgraph, vline, &argv_list, &matched_element); + +	if (cmd) +		*cmd = matched_element; + +	// if matcher error, return corresponding CMD_ERR +	if (MATCHER_ERROR(status)) { +		if (argv_list) +			list_delete(argv_list); +		switch (status) { +		case MATCHER_INCOMPLETE: +			return CMD_ERR_INCOMPLETE; +		case MATCHER_AMBIGUOUS: +			return CMD_ERR_AMBIGUOUS; +		default: +			return CMD_ERR_NO_MATCH; +		} +	} + +	// build argv array from argv list +	struct cmd_token **argv = XMALLOC( +		MTYPE_TMP, argv_list->count * sizeof(struct cmd_token *)); +	struct listnode *ln; +	struct cmd_token *token; +	unsigned int i = 0; +	for (ALL_LIST_ELEMENTS_RO(argv_list, ln, token)) +		argv[i++] = token; + +	int argc = argv_list->count; + +	int ret; +	if (matched_element->daemon) +		ret = CMD_SUCCESS_DAEMON; +	else +		ret = matched_element->func(matched_element, vty, argc, argv); + +	// delete list and cmd_token's in it +	list_delete(argv_list); +	XFREE(MTYPE_TMP, argv); + +	return ret;  }  /** @@ -1156,58 +1099,59 @@ cmd_execute_command_real (vector vline,   * @return The status of the command that has been executed or an error code   *         as to why no command could be executed.   */ -int -cmd_execute_command (vector vline, struct vty *vty, -                     const struct cmd_element **cmd, -                     int vtysh) +int cmd_execute_command(vector vline, struct vty *vty, +			const struct cmd_element **cmd, int vtysh)  { -  int ret, saved_ret = 0; -  enum node_type onode, try_node; +	int ret, saved_ret = 0; +	enum node_type onode, try_node; -  onode = try_node = vty->node; +	onode = try_node = vty->node; -  if (cmd_try_do_shortcut(vty->node, vector_slot(vline, 0))) -    { -      vector shifted_vline; -      unsigned int index; +	if (cmd_try_do_shortcut(vty->node, vector_slot(vline, 0))) { +		vector shifted_vline; +		unsigned int index; -      vty->node = ENABLE_NODE; -      /* We can try it on enable node, cos' the vty is authenticated */ +		vty->node = ENABLE_NODE; +		/* We can try it on enable node, cos' the vty is authenticated +		 */ -      shifted_vline = vector_init (vector_count(vline)); -      /* use memcpy? */ -      for (index = 1; index < vector_active (vline); index++) -        vector_set_index (shifted_vline, index-1, vector_lookup(vline, index)); +		shifted_vline = vector_init(vector_count(vline)); +		/* use memcpy? */ +		for (index = 1; index < vector_active(vline); index++) +			vector_set_index(shifted_vline, index - 1, +					 vector_lookup(vline, index)); -      ret = cmd_execute_command_real (shifted_vline, FILTER_RELAXED, vty, cmd); +		ret = cmd_execute_command_real(shifted_vline, FILTER_RELAXED, +					       vty, cmd); -      vector_free(shifted_vline); -      vty->node = onode; -      return ret; -  } +		vector_free(shifted_vline); +		vty->node = onode; +		return ret; +	} -  saved_ret = ret = cmd_execute_command_real (vline, FILTER_RELAXED, vty, cmd); +	saved_ret = ret = +		cmd_execute_command_real(vline, FILTER_RELAXED, vty, cmd); -  if (vtysh) -    return saved_ret; +	if (vtysh) +		return saved_ret; -  if (ret != CMD_SUCCESS && ret != CMD_WARNING) -    { -      /* This assumes all nodes above CONFIG_NODE are childs of CONFIG_NODE */ -      while (vty->node > CONFIG_NODE) -        { -          try_node = node_parent(try_node); -          vty->node = try_node; -          ret = cmd_execute_command_real (vline, FILTER_RELAXED, vty, cmd); -          if (ret == CMD_SUCCESS || ret == CMD_WARNING) -            return ret; -        } -      /* no command succeeded, reset the vty to the original node */ -      vty->node = onode; -    } +	if (ret != CMD_SUCCESS && ret != CMD_WARNING) { +		/* This assumes all nodes above CONFIG_NODE are childs of +		 * CONFIG_NODE */ +		while (vty->node > CONFIG_NODE) { +			try_node = node_parent(try_node); +			vty->node = try_node; +			ret = cmd_execute_command_real(vline, FILTER_RELAXED, +						       vty, cmd); +			if (ret == CMD_SUCCESS || ret == CMD_WARNING) +				return ret; +		} +		/* no command succeeded, reset the vty to the original node */ +		vty->node = onode; +	} -  /* return command status for original node */ -  return saved_ret; +	/* return command status for original node */ +	return saved_ret;  }  /** @@ -1223,102 +1167,97 @@ cmd_execute_command (vector vline, struct vty *vty,   * @return The status of the command that has been executed or an error code   *         as to why no command could be executed.   */ -int -cmd_execute_command_strict (vector vline, struct vty *vty, -                            const struct cmd_element **cmd) +int cmd_execute_command_strict(vector vline, struct vty *vty, +			       const struct cmd_element **cmd)  { -  return cmd_execute_command_real(vline, FILTER_STRICT, vty, cmd); +	return cmd_execute_command_real(vline, FILTER_STRICT, vty, cmd);  }  /** - * Parse one line of config, walking up the parse tree attempting to find a match + * Parse one line of config, walking up the parse tree attempting to find a + * match   *   * @param vty The vty context in which the command should be executed.   * @param cmd Pointer where the struct cmd_element* of the match command   *            will be stored, if any.  May be set to NULL if this info is   *            not needed. - * @param use_daemon Boolean to control whether or not we match on CMD_SUCCESS_DAEMON + * @param use_daemon Boolean to control whether or not we match on + * CMD_SUCCESS_DAEMON   *                   or not.   * @return The status of the command that has been executed or an error code   *         as to why no command could be executed.   */ -int -command_config_read_one_line (struct vty *vty, const struct cmd_element **cmd, int use_daemon) +int command_config_read_one_line(struct vty *vty, +				 const struct cmd_element **cmd, int use_daemon)  { -  vector vline; -  int saved_node; -  int ret; +	vector vline; +	int saved_node; +	int ret; -  vline = cmd_make_strvec (vty->buf); +	vline = cmd_make_strvec(vty->buf); -  /* In case of comment line */ -  if (vline == NULL) -    return CMD_SUCCESS; +	/* In case of comment line */ +	if (vline == NULL) +		return CMD_SUCCESS; -  /* Execute configuration command : this is strict match */ -  ret = cmd_execute_command_strict (vline, vty, cmd); +	/* Execute configuration command : this is strict match */ +	ret = cmd_execute_command_strict(vline, vty, cmd); -  // Climb the tree and try the command again at each node -  if (!(use_daemon && ret == CMD_SUCCESS_DAEMON) && -      !(!use_daemon && ret == CMD_ERR_NOTHING_TODO) && -      ret != CMD_SUCCESS && -      ret != CMD_WARNING && -      vty->node != CONFIG_NODE) { +	// Climb the tree and try the command again at each node +	if (!(use_daemon && ret == CMD_SUCCESS_DAEMON) +	    && !(!use_daemon && ret == CMD_ERR_NOTHING_TODO) +	    && ret != CMD_SUCCESS && ret != CMD_WARNING +	    && vty->node != CONFIG_NODE) { -    saved_node = vty->node; +		saved_node = vty->node; -    while (!(use_daemon && ret == CMD_SUCCESS_DAEMON) && -           !(!use_daemon && ret == CMD_ERR_NOTHING_TODO) && -           ret != CMD_SUCCESS && -           ret != CMD_WARNING && -           vty->node > CONFIG_NODE) { -      vty->node = node_parent(vty->node); -      ret = cmd_execute_command_strict (vline, vty, cmd); -    } +		while (!(use_daemon && ret == CMD_SUCCESS_DAEMON) +		       && !(!use_daemon && ret == CMD_ERR_NOTHING_TODO) +		       && ret != CMD_SUCCESS && ret != CMD_WARNING +		       && vty->node > CONFIG_NODE) { +			vty->node = node_parent(vty->node); +			ret = cmd_execute_command_strict(vline, vty, cmd); +		} -    // If climbing the tree did not work then ignore the command and -    // stay at the same node -    if (!(use_daemon && ret == CMD_SUCCESS_DAEMON) && -        !(!use_daemon && ret == CMD_ERR_NOTHING_TODO) && -        ret != CMD_SUCCESS && -        ret != CMD_WARNING) -      { -        vty->node = saved_node; -      } -  } +		// If climbing the tree did not work then ignore the command and +		// stay at the same node +		if (!(use_daemon && ret == CMD_SUCCESS_DAEMON) +		    && !(!use_daemon && ret == CMD_ERR_NOTHING_TODO) +		    && ret != CMD_SUCCESS && ret != CMD_WARNING) { +			vty->node = saved_node; +		} +	} -  if (ret != CMD_SUCCESS && ret != CMD_WARNING) -    memcpy (vty->error_buf, vty->buf, VTY_BUFSIZ); +	if (ret != CMD_SUCCESS && ret != CMD_WARNING) +		memcpy(vty->error_buf, vty->buf, VTY_BUFSIZ); -  cmd_free_strvec (vline); +	cmd_free_strvec(vline); -  return ret; +	return ret;  }  /* Configuration make from file. */ -int -config_from_file (struct vty *vty, FILE *fp, unsigned int *line_num) +int config_from_file(struct vty *vty, FILE *fp, unsigned int *line_num)  { -  int ret, error_ret=0; -  *line_num = 0; +	int ret, error_ret = 0; +	*line_num = 0; -  while (fgets (vty->buf, VTY_BUFSIZ, fp)) -    { -      if (!error_ret) -        ++(*line_num); +	while (fgets(vty->buf, VTY_BUFSIZ, fp)) { +		if (!error_ret) +			++(*line_num); -      ret = command_config_read_one_line (vty, NULL, 0); +		ret = command_config_read_one_line(vty, NULL, 0); -      if (ret != CMD_SUCCESS && ret != CMD_WARNING && -          ret != CMD_ERR_NOTHING_TODO) -        error_ret = ret; -    } +		if (ret != CMD_SUCCESS && ret != CMD_WARNING +		    && ret != CMD_ERR_NOTHING_TODO) +			error_ret = ret; +	} -  if (error_ret) { -      return error_ret; -  } +	if (error_ret) { +		return error_ret; +	} -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* Configuration from terminal */ @@ -1328,14 +1267,14 @@ DEFUN (config_terminal,         "Configuration from vty interface\n"         "Configuration terminal\n")  { -  if (vty_config_lock (vty)) -    vty->node = CONFIG_NODE; -  else -    { -      vty_out (vty, "VTY configuration is locked by other VTY%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  return CMD_SUCCESS; +	if (vty_config_lock(vty)) +		vty->node = CONFIG_NODE; +	else { +		vty_out(vty, "VTY configuration is locked by other VTY%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} +	return CMD_SUCCESS;  }  /* Enable command */ @@ -1344,14 +1283,14 @@ DEFUN (enable,         "enable",         "Turn on privileged mode command\n")  { -  /* If enable password is NULL, change to ENABLE_NODE */ -  if ((host.enable == NULL && host.enable_encrypt == NULL) || -      vty->type == VTY_SHELL_SERV) -    vty->node = ENABLE_NODE; -  else -    vty->node = AUTH_ENABLE_NODE; +	/* If enable password is NULL, change to ENABLE_NODE */ +	if ((host.enable == NULL && host.enable_encrypt == NULL) +	    || vty->type == VTY_SHELL_SERV) +		vty->node = ENABLE_NODE; +	else +		vty->node = AUTH_ENABLE_NODE; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* Disable command */ @@ -1360,9 +1299,9 @@ DEFUN (disable,         "disable",         "Turn off privileged mode command\n")  { -  if (vty->node == ENABLE_NODE) -    vty->node = VIEW_NODE; -  return CMD_SUCCESS; +	if (vty->node == ENABLE_NODE) +		vty->node = VIEW_NODE; +	return CMD_SUCCESS;  }  /* Down vty node level. */ @@ -1371,81 +1310,79 @@ DEFUN (config_exit,         "exit",         "Exit current mode and down to previous mode\n")  { -  cmd_exit (vty); -  return CMD_SUCCESS; -} - -void -cmd_exit (struct vty *vty) -{ -  switch (vty->node) -    { -    case VIEW_NODE: -    case ENABLE_NODE: -      if (vty_shell (vty)) -        exit (0); -      else -        vty->status = VTY_CLOSE; -      break; -    case CONFIG_NODE: -      vty->node = ENABLE_NODE; -      vty_config_unlock (vty); -      break; -    case INTERFACE_NODE: -    case PW_NODE: -    case NS_NODE: -    case VRF_NODE: -    case ZEBRA_NODE: -    case BGP_NODE: -    case RIP_NODE: -    case RIPNG_NODE: -    case OSPF_NODE: -    case OSPF6_NODE: -    case LDP_NODE: -    case LDP_L2VPN_NODE: -    case ISIS_NODE: -    case KEYCHAIN_NODE: -    case MASC_NODE: -    case RMAP_NODE: -    case PIM_NODE: -    case VTY_NODE: -      vty->node = CONFIG_NODE; -      break; -    case BGP_IPV4_NODE: -    case BGP_IPV4M_NODE: -    case BGP_VPNV4_NODE: -    case BGP_VPNV6_NODE: -    case BGP_VRF_POLICY_NODE: -    case BGP_VNC_DEFAULTS_NODE: -    case BGP_VNC_NVE_GROUP_NODE: -    case BGP_VNC_L2_GROUP_NODE: -    case BGP_IPV6_NODE: -    case BGP_IPV6M_NODE: -    case BGP_EVPN_NODE: -      vty->node = BGP_NODE; -      break; -    case LDP_IPV4_NODE: -    case LDP_IPV6_NODE: -      vty->node = LDP_NODE; -      break; -    case LDP_IPV4_IFACE_NODE: -      vty->node = LDP_IPV4_NODE; -      break; -    case LDP_IPV6_IFACE_NODE: -      vty->node = LDP_IPV6_NODE; -      break; -    case LDP_PSEUDOWIRE_NODE: -      vty->node = LDP_L2VPN_NODE; -      break; -    case KEYCHAIN_KEY_NODE: -      vty->node = KEYCHAIN_NODE; -      break; -    case LINK_PARAMS_NODE: -      vty->node = INTERFACE_NODE; -      break; -    default: -      break; -    } +	cmd_exit(vty); +	return CMD_SUCCESS; +} + +void cmd_exit(struct vty *vty) +{ +	switch (vty->node) { +	case VIEW_NODE: +	case ENABLE_NODE: +		if (vty_shell(vty)) +			exit(0); +		else +			vty->status = VTY_CLOSE; +		break; +	case CONFIG_NODE: +		vty->node = ENABLE_NODE; +		vty_config_unlock(vty); +		break; +	case INTERFACE_NODE: +	case PW_NODE: +	case NS_NODE: +	case VRF_NODE: +	case ZEBRA_NODE: +	case BGP_NODE: +	case RIP_NODE: +	case RIPNG_NODE: +	case OSPF_NODE: +	case OSPF6_NODE: +	case LDP_NODE: +	case LDP_L2VPN_NODE: +	case ISIS_NODE: +	case KEYCHAIN_NODE: +	case MASC_NODE: +	case RMAP_NODE: +	case PIM_NODE: +	case VTY_NODE: +		vty->node = CONFIG_NODE; +		break; +	case BGP_IPV4_NODE: +	case BGP_IPV4M_NODE: +	case BGP_VPNV4_NODE: +	case BGP_VPNV6_NODE: +	case BGP_VRF_POLICY_NODE: +	case BGP_VNC_DEFAULTS_NODE: +	case BGP_VNC_NVE_GROUP_NODE: +	case BGP_VNC_L2_GROUP_NODE: +	case BGP_IPV6_NODE: +	case BGP_IPV6M_NODE: +	case BGP_EVPN_NODE: +		vty->node = BGP_NODE; +		break; +	case LDP_IPV4_NODE: +	case LDP_IPV6_NODE: +		vty->node = LDP_NODE; +		break; +	case LDP_IPV4_IFACE_NODE: +		vty->node = LDP_IPV4_NODE; +		break; +	case LDP_IPV6_IFACE_NODE: +		vty->node = LDP_IPV6_NODE; +		break; +	case LDP_PSEUDOWIRE_NODE: +		vty->node = LDP_L2VPN_NODE; +		break; +	case KEYCHAIN_KEY_NODE: +		vty->node = KEYCHAIN_NODE; +		break; +	case LINK_PARAMS_NODE: +		vty->node = INTERFACE_NODE; +		break; +	default: +		break; +	}  }  /* ALIAS_FIXME */ @@ -1454,7 +1391,7 @@ DEFUN (config_quit,         "quit",         "Exit current mode and down to previous mode\n")  { -  return config_exit (self, vty, argc, argv); +	return config_exit(self, vty, argc, argv);  } @@ -1464,56 +1401,55 @@ DEFUN (config_end,         "end",         "End current mode and change to enable mode.")  { -  switch (vty->node) -    { -    case VIEW_NODE: -    case ENABLE_NODE: -      /* Nothing to do. */ -      break; -    case CONFIG_NODE: -    case INTERFACE_NODE: -    case PW_NODE: -    case NS_NODE: -    case VRF_NODE: -    case ZEBRA_NODE: -    case RIP_NODE: -    case RIPNG_NODE: -    case BGP_NODE: -    case BGP_VRF_POLICY_NODE: -    case BGP_VNC_DEFAULTS_NODE: -    case BGP_VNC_NVE_GROUP_NODE: -    case BGP_VNC_L2_GROUP_NODE: -    case BGP_VPNV4_NODE: -    case BGP_VPNV6_NODE: -    case BGP_IPV4_NODE: -    case BGP_IPV4M_NODE: -    case BGP_IPV6_NODE: -    case BGP_IPV6M_NODE: -    case BGP_EVPN_NODE: -    case RMAP_NODE: -    case OSPF_NODE: -    case OSPF6_NODE: -    case LDP_NODE: -    case LDP_IPV4_NODE: -    case LDP_IPV6_NODE: -    case LDP_IPV4_IFACE_NODE: -    case LDP_IPV6_IFACE_NODE: -    case LDP_L2VPN_NODE: -    case LDP_PSEUDOWIRE_NODE: -    case ISIS_NODE: -    case KEYCHAIN_NODE: -    case KEYCHAIN_KEY_NODE: -    case MASC_NODE: -    case PIM_NODE: -    case VTY_NODE: -    case LINK_PARAMS_NODE: -      vty_config_unlock (vty); -      vty->node = ENABLE_NODE; -      break; -    default: -      break; -    } -  return CMD_SUCCESS; +	switch (vty->node) { +	case VIEW_NODE: +	case ENABLE_NODE: +		/* Nothing to do. */ +		break; +	case CONFIG_NODE: +	case INTERFACE_NODE: +	case PW_NODE: +	case NS_NODE: +	case VRF_NODE: +	case ZEBRA_NODE: +	case RIP_NODE: +	case RIPNG_NODE: +	case BGP_NODE: +	case BGP_VRF_POLICY_NODE: +	case BGP_VNC_DEFAULTS_NODE: +	case BGP_VNC_NVE_GROUP_NODE: +	case BGP_VNC_L2_GROUP_NODE: +	case BGP_VPNV4_NODE: +	case BGP_VPNV6_NODE: +	case BGP_IPV4_NODE: +	case BGP_IPV4M_NODE: +	case BGP_IPV6_NODE: +	case BGP_IPV6M_NODE: +	case BGP_EVPN_NODE: +	case RMAP_NODE: +	case OSPF_NODE: +	case OSPF6_NODE: +	case LDP_NODE: +	case LDP_IPV4_NODE: +	case LDP_IPV6_NODE: +	case LDP_IPV4_IFACE_NODE: +	case LDP_IPV6_IFACE_NODE: +	case LDP_L2VPN_NODE: +	case LDP_PSEUDOWIRE_NODE: +	case ISIS_NODE: +	case KEYCHAIN_NODE: +	case KEYCHAIN_KEY_NODE: +	case MASC_NODE: +	case PIM_NODE: +	case VTY_NODE: +	case LINK_PARAMS_NODE: +		vty_config_unlock(vty); +		vty->node = ENABLE_NODE; +		break; +	default: +		break; +	} +	return CMD_SUCCESS;  }  /* Show version. */ @@ -1523,14 +1459,13 @@ DEFUN (show_version,         SHOW_STR         "Displays zebra version\n")  { -  vty_out (vty, "%s %s (%s).%s", FRR_FULL_NAME, FRR_VERSION, -	   host.name ? host.name : "", -	   VTY_NEWLINE); -  vty_out (vty, "%s%s%s", FRR_COPYRIGHT, GIT_INFO, VTY_NEWLINE); -  vty_out (vty, "configured with:%s    %s%s", VTY_NEWLINE, -           FRR_CONFIG_ARGS, VTY_NEWLINE); +	vty_out(vty, "%s %s (%s).%s", FRR_FULL_NAME, FRR_VERSION, +		host.name ? host.name : "", VTY_NEWLINE); +	vty_out(vty, "%s%s%s", FRR_COPYRIGHT, GIT_INFO, VTY_NEWLINE); +	vty_out(vty, "configured with:%s    %s%s", VTY_NEWLINE, FRR_CONFIG_ARGS, +		VTY_NEWLINE); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* "Set" version ... ignore version tags */ @@ -1542,12 +1477,13 @@ DEFUN (frr_version_defaults,         "set of configuration defaults used\n"         "version string\n")  { -  if (vty->type == VTY_TERM || vty->type == VTY_SHELL) -    /* only print this when the user tries to do run it */ -    vty_out (vty, "%% NOTE: This command currently does nothing.%s" -             "%% It is written to the configuration for future reference.%s", -             VTY_NEWLINE, VTY_NEWLINE); -  return CMD_SUCCESS; +	if (vty->type == VTY_TERM || vty->type == VTY_SHELL) +		/* only print this when the user tries to do run it */ +		vty_out(vty, +			"%% NOTE: This command currently does nothing.%s" +			"%% It is written to the configuration for future reference.%s", +			VTY_NEWLINE, VTY_NEWLINE); +	return CMD_SUCCESS;  }  /* Help display function for all node. */ @@ -1556,8 +1492,8 @@ DEFUN (config_help,         "help",         "Description of the interactive help system\n")  { -  vty_out (vty, -           "Quagga VTY provides advanced help feature.  When you need help,%s\ +	vty_out(vty, +		"Quagga VTY provides advanced help feature.  When you need help,%s\  anytime at the command line please press '?'.%s\  %s\  If nothing matches, the help list will be empty and you must backup%s\ @@ -1568,79 +1504,74 @@ command argument (e.g. 'show ?') and describes each possible%s\  argument.%s\  2. Partial help is provided when an abbreviated argument is entered%s\     and you want to know what arguments match the input%s\ -   (e.g. 'show me?'.)%s%s", VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, -           VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, -           VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE); -  return CMD_SUCCESS; -} - -static void -permute (struct graph_node *start, struct vty *vty) -{ -  static struct list *position = NULL; -  if (!position) position = list_new (); - -  struct cmd_token *stok = start->data; -  struct graph_node *gnn; -  struct listnode *ln; - -  // recursive dfs -  listnode_add (position, start); -  for (unsigned int i = 0; i < vector_active (start->to); i++) -  { -    struct graph_node *gn = vector_slot (start->to, i); -    struct cmd_token *tok = gn->data; -    if (tok->attr == CMD_ATTR_HIDDEN || -        tok->attr == CMD_ATTR_DEPRECATED) -      continue; -    else if (tok->type == END_TKN || gn == start) -    { -      vty_out (vty, " "); -      for (ALL_LIST_ELEMENTS_RO (position,ln,gnn)) -      { -        struct cmd_token *tt = gnn->data; -        if (tt->type < SPECIAL_TKN) -          vty_out (vty, " %s", tt->text); -      } -      if (gn == start) -        vty_out (vty, "..."); -      vty_out (vty, VTY_NEWLINE); -    } -    else -    { -      bool skip = false; -      if (stok->type == FORK_TKN && tok->type != FORK_TKN) -        for (ALL_LIST_ELEMENTS_RO (position, ln, gnn)) -           if (gnn == gn) -           { -             skip = true; -             break; -           } -      if (!skip) -        permute (gn, vty); -    } -  } -  list_delete_node (position, listtail(position)); -} - -int -cmd_list_cmds (struct vty *vty, int do_permute) -{ -  struct cmd_node *node = vector_slot (cmdvec, vty->node); - -  if (do_permute) -    permute (vector_slot (node->cmdgraph->nodes, 0), vty); -  else -  { -    /* loop over all commands at this node */ -    struct cmd_element *element = NULL; -    for (unsigned int i = 0; i < vector_active(node->cmd_vector); i++) -        if ((element = vector_slot (node->cmd_vector, i)) && -             element->attr != CMD_ATTR_DEPRECATED && -             element->attr != CMD_ATTR_HIDDEN) -          vty_out (vty, "    %s%s", element->string, VTY_NEWLINE); -  } -  return CMD_SUCCESS; +   (e.g. 'show me?'.)%s%s", +		VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, +		VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE, +		VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE); +	return CMD_SUCCESS; +} + +static void permute(struct graph_node *start, struct vty *vty) +{ +	static struct list *position = NULL; +	if (!position) +		position = list_new(); + +	struct cmd_token *stok = start->data; +	struct graph_node *gnn; +	struct listnode *ln; + +	// recursive dfs +	listnode_add(position, start); +	for (unsigned int i = 0; i < vector_active(start->to); i++) { +		struct graph_node *gn = vector_slot(start->to, i); +		struct cmd_token *tok = gn->data; +		if (tok->attr == CMD_ATTR_HIDDEN +		    || tok->attr == CMD_ATTR_DEPRECATED) +			continue; +		else if (tok->type == END_TKN || gn == start) { +			vty_out(vty, " "); +			for (ALL_LIST_ELEMENTS_RO(position, ln, gnn)) { +				struct cmd_token *tt = gnn->data; +				if (tt->type < SPECIAL_TKN) +					vty_out(vty, " %s", tt->text); +			} +			if (gn == start) +				vty_out(vty, "..."); +			vty_out(vty, VTY_NEWLINE); +		} else { +			bool skip = false; +			if (stok->type == FORK_TKN && tok->type != FORK_TKN) +				for (ALL_LIST_ELEMENTS_RO(position, ln, gnn)) +					if (gnn == gn) { +						skip = true; +						break; +					} +			if (!skip) +				permute(gn, vty); +		} +	} +	list_delete_node(position, listtail(position)); +} + +int cmd_list_cmds(struct vty *vty, int do_permute) +{ +	struct cmd_node *node = vector_slot(cmdvec, vty->node); + +	if (do_permute) +		permute(vector_slot(node->cmdgraph->nodes, 0), vty); +	else { +		/* loop over all commands at this node */ +		struct cmd_element *element = NULL; +		for (unsigned int i = 0; i < vector_active(node->cmd_vector); +		     i++) +			if ((element = vector_slot(node->cmd_vector, i)) +			    && element->attr != CMD_ATTR_DEPRECATED +			    && element->attr != CMD_ATTR_HIDDEN) +				vty_out(vty, "    %s%s", element->string, +					VTY_NEWLINE); +	} +	return CMD_SUCCESS;  }  /* Help display function for all node. */ @@ -1650,7 +1581,7 @@ DEFUN (config_list,         "Print command list\n"         "Print all possible command permutations\n")  { -  return cmd_list_cmds (vty, argc == 2); +	return cmd_list_cmds(vty, argc == 2);  }  DEFUN (show_commandtree, @@ -1660,38 +1591,34 @@ DEFUN (show_commandtree,         "Show command tree\n"         "Permutations that we are interested in\n")  { -  return cmd_list_cmds (vty, argc == 3); +	return cmd_list_cmds(vty, argc == 3);  } -static void -vty_write_config (struct vty *vty) +static void vty_write_config(struct vty *vty)  { -  size_t i; -  struct cmd_node *node; +	size_t i; +	struct cmd_node *node; -  if (vty->type == VTY_TERM) -    { -      vty_out (vty, "%sCurrent configuration:%s", VTY_NEWLINE, -               VTY_NEWLINE); -      vty_out (vty, "!%s", VTY_NEWLINE); -    } +	if (vty->type == VTY_TERM) { +		vty_out(vty, "%sCurrent configuration:%s", VTY_NEWLINE, +			VTY_NEWLINE); +		vty_out(vty, "!%s", VTY_NEWLINE); +	} -  vty_out (vty, "frr version %s%s", FRR_VER_SHORT, VTY_NEWLINE); -  vty_out (vty, "frr defaults %s%s", DFLT_NAME, VTY_NEWLINE); -  vty_out (vty, "!%s", VTY_NEWLINE); +	vty_out(vty, "frr version %s%s", FRR_VER_SHORT, VTY_NEWLINE); +	vty_out(vty, "frr defaults %s%s", DFLT_NAME, VTY_NEWLINE); +	vty_out(vty, "!%s", VTY_NEWLINE); -  for (i = 0; i < vector_active (cmdvec); i++) -    if ((node = vector_slot (cmdvec, i)) && node->func -        && (node->vtysh || vty->type != VTY_SHELL)) -      { -        if ((*node->func) (vty)) -          vty_out (vty, "!%s", VTY_NEWLINE); -      } +	for (i = 0; i < vector_active(cmdvec); i++) +		if ((node = vector_slot(cmdvec, i)) && node->func +		    && (node->vtysh || vty->type != VTY_SHELL)) { +			if ((*node->func)(vty)) +				vty_out(vty, "!%s", VTY_NEWLINE); +		} -  if (vty->type == VTY_TERM) -    { -      vty_out (vty, "end%s",VTY_NEWLINE); -    } +	if (vty->type == VTY_TERM) { +		vty_out(vty, "end%s", VTY_NEWLINE); +	}  }  /* Write current configuration into file. */ @@ -1704,127 +1631,119 @@ DEFUN (config_write,         "Write configuration currently in memory\n"         "Write configuration to terminal\n")  { -  int idx_type = 1; -  int fd, dirfd; -  char *config_file, *slash; -  char *config_file_tmp = NULL; -  char *config_file_sav = NULL; -  int ret = CMD_WARNING; -  struct vty *file_vty; -  struct stat conf_stat; - -  // if command was 'write terminal' or 'show running-config' -  if (argc == 2 && (!strcmp(argv[idx_type]->text, "terminal") || -                    !strcmp(argv[0]->text, "show"))) -    { -      vty_write_config (vty); -      return CMD_SUCCESS; -    } - -  if (host.noconfig) -    return CMD_SUCCESS; - -  /* Check and see if we are operating under vtysh configuration */ -  if (host.config == NULL) -    { -      vty_out (vty, "Can't save to configuration file, using vtysh.%s", -               VTY_NEWLINE); -      return CMD_WARNING; -    } - -  /* Get filename. */ -  config_file = host.config; +	int idx_type = 1; +	int fd, dirfd; +	char *config_file, *slash; +	char *config_file_tmp = NULL; +	char *config_file_sav = NULL; +	int ret = CMD_WARNING; +	struct vty *file_vty; +	struct stat conf_stat; + +	// if command was 'write terminal' or 'show running-config' +	if (argc == 2 && (!strcmp(argv[idx_type]->text, "terminal") +			  || !strcmp(argv[0]->text, "show"))) { +		vty_write_config(vty); +		return CMD_SUCCESS; +	} + +	if (host.noconfig) +		return CMD_SUCCESS; + +	/* Check and see if we are operating under vtysh configuration */ +	if (host.config == NULL) { +		vty_out(vty, "Can't save to configuration file, using vtysh.%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	/* Get filename. */ +	config_file = host.config;  #ifndef O_DIRECTORY  #define O_DIRECTORY 0  #endif -  slash = strrchr (config_file, '/'); -  if (slash) -    { -      char *config_dir = XSTRDUP (MTYPE_TMP, config_file); -      config_dir[slash - config_file] = '\0'; -      dirfd = open(config_dir, O_DIRECTORY | O_RDONLY); -      XFREE (MTYPE_TMP, config_dir); -    } -  else -    dirfd = open(".", O_DIRECTORY | O_RDONLY); -  /* if dirfd is invalid, directory sync fails, but we're still OK */ - -  config_file_sav = -    XMALLOC (MTYPE_TMP, strlen (config_file) + strlen (CONF_BACKUP_EXT) + 1); -  strcpy (config_file_sav, config_file); -  strcat (config_file_sav, CONF_BACKUP_EXT); - - -  config_file_tmp = XMALLOC (MTYPE_TMP, strlen (config_file) + 8); -  sprintf (config_file_tmp, "%s.XXXXXX", config_file); - -  /* Open file to configuration write. */ -  fd = mkstemp (config_file_tmp); -  if (fd < 0) -    { -      vty_out (vty, "Can't open configuration file %s.%s", config_file_tmp, -               VTY_NEWLINE); -      goto finished; -    } -  if (fchmod (fd, CONFIGFILE_MASK) != 0) -    { -      vty_out (vty, "Can't chmod configuration file %s: %s (%d).%s", -        config_file_tmp, safe_strerror(errno), errno, VTY_NEWLINE); -      goto finished; -    } - -  /* Make vty for configuration file. */ -  file_vty = vty_new (); -  file_vty->wfd = fd; -  file_vty->type = VTY_FILE; - -  /* Config file header print. */ -  vty_out (file_vty, "!\n! Zebra configuration saved from vty\n!   "); -  vty_time_print (file_vty, 1); -  vty_out (file_vty, "!\n"); -  vty_write_config (file_vty); -  vty_close (file_vty); - -  if (stat(config_file, &conf_stat) >= 0) -    { -      if (unlink (config_file_sav) != 0) -        if (errno != ENOENT) -          { -            vty_out (vty, "Can't unlink backup configuration file %s.%s", config_file_sav, -                     VTY_NEWLINE); -            goto finished; -          } -      if (link (config_file, config_file_sav) != 0) -        { -          vty_out (vty, "Can't backup old configuration file %s.%s", config_file_sav, -                   VTY_NEWLINE); -          goto finished; -        } -      if (dirfd >= 0) -        fsync (dirfd); -    } -  if (rename (config_file_tmp, config_file) != 0) -    { -      vty_out (vty, "Can't save configuration file %s.%s", config_file, -               VTY_NEWLINE); -      goto finished; -    } -  if (dirfd >= 0) -    fsync (dirfd); - -  vty_out (vty, "Configuration saved to %s%s", config_file, -           VTY_NEWLINE); -  ret = CMD_SUCCESS; +	slash = strrchr(config_file, '/'); +	if (slash) { +		char *config_dir = XSTRDUP(MTYPE_TMP, config_file); +		config_dir[slash - config_file] = '\0'; +		dirfd = open(config_dir, O_DIRECTORY | O_RDONLY); +		XFREE(MTYPE_TMP, config_dir); +	} else +		dirfd = open(".", O_DIRECTORY | O_RDONLY); +	/* if dirfd is invalid, directory sync fails, but we're still OK */ + +	config_file_sav = XMALLOC( +		MTYPE_TMP, strlen(config_file) + strlen(CONF_BACKUP_EXT) + 1); +	strcpy(config_file_sav, config_file); +	strcat(config_file_sav, CONF_BACKUP_EXT); + + +	config_file_tmp = XMALLOC(MTYPE_TMP, strlen(config_file) + 8); +	sprintf(config_file_tmp, "%s.XXXXXX", config_file); + +	/* Open file to configuration write. */ +	fd = mkstemp(config_file_tmp); +	if (fd < 0) { +		vty_out(vty, "Can't open configuration file %s.%s", +			config_file_tmp, VTY_NEWLINE); +		goto finished; +	} +	if (fchmod(fd, CONFIGFILE_MASK) != 0) { +		vty_out(vty, "Can't chmod configuration file %s: %s (%d).%s", +			config_file_tmp, safe_strerror(errno), errno, +			VTY_NEWLINE); +		goto finished; +	} + +	/* Make vty for configuration file. */ +	file_vty = vty_new(); +	file_vty->wfd = fd; +	file_vty->type = VTY_FILE; + +	/* Config file header print. */ +	vty_out(file_vty, "!\n! Zebra configuration saved from vty\n!   "); +	vty_time_print(file_vty, 1); +	vty_out(file_vty, "!\n"); +	vty_write_config(file_vty); +	vty_close(file_vty); + +	if (stat(config_file, &conf_stat) >= 0) { +		if (unlink(config_file_sav) != 0) +			if (errno != ENOENT) { +				vty_out(vty, +					"Can't unlink backup configuration file %s.%s", +					config_file_sav, VTY_NEWLINE); +				goto finished; +			} +		if (link(config_file, config_file_sav) != 0) { +			vty_out(vty, +				"Can't backup old configuration file %s.%s", +				config_file_sav, VTY_NEWLINE); +			goto finished; +		} +		if (dirfd >= 0) +			fsync(dirfd); +	} +	if (rename(config_file_tmp, config_file) != 0) { +		vty_out(vty, "Can't save configuration file %s.%s", config_file, +			VTY_NEWLINE); +		goto finished; +	} +	if (dirfd >= 0) +		fsync(dirfd); + +	vty_out(vty, "Configuration saved to %s%s", config_file, VTY_NEWLINE); +	ret = CMD_SUCCESS;  finished: -  if (ret != CMD_SUCCESS) -    unlink (config_file_tmp); -  if (dirfd >= 0) -    close (dirfd); -  XFREE (MTYPE_TMP, config_file_tmp); -  XFREE (MTYPE_TMP, config_file_sav); -  return ret; +	if (ret != CMD_SUCCESS) +		unlink(config_file_tmp); +	if (dirfd >= 0) +		close(dirfd); +	XFREE(MTYPE_TMP, config_file_tmp); +	XFREE(MTYPE_TMP, config_file_sav); +	return ret;  }  /* ALIAS_FIXME for 'write <terminal|memory>' */ @@ -1834,7 +1753,7 @@ DEFUN (show_running_config,         SHOW_STR         "running configuration (same as write terminal/memory)\n")  { -  return config_write (self, vty, argc, argv); +	return config_write(self, vty, argc, argv);  }  /* ALIAS_FIXME for 'write file' */ @@ -1845,9 +1764,9 @@ DEFUN (copy_runningconf_startupconf,         "Copy running config to... \n"         "Copy running config to startup config (same as write file)\n")  { -  if (!host.noconfig) -    vty_write_config (vty); -  return CMD_SUCCESS; +	if (!host.noconfig) +		vty_write_config(vty); +	return CMD_SUCCESS;  }  /** -- **/ @@ -1858,44 +1777,41 @@ DEFUN (show_startup_config,         SHOW_STR         "Contents of startup configuration\n")  { -  char buf[BUFSIZ]; -  FILE *confp; +	char buf[BUFSIZ]; +	FILE *confp; -  if (host.noconfig) -    return CMD_SUCCESS; -  if (host.config == NULL) -    return CMD_WARNING; +	if (host.noconfig) +		return CMD_SUCCESS; +	if (host.config == NULL) +		return CMD_WARNING; -  confp = fopen (host.config, "r"); -  if (confp == NULL) -    { -      vty_out (vty, "Can't open configuration file [%s] due to '%s'%s", -               host.config, safe_strerror(errno), VTY_NEWLINE); -      return CMD_WARNING; -    } +	confp = fopen(host.config, "r"); +	if (confp == NULL) { +		vty_out(vty, "Can't open configuration file [%s] due to '%s'%s", +			host.config, safe_strerror(errno), VTY_NEWLINE); +		return CMD_WARNING; +	} -  while (fgets (buf, BUFSIZ, confp)) -    { -      char *cp = buf; +	while (fgets(buf, BUFSIZ, confp)) { +		char *cp = buf; -      while (*cp != '\r' && *cp != '\n' && *cp != '\0') -        cp++; -      *cp = '\0'; +		while (*cp != '\r' && *cp != '\n' && *cp != '\0') +			cp++; +		*cp = '\0'; -      vty_out (vty, "%s%s", buf, VTY_NEWLINE); -    } +		vty_out(vty, "%s%s", buf, VTY_NEWLINE); +	} -  fclose (confp); +	fclose(confp); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  } -int -cmd_hostname_set (const char *hostname) +int cmd_hostname_set(const char *hostname)  { -  XFREE (MTYPE_HOST, host.name); -  host.name = hostname ? XSTRDUP (MTYPE_HOST, hostname) : NULL; -  return CMD_SUCCESS; +	XFREE(MTYPE_HOST, host.name); +	host.name = hostname ? XSTRDUP(MTYPE_HOST, hostname) : NULL; +	return CMD_SUCCESS;  }  /* Hostname configuration */ @@ -1905,15 +1821,15 @@ DEFUN (config_hostname,         "Set system's network name\n"         "This system's network name\n")  { -  struct cmd_token *word = argv[1]; +	struct cmd_token *word = argv[1]; -  if (!isalpha((int) word->arg[0])) -    { -      vty_out (vty, "Please specify string starting with alphabet%s", VTY_NEWLINE); -      return CMD_WARNING; -    } +	if (!isalpha((int)word->arg[0])) { +		vty_out(vty, "Please specify string starting with alphabet%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  return cmd_hostname_set (word->arg); +	return cmd_hostname_set(word->arg);  }  DEFUN (config_no_hostname, @@ -1923,7 +1839,7 @@ DEFUN (config_no_hostname,         "Reset system's network name\n"         "Host name of this router\n")  { -  return cmd_hostname_set (NULL); +	return cmd_hostname_set(NULL);  }  /* VTY interface password set. */ @@ -1934,40 +1850,40 @@ DEFUN (config_password,         "Specifies a HIDDEN password will follow\n"         "The password string\n")  { -  int idx_8 = 1; -  int idx_word = 2; -  if (argc == 3) // '8' was specified -  { -    if (host.password) -      XFREE (MTYPE_HOST, host.password); -    host.password = NULL; -    if (host.password_encrypt) -      XFREE (MTYPE_HOST, host.password_encrypt); -    host.password_encrypt = XSTRDUP (MTYPE_HOST, argv[idx_word]->arg); -    return CMD_SUCCESS; -  } - -  if (!isalnum (argv[idx_8]->arg[0])) -    { -      vty_out (vty, -               "Please specify string starting with alphanumeric%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  if (host.password) -    XFREE (MTYPE_HOST, host.password); -  host.password = NULL; - -  if (host.encrypt) -    { -      if (host.password_encrypt) -        XFREE (MTYPE_HOST, host.password_encrypt); -      host.password_encrypt = XSTRDUP (MTYPE_HOST, zencrypt (argv[idx_8]->arg)); -    } -  else -    host.password = XSTRDUP (MTYPE_HOST, argv[idx_8]->arg); - -  return CMD_SUCCESS; +	int idx_8 = 1; +	int idx_word = 2; +	if (argc == 3) // '8' was specified +	{ +		if (host.password) +			XFREE(MTYPE_HOST, host.password); +		host.password = NULL; +		if (host.password_encrypt) +			XFREE(MTYPE_HOST, host.password_encrypt); +		host.password_encrypt = +			XSTRDUP(MTYPE_HOST, argv[idx_word]->arg); +		return CMD_SUCCESS; +	} + +	if (!isalnum(argv[idx_8]->arg[0])) { +		vty_out(vty, +			"Please specify string starting with alphanumeric%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	if (host.password) +		XFREE(MTYPE_HOST, host.password); +	host.password = NULL; + +	if (host.encrypt) { +		if (host.password_encrypt) +			XFREE(MTYPE_HOST, host.password_encrypt); +		host.password_encrypt = +			XSTRDUP(MTYPE_HOST, zencrypt(argv[idx_8]->arg)); +	} else +		host.password = XSTRDUP(MTYPE_HOST, argv[idx_8]->arg); + +	return CMD_SUCCESS;  }  /* VTY enable password set. */ @@ -1979,53 +1895,49 @@ DEFUN (config_enable_password,         "Specifies a HIDDEN password will follow\n"         "The HIDDEN 'enable' password string\n")  { -  int idx_8 = 2; -  int idx_word = 3; - -  /* Crypt type is specified. */ -  if (argc == 4) -    { -      if (argv[idx_8]->arg[0] == '8') -        { -          if (host.enable) -            XFREE (MTYPE_HOST, host.enable); -          host.enable = NULL; - -          if (host.enable_encrypt) -            XFREE (MTYPE_HOST, host.enable_encrypt); -          host.enable_encrypt = XSTRDUP (MTYPE_HOST, argv[idx_word]->arg); - -          return CMD_SUCCESS; -        } -      else -        { -          vty_out (vty, "Unknown encryption type.%s", VTY_NEWLINE); -          return CMD_WARNING; -        } -    } - -  if (!isalnum (argv[idx_8]->arg[0])) -    { -      vty_out (vty, -               "Please specify string starting with alphanumeric%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  if (host.enable) -    XFREE (MTYPE_HOST, host.enable); -  host.enable = NULL; - -  /* Plain password input. */ -  if (host.encrypt) -    { -      if (host.enable_encrypt) -        XFREE (MTYPE_HOST, host.enable_encrypt); -      host.enable_encrypt = XSTRDUP (MTYPE_HOST, zencrypt (argv[idx_8]->arg)); -    } -  else -    host.enable = XSTRDUP (MTYPE_HOST, argv[idx_8]->arg); - -  return CMD_SUCCESS; +	int idx_8 = 2; +	int idx_word = 3; + +	/* Crypt type is specified. */ +	if (argc == 4) { +		if (argv[idx_8]->arg[0] == '8') { +			if (host.enable) +				XFREE(MTYPE_HOST, host.enable); +			host.enable = NULL; + +			if (host.enable_encrypt) +				XFREE(MTYPE_HOST, host.enable_encrypt); +			host.enable_encrypt = +				XSTRDUP(MTYPE_HOST, argv[idx_word]->arg); + +			return CMD_SUCCESS; +		} else { +			vty_out(vty, "Unknown encryption type.%s", VTY_NEWLINE); +			return CMD_WARNING; +		} +	} + +	if (!isalnum(argv[idx_8]->arg[0])) { +		vty_out(vty, +			"Please specify string starting with alphanumeric%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	if (host.enable) +		XFREE(MTYPE_HOST, host.enable); +	host.enable = NULL; + +	/* Plain password input. */ +	if (host.encrypt) { +		if (host.enable_encrypt) +			XFREE(MTYPE_HOST, host.enable_encrypt); +		host.enable_encrypt = +			XSTRDUP(MTYPE_HOST, zencrypt(argv[idx_8]->arg)); +	} else +		host.enable = XSTRDUP(MTYPE_HOST, argv[idx_8]->arg); + +	return CMD_SUCCESS;  }  /* VTY enable password delete. */ @@ -2036,15 +1948,15 @@ DEFUN (no_config_enable_password,         "Modify enable password parameters\n"         "Assign the privileged level password\n")  { -  if (host.enable) -    XFREE (MTYPE_HOST, host.enable); -  host.enable = NULL; +	if (host.enable) +		XFREE(MTYPE_HOST, host.enable); +	host.enable = NULL; -  if (host.enable_encrypt) -    XFREE (MTYPE_HOST, host.enable_encrypt); -  host.enable_encrypt = NULL; +	if (host.enable_encrypt) +		XFREE(MTYPE_HOST, host.enable_encrypt); +	host.enable_encrypt = NULL; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (service_password_encrypt, @@ -2053,25 +1965,25 @@ DEFUN (service_password_encrypt,         "Set up miscellaneous service\n"         "Enable encrypted passwords\n")  { -  if (host.encrypt) -    return CMD_SUCCESS; +	if (host.encrypt) +		return CMD_SUCCESS; -  host.encrypt = 1; +	host.encrypt = 1; -  if (host.password) -    { -      if (host.password_encrypt) -        XFREE (MTYPE_HOST, host.password_encrypt); -      host.password_encrypt = XSTRDUP (MTYPE_HOST, zencrypt (host.password)); -    } -  if (host.enable) -    { -      if (host.enable_encrypt) -        XFREE (MTYPE_HOST, host.enable_encrypt); -      host.enable_encrypt = XSTRDUP (MTYPE_HOST, zencrypt (host.enable)); -    } +	if (host.password) { +		if (host.password_encrypt) +			XFREE(MTYPE_HOST, host.password_encrypt); +		host.password_encrypt = +			XSTRDUP(MTYPE_HOST, zencrypt(host.password)); +	} +	if (host.enable) { +		if (host.enable_encrypt) +			XFREE(MTYPE_HOST, host.enable_encrypt); +		host.enable_encrypt = +			XSTRDUP(MTYPE_HOST, zencrypt(host.enable)); +	} -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_service_password_encrypt, @@ -2081,20 +1993,20 @@ DEFUN (no_service_password_encrypt,         "Set up miscellaneous service\n"         "Enable encrypted passwords\n")  { -  if (! host.encrypt) -    return CMD_SUCCESS; +	if (!host.encrypt) +		return CMD_SUCCESS; -  host.encrypt = 0; +	host.encrypt = 0; -  if (host.password_encrypt) -    XFREE (MTYPE_HOST, host.password_encrypt); -  host.password_encrypt = NULL; +	if (host.password_encrypt) +		XFREE(MTYPE_HOST, host.password_encrypt); +	host.password_encrypt = NULL; -  if (host.enable_encrypt) -    XFREE (MTYPE_HOST, host.enable_encrypt); -  host.enable_encrypt = NULL; +	if (host.enable_encrypt) +		XFREE(MTYPE_HOST, host.enable_encrypt); +	host.enable_encrypt = NULL; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (config_terminal_length, @@ -2104,19 +2016,18 @@ DEFUN (config_terminal_length,         "Set number of lines on a screen\n"         "Number of lines on screen (0 for no pausing)\n")  { -  int idx_number = 2; -  int lines; -  char *endptr = NULL; +	int idx_number = 2; +	int lines; +	char *endptr = NULL; -  lines = strtol (argv[idx_number]->arg, &endptr, 10); -  if (lines < 0 || lines > 512 || *endptr != '\0') -    { -      vty_out (vty, "length is malformed%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  vty->lines = lines; +	lines = strtol(argv[idx_number]->arg, &endptr, 10); +	if (lines < 0 || lines > 512 || *endptr != '\0') { +		vty_out(vty, "length is malformed%s", VTY_NEWLINE); +		return CMD_WARNING; +	} +	vty->lines = lines; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (config_terminal_no_length, @@ -2126,8 +2037,8 @@ DEFUN (config_terminal_no_length,         NO_STR         "Set number of lines on a screen\n")  { -  vty->lines = -1; -  return CMD_SUCCESS; +	vty->lines = -1; +	return CMD_SUCCESS;  }  DEFUN (service_terminal_length, @@ -2137,19 +2048,18 @@ DEFUN (service_terminal_length,         "System wide terminal length configuration\n"         "Number of lines of VTY (0 means no line control)\n")  { -  int idx_number = 2; -  int lines; -  char *endptr = NULL; +	int idx_number = 2; +	int lines; +	char *endptr = NULL; -  lines = strtol (argv[idx_number]->arg, &endptr, 10); -  if (lines < 0 || lines > 512 || *endptr != '\0') -    { -      vty_out (vty, "length is malformed%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  host.lines = lines; +	lines = strtol(argv[idx_number]->arg, &endptr, 10); +	if (lines < 0 || lines > 512 || *endptr != '\0') { +		vty_out(vty, "length is malformed%s", VTY_NEWLINE); +		return CMD_WARNING; +	} +	host.lines = lines; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_service_terminal_length, @@ -2160,8 +2070,8 @@ DEFUN (no_service_terminal_length,         "System wide terminal length configuration\n"         "Number of lines of VTY (0 means no line control)\n")  { -  host.lines = -1; -  return CMD_SUCCESS; +	host.lines = -1; +	return CMD_SUCCESS;  }  DEFUN_HIDDEN (do_echo, @@ -2170,13 +2080,14 @@ DEFUN_HIDDEN (do_echo,                "Echo a message back to the vty\n"                "The message to echo\n")  { -  char *message; +	char *message; -  vty_out (vty, "%s%s", ((message = argv_concat (argv, argc, 1)) ? message : ""), -           VTY_NEWLINE); -  if (message) -    XFREE(MTYPE_TMP, message); -  return CMD_SUCCESS; +	vty_out(vty, "%s%s", +		((message = argv_concat(argv, argc, 1)) ? message : ""), +		VTY_NEWLINE); +	if (message) +		XFREE(MTYPE_TMP, message); +	return CMD_SUCCESS;  }  DEFUN (config_logmsg, @@ -2186,19 +2097,20 @@ DEFUN (config_logmsg,         LOG_LEVEL_DESC         "The message to send\n")  { -  int idx_log_level = 1; -  int idx_message = 2; -  int level; -  char *message; +	int idx_log_level = 1; +	int idx_message = 2; +	int level; +	char *message; -  if ((level = level_match(argv[idx_log_level]->arg)) == ZLOG_DISABLED) -    return CMD_ERR_NO_MATCH; +	if ((level = level_match(argv[idx_log_level]->arg)) == ZLOG_DISABLED) +		return CMD_ERR_NO_MATCH; -  zlog(level, "%s", ((message = argv_concat(argv, argc, idx_message)) ? message : "")); -  if (message) -    XFREE(MTYPE_TMP, message); +	zlog(level, "%s", +	     ((message = argv_concat(argv, argc, idx_message)) ? message : "")); +	if (message) +		XFREE(MTYPE_TMP, message); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (show_logging, @@ -2207,51 +2119,49 @@ DEFUN (show_logging,         SHOW_STR         "Show current logging configuration\n")  { -  struct zlog *zl = zlog_default; - -  vty_out (vty, "Syslog logging: "); -  if (zl->maxlvl[ZLOG_DEST_SYSLOG] == ZLOG_DISABLED) -    vty_out (vty, "disabled"); -  else -    vty_out (vty, "level %s, facility %s, ident %s", -             zlog_priority[zl->maxlvl[ZLOG_DEST_SYSLOG]], -             facility_name(zl->facility), zl->ident); -  vty_out (vty, "%s", VTY_NEWLINE); - -  vty_out (vty, "Stdout logging: "); -  if (zl->maxlvl[ZLOG_DEST_STDOUT] == ZLOG_DISABLED) -    vty_out (vty, "disabled"); -  else -    vty_out (vty, "level %s", -             zlog_priority[zl->maxlvl[ZLOG_DEST_STDOUT]]); -  vty_out (vty, "%s", VTY_NEWLINE); - -  vty_out (vty, "Monitor logging: "); -  if (zl->maxlvl[ZLOG_DEST_MONITOR] == ZLOG_DISABLED) -    vty_out (vty, "disabled"); -  else -    vty_out (vty, "level %s", -             zlog_priority[zl->maxlvl[ZLOG_DEST_MONITOR]]); -  vty_out (vty, "%s", VTY_NEWLINE); - -  vty_out (vty, "File logging: "); -  if ((zl->maxlvl[ZLOG_DEST_FILE] == ZLOG_DISABLED) || -      !zl->fp) -    vty_out (vty, "disabled"); -  else -    vty_out (vty, "level %s, filename %s", -             zlog_priority[zl->maxlvl[ZLOG_DEST_FILE]], -             zl->filename); -  vty_out (vty, "%s", VTY_NEWLINE); - -  vty_out (vty, "Protocol name: %s%s", -           zl->protoname, VTY_NEWLINE); -  vty_out (vty, "Record priority: %s%s", -           (zl->record_priority ? "enabled" : "disabled"), VTY_NEWLINE); -  vty_out (vty, "Timestamp precision: %d%s", -           zl->timestamp_precision, VTY_NEWLINE); - -  return CMD_SUCCESS; +	struct zlog *zl = zlog_default; + +	vty_out(vty, "Syslog logging: "); +	if (zl->maxlvl[ZLOG_DEST_SYSLOG] == ZLOG_DISABLED) +		vty_out(vty, "disabled"); +	else +		vty_out(vty, "level %s, facility %s, ident %s", +			zlog_priority[zl->maxlvl[ZLOG_DEST_SYSLOG]], +			facility_name(zl->facility), zl->ident); +	vty_out(vty, "%s", VTY_NEWLINE); + +	vty_out(vty, "Stdout logging: "); +	if (zl->maxlvl[ZLOG_DEST_STDOUT] == ZLOG_DISABLED) +		vty_out(vty, "disabled"); +	else +		vty_out(vty, "level %s", +			zlog_priority[zl->maxlvl[ZLOG_DEST_STDOUT]]); +	vty_out(vty, "%s", VTY_NEWLINE); + +	vty_out(vty, "Monitor logging: "); +	if (zl->maxlvl[ZLOG_DEST_MONITOR] == ZLOG_DISABLED) +		vty_out(vty, "disabled"); +	else +		vty_out(vty, "level %s", +			zlog_priority[zl->maxlvl[ZLOG_DEST_MONITOR]]); +	vty_out(vty, "%s", VTY_NEWLINE); + +	vty_out(vty, "File logging: "); +	if ((zl->maxlvl[ZLOG_DEST_FILE] == ZLOG_DISABLED) || !zl->fp) +		vty_out(vty, "disabled"); +	else +		vty_out(vty, "level %s, filename %s", +			zlog_priority[zl->maxlvl[ZLOG_DEST_FILE]], +			zl->filename); +	vty_out(vty, "%s", VTY_NEWLINE); + +	vty_out(vty, "Protocol name: %s%s", zl->protoname, VTY_NEWLINE); +	vty_out(vty, "Record priority: %s%s", +		(zl->record_priority ? "enabled" : "disabled"), VTY_NEWLINE); +	vty_out(vty, "Timestamp precision: %d%s", zl->timestamp_precision, +		VTY_NEWLINE); + +	return CMD_SUCCESS;  }  DEFUN (config_log_stdout, @@ -2261,19 +2171,18 @@ DEFUN (config_log_stdout,         "Set stdout logging level\n"         LOG_LEVEL_DESC)  { -  int idx_log_level = 2; +	int idx_log_level = 2; -  if (argc == idx_log_level) -  { -    zlog_set_level (ZLOG_DEST_STDOUT, zlog_default->default_lvl); -    return CMD_SUCCESS; -  } -  int level; +	if (argc == idx_log_level) { +		zlog_set_level(ZLOG_DEST_STDOUT, zlog_default->default_lvl); +		return CMD_SUCCESS; +	} +	int level; -  if ((level = level_match(argv[idx_log_level]->arg)) == ZLOG_DISABLED) -    return CMD_ERR_NO_MATCH; -  zlog_set_level (ZLOG_DEST_STDOUT, level); -  return CMD_SUCCESS; +	if ((level = level_match(argv[idx_log_level]->arg)) == ZLOG_DISABLED) +		return CMD_ERR_NO_MATCH; +	zlog_set_level(ZLOG_DEST_STDOUT, level); +	return CMD_SUCCESS;  }  DEFUN (no_config_log_stdout, @@ -2284,8 +2193,8 @@ DEFUN (no_config_log_stdout,         "Cancel logging to stdout\n"         LOG_LEVEL_DESC)  { -  zlog_set_level (ZLOG_DEST_STDOUT, ZLOG_DISABLED); -  return CMD_SUCCESS; +	zlog_set_level(ZLOG_DEST_STDOUT, ZLOG_DISABLED); +	return CMD_SUCCESS;  }  DEFUN (config_log_monitor, @@ -2295,19 +2204,18 @@ DEFUN (config_log_monitor,         "Set terminal line (monitor) logging level\n"         LOG_LEVEL_DESC)  { -  int idx_log_level = 2; +	int idx_log_level = 2; -  if (argc == idx_log_level) -  { -    zlog_set_level (ZLOG_DEST_MONITOR, zlog_default->default_lvl); -    return CMD_SUCCESS; -  } -  int level; +	if (argc == idx_log_level) { +		zlog_set_level(ZLOG_DEST_MONITOR, zlog_default->default_lvl); +		return CMD_SUCCESS; +	} +	int level; -  if ((level = level_match(argv[idx_log_level]->arg)) == ZLOG_DISABLED) -    return CMD_ERR_NO_MATCH; -  zlog_set_level (ZLOG_DEST_MONITOR, level); -  return CMD_SUCCESS; +	if ((level = level_match(argv[idx_log_level]->arg)) == ZLOG_DISABLED) +		return CMD_ERR_NO_MATCH; +	zlog_set_level(ZLOG_DEST_MONITOR, level); +	return CMD_SUCCESS;  }  DEFUN (no_config_log_monitor, @@ -2318,62 +2226,56 @@ DEFUN (no_config_log_monitor,         "Disable terminal line (monitor) logging\n"         LOG_LEVEL_DESC)  { -  zlog_set_level (ZLOG_DEST_MONITOR, ZLOG_DISABLED); -  return CMD_SUCCESS; +	zlog_set_level(ZLOG_DEST_MONITOR, ZLOG_DISABLED); +	return CMD_SUCCESS;  } -static int -set_log_file(struct vty *vty, const char *fname, int loglevel) +static int set_log_file(struct vty *vty, const char *fname, int loglevel)  { -  int ret; -  char *p = NULL; -  const char *fullpath; +	int ret; +	char *p = NULL; +	const char *fullpath; -  /* Path detection. */ -  if (! IS_DIRECTORY_SEP (*fname)) -    { -      char cwd[MAXPATHLEN+1]; -      cwd[MAXPATHLEN] = '\0'; +	/* Path detection. */ +	if (!IS_DIRECTORY_SEP(*fname)) { +		char cwd[MAXPATHLEN + 1]; +		cwd[MAXPATHLEN] = '\0'; -      if (getcwd (cwd, MAXPATHLEN) == NULL) -        { -          zlog_err ("config_log_file: Unable to alloc mem!"); -          return CMD_WARNING; -        } +		if (getcwd(cwd, MAXPATHLEN) == NULL) { +			zlog_err("config_log_file: Unable to alloc mem!"); +			return CMD_WARNING; +		} -      if ( (p = XMALLOC (MTYPE_TMP, strlen (cwd) + strlen (fname) + 2)) -          == NULL) -        { -          zlog_err ("config_log_file: Unable to alloc mem!"); -          return CMD_WARNING; -        } -      sprintf (p, "%s/%s", cwd, fname); -      fullpath = p; -    } -  else -    fullpath = fname; +		if ((p = XMALLOC(MTYPE_TMP, strlen(cwd) + strlen(fname) + 2)) +		    == NULL) { +			zlog_err("config_log_file: Unable to alloc mem!"); +			return CMD_WARNING; +		} +		sprintf(p, "%s/%s", cwd, fname); +		fullpath = p; +	} else +		fullpath = fname; -  ret = zlog_set_file (fullpath, loglevel); +	ret = zlog_set_file(fullpath, loglevel); -  if (p) -    XFREE (MTYPE_TMP, p); +	if (p) +		XFREE(MTYPE_TMP, p); -  if (!ret) -    { -      vty_out (vty, "can't open logfile %s\n", fname); -      return CMD_WARNING; -    } +	if (!ret) { +		vty_out(vty, "can't open logfile %s\n", fname); +		return CMD_WARNING; +	} -  if (host.logfile) -    XFREE (MTYPE_HOST, host.logfile); +	if (host.logfile) +		XFREE(MTYPE_HOST, host.logfile); -  host.logfile = XSTRDUP (MTYPE_HOST, fname); +	host.logfile = XSTRDUP(MTYPE_HOST, fname);  #if defined(HAVE_CUMULUS) -  if (zlog_default->maxlvl[ZLOG_DEST_SYSLOG] != ZLOG_DISABLED) -    zlog_default->maxlvl[ZLOG_DEST_SYSLOG] = ZLOG_DISABLED; +	if (zlog_default->maxlvl[ZLOG_DEST_SYSLOG] != ZLOG_DISABLED) +		zlog_default->maxlvl[ZLOG_DEST_SYSLOG] = ZLOG_DISABLED;  #endif -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (config_log_file, @@ -2384,17 +2286,17 @@ DEFUN (config_log_file,         "Logging filename\n"         LOG_LEVEL_DESC)  { -  int idx_filename = 2; -  int idx_log_levels = 3; -  if (argc == 4) -  { -    int level; -    if ((level = level_match(argv[idx_log_levels]->arg)) == ZLOG_DISABLED) -      return CMD_ERR_NO_MATCH; -    return set_log_file(vty, argv[idx_filename]->arg, level); -  } -  else -    return set_log_file(vty, argv[idx_filename]->arg, zlog_default->default_lvl); +	int idx_filename = 2; +	int idx_log_levels = 3; +	if (argc == 4) { +		int level; +		if ((level = level_match(argv[idx_log_levels]->arg)) +		    == ZLOG_DISABLED) +			return CMD_ERR_NO_MATCH; +		return set_log_file(vty, argv[idx_filename]->arg, level); +	} else +		return set_log_file(vty, argv[idx_filename]->arg, +				    zlog_default->default_lvl);  }  DEFUN (no_config_log_file, @@ -2407,14 +2309,14 @@ DEFUN (no_config_log_file,         "Logging file name\n"         "Logging level\n")  { -  zlog_reset_file (); +	zlog_reset_file(); -  if (host.logfile) -    XFREE (MTYPE_HOST, host.logfile); +	if (host.logfile) +		XFREE(MTYPE_HOST, host.logfile); -  host.logfile = NULL; +	host.logfile = NULL; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (config_log_syslog, @@ -2424,20 +2326,18 @@ DEFUN (config_log_syslog,         "Set syslog logging level\n"         LOG_LEVEL_DESC)  { -  int idx_log_levels = 2; -  if (argc == 3) -  { -    int level; -    if ((level = level_match (argv[idx_log_levels]->arg)) == ZLOG_DISABLED) -      return CMD_ERR_NO_MATCH; -    zlog_set_level (ZLOG_DEST_SYSLOG, level); -    return CMD_SUCCESS; -  } -  else -  { -    zlog_set_level (ZLOG_DEST_SYSLOG, zlog_default->default_lvl); -    return CMD_SUCCESS; -  } +	int idx_log_levels = 2; +	if (argc == 3) { +		int level; +		if ((level = level_match(argv[idx_log_levels]->arg)) +		    == ZLOG_DISABLED) +			return CMD_ERR_NO_MATCH; +		zlog_set_level(ZLOG_DEST_SYSLOG, level); +		return CMD_SUCCESS; +	} else { +		zlog_set_level(ZLOG_DEST_SYSLOG, zlog_default->default_lvl); +		return CMD_SUCCESS; +	}  }  DEFUN (no_config_log_syslog, @@ -2449,8 +2349,8 @@ DEFUN (no_config_log_syslog,         LOG_FACILITY_DESC         LOG_LEVEL_DESC)  { -  zlog_set_level (ZLOG_DEST_SYSLOG, ZLOG_DISABLED); -  return CMD_SUCCESS; +	zlog_set_level(ZLOG_DEST_SYSLOG, ZLOG_DISABLED); +	return CMD_SUCCESS;  }  DEFUN (config_log_facility, @@ -2460,11 +2360,11 @@ DEFUN (config_log_facility,         "Facility parameter for syslog messages\n"         LOG_FACILITY_DESC)  { -  int idx_target = 2; -  int facility = facility_match(argv[idx_target]->arg); +	int idx_target = 2; +	int facility = facility_match(argv[idx_target]->arg); -  zlog_default->facility = facility; -  return CMD_SUCCESS; +	zlog_default->facility = facility; +	return CMD_SUCCESS;  }  DEFUN (no_config_log_facility, @@ -2475,40 +2375,38 @@ DEFUN (no_config_log_facility,         "Reset syslog facility to default (daemon)\n"         LOG_FACILITY_DESC)  { -  zlog_default->facility = LOG_DAEMON; -  return CMD_SUCCESS; +	zlog_default->facility = LOG_DAEMON; +	return CMD_SUCCESS;  } -DEFUN_DEPRECATED (config_log_trap, -                  config_log_trap_cmd, -                  "log trap <emergencies|alerts|critical|errors|warnings|notifications|informational|debugging>", -                  "Logging control\n" -                  "(Deprecated) Set logging level and default for all destinations\n" -                  LOG_LEVEL_DESC) +DEFUN_DEPRECATED( +	config_log_trap, config_log_trap_cmd, +	"log trap <emergencies|alerts|critical|errors|warnings|notifications|informational|debugging>", +	"Logging control\n" +	"(Deprecated) Set logging level and default for all destinations\n" LOG_LEVEL_DESC)  { -  int new_level ; -  int i; +	int new_level; +	int i; -  if ((new_level = level_match(argv[2]->arg)) == ZLOG_DISABLED) -    return CMD_ERR_NO_MATCH; +	if ((new_level = level_match(argv[2]->arg)) == ZLOG_DISABLED) +		return CMD_ERR_NO_MATCH; -  zlog_default->default_lvl = new_level; -  for (i = 0; i < ZLOG_NUM_DESTS; i++) -    if (zlog_default->maxlvl[i] != ZLOG_DISABLED) -      zlog_default->maxlvl[i] = new_level; -  return CMD_SUCCESS; +	zlog_default->default_lvl = new_level; +	for (i = 0; i < ZLOG_NUM_DESTS; i++) +		if (zlog_default->maxlvl[i] != ZLOG_DISABLED) +			zlog_default->maxlvl[i] = new_level; +	return CMD_SUCCESS;  } -DEFUN_DEPRECATED (no_config_log_trap, -                  no_config_log_trap_cmd, -                  "no log trap [emergencies|alerts|critical|errors|warnings|notifications|informational|debugging]", -                  NO_STR -                  "Logging control\n" -                  "Permit all logging information\n" -                  LOG_LEVEL_DESC) +DEFUN_DEPRECATED( +	no_config_log_trap, no_config_log_trap_cmd, +	"no log trap [emergencies|alerts|critical|errors|warnings|notifications|informational|debugging]", +	NO_STR +	"Logging control\n" +	"Permit all logging information\n" LOG_LEVEL_DESC)  { -  zlog_default->default_lvl = LOG_DEBUG; -  return CMD_SUCCESS; +	zlog_default->default_lvl = LOG_DEBUG; +	return CMD_SUCCESS;  }  DEFUN (config_log_record_priority, @@ -2517,8 +2415,8 @@ DEFUN (config_log_record_priority,         "Logging control\n"         "Log the priority of the message within the message\n")  { -  zlog_default->record_priority = 1 ; -  return CMD_SUCCESS; +	zlog_default->record_priority = 1; +	return CMD_SUCCESS;  }  DEFUN (no_config_log_record_priority, @@ -2528,8 +2426,8 @@ DEFUN (no_config_log_record_priority,         "Logging control\n"         "Do not log the priority of the message within the message\n")  { -  zlog_default->record_priority = 0 ; -  return CMD_SUCCESS; +	zlog_default->record_priority = 0; +	return CMD_SUCCESS;  }  DEFUN (config_log_timestamp_precision, @@ -2540,10 +2438,11 @@ DEFUN (config_log_timestamp_precision,         "Set the timestamp precision\n"         "Number of subsecond digits\n")  { -  int idx_number = 3; -  VTY_GET_INTEGER_RANGE("Timestamp Precision", -                        zlog_default->timestamp_precision, argv[idx_number]->arg, 0, 6); -  return CMD_SUCCESS; +	int idx_number = 3; +	VTY_GET_INTEGER_RANGE("Timestamp Precision", +			      zlog_default->timestamp_precision, +			      argv[idx_number]->arg, 0, 6); +	return CMD_SUCCESS;  }  DEFUN (no_config_log_timestamp_precision, @@ -2554,32 +2453,29 @@ DEFUN (no_config_log_timestamp_precision,         "Timestamp configuration\n"         "Reset the timestamp precision to the default value of 0\n")  { -  zlog_default->timestamp_precision = 0 ; -  return CMD_SUCCESS; +	zlog_default->timestamp_precision = 0; +	return CMD_SUCCESS;  } -int -cmd_banner_motd_file (const char *file) +int cmd_banner_motd_file(const char *file)  { -  int success = CMD_SUCCESS; -  char p[PATH_MAX]; -  char *rpath; -  char *in; +	int success = CMD_SUCCESS; +	char p[PATH_MAX]; +	char *rpath; +	char *in; -  rpath = realpath (file, p); -  if (!rpath) -    return CMD_ERR_NO_FILE; -  in = strstr (rpath, SYSCONFDIR); -  if (in == rpath) -    { -      if (host.motdfile) -        XFREE (MTYPE_HOST, host.motdfile); -      host.motdfile = XSTRDUP (MTYPE_HOST, file); -    } -  else -    success = CMD_WARNING; +	rpath = realpath(file, p); +	if (!rpath) +		return CMD_ERR_NO_FILE; +	in = strstr(rpath, SYSCONFDIR); +	if (in == rpath) { +		if (host.motdfile) +			XFREE(MTYPE_HOST, host.motdfile); +		host.motdfile = XSTRDUP(MTYPE_HOST, file); +	} else +		success = CMD_WARNING; -  return success; +	return success;  }  DEFUN (banner_motd_file, @@ -2590,16 +2486,16 @@ DEFUN (banner_motd_file,         "Banner from a file\n"         "Filename\n")  { -  int idx_file = 3; -  const char *filename = argv[idx_file]->arg; -  int cmd = cmd_banner_motd_file (filename); +	int idx_file = 3; +	const char *filename = argv[idx_file]->arg; +	int cmd = cmd_banner_motd_file(filename); -  if (cmd == CMD_ERR_NO_FILE) -    vty_out (vty, "%s does not exist", filename); -  else if (cmd == CMD_WARNING) -    vty_out (vty, "%s must be in %s", filename, SYSCONFDIR); +	if (cmd == CMD_ERR_NO_FILE) +		vty_out(vty, "%s does not exist", filename); +	else if (cmd == CMD_WARNING) +		vty_out(vty, "%s must be in %s", filename, SYSCONFDIR); -  return cmd; +	return cmd;  }  DEFUN (banner_motd_default, @@ -2609,8 +2505,8 @@ DEFUN (banner_motd_default,         "Strings for motd\n"         "Default string\n")  { -  host.motd = default_motd; -  return CMD_SUCCESS; +	host.motd = default_motd; +	return CMD_SUCCESS;  }  DEFUN (no_banner_motd, @@ -2620,39 +2516,36 @@ DEFUN (no_banner_motd,         "Set banner string\n"         "Strings for motd\n")  { -  host.motd = NULL; -  if (host.motdfile) -    XFREE (MTYPE_HOST, host.motdfile); -  host.motdfile = NULL; -  return CMD_SUCCESS; +	host.motd = NULL; +	if (host.motdfile) +		XFREE(MTYPE_HOST, host.motdfile); +	host.motdfile = NULL; +	return CMD_SUCCESS;  }  /* Set config filename.  Called from vty.c */ -void -host_config_set (const char *filename) +void host_config_set(const char *filename)  { -  if (host.config) -    XFREE (MTYPE_HOST, host.config); -  host.config = XSTRDUP (MTYPE_HOST, filename); +	if (host.config) +		XFREE(MTYPE_HOST, host.config); +	host.config = XSTRDUP(MTYPE_HOST, filename);  } -const char * -host_config_get (void) +const char *host_config_get(void)  { -  return host.config; +	return host.config;  } -void -install_default (enum node_type node) +void install_default(enum node_type node)  { -  install_element (node, &config_exit_cmd); -  install_element (node, &config_quit_cmd); -  install_element (node, &config_end_cmd); -  install_element (node, &config_help_cmd); -  install_element (node, &config_list_cmd); +	install_element(node, &config_exit_cmd); +	install_element(node, &config_quit_cmd); +	install_element(node, &config_end_cmd); +	install_element(node, &config_help_cmd); +	install_element(node, &config_list_cmd); -  install_element (node, &config_write_cmd); -  install_element (node, &show_running_config_cmd); +	install_element(node, &config_write_cmd); +	install_element(node, &show_running_config_cmd);  }  /* Initialize command interface. Install basic nodes and commands. @@ -2660,192 +2553,188 @@ install_default (enum node_type node)   * terminal = 0 -- vtysh / no logging, no config control   * terminal = 1 -- normal daemon   * terminal = -1 -- watchfrr / no logging, but minimal config control */ -void -cmd_init (int terminal) -{ -  qobj_init (); - -  /* Allocate initial top vector of commands. */ -  cmdvec = vector_init (VECTOR_MIN_SIZE); - -  /* Default host value settings. */ -  host.name = NULL; -  host.password = NULL; -  host.enable = NULL; -  host.logfile = NULL; -  host.config = NULL; -  host.noconfig = (terminal < 0); -  host.lines = -1; -  host.motd = default_motd; -  host.motdfile = NULL; - -  /* Install top nodes. */ -  install_node (&view_node, NULL); -  install_node (&enable_node, NULL); -  install_node (&auth_node, NULL); -  install_node (&auth_enable_node, NULL); -  install_node (&config_node, config_write_host); - -  /* Each node's basic commands. */ -  install_element (VIEW_NODE, &show_version_cmd); -  if (terminal) -    { -      install_element (VIEW_NODE, &config_list_cmd); -      install_element (VIEW_NODE, &config_exit_cmd); -      install_element (VIEW_NODE, &config_quit_cmd); -      install_element (VIEW_NODE, &config_help_cmd); -      install_element (VIEW_NODE, &config_enable_cmd); -      install_element (VIEW_NODE, &config_terminal_length_cmd); -      install_element (VIEW_NODE, &config_terminal_no_length_cmd); -      install_element (VIEW_NODE, &show_logging_cmd); -      install_element (VIEW_NODE, &show_commandtree_cmd); -      install_element (VIEW_NODE, &echo_cmd); -    } - -  if (terminal) -    { -      install_element (ENABLE_NODE, &config_end_cmd); -      install_element (ENABLE_NODE, &config_disable_cmd); -      install_element (ENABLE_NODE, &config_terminal_cmd); -      install_element (ENABLE_NODE, ©_runningconf_startupconf_cmd); -      install_element (ENABLE_NODE, &config_write_cmd); -      install_element (ENABLE_NODE, &show_running_config_cmd); -    } -  install_element (ENABLE_NODE, &show_startup_config_cmd); - -  if (terminal) -    { -      install_element (ENABLE_NODE, &config_logmsg_cmd); -      install_default (CONFIG_NODE); - -      thread_cmd_init (); -      workqueue_cmd_init (); -    } - -  install_element (CONFIG_NODE, &hostname_cmd); -  install_element (CONFIG_NODE, &no_hostname_cmd); -  install_element (CONFIG_NODE, &frr_version_defaults_cmd); - -  if (terminal > 0) -    { -      install_element (CONFIG_NODE, &password_cmd); -      install_element (CONFIG_NODE, &enable_password_cmd); -      install_element (CONFIG_NODE, &no_enable_password_cmd); - -      install_element (CONFIG_NODE, &config_log_stdout_cmd); -      install_element (CONFIG_NODE, &no_config_log_stdout_cmd); -      install_element (CONFIG_NODE, &config_log_monitor_cmd); -      install_element (CONFIG_NODE, &no_config_log_monitor_cmd); -      install_element (CONFIG_NODE, &config_log_file_cmd); -      install_element (CONFIG_NODE, &no_config_log_file_cmd); -      install_element (CONFIG_NODE, &config_log_syslog_cmd); -      install_element (CONFIG_NODE, &no_config_log_syslog_cmd); -      install_element (CONFIG_NODE, &config_log_facility_cmd); -      install_element (CONFIG_NODE, &no_config_log_facility_cmd); -      install_element (CONFIG_NODE, &config_log_trap_cmd); -      install_element (CONFIG_NODE, &no_config_log_trap_cmd); -      install_element (CONFIG_NODE, &config_log_record_priority_cmd); -      install_element (CONFIG_NODE, &no_config_log_record_priority_cmd); -      install_element (CONFIG_NODE, &config_log_timestamp_precision_cmd); -      install_element (CONFIG_NODE, &no_config_log_timestamp_precision_cmd); -      install_element (CONFIG_NODE, &service_password_encrypt_cmd); -      install_element (CONFIG_NODE, &no_service_password_encrypt_cmd); -      install_element (CONFIG_NODE, &banner_motd_default_cmd); -      install_element (CONFIG_NODE, &banner_motd_file_cmd); -      install_element (CONFIG_NODE, &no_banner_motd_cmd); -      install_element (CONFIG_NODE, &service_terminal_length_cmd); -      install_element (CONFIG_NODE, &no_service_terminal_length_cmd); - -      vrf_install_commands (); -    } +void cmd_init(int terminal) +{ +	qobj_init(); + +	/* Allocate initial top vector of commands. */ +	cmdvec = vector_init(VECTOR_MIN_SIZE); + +	/* Default host value settings. */ +	host.name = NULL; +	host.password = NULL; +	host.enable = NULL; +	host.logfile = NULL; +	host.config = NULL; +	host.noconfig = (terminal < 0); +	host.lines = -1; +	host.motd = default_motd; +	host.motdfile = NULL; + +	/* Install top nodes. */ +	install_node(&view_node, NULL); +	install_node(&enable_node, NULL); +	install_node(&auth_node, NULL); +	install_node(&auth_enable_node, NULL); +	install_node(&config_node, config_write_host); + +	/* Each node's basic commands. */ +	install_element(VIEW_NODE, &show_version_cmd); +	if (terminal) { +		install_element(VIEW_NODE, &config_list_cmd); +		install_element(VIEW_NODE, &config_exit_cmd); +		install_element(VIEW_NODE, &config_quit_cmd); +		install_element(VIEW_NODE, &config_help_cmd); +		install_element(VIEW_NODE, &config_enable_cmd); +		install_element(VIEW_NODE, &config_terminal_length_cmd); +		install_element(VIEW_NODE, &config_terminal_no_length_cmd); +		install_element(VIEW_NODE, &show_logging_cmd); +		install_element(VIEW_NODE, &show_commandtree_cmd); +		install_element(VIEW_NODE, &echo_cmd); +	} + +	if (terminal) { +		install_element(ENABLE_NODE, &config_end_cmd); +		install_element(ENABLE_NODE, &config_disable_cmd); +		install_element(ENABLE_NODE, &config_terminal_cmd); +		install_element(ENABLE_NODE, ©_runningconf_startupconf_cmd); +		install_element(ENABLE_NODE, &config_write_cmd); +		install_element(ENABLE_NODE, &show_running_config_cmd); +	} +	install_element(ENABLE_NODE, &show_startup_config_cmd); + +	if (terminal) { +		install_element(ENABLE_NODE, &config_logmsg_cmd); +		install_default(CONFIG_NODE); + +		thread_cmd_init(); +		workqueue_cmd_init(); +	} + +	install_element(CONFIG_NODE, &hostname_cmd); +	install_element(CONFIG_NODE, &no_hostname_cmd); +	install_element(CONFIG_NODE, &frr_version_defaults_cmd); + +	if (terminal > 0) { +		install_element(CONFIG_NODE, &password_cmd); +		install_element(CONFIG_NODE, &enable_password_cmd); +		install_element(CONFIG_NODE, &no_enable_password_cmd); + +		install_element(CONFIG_NODE, &config_log_stdout_cmd); +		install_element(CONFIG_NODE, &no_config_log_stdout_cmd); +		install_element(CONFIG_NODE, &config_log_monitor_cmd); +		install_element(CONFIG_NODE, &no_config_log_monitor_cmd); +		install_element(CONFIG_NODE, &config_log_file_cmd); +		install_element(CONFIG_NODE, &no_config_log_file_cmd); +		install_element(CONFIG_NODE, &config_log_syslog_cmd); +		install_element(CONFIG_NODE, &no_config_log_syslog_cmd); +		install_element(CONFIG_NODE, &config_log_facility_cmd); +		install_element(CONFIG_NODE, &no_config_log_facility_cmd); +		install_element(CONFIG_NODE, &config_log_trap_cmd); +		install_element(CONFIG_NODE, &no_config_log_trap_cmd); +		install_element(CONFIG_NODE, &config_log_record_priority_cmd); +		install_element(CONFIG_NODE, +				&no_config_log_record_priority_cmd); +		install_element(CONFIG_NODE, +				&config_log_timestamp_precision_cmd); +		install_element(CONFIG_NODE, +				&no_config_log_timestamp_precision_cmd); +		install_element(CONFIG_NODE, &service_password_encrypt_cmd); +		install_element(CONFIG_NODE, &no_service_password_encrypt_cmd); +		install_element(CONFIG_NODE, &banner_motd_default_cmd); +		install_element(CONFIG_NODE, &banner_motd_file_cmd); +		install_element(CONFIG_NODE, &no_banner_motd_cmd); +		install_element(CONFIG_NODE, &service_terminal_length_cmd); +		install_element(CONFIG_NODE, &no_service_terminal_length_cmd); + +		vrf_install_commands(); +	}  #ifdef DEV_BUILD -  grammar_sandbox_init(); +	grammar_sandbox_init();  #endif  } -struct cmd_token * -new_cmd_token (enum cmd_token_type type, u_char attr, -               const char *text, const char *desc) -{ -  struct cmd_token *token = XCALLOC (MTYPE_CMD_TOKENS, sizeof (struct cmd_token)); -  token->type = type; -  token->attr = attr; -  token->text = text ? XSTRDUP (MTYPE_CMD_TEXT, text) : NULL; -  token->desc = desc ? XSTRDUP (MTYPE_CMD_DESC, desc) : NULL; -  token->refcnt = 1; -  token->arg  = NULL; -  token->allowrepeat = false; - -  return token; -} - -void -del_cmd_token (struct cmd_token *token) -{ -  if (!token) return; - -  if (token->text) -    XFREE (MTYPE_CMD_TEXT, token->text); -  if (token->desc) -    XFREE (MTYPE_CMD_DESC, token->desc); -  if (token->arg) -    XFREE (MTYPE_CMD_ARG, token->arg); - -  XFREE (MTYPE_CMD_TOKENS, token); -} - -struct cmd_token * -copy_cmd_token (struct cmd_token *token) -{ -  struct cmd_token *copy = new_cmd_token (token->type, token->attr, NULL, NULL); -  copy->max   = token->max; -  copy->min   = token->min; -  copy->text  = token->text ? XSTRDUP (MTYPE_CMD_TEXT, token->text) : NULL; -  copy->desc  = token->desc ? XSTRDUP (MTYPE_CMD_DESC, token->desc) : NULL; -  copy->arg   = token->arg  ? XSTRDUP (MTYPE_CMD_ARG, token->arg) : NULL; - -  return copy; -} - -void -cmd_terminate () -{ -  struct cmd_node *cmd_node; - -  if (cmdvec) -    { -      for (unsigned int i = 0; i < vector_active (cmdvec); i++) -        if ((cmd_node = vector_slot (cmdvec, i)) != NULL) -        { -          // deleting the graph delets the cmd_element as well -          graph_delete_graph (cmd_node->cmdgraph); -          vector_free (cmd_node->cmd_vector); -          hash_clean (cmd_node->cmd_hash, NULL); -          hash_free (cmd_node->cmd_hash); -          cmd_node->cmd_hash = NULL; -        } - -      vector_free (cmdvec); -      cmdvec = NULL; -    } - -  if (host.name) -    XFREE (MTYPE_HOST, host.name); -  if (host.password) -    XFREE (MTYPE_HOST, host.password); -  if (host.password_encrypt) -    XFREE (MTYPE_HOST, host.password_encrypt); -  if (host.enable) -    XFREE (MTYPE_HOST, host.enable); -  if (host.enable_encrypt) -    XFREE (MTYPE_HOST, host.enable_encrypt); -  if (host.logfile) -    XFREE (MTYPE_HOST, host.logfile); -  if (host.motdfile) -    XFREE (MTYPE_HOST, host.motdfile); -  if (host.config) -    XFREE (MTYPE_HOST, host.config); - -  qobj_finish (); +struct cmd_token *new_cmd_token(enum cmd_token_type type, u_char attr, +				const char *text, const char *desc) +{ +	struct cmd_token *token = +		XCALLOC(MTYPE_CMD_TOKENS, sizeof(struct cmd_token)); +	token->type = type; +	token->attr = attr; +	token->text = text ? XSTRDUP(MTYPE_CMD_TEXT, text) : NULL; +	token->desc = desc ? XSTRDUP(MTYPE_CMD_DESC, desc) : NULL; +	token->refcnt = 1; +	token->arg = NULL; +	token->allowrepeat = false; + +	return token; +} + +void del_cmd_token(struct cmd_token *token) +{ +	if (!token) +		return; + +	if (token->text) +		XFREE(MTYPE_CMD_TEXT, token->text); +	if (token->desc) +		XFREE(MTYPE_CMD_DESC, token->desc); +	if (token->arg) +		XFREE(MTYPE_CMD_ARG, token->arg); + +	XFREE(MTYPE_CMD_TOKENS, token); +} + +struct cmd_token *copy_cmd_token(struct cmd_token *token) +{ +	struct cmd_token *copy = +		new_cmd_token(token->type, token->attr, NULL, NULL); +	copy->max = token->max; +	copy->min = token->min; +	copy->text = token->text ? XSTRDUP(MTYPE_CMD_TEXT, token->text) : NULL; +	copy->desc = token->desc ? XSTRDUP(MTYPE_CMD_DESC, token->desc) : NULL; +	copy->arg = token->arg ? XSTRDUP(MTYPE_CMD_ARG, token->arg) : NULL; + +	return copy; +} + +void cmd_terminate() +{ +	struct cmd_node *cmd_node; + +	if (cmdvec) { +		for (unsigned int i = 0; i < vector_active(cmdvec); i++) +			if ((cmd_node = vector_slot(cmdvec, i)) != NULL) { +				// deleting the graph delets the cmd_element as +				// well +				graph_delete_graph(cmd_node->cmdgraph); +				vector_free(cmd_node->cmd_vector); +				hash_clean(cmd_node->cmd_hash, NULL); +				hash_free(cmd_node->cmd_hash); +				cmd_node->cmd_hash = NULL; +			} + +		vector_free(cmdvec); +		cmdvec = NULL; +	} + +	if (host.name) +		XFREE(MTYPE_HOST, host.name); +	if (host.password) +		XFREE(MTYPE_HOST, host.password); +	if (host.password_encrypt) +		XFREE(MTYPE_HOST, host.password_encrypt); +	if (host.enable) +		XFREE(MTYPE_HOST, host.enable); +	if (host.enable_encrypt) +		XFREE(MTYPE_HOST, host.enable_encrypt); +	if (host.logfile) +		XFREE(MTYPE_HOST, host.logfile); +	if (host.motdfile) +		XFREE(MTYPE_HOST, host.motdfile); +	if (host.config) +		XFREE(MTYPE_HOST, host.config); + +	qobj_finish();  } diff --git a/lib/command.h b/lib/command.h index 313d73f7c8..55d7d30c48 100644 --- a/lib/command.h +++ b/lib/command.h @@ -37,128 +37,125 @@ DECLARE_MTYPE(CMD_ARG)  DECLARE_MTYPE(STRVEC)  /* Host configuration variable */ -struct host -{ -  /* Host name of this router. */ -  char *name; +struct host { +	/* Host name of this router. */ +	char *name; -  /* Password for vty interface. */ -  char *password; -  char *password_encrypt; +	/* Password for vty interface. */ +	char *password; +	char *password_encrypt; -  /* Enable password */ -  char *enable; -  char *enable_encrypt; +	/* Enable password */ +	char *enable; +	char *enable_encrypt; -  /* System wide terminal lines. */ -  int lines; +	/* System wide terminal lines. */ +	int lines; -  /* Log filename. */ -  char *logfile; +	/* Log filename. */ +	char *logfile; -  /* config file name of this host */ -  char *config; -  int noconfig; +	/* config file name of this host */ +	char *config; +	int noconfig; -  /* Flags for services */ -  int advanced; -  int encrypt; +	/* Flags for services */ +	int advanced; +	int encrypt; -  /* Banner configuration. */ -  const char *motd; -  char *motdfile; +	/* Banner configuration. */ +	const char *motd; +	char *motdfile;  };  /* There are some command levels which called from command node. */ -enum node_type -{ -  AUTH_NODE,                    /* Authentication mode of vty interface. */ -  VIEW_NODE,                    /* View node. Default mode of vty interface. */ -  AUTH_ENABLE_NODE,             /* Authentication mode for change enable. */ -  ENABLE_NODE,                  /* Enable node. */ -  CONFIG_NODE,                  /* Config node. Default mode of config file. */ -  SERVICE_NODE,                 /* Service node. */ -  DEBUG_NODE,                   /* Debug node. */ -  VRF_DEBUG_NODE,               /* Vrf Debug node. */ -  DEBUG_VNC_NODE,		/* Debug VNC node. */ -  AAA_NODE,                     /* AAA node. */ -  KEYCHAIN_NODE,                /* Key-chain node. */ -  KEYCHAIN_KEY_NODE,            /* Key-chain key node. */ -  NS_NODE,                      /* Logical-Router node. */ -  VRF_NODE,                     /* VRF mode node. */ -  INTERFACE_NODE,               /* Interface mode node. */ -  ZEBRA_NODE,                   /* zebra connection node. */ -  TABLE_NODE,                   /* rtm_table selection node. */ -  RIP_NODE,                     /* RIP protocol mode node. */ -  RIPNG_NODE,                   /* RIPng protocol mode node. */ -  BGP_NODE,                     /* BGP protocol mode which includes BGP4+ */ -  BGP_VPNV4_NODE,               /* BGP MPLS-VPN PE exchange. */ -  BGP_VPNV6_NODE,               /* BGP MPLS-VPN PE exchange. */ -  BGP_IPV4_NODE,                /* BGP IPv4 unicast address family.  */ -  BGP_IPV4M_NODE,               /* BGP IPv4 multicast address family.  */ -  BGP_IPV6_NODE,                /* BGP IPv6 address family */ -  BGP_IPV6M_NODE,               /* BGP IPv6 multicast address family. */ -  BGP_VRF_POLICY_NODE,          /* BGP VRF policy */ -  BGP_VNC_DEFAULTS_NODE,	/* BGP VNC nve defaults */ -  BGP_VNC_NVE_GROUP_NODE,	/* BGP VNC nve group */ -  BGP_VNC_L2_GROUP_NODE,	/* BGP VNC L2 group */ -  RFP_DEFAULTS_NODE,	/* RFP defaults node */ -  BGP_EVPN_NODE,	        /* BGP EVPN node. */ -  OSPF_NODE,                    /* OSPF protocol mode */ -  OSPF6_NODE,                   /* OSPF protocol for IPv6 mode */ -  LDP_NODE,			/* LDP protocol mode */ -  LDP_IPV4_NODE,		/* LDP IPv4 address family */ -  LDP_IPV6_NODE,		/* LDP IPv6 address family */ -  LDP_IPV4_IFACE_NODE,		/* LDP IPv4 Interface */ -  LDP_IPV6_IFACE_NODE,		/* LDP IPv6 Interface */ -  LDP_L2VPN_NODE,		/* LDP L2VPN node */ -  LDP_PSEUDOWIRE_NODE,		/* LDP Pseudowire node */ -  ISIS_NODE,                    /* ISIS protocol mode */ -  PIM_NODE,                     /* PIM protocol mode */ -  MASC_NODE,                    /* MASC for multicast.  */ -  IRDP_NODE,                    /* ICMP Router Discovery Protocol mode. */ -  IP_NODE,                      /* Static ip route node. */ -  ACCESS_NODE,                  /* Access list node. */ -  PREFIX_NODE,                  /* Prefix list node. */ -  ACCESS_IPV6_NODE,             /* Access list node. */ -  PREFIX_IPV6_NODE,             /* Prefix list node. */ -  AS_LIST_NODE,                 /* AS list node. */ -  COMMUNITY_LIST_NODE,          /* Community list node. */ -  RMAP_NODE,                    /* Route map node. */ -  SMUX_NODE,                    /* SNMP configuration node. */ -  DUMP_NODE,                    /* Packet dump node. */ -  FORWARDING_NODE,              /* IP forwarding node. */ -  PROTOCOL_NODE,                /* protocol filtering node */ -  MPLS_NODE,                    /* MPLS config node */ -  PW_NODE,                      /* Pseudowire config node */ -  VTY_NODE,                     /* Vty node. */ -  LINK_PARAMS_NODE,             /* Link-parameters node */ +enum node_type { +	AUTH_NODE,		/* Authentication mode of vty interface. */ +	VIEW_NODE,		/* View node. Default mode of vty interface. */ +	AUTH_ENABLE_NODE,       /* Authentication mode for change enable. */ +	ENABLE_NODE,		/* Enable node. */ +	CONFIG_NODE,		/* Config node. Default mode of config file. */ +	SERVICE_NODE,		/* Service node. */ +	DEBUG_NODE,		/* Debug node. */ +	VRF_DEBUG_NODE,		/* Vrf Debug node. */ +	DEBUG_VNC_NODE,		/* Debug VNC node. */ +	AAA_NODE,		/* AAA node. */ +	KEYCHAIN_NODE,		/* Key-chain node. */ +	KEYCHAIN_KEY_NODE,      /* Key-chain key node. */ +	NS_NODE,		/* Logical-Router node. */ +	VRF_NODE,		/* VRF mode node. */ +	INTERFACE_NODE,		/* Interface mode node. */ +	ZEBRA_NODE,		/* zebra connection node. */ +	TABLE_NODE,		/* rtm_table selection node. */ +	RIP_NODE,		/* RIP protocol mode node. */ +	RIPNG_NODE,		/* RIPng protocol mode node. */ +	BGP_NODE,		/* BGP protocol mode which includes BGP4+ */ +	BGP_VPNV4_NODE,		/* BGP MPLS-VPN PE exchange. */ +	BGP_VPNV6_NODE,		/* BGP MPLS-VPN PE exchange. */ +	BGP_IPV4_NODE,		/* BGP IPv4 unicast address family.  */ +	BGP_IPV4M_NODE,		/* BGP IPv4 multicast address family.  */ +	BGP_IPV6_NODE,		/* BGP IPv6 address family */ +	BGP_IPV6M_NODE,		/* BGP IPv6 multicast address family. */ +	BGP_VRF_POLICY_NODE,    /* BGP VRF policy */ +	BGP_VNC_DEFAULTS_NODE,  /* BGP VNC nve defaults */ +	BGP_VNC_NVE_GROUP_NODE, /* BGP VNC nve group */ +	BGP_VNC_L2_GROUP_NODE,  /* BGP VNC L2 group */ +	RFP_DEFAULTS_NODE,      /* RFP defaults node */ +	BGP_EVPN_NODE,		/* BGP EVPN node. */ +	OSPF_NODE,		/* OSPF protocol mode */ +	OSPF6_NODE,		/* OSPF protocol for IPv6 mode */ +	LDP_NODE,		/* LDP protocol mode */ +	LDP_IPV4_NODE,		/* LDP IPv4 address family */ +	LDP_IPV6_NODE,		/* LDP IPv6 address family */ +	LDP_IPV4_IFACE_NODE,    /* LDP IPv4 Interface */ +	LDP_IPV6_IFACE_NODE,    /* LDP IPv6 Interface */ +	LDP_L2VPN_NODE,		/* LDP L2VPN node */ +	LDP_PSEUDOWIRE_NODE,    /* LDP Pseudowire node */ +	ISIS_NODE,		/* ISIS protocol mode */ +	PIM_NODE,		/* PIM protocol mode */ +	MASC_NODE,		/* MASC for multicast.  */ +	IRDP_NODE,		/* ICMP Router Discovery Protocol mode. */ +	IP_NODE,		/* Static ip route node. */ +	ACCESS_NODE,		/* Access list node. */ +	PREFIX_NODE,		/* Prefix list node. */ +	ACCESS_IPV6_NODE,       /* Access list node. */ +	PREFIX_IPV6_NODE,       /* Prefix list node. */ +	AS_LIST_NODE,		/* AS list node. */ +	COMMUNITY_LIST_NODE,    /* Community list node. */ +	RMAP_NODE,		/* Route map node. */ +	SMUX_NODE,		/* SNMP configuration node. */ +	DUMP_NODE,		/* Packet dump node. */ +	FORWARDING_NODE,	/* IP forwarding node. */ +	PROTOCOL_NODE,		/* protocol filtering node */ +	MPLS_NODE,		/* MPLS config node */ +	PW_NODE,		/* Pseudowire config node */ +	VTY_NODE,		/* Vty node. */ +	LINK_PARAMS_NODE,       /* Link-parameters node */  };  /* Node which has some commands and prompt string and configuration     function pointer . */ -struct cmd_node -{ -  /* Node index. */ -  enum node_type node; +struct cmd_node { +	/* Node index. */ +	enum node_type node; -  /* Prompt character at vty interface. */ -  const char *prompt; +	/* Prompt character at vty interface. */ +	const char *prompt; -  /* Is this node's configuration goes to vtysh ? */ -  int vtysh; +	/* Is this node's configuration goes to vtysh ? */ +	int vtysh; -  /* Node's configuration write function */ -  int (*func) (struct vty *); +	/* Node's configuration write function */ +	int (*func)(struct vty *); -  /* Node's command graph */ -  struct graph *cmdgraph; +	/* Node's command graph */ +	struct graph *cmdgraph; -  /* Vector of this node's command list. */ -  vector cmd_vector; +	/* Vector of this node's command list. */ +	vector cmd_vector; -  /* Hashed index of command node list, for de-dupping primarily */ -  struct hash *cmd_hash; +	/* Hashed index of command node list, for de-dupping primarily */ +	struct hash *cmd_hash;  };  /** @@ -167,61 +164,57 @@ struct cmd_node   * The type determines what kind of data the token can match (in the   * matching use case) or hold (in the argv use case).   */ -enum cmd_token_type -{ -  WORD_TKN,         // words -  VARIABLE_TKN,     // almost anything -  RANGE_TKN,        // integer range -  IPV4_TKN,         // IPV4 addresses -  IPV4_PREFIX_TKN,  // IPV4 network prefixes -  IPV6_TKN,         // IPV6 prefixes -  IPV6_PREFIX_TKN,  // IPV6 network prefixes - -  /* plumbing types */ -  FORK_TKN,         // marks subgraph beginning -  JOIN_TKN,         // marks subgraph end -  START_TKN,        // first token in line -  END_TKN,          // last token in line - -  SPECIAL_TKN = FORK_TKN, +enum cmd_token_type { +	WORD_TKN,	// words +	VARIABLE_TKN,    // almost anything +	RANGE_TKN,       // integer range +	IPV4_TKN,	// IPV4 addresses +	IPV4_PREFIX_TKN, // IPV4 network prefixes +	IPV6_TKN,	// IPV6 prefixes +	IPV6_PREFIX_TKN, // IPV6 network prefixes + +	/* plumbing types */ +	FORK_TKN,  // marks subgraph beginning +	JOIN_TKN,  // marks subgraph end +	START_TKN, // first token in line +	END_TKN,   // last token in line + +	SPECIAL_TKN = FORK_TKN,  };  /* Command attributes */ -enum -{ -  CMD_ATTR_NORMAL, -  CMD_ATTR_DEPRECATED, -  CMD_ATTR_HIDDEN, +enum { CMD_ATTR_NORMAL, +       CMD_ATTR_DEPRECATED, +       CMD_ATTR_HIDDEN,  };  /* Comamand token struct. */ -struct cmd_token -{ -  enum cmd_token_type type;     // token type -  u_char attr;                  // token attributes -  bool allowrepeat;             // matcher allowed to match token repetively? -  uint32_t refcnt; - -  char *text;                   // token text -  char *desc;                   // token description -  long long min, max;           // for ranges -  char *arg;                    // user input that matches this token - -  struct graph_node *forkjoin;  // paired FORK/JOIN for JOIN/FORK +struct cmd_token { +	enum cmd_token_type type; // token type +	u_char attr;		  // token attributes +	bool allowrepeat;	 // matcher allowed to match token repetively? +	uint32_t refcnt; + +	char *text;	 // token text +	char *desc;	 // token description +	long long min, max; // for ranges +	char *arg;	  // user input that matches this token + +	struct graph_node *forkjoin; // paired FORK/JOIN for JOIN/FORK  };  /* Structure of command element. */ -struct cmd_element -{ -  const char *string;           /* Command specification by string. */ -  const char *doc;              /* Documentation of this command. */ -  int daemon;                   /* Daemon to which this command belong. */ -  u_char attr;                  /* Command attributes */ +struct cmd_element { +	const char *string; /* Command specification by string. */ +	const char *doc;    /* Documentation of this command. */ +	int daemon;	 /* Daemon to which this command belong. */ +	u_char attr;	/* Command attributes */ -  /* handler function for command */ -  int (*func) (const struct cmd_element *, struct vty *, int, struct cmd_token *[]); +	/* handler function for command */ +	int (*func)(const struct cmd_element *, struct vty *, int, +		    struct cmd_token *[]); -  const char *name;             /* symbol name for debugging */ +	const char *name; /* symbol name for debugging */  };  /* Return value of the commands. */ @@ -246,93 +239,100 @@ struct cmd_element  #ifndef VTYSH_EXTRACT_PL  /* helper defines for end-user DEFUN* macros */ -#define DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attrs, dnum) \ -  static struct cmd_element cmdname = \ -  { \ -    .string = cmdstr, \ -    .func = funcname, \ -    .doc = helpstr, \ -    .attr = attrs, \ -    .daemon = dnum, \ -    .name = #cmdname, \ -  }; - -#define DEFUN_CMD_FUNC_DECL(funcname) \ -  static int funcname (const struct cmd_element *, struct vty *, int, struct cmd_token *[]); - -#define DEFUN_CMD_FUNC_TEXT(funcname) \ -  static int funcname \ -    (const struct cmd_element *self __attribute__ ((unused)), \ -     struct vty *vty __attribute__ ((unused)), \ -     int argc __attribute__ ((unused)), \ -     struct cmd_token *argv[] __attribute__ ((unused)) ) - -#define DEFUN(funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_FUNC_DECL(funcname) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, 0) \ -  DEFUN_CMD_FUNC_TEXT(funcname) - -#define DEFUN_ATTR(funcname, cmdname, cmdstr, helpstr, attr) \ -  DEFUN_CMD_FUNC_DECL(funcname) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, 0) \ -  DEFUN_CMD_FUNC_TEXT(funcname) - -#define DEFUN_HIDDEN(funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_ATTR (funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN) - -#define DEFUN_DEPRECATED(funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_ATTR (funcname, cmdname, cmdstr, helpstr, CMD_ATTR_DEPRECATED) \ +#define DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attrs, dnum)     \ +	static struct cmd_element cmdname = {                                  \ +		.string = cmdstr,                                              \ +		.func = funcname,                                              \ +		.doc = helpstr,                                                \ +		.attr = attrs,                                                 \ +		.daemon = dnum,                                                \ +		.name = #cmdname,                                              \ +	}; + +#define DEFUN_CMD_FUNC_DECL(funcname)                                          \ +	static int funcname(const struct cmd_element *, struct vty *, int,     \ +			    struct cmd_token *[]); + +#define DEFUN_CMD_FUNC_TEXT(funcname)                                          \ +	static int funcname(const struct cmd_element *self                     \ +			    __attribute__((unused)),                           \ +			    struct vty *vty __attribute__((unused)),           \ +			    int argc __attribute__((unused)),                  \ +			    struct cmd_token *argv[] __attribute__((unused))) + +#define DEFUN(funcname, cmdname, cmdstr, helpstr)                              \ +	DEFUN_CMD_FUNC_DECL(funcname)                                          \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, 0)            \ +	DEFUN_CMD_FUNC_TEXT(funcname) + +#define DEFUN_ATTR(funcname, cmdname, cmdstr, helpstr, attr)                   \ +	DEFUN_CMD_FUNC_DECL(funcname)                                          \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, 0)         \ +	DEFUN_CMD_FUNC_TEXT(funcname) + +#define DEFUN_HIDDEN(funcname, cmdname, cmdstr, helpstr)                       \ +	DEFUN_ATTR(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN) + +#define DEFUN_DEPRECATED(funcname, cmdname, cmdstr, helpstr)                   \ +	DEFUN_ATTR(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_DEPRECATED)  /* DEFUN_NOSH for commands that vtysh should ignore */ -#define DEFUN_NOSH(funcname, cmdname, cmdstr, helpstr) \ -  DEFUN(funcname, cmdname, cmdstr, helpstr) +#define DEFUN_NOSH(funcname, cmdname, cmdstr, helpstr)                         \ +	DEFUN(funcname, cmdname, cmdstr, helpstr)  /* DEFSH for vtysh. */ -#define DEFSH(daemon, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_ELEMENT(NULL, cmdname, cmdstr, helpstr, 0, daemon) \ +#define DEFSH(daemon, cmdname, cmdstr, helpstr)                                \ +	DEFUN_CMD_ELEMENT(NULL, cmdname, cmdstr, helpstr, 0, daemon) -#define DEFSH_HIDDEN(daemon, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_ELEMENT(NULL, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN, daemon) \ +#define DEFSH_HIDDEN(daemon, cmdname, cmdstr, helpstr)                         \ +	DEFUN_CMD_ELEMENT(NULL, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN,     \ +			  daemon)  /* DEFUN + DEFSH */ -#define DEFUNSH(daemon, funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_FUNC_DECL(funcname) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, daemon) \ -  DEFUN_CMD_FUNC_TEXT(funcname) +#define DEFUNSH(daemon, funcname, cmdname, cmdstr, helpstr)                    \ +	DEFUN_CMD_FUNC_DECL(funcname)                                          \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, daemon)       \ +	DEFUN_CMD_FUNC_TEXT(funcname)  /* DEFUN + DEFSH with attributes */ -#define DEFUNSH_ATTR(daemon, funcname, cmdname, cmdstr, helpstr, attr) \ -  DEFUN_CMD_FUNC_DECL(funcname) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, daemon) \ -  DEFUN_CMD_FUNC_TEXT(funcname) +#define DEFUNSH_ATTR(daemon, funcname, cmdname, cmdstr, helpstr, attr)         \ +	DEFUN_CMD_FUNC_DECL(funcname)                                          \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, daemon)    \ +	DEFUN_CMD_FUNC_TEXT(funcname) -#define DEFUNSH_HIDDEN(daemon, funcname, cmdname, cmdstr, helpstr) \ -  DEFUNSH_ATTR (daemon, funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN) +#define DEFUNSH_HIDDEN(daemon, funcname, cmdname, cmdstr, helpstr)             \ +	DEFUNSH_ATTR(daemon, funcname, cmdname, cmdstr, helpstr,               \ +		     CMD_ATTR_HIDDEN) -#define DEFUNSH_DEPRECATED(daemon, funcname, cmdname, cmdstr, helpstr) \ -  DEFUNSH_ATTR (daemon, funcname, cmdname, cmdstr, helpstr, CMD_ATTR_DEPRECATED) +#define DEFUNSH_DEPRECATED(daemon, funcname, cmdname, cmdstr, helpstr)         \ +	DEFUNSH_ATTR(daemon, funcname, cmdname, cmdstr, helpstr,               \ +		     CMD_ATTR_DEPRECATED)  /* ALIAS macro which define existing command's alias. */ -#define ALIAS(funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, 0) +#define ALIAS(funcname, cmdname, cmdstr, helpstr)                              \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, 0) -#define ALIAS_ATTR(funcname, cmdname, cmdstr, helpstr, attr) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, 0) +#define ALIAS_ATTR(funcname, cmdname, cmdstr, helpstr, attr)                   \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, attr, 0) -#define ALIAS_HIDDEN(funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN, 0) +#define ALIAS_HIDDEN(funcname, cmdname, cmdstr, helpstr)                       \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN, \ +			  0) -#define ALIAS_DEPRECATED(funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_DEPRECATED, 0) +#define ALIAS_DEPRECATED(funcname, cmdname, cmdstr, helpstr)                   \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr,                  \ +			  CMD_ATTR_DEPRECATED, 0) -#define ALIAS_SH(daemon, funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, daemon) +#define ALIAS_SH(daemon, funcname, cmdname, cmdstr, helpstr)                   \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, 0, daemon) -#define ALIAS_SH_HIDDEN(daemon, funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN, daemon) +#define ALIAS_SH_HIDDEN(daemon, funcname, cmdname, cmdstr, helpstr)            \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_HIDDEN, \ +			  daemon) -#define ALIAS_SH_DEPRECATED(daemon, funcname, cmdname, cmdstr, helpstr) \ -  DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr, CMD_ATTR_DEPRECATED, daemon) +#define ALIAS_SH_DEPRECATED(daemon, funcname, cmdname, cmdstr, helpstr)        \ +	DEFUN_CMD_ELEMENT(funcname, cmdname, cmdstr, helpstr,                  \ +			  CMD_ATTR_DEPRECATED, daemon)  #endif /* VTYSH_EXTRACT_PL */ @@ -381,8 +381,8 @@ struct cmd_element  #define SECONDS_STR "Seconds\n"  #define ROUTE_STR "Routing Table\n"  #define PREFIX_LIST_STR "Build a prefix list\n" -#define OSPF6_DUMP_TYPE_LIST \ -"<neighbor|interface|area|lsa|zebra|config|dbex|spf|route|lsdb|redistribute|hook|asbr|prefix|abr>" +#define OSPF6_DUMP_TYPE_LIST                                                   \ +	"<neighbor|interface|area|lsa|zebra|config|dbex|spf|route|lsdb|redistribute|hook|asbr|prefix|abr>"  #define ISIS_STR "IS-IS information\n"  #define AREA_TAG_STR "[area tag]\n"  #define COMMUNITY_AANN_STR "Community number where AA and NN are (0-65535)\n" @@ -402,57 +402,63 @@ struct cmd_element  #define NEIGHBOR_ADDR_STR3 "Neighbor address\nIPv6 address\nInterface name\n"  /* Prototypes. */ -extern void install_node (struct cmd_node *, int (*) (struct vty *)); -extern void install_default (enum node_type); -extern void install_element (enum node_type, struct cmd_element *); +extern void install_node(struct cmd_node *, int (*)(struct vty *)); +extern void install_default(enum node_type); +extern void install_element(enum node_type, struct cmd_element *);  /* known issue with uninstall_element:  changes to cmd_token->attr (i.e.   * deprecated/hidden) are not reversed. */ -extern void uninstall_element (enum node_type, struct cmd_element *); +extern void uninstall_element(enum node_type, struct cmd_element *);  /* Concatenates argv[shift] through argv[argc-1] into a single NUL-terminated     string with a space between each element (allocated using     XMALLOC(MTYPE_TMP)).  Returns NULL if shift >= argc. */ -extern char *argv_concat (struct cmd_token **argv, int argc, int shift); -extern int argv_find (struct cmd_token **argv, int argc, const char *text, int *index); - -extern vector cmd_make_strvec (const char *); -extern void cmd_free_strvec (vector); -extern vector cmd_describe_command (vector, struct vty *, int *status); -extern char **cmd_complete_command (vector, struct vty *, int *status); -extern const char *cmd_prompt (enum node_type); -extern int command_config_read_one_line (struct vty *vty, const struct cmd_element **, int use_config_node); -extern int config_from_file (struct vty *, FILE *, unsigned int *line_num); -extern enum node_type node_parent (enum node_type); -extern int cmd_execute_command (vector, struct vty *, const struct cmd_element **, int); -extern int cmd_execute_command_strict (vector, struct vty *, const struct cmd_element **); -extern void cmd_init (int); -extern void cmd_terminate (void); -extern void cmd_exit (struct vty *vty); -extern int cmd_list_cmds (struct vty *vty, int do_permute); - -extern int cmd_hostname_set (const char *hostname); +extern char *argv_concat(struct cmd_token **argv, int argc, int shift); +extern int argv_find(struct cmd_token **argv, int argc, const char *text, +		     int *index); + +extern vector cmd_make_strvec(const char *); +extern void cmd_free_strvec(vector); +extern vector cmd_describe_command(vector, struct vty *, int *status); +extern char **cmd_complete_command(vector, struct vty *, int *status); +extern const char *cmd_prompt(enum node_type); +extern int command_config_read_one_line(struct vty *vty, +					const struct cmd_element **, +					int use_config_node); +extern int config_from_file(struct vty *, FILE *, unsigned int *line_num); +extern enum node_type node_parent(enum node_type); +extern int cmd_execute_command(vector, struct vty *, +			       const struct cmd_element **, int); +extern int cmd_execute_command_strict(vector, struct vty *, +				      const struct cmd_element **); +extern void cmd_init(int); +extern void cmd_terminate(void); +extern void cmd_exit(struct vty *vty); +extern int cmd_list_cmds(struct vty *vty, int do_permute); + +extern int cmd_hostname_set(const char *hostname);  /* NOT safe for general use; call this only if DEV_BUILD! */ -extern void grammar_sandbox_init (void); +extern void grammar_sandbox_init(void);  /* memory management for cmd_token */ -extern struct cmd_token *new_cmd_token (enum cmd_token_type, u_char attr, -                                        const char *text, const char *desc); -extern void del_cmd_token (struct cmd_token *); -extern struct cmd_token *copy_cmd_token (struct cmd_token *); +extern struct cmd_token *new_cmd_token(enum cmd_token_type, u_char attr, +				       const char *text, const char *desc); +extern void del_cmd_token(struct cmd_token *); +extern struct cmd_token *copy_cmd_token(struct cmd_token *); -extern vector completions_to_vec (struct list *completions); -extern void cmd_merge_graphs (struct graph *old, struct graph *new, int direction); -extern void command_parse_format (struct graph *graph, struct cmd_element *cmd); +extern vector completions_to_vec(struct list *completions); +extern void cmd_merge_graphs(struct graph *old, struct graph *new, +			     int direction); +extern void command_parse_format(struct graph *graph, struct cmd_element *cmd);  /* Export typical functions. */ -extern const char *host_config_get (void); -extern void host_config_set (const char *); +extern const char *host_config_get(void); +extern void host_config_set(const char *); -extern void print_version (const char *); +extern void print_version(const char *); -extern int cmd_banner_motd_file (const char *); +extern int cmd_banner_motd_file(const char *);  /* struct host global, ick */  extern struct host host; diff --git a/lib/command_match.c b/lib/command_match.c index bbd9cd091d..24e850ad2e 100644 --- a/lib/command_match.c +++ b/lib/command_match.c @@ -37,111 +37,100 @@ DEFINE_MTYPE_STATIC(LIB, CMD_MATCHSTACK, "Command Match Stack")  #define TM 0  #endif -#define trace_matcher(...) \ -   do { if (TM) fprintf (stderr, __VA_ARGS__); } while (0); +#define trace_matcher(...)                                                     \ +	do {                                                                   \ +		if (TM)                                                        \ +			fprintf(stderr, __VA_ARGS__);                          \ +	} while (0);  /* matcher helper prototypes */ -static int -add_nexthops (struct list *, struct graph_node *, -              struct graph_node **, size_t); +static int add_nexthops(struct list *, struct graph_node *, +			struct graph_node **, size_t); -static struct list * -command_match_r (struct graph_node *, vector, unsigned int, -                 struct graph_node **); +static struct list *command_match_r(struct graph_node *, vector, unsigned int, +				    struct graph_node **); -static int -score_precedence (enum cmd_token_type); +static int score_precedence(enum cmd_token_type); -static enum match_type -min_match_level (enum cmd_token_type); +static enum match_type min_match_level(enum cmd_token_type); -static void -del_arglist (struct list *); +static void del_arglist(struct list *); -static struct cmd_token * -disambiguate_tokens (struct cmd_token *, struct cmd_token *, char *); +static struct cmd_token *disambiguate_tokens(struct cmd_token *, +					     struct cmd_token *, char *); -static struct list * -disambiguate (struct list *, struct list *, vector, unsigned int); +static struct list *disambiguate(struct list *, struct list *, vector, +				 unsigned int); -int -compare_completions (const void *, const void *); +int compare_completions(const void *, const void *);  /* token matcher prototypes */ -static enum match_type -match_token (struct cmd_token *, char *); +static enum match_type match_token(struct cmd_token *, char *); -static enum match_type -match_ipv4 (const char *); +static enum match_type match_ipv4(const char *); -static enum match_type -match_ipv4_prefix (const char *); +static enum match_type match_ipv4_prefix(const char *); -static enum match_type -match_ipv6 (const char *); +static enum match_type match_ipv6(const char *); -static enum match_type -match_ipv6_prefix (const char *); +static enum match_type match_ipv6_prefix(const char *); -static enum match_type -match_range (struct cmd_token *, const char *); +static enum match_type match_range(struct cmd_token *, const char *); -static enum match_type -match_word (struct cmd_token *, const char *); +static enum match_type match_word(struct cmd_token *, const char *); -static enum match_type -match_variable (struct cmd_token *, const char *); +static enum match_type match_variable(struct cmd_token *, const char *);  /* matching functions */  static enum matcher_rv matcher_rv; -enum matcher_rv -command_match (struct graph *cmdgraph, -               vector vline, -               struct list **argv, -               const struct cmd_element **el) +enum matcher_rv command_match(struct graph *cmdgraph, vector vline, +			      struct list **argv, const struct cmd_element **el)  { -  struct graph_node *stack[MAXDEPTH]; -  matcher_rv = MATCHER_NO_MATCH; - -  // prepend a dummy token to match that pesky start node -  vector vvline = vector_init (vline->alloced + 1); -  vector_set_index (vvline, 0, (void *) XSTRDUP (MTYPE_TMP, "dummy")); -  memcpy (vvline->index + 1, vline->index, sizeof (void *) * vline->alloced); -  vvline->active = vline->active + 1; - -  struct graph_node *start = vector_slot (cmdgraph->nodes, 0); -  if ((*argv = command_match_r (start, vvline, 0, stack))) // successful match -    { -      struct listnode *head = listhead (*argv); -      struct listnode *tail = listtail (*argv); - -      // delete dummy start node -      del_cmd_token ((struct cmd_token *) head->data); -      list_delete_node (*argv, head); - -      // get cmd_element out of list tail -      *el = listgetdata (tail); -      list_delete_node (*argv, tail); - -      // now argv is an ordered list of cmd_token matching the user -      // input, with each cmd_token->arg holding the corresponding input -      assert (*el); -    } - -  if (!*el) { -    trace_matcher ("No match\n"); -  } -  else { -    trace_matcher ("Matched command\n->string %s\n->desc %s\n", (*el)->string, (*el)->doc); -  } - -  // free the leader token we alloc'd -  XFREE (MTYPE_TMP, vector_slot (vvline, 0)); -  // free vector -  vector_free (vvline); - -  return matcher_rv; +	struct graph_node *stack[MAXDEPTH]; +	matcher_rv = MATCHER_NO_MATCH; + +	// prepend a dummy token to match that pesky start node +	vector vvline = vector_init(vline->alloced + 1); +	vector_set_index(vvline, 0, (void *)XSTRDUP(MTYPE_TMP, "dummy")); +	memcpy(vvline->index + 1, vline->index, +	       sizeof(void *) * vline->alloced); +	vvline->active = vline->active + 1; + +	struct graph_node *start = vector_slot(cmdgraph->nodes, 0); +	if ((*argv = command_match_r(start, vvline, 0, +				     stack))) // successful match +	{ +		struct listnode *head = listhead(*argv); +		struct listnode *tail = listtail(*argv); + +		// delete dummy start node +		del_cmd_token((struct cmd_token *)head->data); +		list_delete_node(*argv, head); + +		// get cmd_element out of list tail +		*el = listgetdata(tail); +		list_delete_node(*argv, tail); + +		// now argv is an ordered list of cmd_token matching the user +		// input, with each cmd_token->arg holding the corresponding +		// input +		assert(*el); +	} + +	if (!*el) { +		trace_matcher("No match\n"); +	} else { +		trace_matcher("Matched command\n->string %s\n->desc %s\n", +			      (*el)->string, (*el)->doc); +	} + +	// free the leader token we alloc'd +	XFREE(MTYPE_TMP, vector_slot(vvline, 0)); +	// free vector +	vector_free(vvline); + +	return matcher_rv;  }  /** @@ -195,265 +184,271 @@ command_match (struct graph *cmdgraph,   *   * If no match was found, the return value is NULL.   */ -static struct list * -command_match_r (struct graph_node *start, vector vline, unsigned int n, -                 struct graph_node **stack) +static struct list *command_match_r(struct graph_node *start, vector vline, +				    unsigned int n, struct graph_node **stack)  { -  assert (n < vector_active (vline)); +	assert(n < vector_active(vline)); -  // get the minimum match level that can count as a full match -  struct cmd_token *token = start->data; -  enum match_type minmatch = min_match_level (token->type); +	// get the minimum match level that can count as a full match +	struct cmd_token *token = start->data; +	enum match_type minmatch = min_match_level(token->type); -  /* check history/stack of tokens -   * this disallows matching the same one more than once if there is a -   * circle in the graph (used for keyword arguments) */ -  if (n == MAXDEPTH) -    return NULL; -  if (!token->allowrepeat) -    for (size_t s = 0; s < n; s++) -      if (stack[s] == start) -        return NULL; +	/* check history/stack of tokens +	 * this disallows matching the same one more than once if there is a +	 * circle in the graph (used for keyword arguments) */ +	if (n == MAXDEPTH) +		return NULL; +	if (!token->allowrepeat) +		for (size_t s = 0; s < n; s++) +			if (stack[s] == start) +				return NULL; -  // get the current operating input token -  char *input_token = vector_slot (vline, n); +	// get the current operating input token +	char *input_token = vector_slot(vline, n);  #ifdef TRACE_MATCHER -  fprintf (stdout, "\"%-20s\" matches \"%-30s\" ? ", input_token, token->text); -  enum match_type mt = match_token (token, input_token); -  fprintf (stdout, "min: %d - ", minmatch); -  switch (mt) -  { -    case trivial_match: -      fprintf (stdout, "trivial_match "); -      break; -    case no_match: -      fprintf (stdout, "no_match "); -      break; -    case partly_match: -      fprintf (stdout, "partly_match "); -      break; -    case exact_match: -      fprintf (stdout, "exact_match "); -      break; -  } -  if (mt >= minmatch) fprintf (stdout, " MATCH"); -  fprintf (stdout, "\n"); +	fprintf(stdout, "\"%-20s\" matches \"%-30s\" ? ", input_token, +		token->text); +	enum match_type mt = match_token(token, input_token); +	fprintf(stdout, "min: %d - ", minmatch); +	switch (mt) { +	case trivial_match: +		fprintf(stdout, "trivial_match "); +		break; +	case no_match: +		fprintf(stdout, "no_match "); +		break; +	case partly_match: +		fprintf(stdout, "partly_match "); +		break; +	case exact_match: +		fprintf(stdout, "exact_match "); +		break; +	} +	if (mt >= minmatch) +		fprintf(stdout, " MATCH"); +	fprintf(stdout, "\n");  #endif -  // if we don't match this node, die -  if (match_token (token, input_token) < minmatch) -    return NULL; - -  stack[n] = start; - -  // pointers for iterating linklist -  struct listnode *ln; -  struct graph_node *gn; - -  // get all possible nexthops -  struct list *next = list_new(); -  add_nexthops (next, start, NULL, 0); - -  // determine the best match -  int ambiguous = 0; -  struct list *currbest = NULL; -  for (ALL_LIST_ELEMENTS_RO (next,ln,gn)) -    { -      // if we've matched all input we're looking for END_TKN -      if (n+1 == vector_active (vline)) -        { -          struct cmd_token *tok = gn->data; -          if (tok->type == END_TKN) -            { -              if (currbest) // there is more than one END_TKN in the follow set -              { -                ambiguous = 1; -                break; -              } -              currbest = list_new(); -              // node should have one child node with the element -              struct graph_node *leaf = vector_slot (gn->to, 0); -              // last node in the list will hold the cmd_element; -              // this is important because list_delete() expects -              // that all nodes have the same data type, so when -              // deleting this list the last node must be -              // manually deleted -              struct cmd_element *el = leaf->data; -              listnode_add (currbest, el); -              currbest->del = (void (*)(void *)) &del_cmd_token; -              // do not break immediately; continue walking through the follow set -              // to ensure that there is exactly one END_TKN -            } -          continue; -        } - -      // else recurse on candidate child node -      struct list *result = command_match_r (gn, vline, n+1, stack); - -      // save the best match -      if (result && currbest) -        { -          // pick the best of two matches -          struct list *newbest = disambiguate (currbest, result, vline, n+1); -          // set ambiguity flag -          ambiguous = !newbest || (ambiguous && newbest == currbest); -          // delete the unnecessary result -          struct list *todelete = ((newbest && newbest == result) ? currbest : result); -          del_arglist (todelete); - -          currbest = newbest ? newbest : currbest; -        } -      else if (result) -        currbest = result; -    } - -  if (currbest) -    { -      if (ambiguous) -        { -          del_arglist (currbest); -          currbest = NULL; -          matcher_rv = MATCHER_AMBIGUOUS; -        } -      else -        { -          // copy token, set arg and prepend to currbest -          struct cmd_token *token = start->data; -          struct cmd_token *copy = copy_cmd_token (token); -          copy->arg = XSTRDUP (MTYPE_CMD_ARG, input_token); -          listnode_add_before (currbest, currbest->head, copy); -          matcher_rv = MATCHER_OK; -        } -    } -  else if (n+1 == vector_active (vline) && matcher_rv == MATCHER_NO_MATCH) -    matcher_rv = MATCHER_INCOMPLETE; - -  // cleanup -  list_delete (next); - -  return currbest; +	// if we don't match this node, die +	if (match_token(token, input_token) < minmatch) +		return NULL; + +	stack[n] = start; + +	// pointers for iterating linklist +	struct listnode *ln; +	struct graph_node *gn; + +	// get all possible nexthops +	struct list *next = list_new(); +	add_nexthops(next, start, NULL, 0); + +	// determine the best match +	int ambiguous = 0; +	struct list *currbest = NULL; +	for (ALL_LIST_ELEMENTS_RO(next, ln, gn)) { +		// if we've matched all input we're looking for END_TKN +		if (n + 1 == vector_active(vline)) { +			struct cmd_token *tok = gn->data; +			if (tok->type == END_TKN) { +				if (currbest) // there is more than one END_TKN +					      // in the follow set +				{ +					ambiguous = 1; +					break; +				} +				currbest = list_new(); +				// node should have one child node with the +				// element +				struct graph_node *leaf = +					vector_slot(gn->to, 0); +				// last node in the list will hold the +				// cmd_element; +				// this is important because list_delete() +				// expects +				// that all nodes have the same data type, so +				// when +				// deleting this list the last node must be +				// manually deleted +				struct cmd_element *el = leaf->data; +				listnode_add(currbest, el); +				currbest->del = +					(void (*)(void *)) & del_cmd_token; +				// do not break immediately; continue walking +				// through the follow set +				// to ensure that there is exactly one END_TKN +			} +			continue; +		} + +		// else recurse on candidate child node +		struct list *result = command_match_r(gn, vline, n + 1, stack); + +		// save the best match +		if (result && currbest) { +			// pick the best of two matches +			struct list *newbest = +				disambiguate(currbest, result, vline, n + 1); +			// set ambiguity flag +			ambiguous = +				!newbest || (ambiguous && newbest == currbest); +			// delete the unnecessary result +			struct list *todelete = +				((newbest && newbest == result) ? currbest +								: result); +			del_arglist(todelete); + +			currbest = newbest ? newbest : currbest; +		} else if (result) +			currbest = result; +	} + +	if (currbest) { +		if (ambiguous) { +			del_arglist(currbest); +			currbest = NULL; +			matcher_rv = MATCHER_AMBIGUOUS; +		} else { +			// copy token, set arg and prepend to currbest +			struct cmd_token *token = start->data; +			struct cmd_token *copy = copy_cmd_token(token); +			copy->arg = XSTRDUP(MTYPE_CMD_ARG, input_token); +			listnode_add_before(currbest, currbest->head, copy); +			matcher_rv = MATCHER_OK; +		} +	} else if (n + 1 == vector_active(vline) +		   && matcher_rv == MATCHER_NO_MATCH) +		matcher_rv = MATCHER_INCOMPLETE; + +	// cleanup +	list_delete(next); + +	return currbest;  } -static void -stack_del (void *val) +static void stack_del(void *val)  { -  XFREE (MTYPE_CMD_MATCHSTACK, val); +	XFREE(MTYPE_CMD_MATCHSTACK, val);  } -enum matcher_rv -command_complete (struct graph *graph, -                  vector vline, -                  struct list **completions) +enum matcher_rv command_complete(struct graph *graph, vector vline, +				 struct list **completions)  { -  // pointer to next input token to match -  char *input_token; - -  struct list *current = list_new(), // current nodes to match input token against -                 *next = list_new(); // possible next hops after current input token -  current->del = next->del = stack_del; - -  // pointers used for iterating lists -  struct graph_node **gstack, **newstack; -  struct listnode *node; - -  // add all children of start node to list -  struct graph_node *start = vector_slot (graph->nodes, 0); -  add_nexthops (next, start, &start, 0); - -  unsigned int idx; -  for (idx = 0; idx < vector_active (vline) && next->count > 0; idx++) -    { -      list_delete (current); -      current = next; -      next = list_new(); -      next->del = stack_del; - -      input_token = vector_slot (vline, idx); - -      int exact_match_exists = 0; -      for (ALL_LIST_ELEMENTS_RO (current,node,gstack)) -        if (!exact_match_exists) -          exact_match_exists = (match_token (gstack[0]->data, input_token) == exact_match); -        else -          break; - -      for (ALL_LIST_ELEMENTS_RO (current,node,gstack)) -        { -          struct cmd_token *token = gstack[0]->data; - -          if (token->attr == CMD_ATTR_HIDDEN || token->attr == CMD_ATTR_DEPRECATED) -            continue; - -          enum match_type minmatch = min_match_level (token->type); -          trace_matcher ("\"%s\" matches \"%s\" (%d) ? ", -                         input_token, token->text, token->type); - -          unsigned int last_token = (vector_active (vline) - 1 == idx); -          enum match_type matchtype = match_token (token, input_token); -          switch (matchtype) -            { -              // occurs when last token is whitespace -              case trivial_match: -                trace_matcher ("trivial_match\n"); -                assert(last_token); -                newstack = XMALLOC (MTYPE_CMD_MATCHSTACK, -                                    sizeof(struct graph_node *)); -                /* we're not recursing here, just the first element is OK */ -                newstack[0] = gstack[0]; -                listnode_add (next, newstack); -                break; -              case partly_match: -                trace_matcher ("trivial_match\n"); -                if (exact_match_exists && !last_token) -                  break; -              case exact_match: -                trace_matcher ("exact_match\n"); -                if (last_token) -                  { -                    newstack = XMALLOC (MTYPE_CMD_MATCHSTACK, -                                        sizeof(struct graph_node *)); -                    /* same as above, not recursing on this */ -                    newstack[0] = gstack[0]; -                    listnode_add (next, newstack); -                  } -                else if (matchtype >= minmatch) -                  add_nexthops (next, gstack[0], gstack, idx + 1); -                break; -              default: -                trace_matcher ("no_match\n"); -                break; -            } -        } -    } - -  /* Variable summary -   * ----------------------------------------------------------------- -   * token    = last input token processed -   * idx      = index in `command` of last token processed -   * current  = set of all transitions from the previous input token -   * next     = set of all nodes reachable from all nodes in `matched` -   */ - -  matcher_rv = -     idx == vector_active(vline) && next->count ? -     MATCHER_OK : -     MATCHER_NO_MATCH; - -  *completions = NULL; -  if (!MATCHER_ERROR(matcher_rv)) -  { -    // extract cmd_token into list -    *completions = list_new (); -    for (ALL_LIST_ELEMENTS_RO (next,node,gstack)) { -      listnode_add (*completions, gstack[0]->data); -    } -  } - -  list_delete (current); -  list_delete (next); - -  return matcher_rv; +	// pointer to next input token to match +	char *input_token; + +	struct list * +		current = +		       list_new(), // current nodes to match input token against +		*next = list_new(); // possible next hops after current input +				    // token +	current->del = next->del = stack_del; + +	// pointers used for iterating lists +	struct graph_node **gstack, **newstack; +	struct listnode *node; + +	// add all children of start node to list +	struct graph_node *start = vector_slot(graph->nodes, 0); +	add_nexthops(next, start, &start, 0); + +	unsigned int idx; +	for (idx = 0; idx < vector_active(vline) && next->count > 0; idx++) { +		list_delete(current); +		current = next; +		next = list_new(); +		next->del = stack_del; + +		input_token = vector_slot(vline, idx); + +		int exact_match_exists = 0; +		for (ALL_LIST_ELEMENTS_RO(current, node, gstack)) +			if (!exact_match_exists) +				exact_match_exists = +					(match_token(gstack[0]->data, +						     input_token) +					 == exact_match); +			else +				break; + +		for (ALL_LIST_ELEMENTS_RO(current, node, gstack)) { +			struct cmd_token *token = gstack[0]->data; + +			if (token->attr == CMD_ATTR_HIDDEN +			    || token->attr == CMD_ATTR_DEPRECATED) +				continue; + +			enum match_type minmatch = min_match_level(token->type); +			trace_matcher("\"%s\" matches \"%s\" (%d) ? ", +				      input_token, token->text, token->type); + +			unsigned int last_token = +				(vector_active(vline) - 1 == idx); +			enum match_type matchtype = +				match_token(token, input_token); +			switch (matchtype) { +			// occurs when last token is whitespace +			case trivial_match: +				trace_matcher("trivial_match\n"); +				assert(last_token); +				newstack = XMALLOC(MTYPE_CMD_MATCHSTACK, +						   sizeof(struct graph_node *)); +				/* we're not recursing here, just the first +				 * element is OK */ +				newstack[0] = gstack[0]; +				listnode_add(next, newstack); +				break; +			case partly_match: +				trace_matcher("trivial_match\n"); +				if (exact_match_exists && !last_token) +					break; +			case exact_match: +				trace_matcher("exact_match\n"); +				if (last_token) { +					newstack = XMALLOC( +						MTYPE_CMD_MATCHSTACK, +						sizeof(struct graph_node *)); +					/* same as above, not recursing on this +					 */ +					newstack[0] = gstack[0]; +					listnode_add(next, newstack); +				} else if (matchtype >= minmatch) +					add_nexthops(next, gstack[0], gstack, +						     idx + 1); +				break; +			default: +				trace_matcher("no_match\n"); +				break; +			} +		} +	} + +	/* Variable summary +	 * ----------------------------------------------------------------- +	 * token    = last input token processed +	 * idx      = index in `command` of last token processed +	 * current  = set of all transitions from the previous input token +	 * next     = set of all nodes reachable from all nodes in `matched` +	 */ + +	matcher_rv = idx == vector_active(vline) && next->count +			     ? MATCHER_OK +			     : MATCHER_NO_MATCH; + +	*completions = NULL; +	if (!MATCHER_ERROR(matcher_rv)) { +		// extract cmd_token into list +		*completions = list_new(); +		for (ALL_LIST_ELEMENTS_RO(next, node, gstack)) { +			listnode_add(*completions, gstack[0]->data); +		} +	} + +	list_delete(current); +	list_delete(next); + +	return matcher_rv;  }  /** @@ -469,48 +464,43 @@ command_complete (struct graph *graph,   * NB: non-null "stack" means that new stacks will be added to "list" as   * output, instead of direct node pointers!   */ -static int -add_nexthops (struct list *list, struct graph_node *node, -              struct graph_node **stack, size_t stackpos) +static int add_nexthops(struct list *list, struct graph_node *node, +			struct graph_node **stack, size_t stackpos)  { -  int added = 0; -  struct graph_node *child; -  struct graph_node **nextstack; -  for (unsigned int i = 0; i < vector_active (node->to); i++) -    { -      child = vector_slot (node->to, i); -      size_t j; -      struct cmd_token *token = child->data; -      if (!token->allowrepeat && stack) -        { -          for (j = 0; j < stackpos; j++) -            if (child == stack[j]) -              break; -          if (j != stackpos) -            continue; -        } -      if (token->type >= SPECIAL_TKN && token->type != END_TKN) -        { -          added += add_nexthops (list, child, stack, stackpos); -        } -      else -        { -          if (stack) -            { -              nextstack = XMALLOC (MTYPE_CMD_MATCHSTACK, -                                   (stackpos + 1) * sizeof(struct graph_node *)); -              nextstack[0] = child; -              memcpy(nextstack + 1, stack, stackpos * sizeof(struct graph_node *)); - -              listnode_add (list, nextstack); -            } -          else -            listnode_add (list, child); -          added++; -        } -    } - -  return added; +	int added = 0; +	struct graph_node *child; +	struct graph_node **nextstack; +	for (unsigned int i = 0; i < vector_active(node->to); i++) { +		child = vector_slot(node->to, i); +		size_t j; +		struct cmd_token *token = child->data; +		if (!token->allowrepeat && stack) { +			for (j = 0; j < stackpos; j++) +				if (child == stack[j]) +					break; +			if (j != stackpos) +				continue; +		} +		if (token->type >= SPECIAL_TKN && token->type != END_TKN) { +			added += add_nexthops(list, child, stack, stackpos); +		} else { +			if (stack) { +				nextstack = XMALLOC( +					MTYPE_CMD_MATCHSTACK, +					(stackpos + 1) +						* sizeof(struct graph_node *)); +				nextstack[0] = child; +				memcpy(nextstack + 1, stack, +				       stackpos * sizeof(struct graph_node *)); + +				listnode_add(list, nextstack); +			} else +				listnode_add(list, child); +			added++; +		} +	} + +	return added;  }  /** @@ -520,20 +510,18 @@ add_nexthops (struct list *list, struct graph_node *node,   * @param[in] type node type   * @return minimum match level needed to for a token to fully match   */ -static enum match_type -min_match_level (enum cmd_token_type type) +static enum match_type min_match_level(enum cmd_token_type type)  { -  switch (type) -    { -      // anything matches a start node, for the sake of recursion -      case START_TKN: -        return no_match; -      // allowing words to partly match enables command abbreviation -      case WORD_TKN: -        return partly_match; -      default: -        return exact_match; -    } +	switch (type) { +	// anything matches a start node, for the sake of recursion +	case START_TKN: +		return no_match; +	// allowing words to partly match enables command abbreviation +	case WORD_TKN: +		return partly_match; +	default: +		return exact_match; +	}  }  /** @@ -542,26 +530,24 @@ min_match_level (enum cmd_token_type type)   * @param[in] type node type to score   * @return precedence score   */ -static int -score_precedence (enum cmd_token_type type) +static int score_precedence(enum cmd_token_type type)  { -  switch (type) -    { -      // some of these are mutually exclusive, so they share -      // the same precedence value -      case IPV4_TKN: -      case IPV4_PREFIX_TKN: -      case IPV6_TKN: -      case IPV6_PREFIX_TKN: -      case RANGE_TKN: -        return 2; -      case WORD_TKN: -        return 3; -      case VARIABLE_TKN: -        return 4; -      default: -        return 10; -    } +	switch (type) { +	// some of these are mutually exclusive, so they share +	// the same precedence value +	case IPV4_TKN: +	case IPV4_PREFIX_TKN: +	case IPV6_TKN: +	case IPV6_PREFIX_TKN: +	case RANGE_TKN: +		return 2; +	case WORD_TKN: +		return 3; +	case VARIABLE_TKN: +		return 4; +	default: +		return 10; +	}  }  /** @@ -572,29 +558,27 @@ score_precedence (enum cmd_token_type type)   * @param[in] token the token being matched   * @return the best-matching node, or NULL if the two are entirely ambiguous   */ -static struct cmd_token * -disambiguate_tokens (struct cmd_token *first, -                     struct cmd_token *second, -                     char *input_token) +static struct cmd_token *disambiguate_tokens(struct cmd_token *first, +					     struct cmd_token *second, +					     char *input_token)  { -  // if the types are different, simply go off of type precedence -  if (first->type != second->type) -    { -      int firstprec = score_precedence (first->type); -      int secndprec = score_precedence (second->type); -      if (firstprec != secndprec) -        return firstprec < secndprec ? first : second; -      else -        return NULL; -    } - -  // if they're the same, return the more exact match -  enum match_type fmtype = match_token (first, input_token); -  enum match_type smtype = match_token (second, input_token); -  if (fmtype != smtype) -    return fmtype > smtype ? first : second; - -  return NULL; +	// if the types are different, simply go off of type precedence +	if (first->type != second->type) { +		int firstprec = score_precedence(first->type); +		int secndprec = score_precedence(second->type); +		if (firstprec != secndprec) +			return firstprec < secndprec ? first : second; +		else +			return NULL; +	} + +	// if they're the same, return the more exact match +	enum match_type fmtype = match_token(first, input_token); +	enum match_type smtype = match_token(second, input_token); +	if (fmtype != smtype) +		return fmtype > smtype ? first : second; + +	return NULL;  }  /** @@ -606,35 +590,29 @@ disambiguate_tokens (struct cmd_token *first,   * @param[in] n index into vline to start comparing at   * @return the best-matching list, or NULL if the two are entirely ambiguous   */ -static struct list * -disambiguate (struct list *first, -              struct list *second, -              vector vline, -              unsigned int n) +static struct list *disambiguate(struct list *first, struct list *second, +				 vector vline, unsigned int n)  { -  // doesn't make sense for these to be inequal length -  assert (first->count == second->count); -  assert (first->count == vector_active (vline) - n+1); - -  struct listnode *fnode = listhead (first), -                  *snode = listhead (second); -  struct cmd_token *ftok = listgetdata (fnode), -                     *stok = listgetdata (snode), -                     *best = NULL; - -  // compare each token, if one matches better use that one -  for (unsigned int i = n; i < vector_active (vline); i++) -    { -      char *token = vector_slot(vline, i); -      if ((best = disambiguate_tokens (ftok, stok, token))) -        return best == ftok ? first : second; -      fnode = listnextnode (fnode); -      snode = listnextnode (snode); -      ftok = listgetdata (fnode); -      stok = listgetdata (snode); -    } - -  return NULL; +	// doesn't make sense for these to be inequal length +	assert(first->count == second->count); +	assert(first->count == vector_active(vline) - n + 1); + +	struct listnode *fnode = listhead(first), *snode = listhead(second); +	struct cmd_token *ftok = listgetdata(fnode), *stok = listgetdata(snode), +			 *best = NULL; + +	// compare each token, if one matches better use that one +	for (unsigned int i = n; i < vector_active(vline); i++) { +		char *token = vector_slot(vline, i); +		if ((best = disambiguate_tokens(ftok, stok, token))) +			return best == ftok ? first : second; +		fnode = listnextnode(fnode); +		snode = listnextnode(snode); +		ftok = listgetdata(fnode); +		stok = listgetdata(snode); +	} + +	return NULL;  }  /* @@ -648,179 +626,165 @@ disambiguate (struct list *first,   *   * @param list the arglist to delete   */ -static void -del_arglist (struct list *list) +static void del_arglist(struct list *list)  { -  // manually delete last node -  struct listnode *tail = listtail (list); -  tail->data = NULL; -  list_delete_node (list, tail); +	// manually delete last node +	struct listnode *tail = listtail(list); +	tail->data = NULL; +	list_delete_node(list, tail); -  // delete the rest of the list as usual -  list_delete (list); +	// delete the rest of the list as usual +	list_delete(list);  }  /*---------- token level matching functions ----------*/ -static enum match_type -match_token (struct cmd_token *token, char *input_token) +static enum match_type match_token(struct cmd_token *token, char *input_token)  { -  // nothing trivially matches everything -  if (!input_token) -    return trivial_match; - -  switch (token->type) { -    case WORD_TKN: -      return match_word (token, input_token); -    case IPV4_TKN: -      return match_ipv4 (input_token); -    case IPV4_PREFIX_TKN: -      return match_ipv4_prefix (input_token); -    case IPV6_TKN: -      return match_ipv6 (input_token); -    case IPV6_PREFIX_TKN: -      return match_ipv6_prefix (input_token); -    case RANGE_TKN: -      return match_range (token, input_token); -    case VARIABLE_TKN: -      return match_variable (token, input_token); -    case END_TKN: -    default: -      return no_match; -  } +	// nothing trivially matches everything +	if (!input_token) +		return trivial_match; + +	switch (token->type) { +	case WORD_TKN: +		return match_word(token, input_token); +	case IPV4_TKN: +		return match_ipv4(input_token); +	case IPV4_PREFIX_TKN: +		return match_ipv4_prefix(input_token); +	case IPV6_TKN: +		return match_ipv6(input_token); +	case IPV6_PREFIX_TKN: +		return match_ipv6_prefix(input_token); +	case RANGE_TKN: +		return match_range(token, input_token); +	case VARIABLE_TKN: +		return match_variable(token, input_token); +	case END_TKN: +	default: +		return no_match; +	}  }  #define IPV4_ADDR_STR   "0123456789."  #define IPV4_PREFIX_STR "0123456789./" -static enum match_type -match_ipv4 (const char *str) +static enum match_type match_ipv4(const char *str)  { -  const char *sp; -  int dots = 0, nums = 0; -  char buf[4]; +	const char *sp; +	int dots = 0, nums = 0; +	char buf[4]; + +	for (;;) { +		memset(buf, 0, sizeof(buf)); +		sp = str; +		while (*str != '\0') { +			if (*str == '.') { +				if (dots >= 3) +					return no_match; + +				if (*(str + 1) == '.') +					return no_match; + +				if (*(str + 1) == '\0') +					return partly_match; + +				dots++; +				break; +			} +			if (!isdigit((int)*str)) +				return no_match; + +			str++; +		} + +		if (str - sp > 3) +			return no_match; -  for (;;) -    { -      memset (buf, 0, sizeof (buf)); -      sp = str; -      while (*str != '\0') -        { -          if (*str == '.') -            { -              if (dots >= 3) -                return no_match; +		strncpy(buf, sp, str - sp); +		if (atoi(buf) > 255) +			return no_match; -              if (*(str + 1) == '.') -                return no_match; +		nums++; -              if (*(str + 1) == '\0') -                return partly_match; +		if (*str == '\0') +			break; + +		str++; +	} -              dots++; -              break; -            } -          if (!isdigit ((int) *str)) -            return no_match; +	if (nums < 4) +		return partly_match; -          str++; -        } +	return exact_match; +} -      if (str - sp > 3) -        return no_match; +static enum match_type match_ipv4_prefix(const char *str) +{ +	const char *sp; +	int dots = 0; +	char buf[4]; -      strncpy (buf, sp, str - sp); -      if (atoi (buf) > 255) -        return no_match; +	for (;;) { +		memset(buf, 0, sizeof(buf)); +		sp = str; +		while (*str != '\0' && *str != '/') { +			if (*str == '.') { +				if (dots == 3) +					return no_match; -      nums++; +				if (*(str + 1) == '.' || *(str + 1) == '/') +					return no_match; -      if (*str == '\0') -        break; +				if (*(str + 1) == '\0') +					return partly_match; -      str++; -    } +				dots++; +				break; +			} -  if (nums < 4) -    return partly_match; +			if (!isdigit((int)*str)) +				return no_match; -  return exact_match; -} +			str++; +		} -static enum match_type -match_ipv4_prefix (const char *str) -{ -  const char *sp; -  int dots = 0; -  char buf[4]; - -  for (;;) -    { -      memset (buf, 0, sizeof (buf)); -      sp = str; -      while (*str != '\0' && *str != '/') -        { -          if (*str == '.') -            { -              if (dots == 3) -                return no_match; - -              if (*(str + 1) == '.' || *(str + 1) == '/') -                return no_match; - -              if (*(str + 1) == '\0') -                return partly_match; - -              dots++; -              break; -            } - -          if (!isdigit ((int) *str)) -            return no_match; - -          str++; -        } - -      if (str - sp > 3) -        return no_match; - -      strncpy (buf, sp, str - sp); -      if (atoi (buf) > 255) -        return no_match; - -      if (dots == 3) -        { -          if (*str == '/') -            { -              if (*(str + 1) == '\0') -                return partly_match; - -              str++; -              break; -            } -          else if (*str == '\0') -            return partly_match; -        } - -      if (*str == '\0') -        return partly_match; - -      str++; -    } - -  sp = str; -  while (*str != '\0') -    { -      if (!isdigit ((int) *str)) -        return no_match; - -      str++; -    } - -  if (atoi (sp) > 32) -    return no_match; - -  return exact_match; +		if (str - sp > 3) +			return no_match; + +		strncpy(buf, sp, str - sp); +		if (atoi(buf) > 255) +			return no_match; + +		if (dots == 3) { +			if (*str == '/') { +				if (*(str + 1) == '\0') +					return partly_match; + +				str++; +				break; +			} else if (*str == '\0') +				return partly_match; +		} + +		if (*str == '\0') +			return partly_match; + +		str++; +	} + +	sp = str; +	while (*str != '\0') { +		if (!isdigit((int)*str)) +			return no_match; + +		str++; +	} + +	if (atoi(sp) > 32) +		return no_match; + +	return exact_match;  } @@ -834,194 +798,180 @@ match_ipv4_prefix (const char *str)  #define STATE_SLASH     6  #define STATE_MASK      7 -static enum match_type -match_ipv6 (const char *str) +static enum match_type match_ipv6(const char *str)  { -  struct sockaddr_in6 sin6_dummy; -  int ret; +	struct sockaddr_in6 sin6_dummy; +	int ret; -  if (strspn (str, IPV6_ADDR_STR) != strlen (str)) -    return no_match; +	if (strspn(str, IPV6_ADDR_STR) != strlen(str)) +		return no_match; -  ret = inet_pton(AF_INET6, str, &sin6_dummy.sin6_addr); +	ret = inet_pton(AF_INET6, str, &sin6_dummy.sin6_addr); -  if (ret == 1) -    return exact_match; +	if (ret == 1) +		return exact_match; -  return no_match; +	return no_match;  } -static enum match_type -match_ipv6_prefix (const char *str) +static enum match_type match_ipv6_prefix(const char *str)  { -  int state = STATE_START; -  int colons = 0, nums = 0, double_colon = 0; -  int mask; -  const char *sp = NULL; -  char *endptr = NULL; +	int state = STATE_START; +	int colons = 0, nums = 0, double_colon = 0; +	int mask; +	const char *sp = NULL; +	char *endptr = NULL; -  if (str == NULL) -    return partly_match; +	if (str == NULL) +		return partly_match; -  if (strspn (str, IPV6_PREFIX_STR) != strlen (str)) -    return no_match; - -  while (*str != '\0' && state != STATE_MASK) -    { -      switch (state) -	{ -	case STATE_START: -	  if (*str == ':') -	    { -	      if (*(str + 1) != ':' && *(str + 1) != '\0') -		return no_match; -	      colons--; -	      state = STATE_COLON; -	    } -	  else -	    { -	      sp = str; -	      state = STATE_ADDR; -	    } - -	  continue; -	case STATE_COLON: -	  colons++; -	  if (*(str + 1) == '/') -	    return no_match; -	  else if (*(str + 1) == ':') -	    state = STATE_DOUBLE; -	  else -	    { -	      sp = str + 1; -	      state = STATE_ADDR; -	    } -	  break; -	case STATE_DOUBLE: -	  if (double_colon) -	    return no_match; - -	  if (*(str + 1) == ':') -	    return no_match; -	  else -	    { -	      if (*(str + 1) != '\0' && *(str + 1) != '/') -		colons++; -	      sp = str + 1; - -	      if (*(str + 1) == '/') -		state = STATE_SLASH; -	      else -		state = STATE_ADDR; -	    } - -	  double_colon++; -	  nums += 1; -	  break; -	case STATE_ADDR: -	  if (*(str + 1) == ':' || *(str + 1) == '.' -	      || *(str + 1) == '\0' || *(str + 1) == '/') -	    { -	      if (str - sp > 3) +	if (strspn(str, IPV6_PREFIX_STR) != strlen(str))  		return no_match; -	      for (; sp <= str; sp++) -		if (*sp == '/') -		  return no_match; - -	      nums++; - -	      if (*(str + 1) == ':') -		state = STATE_COLON; -	      else if (*(str + 1) == '.') -		{ -		  if (colons || double_colon) -		    state = STATE_DOT; -		  else -		    return no_match; +	while (*str != '\0' && state != STATE_MASK) { +		switch (state) { +		case STATE_START: +			if (*str == ':') { +				if (*(str + 1) != ':' && *(str + 1) != '\0') +					return no_match; +				colons--; +				state = STATE_COLON; +			} else { +				sp = str; +				state = STATE_ADDR; +			} + +			continue; +		case STATE_COLON: +			colons++; +			if (*(str + 1) == '/') +				return no_match; +			else if (*(str + 1) == ':') +				state = STATE_DOUBLE; +			else { +				sp = str + 1; +				state = STATE_ADDR; +			} +			break; +		case STATE_DOUBLE: +			if (double_colon) +				return no_match; + +			if (*(str + 1) == ':') +				return no_match; +			else { +				if (*(str + 1) != '\0' && *(str + 1) != '/') +					colons++; +				sp = str + 1; + +				if (*(str + 1) == '/') +					state = STATE_SLASH; +				else +					state = STATE_ADDR; +			} + +			double_colon++; +			nums += 1; +			break; +		case STATE_ADDR: +			if (*(str + 1) == ':' || *(str + 1) == '.' +			    || *(str + 1) == '\0' || *(str + 1) == '/') { +				if (str - sp > 3) +					return no_match; + +				for (; sp <= str; sp++) +					if (*sp == '/') +						return no_match; + +				nums++; + +				if (*(str + 1) == ':') +					state = STATE_COLON; +				else if (*(str + 1) == '.') { +					if (colons || double_colon) +						state = STATE_DOT; +					else +						return no_match; +				} else if (*(str + 1) == '/') +					state = STATE_SLASH; +			} +			break; +		case STATE_DOT: +			state = STATE_ADDR; +			break; +		case STATE_SLASH: +			if (*(str + 1) == '\0') +				return partly_match; + +			state = STATE_MASK; +			break; +		default: +			break;  		} -	      else if (*(str + 1) == '/') -		state = STATE_SLASH; -	    } -	  break; -	case STATE_DOT: -	  state = STATE_ADDR; -	  break; -	case STATE_SLASH: -	  if (*(str + 1) == '\0') -	    return partly_match; - -	  state = STATE_MASK; -	  break; -	default: -	  break; -	} -      if (nums > 11) -	return no_match; +		if (nums > 11) +			return no_match; -      if (colons > 7) -	return no_match; +		if (colons > 7) +			return no_match; -      str++; -    } +		str++; +	} -  if (state < STATE_MASK) -    return partly_match; +	if (state < STATE_MASK) +		return partly_match; -  mask = strtol (str, &endptr, 10); -  if (*endptr != '\0') -    return no_match; +	mask = strtol(str, &endptr, 10); +	if (*endptr != '\0') +		return no_match; -  if (mask < 0 || mask > 128) -    return no_match; +	if (mask < 0 || mask > 128) +		return no_match; -  return exact_match; +	return exact_match;  } -static enum match_type -match_range (struct cmd_token *token, const char *str) +static enum match_type match_range(struct cmd_token *token, const char *str)  { -  assert (token->type == RANGE_TKN); +	assert(token->type == RANGE_TKN); -  char *endptr = NULL; -  long long val; +	char *endptr = NULL; +	long long val; -  val = strtoll (str, &endptr, 10); -  if (*endptr != '\0') -    return no_match; +	val = strtoll(str, &endptr, 10); +	if (*endptr != '\0') +		return no_match; -  if (val < token->min || val > token->max) -    return no_match; -  else -    return exact_match; +	if (val < token->min || val > token->max) +		return no_match; +	else +		return exact_match;  } -static enum match_type -match_word (struct cmd_token *token, const char *word) +static enum match_type match_word(struct cmd_token *token, const char *word)  { -  assert (token->type == WORD_TKN); +	assert(token->type == WORD_TKN); -  // if the passed token is 0 length, partly match -  if (!strlen(word)) -    return partly_match; +	// if the passed token is 0 length, partly match +	if (!strlen(word)) +		return partly_match; -  // if the passed token is strictly a prefix of the full word, partly match -  if (strlen (word) < strlen (token->text)) -    return !strncmp (token->text, word, strlen (word)) ? -       partly_match : -       no_match; +	// if the passed token is strictly a prefix of the full word, partly +	// match +	if (strlen(word) < strlen(token->text)) +		return !strncmp(token->text, word, strlen(word)) ? partly_match +								 : no_match; -  // if they are the same length and exactly equal, exact match -  else if (strlen (word) == strlen (token->text)) -    return !strncmp (token->text, word, strlen (word)) ? exact_match : no_match; +	// if they are the same length and exactly equal, exact match +	else if (strlen(word) == strlen(token->text)) +		return !strncmp(token->text, word, strlen(word)) ? exact_match +								 : no_match; -  return no_match; +	return no_match;  } -static enum match_type -match_variable (struct cmd_token *token, const char *word) +static enum match_type match_variable(struct cmd_token *token, const char *word)  { -  assert (token->type == VARIABLE_TKN); -  return exact_match; +	assert(token->type == VARIABLE_TKN); +	return exact_match;  } diff --git a/lib/command_match.h b/lib/command_match.h index 9e18b8d905..3e274d22e2 100644 --- a/lib/command_match.h +++ b/lib/command_match.h @@ -32,38 +32,31 @@  /* These definitions exist in command.c in the current engine but should be   * relocated here in the new engine   */ -enum filter_type -{ -  FILTER_RELAXED, -  FILTER_STRICT -}; +enum filter_type { FILTER_RELAXED, FILTER_STRICT };  /* matcher result value */ -enum matcher_rv -{ -  MATCHER_NO_MATCH, -  MATCHER_INCOMPLETE, -  MATCHER_AMBIGUOUS, -  MATCHER_OK, +enum matcher_rv { +	MATCHER_NO_MATCH, +	MATCHER_INCOMPLETE, +	MATCHER_AMBIGUOUS, +	MATCHER_OK,  };  /* completion match types */ -enum match_type -{ -  trivial_match,  // the input is null -  no_match,       // the input does not match -  partly_match,   // the input matches but is incomplete -  exact_match     // the input matches and is complete +enum match_type { +	trivial_match, // the input is null +	no_match,      // the input does not match +	partly_match,  // the input matches but is incomplete +	exact_match    // the input matches and is complete  };  /* Defines which matcher_rv values constitute an error. Should be used with   * matcher_rv return values to do basic error checking.   */ -#define MATCHER_ERROR(matcher_rv) \ -  (   (matcher_rv) == MATCHER_INCOMPLETE \ -   || (matcher_rv) == MATCHER_NO_MATCH \ -   || (matcher_rv) == MATCHER_AMBIGUOUS \ -  ) +#define MATCHER_ERROR(matcher_rv)                                              \ +	((matcher_rv) == MATCHER_INCOMPLETE                                    \ +	 || (matcher_rv) == MATCHER_NO_MATCH                                   \ +	 || (matcher_rv) == MATCHER_AMBIGUOUS)  /**   * Attempt to find an exact command match for a line of user input. @@ -80,11 +73,9 @@ enum match_type   * safely deleted or modified; it is the instance initialized on startup.   * @return matcher status   */ -enum matcher_rv -command_match (struct graph *cmdgraph, -               vector vline, -               struct list **argv, -               const struct cmd_element **element); +enum matcher_rv command_match(struct graph *cmdgraph, vector vline, +			      struct list **argv, +			      const struct cmd_element **element);  /**   * Compiles possible completions for a given line of user input. @@ -105,9 +96,7 @@ command_match (struct graph *cmdgraph,   * of that element (e.g. 'encapv4', 'encapv6', etc for input 'en').   * @return matcher status   */ -enum matcher_rv -command_complete (struct graph *cmdgraph, -                  vector vline, -                  struct list **completions); +enum matcher_rv command_complete(struct graph *cmdgraph, vector vline, +				 struct list **completions);  #endif /* _ZEBRA_COMMAND_MATCH_H */ @@ -31,690 +31,665 @@  #define DEBUG_E 1  #define DEBUG_V 1 -#define log_error(fmt, ...) \ -  do { if (DEBUG_E) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \ -			    __LINE__, __func__, ##__VA_ARGS__); } while (0) - -#define log_verbose(fmt, ...) \ -  do { if (DEBUG_V) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \ -			    __LINE__, __func__, __VA_ARGS__); } while (0) +#define log_error(fmt, ...)                                                    \ +	do {                                                                   \ +		if (DEBUG_E)                                                   \ +			fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__,          \ +				__LINE__, __func__, ##__VA_ARGS__);            \ +	} while (0) + +#define log_verbose(fmt, ...)                                                  \ +	do {                                                                   \ +		if (DEBUG_V)                                                   \ +			fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__,          \ +				__LINE__, __func__, __VA_ARGS__);              \ +	} while (0)  struct _csv_field_t_ { -  TAILQ_ENTRY(_csv_field_t_) next_field; -  char *field; -  int field_len; +	TAILQ_ENTRY(_csv_field_t_) next_field; +	char *field; +	int field_len;  };  struct _csv_record_t_ { -  TAILQ_HEAD(, _csv_field_t_) fields; -  TAILQ_ENTRY(_csv_record_t_) next_record; -  char *record; -  int rec_len; +	TAILQ_HEAD(, _csv_field_t_) fields; +	TAILQ_ENTRY(_csv_record_t_) next_record; +	char *record; +	int rec_len;  };  struct _csv_t_ { -  TAILQ_HEAD(, _csv_record_t_) records; -  char *buf; -  int buflen; -  int csv_len; -  int pointer; -  int num_recs; +	TAILQ_HEAD(, _csv_record_t_) records; +	char *buf; +	int buflen; +	int csv_len; +	int pointer; +	int num_recs;  }; -int -csvlen (csv_t *csv) +int csvlen(csv_t *csv)  { -  return (csv->csv_len); +	return (csv->csv_len);  } -csv_t * -csv_init (csv_t *csv, -	  char *buf, -	  int buflen) +csv_t *csv_init(csv_t *csv, char *buf, int buflen)  { -  if (csv == NULL) { -    csv = malloc(sizeof(csv_t)); -    if (csv == NULL) { -      log_error("CSV Malloc failed\n"); -      return (NULL); -    } -  } -  memset(csv, 0, sizeof(csv_t)); - -  csv->buf = buf; -  csv->buflen = buflen; -  TAILQ_INIT(&(csv->records)); -  return (csv); +	if (csv == NULL) { +		csv = malloc(sizeof(csv_t)); +		if (csv == NULL) { +			log_error("CSV Malloc failed\n"); +			return (NULL); +		} +	} +	memset(csv, 0, sizeof(csv_t)); + +	csv->buf = buf; +	csv->buflen = buflen; +	TAILQ_INIT(&(csv->records)); +	return (csv);  } -void -csv_clean (csv_t *csv) +void csv_clean(csv_t *csv)  { -  csv_record_t *rec; -  csv_record_t *rec_n; - -  rec = TAILQ_FIRST(&(csv->records)); -  while (rec != NULL) { -    rec_n = TAILQ_NEXT(rec, next_record); -    csv_remove_record(csv, rec); -    rec = rec_n; -  } +	csv_record_t *rec; +	csv_record_t *rec_n; + +	rec = TAILQ_FIRST(&(csv->records)); +	while (rec != NULL) { +		rec_n = TAILQ_NEXT(rec, next_record); +		csv_remove_record(csv, rec); +		rec = rec_n; +	}  } -void -csv_free (csv_t *csv) +void csv_free(csv_t *csv)  { -  if (csv != NULL) { -    free(csv); -  } +	if (csv != NULL) { +		free(csv); +	}  } -static void -csv_init_record (csv_record_t *record) +static void csv_init_record(csv_record_t *record)  { -  TAILQ_INIT(&(record->fields)); -  record->rec_len = 0; +	TAILQ_INIT(&(record->fields)); +	record->rec_len = 0;  } -csv_record_t * -csv_record_iter (csv_t *csv) +csv_record_t *csv_record_iter(csv_t *csv)  { -  return(TAILQ_FIRST(&(csv->records))); +	return (TAILQ_FIRST(&(csv->records)));  } -csv_record_t * -csv_record_iter_next (csv_record_t *rec) +csv_record_t *csv_record_iter_next(csv_record_t *rec)  { -  if(!rec) return NULL; -  return(TAILQ_NEXT(rec, next_record)); +	if (!rec) +		return NULL; +	return (TAILQ_NEXT(rec, next_record));  } -char * -csv_field_iter (csv_record_t *rec, -		csv_field_t **fld) +char *csv_field_iter(csv_record_t *rec, csv_field_t **fld)  { -  if(!rec) return NULL; -  *fld = TAILQ_FIRST(&(rec->fields)); -  return ((*fld)->field); +	if (!rec) +		return NULL; +	*fld = TAILQ_FIRST(&(rec->fields)); +	return ((*fld)->field);  } -char * -csv_field_iter_next (csv_field_t **fld) +char *csv_field_iter_next(csv_field_t **fld)  { -  *fld = TAILQ_NEXT(*fld, next_field); -  if ((*fld) == NULL) { -    return (NULL); -  } -  return ((*fld)->field); +	*fld = TAILQ_NEXT(*fld, next_field); +	if ((*fld) == NULL) { +		return (NULL); +	} +	return ((*fld)->field);  } -int -csv_field_len(csv_field_t *fld) +int csv_field_len(csv_field_t *fld)  { -  if (fld) { -    return fld->field_len; -  } -  return 0; +	if (fld) { +		return fld->field_len; +	} +	return 0;  } -static void -csv_decode_record(csv_record_t *rec) +static void csv_decode_record(csv_record_t *rec)  { -    char *curr = rec->record; -    char *field; -    csv_field_t *fld; - -    field = strpbrk(curr, ","); -    while (field != NULL) { -        fld = malloc(sizeof(csv_field_t)); -        if (fld) { -            TAILQ_INSERT_TAIL(&(rec->fields), fld, next_field); -            fld->field = curr; -            fld->field_len = field-curr; -        } -        curr = field + 1; -        field = strpbrk(curr, ","); -    } -    field = strstr(curr, "\n"); -    if (!field) -        return; - -    fld = malloc(sizeof(csv_field_t)); -    if (fld) { -        fld->field = curr; -        fld->field_len = field-curr; -        TAILQ_INSERT_TAIL(&(rec->fields), fld, next_field); -    } +	char *curr = rec->record; +	char *field; +	csv_field_t *fld; + +	field = strpbrk(curr, ","); +	while (field != NULL) { +		fld = malloc(sizeof(csv_field_t)); +		if (fld) { +			TAILQ_INSERT_TAIL(&(rec->fields), fld, next_field); +			fld->field = curr; +			fld->field_len = field - curr; +		} +		curr = field + 1; +		field = strpbrk(curr, ","); +	} +	field = strstr(curr, "\n"); +	if (!field) +		return; + +	fld = malloc(sizeof(csv_field_t)); +	if (fld) { +		fld->field = curr; +		fld->field_len = field - curr; +		TAILQ_INSERT_TAIL(&(rec->fields), fld, next_field); +	}  } -static csv_field_t * -csv_add_field_to_record(csv_t *csv, -                        csv_record_t *rec, -                        char *col) +static csv_field_t *csv_add_field_to_record(csv_t *csv, csv_record_t *rec, +					    char *col)  { -    csv_field_t *fld; -    char *str = rec->record; -    int rlen = rec->rec_len; -    int blen = csv->buflen; - -    fld = malloc(sizeof(csv_field_t)); -    if (!fld) { -        log_error("field malloc failed\n"); -        /* more cleanup needed */ -        return (NULL); -    } -    TAILQ_INSERT_TAIL(&(rec->fields), fld, next_field); -    fld->field = str+rlen; -    fld->field_len = snprintf((str+rlen), (blen - rlen), "%s", col); -    rlen += fld->field_len; -    rec->rec_len = rlen; -    return fld; +	csv_field_t *fld; +	char *str = rec->record; +	int rlen = rec->rec_len; +	int blen = csv->buflen; + +	fld = malloc(sizeof(csv_field_t)); +	if (!fld) { +		log_error("field malloc failed\n"); +		/* more cleanup needed */ +		return (NULL); +	} +	TAILQ_INSERT_TAIL(&(rec->fields), fld, next_field); +	fld->field = str + rlen; +	fld->field_len = snprintf((str + rlen), (blen - rlen), "%s", col); +	rlen += fld->field_len; +	rec->rec_len = rlen; +	return fld;  } -csv_record_t * -csv_encode (csv_t *csv, -	    int count, -	    ...) +csv_record_t *csv_encode(csv_t *csv, int count, ...)  { -  int tempc; -  va_list list; -  char *buf = csv->buf; -  int len = csv->buflen; -  int pointer = csv->pointer; -  char *str = NULL; -  char *col; -  csv_record_t *rec; -  csv_field_t *fld; - -  if (buf) { -     str = buf + pointer; -  } else { -     /* allocate sufficient buffer */ -     str = (char *)malloc(csv->buflen); -     if (!str) { -        log_error("field str malloc failed\n"); -        return (NULL); -     } -  } - -  va_start(list, count); -  rec = malloc(sizeof(csv_record_t)); -  if (!rec) { -    log_error("record malloc failed\n"); -    if (!buf) -      free(str); -    va_end(list); -    return (NULL); -  } -  csv_init_record(rec); -  rec->record = str; -  TAILQ_INSERT_TAIL(&(csv->records), rec, next_record); -  csv->num_recs++; - -  /** -   * Iterate through the fields passed as a variable list and add them -   */ -  for (tempc = 0; tempc < count; tempc++) { -    col = va_arg(list, char *); -    fld = csv_add_field_to_record(csv, rec, col); -    if (!fld) { -      log_error("fld malloc failed\n"); -      csv_remove_record(csv, rec); -      va_end(list); -      return (NULL); -    } -    if (tempc < (count - 1)) { -      rec->rec_len += snprintf((str+rec->rec_len), (len - rec->rec_len), ","); -    } -  } -  rec->rec_len += snprintf((str+rec->rec_len), (len - rec->rec_len), "\n"); -  va_end(list); -  csv->csv_len += rec->rec_len; -  csv->pointer += rec->rec_len; -  return (rec); +	int tempc; +	va_list list; +	char *buf = csv->buf; +	int len = csv->buflen; +	int pointer = csv->pointer; +	char *str = NULL; +	char *col; +	csv_record_t *rec; +	csv_field_t *fld; + +	if (buf) { +		str = buf + pointer; +	} else { +		/* allocate sufficient buffer */ +		str = (char *)malloc(csv->buflen); +		if (!str) { +			log_error("field str malloc failed\n"); +			return (NULL); +		} +	} + +	va_start(list, count); +	rec = malloc(sizeof(csv_record_t)); +	if (!rec) { +		log_error("record malloc failed\n"); +		if (!buf) +			free(str); +		va_end(list); +		return (NULL); +	} +	csv_init_record(rec); +	rec->record = str; +	TAILQ_INSERT_TAIL(&(csv->records), rec, next_record); +	csv->num_recs++; + +	/** +	 * Iterate through the fields passed as a variable list and add them +	 */ +	for (tempc = 0; tempc < count; tempc++) { +		col = va_arg(list, char *); +		fld = csv_add_field_to_record(csv, rec, col); +		if (!fld) { +			log_error("fld malloc failed\n"); +			csv_remove_record(csv, rec); +			va_end(list); +			return (NULL); +		} +		if (tempc < (count - 1)) { +			rec->rec_len += snprintf((str + rec->rec_len), +						 (len - rec->rec_len), ","); +		} +	} +	rec->rec_len += +		snprintf((str + rec->rec_len), (len - rec->rec_len), "\n"); +	va_end(list); +	csv->csv_len += rec->rec_len; +	csv->pointer += rec->rec_len; +	return (rec);  } -int -csv_num_records (csv_t *csv) +int csv_num_records(csv_t *csv)  { -    if (csv) { -        return csv->num_recs; -    } -    return 0; +	if (csv) { +		return csv->num_recs; +	} +	return 0;  } -csv_record_t * -csv_encode_record (csv_t *csv, -		   csv_record_t *rec, -		   int count, -		   ...) +csv_record_t *csv_encode_record(csv_t *csv, csv_record_t *rec, int count, ...)  { -  int tempc; -  va_list list; -  char *str; -  char *col; -  csv_field_t *fld = NULL; -  int i; - -  va_start(list, count); -  str = csv_field_iter(rec, &fld); -  for (tempc = 0; tempc < count; tempc++) { -    col = va_arg(list, char *); -    for (i = 0; i < fld->field_len; i++) { -      str[i] = col[i]; -    } -    str = csv_field_iter_next(&fld); -  } -  va_end(list); -  return (rec); +	int tempc; +	va_list list; +	char *str; +	char *col; +	csv_field_t *fld = NULL; +	int i; + +	va_start(list, count); +	str = csv_field_iter(rec, &fld); +	for (tempc = 0; tempc < count; tempc++) { +		col = va_arg(list, char *); +		for (i = 0; i < fld->field_len; i++) { +			str[i] = col[i]; +		} +		str = csv_field_iter_next(&fld); +	} +	va_end(list); +	return (rec);  } -csv_record_t * -csv_append_record (csv_t *csv, -                   csv_record_t *rec, -                   int count, -                   ...) +csv_record_t *csv_append_record(csv_t *csv, csv_record_t *rec, int count, ...)  { -    int tempc; -    va_list list; -    int len = csv->buflen, tlen; -    char *str; -    csv_field_t *fld; -    char *col; - -    if (csv->buf) { -        /* not only works with discrete bufs */ -        return NULL; -    } - -    if (!rec) { -        /* create a new rec */ -        rec = calloc(1, sizeof(csv_record_t)); -        if (!rec) { -            log_error("record malloc failed\n"); -            return NULL; -        } -        csv_init_record(rec); -        rec->record = calloc(1, csv->buflen); -        if (!rec->record) { -            log_error("field str malloc failed\n"); -            free(rec); -            return NULL; -        } -        csv_insert_record(csv, rec); -    } - -    str = rec->record; - -    va_start(list, count); - -    if (rec->rec_len && (str[rec->rec_len-1] == '\n')) -            str[rec->rec_len-1] = ','; - -    /** -     * Iterate through the fields passed as a variable list and add them -     */ -    tlen = rec->rec_len; -    for (tempc = 0; tempc < count; tempc++) { -        col = va_arg(list, char *); -        fld = csv_add_field_to_record(csv, rec, col); -        if (!fld) { -            log_error("fld malloc failed\n"); -            break; -        } -        if (tempc < (count - 1)) { -            rec->rec_len += snprintf((str+rec->rec_len), -                                     (len - rec->rec_len), ","); -        } -    } -    rec->rec_len += snprintf((str+rec->rec_len), -                             (len - rec->rec_len), "\n"); -    va_end(list); -    csv->csv_len += (rec->rec_len - tlen); -    csv->pointer += (rec->rec_len - tlen); -    return (rec); +	int tempc; +	va_list list; +	int len = csv->buflen, tlen; +	char *str; +	csv_field_t *fld; +	char *col; + +	if (csv->buf) { +		/* not only works with discrete bufs */ +		return NULL; +	} + +	if (!rec) { +		/* create a new rec */ +		rec = calloc(1, sizeof(csv_record_t)); +		if (!rec) { +			log_error("record malloc failed\n"); +			return NULL; +		} +		csv_init_record(rec); +		rec->record = calloc(1, csv->buflen); +		if (!rec->record) { +			log_error("field str malloc failed\n"); +			free(rec); +			return NULL; +		} +		csv_insert_record(csv, rec); +	} + +	str = rec->record; + +	va_start(list, count); + +	if (rec->rec_len && (str[rec->rec_len - 1] == '\n')) +		str[rec->rec_len - 1] = ','; + +	/** +	 * Iterate through the fields passed as a variable list and add them +	 */ +	tlen = rec->rec_len; +	for (tempc = 0; tempc < count; tempc++) { +		col = va_arg(list, char *); +		fld = csv_add_field_to_record(csv, rec, col); +		if (!fld) { +			log_error("fld malloc failed\n"); +			break; +		} +		if (tempc < (count - 1)) { +			rec->rec_len += snprintf((str + rec->rec_len), +						 (len - rec->rec_len), ","); +		} +	} +	rec->rec_len += +		snprintf((str + rec->rec_len), (len - rec->rec_len), "\n"); +	va_end(list); +	csv->csv_len += (rec->rec_len - tlen); +	csv->pointer += (rec->rec_len - tlen); +	return (rec);  } -int -csv_serialize(csv_t *csv, char *msgbuf, int msglen) +int csv_serialize(csv_t *csv, char *msgbuf, int msglen)  { -  csv_record_t *rec; -  int offset = 0; +	csv_record_t *rec; +	int offset = 0; -  if (!csv || !msgbuf) return -1; +	if (!csv || !msgbuf) +		return -1; -  rec = csv_record_iter(csv); -  while (rec != NULL) { -    if ((offset + rec->rec_len) >= msglen) -        return -1; -    offset += sprintf(&msgbuf[offset], "%s", rec->record); -    rec = csv_record_iter_next(rec); -  } +	rec = csv_record_iter(csv); +	while (rec != NULL) { +		if ((offset + rec->rec_len) >= msglen) +			return -1; +		offset += sprintf(&msgbuf[offset], "%s", rec->record); +		rec = csv_record_iter_next(rec); +	} -  return 0; +	return 0;  } -void -csv_clone_record (csv_t *csv, csv_record_t *in_rec, csv_record_t **out_rec) +void csv_clone_record(csv_t *csv, csv_record_t *in_rec, csv_record_t **out_rec)  { -    char *curr; -    csv_record_t *rec; - -    /* first check if rec belongs to this csv */ -    if(!csv_is_record_valid(csv, in_rec)){ -        log_error("rec not in this csv\n"); -        return; -    } - -    /* only works with csv with discrete bufs */ -    if (csv->buf) { -        log_error("un-supported for this csv type - single buf detected\n"); -        return; -    } - -    /* create a new rec */ -    rec = calloc(1, sizeof(csv_record_t)); -    if (!rec) { -        log_error("record malloc failed\n"); -        return; -    } -    csv_init_record(rec); -    curr = calloc(1, csv->buflen); -    if (!curr) { -        log_error("field str malloc failed\n"); -        free(rec); -        return; -    } -    rec->record = curr; -    rec->rec_len = in_rec->rec_len; -    strcpy(rec->record, in_rec->record); - -    /* decode record into fields */ -    csv_decode_record(rec); - -    *out_rec = rec; +	char *curr; +	csv_record_t *rec; + +	/* first check if rec belongs to this csv */ +	if (!csv_is_record_valid(csv, in_rec)) { +		log_error("rec not in this csv\n"); +		return; +	} + +	/* only works with csv with discrete bufs */ +	if (csv->buf) { +		log_error( +			"un-supported for this csv type - single buf detected\n"); +		return; +	} + +	/* create a new rec */ +	rec = calloc(1, sizeof(csv_record_t)); +	if (!rec) { +		log_error("record malloc failed\n"); +		return; +	} +	csv_init_record(rec); +	curr = calloc(1, csv->buflen); +	if (!curr) { +		log_error("field str malloc failed\n"); +		free(rec); +		return; +	} +	rec->record = curr; +	rec->rec_len = in_rec->rec_len; +	strcpy(rec->record, in_rec->record); + +	/* decode record into fields */ +	csv_decode_record(rec); + +	*out_rec = rec;  } -void -csv_remove_record (csv_t *csv, csv_record_t *rec) +void csv_remove_record(csv_t *csv, csv_record_t *rec)  { -  csv_field_t *fld, *p_fld; - -  /* first check if rec belongs to this csv */ -  if(!csv_is_record_valid(csv, rec)){ -    log_error("rec not in this csv\n"); -    return; -  } - -  /* remove fields */ -  csv_field_iter(rec, &fld); -  while(fld) { -    p_fld = fld; -    csv_field_iter_next(&fld); -    TAILQ_REMOVE(&(rec->fields), p_fld, next_field); -    free(p_fld); -  } - -  TAILQ_REMOVE(&(csv->records), rec, next_record); - -  csv->num_recs--; -  csv->csv_len -= rec->rec_len; -  csv->pointer -= rec->rec_len; -  if (!csv->buf) -    free(rec->record); -  free(rec); +	csv_field_t *fld, *p_fld; + +	/* first check if rec belongs to this csv */ +	if (!csv_is_record_valid(csv, rec)) { +		log_error("rec not in this csv\n"); +		return; +	} + +	/* remove fields */ +	csv_field_iter(rec, &fld); +	while (fld) { +		p_fld = fld; +		csv_field_iter_next(&fld); +		TAILQ_REMOVE(&(rec->fields), p_fld, next_field); +		free(p_fld); +	} + +	TAILQ_REMOVE(&(csv->records), rec, next_record); + +	csv->num_recs--; +	csv->csv_len -= rec->rec_len; +	csv->pointer -= rec->rec_len; +	if (!csv->buf) +		free(rec->record); +	free(rec);  } -void -csv_insert_record (csv_t *csv, csv_record_t *rec) +void csv_insert_record(csv_t *csv, csv_record_t *rec)  { -  /* first check if rec already in csv */ -  if(csv_is_record_valid(csv, rec)){ -    log_error("rec already in this csv\n"); -    return; -  } - -  /* we can only insert records if no buf was supplied during csv init */ -  if (csv->buf) { -    log_error("un-supported for this csv type - single buf detected\n"); -    return; -  } - -  /* do we go beyond the max buf set for this csv ?*/ -  if ((csv->csv_len + rec->rec_len) > csv->buflen ) { -    log_error("cannot insert - exceeded buf size\n"); -    return; -  } - -  TAILQ_INSERT_TAIL(&(csv->records), rec, next_record); -  csv->num_recs++; -  csv->csv_len += rec->rec_len; -  csv->pointer += rec->rec_len; +	/* first check if rec already in csv */ +	if (csv_is_record_valid(csv, rec)) { +		log_error("rec already in this csv\n"); +		return; +	} + +	/* we can only insert records if no buf was supplied during csv init */ +	if (csv->buf) { +		log_error( +			"un-supported for this csv type - single buf detected\n"); +		return; +	} + +	/* do we go beyond the max buf set for this csv ?*/ +	if ((csv->csv_len + rec->rec_len) > csv->buflen) { +		log_error("cannot insert - exceeded buf size\n"); +		return; +	} + +	TAILQ_INSERT_TAIL(&(csv->records), rec, next_record); +	csv->num_recs++; +	csv->csv_len += rec->rec_len; +	csv->pointer += rec->rec_len;  } -csv_record_t * -csv_concat_record (csv_t *csv, -		           csv_record_t *rec1, -		           csv_record_t *rec2) +csv_record_t *csv_concat_record(csv_t *csv, csv_record_t *rec1, +				csv_record_t *rec2)  { -  char *curr; -  char *ret; -  csv_record_t *rec; - -  /* first check if rec1 and rec2 belong to this csv */ -  if(!csv_is_record_valid(csv, rec1) || -     !csv_is_record_valid(csv, rec2)) { -    log_error("rec1 and/or rec2 invalid\n"); -    return (NULL); -  } - -  /* we can only concat records if no buf was supplied during csv init */ -  if (csv->buf) { -    log_error("un-supported for this csv type - single buf detected\n"); -    return (NULL); -  } - -  /* create a new rec */ -  rec = calloc(1, sizeof(csv_record_t)); -  if (!rec) { -    log_error("record malloc failed\n"); -    return (NULL); -  } -  csv_init_record(rec); - -  curr = (char *)calloc(1, csv->buflen); -  if (!curr) { -    log_error("field str malloc failed\n"); -    goto out_rec; -  } -  rec->record = curr; - -  /* concat the record string */ -  ret = strstr(rec1->record, "\n"); -  if (!ret) { -    log_error("rec1 str not properly formatted\n"); -    goto out_curr; -  } - -  snprintf(curr, (int)(ret - rec1->record + 1), "%s", rec1->record); -  strcat(curr, ","); - -  ret = strstr(rec2->record, "\n"); -  if (!ret) { -    log_error("rec2 str not properly formatted\n"); -    goto out_curr; -  } - -  snprintf((curr+strlen(curr)), (int)(ret - rec2->record + 1), "%s", -           rec2->record); -  strcat(curr, "\n"); -  rec->rec_len = strlen(curr); - -  /* paranoia */ -  assert(csv->buflen > -         (csv->csv_len - rec1->rec_len - rec2->rec_len + rec->rec_len)); - -  /* decode record into fields */ -  csv_decode_record(rec); - -  /* now remove rec1 and rec2 and insert rec into this csv */ -  csv_remove_record(csv, rec1); -  csv_remove_record(csv, rec2); -  csv_insert_record(csv, rec); - -  return rec; +	char *curr; +	char *ret; +	csv_record_t *rec; + +	/* first check if rec1 and rec2 belong to this csv */ +	if (!csv_is_record_valid(csv, rec1) +	    || !csv_is_record_valid(csv, rec2)) { +		log_error("rec1 and/or rec2 invalid\n"); +		return (NULL); +	} + +	/* we can only concat records if no buf was supplied during csv init */ +	if (csv->buf) { +		log_error( +			"un-supported for this csv type - single buf detected\n"); +		return (NULL); +	} + +	/* create a new rec */ +	rec = calloc(1, sizeof(csv_record_t)); +	if (!rec) { +		log_error("record malloc failed\n"); +		return (NULL); +	} +	csv_init_record(rec); + +	curr = (char *)calloc(1, csv->buflen); +	if (!curr) { +		log_error("field str malloc failed\n"); +		goto out_rec; +	} +	rec->record = curr; + +	/* concat the record string */ +	ret = strstr(rec1->record, "\n"); +	if (!ret) { +		log_error("rec1 str not properly formatted\n"); +		goto out_curr; +	} + +	snprintf(curr, (int)(ret - rec1->record + 1), "%s", rec1->record); +	strcat(curr, ","); + +	ret = strstr(rec2->record, "\n"); +	if (!ret) { +		log_error("rec2 str not properly formatted\n"); +		goto out_curr; +	} + +	snprintf((curr + strlen(curr)), (int)(ret - rec2->record + 1), "%s", +		 rec2->record); +	strcat(curr, "\n"); +	rec->rec_len = strlen(curr); + +	/* paranoia */ +	assert(csv->buflen +	       > (csv->csv_len - rec1->rec_len - rec2->rec_len + rec->rec_len)); + +	/* decode record into fields */ +	csv_decode_record(rec); + +	/* now remove rec1 and rec2 and insert rec into this csv */ +	csv_remove_record(csv, rec1); +	csv_remove_record(csv, rec2); +	csv_insert_record(csv, rec); + +	return rec;  out_curr: -  free(curr); +	free(curr);  out_rec: -  free(rec); -  return NULL; +	free(rec); +	return NULL;  } -void -csv_decode (csv_t *csv, char *inbuf) +void csv_decode(csv_t *csv, char *inbuf)  { -  char *buf; -  char *pos; -  csv_record_t *rec; - -  buf = (inbuf)? inbuf:csv->buf; -  pos = strpbrk(buf, "\n"); -  while (pos != NULL) { -    rec = calloc(1, sizeof(csv_record_t)); -    if (!rec) -      return; -    csv_init_record(rec); -    TAILQ_INSERT_TAIL(&(csv->records), rec, next_record); -    csv->num_recs++; -    if (csv->buf) -      rec->record = buf; -    else { -      rec->record = calloc(1, csv->buflen); -      if (!rec->record) { -        log_error("field str malloc failed\n"); -        return; -      } -      strncpy(rec->record, buf, pos-buf+1); -    } -    rec->rec_len = pos-buf+1; -    /* decode record into fields */ -    csv_decode_record(rec); -    buf = pos+1; -    pos = strpbrk(buf, "\n"); -  } +	char *buf; +	char *pos; +	csv_record_t *rec; + +	buf = (inbuf) ? inbuf : csv->buf; +	pos = strpbrk(buf, "\n"); +	while (pos != NULL) { +		rec = calloc(1, sizeof(csv_record_t)); +		if (!rec) +			return; +		csv_init_record(rec); +		TAILQ_INSERT_TAIL(&(csv->records), rec, next_record); +		csv->num_recs++; +		if (csv->buf) +			rec->record = buf; +		else { +			rec->record = calloc(1, csv->buflen); +			if (!rec->record) { +				log_error("field str malloc failed\n"); +				return; +			} +			strncpy(rec->record, buf, pos - buf + 1); +		} +		rec->rec_len = pos - buf + 1; +		/* decode record into fields */ +		csv_decode_record(rec); +		buf = pos + 1; +		pos = strpbrk(buf, "\n"); +	}  } -int -csv_is_record_valid(csv_t *csv, csv_record_t *in_rec) +int csv_is_record_valid(csv_t *csv, csv_record_t *in_rec)  { -  csv_record_t *rec; -  int valid = 0; - -  rec = csv_record_iter(csv); -  while (rec) { -    if(rec == in_rec) { -      valid = 1; -      break; -    } -    rec = csv_record_iter_next(rec); -  } - -  return valid; +	csv_record_t *rec; +	int valid = 0; + +	rec = csv_record_iter(csv); +	while (rec) { +		if (rec == in_rec) { +			valid = 1; +			break; +		} +		rec = csv_record_iter_next(rec); +	} + +	return valid;  } -void -csv_dump (csv_t *csv) +void csv_dump(csv_t *csv)  { -  csv_record_t *rec; -  csv_field_t *fld; -  char *str; - -  rec = csv_record_iter(csv); -  while (rec != NULL) { -    str = csv_field_iter(rec, &fld); -    while (str != NULL) { -      fprintf(stderr, "%s\n", str); -      str = csv_field_iter_next(&fld); -    } -    rec = csv_record_iter_next(rec); -  } +	csv_record_t *rec; +	csv_field_t *fld; +	char *str; + +	rec = csv_record_iter(csv); +	while (rec != NULL) { +		str = csv_field_iter(rec, &fld); +		while (str != NULL) { +			fprintf(stderr, "%s\n", str); +			str = csv_field_iter_next(&fld); +		} +		rec = csv_record_iter_next(rec); +	}  }  #ifdef TEST_CSV -static int -get_memory_usage (pid_t pid) +static int get_memory_usage(pid_t pid)  { -  int fd, data, stack; -  char buf[4096], status_child[BUFSIZ]; -  char *vm; - -  sprintf(status_child, "/proc/%d/status", pid); -  if ((fd = open(status_child, O_RDONLY)) < 0) -    return -1; - -  read(fd, buf, 4095); -  buf[4095] = '\0'; -  close(fd); - -  data = stack = 0; - -  vm = strstr(buf, "VmData:"); -  if (vm) { -    sscanf(vm, "%*s %d", &data); -  } -  vm = strstr(buf, "VmStk:"); -  if (vm) { -    sscanf(vm, "%*s %d", &stack); -  } - -  return data + stack; +	int fd, data, stack; +	char buf[4096], status_child[BUFSIZ]; +	char *vm; + +	sprintf(status_child, "/proc/%d/status", pid); +	if ((fd = open(status_child, O_RDONLY)) < 0) +		return -1; + +	read(fd, buf, 4095); +	buf[4095] = '\0'; +	close(fd); + +	data = stack = 0; + +	vm = strstr(buf, "VmData:"); +	if (vm) { +		sscanf(vm, "%*s %d", &data); +	} +	vm = strstr(buf, "VmStk:"); +	if (vm) { +		sscanf(vm, "%*s %d", &stack); +	} + +	return data + stack;  } -int main () +int main()  { -  char buf[10000]; -  csv_t csv; -  int p; -  int i, j; -  csv_record_t *rec; -  csv_field_t *fld; -  char *str; -  char hdr1[32], hdr2[32]; - -  log_verbose("Mem: %ld\n", get_memory_usage(getpid())); -  csv_init(&csv, buf, 256); -  sprintf(hdr1, "%4u", 0); -  sprintf(hdr2, "%4u", 1); -  log_verbose("(%d/%d/%d/%d)\n", strlen(hdr1), -	  strlen(hdr2), atoi(hdr1), atoi(hdr2)); -  rec = csv_encode(&csv, 2, hdr1, hdr2); -  csv_encode(&csv, 4, "name", "age", "sex", "hei"); -  csv_encode(&csv, 3, NULL, "0", NULL); -  csv_encode(&csv, 2, "p", "35"); -  for (i=0; i < 50; i++) { -    csv_encode(&csv, 2, "p", "10"); -  } -  csv_encode(&csv, 2, "pdfadfadfadsadsaddfdfdsfdsd", -                 "35444554545454545"); -  log_verbose("%s\n", buf); -  sprintf(hdr1, "%4u", csv.csv_len); -  sprintf(hdr2, "%4u", 1); -  log_verbose("(%d/%d/%d/%d)\n", strlen(hdr1), -	  strlen(hdr2), atoi(hdr1), atoi(hdr2)); -  rec = csv_encode_record(&csv, rec, 2, hdr1, hdr2); -  log_verbose("(%d/%d)\n%s\n", rec->rec_len, csv.csv_len, buf); - -  log_verbose("Mem: %ld\n", get_memory_usage(getpid())); -  csv_clean(&csv); -  log_verbose("Mem: %ld\n", get_memory_usage(getpid())); -  csv_init(&csv, buf, 256); -  csv_decode(&csv, NULL); -  log_verbose("AFTER DECODE\n"); -  csv_dump(&csv); -  csv_clean(&csv); -  log_verbose("Mem: %ld\n", get_memory_usage(getpid())); +	char buf[10000]; +	csv_t csv; +	int p; +	int i, j; +	csv_record_t *rec; +	csv_field_t *fld; +	char *str; +	char hdr1[32], hdr2[32]; + +	log_verbose("Mem: %ld\n", get_memory_usage(getpid())); +	csv_init(&csv, buf, 256); +	sprintf(hdr1, "%4u", 0); +	sprintf(hdr2, "%4u", 1); +	log_verbose("(%d/%d/%d/%d)\n", strlen(hdr1), strlen(hdr2), atoi(hdr1), +		    atoi(hdr2)); +	rec = csv_encode(&csv, 2, hdr1, hdr2); +	csv_encode(&csv, 4, "name", "age", "sex", "hei"); +	csv_encode(&csv, 3, NULL, "0", NULL); +	csv_encode(&csv, 2, "p", "35"); +	for (i = 0; i < 50; i++) { +		csv_encode(&csv, 2, "p", "10"); +	} +	csv_encode(&csv, 2, "pdfadfadfadsadsaddfdfdsfdsd", "35444554545454545"); +	log_verbose("%s\n", buf); +	sprintf(hdr1, "%4u", csv.csv_len); +	sprintf(hdr2, "%4u", 1); +	log_verbose("(%d/%d/%d/%d)\n", strlen(hdr1), strlen(hdr2), atoi(hdr1), +		    atoi(hdr2)); +	rec = csv_encode_record(&csv, rec, 2, hdr1, hdr2); +	log_verbose("(%d/%d)\n%s\n", rec->rec_len, csv.csv_len, buf); + +	log_verbose("Mem: %ld\n", get_memory_usage(getpid())); +	csv_clean(&csv); +	log_verbose("Mem: %ld\n", get_memory_usage(getpid())); +	csv_init(&csv, buf, 256); +	csv_decode(&csv, NULL); +	log_verbose("AFTER DECODE\n"); +	csv_dump(&csv); +	csv_clean(&csv); +	log_verbose("Mem: %ld\n", get_memory_usage(getpid()));  }  #endif @@ -79,7 +79,7 @@ typedef struct _csv_t_ csv_t;   * Initialize the CSV structure (if necessary, allocate first). Point to   * the passed string buffer.   */ -csv_t * csv_init(csv_t *csv, char *buf, int buflen); +csv_t *csv_init(csv_t *csv, char *buf, int buflen);  /**   * Encode the variable list of arguments as CSV fields. The csv structure @@ -100,8 +100,7 @@ csv_record_t *csv_encode(csv_t *csv, int count, ...);   * processes/nodes - e.g. the message header record can be rewritten AFTER   * encoding all other records, with new information such as total length.   */ -csv_record_t *csv_encode_record(csv_t *csv, csv_record_t *rec, -				int count, ...); +csv_record_t *csv_encode_record(csv_t *csv, csv_record_t *rec, int count, ...);  /**   * Decode a CSV formatted string. The csv structure should have been @@ -150,7 +149,7 @@ int csv_is_record_valid(csv_t *csv, csv_record_t *in_rec);   * rec1 and rec2 are removed   */  csv_record_t *csv_concat_record(csv_t *csv, csv_record_t *rec1, -                               csv_record_t *rec2); +				csv_record_t *rec2);  /**   * Remove a record from csv @@ -168,8 +167,7 @@ void csv_insert_record(csv_t *csv, csv_record_t *rec);   * append fields to a record   * Only works when csv has discrete record bufs   */ -csv_record_t * -csv_append_record (csv_t *csv, csv_record_t *rec, int count, ...); +csv_record_t *csv_append_record(csv_t *csv, csv_record_t *rec, int count, ...);  /**   * Serialize contents of csv into string @@ -181,11 +179,11 @@ int csv_serialize(csv_t *csv, char *msgbuf, int msglen);   * Clone a record.   * Only works when csv has discrete record bufs   */ -void csv_clone_record (csv_t *csv, csv_record_t *in_rec, csv_record_t **out_rec); +void csv_clone_record(csv_t *csv, csv_record_t *in_rec, csv_record_t **out_rec);  /**   * Return number of records   */ -int csv_num_records (csv_t *csv); +int csv_num_records(csv_t *csv);  #endif diff --git a/lib/distribute.c b/lib/distribute.c index f85994c9a8..9f1272111b 100644 --- a/lib/distribute.c +++ b/lib/distribute.c @@ -28,226 +28,216 @@  #include "distribute.h"  #include "memory.h" -DEFINE_MTYPE_STATIC(LIB, DISTRIBUTE,        "Distribute list") +DEFINE_MTYPE_STATIC(LIB, DISTRIBUTE, "Distribute list")  DEFINE_MTYPE_STATIC(LIB, DISTRIBUTE_IFNAME, "Dist-list ifname") -DEFINE_MTYPE_STATIC(LIB, DISTRIBUTE_NAME,   "Dist-list name") +DEFINE_MTYPE_STATIC(LIB, DISTRIBUTE_NAME, "Dist-list name")  /* Hash of distribute list. */  struct hash *disthash;  /* Hook functions. */ -void (*distribute_add_hook) (struct distribute *); -void (*distribute_delete_hook) (struct distribute *); +void (*distribute_add_hook)(struct distribute *); +void (*distribute_delete_hook)(struct distribute *); -static struct distribute * -distribute_new (void) +static struct distribute *distribute_new(void)  { -  return XCALLOC (MTYPE_DISTRIBUTE, sizeof (struct distribute)); +	return XCALLOC(MTYPE_DISTRIBUTE, sizeof(struct distribute));  }  /* Free distribute object. */ -static void -distribute_free (struct distribute *dist) +static void distribute_free(struct distribute *dist)  { -  int i = 0; +	int i = 0; -  if (dist->ifname) -    XFREE (MTYPE_DISTRIBUTE_IFNAME, dist->ifname); +	if (dist->ifname) +		XFREE(MTYPE_DISTRIBUTE_IFNAME, dist->ifname); -  for (i = 0; i < DISTRIBUTE_MAX; i++) -    if (dist->list[i]) -      XFREE(MTYPE_DISTRIBUTE_NAME, dist->list[i]); +	for (i = 0; i < DISTRIBUTE_MAX; i++) +		if (dist->list[i]) +			XFREE(MTYPE_DISTRIBUTE_NAME, dist->list[i]); -  for (i = 0; i < DISTRIBUTE_MAX; i++) -    if (dist->prefix[i]) -      XFREE(MTYPE_DISTRIBUTE_NAME, dist->prefix[i]); +	for (i = 0; i < DISTRIBUTE_MAX; i++) +		if (dist->prefix[i]) +			XFREE(MTYPE_DISTRIBUTE_NAME, dist->prefix[i]); -  XFREE (MTYPE_DISTRIBUTE, dist); +	XFREE(MTYPE_DISTRIBUTE, dist);  } -static void -distribute_free_if_empty(struct distribute *dist) +static void distribute_free_if_empty(struct distribute *dist)  { -  int i; +	int i; -  for (i = 0; i < DISTRIBUTE_MAX; i++) -    if (dist->list[i] != NULL || dist->prefix[i] != NULL) -      return; +	for (i = 0; i < DISTRIBUTE_MAX; i++) +		if (dist->list[i] != NULL || dist->prefix[i] != NULL) +			return; -  hash_release (disthash, dist); -  distribute_free (dist); +	hash_release(disthash, dist); +	distribute_free(dist);  }  /* Lookup interface's distribute list. */ -struct distribute * -distribute_lookup (const char *ifname) +struct distribute *distribute_lookup(const char *ifname)  { -  struct distribute key; -  struct distribute *dist; +	struct distribute key; +	struct distribute *dist; -  /* temporary reference */ -  key.ifname = (ifname) ? XSTRDUP(MTYPE_DISTRIBUTE_IFNAME, ifname) : NULL; +	/* temporary reference */ +	key.ifname = (ifname) ? XSTRDUP(MTYPE_DISTRIBUTE_IFNAME, ifname) : NULL; -  dist = hash_lookup (disthash, &key); +	dist = hash_lookup(disthash, &key); -  if (key.ifname) -    XFREE(MTYPE_DISTRIBUTE_IFNAME, key.ifname); +	if (key.ifname) +		XFREE(MTYPE_DISTRIBUTE_IFNAME, key.ifname); -  return dist; +	return dist;  } -void -distribute_list_add_hook (void (*func) (struct distribute *)) +void distribute_list_add_hook(void (*func)(struct distribute *))  { -  distribute_add_hook = func; +	distribute_add_hook = func;  } -void -distribute_list_delete_hook (void (*func) (struct distribute *)) +void distribute_list_delete_hook(void (*func)(struct distribute *))  { -  distribute_delete_hook = func; +	distribute_delete_hook = func;  } -static void * -distribute_hash_alloc (struct distribute *arg) +static void *distribute_hash_alloc(struct distribute *arg)  { -  struct distribute *dist; - -  dist = distribute_new (); -  if (arg->ifname) -    dist->ifname = XSTRDUP (MTYPE_DISTRIBUTE_IFNAME, arg->ifname); -  else -    dist->ifname = NULL; -  return dist; +	struct distribute *dist; + +	dist = distribute_new(); +	if (arg->ifname) +		dist->ifname = XSTRDUP(MTYPE_DISTRIBUTE_IFNAME, arg->ifname); +	else +		dist->ifname = NULL; +	return dist;  }  /* Make new distribute list and push into hash. */ -static struct distribute * -distribute_get (const char *ifname) +static struct distribute *distribute_get(const char *ifname)  { -  struct distribute key; -  struct distribute *ret; +	struct distribute key; +	struct distribute *ret; + +	/* temporary reference */ +	key.ifname = (ifname) ? XSTRDUP(MTYPE_DISTRIBUTE_IFNAME, ifname) : NULL; -  /* temporary reference */ -  key.ifname = (ifname) ? XSTRDUP(MTYPE_DISTRIBUTE_IFNAME, ifname) : NULL; -   -  ret = hash_get (disthash, &key, (void * (*) (void *))distribute_hash_alloc); +	ret = hash_get(disthash, &key, +		       (void *(*)(void *))distribute_hash_alloc); -  if (key.ifname) -    XFREE(MTYPE_DISTRIBUTE_IFNAME, key.ifname); +	if (key.ifname) +		XFREE(MTYPE_DISTRIBUTE_IFNAME, key.ifname); -  return ret; +	return ret;  } -static unsigned int -distribute_hash_make (void *arg) +static unsigned int distribute_hash_make(void *arg)  { -  const struct distribute *dist = arg; +	const struct distribute *dist = arg; -  return dist->ifname ? string_hash_make (dist->ifname) : 0; +	return dist->ifname ? string_hash_make(dist->ifname) : 0;  }  /* If two distribute-list have same value then return 1 else return     0. This function is used by hash package. */ -static int -distribute_cmp (const struct distribute *dist1, const struct distribute *dist2) +static int distribute_cmp(const struct distribute *dist1, +			  const struct distribute *dist2)  { -  if (dist1->ifname && dist2->ifname) -    if (strcmp (dist1->ifname, dist2->ifname) == 0) -      return 1; -  if (! dist1->ifname && ! dist2->ifname) -    return 1; -  return 0; +	if (dist1->ifname && dist2->ifname) +		if (strcmp(dist1->ifname, dist2->ifname) == 0) +			return 1; +	if (!dist1->ifname && !dist2->ifname) +		return 1; +	return 0;  }  /* Set access-list name to the distribute list. */ -static void -distribute_list_set (const char *ifname, enum distribute_type type,  -                     const char *alist_name) +static void distribute_list_set(const char *ifname, enum distribute_type type, +				const char *alist_name)  { -  struct distribute *dist; +	struct distribute *dist; -  dist = distribute_get (ifname); +	dist = distribute_get(ifname); -  if (dist->list[type]) -    XFREE(MTYPE_DISTRIBUTE_NAME, dist->list[type]); -  dist->list[type] = XSTRDUP(MTYPE_DISTRIBUTE_NAME, alist_name); +	if (dist->list[type]) +		XFREE(MTYPE_DISTRIBUTE_NAME, dist->list[type]); +	dist->list[type] = XSTRDUP(MTYPE_DISTRIBUTE_NAME, alist_name); -  /* Apply this distribute-list to the interface. */ -  (*distribute_add_hook) (dist); +	/* Apply this distribute-list to the interface. */ +	(*distribute_add_hook)(dist);  }  /* Unset distribute-list.  If matched distribute-list exist then     return 1. */ -static int -distribute_list_unset (const char *ifname, enum distribute_type type,  -		       const char *alist_name) +static int distribute_list_unset(const char *ifname, enum distribute_type type, +				 const char *alist_name)  { -  struct distribute *dist; +	struct distribute *dist; -  dist = distribute_lookup (ifname); -  if (!dist) -    return 0; +	dist = distribute_lookup(ifname); +	if (!dist) +		return 0; -  if (!dist->list[type]) -	return 0; -  if (strcmp (dist->list[type], alist_name) != 0) -	return 0; +	if (!dist->list[type]) +		return 0; +	if (strcmp(dist->list[type], alist_name) != 0) +		return 0; -  XFREE(MTYPE_DISTRIBUTE_NAME, dist->list[type]); -  dist->list[type] = NULL; +	XFREE(MTYPE_DISTRIBUTE_NAME, dist->list[type]); +	dist->list[type] = NULL; -  /* Apply this distribute-list to the interface. */ -  (*distribute_delete_hook) (dist); +	/* Apply this distribute-list to the interface. */ +	(*distribute_delete_hook)(dist); -  /* If all dist are NULL, then free distribute list. */ -  distribute_free_if_empty(dist); -  return 1; +	/* If all dist are NULL, then free distribute list. */ +	distribute_free_if_empty(dist); +	return 1;  }  /* Set access-list name to the distribute list. */ -static void -distribute_list_prefix_set (const char *ifname, enum distribute_type type, -			    const char *plist_name) +static void distribute_list_prefix_set(const char *ifname, +				       enum distribute_type type, +				       const char *plist_name)  { -  struct distribute *dist; +	struct distribute *dist; -  dist = distribute_get (ifname); +	dist = distribute_get(ifname); -  if (dist->prefix[type]) -    XFREE(MTYPE_DISTRIBUTE_NAME, dist->prefix[type]); -  dist->prefix[type] = XSTRDUP(MTYPE_DISTRIBUTE_NAME, plist_name); +	if (dist->prefix[type]) +		XFREE(MTYPE_DISTRIBUTE_NAME, dist->prefix[type]); +	dist->prefix[type] = XSTRDUP(MTYPE_DISTRIBUTE_NAME, plist_name); -  /* Apply this distribute-list to the interface. */ -  (*distribute_add_hook) (dist); +	/* Apply this distribute-list to the interface. */ +	(*distribute_add_hook)(dist);  }  /* Unset distribute-list.  If matched distribute-list exist then     return 1. */ -static int -distribute_list_prefix_unset (const char *ifname, enum distribute_type type, -			      const char *plist_name) +static int distribute_list_prefix_unset(const char *ifname, +					enum distribute_type type, +					const char *plist_name)  { -  struct distribute *dist; +	struct distribute *dist; -  dist = distribute_lookup (ifname); -  if (!dist) -    return 0; +	dist = distribute_lookup(ifname); +	if (!dist) +		return 0; -  if (!dist->prefix[type]) -	return 0; -  if (strcmp (dist->prefix[type], plist_name) != 0) -	return 0; +	if (!dist->prefix[type]) +		return 0; +	if (strcmp(dist->prefix[type], plist_name) != 0) +		return 0; -  XFREE(MTYPE_DISTRIBUTE_NAME, dist->prefix[type]); -  dist->prefix[type] = NULL; +	XFREE(MTYPE_DISTRIBUTE_NAME, dist->prefix[type]); +	dist->prefix[type] = NULL; -  /* Apply this distribute-list to the interface. */ -  (*distribute_delete_hook) (dist); +	/* Apply this distribute-list to the interface. */ +	(*distribute_delete_hook)(dist); -  /* If all dist are NULL, then free distribute list. */ -  distribute_free_if_empty(dist); -  return 1; +	/* If all dist are NULL, then free distribute list. */ +	distribute_free_if_empty(dist); +	return 1;  }  DEFUN (distribute_list, @@ -260,25 +250,26 @@ DEFUN (distribute_list,         "Filter outgoing routing updates\n"         "Interface name\n")  { -  int prefix = (argv[1]->type == WORD_TKN) ? 1 : 0; +	int prefix = (argv[1]->type == WORD_TKN) ? 1 : 0; + +	/* Check of distribute list type. */ +	enum distribute_type type = argv[2 + prefix]->arg[0] == 'i' +					    ? DISTRIBUTE_V4_IN +					    : DISTRIBUTE_V4_OUT; -  /* Check of distribute list type. */ -  enum distribute_type type = argv[2 + prefix]->arg[0] == 'i' ? -    DISTRIBUTE_V4_IN : DISTRIBUTE_V4_OUT; +	/* Set appropriate function call */ +	void (*distfn)(const char *, enum distribute_type, const char *) = +		prefix ? &distribute_list_prefix_set : &distribute_list_set; -  /* Set appropriate function call */ -  void (*distfn)(const char *, enum distribute_type, const char *) = prefix ?  -    &distribute_list_prefix_set : &distribute_list_set; -   -  /* if interface is present, get name */ -  const char *ifname = NULL; -  if (argv[argc - 1]->type == VARIABLE_TKN) -    ifname = argv[argc - 1]->arg; +	/* if interface is present, get name */ +	const char *ifname = NULL; +	if (argv[argc - 1]->type == VARIABLE_TKN) +		ifname = argv[argc - 1]->arg; -  /* Get interface name corresponding distribute list. */ -  distfn (ifname, type, argv[1 + prefix]->arg); +	/* Get interface name corresponding distribute list. */ +	distfn(ifname, type, argv[1 + prefix]->arg); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (ipv6_distribute_list, @@ -292,27 +283,28 @@ DEFUN (ipv6_distribute_list,         "Filter outgoing routing updates\n"         "Interface name\n")  { -  int prefix = (argv[2]->type == WORD_TKN) ? 1 : 0; +	int prefix = (argv[2]->type == WORD_TKN) ? 1 : 0; -  /* Check of distribute list type. */ -  enum distribute_type type = argv[3 + prefix]->arg[0] == 'i' ? -    DISTRIBUTE_V6_IN : DISTRIBUTE_V6_OUT; +	/* Check of distribute list type. */ +	enum distribute_type type = argv[3 + prefix]->arg[0] == 'i' +					    ? DISTRIBUTE_V6_IN +					    : DISTRIBUTE_V6_OUT; -  /* Set appropriate function call */ -  void (*distfn)(const char *, enum distribute_type, const char *) = prefix ?  -    &distribute_list_prefix_set : &distribute_list_set; -   -  /* if interface is present, get name */ -  const char *ifname = NULL; -  if (argv[argc - 1]->type == VARIABLE_TKN) -    ifname = argv[argc - 1]->arg; +	/* Set appropriate function call */ +	void (*distfn)(const char *, enum distribute_type, const char *) = +		prefix ? &distribute_list_prefix_set : &distribute_list_set; -  /* Get interface name corresponding distribute list. */ -  distfn (ifname, type, argv[1 + prefix]->arg); +	/* if interface is present, get name */ +	const char *ifname = NULL; +	if (argv[argc - 1]->type == VARIABLE_TKN) +		ifname = argv[argc - 1]->arg; -  return CMD_SUCCESS; +	/* Get interface name corresponding distribute list. */ +	distfn(ifname, type, argv[1 + prefix]->arg); + +	return CMD_SUCCESS;  } -        +  DEFUN (no_distribute_list,         no_distribute_list_cmd,         "no [ipv6] distribute-list [prefix] WORD <in|out> [WORD]", @@ -325,231 +317,239 @@ DEFUN (no_distribute_list,         "Filter outgoing routing updates\n"         "Interface name\n")  { -  int ipv6 = strmatch(argv[1]->text, "ipv6"); -  int prefix = (argv[2 + ipv6]->type == WORD_TKN) ? 1 : 0; - -  int idx_alname = 2 + ipv6 + prefix; -  int idx_disttype = idx_alname + 1; - -  /* Check of distribute list type. */ -  enum distribute_type distin = (ipv6) ? DISTRIBUTE_V6_IN : DISTRIBUTE_V4_IN; -  enum distribute_type distout = (ipv6) ? DISTRIBUTE_V6_OUT : DISTRIBUTE_V4_OUT; - -  enum distribute_type type = argv[idx_disttype]->arg[0] == 'i' ? distin : distout; - -  /* Set appropriate function call */ -  int (*distfn)(const char *, enum distribute_type, const char *) = prefix ?  -    &distribute_list_prefix_unset : &distribute_list_unset; -   -  /* if interface is present, get name */ -  const char *ifname = NULL; -  if (argv[argc - 1]->type == VARIABLE_TKN) -    ifname = argv[argc - 1]->arg; -  /* Get interface name corresponding distribute list. */ -  int ret = distfn (ifname, type, argv[2 + prefix]->arg); - -  if (! ret) -    { -      vty_out (vty, "distribute list doesn't exist%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  return CMD_SUCCESS; +	int ipv6 = strmatch(argv[1]->text, "ipv6"); +	int prefix = (argv[2 + ipv6]->type == WORD_TKN) ? 1 : 0; + +	int idx_alname = 2 + ipv6 + prefix; +	int idx_disttype = idx_alname + 1; + +	/* Check of distribute list type. */ +	enum distribute_type distin = +		(ipv6) ? DISTRIBUTE_V6_IN : DISTRIBUTE_V4_IN; +	enum distribute_type distout = +		(ipv6) ? DISTRIBUTE_V6_OUT : DISTRIBUTE_V4_OUT; + +	enum distribute_type type = +		argv[idx_disttype]->arg[0] == 'i' ? distin : distout; + +	/* Set appropriate function call */ +	int (*distfn)(const char *, enum distribute_type, const char *) = +		prefix ? &distribute_list_prefix_unset : &distribute_list_unset; + +	/* if interface is present, get name */ +	const char *ifname = NULL; +	if (argv[argc - 1]->type == VARIABLE_TKN) +		ifname = argv[argc - 1]->arg; +	/* Get interface name corresponding distribute list. */ +	int ret = distfn(ifname, type, argv[2 + prefix]->arg); + +	if (!ret) { +		vty_out(vty, "distribute list doesn't exist%s", VTY_NEWLINE); +		return CMD_WARNING; +	} +	return CMD_SUCCESS;  } -static int -distribute_print (struct vty *vty, char *tab[], int is_prefix, -                  enum distribute_type type, int has_print) +static int distribute_print(struct vty *vty, char *tab[], int is_prefix, +			    enum distribute_type type, int has_print)  { -  if (tab[type]) { -    vty_out (vty, "%s %s%s", -             has_print ? "," : "", -             is_prefix ? "(prefix-list) " : "", -             tab[type]); -    return 1; -  } -  return has_print; +	if (tab[type]) { +		vty_out(vty, "%s %s%s", has_print ? "," : "", +			is_prefix ? "(prefix-list) " : "", tab[type]); +		return 1; +	} +	return has_print;  } -int -config_show_distribute (struct vty *vty) +int config_show_distribute(struct vty *vty)  { -  unsigned int i; -  int has_print = 0; -  struct hash_backet *mp; -  struct distribute *dist; - -  /* Output filter configuration. */ -  dist = distribute_lookup (NULL); -      vty_out (vty, "  Outgoing update filter list for all interface is"); -  has_print = 0; -  if (dist) -    { -      has_print = distribute_print(vty, dist->list,   0, -                                   DISTRIBUTE_V4_OUT, has_print); -      has_print = distribute_print(vty, dist->prefix, 1, -                                   DISTRIBUTE_V4_OUT, has_print); -      has_print = distribute_print(vty, dist->list,   0, -                                   DISTRIBUTE_V6_OUT, has_print); -      has_print = distribute_print(vty, dist->prefix, 1, -                                   DISTRIBUTE_V6_OUT, has_print); -    } -  if (has_print) -    vty_out (vty, "%s", VTY_NEWLINE); -  else -    vty_out (vty, " not set%s", VTY_NEWLINE); - -  for (i = 0; i < disthash->size; i++) -    for (mp = disthash->index[i]; mp; mp = mp->next) -      { -	dist = mp->data; -	if (dist->ifname) -	    { -	      vty_out (vty, "    %s filtered by", dist->ifname); -            has_print = 0; -            has_print = distribute_print(vty, dist->list,   0, -                                         DISTRIBUTE_V4_OUT, has_print); -            has_print = distribute_print(vty, dist->prefix, 1, -                                         DISTRIBUTE_V4_OUT, has_print); -            has_print = distribute_print(vty, dist->list,   0, -                                         DISTRIBUTE_V6_OUT, has_print); -            has_print = distribute_print(vty, dist->prefix, 1, -                                         DISTRIBUTE_V6_OUT, has_print); -            if (has_print) -	      vty_out (vty, "%s", VTY_NEWLINE); -            else -              vty_out(vty, " nothing%s", VTY_NEWLINE); -	    } -      } - - -  /* Input filter configuration. */ -  dist = distribute_lookup (NULL); -      vty_out (vty, "  Incoming update filter list for all interface is"); -  has_print = 0; -  if (dist) -    { -      has_print = distribute_print(vty, dist->list,   0, -                                   DISTRIBUTE_V4_IN, has_print); -      has_print = distribute_print(vty, dist->prefix, 1, -                                   DISTRIBUTE_V4_IN, has_print); -      has_print = distribute_print(vty, dist->list,   0, -                                   DISTRIBUTE_V6_IN, has_print); -      has_print = distribute_print(vty, dist->prefix, 1, -                                   DISTRIBUTE_V6_IN, has_print); -    } -  if (has_print) -    vty_out (vty, "%s", VTY_NEWLINE); -  else -    vty_out (vty, " not set%s", VTY_NEWLINE); - -  for (i = 0; i < disthash->size; i++) -    for (mp = disthash->index[i]; mp; mp = mp->next) -      { -	dist = mp->data; -	if (dist->ifname) -	    { -	      vty_out (vty, "    %s filtered by", dist->ifname); -            has_print = 0; -            has_print = distribute_print(vty, dist->list,   0, -                                         DISTRIBUTE_V4_IN, has_print); -            has_print = distribute_print(vty, dist->prefix, 1, -                                         DISTRIBUTE_V4_IN, has_print); -            has_print = distribute_print(vty, dist->list,   0, -                                         DISTRIBUTE_V6_IN, has_print); -            has_print = distribute_print(vty, dist->prefix, 1, -                                         DISTRIBUTE_V6_IN, has_print); -            if (has_print) -	      vty_out (vty, "%s", VTY_NEWLINE); -            else -              vty_out(vty, " nothing%s", VTY_NEWLINE); -	    } -      } -  return 0; +	unsigned int i; +	int has_print = 0; +	struct hash_backet *mp; +	struct distribute *dist; + +	/* Output filter configuration. */ +	dist = distribute_lookup(NULL); +	vty_out(vty, "  Outgoing update filter list for all interface is"); +	has_print = 0; +	if (dist) { +		has_print = distribute_print(vty, dist->list, 0, +					     DISTRIBUTE_V4_OUT, has_print); +		has_print = distribute_print(vty, dist->prefix, 1, +					     DISTRIBUTE_V4_OUT, has_print); +		has_print = distribute_print(vty, dist->list, 0, +					     DISTRIBUTE_V6_OUT, has_print); +		has_print = distribute_print(vty, dist->prefix, 1, +					     DISTRIBUTE_V6_OUT, has_print); +	} +	if (has_print) +		vty_out(vty, "%s", VTY_NEWLINE); +	else +		vty_out(vty, " not set%s", VTY_NEWLINE); + +	for (i = 0; i < disthash->size; i++) +		for (mp = disthash->index[i]; mp; mp = mp->next) { +			dist = mp->data; +			if (dist->ifname) { +				vty_out(vty, "    %s filtered by", +					dist->ifname); +				has_print = 0; +				has_print = distribute_print(vty, dist->list, 0, +							     DISTRIBUTE_V4_OUT, +							     has_print); +				has_print = distribute_print( +					vty, dist->prefix, 1, DISTRIBUTE_V4_OUT, +					has_print); +				has_print = distribute_print(vty, dist->list, 0, +							     DISTRIBUTE_V6_OUT, +							     has_print); +				has_print = distribute_print( +					vty, dist->prefix, 1, DISTRIBUTE_V6_OUT, +					has_print); +				if (has_print) +					vty_out(vty, "%s", VTY_NEWLINE); +				else +					vty_out(vty, " nothing%s", VTY_NEWLINE); +			} +		} + + +	/* Input filter configuration. */ +	dist = distribute_lookup(NULL); +	vty_out(vty, "  Incoming update filter list for all interface is"); +	has_print = 0; +	if (dist) { +		has_print = distribute_print(vty, dist->list, 0, +					     DISTRIBUTE_V4_IN, has_print); +		has_print = distribute_print(vty, dist->prefix, 1, +					     DISTRIBUTE_V4_IN, has_print); +		has_print = distribute_print(vty, dist->list, 0, +					     DISTRIBUTE_V6_IN, has_print); +		has_print = distribute_print(vty, dist->prefix, 1, +					     DISTRIBUTE_V6_IN, has_print); +	} +	if (has_print) +		vty_out(vty, "%s", VTY_NEWLINE); +	else +		vty_out(vty, " not set%s", VTY_NEWLINE); + +	for (i = 0; i < disthash->size; i++) +		for (mp = disthash->index[i]; mp; mp = mp->next) { +			dist = mp->data; +			if (dist->ifname) { +				vty_out(vty, "    %s filtered by", +					dist->ifname); +				has_print = 0; +				has_print = distribute_print(vty, dist->list, 0, +							     DISTRIBUTE_V4_IN, +							     has_print); +				has_print = distribute_print( +					vty, dist->prefix, 1, DISTRIBUTE_V4_IN, +					has_print); +				has_print = distribute_print(vty, dist->list, 0, +							     DISTRIBUTE_V6_IN, +							     has_print); +				has_print = distribute_print( +					vty, dist->prefix, 1, DISTRIBUTE_V6_IN, +					has_print); +				if (has_print) +					vty_out(vty, "%s", VTY_NEWLINE); +				else +					vty_out(vty, " nothing%s", VTY_NEWLINE); +			} +		} +	return 0;  }  /* Configuration write function. */ -int -config_write_distribute (struct vty *vty) +int config_write_distribute(struct vty *vty)  { -  unsigned int i; -  int j; -  int output, v6; -  struct hash_backet *mp; -  int write = 0; - -  for (i = 0; i < disthash->size; i++) -    for (mp = disthash->index[i]; mp; mp = mp->next) -      { -	struct distribute *dist; - -	dist = mp->data; - -	for (j = 0; j < DISTRIBUTE_MAX; j++) -	  if (dist->list[j]) { -	    output = j == DISTRIBUTE_V4_OUT || j == DISTRIBUTE_V6_OUT; -            v6 = j == DISTRIBUTE_V6_IN || j == DISTRIBUTE_V6_OUT; -	    vty_out (vty, " %sdistribute-list %s %s %s%s", -                     v6 ? "ipv6 " : "", -		     dist->list[j], -		     output ? "out" : "in", -		     dist->ifname ? dist->ifname : "", -		     VTY_NEWLINE); -	    write++; -	  } - -	for (j = 0; j < DISTRIBUTE_MAX; j++) -	  if (dist->prefix[j]) { -	    output = j == DISTRIBUTE_V4_OUT || j == DISTRIBUTE_V6_OUT; -            v6 = j == DISTRIBUTE_V6_IN || j == DISTRIBUTE_V6_OUT; -	    vty_out (vty, " %sdistribute-list prefix %s %s %s%s", -                     v6 ? "ipv6 " : "", -		     dist->prefix[j], -		     output ? "out" : "in", -		     dist->ifname ? dist->ifname : "", -		     VTY_NEWLINE); -	    write++; -	  } -      } -  return write; +	unsigned int i; +	int j; +	int output, v6; +	struct hash_backet *mp; +	int write = 0; + +	for (i = 0; i < disthash->size; i++) +		for (mp = disthash->index[i]; mp; mp = mp->next) { +			struct distribute *dist; + +			dist = mp->data; + +			for (j = 0; j < DISTRIBUTE_MAX; j++) +				if (dist->list[j]) { +					output = j == DISTRIBUTE_V4_OUT +						 || j == DISTRIBUTE_V6_OUT; +					v6 = j == DISTRIBUTE_V6_IN +					     || j == DISTRIBUTE_V6_OUT; +					vty_out(vty, +						" %sdistribute-list %s %s %s%s", +						v6 ? "ipv6 " : "", +						dist->list[j], +						output ? "out" : "in", +						dist->ifname ? dist->ifname +							     : "", +						VTY_NEWLINE); +					write++; +				} + +			for (j = 0; j < DISTRIBUTE_MAX; j++) +				if (dist->prefix[j]) { +					output = j == DISTRIBUTE_V4_OUT +						 || j == DISTRIBUTE_V6_OUT; +					v6 = j == DISTRIBUTE_V6_IN +					     || j == DISTRIBUTE_V6_OUT; +					vty_out(vty, +						" %sdistribute-list prefix %s %s %s%s", +						v6 ? "ipv6 " : "", +						dist->prefix[j], +						output ? "out" : "in", +						dist->ifname ? dist->ifname +							     : "", +						VTY_NEWLINE); +					write++; +				} +		} +	return write;  }  /* Clear all distribute list. */ -void -distribute_list_reset () +void distribute_list_reset()  { -  hash_clean (disthash, (void (*) (void *)) distribute_free); +	hash_clean(disthash, (void (*)(void *))distribute_free);  }  /* Initialize distribute list related hash. */ -void -distribute_list_init (int node) +void distribute_list_init(int node)  { -  disthash = hash_create (distribute_hash_make, -                          (int (*) (const void *, const void *)) distribute_cmp); - -  /* vtysh command-extraction doesn't grok install_element(node, ) */ -  if (node == RIP_NODE) { -    install_element (RIP_NODE, &distribute_list_cmd); -    install_element (RIP_NODE, &no_distribute_list_cmd); -  } else if (node == RIPNG_NODE) { -    install_element (RIPNG_NODE, &distribute_list_cmd); -    install_element (RIPNG_NODE, &no_distribute_list_cmd); -  } - -  /* install v6 */ -  if (node == RIPNG_NODE) { -    install_element (RIPNG_NODE, &ipv6_distribute_list_cmd); -  } - -  /* TODO: install v4 syntax command for v6 only protocols. */ - /* if (node == RIPNG_NODE) { -  *   install_element (node, &ipv6_as_v4_distribute_list_all_cmd); -  *   install_element (node, &no_ipv6_as_v4_distribute_list_all_cmd); -  *   install_element (node, &ipv6_as_v4_distribute_list_cmd); -  *   install_element (node, &no_ipv6_as_v4_distribute_list_cmd); -  *   install_element (node, &ipv6_as_v4_distribute_list_prefix_all_cmd); -  *   install_element (node, &no_ipv6_as_v4_distribute_list_prefix_all_cmd); -  *   install_element (node, &ipv6_as_v4_distribute_list_prefix_cmd); -  *   install_element (node, &no_ipv6_as_v4_distribute_list_prefix_cmd); -    }*/ +	disthash = hash_create( +		distribute_hash_make, +		(int (*)(const void *, const void *))distribute_cmp); + +	/* vtysh command-extraction doesn't grok install_element(node, ) */ +	if (node == RIP_NODE) { +		install_element(RIP_NODE, &distribute_list_cmd); +		install_element(RIP_NODE, &no_distribute_list_cmd); +	} else if (node == RIPNG_NODE) { +		install_element(RIPNG_NODE, &distribute_list_cmd); +		install_element(RIPNG_NODE, &no_distribute_list_cmd); +	} + +	/* install v6 */ +	if (node == RIPNG_NODE) { +		install_element(RIPNG_NODE, &ipv6_distribute_list_cmd); +	} + +	/* TODO: install v4 syntax command for v6 only protocols. */ +	/* if (node == RIPNG_NODE) { +	 *   install_element (node, &ipv6_as_v4_distribute_list_all_cmd); +	 *   install_element (node, &no_ipv6_as_v4_distribute_list_all_cmd); +	 *   install_element (node, &ipv6_as_v4_distribute_list_cmd); +	 *   install_element (node, &no_ipv6_as_v4_distribute_list_cmd); +	 *   install_element (node, &ipv6_as_v4_distribute_list_prefix_all_cmd); +	 *   install_element (node, +	 &no_ipv6_as_v4_distribute_list_prefix_all_cmd); +	 *   install_element (node, &ipv6_as_v4_distribute_list_prefix_cmd); +	 *   install_element (node, &no_ipv6_as_v4_distribute_list_prefix_cmd); +	   }*/  } diff --git a/lib/distribute.h b/lib/distribute.h index e9625a3548..66b1f5e949 100644 --- a/lib/distribute.h +++ b/lib/distribute.h @@ -27,37 +27,37 @@  #include "filter.h"  /* Disctirubte list types. */ -enum distribute_type -{ -  DISTRIBUTE_V4_IN, -  DISTRIBUTE_V6_IN, -  DISTRIBUTE_V4_OUT, -  DISTRIBUTE_V6_OUT, -  DISTRIBUTE_MAX +enum distribute_type { +	DISTRIBUTE_V4_IN, +	DISTRIBUTE_V6_IN, +	DISTRIBUTE_V4_OUT, +	DISTRIBUTE_V6_OUT, +	DISTRIBUTE_MAX  }; -struct distribute -{ -  /* Name of the interface. */ -  char *ifname; +struct distribute { +	/* Name of the interface. */ +	char *ifname; -  /* Filter name of `in' and `out' */ -  char *list[DISTRIBUTE_MAX]; +	/* Filter name of `in' and `out' */ +	char *list[DISTRIBUTE_MAX]; -  /* prefix-list name of `in' and `out' */ -  char *prefix[DISTRIBUTE_MAX]; +	/* prefix-list name of `in' and `out' */ +	char *prefix[DISTRIBUTE_MAX];  };  /* Prototypes for distribute-list. */ -extern void distribute_list_init (int); -extern void distribute_list_reset (void); -extern void distribute_list_add_hook (void (*) (struct distribute *)); -extern void distribute_list_delete_hook (void (*) (struct distribute *)); -extern struct distribute *distribute_lookup (const char *); -extern int config_write_distribute (struct vty *); -extern int config_show_distribute (struct vty *); - -extern enum filter_type distribute_apply_in (struct interface *, struct prefix *); -extern enum filter_type distribute_apply_out (struct interface *, struct prefix *); +extern void distribute_list_init(int); +extern void distribute_list_reset(void); +extern void distribute_list_add_hook(void (*)(struct distribute *)); +extern void distribute_list_delete_hook(void (*)(struct distribute *)); +extern struct distribute *distribute_lookup(const char *); +extern int config_write_distribute(struct vty *); +extern int config_show_distribute(struct vty *); + +extern enum filter_type distribute_apply_in(struct interface *, +					    struct prefix *); +extern enum filter_type distribute_apply_out(struct interface *, +					     struct prefix *);  #endif /* _ZEBRA_DISTRIBUTE_H */ diff --git a/lib/event_counter.c b/lib/event_counter.c index e94aa4c0f6..43d130f9ab 100644 --- a/lib/event_counter.c +++ b/lib/event_counter.c @@ -45,29 +45,28 @@  #include "event_counter.h" -void -event_counter_inc (struct event_counter *counter) +void event_counter_inc(struct event_counter *counter)  { -  counter->count++; -  counter->last = time (NULL); +	counter->count++; +	counter->last = time(NULL);  } -const char * -event_counter_format (const struct event_counter *counter) +const char *event_counter_format(const struct event_counter *counter)  { -  struct tm last_change_store; -  struct tm *last_change; -  char timebuf[sizeof ("Thu, 01 Jan 1970 00:00:00 +0000")]; -  static char rv[20 + sizeof ("  last: ") + sizeof (timebuf)]; +	struct tm last_change_store; +	struct tm *last_change; +	char timebuf[sizeof("Thu, 01 Jan 1970 00:00:00 +0000")]; +	static char rv[20 + sizeof("  last: ") + sizeof(timebuf)]; -  last_change = localtime_r (&counter->last, &last_change_store); -  if (!last_change || strftime (timebuf, sizeof (timebuf), -                                "%a, %d %b %Y %T %z", last_change) == 0) -    { -      strncpy (timebuf, "???", sizeof (timebuf)); -    } +	last_change = localtime_r(&counter->last, &last_change_store); +	if (!last_change +	    || strftime(timebuf, sizeof(timebuf), "%a, %d %b %Y %T %z", +			last_change) +		       == 0) { +		strncpy(timebuf, "???", sizeof(timebuf)); +	} -  snprintf (rv, sizeof (rv), "%5llu  last: %s", counter->count, -            counter->last ? timebuf : "(never)"); -  return rv; +	snprintf(rv, sizeof(rv), "%5llu  last: %s", counter->count, +		 counter->last ? timebuf : "(never)"); +	return rv;  } diff --git a/lib/event_counter.h b/lib/event_counter.h index f40c6cde63..730e955cd3 100644 --- a/lib/event_counter.h +++ b/lib/event_counter.h @@ -44,13 +44,12 @@  #ifndef _ZEBRA_EVENT_COUNTER_H  #define _ZEBRA_EVENT_COUNTER_H -struct event_counter -{ -  unsigned long long count; -  time_t last; +struct event_counter { +	unsigned long long count; +	time_t last;  }; -void event_counter_inc (struct event_counter *counter); -const char *event_counter_format (const struct event_counter *counter); +void event_counter_inc(struct event_counter *counter); +const char *event_counter_format(const struct event_counter *counter);  #endif diff --git a/lib/fifo.h b/lib/fifo.h index 6be75b7611..e75a72197a 100644 --- a/lib/fifo.h +++ b/lib/fifo.h @@ -21,42 +21,38 @@ Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  #define __LIB_FIFO_H__  /* FIFO -- first in first out structure and macros.  */ -struct fifo -{ -  struct fifo *next; -  struct fifo *prev; +struct fifo { +	struct fifo *next; +	struct fifo *prev;  }; -#define FIFO_INIT(F)                                  \ -  do {                                                \ -    struct fifo *Xfifo = (struct fifo *)(F);          \ -    Xfifo->next = Xfifo->prev = Xfifo;                \ -  } while (0) - -#define FIFO_ADD(F,N)                                 \ -  do {                                                \ -    struct fifo *Xfifo = (struct fifo *)(F);          \ -    struct fifo *Xnode = (struct fifo *)(N);          \ -    Xnode->next = Xfifo;                              \ -    Xnode->prev = Xfifo->prev;                        \ -    Xfifo->prev = Xfifo->prev->next = Xnode;          \ -  } while (0) - -#define FIFO_DEL(N)                                   \ -  do {                                                \ -    struct fifo *Xnode = (struct fifo *)(N);          \ -    Xnode->prev->next = Xnode->next;                  \ -    Xnode->next->prev = Xnode->prev;                  \ -  } while (0) - -#define FIFO_HEAD(F)                                  \ -  ((((struct fifo *)(F))->next == (struct fifo *)(F)) \ -  ? NULL : (F)->next) - -#define FIFO_EMPTY(F)                                 \ -  (((struct fifo *)(F))->next == (struct fifo *)(F)) - -#define FIFO_TOP(F)                                   \ -  (FIFO_EMPTY(F) ? NULL : ((struct fifo *)(F))->next) +#define FIFO_INIT(F)                                                           \ +	do {                                                                   \ +		struct fifo *Xfifo = (struct fifo *)(F);                       \ +		Xfifo->next = Xfifo->prev = Xfifo;                             \ +	} while (0) + +#define FIFO_ADD(F, N)                                                         \ +	do {                                                                   \ +		struct fifo *Xfifo = (struct fifo *)(F);                       \ +		struct fifo *Xnode = (struct fifo *)(N);                       \ +		Xnode->next = Xfifo;                                           \ +		Xnode->prev = Xfifo->prev;                                     \ +		Xfifo->prev = Xfifo->prev->next = Xnode;                       \ +	} while (0) + +#define FIFO_DEL(N)                                                            \ +	do {                                                                   \ +		struct fifo *Xnode = (struct fifo *)(N);                       \ +		Xnode->prev->next = Xnode->next;                               \ +		Xnode->next->prev = Xnode->prev;                               \ +	} while (0) + +#define FIFO_HEAD(F)                                                           \ +	((((struct fifo *)(F))->next == (struct fifo *)(F)) ? NULL : (F)->next) + +#define FIFO_EMPTY(F) (((struct fifo *)(F))->next == (struct fifo *)(F)) + +#define FIFO_TOP(F) (FIFO_EMPTY(F) ? NULL : ((struct fifo *)(F))->next)  #endif /* __LIB_FIFO_H__ */ diff --git a/lib/filter.c b/lib/filter.c index fd73d4de73..bd7e8f8b7b 100644 --- a/lib/filter.c +++ b/lib/filter.c @@ -30,475 +30,432 @@  #include "log.h"  #include "routemap.h" -DEFINE_MTYPE_STATIC(LIB, ACCESS_LIST,     "Access List") +DEFINE_MTYPE_STATIC(LIB, ACCESS_LIST, "Access List")  DEFINE_MTYPE_STATIC(LIB, ACCESS_LIST_STR, "Access List Str") -DEFINE_MTYPE_STATIC(LIB, ACCESS_FILTER,   "Access Filter") - -struct filter_cisco -{ -  /* Cisco access-list */ -  int extended; -  struct in_addr addr; -  struct in_addr addr_mask; -  struct in_addr mask; -  struct in_addr mask_mask; +DEFINE_MTYPE_STATIC(LIB, ACCESS_FILTER, "Access Filter") + +struct filter_cisco { +	/* Cisco access-list */ +	int extended; +	struct in_addr addr; +	struct in_addr addr_mask; +	struct in_addr mask; +	struct in_addr mask_mask;  }; -struct filter_zebra -{ -  /* If this filter is "exact" match then this flag is set. */ -  int exact; +struct filter_zebra { +	/* If this filter is "exact" match then this flag is set. */ +	int exact; -  /* Prefix information. */ -  struct prefix prefix; +	/* Prefix information. */ +	struct prefix prefix;  };  /* Filter element of access list */ -struct filter -{ -  /* For doubly linked list. */ -  struct filter *next; -  struct filter *prev; +struct filter { +	/* For doubly linked list. */ +	struct filter *next; +	struct filter *prev; -  /* Filter type information. */ -  enum filter_type type; +	/* Filter type information. */ +	enum filter_type type; -  /* Cisco access-list */ -  int cisco; +	/* Cisco access-list */ +	int cisco; -  union -    { -      struct filter_cisco cfilter; -      struct filter_zebra zfilter; -    } u; +	union { +		struct filter_cisco cfilter; +		struct filter_zebra zfilter; +	} u;  };  /* List of access_list. */ -struct access_list_list -{ -  struct access_list *head; -  struct access_list *tail; +struct access_list_list { +	struct access_list *head; +	struct access_list *tail;  };  /* Master structure of access_list. */ -struct access_master -{ -  /* List of access_list which name is number. */ -  struct access_list_list num; +struct access_master { +	/* List of access_list which name is number. */ +	struct access_list_list num; -  /* List of access_list which name is string. */ -  struct access_list_list str; +	/* List of access_list which name is string. */ +	struct access_list_list str; -  /* Hook function which is executed when new access_list is added. */ -  void (*add_hook) (struct access_list *); +	/* Hook function which is executed when new access_list is added. */ +	void (*add_hook)(struct access_list *); -  /* Hook function which is executed when access_list is deleted. */ -  void (*delete_hook) (struct access_list *); +	/* Hook function which is executed when access_list is deleted. */ +	void (*delete_hook)(struct access_list *);  };  /* Static structure for IPv4 access_list's master. */ -static struct access_master access_master_ipv4 =  -{  -  {NULL, NULL}, -  {NULL, NULL}, -  NULL, -  NULL, +static struct access_master access_master_ipv4 = { +	{NULL, NULL}, +	{NULL, NULL}, +	NULL, +	NULL,  };  /* Static structure for IPv6 access_list's master. */ -static struct access_master access_master_ipv6 =  -{  -  {NULL, NULL}, -  {NULL, NULL}, -  NULL, -  NULL, +static struct access_master access_master_ipv6 = { +	{NULL, NULL}, +	{NULL, NULL}, +	NULL, +	NULL,  }; -static struct access_master * -access_master_get (afi_t afi) +static struct access_master *access_master_get(afi_t afi)  { -  if (afi == AFI_IP) -    return &access_master_ipv4; -  else if (afi == AFI_IP6) -    return &access_master_ipv6; -  return NULL; +	if (afi == AFI_IP) +		return &access_master_ipv4; +	else if (afi == AFI_IP6) +		return &access_master_ipv6; +	return NULL;  }  /* Allocate new filter structure. */ -static struct filter * -filter_new (void) +static struct filter *filter_new(void)  { -  return (struct filter *) XCALLOC (MTYPE_ACCESS_FILTER, -				    sizeof (struct filter)); +	return (struct filter *)XCALLOC(MTYPE_ACCESS_FILTER, +					sizeof(struct filter));  } -static void -filter_free (struct filter *filter) +static void filter_free(struct filter *filter)  { -  XFREE (MTYPE_ACCESS_FILTER, filter); +	XFREE(MTYPE_ACCESS_FILTER, filter);  }  /* Return string of filter_type. */ -static const char * -filter_type_str (struct filter *filter) -{ -  switch (filter->type) -    { -    case FILTER_PERMIT: -      return "permit"; -      break; -    case FILTER_DENY: -      return "deny"; -      break; -    case FILTER_DYNAMIC: -      return "dynamic"; -      break; -    default: -      return ""; -      break; -    } +static const char *filter_type_str(struct filter *filter) +{ +	switch (filter->type) { +	case FILTER_PERMIT: +		return "permit"; +		break; +	case FILTER_DENY: +		return "deny"; +		break; +	case FILTER_DYNAMIC: +		return "dynamic"; +		break; +	default: +		return ""; +		break; +	}  }  /* If filter match to the prefix then return 1. */ -static int -filter_match_cisco (struct filter *mfilter, struct prefix *p) +static int filter_match_cisco(struct filter *mfilter, struct prefix *p)  { -  struct filter_cisco *filter; -  struct in_addr mask; -  u_int32_t check_addr; -  u_int32_t check_mask; +	struct filter_cisco *filter; +	struct in_addr mask; +	u_int32_t check_addr; +	u_int32_t check_mask; -  filter = &mfilter->u.cfilter; -  check_addr = p->u.prefix4.s_addr & ~filter->addr_mask.s_addr; +	filter = &mfilter->u.cfilter; +	check_addr = p->u.prefix4.s_addr & ~filter->addr_mask.s_addr; -  if (filter->extended) -    { -      masklen2ip (p->prefixlen, &mask); -      check_mask = mask.s_addr & ~filter->mask_mask.s_addr; +	if (filter->extended) { +		masklen2ip(p->prefixlen, &mask); +		check_mask = mask.s_addr & ~filter->mask_mask.s_addr; -      if (memcmp (&check_addr, &filter->addr.s_addr, 4) == 0 -          && memcmp (&check_mask, &filter->mask.s_addr, 4) == 0) -	return 1; -    } -  else if (memcmp (&check_addr, &filter->addr.s_addr, 4) == 0) -    return 1; +		if (memcmp(&check_addr, &filter->addr.s_addr, 4) == 0 +		    && memcmp(&check_mask, &filter->mask.s_addr, 4) == 0) +			return 1; +	} else if (memcmp(&check_addr, &filter->addr.s_addr, 4) == 0) +		return 1; -  return 0; +	return 0;  }  /* If filter match to the prefix then return 1. */ -static int -filter_match_zebra (struct filter *mfilter, struct prefix *p) +static int filter_match_zebra(struct filter *mfilter, struct prefix *p)  { -  struct filter_zebra *filter; +	struct filter_zebra *filter; -  filter = &mfilter->u.zfilter; +	filter = &mfilter->u.zfilter; -  if (filter->prefix.family == p->family) -    { -      if (filter->exact) -	{ -	  if (filter->prefix.prefixlen == p->prefixlen) -	    return prefix_match (&filter->prefix, p); -	  else -	    return 0; -	} -      else -	return prefix_match (&filter->prefix, p); -    } -  else -    return 0; +	if (filter->prefix.family == p->family) { +		if (filter->exact) { +			if (filter->prefix.prefixlen == p->prefixlen) +				return prefix_match(&filter->prefix, p); +			else +				return 0; +		} else +			return prefix_match(&filter->prefix, p); +	} else +		return 0;  }  /* Allocate new access list structure. */ -static struct access_list * -access_list_new (void) +static struct access_list *access_list_new(void)  { -  return (struct access_list *) XCALLOC (MTYPE_ACCESS_LIST, -					 sizeof (struct access_list)); +	return (struct access_list *)XCALLOC(MTYPE_ACCESS_LIST, +					     sizeof(struct access_list));  }  /* Free allocated access_list. */ -static void -access_list_free (struct access_list *access) +static void access_list_free(struct access_list *access)  { -  XFREE (MTYPE_ACCESS_LIST, access); +	XFREE(MTYPE_ACCESS_LIST, access);  }  /* Delete access_list from access_master and free it. */ -static void -access_list_delete (struct access_list *access) +static void access_list_delete(struct access_list *access)  { -  struct filter *filter; -  struct filter *next; -  struct access_list_list *list; -  struct access_master *master; +	struct filter *filter; +	struct filter *next; +	struct access_list_list *list; +	struct access_master *master; -  for (filter = access->head; filter; filter = next) -    { -      next = filter->next; -      filter_free (filter); -    } +	for (filter = access->head; filter; filter = next) { +		next = filter->next; +		filter_free(filter); +	} -  master = access->master; +	master = access->master; -  if (access->type == ACCESS_TYPE_NUMBER) -    list = &master->num; -  else -    list = &master->str; +	if (access->type == ACCESS_TYPE_NUMBER) +		list = &master->num; +	else +		list = &master->str; -  if (access->next) -    access->next->prev = access->prev; -  else -    list->tail = access->prev; +	if (access->next) +		access->next->prev = access->prev; +	else +		list->tail = access->prev; -  if (access->prev) -    access->prev->next = access->next; -  else -    list->head = access->next; +	if (access->prev) +		access->prev->next = access->next; +	else +		list->head = access->next; -  if (access->name) -    XFREE (MTYPE_ACCESS_LIST_STR, access->name); +	if (access->name) +		XFREE(MTYPE_ACCESS_LIST_STR, access->name); -  if (access->remark) -    XFREE (MTYPE_TMP, access->remark); +	if (access->remark) +		XFREE(MTYPE_TMP, access->remark); -  access_list_free (access); +	access_list_free(access);  }  /* Insert new access list to list of access_list.  Each acceess_list     is sorted by the name. */ -static struct access_list * -access_list_insert (afi_t afi, const char *name) -{ -  unsigned int i; -  long number; -  struct access_list *access; -  struct access_list *point; -  struct access_list_list *alist; -  struct access_master *master; - -  master = access_master_get (afi); -  if (master == NULL) -    return NULL; - -  /* Allocate new access_list and copy given name. */ -  access = access_list_new (); -  access->name = XSTRDUP (MTYPE_ACCESS_LIST_STR, name); -  access->master = master; - -  /* If name is made by all digit character.  We treat it as -     number. */ -  for (number = 0, i = 0; i < strlen (name); i++) -    { -      if (isdigit ((int) name[i])) -	number = (number * 10) + (name[i] - '0'); -      else -	break; -    } - -  /* In case of name is all digit character */ -  if (i == strlen (name)) -    { -      access->type = ACCESS_TYPE_NUMBER; - -      /* Set access_list to number list. */ -      alist = &master->num; - -      for (point = alist->head; point; point = point->next) -	if (atol (point->name) >= number) -	  break; -    } -  else -    { -      access->type = ACCESS_TYPE_STRING; - -      /* Set access_list to string list. */ -      alist = &master->str; -   -      /* Set point to insertion point. */ -      for (point = alist->head; point; point = point->next) -	if (strcmp (point->name, name) >= 0) -	  break; -    } - -  /* In case of this is the first element of master. */ -  if (alist->head == NULL) -    { -      alist->head = alist->tail = access; -      return access; -    } - -  /* In case of insertion is made at the tail of access_list. */ -  if (point == NULL) -    { -      access->prev = alist->tail; -      alist->tail->next = access; -      alist->tail = access; -      return access; -    } - -  /* In case of insertion is made at the head of access_list. */ -  if (point == alist->head) -    { -      access->next = alist->head; -      alist->head->prev = access; -      alist->head = access; -      return access; -    } - -  /* Insertion is made at middle of the access_list. */ -  access->next = point; -  access->prev = point->prev; - -  if (point->prev) -    point->prev->next = access; -  point->prev = access; - -  return access; +static struct access_list *access_list_insert(afi_t afi, const char *name) +{ +	unsigned int i; +	long number; +	struct access_list *access; +	struct access_list *point; +	struct access_list_list *alist; +	struct access_master *master; + +	master = access_master_get(afi); +	if (master == NULL) +		return NULL; + +	/* Allocate new access_list and copy given name. */ +	access = access_list_new(); +	access->name = XSTRDUP(MTYPE_ACCESS_LIST_STR, name); +	access->master = master; + +	/* If name is made by all digit character.  We treat it as +	   number. */ +	for (number = 0, i = 0; i < strlen(name); i++) { +		if (isdigit((int)name[i])) +			number = (number * 10) + (name[i] - '0'); +		else +			break; +	} + +	/* In case of name is all digit character */ +	if (i == strlen(name)) { +		access->type = ACCESS_TYPE_NUMBER; + +		/* Set access_list to number list. */ +		alist = &master->num; + +		for (point = alist->head; point; point = point->next) +			if (atol(point->name) >= number) +				break; +	} else { +		access->type = ACCESS_TYPE_STRING; + +		/* Set access_list to string list. */ +		alist = &master->str; + +		/* Set point to insertion point. */ +		for (point = alist->head; point; point = point->next) +			if (strcmp(point->name, name) >= 0) +				break; +	} + +	/* In case of this is the first element of master. */ +	if (alist->head == NULL) { +		alist->head = alist->tail = access; +		return access; +	} + +	/* In case of insertion is made at the tail of access_list. */ +	if (point == NULL) { +		access->prev = alist->tail; +		alist->tail->next = access; +		alist->tail = access; +		return access; +	} + +	/* In case of insertion is made at the head of access_list. */ +	if (point == alist->head) { +		access->next = alist->head; +		alist->head->prev = access; +		alist->head = access; +		return access; +	} + +	/* Insertion is made at middle of the access_list. */ +	access->next = point; +	access->prev = point->prev; + +	if (point->prev) +		point->prev->next = access; +	point->prev = access; + +	return access;  }  /* Lookup access_list from list of access_list by name. */ -struct access_list * -access_list_lookup (afi_t afi, const char *name) +struct access_list *access_list_lookup(afi_t afi, const char *name)  { -  struct access_list *access; -  struct access_master *master; +	struct access_list *access; +	struct access_master *master; -  if (name == NULL) -    return NULL; +	if (name == NULL) +		return NULL; -  master = access_master_get (afi); -  if (master == NULL) -    return NULL; +	master = access_master_get(afi); +	if (master == NULL) +		return NULL; -  for (access = master->num.head; access; access = access->next) -    if (strcmp (access->name, name) == 0) -      return access; +	for (access = master->num.head; access; access = access->next) +		if (strcmp(access->name, name) == 0) +			return access; -  for (access = master->str.head; access; access = access->next) -    if (strcmp (access->name, name) == 0) -      return access; +	for (access = master->str.head; access; access = access->next) +		if (strcmp(access->name, name) == 0) +			return access; -  return NULL; +	return NULL;  }  /* Get access list from list of access_list.  If there isn't matched     access_list create new one and return it. */ -static struct access_list * -access_list_get (afi_t afi, const char *name) +static struct access_list *access_list_get(afi_t afi, const char *name)  { -  struct access_list *access; +	struct access_list *access; -  access = access_list_lookup (afi, name); -  if (access == NULL) -    access = access_list_insert (afi, name); -  return access; +	access = access_list_lookup(afi, name); +	if (access == NULL) +		access = access_list_insert(afi, name); +	return access;  }  /* Apply access list to object (which should be struct prefix *). */ -enum filter_type -access_list_apply (struct access_list *access, void *object) +enum filter_type access_list_apply(struct access_list *access, void *object)  { -  struct filter *filter; -  struct prefix *p; +	struct filter *filter; +	struct prefix *p; -  p = (struct prefix *) object; +	p = (struct prefix *)object; -  if (access == NULL) -    return FILTER_DENY; +	if (access == NULL) +		return FILTER_DENY; -  for (filter = access->head; filter; filter = filter->next) -    { -      if (filter->cisco) -	{ -	  if (filter_match_cisco (filter, p)) -	    return filter->type; -	} -      else -	{ -	  if (filter_match_zebra (filter, p)) -	    return filter->type; +	for (filter = access->head; filter; filter = filter->next) { +		if (filter->cisco) { +			if (filter_match_cisco(filter, p)) +				return filter->type; +		} else { +			if (filter_match_zebra(filter, p)) +				return filter->type; +		}  	} -    } -  return FILTER_DENY; +	return FILTER_DENY;  }  /* Add hook function. */ -void -access_list_add_hook (void (*func) (struct access_list *access)) +void access_list_add_hook(void (*func)(struct access_list *access))  { -  access_master_ipv4.add_hook = func; -  access_master_ipv6.add_hook = func; +	access_master_ipv4.add_hook = func; +	access_master_ipv6.add_hook = func;  }  /* Delete hook function. */ -void -access_list_delete_hook (void (*func) (struct access_list *access)) +void access_list_delete_hook(void (*func)(struct access_list *access))  { -  access_master_ipv4.delete_hook = func; -  access_master_ipv6.delete_hook = func; +	access_master_ipv4.delete_hook = func; +	access_master_ipv6.delete_hook = func;  }  /* Add new filter to the end of specified access_list. */ -static void -access_list_filter_add (struct access_list *access, struct filter *filter) +static void access_list_filter_add(struct access_list *access, +				   struct filter *filter)  { -  filter->next = NULL; -  filter->prev = access->tail; +	filter->next = NULL; +	filter->prev = access->tail; -  if (access->tail) -    access->tail->next = filter; -  else -    access->head = filter; -  access->tail = filter; +	if (access->tail) +		access->tail->next = filter; +	else +		access->head = filter; +	access->tail = filter; -  /* Run hook function. */ -  if (access->master->add_hook) -    (*access->master->add_hook) (access); -  route_map_notify_dependencies(access->name, RMAP_EVENT_FILTER_ADDED); +	/* Run hook function. */ +	if (access->master->add_hook) +		(*access->master->add_hook)(access); +	route_map_notify_dependencies(access->name, RMAP_EVENT_FILTER_ADDED);  }  /* If access_list has no filter then return 1. */ -static int -access_list_empty (struct access_list *access) +static int access_list_empty(struct access_list *access)  { -  if (access->head == NULL && access->tail == NULL) -    return 1; -  else -    return 0; +	if (access->head == NULL && access->tail == NULL) +		return 1; +	else +		return 0;  }  /* Delete filter from specified access_list.  If there is hook     function execute it. */ -static void -access_list_filter_delete (struct access_list *access, struct filter *filter) +static void access_list_filter_delete(struct access_list *access, +				      struct filter *filter)  { -  struct access_master *master; +	struct access_master *master; -  master = access->master; +	master = access->master; -  if (filter->next) -    filter->next->prev = filter->prev; -  else -    access->tail = filter->prev; +	if (filter->next) +		filter->next->prev = filter->prev; +	else +		access->tail = filter->prev; -  if (filter->prev) -    filter->prev->next = filter->next; -  else -    access->head = filter->next; +	if (filter->prev) +		filter->prev->next = filter->next; +	else +		access->head = filter->next; -  filter_free (filter); +	filter_free(filter); -  route_map_notify_dependencies(access->name, RMAP_EVENT_FILTER_DELETED); -  /* Run hook function. */ -  if (master->delete_hook) -    (*master->delete_hook) (access); +	route_map_notify_dependencies(access->name, RMAP_EVENT_FILTER_DELETED); +	/* Run hook function. */ +	if (master->delete_hook) +		(*master->delete_hook)(access); -  /* If access_list becomes empty delete it from access_master. */ -  if (access_list_empty (access)) -    access_list_delete (access); +	/* If access_list becomes empty delete it from access_master. */ +	if (access_list_empty(access)) +		access_list_delete(access);  }  /* @@ -513,184 +470,169 @@ access_list_filter_delete (struct access_list *access, struct filter *filter)    host                 A single host address  */ -static struct filter * -filter_lookup_cisco (struct access_list *access, struct filter *mnew) +static struct filter *filter_lookup_cisco(struct access_list *access, +					  struct filter *mnew) +{ +	struct filter *mfilter; +	struct filter_cisco *filter; +	struct filter_cisco *new; + +	new = &mnew->u.cfilter; + +	for (mfilter = access->head; mfilter; mfilter = mfilter->next) { +		filter = &mfilter->u.cfilter; + +		if (filter->extended) { +			if (mfilter->type == mnew->type +			    && filter->addr.s_addr == new->addr.s_addr +			    && filter->addr_mask.s_addr == new->addr_mask.s_addr +			    && filter->mask.s_addr == new->mask.s_addr +			    && filter->mask_mask.s_addr +				       == new->mask_mask.s_addr) +				return mfilter; +		} else { +			if (mfilter->type == mnew->type +			    && filter->addr.s_addr == new->addr.s_addr +			    && filter->addr_mask.s_addr +				       == new->addr_mask.s_addr) +				return mfilter; +		} +	} + +	return NULL; +} + +static struct filter *filter_lookup_zebra(struct access_list *access, +					  struct filter *mnew)  { -  struct filter *mfilter; -  struct filter_cisco *filter; -  struct filter_cisco *new; +	struct filter *mfilter; +	struct filter_zebra *filter; +	struct filter_zebra *new; -  new = &mnew->u.cfilter; +	new = &mnew->u.zfilter; -  for (mfilter = access->head; mfilter; mfilter = mfilter->next) -    { -      filter = &mfilter->u.cfilter; +	for (mfilter = access->head; mfilter; mfilter = mfilter->next) { +		filter = &mfilter->u.zfilter; -      if (filter->extended) -	{ -	  if (mfilter->type == mnew->type -	      && filter->addr.s_addr == new->addr.s_addr -	      && filter->addr_mask.s_addr == new->addr_mask.s_addr -	      && filter->mask.s_addr == new->mask.s_addr -	      && filter->mask_mask.s_addr == new->mask_mask.s_addr) -	    return mfilter; +		if (filter->exact == new->exact +		    && mfilter->type +			       == mnew->type &&prefix_same(&filter->prefix, +							   &new->prefix)) +			return mfilter;  	} -      else -	{ -	  if (mfilter->type == mnew->type -	      && filter->addr.s_addr == new->addr.s_addr -	      && filter->addr_mask.s_addr == new->addr_mask.s_addr) -	    return mfilter; +	return NULL; +} + +static int vty_access_list_remark_unset(struct vty *vty, afi_t afi, +					const char *name) +{ +	struct access_list *access; + +	access = access_list_lookup(afi, name); +	if (!access) { +		vty_out(vty, "%% access-list %s doesn't exist%s", name, +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	if (access->remark) { +		XFREE(MTYPE_TMP, access->remark); +		access->remark = NULL;  	} -    } - -  return NULL; -} - -static struct filter * -filter_lookup_zebra (struct access_list *access, struct filter *mnew) -{ -  struct filter *mfilter; -  struct filter_zebra *filter; -  struct filter_zebra *new; - -  new = &mnew->u.zfilter; - -  for (mfilter = access->head; mfilter; mfilter = mfilter->next) -    { -      filter = &mfilter->u.zfilter; - -      if (filter->exact == new->exact -	  && mfilter->type == mnew->type -	  && prefix_same (&filter->prefix, &new->prefix)) -	return mfilter; -    } -  return NULL; -} - -static int -vty_access_list_remark_unset (struct vty *vty, afi_t afi, const char *name) -{ -  struct access_list *access; - -  access = access_list_lookup (afi, name); -  if (! access) -    { -      vty_out (vty, "%% access-list %s doesn't exist%s", name, -	       VTY_NEWLINE); -      return CMD_WARNING; -    } - -  if (access->remark) -    { -      XFREE (MTYPE_TMP, access->remark); -      access->remark = NULL; -    } - -  if (access->head == NULL && access->tail == NULL && access->remark == NULL) -    access_list_delete (access); - -  return CMD_SUCCESS; -} - -static int -filter_set_cisco (struct vty *vty, const char *name_str, const char *type_str, -		  const char *addr_str, const char *addr_mask_str, -		  const char *mask_str, const char *mask_mask_str, -		  int extended, int set) -{ -  int ret; -  enum filter_type type; -  struct filter *mfilter; -  struct filter_cisco *filter; -  struct access_list *access; -  struct in_addr addr; -  struct in_addr addr_mask; -  struct in_addr mask; -  struct in_addr mask_mask; - -  /* Check of filter type. */ -  if (strncmp (type_str, "p", 1) == 0) -    type = FILTER_PERMIT; -  else if (strncmp (type_str, "d", 1) == 0) -    type = FILTER_DENY; -  else -    { -      vty_out (vty, "%% filter type must be permit or deny%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  ret = inet_aton (addr_str, &addr); -  if (ret <= 0) -    { -      vty_out (vty, "%%Inconsistent address and mask%s", -	       VTY_NEWLINE); -      return CMD_WARNING; -    } - -  ret = inet_aton (addr_mask_str, &addr_mask); -  if (ret <= 0) -    { -      vty_out (vty, "%%Inconsistent address and mask%s", -	       VTY_NEWLINE); -      return CMD_WARNING; -    } - -  if (extended) -    { -      ret = inet_aton (mask_str, &mask); -      if (ret <= 0) -	{ -	  vty_out (vty, "%%Inconsistent address and mask%s", -		   VTY_NEWLINE); -	  return CMD_WARNING; + +	if (access->head == NULL && access->tail == NULL +	    && access->remark == NULL) +		access_list_delete(access); + +	return CMD_SUCCESS; +} + +static int filter_set_cisco(struct vty *vty, const char *name_str, +			    const char *type_str, const char *addr_str, +			    const char *addr_mask_str, const char *mask_str, +			    const char *mask_mask_str, int extended, int set) +{ +	int ret; +	enum filter_type type; +	struct filter *mfilter; +	struct filter_cisco *filter; +	struct access_list *access; +	struct in_addr addr; +	struct in_addr addr_mask; +	struct in_addr mask; +	struct in_addr mask_mask; + +	/* Check of filter type. */ +	if (strncmp(type_str, "p", 1) == 0) +		type = FILTER_PERMIT; +	else if (strncmp(type_str, "d", 1) == 0) +		type = FILTER_DENY; +	else { +		vty_out(vty, "%% filter type must be permit or deny%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	ret = inet_aton(addr_str, &addr); +	if (ret <= 0) { +		vty_out(vty, "%%Inconsistent address and mask%s", VTY_NEWLINE); +		return CMD_WARNING; +	} + +	ret = inet_aton(addr_mask_str, &addr_mask); +	if (ret <= 0) { +		vty_out(vty, "%%Inconsistent address and mask%s", VTY_NEWLINE); +		return CMD_WARNING; +	} + +	if (extended) { +		ret = inet_aton(mask_str, &mask); +		if (ret <= 0) { +			vty_out(vty, "%%Inconsistent address and mask%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} + +		ret = inet_aton(mask_mask_str, &mask_mask); +		if (ret <= 0) { +			vty_out(vty, "%%Inconsistent address and mask%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} +	} + +	mfilter = filter_new(); +	mfilter->type = type; +	mfilter->cisco = 1; +	filter = &mfilter->u.cfilter; +	filter->extended = extended; +	filter->addr.s_addr = addr.s_addr & ~addr_mask.s_addr; +	filter->addr_mask.s_addr = addr_mask.s_addr; + +	if (extended) { +		filter->mask.s_addr = mask.s_addr & ~mask_mask.s_addr; +		filter->mask_mask.s_addr = mask_mask.s_addr;  	} -      ret = inet_aton (mask_mask_str, &mask_mask); -      if (ret <= 0) -	{ -	  vty_out (vty, "%%Inconsistent address and mask%s", -		   VTY_NEWLINE); -	  return CMD_WARNING; +	/* Install new filter to the access_list. */ +	access = access_list_get(AFI_IP, name_str); + +	if (set) { +		if (filter_lookup_cisco(access, mfilter)) +			filter_free(mfilter); +		else +			access_list_filter_add(access, mfilter); +	} else { +		struct filter *delete_filter; + +		delete_filter = filter_lookup_cisco(access, mfilter); +		if (delete_filter) +			access_list_filter_delete(access, delete_filter); + +		filter_free(mfilter);  	} -    } - -  mfilter = filter_new(); -  mfilter->type = type; -  mfilter->cisco = 1; -  filter = &mfilter->u.cfilter; -  filter->extended = extended; -  filter->addr.s_addr = addr.s_addr & ~addr_mask.s_addr; -  filter->addr_mask.s_addr = addr_mask.s_addr; - -  if (extended) -    { -      filter->mask.s_addr = mask.s_addr & ~mask_mask.s_addr; -      filter->mask_mask.s_addr = mask_mask.s_addr; -    } - -  /* Install new filter to the access_list. */ -  access = access_list_get (AFI_IP, name_str); - -  if (set) -    { -      if (filter_lookup_cisco (access, mfilter)) -	filter_free (mfilter); -      else -	access_list_filter_add (access, mfilter); -    } -  else -    { -      struct filter *delete_filter; - -      delete_filter = filter_lookup_cisco (access, mfilter); -      if (delete_filter) -	access_list_filter_delete (access, delete_filter); - -      filter_free (mfilter); -    } - -  return CMD_SUCCESS; + +	return CMD_SUCCESS;  }  /* Standard access-list */ @@ -705,12 +647,13 @@ DEFUN (access_list_standard,         "Address to match\n"         "Wildcard bits\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 3; -  int idx_ipv4_2 = 4; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, argv[idx_ipv4_2]->arg, -			   NULL, NULL, 0, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 3; +	int idx_ipv4_2 = 4; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, NULL, NULL, 0, 1);  }  DEFUN (access_list_standard_nomask, @@ -723,11 +666,12 @@ DEFUN (access_list_standard_nomask,         "Specify packets to forward\n"         "Address to match\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 3; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, "0.0.0.0", -			   NULL, NULL, 0, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 3; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", NULL, NULL, 0, 1);  }  DEFUN (access_list_standard_host, @@ -741,11 +685,12 @@ DEFUN (access_list_standard_host,         "A single host address\n"         "Address to match\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 4; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, "0.0.0.0", -			   NULL, NULL, 0, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 4; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", NULL, NULL, 0, 1);  }  DEFUN (access_list_standard_any, @@ -758,10 +703,11 @@ DEFUN (access_list_standard_any,         "Specify packets to forward\n"         "Any source host\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", -			   "255.255.255.255", NULL, NULL, 0, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, "0.0.0.0", +				"255.255.255.255", NULL, NULL, 0, 1);  }  DEFUN (no_access_list_standard, @@ -776,12 +722,13 @@ DEFUN (no_access_list_standard,         "Address to match\n"         "Wildcard bits\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 4; -  int idx_ipv4_2 = 5; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, argv[idx_ipv4_2]->arg, -			   NULL, NULL, 0, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 4; +	int idx_ipv4_2 = 5; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, NULL, NULL, 0, 0);  }  DEFUN (no_access_list_standard_nomask, @@ -795,11 +742,12 @@ DEFUN (no_access_list_standard_nomask,         "Specify packets to forward\n"         "Address to match\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 4; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, "0.0.0.0", -			   NULL, NULL, 0, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 4; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", NULL, NULL, 0, 0);  }  DEFUN (no_access_list_standard_host, @@ -814,11 +762,12 @@ DEFUN (no_access_list_standard_host,         "A single host address\n"         "Address to match\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 5; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, "0.0.0.0", -			   NULL, NULL, 0, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 5; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", NULL, NULL, 0, 0);  }  DEFUN (no_access_list_standard_any, @@ -832,10 +781,11 @@ DEFUN (no_access_list_standard_any,         "Specify packets to forward\n"         "Any source host\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", -			   "255.255.255.255", NULL, NULL, 0, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, "0.0.0.0", +				"255.255.255.255", NULL, NULL, 0, 0);  }  /* Extended access-list */ @@ -853,14 +803,16 @@ DEFUN (access_list_extended,         "Destination address\n"         "Destination Wildcard bits\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 4; -  int idx_ipv4_2 = 5; -  int idx_ipv4_3 = 6; -  int idx_ipv4_4 = 7; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   argv[idx_ipv4_2]->arg, argv[idx_ipv4_3]->arg, argv[idx_ipv4_4]->arg, 1 ,1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 4; +	int idx_ipv4_2 = 5; +	int idx_ipv4_3 = 6; +	int idx_ipv4_4 = 7; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, argv[idx_ipv4_3]->arg, +				argv[idx_ipv4_4]->arg, 1, 1);  }  DEFUN (access_list_extended_mask_any, @@ -876,13 +828,14 @@ DEFUN (access_list_extended_mask_any,         "Source wildcard bits\n"         "Any destination host\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 4; -  int idx_ipv4_2 = 5; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   argv[idx_ipv4_2]->arg, "0.0.0.0", -			   "255.255.255.255", 1, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 4; +	int idx_ipv4_2 = 5; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, "0.0.0.0", +				"255.255.255.255", 1, 1);  }  DEFUN (access_list_extended_any_mask, @@ -898,13 +851,14 @@ DEFUN (access_list_extended_any_mask,         "Destination address\n"         "Destination Wildcard bits\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 5; -  int idx_ipv4_2 = 6; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", -			   "255.255.255.255", argv[idx_ipv4]->arg, -			   argv[idx_ipv4_2]->arg, 1, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 5; +	int idx_ipv4_2 = 6; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, "0.0.0.0", +				"255.255.255.255", argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, 1, 1);  }  DEFUN (access_list_extended_any_any, @@ -919,11 +873,11 @@ DEFUN (access_list_extended_any_any,         "Any source host\n"         "Any destination host\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", -			   "255.255.255.255", "0.0.0.0", -			   "255.255.255.255", 1, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	return filter_set_cisco( +		vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", +		"255.255.255.255", "0.0.0.0", "255.255.255.255", 1, 1);  }  DEFUN (access_list_extended_mask_host, @@ -940,14 +894,15 @@ DEFUN (access_list_extended_mask_host,         "A single destination host\n"         "Destination address\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 4; -  int idx_ipv4_2 = 5; -  int idx_ipv4_3 = 7; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   argv[idx_ipv4_2]->arg, argv[idx_ipv4_3]->arg, -			   "0.0.0.0", 1, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 4; +	int idx_ipv4_2 = 5; +	int idx_ipv4_3 = 7; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, argv[idx_ipv4_3]->arg, +				"0.0.0.0", 1, 1);  }  DEFUN (access_list_extended_host_mask, @@ -964,14 +919,15 @@ DEFUN (access_list_extended_host_mask,         "Destination address\n"         "Destination Wildcard bits\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 5; -  int idx_ipv4_2 = 6; -  int idx_ipv4_3 = 7; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   "0.0.0.0", argv[idx_ipv4_2]->arg, -			   argv[idx_ipv4_3]->arg, 1, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 5; +	int idx_ipv4_2 = 6; +	int idx_ipv4_3 = 7; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", argv[idx_ipv4_2]->arg, +				argv[idx_ipv4_3]->arg, 1, 1);  }  DEFUN (access_list_extended_host_host, @@ -988,13 +944,14 @@ DEFUN (access_list_extended_host_host,         "A single destination host\n"         "Destination address\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 5; -  int idx_ipv4_2 = 7; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   "0.0.0.0", argv[idx_ipv4_2]->arg, -			   "0.0.0.0", 1, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 5; +	int idx_ipv4_2 = 7; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", argv[idx_ipv4_2]->arg, "0.0.0.0", 1, +				1);  }  DEFUN (access_list_extended_any_host, @@ -1010,12 +967,12 @@ DEFUN (access_list_extended_any_host,         "A single destination host\n"         "Destination address\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 6; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", -			   "255.255.255.255", argv[idx_ipv4]->arg, -			   "0.0.0.0", 1, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 6; +	return filter_set_cisco( +		vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", +		"255.255.255.255", argv[idx_ipv4]->arg, "0.0.0.0", 1, 1);  }  DEFUN (access_list_extended_host_any, @@ -1031,12 +988,12 @@ DEFUN (access_list_extended_host_any,         "Source address\n"         "Any destination host\n")  { -  int idx_acl = 1; -  int idx_permit_deny = 2; -  int idx_ipv4 = 5; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   "0.0.0.0", "0.0.0.0", -			   "255.255.255.255", 1, 1); +	int idx_acl = 1; +	int idx_permit_deny = 2; +	int idx_ipv4 = 5; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", "0.0.0.0", "255.255.255.255", 1, 1);  }  DEFUN (no_access_list_extended, @@ -1054,14 +1011,16 @@ DEFUN (no_access_list_extended,         "Destination address\n"         "Destination Wildcard bits\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 5; -  int idx_ipv4_2 = 6; -  int idx_ipv4_3 = 7; -  int idx_ipv4_4 = 8; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   argv[idx_ipv4_2]->arg, argv[idx_ipv4_3]->arg, argv[idx_ipv4_4]->arg, 1, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 5; +	int idx_ipv4_2 = 6; +	int idx_ipv4_3 = 7; +	int idx_ipv4_4 = 8; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, argv[idx_ipv4_3]->arg, +				argv[idx_ipv4_4]->arg, 1, 0);  }  DEFUN (no_access_list_extended_mask_any, @@ -1078,13 +1037,14 @@ DEFUN (no_access_list_extended_mask_any,         "Source wildcard bits\n"         "Any destination host\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 5; -  int idx_ipv4_2 = 6; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   argv[idx_ipv4_2]->arg, "0.0.0.0", -			   "255.255.255.255", 1, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 5; +	int idx_ipv4_2 = 6; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, "0.0.0.0", +				"255.255.255.255", 1, 0);  }  DEFUN (no_access_list_extended_any_mask, @@ -1101,13 +1061,14 @@ DEFUN (no_access_list_extended_any_mask,         "Destination address\n"         "Destination Wildcard bits\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 6; -  int idx_ipv4_2 = 7; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", -			   "255.255.255.255", argv[idx_ipv4]->arg, -			   argv[idx_ipv4_2]->arg, 1, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 6; +	int idx_ipv4_2 = 7; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, "0.0.0.0", +				"255.255.255.255", argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, 1, 0);  }  DEFUN (no_access_list_extended_any_any, @@ -1123,11 +1084,11 @@ DEFUN (no_access_list_extended_any_any,         "Any source host\n"         "Any destination host\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", -			   "255.255.255.255", "0.0.0.0", -			   "255.255.255.255", 1, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	return filter_set_cisco( +		vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", +		"255.255.255.255", "0.0.0.0", "255.255.255.255", 1, 0);  }  DEFUN (no_access_list_extended_mask_host, @@ -1145,14 +1106,15 @@ DEFUN (no_access_list_extended_mask_host,         "A single destination host\n"         "Destination address\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 5; -  int idx_ipv4_2 = 6; -  int idx_ipv4_3 = 8; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   argv[idx_ipv4_2]->arg, argv[idx_ipv4_3]->arg, -			   "0.0.0.0", 1, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 5; +	int idx_ipv4_2 = 6; +	int idx_ipv4_3 = 8; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				argv[idx_ipv4_2]->arg, argv[idx_ipv4_3]->arg, +				"0.0.0.0", 1, 0);  }  DEFUN (no_access_list_extended_host_mask, @@ -1170,14 +1132,15 @@ DEFUN (no_access_list_extended_host_mask,         "Destination address\n"         "Destination Wildcard bits\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 6; -  int idx_ipv4_2 = 7; -  int idx_ipv4_3 = 8; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   "0.0.0.0", argv[idx_ipv4_2]->arg, -			   argv[idx_ipv4_3]->arg, 1, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 6; +	int idx_ipv4_2 = 7; +	int idx_ipv4_3 = 8; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", argv[idx_ipv4_2]->arg, +				argv[idx_ipv4_3]->arg, 1, 0);  }  DEFUN (no_access_list_extended_host_host, @@ -1195,13 +1158,14 @@ DEFUN (no_access_list_extended_host_host,         "A single destination host\n"         "Destination address\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 6; -  int idx_ipv4_2 = 8; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   "0.0.0.0", argv[idx_ipv4_2]->arg, -			   "0.0.0.0", 1, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 6; +	int idx_ipv4_2 = 8; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", argv[idx_ipv4_2]->arg, "0.0.0.0", 1, +				0);  }  DEFUN (no_access_list_extended_any_host, @@ -1218,12 +1182,12 @@ DEFUN (no_access_list_extended_any_host,         "A single destination host\n"         "Destination address\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 7; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", -			   "255.255.255.255", argv[idx_ipv4]->arg, -			   "0.0.0.0", 1, 0); +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 7; +	return filter_set_cisco( +		vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, "0.0.0.0", +		"255.255.255.255", argv[idx_ipv4]->arg, "0.0.0.0", 1, 0);  }  DEFUN (no_access_list_extended_host_any, @@ -1240,99 +1204,92 @@ DEFUN (no_access_list_extended_host_any,         "Source address\n"         "Any destination host\n")  { -  int idx_acl = 2; -  int idx_permit_deny = 3; -  int idx_ipv4 = 6; -  return filter_set_cisco (vty, argv[idx_acl]->arg, argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, -			   "0.0.0.0", "0.0.0.0", -			   "255.255.255.255", 1, 0); -} - -static int -filter_set_zebra (struct vty *vty, const char *name_str, const char *type_str, -		  afi_t afi, const char *prefix_str, int exact, int set) -{ -  int ret; -  enum filter_type type; -  struct filter *mfilter; -  struct filter_zebra *filter; -  struct access_list *access; -  struct prefix p; - -  if (strlen(name_str) > ACL_NAMSIZ) -    { -      vty_out (vty, "%% ACL name %s is invalid: length exceeds " -                    "%d characters%s", -               name_str, ACL_NAMSIZ, VTY_NEWLINE); -      return CMD_WARNING; -    } - -  /* Check of filter type. */ -  if (strncmp (type_str, "p", 1) == 0) -    type = FILTER_PERMIT; -  else if (strncmp (type_str, "d", 1) == 0) -    type = FILTER_DENY; -  else -    { -      vty_out (vty, "filter type must be [permit|deny]%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  /* Check string format of prefix and prefixlen. */ -  if (afi == AFI_IP) -    { -      ret = str2prefix_ipv4 (prefix_str, (struct prefix_ipv4 *)&p); -      if (ret <= 0) -	{ -	  vty_out (vty, "IP address prefix/prefixlen is malformed%s", -		   VTY_NEWLINE); -	  return CMD_WARNING; +	int idx_acl = 2; +	int idx_permit_deny = 3; +	int idx_ipv4 = 6; +	return filter_set_cisco(vty, argv[idx_acl]->arg, +				argv[idx_permit_deny]->arg, argv[idx_ipv4]->arg, +				"0.0.0.0", "0.0.0.0", "255.255.255.255", 1, 0); +} + +static int filter_set_zebra(struct vty *vty, const char *name_str, +			    const char *type_str, afi_t afi, +			    const char *prefix_str, int exact, int set) +{ +	int ret; +	enum filter_type type; +	struct filter *mfilter; +	struct filter_zebra *filter; +	struct access_list *access; +	struct prefix p; + +	if (strlen(name_str) > ACL_NAMSIZ) { +		vty_out(vty, +			"%% ACL name %s is invalid: length exceeds " +			"%d characters%s", +			name_str, ACL_NAMSIZ, VTY_NEWLINE); +		return CMD_WARNING;  	} -    } -  else if (afi == AFI_IP6) -    { -      ret = str2prefix_ipv6 (prefix_str, (struct prefix_ipv6 *) &p); -      if (ret <= 0) -	{ -	  vty_out (vty, "IPv6 address prefix/prefixlen is malformed%s", -		   VTY_NEWLINE); -		   return CMD_WARNING; -	} -    } -  else -    return CMD_WARNING; - -  mfilter = filter_new (); -  mfilter->type = type; -  filter = &mfilter->u.zfilter; -  prefix_copy (&filter->prefix, &p); - -  /* "exact-match" */ -  if (exact) -    filter->exact = 1; -  /* Install new filter to the access_list. */ -  access = access_list_get (afi, name_str); - -  if (set) -    { -      if (filter_lookup_zebra (access, mfilter)) -	filter_free (mfilter); -      else -	access_list_filter_add (access, mfilter); -    } -  else -    { -      struct filter *delete_filter; - -      delete_filter = filter_lookup_zebra (access, mfilter); -      if (delete_filter) -        access_list_filter_delete (access, delete_filter); +	/* Check of filter type. */ +	if (strncmp(type_str, "p", 1) == 0) +		type = FILTER_PERMIT; +	else if (strncmp(type_str, "d", 1) == 0) +		type = FILTER_DENY; +	else { +		vty_out(vty, "filter type must be [permit|deny]%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -      filter_free (mfilter); -    } +	/* Check string format of prefix and prefixlen. */ +	if (afi == AFI_IP) { +		ret = str2prefix_ipv4(prefix_str, (struct prefix_ipv4 *)&p); +		if (ret <= 0) { +			vty_out(vty, +				"IP address prefix/prefixlen is malformed%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} +	} else if (afi == AFI_IP6) { +		ret = str2prefix_ipv6(prefix_str, (struct prefix_ipv6 *)&p); +		if (ret <= 0) { +			vty_out(vty, +				"IPv6 address prefix/prefixlen is malformed%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} +	} else +		return CMD_WARNING; + +	mfilter = filter_new(); +	mfilter->type = type; +	filter = &mfilter->u.zfilter; +	prefix_copy(&filter->prefix, &p); + +	/* "exact-match" */ +	if (exact) +		filter->exact = 1; + +	/* Install new filter to the access_list. */ +	access = access_list_get(afi, name_str); + +	if (set) { +		if (filter_lookup_zebra(access, mfilter)) +			filter_free(mfilter); +		else +			access_list_filter_add(access, mfilter); +	} else { +		struct filter *delete_filter; + +		delete_filter = filter_lookup_zebra(access, mfilter); +		if (delete_filter) +			access_list_filter_delete(access, delete_filter); + +		filter_free(mfilter); +	} -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (access_list_exact, @@ -1345,18 +1302,19 @@ DEFUN (access_list_exact,         "Prefix to match. e.g. 10.0.0.0/8\n"         "Exact match of the prefixes\n")  { -  int idx; -  int exact = 0; -  int idx_word = 1; -  int idx_permit_deny = 2; -  int idx_ipv4_prefixlen = 3; -  idx = idx_ipv4_prefixlen; +	int idx; +	int exact = 0; +	int idx_word = 1; +	int idx_permit_deny = 2; +	int idx_ipv4_prefixlen = 3; +	idx = idx_ipv4_prefixlen; -  if (argv_find (argv, argc, "exact-match", &idx)) -    exact = 1; +	if (argv_find(argv, argc, "exact-match", &idx)) +		exact = 1; -  return filter_set_zebra (vty, argv[idx_word]->arg, argv[idx_permit_deny]->arg, -                           AFI_IP, argv[idx_ipv4_prefixlen]->arg, exact, 1); +	return filter_set_zebra(vty, argv[idx_word]->arg, +				argv[idx_permit_deny]->arg, AFI_IP, +				argv[idx_ipv4_prefixlen]->arg, exact, 1);  }  DEFUN (access_list_any, @@ -1368,9 +1326,11 @@ DEFUN (access_list_any,         "Specify packets to forward\n"         "Prefix to match. e.g. 10.0.0.0/8\n")  { -  int idx_word = 1; -  int idx_permit_deny = 2; -  return filter_set_zebra (vty, argv[idx_word]->arg, argv[idx_permit_deny]->arg, AFI_IP, "0.0.0.0/0", 0, 1); +	int idx_word = 1; +	int idx_permit_deny = 2; +	return filter_set_zebra(vty, argv[idx_word]->arg, +				argv[idx_permit_deny]->arg, AFI_IP, "0.0.0.0/0", +				0, 1);  }  DEFUN (no_access_list_exact, @@ -1384,17 +1344,19 @@ DEFUN (no_access_list_exact,         "Prefix to match. e.g. 10.0.0.0/8\n"         "Exact match of the prefixes\n")  { -  int idx; -  int exact = 0; -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv4_prefixlen = 4; -  idx = idx_ipv4_prefixlen; +	int idx; +	int exact = 0; +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv4_prefixlen = 4; +	idx = idx_ipv4_prefixlen; -  if (argv_find (argv, argc, "exact-match", &idx)) -    exact = 1; +	if (argv_find(argv, argc, "exact-match", &idx)) +		exact = 1; -  return filter_set_zebra (vty, argv[idx_word]->arg, argv[idx_permit_deny]->arg, AFI_IP, argv[idx_ipv4_prefixlen]->arg, exact, 0); +	return filter_set_zebra(vty, argv[idx_word]->arg, +				argv[idx_permit_deny]->arg, AFI_IP, +				argv[idx_ipv4_prefixlen]->arg, exact, 0);  }  DEFUN (no_access_list_any, @@ -1407,9 +1369,11 @@ DEFUN (no_access_list_any,         "Specify packets to forward\n"         "Prefix to match. e.g. 10.0.0.0/8\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  return filter_set_zebra (vty, argv[idx_word]->arg, argv[idx_permit_deny]->arg, AFI_IP, "0.0.0.0/0", 0, 0); +	int idx_word = 2; +	int idx_permit_deny = 3; +	return filter_set_zebra(vty, argv[idx_word]->arg, +				argv[idx_permit_deny]->arg, AFI_IP, "0.0.0.0/0", +				0, 0);  }  DEFUN (no_access_list_all, @@ -1423,30 +1387,29 @@ DEFUN (no_access_list_all,         "IP extended access list (expanded range)\n"         "IP zebra access-list name\n")  { -  int idx_acl = 2; -  struct access_list *access; -  struct access_master *master; +	int idx_acl = 2; +	struct access_list *access; +	struct access_master *master; -  /* Looking up access_list. */ -  access = access_list_lookup (AFI_IP, argv[idx_acl]->arg); -  if (access == NULL) -    { -      vty_out (vty, "%% access-list %s doesn't exist%s", argv[idx_acl]->arg, -	       VTY_NEWLINE); -      return CMD_WARNING; -    } +	/* Looking up access_list. */ +	access = access_list_lookup(AFI_IP, argv[idx_acl]->arg); +	if (access == NULL) { +		vty_out(vty, "%% access-list %s doesn't exist%s", +			argv[idx_acl]->arg, VTY_NEWLINE); +		return CMD_WARNING; +	} + +	master = access->master; -  master = access->master; +	route_map_notify_dependencies(access->name, RMAP_EVENT_FILTER_DELETED); +	/* Run hook function. */ +	if (master->delete_hook) +		(*master->delete_hook)(access); -  route_map_notify_dependencies(access->name, RMAP_EVENT_FILTER_DELETED); -  /* Run hook function. */ -  if (master->delete_hook) -    (*master->delete_hook) (access); -  -  /* Delete all filter from access-list. */ -  access_list_delete (access); +	/* Delete all filter from access-list. */ +	access_list_delete(access); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (access_list_remark, @@ -1461,20 +1424,19 @@ DEFUN (access_list_remark,         "Access list entry comment\n"         "Comment up to 100 characters\n")  { -  int idx_acl = 1; -  int idx_remark = 3; -  struct access_list *access; +	int idx_acl = 1; +	int idx_remark = 3; +	struct access_list *access; -  access = access_list_get (AFI_IP, argv[idx_acl]->arg); +	access = access_list_get(AFI_IP, argv[idx_acl]->arg); -  if (access->remark) -    { -      XFREE (MTYPE_TMP, access->remark); -      access->remark = NULL; -    } -  access->remark = argv_concat(argv, argc, idx_remark); +	if (access->remark) { +		XFREE(MTYPE_TMP, access->remark); +		access->remark = NULL; +	} +	access->remark = argv_concat(argv, argc, idx_remark); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_access_list_remark, @@ -1489,8 +1451,8 @@ DEFUN (no_access_list_remark,         "IP zebra access-list\n"         "Access list entry comment\n")  { -  int idx_acl = 2; -  return vty_access_list_remark_unset (vty, AFI_IP, argv[idx_acl]->arg); +	int idx_acl = 2; +	return vty_access_list_remark_unset(vty, AFI_IP, argv[idx_acl]->arg);  }  /* ALIAS_FIXME */ @@ -1507,7 +1469,7 @@ DEFUN (no_access_list_remark_comment,         "Access list entry comment\n"         "Comment up to 100 characters\n")  { -  return no_access_list_remark (self, vty, argc, argv); +	return no_access_list_remark(self, vty, argc, argv);  }  DEFUN (ipv6_access_list_exact, @@ -1521,18 +1483,18 @@ DEFUN (ipv6_access_list_exact,         "IPv6 prefix\n"         "Exact match of the prefixes\n")  { -  int idx; -  int exact = 0; -  int idx_word = 2; -  int idx_allow = 3; -  int idx_addr = 4; -  idx = idx_addr; +	int idx; +	int exact = 0; +	int idx_word = 2; +	int idx_allow = 3; +	int idx_addr = 4; +	idx = idx_addr; -  if (argv_find (argv, argc, "exact-match", &idx)) -    exact = 1; +	if (argv_find(argv, argc, "exact-match", &idx)) +		exact = 1; -  return filter_set_zebra (vty, argv[idx_word]->arg, argv[idx_allow]->text, -                           AFI_IP6, argv[idx_addr]->arg, exact, 1); +	return filter_set_zebra(vty, argv[idx_word]->arg, argv[idx_allow]->text, +				AFI_IP6, argv[idx_addr]->arg, exact, 1);  }  DEFUN (ipv6_access_list_any, @@ -1545,9 +1507,11 @@ DEFUN (ipv6_access_list_any,         "Specify packets to forward\n"         "Any prefixi to match\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  return filter_set_zebra (vty, argv[idx_word]->arg, argv[idx_permit_deny]->arg, AFI_IP6, "::/0", 0, 1); +	int idx_word = 2; +	int idx_permit_deny = 3; +	return filter_set_zebra(vty, argv[idx_word]->arg, +				argv[idx_permit_deny]->arg, AFI_IP6, "::/0", 0, +				1);  }  DEFUN (no_ipv6_access_list_exact, @@ -1562,18 +1526,19 @@ DEFUN (no_ipv6_access_list_exact,         "Prefix to match. e.g. 3ffe:506::/32\n"         "Exact match of the prefixes\n")  { -  int idx; -  int exact = 0; -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv6_prefixlen = 5; -  idx = idx_ipv6_prefixlen; +	int idx; +	int exact = 0; +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv6_prefixlen = 5; +	idx = idx_ipv6_prefixlen; -  if (argv_find (argv, argc, "exact-match", &idx)) -    exact = 1; +	if (argv_find(argv, argc, "exact-match", &idx)) +		exact = 1; -  return filter_set_zebra (vty, argv[idx_word]->arg, argv[idx_permit_deny]->arg, -                           AFI_IP6, argv[idx_ipv6_prefixlen]->arg, exact, 0); +	return filter_set_zebra(vty, argv[idx_word]->arg, +				argv[idx_permit_deny]->arg, AFI_IP6, +				argv[idx_ipv6_prefixlen]->arg, exact, 0);  }  DEFUN (no_ipv6_access_list_any, @@ -1587,9 +1552,11 @@ DEFUN (no_ipv6_access_list_any,         "Specify packets to forward\n"         "Any prefixi to match\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  return filter_set_zebra (vty, argv[idx_word]->arg, argv[idx_permit_deny]->arg, AFI_IP6, "::/0", 0, 0); +	int idx_word = 3; +	int idx_permit_deny = 4; +	return filter_set_zebra(vty, argv[idx_word]->arg, +				argv[idx_permit_deny]->arg, AFI_IP6, "::/0", 0, +				0);  } @@ -1601,30 +1568,29 @@ DEFUN (no_ipv6_access_list_all,         "Add an access list entry\n"         "IPv6 zebra access-list\n")  { -  int idx_word = 3; -  struct access_list *access; -  struct access_master *master; +	int idx_word = 3; +	struct access_list *access; +	struct access_master *master; -  /* Looking up access_list. */ -  access = access_list_lookup (AFI_IP6, argv[idx_word]->arg); -  if (access == NULL) -    { -      vty_out (vty, "%% access-list %s doesn't exist%s", argv[idx_word]->arg, -	       VTY_NEWLINE); -      return CMD_WARNING; -    } +	/* Looking up access_list. */ +	access = access_list_lookup(AFI_IP6, argv[idx_word]->arg); +	if (access == NULL) { +		vty_out(vty, "%% access-list %s doesn't exist%s", +			argv[idx_word]->arg, VTY_NEWLINE); +		return CMD_WARNING; +	} -  master = access->master; +	master = access->master; -  route_map_notify_dependencies(access->name, RMAP_EVENT_FILTER_DELETED); -  /* Run hook function. */ -  if (master->delete_hook) -    (*master->delete_hook) (access); +	route_map_notify_dependencies(access->name, RMAP_EVENT_FILTER_DELETED); +	/* Run hook function. */ +	if (master->delete_hook) +		(*master->delete_hook)(access); -  /* Delete all filter from access-list. */ -  access_list_delete (access); +	/* Delete all filter from access-list. */ +	access_list_delete(access); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (ipv6_access_list_remark, @@ -1636,20 +1602,19 @@ DEFUN (ipv6_access_list_remark,         "Access list entry comment\n"         "Comment up to 100 characters\n")  { -  int idx_word = 2; -  int idx_line = 4; -  struct access_list *access; +	int idx_word = 2; +	int idx_line = 4; +	struct access_list *access; -  access = access_list_get (AFI_IP6, argv[idx_word]->arg); +	access = access_list_get(AFI_IP6, argv[idx_word]->arg); -  if (access->remark) -    { -      XFREE (MTYPE_TMP, access->remark); -      access->remark = NULL; -    } -  access->remark = argv_concat(argv, argc, idx_line); +	if (access->remark) { +		XFREE(MTYPE_TMP, access->remark); +		access->remark = NULL; +	} +	access->remark = argv_concat(argv, argc, idx_line); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_ipv6_access_list_remark, @@ -1661,8 +1626,8 @@ DEFUN (no_ipv6_access_list_remark,         "IPv6 zebra access-list\n"         "Access list entry comment\n")  { -  int idx_word = 3; -  return vty_access_list_remark_unset (vty, AFI_IP6, argv[idx_word]->arg); +	int idx_word = 3; +	return vty_access_list_remark_unset(vty, AFI_IP6, argv[idx_word]->arg);  }  /* ALIAS_FIXME */ @@ -1676,115 +1641,116 @@ DEFUN (no_ipv6_access_list_remark_comment,         "Access list entry comment\n"         "Comment up to 100 characters\n")  { -  return no_ipv6_access_list_remark (self, vty, argc, argv); +	return no_ipv6_access_list_remark(self, vty, argc, argv);  } -void config_write_access_zebra (struct vty *, struct filter *); -void config_write_access_cisco (struct vty *, struct filter *); +void config_write_access_zebra(struct vty *, struct filter *); +void config_write_access_cisco(struct vty *, struct filter *);  /* show access-list command. */ -static int -filter_show (struct vty *vty, const char *name, afi_t afi) -{ -  struct access_list *access; -  struct access_master *master; -  struct filter *mfilter; -  struct filter_cisco *filter; -  int write = 0; - -  master = access_master_get (afi); -  if (master == NULL) -    return 0; - -  /* Print the name of the protocol */ -  vty_out(vty, "%s:%s", zlog_protoname(), VTY_NEWLINE); - -  for (access = master->num.head; access; access = access->next) -    { -      if (name && strcmp (access->name, name) != 0) -	continue; - -      write = 1; - -      for (mfilter = access->head; mfilter; mfilter = mfilter->next) -	{ -	  filter = &mfilter->u.cfilter; - -	  if (write) -	    { -	      vty_out (vty, "%s IP%s access list %s%s", -		       mfilter->cisco ?  -		       (filter->extended ? "Extended" : "Standard") : "Zebra", -		       afi == AFI_IP6 ? "v6" : "", -		       access->name, VTY_NEWLINE); -	      write = 0; -	    } - -	  vty_out (vty, "    %s%s", filter_type_str (mfilter), -		   mfilter->type == FILTER_DENY ? "  " : ""); - -	  if (! mfilter->cisco) -	    config_write_access_zebra (vty, mfilter); -	  else if (filter->extended) -	    config_write_access_cisco (vty, mfilter); -	  else -	    { -	      if (filter->addr_mask.s_addr == 0xffffffff) -		vty_out (vty, " any%s", VTY_NEWLINE); -	      else -		{ -		  vty_out (vty, " %s", inet_ntoa (filter->addr)); -		  if (filter->addr_mask.s_addr != 0) -		    vty_out (vty, ", wildcard bits %s", inet_ntoa (filter->addr_mask)); -		  vty_out (vty, "%s", VTY_NEWLINE); +static int filter_show(struct vty *vty, const char *name, afi_t afi) +{ +	struct access_list *access; +	struct access_master *master; +	struct filter *mfilter; +	struct filter_cisco *filter; +	int write = 0; + +	master = access_master_get(afi); +	if (master == NULL) +		return 0; + +	/* Print the name of the protocol */ +	vty_out(vty, "%s:%s", zlog_protoname(), VTY_NEWLINE); + +	for (access = master->num.head; access; access = access->next) { +		if (name && strcmp(access->name, name) != 0) +			continue; + +		write = 1; + +		for (mfilter = access->head; mfilter; mfilter = mfilter->next) { +			filter = &mfilter->u.cfilter; + +			if (write) { +				vty_out(vty, "%s IP%s access list %s%s", +					mfilter->cisco ? (filter->extended +								  ? "Extended" +								  : "Standard") +						       : "Zebra", +					afi == AFI_IP6 ? "v6" : "", +					access->name, VTY_NEWLINE); +				write = 0; +			} + +			vty_out(vty, "    %s%s", filter_type_str(mfilter), +				mfilter->type == FILTER_DENY ? "  " : ""); + +			if (!mfilter->cisco) +				config_write_access_zebra(vty, mfilter); +			else if (filter->extended) +				config_write_access_cisco(vty, mfilter); +			else { +				if (filter->addr_mask.s_addr == 0xffffffff) +					vty_out(vty, " any%s", VTY_NEWLINE); +				else { +					vty_out(vty, " %s", +						inet_ntoa(filter->addr)); +					if (filter->addr_mask.s_addr != 0) +						vty_out(vty, +							", wildcard bits %s", +							inet_ntoa( +								filter->addr_mask)); +					vty_out(vty, "%s", VTY_NEWLINE); +				} +			}  		} -	    }  	} -    } - -  for (access = master->str.head; access; access = access->next) -    { -      if (name && strcmp (access->name, name) != 0) -	continue; - -      write = 1; - -      for (mfilter = access->head; mfilter; mfilter = mfilter->next) -	{ -	  filter = &mfilter->u.cfilter; - -	  if (write) -	    { -	      vty_out (vty, "%s IP%s access list %s%s", -		       mfilter->cisco ?  -		       (filter->extended ? "Extended" : "Standard") : "Zebra", -		       afi == AFI_IP6 ? "v6" : "", -		       access->name, VTY_NEWLINE); -	      write = 0; -	    } - -	  vty_out (vty, "    %s%s", filter_type_str (mfilter), -		   mfilter->type == FILTER_DENY ? "  " : ""); - -	  if (! mfilter->cisco) -	    config_write_access_zebra (vty, mfilter); -	  else if (filter->extended) -	    config_write_access_cisco (vty, mfilter); -	  else -	    { -	      if (filter->addr_mask.s_addr == 0xffffffff) -		vty_out (vty, " any%s", VTY_NEWLINE); -	      else -		{ -		  vty_out (vty, " %s", inet_ntoa (filter->addr)); -		  if (filter->addr_mask.s_addr != 0) -		    vty_out (vty, ", wildcard bits %s", inet_ntoa (filter->addr_mask)); -		  vty_out (vty, "%s", VTY_NEWLINE); + +	for (access = master->str.head; access; access = access->next) { +		if (name && strcmp(access->name, name) != 0) +			continue; + +		write = 1; + +		for (mfilter = access->head; mfilter; mfilter = mfilter->next) { +			filter = &mfilter->u.cfilter; + +			if (write) { +				vty_out(vty, "%s IP%s access list %s%s", +					mfilter->cisco ? (filter->extended +								  ? "Extended" +								  : "Standard") +						       : "Zebra", +					afi == AFI_IP6 ? "v6" : "", +					access->name, VTY_NEWLINE); +				write = 0; +			} + +			vty_out(vty, "    %s%s", filter_type_str(mfilter), +				mfilter->type == FILTER_DENY ? "  " : ""); + +			if (!mfilter->cisco) +				config_write_access_zebra(vty, mfilter); +			else if (filter->extended) +				config_write_access_cisco(vty, mfilter); +			else { +				if (filter->addr_mask.s_addr == 0xffffffff) +					vty_out(vty, " any%s", VTY_NEWLINE); +				else { +					vty_out(vty, " %s", +						inet_ntoa(filter->addr)); +					if (filter->addr_mask.s_addr != 0) +						vty_out(vty, +							", wildcard bits %s", +							inet_ntoa( +								filter->addr_mask)); +					vty_out(vty, "%s", VTY_NEWLINE); +				} +			}  		} -	    }  	} -    } -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (show_ip_access_list, @@ -1794,7 +1760,7 @@ DEFUN (show_ip_access_list,         IP_STR         "List IP access lists\n")  { -  return filter_show (vty, NULL, AFI_IP); +	return filter_show(vty, NULL, AFI_IP);  }  DEFUN (show_ip_access_list_name, @@ -1809,8 +1775,8 @@ DEFUN (show_ip_access_list_name,         "IP extended access list (expanded range)\n"         "IP zebra access-list\n")  { -  int idx_acl = 3; -  return filter_show (vty, argv[idx_acl]->arg, AFI_IP); +	int idx_acl = 3; +	return filter_show(vty, argv[idx_acl]->arg, AFI_IP);  }  DEFUN (show_ipv6_access_list, @@ -1820,7 +1786,7 @@ DEFUN (show_ipv6_access_list,         IPV6_STR         "List IPv6 access lists\n")  { -  return filter_show (vty, NULL, AFI_IP6); +	return filter_show(vty, NULL, AFI_IP6);  }  DEFUN (show_ipv6_access_list_name, @@ -1831,309 +1797,270 @@ DEFUN (show_ipv6_access_list_name,         "List IPv6 access lists\n"         "IPv6 zebra access-list\n")  { -  int idx_word = 3; -  return filter_show (vty, argv[idx_word]->arg, AFI_IP6); -} - -void -config_write_access_cisco (struct vty *vty, struct filter *mfilter) -{ -  struct filter_cisco *filter; - -  filter = &mfilter->u.cfilter; - -  if (filter->extended) -    { -      vty_out (vty, " ip"); -      if (filter->addr_mask.s_addr == 0xffffffff) -	vty_out (vty, " any"); -      else if (filter->addr_mask.s_addr == 0) -	vty_out (vty, " host %s", inet_ntoa (filter->addr)); -      else -	{ -	  vty_out (vty, " %s", inet_ntoa (filter->addr)); -	  vty_out (vty, " %s", inet_ntoa (filter->addr_mask)); -        } - -      if (filter->mask_mask.s_addr == 0xffffffff) -	vty_out (vty, " any"); -      else if (filter->mask_mask.s_addr == 0) -	vty_out (vty, " host %s", inet_ntoa (filter->mask)); -      else -	{ -	  vty_out (vty, " %s", inet_ntoa (filter->mask)); -	  vty_out (vty, " %s", inet_ntoa (filter->mask_mask)); -	} -      vty_out (vty, "%s", VTY_NEWLINE); -    } -  else -    { -      if (filter->addr_mask.s_addr == 0xffffffff) -	vty_out (vty, " any%s", VTY_NEWLINE); -      else -	{ -	  vty_out (vty, " %s", inet_ntoa (filter->addr)); -	  if (filter->addr_mask.s_addr != 0) -	    vty_out (vty, " %s", inet_ntoa (filter->addr_mask)); -	  vty_out (vty, "%s", VTY_NEWLINE); +	int idx_word = 3; +	return filter_show(vty, argv[idx_word]->arg, AFI_IP6); +} + +void config_write_access_cisco(struct vty *vty, struct filter *mfilter) +{ +	struct filter_cisco *filter; + +	filter = &mfilter->u.cfilter; + +	if (filter->extended) { +		vty_out(vty, " ip"); +		if (filter->addr_mask.s_addr == 0xffffffff) +			vty_out(vty, " any"); +		else if (filter->addr_mask.s_addr == 0) +			vty_out(vty, " host %s", inet_ntoa(filter->addr)); +		else { +			vty_out(vty, " %s", inet_ntoa(filter->addr)); +			vty_out(vty, " %s", inet_ntoa(filter->addr_mask)); +		} + +		if (filter->mask_mask.s_addr == 0xffffffff) +			vty_out(vty, " any"); +		else if (filter->mask_mask.s_addr == 0) +			vty_out(vty, " host %s", inet_ntoa(filter->mask)); +		else { +			vty_out(vty, " %s", inet_ntoa(filter->mask)); +			vty_out(vty, " %s", inet_ntoa(filter->mask_mask)); +		} +		vty_out(vty, "%s", VTY_NEWLINE); +	} else { +		if (filter->addr_mask.s_addr == 0xffffffff) +			vty_out(vty, " any%s", VTY_NEWLINE); +		else { +			vty_out(vty, " %s", inet_ntoa(filter->addr)); +			if (filter->addr_mask.s_addr != 0) +				vty_out(vty, " %s", +					inet_ntoa(filter->addr_mask)); +			vty_out(vty, "%s", VTY_NEWLINE); +		}  	} -    }  } -void -config_write_access_zebra (struct vty *vty, struct filter *mfilter) +void config_write_access_zebra(struct vty *vty, struct filter *mfilter)  { -  struct filter_zebra *filter; -  struct prefix *p; -  char buf[BUFSIZ]; +	struct filter_zebra *filter; +	struct prefix *p; +	char buf[BUFSIZ]; -  filter = &mfilter->u.zfilter; -  p = &filter->prefix; +	filter = &mfilter->u.zfilter; +	p = &filter->prefix; -  if (p->prefixlen == 0 && ! filter->exact) -    vty_out (vty, " any"); -  else -    vty_out (vty, " %s/%d%s", -	     inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -	     p->prefixlen, -	     filter->exact ? " exact-match" : ""); +	if (p->prefixlen == 0 && !filter->exact) +		vty_out(vty, " any"); +	else +		vty_out(vty, " %s/%d%s", +			inet_ntop(p->family, &p->u.prefix, buf, BUFSIZ), +			p->prefixlen, filter->exact ? " exact-match" : ""); -  vty_out (vty, "%s", VTY_NEWLINE); +	vty_out(vty, "%s", VTY_NEWLINE);  } -static int -config_write_access (struct vty *vty, afi_t afi) +static int config_write_access(struct vty *vty, afi_t afi)  { -  struct access_list *access; -  struct access_master *master; -  struct filter *mfilter; -  int write = 0; +	struct access_list *access; +	struct access_master *master; +	struct filter *mfilter; +	int write = 0; -  master = access_master_get (afi); -  if (master == NULL) -    return 0; +	master = access_master_get(afi); +	if (master == NULL) +		return 0; -  for (access = master->num.head; access; access = access->next) -    { -      if (access->remark) -	{ -	  vty_out (vty, "%saccess-list %s remark %s%s", -		   afi == AFI_IP ? "" : "ipv6 ", -		   access->name, access->remark, -		   VTY_NEWLINE); -	  write++; -	} +	for (access = master->num.head; access; access = access->next) { +		if (access->remark) { +			vty_out(vty, "%saccess-list %s remark %s%s", +				afi == AFI_IP ? "" : "ipv6 ", access->name, +				access->remark, VTY_NEWLINE); +			write++; +		} -      for (mfilter = access->head; mfilter; mfilter = mfilter->next) -	{ -	  vty_out (vty, "%saccess-list %s %s", -	     afi == AFI_IP ? "" : "ipv6 ", -	     access->name, -	     filter_type_str (mfilter)); +		for (mfilter = access->head; mfilter; mfilter = mfilter->next) { +			vty_out(vty, "%saccess-list %s %s", +				afi == AFI_IP ? "" : "ipv6 ", access->name, +				filter_type_str(mfilter)); -	  if (mfilter->cisco) -	    config_write_access_cisco (vty, mfilter); -	  else -	    config_write_access_zebra (vty, mfilter); +			if (mfilter->cisco) +				config_write_access_cisco(vty, mfilter); +			else +				config_write_access_zebra(vty, mfilter); -	  write++; -	} -    } - -  for (access = master->str.head; access; access = access->next) -    { -      if (access->remark) -	{ -	  vty_out (vty, "%saccess-list %s remark %s%s", -		   afi == AFI_IP ? "" : "ipv6 ", -		   access->name, access->remark, -		   VTY_NEWLINE); -	  write++; +			write++; +		}  	} -      for (mfilter = access->head; mfilter; mfilter = mfilter->next) -	{ -	  vty_out (vty, "%saccess-list %s %s", -	     afi == AFI_IP ? "" : "ipv6 ", -	     access->name, -	     filter_type_str (mfilter)); +	for (access = master->str.head; access; access = access->next) { +		if (access->remark) { +			vty_out(vty, "%saccess-list %s remark %s%s", +				afi == AFI_IP ? "" : "ipv6 ", access->name, +				access->remark, VTY_NEWLINE); +			write++; +		} + +		for (mfilter = access->head; mfilter; mfilter = mfilter->next) { +			vty_out(vty, "%saccess-list %s %s", +				afi == AFI_IP ? "" : "ipv6 ", access->name, +				filter_type_str(mfilter)); -	  if (mfilter->cisco) -	    config_write_access_cisco (vty, mfilter); -	  else -	    config_write_access_zebra (vty, mfilter); +			if (mfilter->cisco) +				config_write_access_cisco(vty, mfilter); +			else +				config_write_access_zebra(vty, mfilter); -	  write++; +			write++; +		}  	} -    } -  return write; +	return write;  }  /* Access-list node. */ -static struct cmd_node access_node = -{ -  ACCESS_NODE, -  "",				/* Access list has no interface. */ -  1 -}; +static struct cmd_node access_node = {ACCESS_NODE, +				      "", /* Access list has no interface. */ +				      1}; -static int -config_write_access_ipv4 (struct vty *vty) +static int config_write_access_ipv4(struct vty *vty)  { -  return config_write_access (vty, AFI_IP); +	return config_write_access(vty, AFI_IP);  } -static void -access_list_reset_ipv4 (void) +static void access_list_reset_ipv4(void)  { -  struct access_list *access; -  struct access_list *next; -  struct access_master *master; +	struct access_list *access; +	struct access_list *next; +	struct access_master *master; -  master = access_master_get (AFI_IP); -  if (master == NULL) -    return; +	master = access_master_get(AFI_IP); +	if (master == NULL) +		return; -  for (access = master->num.head; access; access = next) -    { -      next = access->next; -      access_list_delete (access); -    } -  for (access = master->str.head; access; access = next) -    { -      next = access->next; -      access_list_delete (access); -    } +	for (access = master->num.head; access; access = next) { +		next = access->next; +		access_list_delete(access); +	} +	for (access = master->str.head; access; access = next) { +		next = access->next; +		access_list_delete(access); +	} -  assert (master->num.head == NULL); -  assert (master->num.tail == NULL); +	assert(master->num.head == NULL); +	assert(master->num.tail == NULL); -  assert (master->str.head == NULL); -  assert (master->str.tail == NULL); +	assert(master->str.head == NULL); +	assert(master->str.tail == NULL);  }  /* Install vty related command. */ -static void -access_list_init_ipv4 (void) -{ -  install_node (&access_node, config_write_access_ipv4); - -  install_element (ENABLE_NODE, &show_ip_access_list_cmd); -  install_element (ENABLE_NODE, &show_ip_access_list_name_cmd); - -  /* Zebra access-list */ -  install_element (CONFIG_NODE, &access_list_exact_cmd); -  install_element (CONFIG_NODE, &access_list_any_cmd); -  install_element (CONFIG_NODE, &no_access_list_exact_cmd); -  install_element (CONFIG_NODE, &no_access_list_any_cmd); - -  /* Standard access-list */ -  install_element (CONFIG_NODE, &access_list_standard_cmd); -  install_element (CONFIG_NODE, &access_list_standard_nomask_cmd); -  install_element (CONFIG_NODE, &access_list_standard_host_cmd); -  install_element (CONFIG_NODE, &access_list_standard_any_cmd); -  install_element (CONFIG_NODE, &no_access_list_standard_cmd); -  install_element (CONFIG_NODE, &no_access_list_standard_nomask_cmd); -  install_element (CONFIG_NODE, &no_access_list_standard_host_cmd); -  install_element (CONFIG_NODE, &no_access_list_standard_any_cmd); - -  /* Extended access-list */ -  install_element (CONFIG_NODE, &access_list_extended_cmd); -  install_element (CONFIG_NODE, &access_list_extended_any_mask_cmd); -  install_element (CONFIG_NODE, &access_list_extended_mask_any_cmd); -  install_element (CONFIG_NODE, &access_list_extended_any_any_cmd); -  install_element (CONFIG_NODE, &access_list_extended_host_mask_cmd); -  install_element (CONFIG_NODE, &access_list_extended_mask_host_cmd); -  install_element (CONFIG_NODE, &access_list_extended_host_host_cmd); -  install_element (CONFIG_NODE, &access_list_extended_any_host_cmd); -  install_element (CONFIG_NODE, &access_list_extended_host_any_cmd); -  install_element (CONFIG_NODE, &no_access_list_extended_cmd); -  install_element (CONFIG_NODE, &no_access_list_extended_any_mask_cmd); -  install_element (CONFIG_NODE, &no_access_list_extended_mask_any_cmd); -  install_element (CONFIG_NODE, &no_access_list_extended_any_any_cmd); -  install_element (CONFIG_NODE, &no_access_list_extended_host_mask_cmd); -  install_element (CONFIG_NODE, &no_access_list_extended_mask_host_cmd); -  install_element (CONFIG_NODE, &no_access_list_extended_host_host_cmd); -  install_element (CONFIG_NODE, &no_access_list_extended_any_host_cmd); -  install_element (CONFIG_NODE, &no_access_list_extended_host_any_cmd); - -  install_element (CONFIG_NODE, &access_list_remark_cmd); -  install_element (CONFIG_NODE, &no_access_list_all_cmd); -  install_element (CONFIG_NODE, &no_access_list_remark_cmd); -  install_element (CONFIG_NODE, &no_access_list_remark_comment_cmd); -} - -static struct cmd_node access_ipv6_node = -{ -  ACCESS_IPV6_NODE, -  "", -  1 -}; - -static int -config_write_access_ipv6 (struct vty *vty) -{ -  return config_write_access (vty, AFI_IP6); -} - -static void -access_list_reset_ipv6 (void) -{ -  struct access_list *access; -  struct access_list *next; -  struct access_master *master; - -  master = access_master_get (AFI_IP6); -  if (master == NULL) -    return; - -  for (access = master->num.head; access; access = next) -    { -      next = access->next; -      access_list_delete (access); -    } -  for (access = master->str.head; access; access = next) -    { -      next = access->next; -      access_list_delete (access); -    } +static void access_list_init_ipv4(void) +{ +	install_node(&access_node, config_write_access_ipv4); + +	install_element(ENABLE_NODE, &show_ip_access_list_cmd); +	install_element(ENABLE_NODE, &show_ip_access_list_name_cmd); + +	/* Zebra access-list */ +	install_element(CONFIG_NODE, &access_list_exact_cmd); +	install_element(CONFIG_NODE, &access_list_any_cmd); +	install_element(CONFIG_NODE, &no_access_list_exact_cmd); +	install_element(CONFIG_NODE, &no_access_list_any_cmd); + +	/* Standard access-list */ +	install_element(CONFIG_NODE, &access_list_standard_cmd); +	install_element(CONFIG_NODE, &access_list_standard_nomask_cmd); +	install_element(CONFIG_NODE, &access_list_standard_host_cmd); +	install_element(CONFIG_NODE, &access_list_standard_any_cmd); +	install_element(CONFIG_NODE, &no_access_list_standard_cmd); +	install_element(CONFIG_NODE, &no_access_list_standard_nomask_cmd); +	install_element(CONFIG_NODE, &no_access_list_standard_host_cmd); +	install_element(CONFIG_NODE, &no_access_list_standard_any_cmd); + +	/* Extended access-list */ +	install_element(CONFIG_NODE, &access_list_extended_cmd); +	install_element(CONFIG_NODE, &access_list_extended_any_mask_cmd); +	install_element(CONFIG_NODE, &access_list_extended_mask_any_cmd); +	install_element(CONFIG_NODE, &access_list_extended_any_any_cmd); +	install_element(CONFIG_NODE, &access_list_extended_host_mask_cmd); +	install_element(CONFIG_NODE, &access_list_extended_mask_host_cmd); +	install_element(CONFIG_NODE, &access_list_extended_host_host_cmd); +	install_element(CONFIG_NODE, &access_list_extended_any_host_cmd); +	install_element(CONFIG_NODE, &access_list_extended_host_any_cmd); +	install_element(CONFIG_NODE, &no_access_list_extended_cmd); +	install_element(CONFIG_NODE, &no_access_list_extended_any_mask_cmd); +	install_element(CONFIG_NODE, &no_access_list_extended_mask_any_cmd); +	install_element(CONFIG_NODE, &no_access_list_extended_any_any_cmd); +	install_element(CONFIG_NODE, &no_access_list_extended_host_mask_cmd); +	install_element(CONFIG_NODE, &no_access_list_extended_mask_host_cmd); +	install_element(CONFIG_NODE, &no_access_list_extended_host_host_cmd); +	install_element(CONFIG_NODE, &no_access_list_extended_any_host_cmd); +	install_element(CONFIG_NODE, &no_access_list_extended_host_any_cmd); + +	install_element(CONFIG_NODE, &access_list_remark_cmd); +	install_element(CONFIG_NODE, &no_access_list_all_cmd); +	install_element(CONFIG_NODE, &no_access_list_remark_cmd); +	install_element(CONFIG_NODE, &no_access_list_remark_comment_cmd); +} + +static struct cmd_node access_ipv6_node = {ACCESS_IPV6_NODE, "", 1}; + +static int config_write_access_ipv6(struct vty *vty) +{ +	return config_write_access(vty, AFI_IP6); +} + +static void access_list_reset_ipv6(void) +{ +	struct access_list *access; +	struct access_list *next; +	struct access_master *master; + +	master = access_master_get(AFI_IP6); +	if (master == NULL) +		return; + +	for (access = master->num.head; access; access = next) { +		next = access->next; +		access_list_delete(access); +	} +	for (access = master->str.head; access; access = next) { +		next = access->next; +		access_list_delete(access); +	} -  assert (master->num.head == NULL); -  assert (master->num.tail == NULL); +	assert(master->num.head == NULL); +	assert(master->num.tail == NULL); -  assert (master->str.head == NULL); -  assert (master->str.tail == NULL); +	assert(master->str.head == NULL); +	assert(master->str.tail == NULL);  } -static void -access_list_init_ipv6 (void) +static void access_list_init_ipv6(void)  { -  install_node (&access_ipv6_node, config_write_access_ipv6); +	install_node(&access_ipv6_node, config_write_access_ipv6); -  install_element (ENABLE_NODE, &show_ipv6_access_list_cmd); -  install_element (ENABLE_NODE, &show_ipv6_access_list_name_cmd); +	install_element(ENABLE_NODE, &show_ipv6_access_list_cmd); +	install_element(ENABLE_NODE, &show_ipv6_access_list_name_cmd); -  install_element (CONFIG_NODE, &ipv6_access_list_exact_cmd); -  install_element (CONFIG_NODE, &ipv6_access_list_any_cmd); -  install_element (CONFIG_NODE, &no_ipv6_access_list_exact_cmd); -  install_element (CONFIG_NODE, &no_ipv6_access_list_any_cmd); +	install_element(CONFIG_NODE, &ipv6_access_list_exact_cmd); +	install_element(CONFIG_NODE, &ipv6_access_list_any_cmd); +	install_element(CONFIG_NODE, &no_ipv6_access_list_exact_cmd); +	install_element(CONFIG_NODE, &no_ipv6_access_list_any_cmd); -  install_element (CONFIG_NODE, &no_ipv6_access_list_all_cmd); -  install_element (CONFIG_NODE, &ipv6_access_list_remark_cmd); -  install_element (CONFIG_NODE, &no_ipv6_access_list_remark_cmd); -  install_element (CONFIG_NODE, &no_ipv6_access_list_remark_comment_cmd); +	install_element(CONFIG_NODE, &no_ipv6_access_list_all_cmd); +	install_element(CONFIG_NODE, &ipv6_access_list_remark_cmd); +	install_element(CONFIG_NODE, &no_ipv6_access_list_remark_cmd); +	install_element(CONFIG_NODE, &no_ipv6_access_list_remark_comment_cmd);  } -void -access_list_init () +void access_list_init()  { -  access_list_init_ipv4 (); -  access_list_init_ipv6(); +	access_list_init_ipv4(); +	access_list_init_ipv6();  } -void -access_list_reset () +void access_list_reset()  { -  access_list_reset_ipv4 (); -  access_list_reset_ipv6(); +	access_list_reset_ipv4(); +	access_list_reset_ipv6();  } diff --git a/lib/filter.h b/lib/filter.h index 6b5ccb52ec..02227de6eb 100644 --- a/lib/filter.h +++ b/lib/filter.h @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the   * Free Software Foundation, Inc., 59 Temple Place - Suite 330, - * Boston, MA 02111-1307, USA.  + * Boston, MA 02111-1307, USA.   */  #ifndef _ZEBRA_FILTER_H @@ -34,42 +34,32 @@  #define FILTER_MAX                2  /* Filter type is made by `permit', `deny' and `dynamic'. */ -enum filter_type  -{ -  FILTER_DENY, -  FILTER_PERMIT, -  FILTER_DYNAMIC -}; +enum filter_type { FILTER_DENY, FILTER_PERMIT, FILTER_DYNAMIC }; -enum access_type -{ -  ACCESS_TYPE_STRING, -  ACCESS_TYPE_NUMBER -}; +enum access_type { ACCESS_TYPE_STRING, ACCESS_TYPE_NUMBER };  /* Access list */ -struct access_list -{ -  char *name; -  char *remark; +struct access_list { +	char *name; +	char *remark; -  struct access_master *master; +	struct access_master *master; -  enum access_type type; +	enum access_type type; -  struct access_list *next; -  struct access_list *prev; +	struct access_list *next; +	struct access_list *prev; -  struct filter *head; -  struct filter *tail; +	struct filter *head; +	struct filter *tail;  };  /* Prototypes for access-list. */ -extern void access_list_init (void); -extern void access_list_reset (void); -extern void access_list_add_hook (void (*func)(struct access_list *)); -extern void access_list_delete_hook (void (*func)(struct access_list *)); -extern struct access_list *access_list_lookup (afi_t, const char *); -extern enum filter_type access_list_apply (struct access_list *, void *); +extern void access_list_init(void); +extern void access_list_reset(void); +extern void access_list_add_hook(void (*func)(struct access_list *)); +extern void access_list_delete_hook(void (*func)(struct access_list *)); +extern struct access_list *access_list_lookup(afi_t, const char *); +extern enum filter_type access_list_apply(struct access_list *, void *);  #endif /* _ZEBRA_FILTER_H */ diff --git a/lib/getopt.c b/lib/getopt.c index 7a58a8a8cc..f8791a4524 100644 --- a/lib/getopt.c +++ b/lib/getopt.c @@ -4,7 +4,7 @@     before changing it!     Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98 -   	Free Software Foundation, Inc. +	Free Software Foundation, Inc.     NOTE: The canonical source of this file is maintained with the GNU C Library.     Bugs can be reported to bug-glibc@gnu.org. @@ -35,9 +35,9 @@  #if !defined __STDC__ || !__STDC__  /* This is a separate conditional since some stdc systems     reject `defined (const)'.  */ -# ifndef const +#ifndef const  #  define const -# endif +#endif  #endif  #include <stdio.h> @@ -52,10 +52,10 @@  #define GETOPT_INTERFACE_VERSION 2  #if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 -# include <gnu-versions.h> -# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +#include <gnu-versions.h> +#if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION  #  define ELIDE_CODE -# endif +#endif  #endif  #ifndef ELIDE_CODE @@ -63,29 +63,29 @@  /* This needs to come after some library #include     to get __GNU_LIBRARY__ defined.  */ -#ifdef	__GNU_LIBRARY__ +#ifdef __GNU_LIBRARY__  /* Don't include stdlib.h for non-GNU C libraries because some of them     contain conflicting prototypes for getopt.  */ -# include <stdlib.h> -# include <unistd.h> -#endif	/* GNU C library.  */ +#include <stdlib.h> +#include <unistd.h> +#endif /* GNU C library.  */  #ifdef VMS -# include <unixlib.h> -# if HAVE_STRING_H - 0 -#  include <string.h> -# endif +#include <unixlib.h> +#if HAVE_STRING_H - 0 +#include <string.h> +#endif  #endif  #ifndef _  /* This is for other GNU distributions with internationalized messages.     When compiling libc, the _ macro is predefined.  */ -# ifdef HAVE_LIBINTL_H -#  include <libintl.h> +#ifdef HAVE_LIBINTL_H +#include <libintl.h>  #  define _(msgid)	gettext (msgid) -# else +#else  #  define _(msgid)	(msgid) -# endif +#endif  #endif  /* This version of `getopt' appears to the caller like standard Unix `getopt' @@ -182,48 +182,42 @@ int optopt = '?';     of the value of `ordering'.  In the case of RETURN_IN_ORDER, only     `--' can cause `getopt' to return -1 with `optind' != ARGC.  */ -static enum -{ -  REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER -} ordering; +static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;  /* Value of POSIXLY_CORRECT environment variable.  */  static char *posixly_correct; -#ifdef	__GNU_LIBRARY__ +#ifdef __GNU_LIBRARY__  /* We want to avoid inclusion of string.h with non-GNU libraries     because there are many ways it can cause trouble.     On some systems, it contains special magic macros that don't work     in GCC.  */ -# include <string.h> +#include <string.h>  # define my_index	strchr  #else -# if HAVE_STRING_H -#  include <string.h> -# else -#  include <strings.h> -# endif +#if HAVE_STRING_H +#include <string.h> +#else +#include <strings.h> +#endif  /* Avoid depending on library functions or files     whose names are inconsistent.  */  #ifndef getenv -extern char *getenv (); +extern char *getenv();  #endif -static char * -my_index (str, chr) -     const char *str; -     int chr; +static char *my_index(str, chr) const char *str; +int chr;  { -  while (*str) -    { -      if (*str == chr) -	return (char *) str; -      str++; -    } -  return 0; +	while (*str) { +		if (*str == chr) +			return (char *)str; +		str++; +	} +	return 0;  }  /* If using GCC, we can safely declare strlen this way. @@ -231,11 +225,11 @@ my_index (str, chr)  #ifdef __GNUC__  /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.     That was relevant to code that was here before.  */ -# if (!defined __STDC__ || !__STDC__) && !defined strlen +#if (!defined __STDC__ || !__STDC__) && !defined strlen  /* gcc with -traditional declares the built-in strlen to return int,     and has done so at least since version 2.4.5. -- rms.  */ -extern int strlen (const char *); -# endif /* not __STDC__ */ +extern int strlen(const char *); +#endif /* not __STDC__ */  #endif /* __GNUC__ */  #endif /* not __GNU_LIBRARY__ */ @@ -265,29 +259,27 @@ static char *const *original_argv;  /* Make sure the environment variable bash 2.0 puts in the environment     is valid for the getopt call we must make sure that the ARGV passed     to getopt is that one passed to the process.  */ -static void -__attribute__ ((unused)) -store_args_and_env (int argc, char *const *argv) +static void __attribute__((unused)) +store_args_and_env(int argc, char *const *argv)  { -  /* XXX This is no good solution.  We should rather copy the args so -     that we can compare them later.  But we must not use malloc(3).  */ -  original_argc = argc; -  original_argv = argv; +	/* XXX This is no good solution.  We should rather copy the args so +	   that we can compare them later.  But we must not use malloc(3).  */ +	original_argc = argc; +	original_argv = argv;  } -# ifdef text_set_element -text_set_element (__libc_subinit, store_args_and_env); -# endif /* text_set_element */ - -# define SWAP_FLAGS(ch1, ch2) \ -  if (nonoption_flags_len > 0)						      \ -    {									      \ -      char __tmp = __getopt_nonoption_flags[ch1];			      \ -      __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2];	      \ -      __getopt_nonoption_flags[ch2] = __tmp;				      \ -    } -#else	/* !_LIBC */ +#ifdef text_set_element +text_set_element(__libc_subinit, store_args_and_env); +#endif /* text_set_element */ + +#define SWAP_FLAGS(ch1, ch2)                                                   \ +	if (nonoption_flags_len > 0) {                                         \ +		char __tmp = __getopt_nonoption_flags[ch1];                    \ +		__getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ +		__getopt_nonoption_flags[ch2] = __tmp;                         \ +	} +#else  /* !_LIBC */  # define SWAP_FLAGS(ch1, ch2) -#endif	/* _LIBC */ +#endif /* _LIBC */  /* Exchange two adjacent subsequences of ARGV.     One subsequence is elements [first_nonopt,last_nonopt) @@ -299,158 +291,147 @@ text_set_element (__libc_subinit, store_args_and_env);     the new indices of the non-options in ARGV after they are moved.  */  #if defined __STDC__ && __STDC__ -static void exchange (char **); +static void exchange(char **);  #endif -static void -exchange (argv) -     char **argv; +static void exchange(argv) char **argv;  { -  int bottom = first_nonopt; -  int middle = last_nonopt; -  int top = optind; -  char *tem; +	int bottom = first_nonopt; +	int middle = last_nonopt; +	int top = optind; +	char *tem; -  /* Exchange the shorter segment with the far end of the longer segment. -     That puts the shorter segment into the right place. -     It leaves the longer segment in the right place overall, -     but it consists of two parts that need to be swapped next.  */ +/* Exchange the shorter segment with the far end of the longer segment. +   That puts the shorter segment into the right place. +   It leaves the longer segment in the right place overall, +   but it consists of two parts that need to be swapped next.  */  #ifdef _LIBC -  /* First make sure the handling of the `__getopt_nonoption_flags' -     string can work normally.  Our top argument must be in the range -     of the string.  */ -  if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) -    { -      /* We must extend the array.  The user plays games with us and -	 presents new arguments.  */ -      char *new_str = malloc (top + 1); -      if (new_str == NULL) -	nonoption_flags_len = nonoption_flags_max_len = 0; -      else -	{ -	  memset (__mempcpy (new_str, __getopt_nonoption_flags, -			     nonoption_flags_max_len), -		  '\0', top + 1 - nonoption_flags_max_len); -	  nonoption_flags_max_len = top + 1; -	  __getopt_nonoption_flags = new_str; +	/* First make sure the handling of the `__getopt_nonoption_flags' +	   string can work normally.  Our top argument must be in the range +	   of the string.  */ +	if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) { +		/* We must extend the array.  The user plays games with us and +		   presents new arguments.  */ +		char *new_str = malloc(top + 1); +		if (new_str == NULL) +			nonoption_flags_len = nonoption_flags_max_len = 0; +		else { +			memset(__mempcpy(new_str, __getopt_nonoption_flags, +					 nonoption_flags_max_len), +			       '\0', top + 1 - nonoption_flags_max_len); +			nonoption_flags_max_len = top + 1; +			__getopt_nonoption_flags = new_str; +		}  	} -    }  #endif -  while (top > middle && middle > bottom) -    { -      if (top - middle > middle - bottom) -	{ -	  /* Bottom segment is the short one.  */ -	  int len = middle - bottom; -	  register int i; - -	  /* Swap it with the top part of the top segment.  */ -	  for (i = 0; i < len; i++) -	    { -	      tem = argv[bottom + i]; -	      argv[bottom + i] = argv[top - (middle - bottom) + i]; -	      argv[top - (middle - bottom) + i] = tem; -	      SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); -	    } -	  /* Exclude the moved bottom segment from further swapping.  */ -	  top -= len; -	} -      else -	{ -	  /* Top segment is the short one.  */ -	  int len = top - middle; -	  register int i; - -	  /* Swap it with the bottom part of the bottom segment.  */ -	  for (i = 0; i < len; i++) -	    { -	      tem = argv[bottom + i]; -	      argv[bottom + i] = argv[middle + i]; -	      argv[middle + i] = tem; -	      SWAP_FLAGS (bottom + i, middle + i); -	    } -	  /* Exclude the moved top segment from further swapping.  */ -	  bottom += len; +	while (top > middle && middle > bottom) { +		if (top - middle > middle - bottom) { +			/* Bottom segment is the short one.  */ +			int len = middle - bottom; +			register int i; + +			/* Swap it with the top part of the top segment.  */ +			for (i = 0; i < len; i++) { +				tem = argv[bottom + i]; +				argv[bottom + i] = +					argv[top - (middle - bottom) + i]; +				argv[top - (middle - bottom) + i] = tem; +				SWAP_FLAGS(bottom + i, +					   top - (middle - bottom) + i); +			} +			/* Exclude the moved bottom segment from further +			 * swapping.  */ +			top -= len; +		} else { +			/* Top segment is the short one.  */ +			int len = top - middle; +			register int i; + +			/* Swap it with the bottom part of the bottom segment. +			 */ +			for (i = 0; i < len; i++) { +				tem = argv[bottom + i]; +				argv[bottom + i] = argv[middle + i]; +				argv[middle + i] = tem; +				SWAP_FLAGS(bottom + i, middle + i); +			} +			/* Exclude the moved top segment from further swapping. +			 */ +			bottom += len; +		}  	} -    } -  /* Update records for the slots the non-options now occupy.  */ +	/* Update records for the slots the non-options now occupy.  */ -  first_nonopt += (optind - last_nonopt); -  last_nonopt = optind; +	first_nonopt += (optind - last_nonopt); +	last_nonopt = optind;  }  /* Initialize the internal data when the first call is made.  */  #if defined __STDC__ && __STDC__ -static const char *_getopt_initialize (int, char *const *, const char *); +static const char *_getopt_initialize(int, char *const *, const char *);  #endif -static const char * -_getopt_initialize (argc, argv, optstring) -     int argc; -     char *const *argv; -     const char *optstring; +static const char *_getopt_initialize(argc, argv, optstring) int argc; +char *const *argv; +const char *optstring;  { -  /* Start processing options with ARGV-element 1 (since ARGV-element 0 -     is the program name); the sequence of previously skipped -     non-option ARGV-elements is empty.  */ +	/* Start processing options with ARGV-element 1 (since ARGV-element 0 +	   is the program name); the sequence of previously skipped +	   non-option ARGV-elements is empty.  */ -  first_nonopt = last_nonopt = optind; +	first_nonopt = last_nonopt = optind; -  nextchar = NULL; +	nextchar = NULL; -  posixly_correct = getenv ("POSIXLY_CORRECT"); +	posixly_correct = getenv("POSIXLY_CORRECT"); -  /* Determine how to handle the ordering of options and nonoptions.  */ +	/* Determine how to handle the ordering of options and nonoptions.  */ -  if (optstring[0] == '-') -    { -      ordering = RETURN_IN_ORDER; -      ++optstring; -    } -  else if (optstring[0] == '+') -    { -      ordering = REQUIRE_ORDER; -      ++optstring; -    } -  else if (posixly_correct != NULL) -    ordering = REQUIRE_ORDER; -  else -    ordering = PERMUTE; +	if (optstring[0] == '-') { +		ordering = RETURN_IN_ORDER; +		++optstring; +	} else if (optstring[0] == '+') { +		ordering = REQUIRE_ORDER; +		++optstring; +	} else if (posixly_correct != NULL) +		ordering = REQUIRE_ORDER; +	else +		ordering = PERMUTE;  #ifdef _LIBC -  if (posixly_correct == NULL -      && argc == original_argc && argv == original_argv) -    { -      if (nonoption_flags_max_len == 0) -	{ -	  if (__getopt_nonoption_flags == NULL -	      || __getopt_nonoption_flags[0] == '\0') -	    nonoption_flags_max_len = -1; -	  else -	    { -	      const char *orig_str = __getopt_nonoption_flags; -	      int len = nonoption_flags_max_len = strlen (orig_str); -	      if (nonoption_flags_max_len < argc) -		nonoption_flags_max_len = argc; -	      __getopt_nonoption_flags = -		(char *) malloc (nonoption_flags_max_len); -	      if (__getopt_nonoption_flags == NULL) -		nonoption_flags_max_len = -1; -	      else -		memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), -			'\0', nonoption_flags_max_len - len); -	    } -	} -      nonoption_flags_len = nonoption_flags_max_len; -    } -  else -    nonoption_flags_len = 0; +	if (posixly_correct == NULL && argc == original_argc +	    && argv == original_argv) { +		if (nonoption_flags_max_len == 0) { +			if (__getopt_nonoption_flags == NULL +			    || __getopt_nonoption_flags[0] == '\0') +				nonoption_flags_max_len = -1; +			else { +				const char *orig_str = __getopt_nonoption_flags; +				int len = nonoption_flags_max_len = +					strlen(orig_str); +				if (nonoption_flags_max_len < argc) +					nonoption_flags_max_len = argc; +				__getopt_nonoption_flags = +					(char *)malloc(nonoption_flags_max_len); +				if (__getopt_nonoption_flags == NULL) +					nonoption_flags_max_len = -1; +				else +					memset(__mempcpy( +						       __getopt_nonoption_flags, +						       orig_str, len), +					       '\0', +					       nonoption_flags_max_len - len); +			} +		} +		nonoption_flags_len = nonoption_flags_max_len; +	} else +		nonoption_flags_len = 0;  #endif -  return optstring; +	return optstring;  }  /* Scan elements of ARGV (whose length is ARGC) for option characters @@ -509,548 +490,536 @@ _getopt_initialize (argc, argv, optstring)     If LONG_ONLY is nonzero, '-' as well as '--' can introduce     long-named options.  */ -int -_getopt_internal (argc, argv, optstring, longopts, longind, long_only) -     int argc; -     char *const *argv; -     const char *optstring; -     const struct option *longopts; -     int *longind; -     int long_only; +int _getopt_internal(argc, argv, optstring, longopts, longind, +		     long_only) int argc; +char *const *argv; +const char *optstring; +const struct option *longopts; +int *longind; +int long_only;  { -  optarg = NULL; - -  if (optind == 0 || !__getopt_initialized) -    { -      if (optind == 0) -	optind = 1;	/* Don't scan ARGV[0], the program name.  */ -      optstring = _getopt_initialize (argc, argv, optstring); -      __getopt_initialized = 1; -    } - -  /* Test whether ARGV[optind] points to a non-option argument. -     Either it does not have option syntax, or there is an environment flag -     from the shell indicating it is not an option.  The later information -     is only used when the used in the GNU libc.  */ +	optarg = NULL; + +	if (optind == 0 || !__getopt_initialized) { +		if (optind == 0) +			optind = 1; /* Don't scan ARGV[0], the program name.  */ +		optstring = _getopt_initialize(argc, argv, optstring); +		__getopt_initialized = 1; +	} + +/* Test whether ARGV[optind] points to a non-option argument. +   Either it does not have option syntax, or there is an environment flag +   from the shell indicating it is not an option.  The later information +   is only used when the used in the GNU libc.  */  #ifdef _LIBC -# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0'	      \ -		      || (optind < nonoption_flags_len			      \ -			  && __getopt_nonoption_flags[optind] == '1')) +#define NONOPTION_P                                                            \ +	(argv[optind][0] != '-' || argv[optind][1] == '\0'                     \ +	 || (optind < nonoption_flags_len                                      \ +	     && __getopt_nonoption_flags[optind] == '1'))  #else  # define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0')  #endif -  if (nextchar == NULL || *nextchar == '\0') -    { -      /* Advance to the next ARGV-element.  */ +	if (nextchar == NULL || *nextchar == '\0') { +		/* Advance to the next ARGV-element.  */ + +		/* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has +		   been +		   moved back by the user (who may also have changed the +		   arguments).  */ +		if (last_nonopt > optind) +			last_nonopt = optind; +		if (first_nonopt > optind) +			first_nonopt = optind; + +		if (ordering == PERMUTE) { +			/* If we have just processed some options following some +			   non-options, +			   exchange them so that the options come first.  */ + +			if (first_nonopt != last_nonopt +			    && last_nonopt != optind) +				exchange((char **)argv); +			else if (last_nonopt != optind) +				first_nonopt = optind; + +			/* Skip any additional non-options +			   and extend the range of non-options previously +			   skipped.  */ + +			while (optind < argc && NONOPTION_P) +				optind++; +			last_nonopt = optind; +		} -      /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been -	 moved back by the user (who may also have changed the arguments).  */ -      if (last_nonopt > optind) -	last_nonopt = optind; -      if (first_nonopt > optind) -	first_nonopt = optind; +		/* The special ARGV-element `--' means premature end of options. +		   Skip it like a null option, +		   then exchange with previous non-options as if it were an +		   option, +		   then skip everything else like a non-option.  */ -      if (ordering == PERMUTE) -	{ -	  /* If we have just processed some options following some non-options, -	     exchange them so that the options come first.  */ +		if (optind != argc && !strcmp(argv[optind], "--")) { +			optind++; -	  if (first_nonopt != last_nonopt && last_nonopt != optind) -	    exchange ((char **) argv); -	  else if (last_nonopt != optind) -	    first_nonopt = optind; +			if (first_nonopt != last_nonopt +			    && last_nonopt != optind) +				exchange((char **)argv); +			else if (first_nonopt == last_nonopt) +				first_nonopt = optind; +			last_nonopt = argc; -	  /* Skip any additional non-options -	     and extend the range of non-options previously skipped.  */ +			optind = argc; +		} -	  while (optind < argc && NONOPTION_P) -	    optind++; -	  last_nonopt = optind; -	} +		/* If we have done all the ARGV-elements, stop the scan +		   and back over any non-options that we skipped and permuted. +		   */ + +		if (optind == argc) { +			/* Set the next-arg-index to point at the non-options +			   that we previously skipped, so the caller will digest +			   them.  */ +			if (first_nonopt != last_nonopt) +				optind = first_nonopt; +			return -1; +		} -      /* The special ARGV-element `--' means premature end of options. -	 Skip it like a null option, -	 then exchange with previous non-options as if it were an option, -	 then skip everything else like a non-option.  */ +		/* If we have come to a non-option and did not permute it, +		   either stop the scan or describe it to the caller and pass it +		   by.  */ -      if (optind != argc && !strcmp (argv[optind], "--")) -	{ -	  optind++; +		if (NONOPTION_P) { +			if (ordering == REQUIRE_ORDER) +				return -1; +			optarg = argv[optind++]; +			return 1; +		} -	  if (first_nonopt != last_nonopt && last_nonopt != optind) -	    exchange ((char **) argv); -	  else if (first_nonopt == last_nonopt) -	    first_nonopt = optind; -	  last_nonopt = argc; +		/* We have found another option-ARGV-element. +		   Skip the initial punctuation.  */ -	  optind = argc; +		nextchar = (argv[optind] + 1 +			    + (longopts != NULL && argv[optind][1] == '-'));  	} -      /* If we have done all the ARGV-elements, stop the scan -	 and back over any non-options that we skipped and permuted.  */ - -      if (optind == argc) -	{ -	  /* Set the next-arg-index to point at the non-options -	     that we previously skipped, so the caller will digest them.  */ -	  if (first_nonopt != last_nonopt) -	    optind = first_nonopt; -	  return -1; -	} +	/* Decode the current option-ARGV-element.  */ + +	/* Check whether the ARGV-element is a long option. + +	   If long_only and the ARGV-element has the form "-f", where f is +	   a valid short option, don't consider it an abbreviated form of +	   a long option that starts with f.  Otherwise there would be no +	   way to give the -f short option. + +	   On the other hand, if there's a long option "fubar" and +	   the ARGV-element is "-fu", do consider that an abbreviation of +	   the long option, just like "--fu", and not "-f" with arg "u". + +	   This distinction seems to be the most useful approach.  */ + +	if (longopts != NULL +	    && (argv[optind][1] == '-' +		|| (long_only && (argv[optind][2] +				  || !my_index(optstring, argv[optind][1]))))) { +		char *nameend; +		const struct option *p; +		const struct option *pfound = NULL; +		int exact = 0; +		int ambig = 0; +		int indfound = -1; +		int option_index; + +		for (nameend = nextchar; *nameend && *nameend != '='; nameend++) +			/* Do nothing.  */; + +		/* Test all long options for either exact match +		   or abbreviated matches.  */ +		for (p = longopts, option_index = 0; p->name; +		     p++, option_index++) +			if (!strncmp(p->name, nextchar, nameend - nextchar)) { +				if ((unsigned int)(nameend - nextchar) +				    == (unsigned int)strlen(p->name)) { +					/* Exact match found.  */ +					pfound = p; +					indfound = option_index; +					exact = 1; +					break; +				} else if (pfound == NULL) { +					/* First nonexact match found.  */ +					pfound = p; +					indfound = option_index; +				} else +					/* Second or later nonexact match found. +					 */ +					ambig = 1; +			} + +		if (ambig && !exact) { +			if (opterr) +				fprintf(stderr, +					_("%s: option `%s' is ambiguous\n"), +					argv[0], argv[optind]); +			nextchar += strlen(nextchar); +			optind++; +			optopt = 0; +			return '?'; +		} -      /* If we have come to a non-option and did not permute it, -	 either stop the scan or describe it to the caller and pass it by.  */ +		if (pfound != NULL) { +			option_index = indfound; +			optind++; +			if (*nameend) { +				/* Don't test has_arg with >, because some C +				   compilers don't +				   allow it to be used on enums.  */ +				if (pfound->has_arg) +					optarg = nameend + 1; +				else { +					if (opterr) { +						if (argv[optind - 1][1] == '-') +							/* --option */ +							fprintf(stderr, +								_("%s: option `--%s' doesn't allow an argument\n"), +								argv[0], +								pfound->name); +						else +							/* +option or -option */ +							fprintf(stderr, +								_("%s: option `%c%s' doesn't allow an argument\n"), +								argv[0], +								argv[optind - 1] +								    [0], +								pfound->name); +					} + +					nextchar += strlen(nextchar); + +					optopt = pfound->val; +					return '?'; +				} +			} else if (pfound->has_arg == 1) { +				if (optind < argc) +					optarg = argv[optind++]; +				else { +					if (opterr) +						fprintf(stderr, +							_("%s: option `%s' requires an argument\n"), +							argv[0], +							argv[optind - 1]); +					nextchar += strlen(nextchar); +					optopt = pfound->val; +					return optstring[0] == ':' ? ':' : '?'; +				} +			} +			nextchar += strlen(nextchar); +			if (longind != NULL) +				*longind = option_index; +			if (pfound->flag) { +				*(pfound->flag) = pfound->val; +				return 0; +			} +			return pfound->val; +		} -      if (NONOPTION_P) -	{ -	  if (ordering == REQUIRE_ORDER) -	    return -1; -	  optarg = argv[optind++]; -	  return 1; +		/* Can't find it as a long option.  If this is not +		   getopt_long_only, +		   or the option starts with '--' or is not a valid short +		   option, then it's an error. +		   Otherwise interpret it as a short option.  */ +		if (!long_only || argv[optind][1] == '-' +		    || my_index(optstring, *nextchar) == NULL) { +			if (opterr) { +				if (argv[optind][1] == '-') +					/* --option */ +					fprintf(stderr, +						_("%s: unrecognized option `--%s'\n"), +						argv[0], nextchar); +				else +					/* +option or -option */ +					fprintf(stderr, +						_("%s: unrecognized option `%c%s'\n"), +						argv[0], argv[optind][0], +						nextchar); +			} +			nextchar = (char *)""; +			optind++; +			optopt = 0; +			return '?'; +		}  	} -      /* We have found another option-ARGV-element. -	 Skip the initial punctuation.  */ - -      nextchar = (argv[optind] + 1 -		  + (longopts != NULL && argv[optind][1] == '-')); -    } - -  /* Decode the current option-ARGV-element.  */ - -  /* Check whether the ARGV-element is a long option. - -     If long_only and the ARGV-element has the form "-f", where f is -     a valid short option, don't consider it an abbreviated form of -     a long option that starts with f.  Otherwise there would be no -     way to give the -f short option. - -     On the other hand, if there's a long option "fubar" and -     the ARGV-element is "-fu", do consider that an abbreviation of -     the long option, just like "--fu", and not "-f" with arg "u". - -     This distinction seems to be the most useful approach.  */ - -  if (longopts != NULL -      && (argv[optind][1] == '-' -	  || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) -    { -      char *nameend; -      const struct option *p; -      const struct option *pfound = NULL; -      int exact = 0; -      int ambig = 0; -      int indfound = -1; -      int option_index; - -      for (nameend = nextchar; *nameend && *nameend != '='; nameend++) -	/* Do nothing.  */ ; - -      /* Test all long options for either exact match -	 or abbreviated matches.  */ -      for (p = longopts, option_index = 0; p->name; p++, option_index++) -	if (!strncmp (p->name, nextchar, nameend - nextchar)) -	  { -	    if ((unsigned int) (nameend - nextchar) -		== (unsigned int) strlen (p->name)) -	      { -		/* Exact match found.  */ -		pfound = p; -		indfound = option_index; -		exact = 1; -		break; -	      } -	    else if (pfound == NULL) -	      { -		/* First nonexact match found.  */ -		pfound = p; -		indfound = option_index; -	      } -	    else -	      /* Second or later nonexact match found.  */ -	      ambig = 1; -	  } - -      if (ambig && !exact) -	{ -	  if (opterr) -	    fprintf (stderr, _("%s: option `%s' is ambiguous\n"), -		     argv[0], argv[optind]); -	  nextchar += strlen (nextchar); -	  optind++; -	  optopt = 0; -	  return '?'; -	} +	/* Look at and handle the next short option-character.  */ -      if (pfound != NULL)  	{ -	  option_index = indfound; -	  optind++; -	  if (*nameend) -	    { -	      /* Don't test has_arg with >, because some C compilers don't -		 allow it to be used on enums.  */ -	      if (pfound->has_arg) -		optarg = nameend + 1; -	      else -		{ -		  if (opterr) -                    { -		      if (argv[optind - 1][1] == '-') -		        /* --option */ -		        fprintf (stderr, -		         _("%s: option `--%s' doesn't allow an argument\n"), -		         argv[0], pfound->name); -		      else -		        /* +option or -option */ -		        fprintf (stderr, -		         _("%s: option `%c%s' doesn't allow an argument\n"), -		         argv[0], argv[optind - 1][0], pfound->name); -                    } - -		  nextchar += strlen (nextchar); - -		  optopt = pfound->val; -		  return '?'; -		} -	    } -	  else if (pfound->has_arg == 1) -	    { -	      if (optind < argc) -		optarg = argv[optind++]; -	      else -		{ -		  if (opterr) -		    fprintf (stderr, -			   _("%s: option `%s' requires an argument\n"), -			   argv[0], argv[optind - 1]); -		  nextchar += strlen (nextchar); -		  optopt = pfound->val; -		  return optstring[0] == ':' ? ':' : '?'; +		char c = *nextchar++; +		char *temp = my_index(optstring, c); + +		/* Increment `optind' when we start to process its last +		 * character.  */ +		if (*nextchar == '\0') +			++optind; + +		if (temp == NULL || c == ':') { +			if (opterr) { +				if (posixly_correct) +					/* 1003.2 specifies the format of this +					 * message.  */ +					fprintf(stderr, +						_("%s: illegal option -- %c\n"), +						argv[0], c); +				else +					fprintf(stderr, +						_("%s: invalid option -- %c\n"), +						argv[0], c); +			} +			optopt = c; +			return '?';  		} -	    } -	  nextchar += strlen (nextchar); -	  if (longind != NULL) -	    *longind = option_index; -	  if (pfound->flag) -	    { -	      *(pfound->flag) = pfound->val; -	      return 0; -	    } -	  return pfound->val; -	} - -      /* Can't find it as a long option.  If this is not getopt_long_only, -	 or the option starts with '--' or is not a valid short -	 option, then it's an error. -	 Otherwise interpret it as a short option.  */ -      if (!long_only || argv[optind][1] == '-' -	  || my_index (optstring, *nextchar) == NULL) -	{ -	  if (opterr) -	    { -	      if (argv[optind][1] == '-') -		/* --option */ -		fprintf (stderr, _("%s: unrecognized option `--%s'\n"), -			 argv[0], nextchar); -	      else -		/* +option or -option */ -		fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), -			 argv[0], argv[optind][0], nextchar); -	    } -	  nextchar = (char *) ""; -	  optind++; -	  optopt = 0; -	  return '?'; -	} -    } - -  /* Look at and handle the next short option-character.  */ - -  { -    char c = *nextchar++; -    char *temp = my_index (optstring, c); - -    /* Increment `optind' when we start to process its last character.  */ -    if (*nextchar == '\0') -      ++optind; - -    if (temp == NULL || c == ':') -      { -	if (opterr) -	  { -	    if (posixly_correct) -	      /* 1003.2 specifies the format of this message.  */ -	      fprintf (stderr, _("%s: illegal option -- %c\n"), -		       argv[0], c); -	    else -	      fprintf (stderr, _("%s: invalid option -- %c\n"), -		       argv[0], c); -	  } -	optopt = c; -	return '?'; -      } -    /* Convenience. Treat POSIX -W foo same as long option --foo */ -    if (temp[0] == 'W' && temp[1] == ';') -      { -	char *nameend; -	const struct option *p; -	const struct option *pfound = NULL; -	int exact = 0; -	int ambig = 0; -	int indfound = 0; -	int option_index; - -	/* This is an option that requires an argument.  */ -	if (*nextchar != '\0') -	  { -	    optarg = nextchar; -	    /* If we end this ARGV-element by taking the rest as an arg, -	       we must advance to the next element now.  */ -	    optind++; -	  } -	else if (optind == argc) -	  { -	    if (opterr) -	      { -		/* 1003.2 specifies the format of this message.  */ -		fprintf (stderr, _("%s: option requires an argument -- %c\n"), -			 argv[0], c); -	      } -	    optopt = c; -	    if (optstring[0] == ':') -	      c = ':'; -	    else -	      c = '?'; -	    return c; -	  } -	else -	  /* We already incremented `optind' once; -	     increment it again when taking next ARGV-elt as argument.  */ -	  optarg = argv[optind++]; - -	/* optarg is now the argument, see if it's in the -	   table of longopts.  */ - -	for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) -	  /* Do nothing.  */ ; - -	/* Test all long options for either exact match -	   or abbreviated matches.  */ -	for (p = longopts, option_index = 0; p->name; p++, option_index++) -	  if (!strncmp (p->name, nextchar, nameend - nextchar)) -	    { -	      if ((unsigned int) (nameend - nextchar) == strlen (p->name)) -		{ -		  /* Exact match found.  */ -		  pfound = p; -		  indfound = option_index; -		  exact = 1; -		  break; +		/* Convenience. Treat POSIX -W foo same as long option --foo */ +		if (temp[0] == 'W' && temp[1] == ';') { +			char *nameend; +			const struct option *p; +			const struct option *pfound = NULL; +			int exact = 0; +			int ambig = 0; +			int indfound = 0; +			int option_index; + +			/* This is an option that requires an argument.  */ +			if (*nextchar != '\0') { +				optarg = nextchar; +				/* If we end this ARGV-element by taking the +				   rest as an arg, +				   we must advance to the next element now.  */ +				optind++; +			} else if (optind == argc) { +				if (opterr) { +					/* 1003.2 specifies the format of this +					 * message.  */ +					fprintf(stderr, +						_("%s: option requires an argument -- %c\n"), +						argv[0], c); +				} +				optopt = c; +				if (optstring[0] == ':') +					c = ':'; +				else +					c = '?'; +				return c; +			} else +				/* We already incremented `optind' once; +				   increment it again when taking next ARGV-elt +				   as argument.  */ +				optarg = argv[optind++]; + +			/* optarg is now the argument, see if it's in the +			   table of longopts.  */ + +			for (nextchar = nameend = optarg; +			     *nameend && *nameend != '='; nameend++) +				/* Do nothing.  */; + +			/* Test all long options for either exact match +			   or abbreviated matches.  */ +			for (p = longopts, option_index = 0; p->name; +			     p++, option_index++) +				if (!strncmp(p->name, nextchar, +					     nameend - nextchar)) { +					if ((unsigned int)(nameend - nextchar) +					    == strlen(p->name)) { +						/* Exact match found.  */ +						pfound = p; +						indfound = option_index; +						exact = 1; +						break; +					} else if (pfound == NULL) { +						/* First nonexact match found. +						 */ +						pfound = p; +						indfound = option_index; +					} else +						/* Second or later nonexact +						 * match found.  */ +						ambig = 1; +				} +			if (ambig && !exact) { +				if (opterr) +					fprintf(stderr, +						_("%s: option `-W %s' is ambiguous\n"), +						argv[0], argv[optind]); +				nextchar += strlen(nextchar); +				optind++; +				return '?'; +			} +			if (pfound != NULL) { +				option_index = indfound; +				if (*nameend) { +					/* Don't test has_arg with >, because +					   some C compilers don't +					   allow it to be used on enums.  */ +					if (pfound->has_arg) +						optarg = nameend + 1; +					else { +						if (opterr) +							fprintf(stderr, _("\ +%s: option `-W %s' doesn't allow an argument\n"), +								argv[0], +								pfound->name); + +						nextchar += strlen(nextchar); +						return '?'; +					} +				} else if (pfound->has_arg == 1) { +					if (optind < argc) +						optarg = argv[optind++]; +					else { +						if (opterr) +							fprintf(stderr, +								_("%s: option `%s' requires an argument\n"), +								argv[0], +								argv[optind +								     - 1]); +						nextchar += strlen(nextchar); +						return optstring[0] == ':' +							       ? ':' +							       : '?'; +					} +				} +				nextchar += strlen(nextchar); +				if (longind != NULL) +					*longind = option_index; +				if (pfound->flag) { +					*(pfound->flag) = pfound->val; +					return 0; +				} +				return pfound->val; +			} +			nextchar = NULL; +			return 'W'; /* Let the application handle it.   */  		} -	      else if (pfound == NULL) -		{ -		  /* First nonexact match found.  */ -		  pfound = p; -		  indfound = option_index; +		if (temp[1] == ':') { +			if (temp[2] == ':') { +				/* This is an option that accepts an argument +				 * optionally.  */ +				if (*nextchar != '\0') { +					optarg = nextchar; +					optind++; +				} else +					optarg = NULL; +				nextchar = NULL; +			} else { +				/* This is an option that requires an argument. +				 */ +				if (*nextchar != '\0') { +					optarg = nextchar; +					/* If we end this ARGV-element by taking +					   the rest as an arg, +					   we must advance to the next element +					   now.  */ +					optind++; +				} else if (optind == argc) { +					if (opterr) { +						/* 1003.2 specifies the format +						 * of this message.  */ +						fprintf(stderr, +							_("%s: option requires an argument -- %c\n"), +							argv[0], c); +					} +					optopt = c; +					if (optstring[0] == ':') +						c = ':'; +					else +						c = '?'; +				} else +					/* We already incremented `optind' once; +					   increment it again when taking next +					   ARGV-elt as argument.  */ +					optarg = argv[optind++]; +				nextchar = NULL; +			}  		} -	      else -		/* Second or later nonexact match found.  */ -		ambig = 1; -	    } -	if (ambig && !exact) -	  { -	    if (opterr) -	      fprintf (stderr, _("%s: option `-W %s' is ambiguous\n"), -		       argv[0], argv[optind]); -	    nextchar += strlen (nextchar); -	    optind++; -	    return '?'; -	  } -	if (pfound != NULL) -	  { -	    option_index = indfound; -	    if (*nameend) -	      { -		/* Don't test has_arg with >, because some C compilers don't -		   allow it to be used on enums.  */ -		if (pfound->has_arg) -		  optarg = nameend + 1; -		else -		  { -		    if (opterr) -		      fprintf (stderr, _("\ -%s: option `-W %s' doesn't allow an argument\n"), -			       argv[0], pfound->name); - -		    nextchar += strlen (nextchar); -		    return '?'; -		  } -	      } -	    else if (pfound->has_arg == 1) -	      { -		if (optind < argc) -		  optarg = argv[optind++]; -		else -		  { -		    if (opterr) -		      fprintf (stderr, -			       _("%s: option `%s' requires an argument\n"), -			       argv[0], argv[optind - 1]); -		    nextchar += strlen (nextchar); -		    return optstring[0] == ':' ? ':' : '?'; -		  } -	      } -	    nextchar += strlen (nextchar); -	    if (longind != NULL) -	      *longind = option_index; -	    if (pfound->flag) -	      { -		*(pfound->flag) = pfound->val; -		return 0; -	      } -	    return pfound->val; -	  } -	  nextchar = NULL; -	  return 'W';	/* Let the application handle it.   */ -      } -    if (temp[1] == ':') -      { -	if (temp[2] == ':') -	  { -	    /* This is an option that accepts an argument optionally.  */ -	    if (*nextchar != '\0') -	      { -		optarg = nextchar; -		optind++; -	      } -	    else -	      optarg = NULL; -	    nextchar = NULL; -	  } -	else -	  { -	    /* This is an option that requires an argument.  */ -	    if (*nextchar != '\0') -	      { -		optarg = nextchar; -		/* If we end this ARGV-element by taking the rest as an arg, -		   we must advance to the next element now.  */ -		optind++; -	      } -	    else if (optind == argc) -	      { -		if (opterr) -		  { -		    /* 1003.2 specifies the format of this message.  */ -		    fprintf (stderr, -			   _("%s: option requires an argument -- %c\n"), -			   argv[0], c); -		  } -		optopt = c; -		if (optstring[0] == ':') -		  c = ':'; -		else -		  c = '?'; -	      } -	    else -	      /* We already incremented `optind' once; -		 increment it again when taking next ARGV-elt as argument.  */ -	      optarg = argv[optind++]; -	    nextchar = NULL; -	  } -      } -    return c; -  } +		return c; +	}  }  #ifdef REALLY_NEED_PLAIN_GETOPT -int -getopt (argc, argv, optstring) -     int argc; -     char *const *argv; -     const char *optstring; +int getopt(argc, argv, optstring) int argc; +char *const *argv; +const char *optstring;  { -  return _getopt_internal (argc, argv, optstring, -			   (const struct option *) 0, -			   (int *) 0, -			   0); +	return _getopt_internal(argc, argv, optstring, (const struct option *)0, +				(int *)0, 0);  }  #endif /* REALLY_NEED_PLAIN_GETOPT */ -#endif	/* Not ELIDE_CODE.  */ +#endif /* Not ELIDE_CODE.  */  #ifdef TEST  /* Compile with -DTEST to make an executable for use in testing     the above definition of `getopt'.  */ -int -main (argc, argv) -     int argc; -     char **argv; +int main(argc, argv) int argc; +char **argv;  { -  int c; -  int digit_optind = 0; - -  while (1) -    { -      int this_option_optind = optind ? optind : 1; - -      c = getopt (argc, argv, "abc:d:0123456789"); -      if (c == -1) -	break; - -      switch (c) -	{ -	case '0': -	case '1': -	case '2': -	case '3': -	case '4': -	case '5': -	case '6': -	case '7': -	case '8': -	case '9': -	  if (digit_optind != 0 && digit_optind != this_option_optind) -	    printf ("digits occur in two different argv-elements.\n"); -	  digit_optind = this_option_optind; -	  printf ("option %c\n", c); -	  break; - -	case 'a': -	  printf ("option a\n"); -	  break; - -	case 'b': -	  printf ("option b\n"); -	  break; - -	case 'c': -	  printf ("option c with value `%s'\n", optarg); -	  break; - -	case '?': -	  break; - -	default: -	  printf ("?? getopt returned character code 0%o ??\n", c); +	int c; +	int digit_optind = 0; + +	while (1) { +		int this_option_optind = optind ? optind : 1; + +		c = getopt(argc, argv, "abc:d:0123456789"); +		if (c == -1) +			break; + +		switch (c) { +		case '0': +		case '1': +		case '2': +		case '3': +		case '4': +		case '5': +		case '6': +		case '7': +		case '8': +		case '9': +			if (digit_optind != 0 +			    && digit_optind != this_option_optind) +				printf("digits occur in two different argv-elements.\n"); +			digit_optind = this_option_optind; +			printf("option %c\n", c); +			break; + +		case 'a': +			printf("option a\n"); +			break; + +		case 'b': +			printf("option b\n"); +			break; + +		case 'c': +			printf("option c with value `%s'\n", optarg); +			break; + +		case '?': +			break; + +		default: +			printf("?? getopt returned character code 0%o ??\n", c); +		}  	} -    } -  if (optind < argc) -    { -      printf ("non-option ARGV-elements: "); -      while (optind < argc) -	printf ("%s ", argv[optind++]); -      printf ("\n"); -    } +	if (optind < argc) { +		printf("non-option ARGV-elements: "); +		while (optind < argc) +			printf("%s ", argv[optind++]); +		printf("\n"); +	} -  exit (0); +	exit(0);  }  #endif /* TEST */ diff --git a/lib/getopt.h b/lib/getopt.h index b359a47beb..73a8c15d03 100644 --- a/lib/getopt.h +++ b/lib/getopt.h @@ -34,7 +34,7 @@   * to use the system version.   */ -#ifdef	__cplusplus +#ifdef __cplusplus  extern "C" {  #endif @@ -90,18 +90,17 @@ extern int optopt;     one).  For long options that have a zero `flag' field, `getopt'     returns the contents of the `val' field.  */ -struct option -{ -#if defined (__STDC__) && __STDC__ -  const char *name; +struct option { +#if defined(__STDC__) && __STDC__ +	const char *name;  #else -  char *name; +	char *name;  #endif -  /* has_arg can't be an enum because some compilers complain about -     type mismatches in all the code that assumes it is an int.  */ -  int has_arg; -  int *flag; -  int val; +	/* has_arg can't be an enum because some compilers complain about +	   type mismatches in all the code that assumes it is an int.  */ +	int has_arg; +	int *flag; +	int val;  };  /* Names for the values of the `has_arg' field of `struct option'.  */ @@ -110,7 +109,7 @@ struct option  #define required_argument	1  #define optional_argument	2 -#if defined (__STDC__) && __STDC__ +#if defined(__STDC__) && __STDC__  #if REALLY_NEED_PLAIN_GETOPT @@ -120,39 +119,37 @@ struct option   * should be written to define NONPOSIX_GETOPT_DEFINITION.   */  #ifndef NONPOSIX_GETOPT_DEFINITION -extern int getopt (int argc, char *const *argv, const char *shortopts); -#else /* NONPOSIX_GETOPT_DEFINITION */ -extern int getopt (void); +extern int getopt(int argc, char *const *argv, const char *shortopts); +#else  /* NONPOSIX_GETOPT_DEFINITION */ +extern int getopt(void);  #endif /* NONPOSIX_GETOPT_DEFINITION */  #endif -extern int getopt_long (int argc, char *const *argv, const char *shortopts, -		        const struct option *longopts, int *longind); -extern int getopt_long_only (int argc, char *const *argv, -			     const char *shortopts, -		             const struct option *longopts, int *longind); +extern int getopt_long(int argc, char *const *argv, const char *shortopts, +		       const struct option *longopts, int *longind); +extern int getopt_long_only(int argc, char *const *argv, const char *shortopts, +			    const struct option *longopts, int *longind);  /* Internal only.  Users should not call this directly.  */ -extern int _getopt_internal (int argc, char *const *argv, -			     const char *shortopts, -		             const struct option *longopts, int *longind, -			     int long_only); +extern int _getopt_internal(int argc, char *const *argv, const char *shortopts, +			    const struct option *longopts, int *longind, +			    int long_only);  #else /* not __STDC__ */  #ifdef REALLY_NEED_PLAIN_GETOPT -extern int getopt (); +extern int getopt();  #endif /* REALLY_NEED_PLAIN_GETOPT */ -extern int getopt_long (); -extern int getopt_long_only (); +extern int getopt_long(); +extern int getopt_long_only(); -extern int _getopt_internal (); +extern int _getopt_internal();  #endif /* __STDC__ */ -#ifdef	__cplusplus +#ifdef __cplusplus  }  #endif diff --git a/lib/getopt1.c b/lib/getopt1.c index bd3099e799..5501214262 100644 --- a/lib/getopt1.c +++ b/lib/getopt1.c @@ -58,19 +58,18 @@  #include <stdlib.h>  #endif -#ifndef	NULL +#ifndef NULL  #define NULL 0  #endif -int -getopt_long (argc, argv, options, long_options, opt_index) -     int argc; -     char *const *argv; -     const char *options; -     const struct option *long_options; -     int *opt_index; +int getopt_long(argc, argv, options, long_options, opt_index) int argc; +char *const *argv; +const char *options; +const struct option *long_options; +int *opt_index;  { -  return _getopt_internal (argc, argv, options, long_options, opt_index, 0); +	return _getopt_internal(argc, argv, options, long_options, opt_index, +				0);  }  /* Like getopt_long, but '-' as well as '--' can indicate a long option. @@ -78,110 +77,100 @@ getopt_long (argc, argv, options, long_options, opt_index)     but does match a short option, it is parsed as a short option     instead.  */ -int -getopt_long_only (argc, argv, options, long_options, opt_index) -     int argc; -     char *const *argv; -     const char *options; -     const struct option *long_options; -     int *opt_index; +int getopt_long_only(argc, argv, options, long_options, opt_index) int argc; +char *const *argv; +const char *options; +const struct option *long_options; +int *opt_index;  { -  return _getopt_internal (argc, argv, options, long_options, opt_index, 1); +	return _getopt_internal(argc, argv, options, long_options, opt_index, +				1);  } -#endif	/* Not ELIDE_CODE.  */ +#endif /* Not ELIDE_CODE.  */  #ifdef TEST  #include <stdio.h> -int -main (argc, argv) -     int argc; -     char **argv; +int main(argc, argv) int argc; +char **argv;  { -  int c; -  int digit_optind = 0; - -  while (1) -    { -      int this_option_optind = optind ? optind : 1; -      int option_index = 0; -      static struct option long_options[] = -      { -	{"add", 1, 0, 0}, -	{"append", 0, 0, 0}, -	{"delete", 1, 0, 0}, -	{"verbose", 0, 0, 0}, -	{"create", 0, 0, 0}, -	{"file", 1, 0, 0}, -	{0, 0, 0, 0} -      }; - -      c = getopt_long (argc, argv, "abc:d:0123456789", -		       long_options, &option_index); -      if (c == -1) -	break; - -      switch (c) -	{ -	case 0: -	  printf ("option %s", long_options[option_index].name); -	  if (optarg) -	    printf (" with arg %s", optarg); -	  printf ("\n"); -	  break; - -	case '0': -	case '1': -	case '2': -	case '3': -	case '4': -	case '5': -	case '6': -	case '7': -	case '8': -	case '9': -	  if (digit_optind != 0 && digit_optind != this_option_optind) -	    printf ("digits occur in two different argv-elements.\n"); -	  digit_optind = this_option_optind; -	  printf ("option %c\n", c); -	  break; - -	case 'a': -	  printf ("option a\n"); -	  break; - -	case 'b': -	  printf ("option b\n"); -	  break; - -	case 'c': -	  printf ("option c with value `%s'\n", optarg); -	  break; - -	case 'd': -	  printf ("option d with value `%s'\n", optarg); -	  break; - -	case '?': -	  break; - -	default: -	  printf ("?? getopt returned character code 0%o ??\n", c); +	int c; +	int digit_optind = 0; + +	while (1) { +		int this_option_optind = optind ? optind : 1; +		int option_index = 0; +		static struct option long_options[] = { +			{"add", 1, 0, 0},    {"append", 0, 0, 0}, +			{"delete", 1, 0, 0}, {"verbose", 0, 0, 0}, +			{"create", 0, 0, 0}, {"file", 1, 0, 0}, +			{0, 0, 0, 0}}; + +		c = getopt_long(argc, argv, "abc:d:0123456789", long_options, +				&option_index); +		if (c == -1) +			break; + +		switch (c) { +		case 0: +			printf("option %s", long_options[option_index].name); +			if (optarg) +				printf(" with arg %s", optarg); +			printf("\n"); +			break; + +		case '0': +		case '1': +		case '2': +		case '3': +		case '4': +		case '5': +		case '6': +		case '7': +		case '8': +		case '9': +			if (digit_optind != 0 +			    && digit_optind != this_option_optind) +				printf("digits occur in two different argv-elements.\n"); +			digit_optind = this_option_optind; +			printf("option %c\n", c); +			break; + +		case 'a': +			printf("option a\n"); +			break; + +		case 'b': +			printf("option b\n"); +			break; + +		case 'c': +			printf("option c with value `%s'\n", optarg); +			break; + +		case 'd': +			printf("option d with value `%s'\n", optarg); +			break; + +		case '?': +			break; + +		default: +			printf("?? getopt returned character code 0%o ??\n", c); +		}  	} -    } -  if (optind < argc) -    { -      printf ("non-option ARGV-elements: "); -      while (optind < argc) -	printf ("%s ", argv[optind++]); -      printf ("\n"); -    } +	if (optind < argc) { +		printf("non-option ARGV-elements: "); +		while (optind < argc) +			printf("%s ", argv[optind++]); +		printf("\n"); +	} -  exit (0); +	exit(0);  }  #endif /* TEST */ diff --git a/lib/grammar_sandbox.c b/lib/grammar_sandbox.c index 3561d7466a..575c311149 100644 --- a/lib/grammar_sandbox.c +++ b/lib/grammar_sandbox.c @@ -37,16 +37,13 @@ DEFINE_MTYPE_STATIC(LIB, CMD_TOKENS, "Command desc")  #define MAXDEPTH 64  /** headers **/ -void -grammar_sandbox_init (void); -void -pretty_print_graph (struct vty *vty, struct graph_node *, int, int, struct graph_node **, size_t); -static void -pretty_print_dot (FILE *ofd, unsigned opts, struct graph_node *start, -                  struct graph_node **stack, size_t stackpos, -                  struct graph_node **visited, size_t *visitpos); -void -init_cmdgraph (struct vty *, struct graph **); +void grammar_sandbox_init(void); +void pretty_print_graph(struct vty *vty, struct graph_node *, int, int, +			struct graph_node **, size_t); +static void pretty_print_dot(FILE *ofd, unsigned opts, struct graph_node *start, +			     struct graph_node **stack, size_t stackpos, +			     struct graph_node **visited, size_t *visitpos); +void init_cmdgraph(struct vty *, struct graph **);  /** shim interface commands **/  struct graph *nodegraph = NULL, *nodegraph_free = NULL; @@ -58,25 +55,28 @@ DEFUN (grammar_test,         "parse a command\n"         "command to pass to new parser\n")  { -  int idx_command = 2; -  // make a string from tokenized command line -  char *command = argv_concat (argv, argc, idx_command); - -  // create cmd_element for parser -  struct cmd_element *cmd = XCALLOC (MTYPE_CMD_TOKENS, sizeof (struct cmd_element)); -  cmd->string = command; -  cmd->doc = "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n"; -  cmd->func = NULL; - -  // parse the command and install it into the command graph -  struct graph *graph = graph_new(); -  struct cmd_token *token = new_cmd_token (START_TKN, CMD_ATTR_NORMAL, NULL, NULL); -  graph_new_node (graph, token, (void (*)(void *)) &del_cmd_token); - -  command_parse_format (graph, cmd); -  cmd_merge_graphs (nodegraph, graph, +1); - -  return CMD_SUCCESS; +	int idx_command = 2; +	// make a string from tokenized command line +	char *command = argv_concat(argv, argc, idx_command); + +	// create cmd_element for parser +	struct cmd_element *cmd = +		XCALLOC(MTYPE_CMD_TOKENS, sizeof(struct cmd_element)); +	cmd->string = command; +	cmd->doc = +		"0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n"; +	cmd->func = NULL; + +	// parse the command and install it into the command graph +	struct graph *graph = graph_new(); +	struct cmd_token *token = +		new_cmd_token(START_TKN, CMD_ATTR_NORMAL, NULL, NULL); +	graph_new_node(graph, token, (void (*)(void *)) & del_cmd_token); + +	command_parse_format(graph, cmd); +	cmd_merge_graphs(nodegraph, graph, +1); + +	return CMD_SUCCESS;  }  DEFUN (grammar_test_complete, @@ -86,55 +86,55 @@ DEFUN (grammar_test_complete,         "attempt to complete input on DFA\n"         "command to complete\n")  { -  int idx_command = 2; -  char *cmdstr = argv_concat (argv, argc, idx_command); -  if (!cmdstr) -    return CMD_SUCCESS; - -  vector command = cmd_make_strvec (cmdstr); -  if (!command) -    { -      XFREE (MTYPE_TMP, cmdstr); -      return CMD_SUCCESS; -    } - -  // generate completions of user input -  struct list *completions; -  enum matcher_rv result = command_complete (nodegraph, command, &completions); - -  // print completions or relevant error message -  if (!MATCHER_ERROR(result)) -    { -      vector comps = completions_to_vec (completions); -      struct cmd_token *tkn; - -      // calculate length of longest tkn->text in completions -      unsigned int width = 0, i = 0; -      for (i = 0; i < vector_active (comps); i++) { -        tkn = vector_slot (comps, i); -        unsigned int len = strlen (tkn->text); -        width = len > width ? len : width; -      } - -      // print completions -      for (i = 0; i < vector_active (comps); i++) { -        tkn = vector_slot (comps, i); -        vty_out (vty, "  %-*s  %s%s", width, tkn->text, tkn->desc, VTY_NEWLINE); -      } - -      for (i = 0; i < vector_active (comps); i++) -        del_cmd_token ((struct cmd_token *) vector_slot (comps, i)); -      vector_free (comps); -    } -  else -    vty_out (vty, "%% No match%s", VTY_NEWLINE); - -  // free resources -  list_delete (completions); -  cmd_free_strvec (command); -  XFREE (MTYPE_TMP, cmdstr); - -  return CMD_SUCCESS; +	int idx_command = 2; +	char *cmdstr = argv_concat(argv, argc, idx_command); +	if (!cmdstr) +		return CMD_SUCCESS; + +	vector command = cmd_make_strvec(cmdstr); +	if (!command) { +		XFREE(MTYPE_TMP, cmdstr); +		return CMD_SUCCESS; +	} + +	// generate completions of user input +	struct list *completions; +	enum matcher_rv result = +		command_complete(nodegraph, command, &completions); + +	// print completions or relevant error message +	if (!MATCHER_ERROR(result)) { +		vector comps = completions_to_vec(completions); +		struct cmd_token *tkn; + +		// calculate length of longest tkn->text in completions +		unsigned int width = 0, i = 0; +		for (i = 0; i < vector_active(comps); i++) { +			tkn = vector_slot(comps, i); +			unsigned int len = strlen(tkn->text); +			width = len > width ? len : width; +		} + +		// print completions +		for (i = 0; i < vector_active(comps); i++) { +			tkn = vector_slot(comps, i); +			vty_out(vty, "  %-*s  %s%s", width, tkn->text, +				tkn->desc, VTY_NEWLINE); +		} + +		for (i = 0; i < vector_active(comps); i++) +			del_cmd_token( +				(struct cmd_token *)vector_slot(comps, i)); +		vector_free(comps); +	} else +		vty_out(vty, "%% No match%s", VTY_NEWLINE); + +	// free resources +	list_delete(completions); +	cmd_free_strvec(command); +	XFREE(MTYPE_TMP, cmdstr); + +	return CMD_SUCCESS;  }  DEFUN (grammar_test_match, @@ -144,60 +144,59 @@ DEFUN (grammar_test_match,         "attempt to match input on DFA\n"         "command to match\n")  { -  int idx_command = 2; -  if (argv[2]->arg[0] == '#') -    return CMD_SUCCESS; - -  char *cmdstr = argv_concat(argv, argc, idx_command); -  if (!cmdstr) -    return CMD_SUCCESS; -  vector command = cmd_make_strvec (cmdstr); -  if (!command) -    { -       XFREE (MTYPE_TMP, cmdstr); -       return CMD_SUCCESS; -    } - -  struct list *argvv = NULL; -  const struct cmd_element *element = NULL; -  enum matcher_rv result = command_match (nodegraph, command, &argvv, &element); - -  // print completions or relevant error message -  if (element) -    { -      vty_out (vty, "Matched: %s%s", element->string, VTY_NEWLINE); -      struct listnode *ln; -      struct cmd_token *token; -      for (ALL_LIST_ELEMENTS_RO(argvv,ln,token)) -        vty_out (vty, "%s -- %s%s", token->text, token->arg, VTY_NEWLINE); - -      vty_out (vty, "func: %p%s", element->func, VTY_NEWLINE); - -      list_delete (argvv); -    } -  else { -     assert(MATCHER_ERROR(result)); -     switch (result) { -       case MATCHER_NO_MATCH: -          vty_out (vty, "%% Unknown command%s", VTY_NEWLINE); -          break; -       case MATCHER_INCOMPLETE: -          vty_out (vty, "%% Incomplete command%s", VTY_NEWLINE); -          break; -       case MATCHER_AMBIGUOUS: -          vty_out (vty, "%% Ambiguous command%s", VTY_NEWLINE); -          break; -       default: -          vty_out (vty, "%% Unknown error%s", VTY_NEWLINE); -          break; -     } -  } - -  // free resources -  cmd_free_strvec (command); -  XFREE (MTYPE_TMP, cmdstr); - -  return CMD_SUCCESS; +	int idx_command = 2; +	if (argv[2]->arg[0] == '#') +		return CMD_SUCCESS; + +	char *cmdstr = argv_concat(argv, argc, idx_command); +	if (!cmdstr) +		return CMD_SUCCESS; +	vector command = cmd_make_strvec(cmdstr); +	if (!command) { +		XFREE(MTYPE_TMP, cmdstr); +		return CMD_SUCCESS; +	} + +	struct list *argvv = NULL; +	const struct cmd_element *element = NULL; +	enum matcher_rv result = +		command_match(nodegraph, command, &argvv, &element); + +	// print completions or relevant error message +	if (element) { +		vty_out(vty, "Matched: %s%s", element->string, VTY_NEWLINE); +		struct listnode *ln; +		struct cmd_token *token; +		for (ALL_LIST_ELEMENTS_RO(argvv, ln, token)) +			vty_out(vty, "%s -- %s%s", token->text, token->arg, +				VTY_NEWLINE); + +		vty_out(vty, "func: %p%s", element->func, VTY_NEWLINE); + +		list_delete(argvv); +	} else { +		assert(MATCHER_ERROR(result)); +		switch (result) { +		case MATCHER_NO_MATCH: +			vty_out(vty, "%% Unknown command%s", VTY_NEWLINE); +			break; +		case MATCHER_INCOMPLETE: +			vty_out(vty, "%% Incomplete command%s", VTY_NEWLINE); +			break; +		case MATCHER_AMBIGUOUS: +			vty_out(vty, "%% Ambiguous command%s", VTY_NEWLINE); +			break; +		default: +			vty_out(vty, "%% Unknown error%s", VTY_NEWLINE); +			break; +		} +	} + +	// free resources +	cmd_free_strvec(command); +	XFREE(MTYPE_TMP, cmdstr); + +	return CMD_SUCCESS;  }  /** @@ -210,28 +209,31 @@ DEFUN (grammar_test_doc,         "Test function for docstring\n"         "Command end\n")  { -  // create cmd_element with docstring -  struct cmd_element *cmd = XCALLOC (MTYPE_CMD_TOKENS, sizeof (struct cmd_element)); -  cmd->string = XSTRDUP (MTYPE_CMD_TOKENS, "test docstring <example|selector follow> (1-255) end VARIABLE [OPTION|set lol] . VARARG"); -  cmd->doc = XSTRDUP (MTYPE_CMD_TOKENS, -             "Test stuff\n" -             "docstring thing\n" -             "first example\n" -             "second example\n" -             "follow\n" -             "random range\n" -             "end thingy\n" -             "variable\n" -             "optional variable\n" -             "optional set\n" -             "optional lol\n" -             "vararg!\n"); -  cmd->func = NULL; - -  // parse element -  command_parse_format (nodegraph, cmd); - -  return CMD_SUCCESS; +	// create cmd_element with docstring +	struct cmd_element *cmd = +		XCALLOC(MTYPE_CMD_TOKENS, sizeof(struct cmd_element)); +	cmd->string = XSTRDUP( +		MTYPE_CMD_TOKENS, +		"test docstring <example|selector follow> (1-255) end VARIABLE [OPTION|set lol] . VARARG"); +	cmd->doc = XSTRDUP(MTYPE_CMD_TOKENS, +			   "Test stuff\n" +			   "docstring thing\n" +			   "first example\n" +			   "second example\n" +			   "follow\n" +			   "random range\n" +			   "end thingy\n" +			   "variable\n" +			   "optional variable\n" +			   "optional set\n" +			   "optional lol\n" +			   "vararg!\n"); +	cmd->func = NULL; + +	// parse element +	command_parse_format(nodegraph, cmd); + +	return CMD_SUCCESS;  }  /** @@ -244,13 +246,14 @@ DEFUN (grammar_test_show,         "print current accumulated DFA\n"         "include docstrings\n")  { -  struct graph_node *stack[MAXDEPTH]; - -  if (!nodegraph) -    vty_out(vty, "nodegraph uninitialized\r\n"); -  else -    pretty_print_graph (vty, vector_slot (nodegraph->nodes, 0), 0, argc >= 3, stack, 0); -  return CMD_SUCCESS; +	struct graph_node *stack[MAXDEPTH]; + +	if (!nodegraph) +		vty_out(vty, "nodegraph uninitialized\r\n"); +	else +		pretty_print_graph(vty, vector_slot(nodegraph->nodes, 0), 0, +				   argc >= 3, stack, 0); +	return CMD_SUCCESS;  }  DEFUN (grammar_test_dot, @@ -260,104 +263,95 @@ DEFUN (grammar_test_dot,         "print current graph for dot\n"         ".dot filename\n")  { -  struct graph_node *stack[MAXDEPTH]; -  struct graph_node *visited[MAXDEPTH*MAXDEPTH]; -  size_t vpos = 0; - -  if (!nodegraph) { -    vty_out(vty, "nodegraph uninitialized\r\n"); -    return CMD_SUCCESS; -  } -  FILE *ofd = fopen(argv[2]->arg, "w"); -  if (!ofd) { -    vty_out(vty, "%s: %s\r\n", argv[2]->arg, strerror(errno)); -    return CMD_SUCCESS; -  } - -  fprintf(ofd, "digraph {\n  graph [ rankdir = LR ];\n  node [ fontname = \"Fira Mono\", fontsize = 9 ];\n\n"); -  pretty_print_dot (ofd, 0, -                    vector_slot (nodegraph->nodes, 0), -                    stack, 0, visited, &vpos); -  fprintf(ofd, "}\n"); -  fclose(ofd); -  return CMD_SUCCESS; +	struct graph_node *stack[MAXDEPTH]; +	struct graph_node *visited[MAXDEPTH * MAXDEPTH]; +	size_t vpos = 0; + +	if (!nodegraph) { +		vty_out(vty, "nodegraph uninitialized\r\n"); +		return CMD_SUCCESS; +	} +	FILE *ofd = fopen(argv[2]->arg, "w"); +	if (!ofd) { +		vty_out(vty, "%s: %s\r\n", argv[2]->arg, strerror(errno)); +		return CMD_SUCCESS; +	} + +	fprintf(ofd, +		"digraph {\n  graph [ rankdir = LR ];\n  node [ fontname = \"Fira Mono\", fontsize = 9 ];\n\n"); +	pretty_print_dot(ofd, 0, vector_slot(nodegraph->nodes, 0), stack, 0, +			 visited, &vpos); +	fprintf(ofd, "}\n"); +	fclose(ofd); +	return CMD_SUCCESS;  } -struct cmd_permute_item -{ -  char *cmd; -  struct cmd_element *el; +struct cmd_permute_item { +	char *cmd; +	struct cmd_element *el;  }; -static void -cmd_permute_free (void *arg) +static void cmd_permute_free(void *arg)  { -  struct cmd_permute_item *i = arg; -  XFREE (MTYPE_TMP, i->cmd); -  XFREE (MTYPE_TMP, i); +	struct cmd_permute_item *i = arg; +	XFREE(MTYPE_TMP, i->cmd); +	XFREE(MTYPE_TMP, i);  } -static int -cmd_permute_cmp (void *a, void *b) +static int cmd_permute_cmp(void *a, void *b)  { -  struct cmd_permute_item *aa = a, *bb = b; -  return strcmp (aa->cmd, bb->cmd); +	struct cmd_permute_item *aa = a, *bb = b; +	return strcmp(aa->cmd, bb->cmd);  } -static void -cmd_graph_permute (struct list *out, struct graph_node **stack, -                   size_t stackpos, char *cmd) +static void cmd_graph_permute(struct list *out, struct graph_node **stack, +			      size_t stackpos, char *cmd)  { -  struct graph_node *gn = stack[stackpos]; -  struct cmd_token *tok = gn->data; -  char *appendp = cmd + strlen(cmd); -  size_t i, j; - -  if (tok->type < SPECIAL_TKN) -    { -      sprintf (appendp, "%s ", tok->text); -      appendp += strlen (appendp); -    } -  else if (tok->type == END_TKN) -    { -      struct cmd_permute_item *i = XMALLOC (MTYPE_TMP, sizeof (*i)); -      i->el = ((struct graph_node *)vector_slot (gn->to, 0))->data; -      i->cmd = XSTRDUP (MTYPE_TMP, cmd); -      i->cmd[strlen(cmd) - 1] = '\0'; -      listnode_add_sort (out, i); -      return; -    } - -  if (++stackpos == MAXDEPTH) -    return; - -  for (i = 0; i < vector_active (gn->to); i++) -    { -      struct graph_node *gnext = vector_slot (gn->to, i); -      for (j = 0; j < stackpos; j++) -        if (stack[j] == gnext) -          break; -      if (j != stackpos) -        continue; - -      stack[stackpos] = gnext; -      *appendp = '\0'; -      cmd_graph_permute (out, stack, stackpos, cmd); -    } +	struct graph_node *gn = stack[stackpos]; +	struct cmd_token *tok = gn->data; +	char *appendp = cmd + strlen(cmd); +	size_t i, j; + +	if (tok->type < SPECIAL_TKN) { +		sprintf(appendp, "%s ", tok->text); +		appendp += strlen(appendp); +	} else if (tok->type == END_TKN) { +		struct cmd_permute_item *i = XMALLOC(MTYPE_TMP, sizeof(*i)); +		i->el = ((struct graph_node *)vector_slot(gn->to, 0))->data; +		i->cmd = XSTRDUP(MTYPE_TMP, cmd); +		i->cmd[strlen(cmd) - 1] = '\0'; +		listnode_add_sort(out, i); +		return; +	} + +	if (++stackpos == MAXDEPTH) +		return; + +	for (i = 0; i < vector_active(gn->to); i++) { +		struct graph_node *gnext = vector_slot(gn->to, i); +		for (j = 0; j < stackpos; j++) +			if (stack[j] == gnext) +				break; +		if (j != stackpos) +			continue; + +		stack[stackpos] = gnext; +		*appendp = '\0'; +		cmd_graph_permute(out, stack, stackpos, cmd); +	}  } -static struct list * -cmd_graph_permutations (struct graph *graph) +static struct list *cmd_graph_permutations(struct graph *graph)  { -  char accumulate[2048] = ""; -  struct graph_node *stack[MAXDEPTH]; - -  struct list *rv = list_new (); -  rv->cmp = cmd_permute_cmp; -  rv->del = cmd_permute_free; -  stack[0] = vector_slot (graph->nodes, 0); -  cmd_graph_permute (rv, stack, 0, accumulate); -  return rv; +	char accumulate[2048] = ""; +	struct graph_node *stack[MAXDEPTH]; + +	struct list *rv = list_new(); +	rv->cmp = cmd_permute_cmp; +	rv->del = cmd_permute_free; +	stack[0] = vector_slot(graph->nodes, 0); +	cmd_graph_permute(rv, stack, 0, accumulate); +	return rv;  }  extern vector cmdvec; @@ -370,68 +364,71 @@ DEFUN (grammar_findambig,         "Print all permutations\n"         "Scan all nodes\n")  { -  struct list *commands; -  struct cmd_permute_item *prev = NULL, *cur = NULL; -  struct listnode *ln; -  int i, printall, scan, scannode = 0; -  int ambig = 0; - -  i = 0; -  printall = argv_find (argv, argc, "printall", &i); -  i = 0; -  scan = argv_find (argv, argc, "nodescan", &i); - -  if (scan && nodegraph_free) -    { -      graph_delete_graph (nodegraph_free); -      nodegraph_free = NULL; -    } - -  if (!scan && !nodegraph) -    { -      vty_out(vty, "nodegraph uninitialized\r\n"); -      return CMD_WARNING; -    } - -  do { -    if (scan) -      { -        struct cmd_node *cnode = vector_slot (cmdvec, scannode++); -        if (!cnode) -          continue; -        nodegraph = cnode->cmdgraph; -        if (!nodegraph) -          continue; -        vty_out (vty, "scanning node %d%s", scannode - 1, VTY_NEWLINE); -      } - -    commands = cmd_graph_permutations (nodegraph); -    prev = NULL; -    for (ALL_LIST_ELEMENTS_RO (commands, ln, cur)) -      { -        int same = prev && !strcmp (prev->cmd, cur->cmd); -        if (printall && !same) -          vty_out (vty, "'%s' [%x]%s", cur->cmd, cur->el->daemon, VTY_NEWLINE); -        if (same) -          { -            vty_out (vty, "'%s' AMBIGUOUS:%s", cur->cmd, VTY_NEWLINE); -            vty_out (vty, "  %s%s   '%s'%s", prev->el->name, VTY_NEWLINE, prev->el->string, VTY_NEWLINE); -            vty_out (vty, "  %s%s   '%s'%s", cur->el->name,  VTY_NEWLINE, cur->el->string,  VTY_NEWLINE); -            vty_out (vty, "%s", VTY_NEWLINE); -            ambig++; -          } -        prev = cur; -      } -    list_delete (commands); - -    vty_out (vty, "%s", VTY_NEWLINE); -  } while (scan && scannode < LINK_PARAMS_NODE); - -  vty_out (vty, "%d ambiguous commands found.%s", ambig, VTY_NEWLINE); - -  if (scan) -    nodegraph = NULL; -  return ambig == 0 ? CMD_SUCCESS : CMD_WARNING; +	struct list *commands; +	struct cmd_permute_item *prev = NULL, *cur = NULL; +	struct listnode *ln; +	int i, printall, scan, scannode = 0; +	int ambig = 0; + +	i = 0; +	printall = argv_find(argv, argc, "printall", &i); +	i = 0; +	scan = argv_find(argv, argc, "nodescan", &i); + +	if (scan && nodegraph_free) { +		graph_delete_graph(nodegraph_free); +		nodegraph_free = NULL; +	} + +	if (!scan && !nodegraph) { +		vty_out(vty, "nodegraph uninitialized\r\n"); +		return CMD_WARNING; +	} + +	do { +		if (scan) { +			struct cmd_node *cnode = +				vector_slot(cmdvec, scannode++); +			if (!cnode) +				continue; +			nodegraph = cnode->cmdgraph; +			if (!nodegraph) +				continue; +			vty_out(vty, "scanning node %d%s", scannode - 1, +				VTY_NEWLINE); +		} + +		commands = cmd_graph_permutations(nodegraph); +		prev = NULL; +		for (ALL_LIST_ELEMENTS_RO(commands, ln, cur)) { +			int same = prev && !strcmp(prev->cmd, cur->cmd); +			if (printall && !same) +				vty_out(vty, "'%s' [%x]%s", cur->cmd, +					cur->el->daemon, VTY_NEWLINE); +			if (same) { +				vty_out(vty, "'%s' AMBIGUOUS:%s", cur->cmd, +					VTY_NEWLINE); +				vty_out(vty, "  %s%s   '%s'%s", prev->el->name, +					VTY_NEWLINE, prev->el->string, +					VTY_NEWLINE); +				vty_out(vty, "  %s%s   '%s'%s", cur->el->name, +					VTY_NEWLINE, cur->el->string, +					VTY_NEWLINE); +				vty_out(vty, "%s", VTY_NEWLINE); +				ambig++; +			} +			prev = cur; +		} +		list_delete(commands); + +		vty_out(vty, "%s", VTY_NEWLINE); +	} while (scan && scannode < LINK_PARAMS_NODE); + +	vty_out(vty, "%d ambiguous commands found.%s", ambig, VTY_NEWLINE); + +	if (scan) +		nodegraph = NULL; +	return ambig == 0 ? CMD_SUCCESS : CMD_WARNING;  }  DEFUN (grammar_init_graph, @@ -440,12 +437,12 @@ DEFUN (grammar_init_graph,         GRAMMAR_STR         "(re)initialize graph\n")  { -  if (nodegraph_free) -    graph_delete_graph (nodegraph_free); -  nodegraph_free = NULL; +	if (nodegraph_free) +		graph_delete_graph(nodegraph_free); +	nodegraph_free = NULL; -  init_cmdgraph (vty, &nodegraph); -  return CMD_SUCCESS; +	init_cmdgraph(vty, &nodegraph); +	return CMD_SUCCESS;  }  DEFUN (grammar_access, @@ -455,57 +452,55 @@ DEFUN (grammar_access,         "access node graph\n"         "node number\n")  { -  if (nodegraph_free) -    graph_delete_graph (nodegraph_free); -  nodegraph_free = NULL; - -  struct cmd_node *cnode; - -  cnode = vector_slot (cmdvec, atoi (argv[2]->arg)); -  if (!cnode) -    { -      vty_out (vty, "%% no such node%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  vty_out (vty, "node %d%s", (int)cnode->node, VTY_NEWLINE); -  nodegraph = cnode->cmdgraph; -  return CMD_SUCCESS; +	if (nodegraph_free) +		graph_delete_graph(nodegraph_free); +	nodegraph_free = NULL; + +	struct cmd_node *cnode; + +	cnode = vector_slot(cmdvec, atoi(argv[2]->arg)); +	if (!cnode) { +		vty_out(vty, "%% no such node%s", VTY_NEWLINE); +		return CMD_WARNING; +	} + +	vty_out(vty, "node %d%s", (int)cnode->node, VTY_NEWLINE); +	nodegraph = cnode->cmdgraph; +	return CMD_SUCCESS;  }  /* this is called in vtysh.c to set up the testing shim */ -void grammar_sandbox_init(void) { -  init_cmdgraph (NULL, &nodegraph); - -  // install all enable elements -  install_element (ENABLE_NODE, &grammar_test_cmd); -  install_element (ENABLE_NODE, &grammar_test_show_cmd); -  install_element (ENABLE_NODE, &grammar_test_dot_cmd); -  install_element (ENABLE_NODE, &grammar_test_match_cmd); -  install_element (ENABLE_NODE, &grammar_test_complete_cmd); -  install_element (ENABLE_NODE, &grammar_test_doc_cmd); -  install_element (ENABLE_NODE, &grammar_findambig_cmd); -  install_element (ENABLE_NODE, &grammar_init_graph_cmd); -  install_element (ENABLE_NODE, &grammar_access_cmd); +void grammar_sandbox_init(void) +{ +	init_cmdgraph(NULL, &nodegraph); + +	// install all enable elements +	install_element(ENABLE_NODE, &grammar_test_cmd); +	install_element(ENABLE_NODE, &grammar_test_show_cmd); +	install_element(ENABLE_NODE, &grammar_test_dot_cmd); +	install_element(ENABLE_NODE, &grammar_test_match_cmd); +	install_element(ENABLE_NODE, &grammar_test_complete_cmd); +	install_element(ENABLE_NODE, &grammar_test_doc_cmd); +	install_element(ENABLE_NODE, &grammar_findambig_cmd); +	install_element(ENABLE_NODE, &grammar_init_graph_cmd); +	install_element(ENABLE_NODE, &grammar_access_cmd);  }  #define item(x) { x, #x } -struct message tokennames[] = { -  item(WORD_TKN),         // words -  item(VARIABLE_TKN),     // almost anything -  item(RANGE_TKN),        // integer range -  item(IPV4_TKN),         // IPV4 addresses -  item(IPV4_PREFIX_TKN),  // IPV4 network prefixes -  item(IPV6_TKN),         // IPV6 prefixes -  item(IPV6_PREFIX_TKN),  // IPV6 network prefixes - -  /* plumbing types */ -  item(FORK_TKN), -  item(JOIN_TKN), -  item(START_TKN),        // first token in line -  item(END_TKN),          // last token in line -  { 0 } -}; +struct message tokennames[] = {item(WORD_TKN),	// words +			       item(VARIABLE_TKN),    // almost anything +			       item(RANGE_TKN),       // integer range +			       item(IPV4_TKN),	// IPV4 addresses +			       item(IPV4_PREFIX_TKN), // IPV4 network prefixes +			       item(IPV6_TKN),	// IPV6 prefixes +			       item(IPV6_PREFIX_TKN), // IPV6 network prefixes + +			       /* plumbing types */ +			       item(FORK_TKN), +			       item(JOIN_TKN), +			       item(START_TKN), // first token in line +			       item(END_TKN),   // last token in line +			       {0}};  /**   * Pretty-prints a graph, assuming it is a tree. @@ -513,141 +508,153 @@ struct message tokennames[] = {   * @param start the node to take as the root   * @param level indent level for recursive calls, always pass 0   */ -void -pretty_print_graph (struct vty *vty, struct graph_node *start, int level, -                    int desc, struct graph_node **stack, size_t stackpos) +void pretty_print_graph(struct vty *vty, struct graph_node *start, int level, +			int desc, struct graph_node **stack, size_t stackpos)  { -  // print this node -  char tokennum[32]; -  struct cmd_token *tok = start->data; - -  snprintf(tokennum, sizeof(tokennum), "%d?", tok->type); -  vty_out(vty, "%s", lookup_msg(tokennames, tok->type, NULL)); -  if (tok->text) -    vty_out(vty, ":\"%s\"", tok->text); -  if (desc) -    vty_out(vty, " ?'%s'", tok->desc); -  vty_out(vty, " "); - -  if (stackpos == MAXDEPTH) -    { -      vty_out(vty, " -aborting! (depth limit)%s", VTY_NEWLINE); -      return; -    } -  stack[stackpos++] = start; - -  int numto = desc ? 2 : vector_active (start->to); -  if (numto) -    { -      if (numto > 1) -        vty_out(vty, "%s", VTY_NEWLINE); -      for (unsigned int i = 0; i < vector_active (start->to); i++) -        { -          struct graph_node *adj = vector_slot (start->to, i); -          // if we're listing multiple children, indent! -          if (numto > 1) -            for (int j = 0; j < level+1; j++) -              vty_out(vty, "    "); -          // if this node is a vararg, just print * -          if (adj == start) -            vty_out(vty, "*"); -          else if (((struct cmd_token *)adj->data)->type == END_TKN) -            vty_out(vty, "--END%s", VTY_NEWLINE); -          else { -            size_t k; -            for (k = 0; k < stackpos; k++) -              if (stack[k] == adj) { -                vty_out(vty, "<<loop@%zu %s", k, VTY_NEWLINE); -                break; -              } -            if (k == stackpos) -              pretty_print_graph (vty, adj, numto > 1 ? level+1 : level, desc, stack, stackpos); -          } -       } -    } -  else -    vty_out(vty, "%s", VTY_NEWLINE); +	// print this node +	char tokennum[32]; +	struct cmd_token *tok = start->data; + +	snprintf(tokennum, sizeof(tokennum), "%d?", tok->type); +	vty_out(vty, "%s", lookup_msg(tokennames, tok->type, NULL)); +	if (tok->text) +		vty_out(vty, ":\"%s\"", tok->text); +	if (desc) +		vty_out(vty, " ?'%s'", tok->desc); +	vty_out(vty, " "); + +	if (stackpos == MAXDEPTH) { +		vty_out(vty, " -aborting! (depth limit)%s", VTY_NEWLINE); +		return; +	} +	stack[stackpos++] = start; + +	int numto = desc ? 2 : vector_active(start->to); +	if (numto) { +		if (numto > 1) +			vty_out(vty, "%s", VTY_NEWLINE); +		for (unsigned int i = 0; i < vector_active(start->to); i++) { +			struct graph_node *adj = vector_slot(start->to, i); +			// if we're listing multiple children, indent! +			if (numto > 1) +				for (int j = 0; j < level + 1; j++) +					vty_out(vty, "    "); +			// if this node is a vararg, just print * +			if (adj == start) +				vty_out(vty, "*"); +			else if (((struct cmd_token *)adj->data)->type +				 == END_TKN) +				vty_out(vty, "--END%s", VTY_NEWLINE); +			else { +				size_t k; +				for (k = 0; k < stackpos; k++) +					if (stack[k] == adj) { +						vty_out(vty, "<<loop@%zu %s", k, +							VTY_NEWLINE); +						break; +					} +				if (k == stackpos) +					pretty_print_graph( +						vty, adj, +						numto > 1 ? level + 1 : level, +						desc, stack, stackpos); +			} +		} +	} else +		vty_out(vty, "%s", VTY_NEWLINE);  } -static void -pretty_print_dot (FILE *ofd, unsigned opts, struct graph_node *start, -                  struct graph_node **stack, size_t stackpos, -                  struct graph_node **visited, size_t *visitpos) +static void pretty_print_dot(FILE *ofd, unsigned opts, struct graph_node *start, +			     struct graph_node **stack, size_t stackpos, +			     struct graph_node **visited, size_t *visitpos)  { -  // print this node -  char tokennum[32]; -  struct cmd_token *tok = start->data; -  const char *color; - -  for (size_t i = 0; i < (*visitpos); i++) -    if (visited[i] == start) -      return; -  visited[(*visitpos)++] = start; -  if ((*visitpos) == MAXDEPTH*MAXDEPTH) -    return; - -  snprintf(tokennum, sizeof(tokennum), "%d?", tok->type); -  fprintf(ofd, "  n%p [ shape=box, label=<", start); - -  fprintf(ofd, "<b>%s</b>", lookup_msg(tokennames, tok->type, NULL)); -  if (tok->attr == CMD_ATTR_DEPRECATED) -    fprintf(ofd, " (d)"); -  else if (tok->attr == CMD_ATTR_HIDDEN) -    fprintf(ofd, " (h)"); -  if (tok->text) { -    if (tok->type == WORD_TKN) -      fprintf(ofd, "<br/>\"<font color=\"#0055ff\" point-size=\"11\"><b>%s</b></font>\"", tok->text); -    else -      fprintf(ofd, "<br/>%s", tok->text); -  } -/*  if (desc) -    fprintf(ofd, " ?'%s'", tok->desc); */ -  switch (tok->type) { -  case START_TKN:	color = "#ccffcc"; break; -  case FORK_TKN:	color = "#aaddff"; break; -  case JOIN_TKN:	color = "#ddaaff"; break; -  case WORD_TKN:	color = "#ffffff"; break; -  default:		color = "#ffffff"; break; -  } -  fprintf(ofd, ">, style = filled, fillcolor = \"%s\" ];\n", color); - -  if (stackpos == MAXDEPTH) -    return; -  stack[stackpos++] = start; - -  for (unsigned int i = 0; i < vector_active (start->to); i++) -    { -      struct graph_node *adj = vector_slot (start->to, i); -      // if this node is a vararg, just print * -      if (adj == start) { -        fprintf(ofd, "  n%p -> n%p;\n", start, start); -      } else if (((struct cmd_token *)adj->data)->type == END_TKN) { -        //struct cmd_token *et = adj->data; -        fprintf(ofd, "  n%p -> end%p;\n", start, adj); -        fprintf(ofd, "  end%p [ shape=box, label=<end>, style = filled, fillcolor = \"#ffddaa\" ];\n", adj); -      } else { -        fprintf(ofd, "  n%p -> n%p;\n", start, adj); -        size_t k; -        for (k = 0; k < stackpos; k++) -          if (stack[k] == adj) -            break; -        if (k == stackpos) { -          pretty_print_dot (ofd, opts, adj, stack, stackpos, visited, visitpos); -        } -      } -   } +	// print this node +	char tokennum[32]; +	struct cmd_token *tok = start->data; +	const char *color; + +	for (size_t i = 0; i < (*visitpos); i++) +		if (visited[i] == start) +			return; +	visited[(*visitpos)++] = start; +	if ((*visitpos) == MAXDEPTH * MAXDEPTH) +		return; + +	snprintf(tokennum, sizeof(tokennum), "%d?", tok->type); +	fprintf(ofd, "  n%p [ shape=box, label=<", start); + +	fprintf(ofd, "<b>%s</b>", lookup_msg(tokennames, tok->type, NULL)); +	if (tok->attr == CMD_ATTR_DEPRECATED) +		fprintf(ofd, " (d)"); +	else if (tok->attr == CMD_ATTR_HIDDEN) +		fprintf(ofd, " (h)"); +	if (tok->text) { +		if (tok->type == WORD_TKN) +			fprintf(ofd, +				"<br/>\"<font color=\"#0055ff\" point-size=\"11\"><b>%s</b></font>\"", +				tok->text); +		else +			fprintf(ofd, "<br/>%s", tok->text); +	} +	/*  if (desc) +	    fprintf(ofd, " ?'%s'", tok->desc); */ +	switch (tok->type) { +	case START_TKN: +		color = "#ccffcc"; +		break; +	case FORK_TKN: +		color = "#aaddff"; +		break; +	case JOIN_TKN: +		color = "#ddaaff"; +		break; +	case WORD_TKN: +		color = "#ffffff"; +		break; +	default: +		color = "#ffffff"; +		break; +	} +	fprintf(ofd, ">, style = filled, fillcolor = \"%s\" ];\n", color); + +	if (stackpos == MAXDEPTH) +		return; +	stack[stackpos++] = start; + +	for (unsigned int i = 0; i < vector_active(start->to); i++) { +		struct graph_node *adj = vector_slot(start->to, i); +		// if this node is a vararg, just print * +		if (adj == start) { +			fprintf(ofd, "  n%p -> n%p;\n", start, start); +		} else if (((struct cmd_token *)adj->data)->type == END_TKN) { +			// struct cmd_token *et = adj->data; +			fprintf(ofd, "  n%p -> end%p;\n", start, adj); +			fprintf(ofd, +				"  end%p [ shape=box, label=<end>, style = filled, fillcolor = \"#ffddaa\" ];\n", +				adj); +		} else { +			fprintf(ofd, "  n%p -> n%p;\n", start, adj); +			size_t k; +			for (k = 0; k < stackpos; k++) +				if (stack[k] == adj) +					break; +			if (k == stackpos) { +				pretty_print_dot(ofd, opts, adj, stack, +						 stackpos, visited, visitpos); +			} +		} +	}  }  /** stuff that should go in command.c + command.h */ -void -init_cmdgraph (struct vty *vty, struct graph **graph) +void init_cmdgraph(struct vty *vty, struct graph **graph)  { -  // initialize graph, add start noe -  *graph = graph_new (); -  nodegraph_free = *graph; -  struct cmd_token *token = new_cmd_token (START_TKN, 0, NULL, NULL); -  graph_new_node (*graph, token, (void (*)(void *)) &del_cmd_token); -  if (vty) -    vty_out (vty, "initialized graph%s", VTY_NEWLINE); +	// initialize graph, add start noe +	*graph = graph_new(); +	nodegraph_free = *graph; +	struct cmd_token *token = new_cmd_token(START_TKN, 0, NULL, NULL); +	graph_new_node(*graph, token, (void (*)(void *)) & del_cmd_token); +	if (vty) +		vty_out(vty, "initialized graph%s", VTY_NEWLINE);  } diff --git a/lib/grammar_sandbox_main.c b/lib/grammar_sandbox_main.c index 681d4da440..f529245f9c 100644 --- a/lib/grammar_sandbox_main.c +++ b/lib/grammar_sandbox_main.c @@ -28,37 +28,37 @@  static void vty_do_exit(void)  { -  printf ("\nend.\n"); -  exit (0); +	printf("\nend.\n"); +	exit(0);  }  struct thread_master *master;  int main(int argc, char **argv)  { -  struct thread thread; +	struct thread thread; -  master = thread_master_create (); +	master = thread_master_create(); -  openzlog ("grammar_sandbox", "NONE", 0, -                           LOG_CONS|LOG_NDELAY|LOG_PID, LOG_DAEMON); -  zlog_set_level (ZLOG_DEST_SYSLOG, ZLOG_DISABLED); -  zlog_set_level (ZLOG_DEST_STDOUT, LOG_DEBUG); -  zlog_set_level (ZLOG_DEST_MONITOR, ZLOG_DISABLED); +	openzlog("grammar_sandbox", "NONE", 0, LOG_CONS | LOG_NDELAY | LOG_PID, +		 LOG_DAEMON); +	zlog_set_level(ZLOG_DEST_SYSLOG, ZLOG_DISABLED); +	zlog_set_level(ZLOG_DEST_STDOUT, LOG_DEBUG); +	zlog_set_level(ZLOG_DEST_MONITOR, ZLOG_DISABLED); -  /* Library inits. */ -  cmd_init (1); -  host.name = strdup ("test"); +	/* Library inits. */ +	cmd_init(1); +	host.name = strdup("test"); -  vty_init (master); -  memory_init (); +	vty_init(master); +	memory_init(); -  vty_stdio (vty_do_exit); +	vty_stdio(vty_do_exit); -  /* Fetch next active thread. */ -  while (thread_fetch (master, &thread)) -    thread_call (&thread); +	/* Fetch next active thread. */ +	while (thread_fetch(master, &thread)) +		thread_call(&thread); -  /* Not reached. */ -  exit (0); +	/* Not reached. */ +	exit(0);  } diff --git a/lib/graph.c b/lib/graph.c index 0992059ef1..d593a66403 100644 --- a/lib/graph.c +++ b/lib/graph.c @@ -25,124 +25,115 @@  #include "graph.h"  #include "memory.h" -DEFINE_MTYPE_STATIC(LIB, GRAPH,      "Graph") +DEFINE_MTYPE_STATIC(LIB, GRAPH, "Graph")  DEFINE_MTYPE_STATIC(LIB, GRAPH_NODE, "Graph Node") -struct graph * -graph_new () +struct graph *graph_new()  { -  struct graph *graph = XCALLOC (MTYPE_GRAPH, sizeof(struct graph)); -  graph->nodes = vector_init (VECTOR_MIN_SIZE); +	struct graph *graph = XCALLOC(MTYPE_GRAPH, sizeof(struct graph)); +	graph->nodes = vector_init(VECTOR_MIN_SIZE); -  return graph; +	return graph;  } -struct graph_node * -graph_new_node (struct graph *graph, void *data, void (*del) (void*)) +struct graph_node *graph_new_node(struct graph *graph, void *data, +				  void (*del)(void *))  { -  struct graph_node *node = -     XCALLOC(MTYPE_GRAPH_NODE, sizeof(struct graph_node)); +	struct graph_node *node = +		XCALLOC(MTYPE_GRAPH_NODE, sizeof(struct graph_node)); -  node->from = vector_init (VECTOR_MIN_SIZE); -  node->to   = vector_init (VECTOR_MIN_SIZE); -  node->data = data; -  node->del  = del; +	node->from = vector_init(VECTOR_MIN_SIZE); +	node->to = vector_init(VECTOR_MIN_SIZE); +	node->data = data; +	node->del = del; -  vector_set (graph->nodes, node); +	vector_set(graph->nodes, node); -  return node; +	return node;  } -static void -vector_remove (vector v, unsigned int ix) +static void vector_remove(vector v, unsigned int ix)  { -  if (ix >= v->active) -    return; - -  /* v->active is guaranteed >= 1 because ix can't be lower than 0 -   * and v->active is > ix. */ -  v->active--; -  /* if ix == v->active--, we set the item to itself, then to NULL... -   * still correct, no check neccessary. */ -  v->index[ix] = v->index[v->active]; -  v->index[v->active] = NULL; +	if (ix >= v->active) +		return; + +	/* v->active is guaranteed >= 1 because ix can't be lower than 0 +	 * and v->active is > ix. */ +	v->active--; +	/* if ix == v->active--, we set the item to itself, then to NULL... +	 * still correct, no check neccessary. */ +	v->index[ix] = v->index[v->active]; +	v->index[v->active] = NULL;  } -void -graph_delete_node (struct graph *graph, struct graph_node *node) +void graph_delete_node(struct graph *graph, struct graph_node *node)  { -  if (!node) return; - -  // an adjacent node -  struct graph_node *adj; - -  // remove all edges from other nodes to us -  for (unsigned int i = vector_active (node->from); i--; /**/) -    { -      adj = vector_slot (node->from, i); -      graph_remove_edge (adj, node); -    } - -  // remove all edges from us to other nodes -  for (unsigned int i = vector_active (node->to); i--; /**/) -    { -      adj = vector_slot (node->to, i); -      graph_remove_edge (node, adj); -    } - -  // if there is a deletion callback, call it -  if (node->del && node->data) -    (*node->del) (node->data); - -  // free adjacency lists -  vector_free (node->to); -  vector_free (node->from); - -  // remove node from graph->nodes -  for (unsigned int i = vector_active (graph->nodes); i--; /**/) -    if (vector_slot (graph->nodes, i) == node) -      { -        vector_remove (graph->nodes, i); -        break; -      } - -  // free the node itself -  XFREE (MTYPE_GRAPH_NODE, node); +	if (!node) +		return; + +	// an adjacent node +	struct graph_node *adj; + +	// remove all edges from other nodes to us +	for (unsigned int i = vector_active(node->from); i--; /**/) { +		adj = vector_slot(node->from, i); +		graph_remove_edge(adj, node); +	} + +	// remove all edges from us to other nodes +	for (unsigned int i = vector_active(node->to); i--; /**/) { +		adj = vector_slot(node->to, i); +		graph_remove_edge(node, adj); +	} + +	// if there is a deletion callback, call it +	if (node->del && node->data) +		(*node->del)(node->data); + +	// free adjacency lists +	vector_free(node->to); +	vector_free(node->from); + +	// remove node from graph->nodes +	for (unsigned int i = vector_active(graph->nodes); i--; /**/) +		if (vector_slot(graph->nodes, i) == node) { +			vector_remove(graph->nodes, i); +			break; +		} + +	// free the node itself +	XFREE(MTYPE_GRAPH_NODE, node);  } -struct graph_node * -graph_add_edge (struct graph_node *from, struct graph_node *to) +struct graph_node *graph_add_edge(struct graph_node *from, +				  struct graph_node *to)  { -  vector_set (from->to, to); -  vector_set (to->from, from); -  return to; +	vector_set(from->to, to); +	vector_set(to->from, from); +	return to;  } -void -graph_remove_edge (struct graph_node *from, struct graph_node *to) +void graph_remove_edge(struct graph_node *from, struct graph_node *to)  { -  // remove from from to->from -  for (unsigned int i = vector_active (to->from); i--; /**/) -    if (vector_slot (to->from, i) == from) -      { -        vector_remove (to->from, i); -        break; -      } -  // remove to from from->to -  for (unsigned int i = vector_active (from->to); i--; /**/) -    if (vector_slot (from->to, i) == to) -      { -        vector_remove (from->to, i); -        break; -      } +	// remove from from to->from +	for (unsigned int i = vector_active(to->from); i--; /**/) +		if (vector_slot(to->from, i) == from) { +			vector_remove(to->from, i); +			break; +		} +	// remove to from from->to +	for (unsigned int i = vector_active(from->to); i--; /**/) +		if (vector_slot(from->to, i) == to) { +			vector_remove(from->to, i); +			break; +		}  } -void -graph_delete_graph (struct graph *graph) +void graph_delete_graph(struct graph *graph)  { -  // delete each node in the graph -  for (unsigned int i = vector_active (graph->nodes); i--; /**/) -    graph_delete_node (graph, vector_slot (graph->nodes, i)); +	// delete each node in the graph +	for (unsigned int i = vector_active(graph->nodes); i--; /**/) +		graph_delete_node(graph, vector_slot(graph->nodes, i)); -  vector_free (graph->nodes); -  XFREE (MTYPE_GRAPH, graph); +	vector_free(graph->nodes); +	XFREE(MTYPE_GRAPH, graph);  } diff --git a/lib/graph.h b/lib/graph.h index 8d8aa3823b..180d16e0f9 100644 --- a/lib/graph.h +++ b/lib/graph.h @@ -27,22 +27,19 @@  #include "vector.h" -struct graph -{ -  vector nodes; +struct graph { +	vector nodes;  }; -struct graph_node -{ -  vector from;                  // nodes which have edges to this node -  vector to;                    // nodes which this node has edges to +struct graph_node { +	vector from; // nodes which have edges to this node +	vector to;   // nodes which this node has edges to -  void *data;                   // node data -  void (*del) (void *data);     // deletion callback +	void *data;		 // node data +	void (*del)(void *data); // deletion callback  }; -struct graph * -graph_new (void); +struct graph *graph_new(void);  /**   * Creates a new node. @@ -52,8 +49,8 @@ graph_new (void);   * @param[in] del data deletion callback   * @return the new node   */ -struct graph_node * -graph_new_node (struct graph *graph, void *data, void (*del) (void*)); +struct graph_node *graph_new_node(struct graph *graph, void *data, +				  void (*del)(void *));  /**   * Deletes a node. @@ -67,8 +64,7 @@ graph_new_node (struct graph *graph, void *data, void (*del) (void*));   * @param[in] graph the graph this node belongs to   * @param[out] node pointer to node to delete   */ -void -graph_delete_node (struct graph *graph, struct graph_node *node); +void graph_delete_node(struct graph *graph, struct graph_node *node);  /**   * Makes a directed edge between two nodes. @@ -77,8 +73,8 @@ graph_delete_node (struct graph *graph, struct graph_node *node);   * @param[in] to   * @return to   */ -struct graph_node * -graph_add_edge (struct graph_node *from, struct graph_node *to); +struct graph_node *graph_add_edge(struct graph_node *from, +				  struct graph_node *to);  /**   * Removes a directed edge between two nodes. @@ -86,8 +82,7 @@ graph_add_edge (struct graph_node *from, struct graph_node *to);   * @param[in] from   * @param[in] to   */ -void -graph_remove_edge (struct graph_node *from, struct graph_node *to); +void graph_remove_edge(struct graph_node *from, struct graph_node *to);  /**   * Deletes a graph. @@ -95,7 +90,6 @@ graph_remove_edge (struct graph_node *from, struct graph_node *to);   *   * @param graph the graph to delete   */ -void -graph_delete_graph (struct graph *graph); +void graph_delete_graph(struct graph *graph);  #endif /* _ZEBRA_COMMAND_GRAPH_H */ diff --git a/lib/hash.c b/lib/hash.c index cb8531fccf..479aaea47c 100644 --- a/lib/hash.c +++ b/lib/hash.c @@ -24,265 +24,246 @@  #include "hash.h"  #include "memory.h" -DEFINE_MTYPE(       LIB, HASH,        "Hash") -DEFINE_MTYPE(       LIB, HASH_BACKET, "Hash Bucket") -DEFINE_MTYPE_STATIC(LIB, HASH_INDEX,  "Hash Index") +DEFINE_MTYPE(LIB, HASH, "Hash") +DEFINE_MTYPE(LIB, HASH_BACKET, "Hash Bucket") +DEFINE_MTYPE_STATIC(LIB, HASH_INDEX, "Hash Index")  /* Allocate a new hash.  */ -struct hash * -hash_create_size (unsigned int size, unsigned int (*hash_key) (void *), -		  int (*hash_cmp) (const void *, const void *)) +struct hash *hash_create_size(unsigned int size, +			      unsigned int (*hash_key)(void *), +			      int (*hash_cmp)(const void *, const void *))  { -  struct hash *hash; - -  assert ((size & (size-1)) == 0); -  hash = XMALLOC (MTYPE_HASH, sizeof (struct hash)); -  hash->index = XCALLOC (MTYPE_HASH_INDEX, -			 sizeof (struct hash_backet *) * size); -  hash->size = size; -  hash->no_expand = 0; -  hash->hash_key = hash_key; -  hash->hash_cmp = hash_cmp; -  hash->count = 0; - -  return hash; +	struct hash *hash; + +	assert((size & (size - 1)) == 0); +	hash = XMALLOC(MTYPE_HASH, sizeof(struct hash)); +	hash->index = +		XCALLOC(MTYPE_HASH_INDEX, sizeof(struct hash_backet *) * size); +	hash->size = size; +	hash->no_expand = 0; +	hash->hash_key = hash_key; +	hash->hash_cmp = hash_cmp; +	hash->count = 0; + +	return hash;  }  /* Allocate a new hash with default hash size.  */ -struct hash * -hash_create (unsigned int (*hash_key) (void *),  -             int (*hash_cmp) (const void *, const void *)) +struct hash *hash_create(unsigned int (*hash_key)(void *), +			 int (*hash_cmp)(const void *, const void *))  { -  return hash_create_size (HASH_INITIAL_SIZE, hash_key, hash_cmp); +	return hash_create_size(HASH_INITIAL_SIZE, hash_key, hash_cmp);  }  /* Utility function for hash_get().  When this function is specified     as alloc_func, return arugment as it is.  This function is used for     intern already allocated value.  */ -void * -hash_alloc_intern (void *arg) +void *hash_alloc_intern(void *arg)  { -  return arg; +	return arg;  }  /* Expand hash if the chain length exceeds the threshold. */ -static void hash_expand (struct hash *hash) +static void hash_expand(struct hash *hash)  { -  unsigned int i, new_size, losers; -  struct hash_backet *hb, *hbnext, **new_index; - -  new_size = hash->size * 2; -  new_index = XCALLOC(MTYPE_HASH_INDEX, sizeof(struct hash_backet *) * new_size); -  if (new_index == NULL) -    return; - -  for (i = 0; i < hash->size; i++) -    for (hb = hash->index[i]; hb; hb = hbnext) -      { -	unsigned int h = hb->key & (new_size - 1); - -	hbnext = hb->next; -	hb->next = new_index[h]; -	new_index[h] = hb; -      } - -  /* Switch to new table */ -  XFREE(MTYPE_HASH_INDEX, hash->index); -  hash->size = new_size; -  hash->index = new_index; - -  /* Ideally, new index should have chains half as long as the original. -     If expansion didn't help, then not worth expanding again, -     the problem is the hash function. */ -  losers = 0; -  for (i = 0; i < hash->size; i++) -    { -      unsigned int len = 0; -      for (hb = hash->index[i]; hb; hb = hb->next) -	{ -	  if (++len > HASH_THRESHOLD/2) -	    ++losers; -	  if (len >= HASH_THRESHOLD) -	    hash->no_expand = 1; +	unsigned int i, new_size, losers; +	struct hash_backet *hb, *hbnext, **new_index; + +	new_size = hash->size * 2; +	new_index = XCALLOC(MTYPE_HASH_INDEX, +			    sizeof(struct hash_backet *) * new_size); +	if (new_index == NULL) +		return; + +	for (i = 0; i < hash->size; i++) +		for (hb = hash->index[i]; hb; hb = hbnext) { +			unsigned int h = hb->key & (new_size - 1); + +			hbnext = hb->next; +			hb->next = new_index[h]; +			new_index[h] = hb; +		} + +	/* Switch to new table */ +	XFREE(MTYPE_HASH_INDEX, hash->index); +	hash->size = new_size; +	hash->index = new_index; + +	/* Ideally, new index should have chains half as long as the original. +	   If expansion didn't help, then not worth expanding again, +	   the problem is the hash function. */ +	losers = 0; +	for (i = 0; i < hash->size; i++) { +		unsigned int len = 0; +		for (hb = hash->index[i]; hb; hb = hb->next) { +			if (++len > HASH_THRESHOLD / 2) +				++losers; +			if (len >= HASH_THRESHOLD) +				hash->no_expand = 1; +		}  	} -    } -  if (losers > hash->count / 2) -    hash->no_expand = 1; +	if (losers > hash->count / 2) +		hash->no_expand = 1;  }  /* Lookup and return hash backet in hash.  If there is no     corresponding hash backet and alloc_func is specified, create new     hash backet.  */ -void * -hash_get (struct hash *hash, void *data, void * (*alloc_func) (void *)) +void *hash_get(struct hash *hash, void *data, void *(*alloc_func)(void *))  { -  unsigned int key; -  unsigned int index; -  void *newdata; -  unsigned int len; -  struct hash_backet *backet; - -  key = (*hash->hash_key) (data); -  index = key & (hash->size - 1); -  len = 0; - -  for (backet = hash->index[index]; backet != NULL; backet = backet->next) -    { -      if (backet->key == key && (*hash->hash_cmp) (backet->data, data)) -	return backet->data; -      ++len; -    } - -  if (alloc_func) -    { -      newdata = (*alloc_func) (data); -      if (newdata == NULL) -	return NULL; - -      if (len > HASH_THRESHOLD && !hash->no_expand) -	{ -	  hash_expand (hash); -	  index = key & (hash->size - 1); +	unsigned int key; +	unsigned int index; +	void *newdata; +	unsigned int len; +	struct hash_backet *backet; + +	key = (*hash->hash_key)(data); +	index = key & (hash->size - 1); +	len = 0; + +	for (backet = hash->index[index]; backet != NULL; +	     backet = backet->next) { +		if (backet->key == key && (*hash->hash_cmp)(backet->data, data)) +			return backet->data; +		++len;  	} -      backet = XMALLOC (MTYPE_HASH_BACKET, sizeof (struct hash_backet)); -      backet->data = newdata; -      backet->key = key; -      backet->next = hash->index[index]; -      hash->index[index] = backet; -      hash->count++; -      return backet->data; -    } -  return NULL; +	if (alloc_func) { +		newdata = (*alloc_func)(data); +		if (newdata == NULL) +			return NULL; + +		if (len > HASH_THRESHOLD && !hash->no_expand) { +			hash_expand(hash); +			index = key & (hash->size - 1); +		} + +		backet = XMALLOC(MTYPE_HASH_BACKET, sizeof(struct hash_backet)); +		backet->data = newdata; +		backet->key = key; +		backet->next = hash->index[index]; +		hash->index[index] = backet; +		hash->count++; +		return backet->data; +	} +	return NULL;  }  /* Hash lookup.  */ -void * -hash_lookup (struct hash *hash, void *data) +void *hash_lookup(struct hash *hash, void *data)  { -  return hash_get (hash, data, NULL); +	return hash_get(hash, data, NULL);  }  /* Simple Bernstein hash which is simple and fast for common case */ -unsigned int string_hash_make (const char *str) +unsigned int string_hash_make(const char *str)  { -  unsigned int hash = 0; +	unsigned int hash = 0; -  while (*str) -    hash = (hash * 33) ^ (unsigned int) *str++; +	while (*str) +		hash = (hash * 33) ^ (unsigned int)*str++; -  return hash; +	return hash;  }  /* This function release registered value from specified hash.  When     release is successfully finished, return the data pointer in the     hash backet.  */ -void * -hash_release (struct hash *hash, void *data) +void *hash_release(struct hash *hash, void *data)  { -  void *ret; -  unsigned int key; -  unsigned int index; -  struct hash_backet *backet; -  struct hash_backet *pp; - -  key = (*hash->hash_key) (data); -  index = key & (hash->size - 1); - -  for (backet = pp = hash->index[index]; backet; backet = backet->next) -    { -      if (backet->key == key && (*hash->hash_cmp) (backet->data, data))  -	{ -	  if (backet == pp)  -	    hash->index[index] = backet->next; -	  else  -	    pp->next = backet->next; - -	  ret = backet->data; -	  XFREE (MTYPE_HASH_BACKET, backet); -	  hash->count--; -	  return ret; +	void *ret; +	unsigned int key; +	unsigned int index; +	struct hash_backet *backet; +	struct hash_backet *pp; + +	key = (*hash->hash_key)(data); +	index = key & (hash->size - 1); + +	for (backet = pp = hash->index[index]; backet; backet = backet->next) { +		if (backet->key == key +		    && (*hash->hash_cmp)(backet->data, data)) { +			if (backet == pp) +				hash->index[index] = backet->next; +			else +				pp->next = backet->next; + +			ret = backet->data; +			XFREE(MTYPE_HASH_BACKET, backet); +			hash->count--; +			return ret; +		} +		pp = backet;  	} -      pp = backet; -    } -  return NULL; +	return NULL;  }  /* Iterator function for hash.  */ -void -hash_iterate (struct hash *hash,  -	      void (*func) (struct hash_backet *, void *), void *arg) +void hash_iterate(struct hash *hash, void (*func)(struct hash_backet *, void *), +		  void *arg)  { -  unsigned int i; -  struct hash_backet *hb; -  struct hash_backet *hbnext; - -  for (i = 0; i < hash->size; i++) -    for (hb = hash->index[i]; hb; hb = hbnext) -      { -	/* get pointer to next hash backet here, in case (*func) -	 * decides to delete hb by calling hash_release -	 */ -	hbnext = hb->next; -	(*func) (hb, arg); -      } +	unsigned int i; +	struct hash_backet *hb; +	struct hash_backet *hbnext; + +	for (i = 0; i < hash->size; i++) +		for (hb = hash->index[i]; hb; hb = hbnext) { +			/* get pointer to next hash backet here, in case (*func) +			 * decides to delete hb by calling hash_release +			 */ +			hbnext = hb->next; +			(*func)(hb, arg); +		}  }  /* Iterator function for hash.  */ -void -hash_walk (struct hash *hash, -	   int (*func) (struct hash_backet *, void *), void *arg) +void hash_walk(struct hash *hash, int (*func)(struct hash_backet *, void *), +	       void *arg)  { -  unsigned int i; -  struct hash_backet *hb; -  struct hash_backet *hbnext; -  int ret = HASHWALK_CONTINUE; - -  for (i = 0; i < hash->size; i++) -    { -      for (hb = hash->index[i]; hb; hb = hbnext) -	{ -	  /* get pointer to next hash backet here, in case (*func) -	   * decides to delete hb by calling hash_release -	   */ -	  hbnext = hb->next; -	  ret = (*func) (hb, arg); -	  if (ret == HASHWALK_ABORT) -	    return; +	unsigned int i; +	struct hash_backet *hb; +	struct hash_backet *hbnext; +	int ret = HASHWALK_CONTINUE; + +	for (i = 0; i < hash->size; i++) { +		for (hb = hash->index[i]; hb; hb = hbnext) { +			/* get pointer to next hash backet here, in case (*func) +			 * decides to delete hb by calling hash_release +			 */ +			hbnext = hb->next; +			ret = (*func)(hb, arg); +			if (ret == HASHWALK_ABORT) +				return; +		}  	} -    }  }  /* Clean up hash.  */ -void -hash_clean (struct hash *hash, void (*free_func) (void *)) +void hash_clean(struct hash *hash, void (*free_func)(void *))  { -  unsigned int i; -  struct hash_backet *hb; -  struct hash_backet *next; - -  for (i = 0; i < hash->size; i++) -    { -      for (hb = hash->index[i]; hb; hb = next) -	{ -	  next = hb->next; -	       -	  if (free_func) -	    (*free_func) (hb->data); - -	  XFREE (MTYPE_HASH_BACKET, hb); -	  hash->count--; +	unsigned int i; +	struct hash_backet *hb; +	struct hash_backet *next; + +	for (i = 0; i < hash->size; i++) { +		for (hb = hash->index[i]; hb; hb = next) { +			next = hb->next; + +			if (free_func) +				(*free_func)(hb->data); + +			XFREE(MTYPE_HASH_BACKET, hb); +			hash->count--; +		} +		hash->index[i] = NULL;  	} -      hash->index[i] = NULL; -    }  }  /* Free hash memory.  You may call hash_clean before call this     function.  */ -void -hash_free (struct hash *hash) +void hash_free(struct hash *hash)  { -  XFREE (MTYPE_HASH_INDEX, hash->index); -  XFREE (MTYPE_HASH, hash); +	XFREE(MTYPE_HASH_INDEX, hash->index); +	XFREE(MTYPE_HASH, hash);  } diff --git a/lib/hash.h b/lib/hash.h index 11ecf75ec9..202d761a5c 100644 --- a/lib/hash.h +++ b/lib/hash.h @@ -26,65 +26,63 @@ Boston, MA 02111-1307, USA.  */  DECLARE_MTYPE(HASH)  DECLARE_MTYPE(HASH_BACKET) -/* Default hash table size.  */  +/* Default hash table size.  */  #define HASH_INITIAL_SIZE     256	/* initial number of backets. */  #define HASH_THRESHOLD	      10	/* expand when backet. */  #define HASHWALK_CONTINUE 0  #define HASHWALK_ABORT -1 -struct hash_backet -{ -  /* Linked list.  */ -  struct hash_backet *next; +struct hash_backet { +	/* Linked list.  */ +	struct hash_backet *next; -  /* Hash key. */ -  unsigned int key; +	/* Hash key. */ +	unsigned int key; -  /* Data.  */ -  void *data; +	/* Data.  */ +	void *data;  }; -struct hash -{ -  /* Hash backet. */ -  struct hash_backet **index; +struct hash { +	/* Hash backet. */ +	struct hash_backet **index; -  /* Hash table size. Must be power of 2 */ -  unsigned int size; +	/* Hash table size. Must be power of 2 */ +	unsigned int size; -  /* If expansion failed. */ -  int no_expand; +	/* If expansion failed. */ +	int no_expand; -  /* Key make function. */ -  unsigned int (*hash_key) (void *); +	/* Key make function. */ +	unsigned int (*hash_key)(void *); -  /* Data compare function. */ -  int (*hash_cmp) (const void *, const void *); +	/* Data compare function. */ +	int (*hash_cmp)(const void *, const void *); -  /* Backet alloc. */ -  unsigned long count; +	/* Backet alloc. */ +	unsigned long count;  }; -extern struct hash *hash_create (unsigned int (*) (void *),  -				 int (*) (const void *, const void *)); -extern struct hash *hash_create_size (unsigned int, unsigned int (*) (void *),  -				      int (*) (const void *, const void *)); +extern struct hash *hash_create(unsigned int (*)(void *), +				int (*)(const void *, const void *)); +extern struct hash *hash_create_size(unsigned int, unsigned int (*)(void *), +				     int (*)(const void *, const void *)); -extern void *hash_get (struct hash *, void *, void * (*) (void *)); -extern void *hash_alloc_intern (void *); -extern void *hash_lookup (struct hash *, void *); -extern void *hash_release (struct hash *, void *); +extern void *hash_get(struct hash *, void *, void *(*)(void *)); +extern void *hash_alloc_intern(void *); +extern void *hash_lookup(struct hash *, void *); +extern void *hash_release(struct hash *, void *); -extern void hash_iterate (struct hash *,  -		   void (*) (struct hash_backet *, void *), void *); +extern void hash_iterate(struct hash *, void (*)(struct hash_backet *, void *), +			 void *); -extern void hash_walk (struct hash *, -		   int (*) (struct hash_backet *, void *), void *); +extern void hash_walk(struct hash *, int (*)(struct hash_backet *, void *), +		      void *); -extern void hash_clean (struct hash *, void (*) (void *)); -extern void hash_free (struct hash *); +extern void hash_clean(struct hash *, void (*)(void *)); +extern void hash_free(struct hash *); -extern unsigned int string_hash_make (const char *); +extern unsigned int string_hash_make(const char *);  #endif /* _ZEBRA_HASH_H */ diff --git a/lib/hook.c b/lib/hook.c index 04d803cd8d..2c877cbf45 100644 --- a/lib/hook.c +++ b/lib/hook.c @@ -39,18 +39,15 @@ void _hook_register(struct hook *hook, void *funcptr, void *arg, bool has_arg,  	hook->entries = he;  } -void _hook_unregister(struct hook *hook, void *funcptr, -		      void *arg, bool has_arg) +void _hook_unregister(struct hook *hook, void *funcptr, void *arg, bool has_arg)  {  	struct hookent *he, **prev;  	for (prev = &hook->entries; (he = *prev) != NULL; prev = &he->next)  		if (he->hookfn == funcptr && he->hookarg == arg -				&& he->has_arg == has_arg) -		{ +		    && he->has_arg == has_arg) {  			*prev = he->next;  			XFREE(MTYPE_HOOK_ENTRY, he);  			break;  		}  } - diff --git a/lib/hook.h b/lib/hook.h index 0cb7ab5c7d..4a5cee2fd3 100644 --- a/lib/hook.h +++ b/lib/hook.h @@ -91,7 +91,7 @@  struct hookent {  	struct hookent *next; -	void *hookfn;		/* actually a function pointer */ +	void *hookfn; /* actually a function pointer */  	void *hookarg;  	bool has_arg;  	struct frrmod_runtime *module; @@ -111,29 +111,27 @@ struct hook {  extern void _hook_register(struct hook *hook, void *funcptr, void *arg,  			   bool has_arg, struct frrmod_runtime *module,  			   const char *funcname); -#define hook_register(hookname, func) \ -	_hook_register(&_hook_ ## hookname, \ -			_hook_typecheck_ ## hookname (func), \ -			NULL, false, THIS_MODULE, #func) -#define hook_register_arg(hookname, func, arg) \ -	_hook_register(&_hook_ ## hookname, \ -			_hook_typecheck_arg_ ## hookname (func), \ -			arg, true, THIS_MODULE, #func) +#define hook_register(hookname, func)                                          \ +	_hook_register(&_hook_##hookname, _hook_typecheck_##hookname(func),    \ +		       NULL, false, THIS_MODULE, #func) +#define hook_register_arg(hookname, func, arg)                                 \ +	_hook_register(&_hook_##hookname,                                      \ +		       _hook_typecheck_arg_##hookname(func), arg, true,        \ +		       THIS_MODULE, #func)  extern void _hook_unregister(struct hook *hook, void *funcptr, void *arg,  			     bool has_arg); -#define hook_unregister(hookname, func) \ -	_hook_unregister(&_hook_ ## hookname, \ -			_hook_typecheck_ ## hookname (func), NULL, false) -#define hook_unregister_arg(hookname, func, arg) \ -	_hook_unregister(&_hook_ ## hookname, \ -			_hook_typecheck_arg_ ## hookname (func), arg, true) +#define hook_unregister(hookname, func)                                        \ +	_hook_unregister(&_hook_##hookname, _hook_typecheck_##hookname(func),  \ +			 NULL, false) +#define hook_unregister_arg(hookname, func, arg)                               \ +	_hook_unregister(&_hook_##hookname,                                    \ +			 _hook_typecheck_arg_##hookname(func), arg, true)  /* invoke hooks   * this is private (static) to the file that has the DEFINE_HOOK statement   */ -#define hook_call(hookname, ...) \ -	hook_call_ ## hookname (__VA_ARGS__) +#define hook_call(hookname, ...) hook_call_##hookname(__VA_ARGS__)  /* helpers to add the void * arg */  #define HOOK_ADDDEF(...) (void *hookarg , ## __VA_ARGS__) @@ -146,42 +144,44 @@ extern void _hook_unregister(struct hook *hook, void *funcptr, void *arg,   * theoretically passlist is not neccessary, but let's keep things simple and   * use exact same args on DECLARE and DEFINE.   */ -#define DECLARE_HOOK(hookname, arglist, passlist) \ -	extern struct hook _hook_ ## hookname; \ -	__attribute__((unused)) \ -	static void *_hook_typecheck_ ## hookname ( \ -			int (*funcptr) arglist) { \ -		return (void *)funcptr; } \ -	__attribute__((unused)) \ -	static void *_hook_typecheck_arg_ ## hookname ( \ -			int (*funcptr) HOOK_ADDDEF arglist) { \ -		return (void *)funcptr; } +#define DECLARE_HOOK(hookname, arglist, passlist)                              \ +	extern struct hook _hook_##hookname;                                   \ +	__attribute__((unused)) static void *_hook_typecheck_##hookname(       \ +		int(*funcptr) arglist)                                         \ +	{                                                                      \ +		return (void *)funcptr;                                        \ +	}                                                                      \ +	__attribute__((unused)) static void *_hook_typecheck_arg_##hookname(   \ +		int(*funcptr) HOOK_ADDDEF arglist)                             \ +	{                                                                      \ +		return (void *)funcptr;                                        \ +	}  /* use in source file - contains hook-related definitions.   */ -#define DEFINE_HOOK(hookname, arglist, passlist) \ -	struct hook _hook_ ## hookname = { \ -		.name = #hookname, \ -		.entries = NULL, \ -	}; \ -	static int hook_call_ ## hookname arglist { \ -		int hooksum = 0; \ -		struct hookent *he = _hook_ ## hookname .entries; \ -		void *hookarg; \ -		union { \ -			void *voidptr; \ -			int (*fptr) arglist; \ -			int (*farg) HOOK_ADDDEF arglist; \ -		} hookp; \ -		for (; he; he = he->next) { \ -			hookarg = he->hookarg; \ -			hookp.voidptr = he->hookfn; \ -			if (!he->has_arg) \ -				hooksum += hookp.fptr passlist; \ -			else \ -				hooksum += hookp.farg HOOK_ADDARG passlist; \ -		} \ -		return hooksum; \ +#define DEFINE_HOOK(hookname, arglist, passlist)                               \ +	struct hook _hook_##hookname = {                                       \ +		.name = #hookname, .entries = NULL,                            \ +	};                                                                     \ +	static int hook_call_##hookname arglist                                \ +	{                                                                      \ +		int hooksum = 0;                                               \ +		struct hookent *he = _hook_##hookname.entries;                 \ +		void *hookarg;                                                 \ +		union {                                                        \ +			void *voidptr;                                         \ +			int(*fptr) arglist;                                    \ +			int(*farg) HOOK_ADDDEF arglist;                        \ +		} hookp;                                                       \ +		for (; he; he = he->next) {                                    \ +			hookarg = he->hookarg;                                 \ +			hookp.voidptr = he->hookfn;                            \ +			if (!he->has_arg)                                      \ +				hooksum += hookp.fptr passlist;                \ +			else                                                   \ +				hooksum += hookp.farg HOOK_ADDARG passlist;    \ +		}                                                              \ +		return hooksum;                                                \  	}  #endif /* _FRR_HOOK_H */ @@ -1,10 +1,10 @@ -/*  +/*   * Interface functions.   * Copyright (C) 1997, 98 Kunihiro Ishiguro   *   * This file is part of GNU Zebra. - *  + *   * GNU Zebra is free software; you can redistribute it and/or modify   * it under the terms of the GNU General Public License as published   * by the Free Software Foundation; either version 2, or (at your @@ -36,11 +36,11 @@  #include "buffer.h"  #include "log.h" -DEFINE_MTYPE(       LIB, IF,              "Interface") -DEFINE_MTYPE_STATIC(LIB, CONNECTED,       "Connected") -DEFINE_MTYPE_STATIC(LIB, NBR_CONNECTED,   "Neighbor Connected") -DEFINE_MTYPE(       LIB, CONNECTED_LABEL, "Connected interface label") -DEFINE_MTYPE_STATIC(LIB, IF_LINK_PARAMS,  "Informational Link Parameters") +DEFINE_MTYPE(LIB, IF, "Interface") +DEFINE_MTYPE_STATIC(LIB, CONNECTED, "Connected") +DEFINE_MTYPE_STATIC(LIB, NBR_CONNECTED, "Neighbor Connected") +DEFINE_MTYPE(LIB, CONNECTED_LABEL, "Connected interface label") +DEFINE_MTYPE_STATIC(LIB, IF_LINK_PARAMS, "Informational Link Parameters")  DEFINE_QOBJ_TYPE(interface) @@ -48,11 +48,12 @@ DEFINE_QOBJ_TYPE(interface)  int ptm_enable = 0;  /* One for each program.  This structure is needed to store hooks. */ -struct if_master -{ -  int (*if_new_hook) (struct interface *); -  int (*if_delete_hook) (struct interface *); -} if_master = {0,}; +struct if_master { +	int (*if_new_hook)(struct interface *); +	int (*if_delete_hook)(struct interface *); +} if_master = { +	0, +};  /* Compare interface names, returning an integer greater than, equal to, or   * less than 0, (following the strcmp convention), according to the @@ -61,548 +62,521 @@ struct if_master   * lexicographic by name, and then numeric by number.  No number sorts   * before all numbers.  Examples: de0 < de1, de100 < fxp0 < xl0, devpty <   * devpty0, de0 < del0 - */          -int -if_cmp_name_func (char *p1, char *p2) + */ +int if_cmp_name_func(char *p1, char *p2)  { -  unsigned int l1, l2; -  long int x1, x2; -  int res; - -  while (*p1 && *p2) { -    /* look up to any number */ -    l1 = strcspn(p1, "0123456789"); -    l2 = strcspn(p2, "0123456789"); - -    /* name lengths are different -> compare names */ -    if (l1 != l2) -      return (strcmp(p1, p2)); - -    /* Note that this relies on all numbers being less than all letters, so -     * that de0 < del0. -     */ -    res = strncmp(p1, p2, l1); - -    /* names are different -> compare them */ -    if (res) -      return res; - -    /* with identical name part, go to numeric part */ -    p1 += l1; -    p2 += l1; - -    if (!*p1)  -      return -1; -    if (!*p2)  -      return 1; - -    x1 = strtol(p1, &p1, 10); -    x2 = strtol(p2, &p2, 10); - -    /* let's compare numbers now */ -    if (x1 < x2) -      return -1; -    if (x1 > x2) -      return 1; - -    /* numbers were equal, lets do it again.. -    (it happens with name like "eth123.456:789") */ -  } -  if (*p1) -    return 1; -  if (*p2) -    return -1; -  return 0; +	unsigned int l1, l2; +	long int x1, x2; +	int res; + +	while (*p1 && *p2) { +		/* look up to any number */ +		l1 = strcspn(p1, "0123456789"); +		l2 = strcspn(p2, "0123456789"); + +		/* name lengths are different -> compare names */ +		if (l1 != l2) +			return (strcmp(p1, p2)); + +		/* Note that this relies on all numbers being less than all +		 * letters, so +		 * that de0 < del0. +		 */ +		res = strncmp(p1, p2, l1); + +		/* names are different -> compare them */ +		if (res) +			return res; + +		/* with identical name part, go to numeric part */ +		p1 += l1; +		p2 += l1; + +		if (!*p1) +			return -1; +		if (!*p2) +			return 1; + +		x1 = strtol(p1, &p1, 10); +		x2 = strtol(p2, &p2, 10); + +		/* let's compare numbers now */ +		if (x1 < x2) +			return -1; +		if (x1 > x2) +			return 1; + +		/* numbers were equal, lets do it again.. +		(it happens with name like "eth123.456:789") */ +	} +	if (*p1) +		return 1; +	if (*p2) +		return -1; +	return 0;  } -static int -if_cmp_func (struct interface *ifp1, struct interface *ifp2) +static int if_cmp_func(struct interface *ifp1, struct interface *ifp2)  { -  return if_cmp_name_func (ifp1->name, ifp2->name); +	return if_cmp_name_func(ifp1->name, ifp2->name);  }  /* Create new interface structure. */ -struct interface * -if_create (const char *name, int namelen, vrf_id_t vrf_id) +struct interface *if_create(const char *name, int namelen, vrf_id_t vrf_id)  { -  struct interface *ifp; -  struct list *intf_list = vrf_iflist_get (vrf_id); - -  ifp = XCALLOC (MTYPE_IF, sizeof (struct interface)); -  ifp->ifindex = IFINDEX_INTERNAL; -   -  assert (name); -  assert (namelen <= INTERFACE_NAMSIZ);	/* Need space for '\0' at end. */ -  strncpy (ifp->name, name, namelen); -  ifp->name[namelen] = '\0'; -  ifp->vrf_id = vrf_id; -  if (if_lookup_by_name (ifp->name, vrf_id) == NULL) -    listnode_add_sort (intf_list, ifp); -  else -    zlog_err("if_create(%s): corruption detected -- interface with this " -             "name exists already in VRF %u!", ifp->name, vrf_id); -  ifp->connected = list_new (); -  ifp->connected->del = (void (*) (void *)) connected_free; +	struct interface *ifp; +	struct list *intf_list = vrf_iflist_get(vrf_id); + +	ifp = XCALLOC(MTYPE_IF, sizeof(struct interface)); +	ifp->ifindex = IFINDEX_INTERNAL; + +	assert(name); +	assert(namelen <= INTERFACE_NAMSIZ); /* Need space for '\0' at end. */ +	strncpy(ifp->name, name, namelen); +	ifp->name[namelen] = '\0'; +	ifp->vrf_id = vrf_id; +	if (if_lookup_by_name(ifp->name, vrf_id) == NULL) +		listnode_add_sort(intf_list, ifp); +	else +		zlog_err( +			"if_create(%s): corruption detected -- interface with this " +			"name exists already in VRF %u!", +			ifp->name, vrf_id); +	ifp->connected = list_new(); +	ifp->connected->del = (void (*)(void *))connected_free; + +	ifp->nbr_connected = list_new(); +	ifp->nbr_connected->del = (void (*)(void *))nbr_connected_free; + +	/* Enable Link-detection by default */ +	SET_FLAG(ifp->status, ZEBRA_INTERFACE_LINKDETECTION); + +	QOBJ_REG(ifp, interface); + +	if (if_master.if_new_hook) +		(*if_master.if_new_hook)(ifp); -  ifp->nbr_connected = list_new (); -  ifp->nbr_connected->del = (void (*) (void *)) nbr_connected_free; - -  /* Enable Link-detection by default */ -  SET_FLAG(ifp->status, ZEBRA_INTERFACE_LINKDETECTION); - -  QOBJ_REG (ifp, interface); - -  if (if_master.if_new_hook) -    (*if_master.if_new_hook) (ifp); - -  return ifp; +	return ifp;  }  /* Create new interface structure. */ -void -if_update (struct interface *ifp, const char *name, int namelen, vrf_id_t vrf_id) +void if_update(struct interface *ifp, const char *name, int namelen, +	       vrf_id_t vrf_id)  { -  struct list *intf_list = vrf_iflist_get (vrf_id); - -  /* remove interface from old master vrf list */ -  if (vrf_iflist (ifp->vrf_id)) -    listnode_delete (vrf_iflist (ifp->vrf_id), ifp); - -  assert (name); -  assert (namelen <= INTERFACE_NAMSIZ);	/* Need space for '\0' at end. */ -  strncpy (ifp->name, name, namelen); -  ifp->name[namelen] = '\0'; -  ifp->vrf_id = vrf_id; -  if (if_lookup_by_name (ifp->name, vrf_id) == NULL) -    listnode_add_sort (intf_list, ifp); -  else -    zlog_err("if_create(%s): corruption detected -- interface with this " -             "name exists already in VRF %u!", ifp->name, vrf_id); - -  return; +	struct list *intf_list = vrf_iflist_get(vrf_id); + +	/* remove interface from old master vrf list */ +	if (vrf_iflist(ifp->vrf_id)) +		listnode_delete(vrf_iflist(ifp->vrf_id), ifp); + +	assert(name); +	assert(namelen <= INTERFACE_NAMSIZ); /* Need space for '\0' at end. */ +	strncpy(ifp->name, name, namelen); +	ifp->name[namelen] = '\0'; +	ifp->vrf_id = vrf_id; +	if (if_lookup_by_name(ifp->name, vrf_id) == NULL) +		listnode_add_sort(intf_list, ifp); +	else +		zlog_err( +			"if_create(%s): corruption detected -- interface with this " +			"name exists already in VRF %u!", +			ifp->name, vrf_id); + +	return;  }  /* Delete interface structure. */ -void -if_delete_retain (struct interface *ifp) +void if_delete_retain(struct interface *ifp)  { -  if (if_master.if_delete_hook) -    (*if_master.if_delete_hook) (ifp); +	if (if_master.if_delete_hook) +		(*if_master.if_delete_hook)(ifp); -  QOBJ_UNREG (ifp); +	QOBJ_UNREG(ifp); -  /* Free connected address list */ -  list_delete_all_node (ifp->connected); +	/* Free connected address list */ +	list_delete_all_node(ifp->connected); -  /* Free connected nbr address list */ -  list_delete_all_node (ifp->nbr_connected); +	/* Free connected nbr address list */ +	list_delete_all_node(ifp->nbr_connected);  }  /* Delete and free interface structure. */ -void -if_delete (struct interface *ifp) +void if_delete(struct interface *ifp)  { -  listnode_delete (vrf_iflist (ifp->vrf_id), ifp); +	listnode_delete(vrf_iflist(ifp->vrf_id), ifp); -  if_delete_retain(ifp); +	if_delete_retain(ifp); -  list_free (ifp->connected); -  list_free (ifp->nbr_connected); +	list_free(ifp->connected); +	list_free(ifp->nbr_connected); -  if_link_params_free (ifp); +	if_link_params_free(ifp); -  XFREE (MTYPE_IF, ifp); +	XFREE(MTYPE_IF, ifp);  }  /* Add hook to interface master. */ -void -if_add_hook (int type, int (*func)(struct interface *ifp)) +void if_add_hook(int type, int (*func)(struct interface *ifp))  { -  switch (type) { -  case IF_NEW_HOOK: -    if_master.if_new_hook = func; -    break; -  case IF_DELETE_HOOK: -    if_master.if_delete_hook = func; -    break; -  default: -    break; -  } +	switch (type) { +	case IF_NEW_HOOK: +		if_master.if_new_hook = func; +		break; +	case IF_DELETE_HOOK: +		if_master.if_delete_hook = func; +		break; +	default: +		break; +	}  }  /* Interface existance check by index. */ -struct interface * -if_lookup_by_index (ifindex_t ifindex, vrf_id_t vrf_id) +struct interface *if_lookup_by_index(ifindex_t ifindex, vrf_id_t vrf_id)  { -  struct listnode *node; -  struct interface *ifp; +	struct listnode *node; +	struct interface *ifp; -  for (ALL_LIST_ELEMENTS_RO (vrf_iflist (vrf_id), node, ifp)) -    { -      if (ifp->ifindex == ifindex) -	return ifp; -    } -  return NULL; +	for (ALL_LIST_ELEMENTS_RO(vrf_iflist(vrf_id), node, ifp)) { +		if (ifp->ifindex == ifindex) +			return ifp; +	} +	return NULL;  } -const char * -ifindex2ifname (ifindex_t ifindex, vrf_id_t vrf_id) +const char *ifindex2ifname(ifindex_t ifindex, vrf_id_t vrf_id)  { -  struct interface *ifp; +	struct interface *ifp; -  return ((ifp = if_lookup_by_index (ifindex, vrf_id)) != NULL) ? -  	 ifp->name : "unknown"; +	return ((ifp = if_lookup_by_index(ifindex, vrf_id)) != NULL) +		       ? ifp->name +		       : "unknown";  } -ifindex_t -ifname2ifindex (const char *name, vrf_id_t vrf_id) +ifindex_t ifname2ifindex(const char *name, vrf_id_t vrf_id)  { -  struct interface *ifp; +	struct interface *ifp; -  return ((ifp = if_lookup_by_name (name, vrf_id)) != NULL) ? ifp->ifindex -                                                   : IFINDEX_INTERNAL; +	return ((ifp = if_lookup_by_name(name, vrf_id)) != NULL) +		       ? ifp->ifindex +		       : IFINDEX_INTERNAL;  }  /* Interface existance check by interface name. */ -struct interface * -if_lookup_by_name (const char *name, vrf_id_t vrf_id) +struct interface *if_lookup_by_name(const char *name, vrf_id_t vrf_id)  { -  struct listnode *node; -  struct interface *ifp; -   -  if (name) -    for (ALL_LIST_ELEMENTS_RO (vrf_iflist (vrf_id), node, ifp)) -      { -        if (strcmp(name, ifp->name) == 0) -          return ifp; -      } -  return NULL; +	struct listnode *node; +	struct interface *ifp; + +	if (name) +		for (ALL_LIST_ELEMENTS_RO(vrf_iflist(vrf_id), node, ifp)) { +			if (strcmp(name, ifp->name) == 0) +				return ifp; +		} +	return NULL;  } -struct interface * -if_lookup_by_name_all_vrf (const char *name) +struct interface *if_lookup_by_name_all_vrf(const char *name)  { -  struct vrf *vrf; -  struct interface *ifp; +	struct vrf *vrf; +	struct interface *ifp; -  RB_FOREACH (vrf, vrf_id_head, &vrfs_by_id) -    { -      ifp = if_lookup_by_name (name, vrf->vrf_id); -      if (ifp) -	return ifp; -    } +	RB_FOREACH(vrf, vrf_id_head, &vrfs_by_id) +	{ +		ifp = if_lookup_by_name(name, vrf->vrf_id); +		if (ifp) +			return ifp; +	} -  return NULL; +	return NULL;  } -struct interface * -if_lookup_by_name_len (const char *name, size_t namelen, vrf_id_t vrf_id) +struct interface *if_lookup_by_name_len(const char *name, size_t namelen, +					vrf_id_t vrf_id)  { -  struct listnode *node; -  struct interface *ifp; +	struct listnode *node; +	struct interface *ifp; -  if (namelen > INTERFACE_NAMSIZ) -    return NULL; +	if (namelen > INTERFACE_NAMSIZ) +		return NULL; -  for (ALL_LIST_ELEMENTS_RO (vrf_iflist (vrf_id), node, ifp)) -    { -      if (!memcmp(name, ifp->name, namelen) && (ifp->name[namelen] == '\0')) -	return ifp; -    } -  return NULL; +	for (ALL_LIST_ELEMENTS_RO(vrf_iflist(vrf_id), node, ifp)) { +		if (!memcmp(name, ifp->name, namelen) +		    && (ifp->name[namelen] == '\0')) +			return ifp; +	} +	return NULL;  }  /* Lookup interface by IPv4 address. */ -struct interface * -if_lookup_exact_address (void *src, int family, vrf_id_t vrf_id) +struct interface *if_lookup_exact_address(void *src, int family, +					  vrf_id_t vrf_id)  { -  struct listnode *node; -  struct listnode *cnode; -  struct interface *ifp; -  struct prefix *p; -  struct connected *c; - -  for (ALL_LIST_ELEMENTS_RO (vrf_iflist (vrf_id), node, ifp)) -    { -      for (ALL_LIST_ELEMENTS_RO (ifp->connected, cnode, c)) -	{ -	  p = c->address; - -	  if (p && (p->family == family)) -	    { -	      if (family == AF_INET) -		{ -		  if (IPV4_ADDR_SAME (&p->u.prefix4, (struct in_addr *)src)) -		    return ifp; +	struct listnode *node; +	struct listnode *cnode; +	struct interface *ifp; +	struct prefix *p; +	struct connected *c; + +	for (ALL_LIST_ELEMENTS_RO(vrf_iflist(vrf_id), node, ifp)) { +		for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, c)) { +			p = c->address; + +			if (p && (p->family == family)) { +				if (family == AF_INET) { +					if (IPV4_ADDR_SAME( +						    &p->u.prefix4, +						    (struct in_addr *)src)) +						return ifp; +				} else if (family == AF_INET6) { +					if (IPV6_ADDR_SAME( +						    &p->u.prefix6, +						    (struct in6_addr *)src)) +						return ifp; +				} +			}  		} -	      else if (family == AF_INET6) -		{ -		  if (IPV6_ADDR_SAME (&p->u.prefix6, (struct in6_addr *)src)) -		    return ifp; -		} -	    }  	} -    } -  return NULL; +	return NULL;  }  /* Lookup interface by IPv4 address. */ -struct connected * -if_lookup_address (void *matchaddr, int family, vrf_id_t vrf_id) +struct connected *if_lookup_address(void *matchaddr, int family, +				    vrf_id_t vrf_id)  { -  struct listnode *node; -  struct prefix addr; -  int bestlen = 0; -  struct listnode *cnode; -  struct interface *ifp; -  struct connected *c; -  struct connected *match; - -  if (family == AF_INET) -    { -      addr.family = AF_INET; -      addr.u.prefix4 = *((struct in_addr *)matchaddr); -      addr.prefixlen = IPV4_MAX_BITLEN; -    } -  else if (family == AF_INET6) -    { -      addr.family = AF_INET6; -      addr.u.prefix6 = *((struct in6_addr *)matchaddr); -      addr.prefixlen = IPV6_MAX_BITLEN; -    } +	struct listnode *node; +	struct prefix addr; +	int bestlen = 0; +	struct listnode *cnode; +	struct interface *ifp; +	struct connected *c; +	struct connected *match; + +	if (family == AF_INET) { +		addr.family = AF_INET; +		addr.u.prefix4 = *((struct in_addr *)matchaddr); +		addr.prefixlen = IPV4_MAX_BITLEN; +	} else if (family == AF_INET6) { +		addr.family = AF_INET6; +		addr.u.prefix6 = *((struct in6_addr *)matchaddr); +		addr.prefixlen = IPV6_MAX_BITLEN; +	} -  match = NULL; +	match = NULL; -  for (ALL_LIST_ELEMENTS_RO (vrf_iflist (vrf_id), node, ifp)) -    { -      for (ALL_LIST_ELEMENTS_RO (ifp->connected, cnode, c)) -	{ -	  if (c->address && (c->address->family == AF_INET) && -	      prefix_match(CONNECTED_PREFIX(c), &addr) && -	      (c->address->prefixlen > bestlen)) -	    { -	      bestlen = c->address->prefixlen; -	      match = c; -	    } +	for (ALL_LIST_ELEMENTS_RO(vrf_iflist(vrf_id), node, ifp)) { +		for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, c)) { +			if (c->address && (c->address->family == AF_INET) +			    && prefix_match(CONNECTED_PREFIX(c), &addr) +			    && (c->address->prefixlen > bestlen)) { +				bestlen = c->address->prefixlen; +				match = c; +			} +		}  	} -    } -  return match; +	return match;  }  /* Lookup interface by prefix */ -struct interface * -if_lookup_prefix (struct prefix *prefix, vrf_id_t vrf_id) +struct interface *if_lookup_prefix(struct prefix *prefix, vrf_id_t vrf_id)  { -  struct listnode *node; -  struct listnode *cnode; -  struct interface *ifp; -  struct connected *c; - -  for (ALL_LIST_ELEMENTS_RO (vrf_iflist (vrf_id), node, ifp)) -    { -      for (ALL_LIST_ELEMENTS_RO (ifp->connected, cnode, c)) -        { -          if (prefix_cmp(c->address, prefix) == 0) -            { -              return ifp; -            } -        } -    } -  return NULL; +	struct listnode *node; +	struct listnode *cnode; +	struct interface *ifp; +	struct connected *c; + +	for (ALL_LIST_ELEMENTS_RO(vrf_iflist(vrf_id), node, ifp)) { +		for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, c)) { +			if (prefix_cmp(c->address, prefix) == 0) { +				return ifp; +			} +		} +	} +	return NULL;  }  /* Get interface by name if given name interface doesn't exist create     one. */ -struct interface * -if_get_by_name (const char *name, vrf_id_t vrf_id) +struct interface *if_get_by_name(const char *name, vrf_id_t vrf_id)  { -  struct interface *ifp; +	struct interface *ifp; -  return ((ifp = if_lookup_by_name (name, vrf_id)) != NULL) ? ifp : -         if_create (name, strlen(name), vrf_id); +	return ((ifp = if_lookup_by_name(name, vrf_id)) != NULL) +		       ? ifp +		       : if_create(name, strlen(name), vrf_id);  } -struct interface * -if_get_by_name_len (const char *name, size_t namelen, vrf_id_t vrf_id, int vty) +struct interface *if_get_by_name_len(const char *name, size_t namelen, +				     vrf_id_t vrf_id, int vty)  { -  struct interface *ifp; -  struct vrf *vrf; -  struct listnode *node; +	struct interface *ifp; +	struct vrf *vrf; +	struct listnode *node; -  ifp = if_lookup_by_name_len (name, namelen, vrf_id); -  if (ifp) -    return ifp; +	ifp = if_lookup_by_name_len(name, namelen, vrf_id); +	if (ifp) +		return ifp; -  /* Didn't find the interface on that vrf. Defined on a different one? */  -  RB_FOREACH (vrf, vrf_id_head, &vrfs_by_id) -    { -      for (ALL_LIST_ELEMENTS_RO (vrf_iflist (vrf->vrf_id), node, ifp)) +	/* Didn't find the interface on that vrf. Defined on a different one? */ +	RB_FOREACH(vrf, vrf_id_head, &vrfs_by_id)  	{ -	  if (!memcmp(name, ifp->name, namelen) && (ifp->name[namelen] == '\0')) -	    { -	      /* Found a match.  If the interface command was entered in vty without a  -	       * VRF (passed as VRF_DEFAULT), accept the ifp we found.   If a vrf was -	       * entered and there is a mismatch, reject it if from vty. If it came  -	       * from the kernel by way of zclient,  believe it and update -	       * the ifp accordingly. -	       */ -              if (vty) -                { -                  if (vrf_id == VRF_DEFAULT) -                    return ifp; -                  return NULL; -                } -	      else -		{ -		  if_update (ifp, name, namelen, vrf_id); -		  return ifp; +		for (ALL_LIST_ELEMENTS_RO(vrf_iflist(vrf->vrf_id), node, ifp)) { +			if (!memcmp(name, ifp->name, namelen) +			    && (ifp->name[namelen] == '\0')) { +				/* Found a match.  If the interface command was +				 * entered in vty without a +				 * VRF (passed as VRF_DEFAULT), accept the ifp +				 * we found.   If a vrf was +				 * entered and there is a mismatch, reject it if +				 * from vty. If it came +				 * from the kernel by way of zclient,  believe +				 * it and update +				 * the ifp accordingly. +				 */ +				if (vty) { +					if (vrf_id == VRF_DEFAULT) +						return ifp; +					return NULL; +				} else { +					if_update(ifp, name, namelen, vrf_id); +					return ifp; +				} +			}  		} -	    }  	} -    } -  return (if_create (name, namelen, vrf_id)); +	return (if_create(name, namelen, vrf_id));  }  /* Does interface up ? */ -int -if_is_up (struct interface *ifp) +int if_is_up(struct interface *ifp)  { -  return ifp->flags & IFF_UP; +	return ifp->flags & IFF_UP;  }  /* Is interface running? */ -int -if_is_running (struct interface *ifp) +int if_is_running(struct interface *ifp)  { -  return ifp->flags & IFF_RUNNING; +	return ifp->flags & IFF_RUNNING;  }  /* Is the interface operative, eg. either UP & RUNNING     or UP & !ZEBRA_INTERFACE_LINK_DETECTION and     if ptm checking is enabled, then ptm check has passed */ -int -if_is_operative (struct interface *ifp) +int if_is_operative(struct interface *ifp)  { -  return ((ifp->flags & IFF_UP) && -	  (((ifp->flags & IFF_RUNNING) && -	    (ifp->ptm_status || !ifp->ptm_enable)) || -	   !CHECK_FLAG(ifp->status, ZEBRA_INTERFACE_LINKDETECTION))); +	return ((ifp->flags & IFF_UP) +		&& (((ifp->flags & IFF_RUNNING) +		     && (ifp->ptm_status || !ifp->ptm_enable)) +		    || !CHECK_FLAG(ifp->status, +				   ZEBRA_INTERFACE_LINKDETECTION)));  }  /* Is the interface operative, eg. either UP & RUNNING     or UP & !ZEBRA_INTERFACE_LINK_DETECTION, without PTM check */ -int -if_is_no_ptm_operative (struct interface *ifp) +int if_is_no_ptm_operative(struct interface *ifp)  { -  return ((ifp->flags & IFF_UP) && -	  ((ifp->flags & IFF_RUNNING) || -	   !CHECK_FLAG(ifp->status, ZEBRA_INTERFACE_LINKDETECTION))); +	return ((ifp->flags & IFF_UP) +		&& ((ifp->flags & IFF_RUNNING) +		    || !CHECK_FLAG(ifp->status, +				   ZEBRA_INTERFACE_LINKDETECTION)));  }  /* Is this loopback interface ? */ -int -if_is_loopback (struct interface *ifp) +int if_is_loopback(struct interface *ifp)  { -  /* XXX: Do this better, eg what if IFF_WHATEVER means X on platform M -   * but Y on platform N? -   */ -  return (ifp->flags & (IFF_LOOPBACK|IFF_NOXMIT|IFF_VIRTUAL)); +	/* XXX: Do this better, eg what if IFF_WHATEVER means X on platform M +	 * but Y on platform N? +	 */ +	return (ifp->flags & (IFF_LOOPBACK | IFF_NOXMIT | IFF_VIRTUAL));  }  /* Does this interface support broadcast ? */ -int -if_is_broadcast (struct interface *ifp) +int if_is_broadcast(struct interface *ifp)  { -  return ifp->flags & IFF_BROADCAST; +	return ifp->flags & IFF_BROADCAST;  }  /* Does this interface support broadcast ? */ -int -if_is_pointopoint (struct interface *ifp) +int if_is_pointopoint(struct interface *ifp)  { -  return ifp->flags & IFF_POINTOPOINT; +	return ifp->flags & IFF_POINTOPOINT;  }  /* Does this interface support multicast ? */ -int -if_is_multicast (struct interface *ifp) +int if_is_multicast(struct interface *ifp)  { -  return ifp->flags & IFF_MULTICAST; +	return ifp->flags & IFF_MULTICAST;  }  /* Printout flag information into log */ -const char * -if_flag_dump (unsigned long flag) +const char *if_flag_dump(unsigned long flag)  { -  int separator = 0; -  static char logbuf[BUFSIZ]; - -#define IFF_OUT_LOG(X,STR) \ -  if (flag & (X)) \ -    { \ -      if (separator) \ -	strlcat (logbuf, ",", BUFSIZ); \ -      else \ -	separator = 1; \ -      strlcat (logbuf, STR, BUFSIZ); \ -    } +	int separator = 0; +	static char logbuf[BUFSIZ]; + +#define IFF_OUT_LOG(X, STR)                                                    \ +	if (flag & (X)) {                                                      \ +		if (separator)                                                 \ +			strlcat(logbuf, ",", BUFSIZ);                          \ +		else                                                           \ +			separator = 1;                                         \ +		strlcat(logbuf, STR, BUFSIZ);                                  \ +	} -  strlcpy (logbuf, "<", BUFSIZ); -  IFF_OUT_LOG (IFF_UP, "UP"); -  IFF_OUT_LOG (IFF_BROADCAST, "BROADCAST"); -  IFF_OUT_LOG (IFF_DEBUG, "DEBUG"); -  IFF_OUT_LOG (IFF_LOOPBACK, "LOOPBACK"); -  IFF_OUT_LOG (IFF_POINTOPOINT, "POINTOPOINT"); -  IFF_OUT_LOG (IFF_NOTRAILERS, "NOTRAILERS"); -  IFF_OUT_LOG (IFF_RUNNING, "RUNNING"); -  IFF_OUT_LOG (IFF_NOARP, "NOARP"); -  IFF_OUT_LOG (IFF_PROMISC, "PROMISC"); -  IFF_OUT_LOG (IFF_ALLMULTI, "ALLMULTI"); -  IFF_OUT_LOG (IFF_OACTIVE, "OACTIVE"); -  IFF_OUT_LOG (IFF_SIMPLEX, "SIMPLEX"); -  IFF_OUT_LOG (IFF_LINK0, "LINK0"); -  IFF_OUT_LOG (IFF_LINK1, "LINK1"); -  IFF_OUT_LOG (IFF_LINK2, "LINK2"); -  IFF_OUT_LOG (IFF_MULTICAST, "MULTICAST"); -  IFF_OUT_LOG (IFF_NOXMIT, "NOXMIT"); -  IFF_OUT_LOG (IFF_NORTEXCH, "NORTEXCH"); -  IFF_OUT_LOG (IFF_VIRTUAL, "VIRTUAL"); -  IFF_OUT_LOG (IFF_IPV4, "IPv4"); -  IFF_OUT_LOG (IFF_IPV6, "IPv6"); - -  strlcat (logbuf, ">", BUFSIZ); - -  return logbuf; +	strlcpy(logbuf, "<", BUFSIZ); +	IFF_OUT_LOG(IFF_UP, "UP"); +	IFF_OUT_LOG(IFF_BROADCAST, "BROADCAST"); +	IFF_OUT_LOG(IFF_DEBUG, "DEBUG"); +	IFF_OUT_LOG(IFF_LOOPBACK, "LOOPBACK"); +	IFF_OUT_LOG(IFF_POINTOPOINT, "POINTOPOINT"); +	IFF_OUT_LOG(IFF_NOTRAILERS, "NOTRAILERS"); +	IFF_OUT_LOG(IFF_RUNNING, "RUNNING"); +	IFF_OUT_LOG(IFF_NOARP, "NOARP"); +	IFF_OUT_LOG(IFF_PROMISC, "PROMISC"); +	IFF_OUT_LOG(IFF_ALLMULTI, "ALLMULTI"); +	IFF_OUT_LOG(IFF_OACTIVE, "OACTIVE"); +	IFF_OUT_LOG(IFF_SIMPLEX, "SIMPLEX"); +	IFF_OUT_LOG(IFF_LINK0, "LINK0"); +	IFF_OUT_LOG(IFF_LINK1, "LINK1"); +	IFF_OUT_LOG(IFF_LINK2, "LINK2"); +	IFF_OUT_LOG(IFF_MULTICAST, "MULTICAST"); +	IFF_OUT_LOG(IFF_NOXMIT, "NOXMIT"); +	IFF_OUT_LOG(IFF_NORTEXCH, "NORTEXCH"); +	IFF_OUT_LOG(IFF_VIRTUAL, "VIRTUAL"); +	IFF_OUT_LOG(IFF_IPV4, "IPv4"); +	IFF_OUT_LOG(IFF_IPV6, "IPv6"); + +	strlcat(logbuf, ">", BUFSIZ); + +	return logbuf;  #undef IFF_OUT_LOG  }  /* For debugging */ -static void -if_dump (const struct interface *ifp) +static void if_dump(const struct interface *ifp)  { -  struct listnode *node; -  struct connected *c __attribute__((unused)); - -  for (ALL_LIST_ELEMENTS_RO (ifp->connected, node, c)) -    zlog_info ("Interface %s vrf %u index %d metric %d mtu %d " -               "mtu6 %d %s", -               ifp->name, ifp->vrf_id, ifp->ifindex, ifp->metric, ifp->mtu, -               ifp->mtu6, if_flag_dump (ifp->flags)); +	struct listnode *node; +	struct connected *c __attribute__((unused)); + +	for (ALL_LIST_ELEMENTS_RO(ifp->connected, node, c)) +		zlog_info( +			"Interface %s vrf %u index %d metric %d mtu %d " +			"mtu6 %d %s", +			ifp->name, ifp->vrf_id, ifp->ifindex, ifp->metric, +			ifp->mtu, ifp->mtu6, if_flag_dump(ifp->flags));  }  /* Interface printing for all interface. */ -void -if_dump_all (void) +void if_dump_all(void)  { -  struct vrf *vrf; -  struct listnode *node; -  void *p; - -  RB_FOREACH (vrf, vrf_id_head, &vrfs_by_id) -    if (vrf->iflist != NULL) -      for (ALL_LIST_ELEMENTS_RO (vrf->iflist, node, p)) -        if_dump (p); +	struct vrf *vrf; +	struct listnode *node; +	void *p; + +	RB_FOREACH(vrf, vrf_id_head, &vrfs_by_id) +	if (vrf->iflist != NULL) +		for (ALL_LIST_ELEMENTS_RO(vrf->iflist, node, p)) +			if_dump(p);  }  DEFUN (interface_desc, @@ -611,14 +585,14 @@ DEFUN (interface_desc,         "Interface specific description\n"         "Characters describing this interface\n")  { -  int idx_line = 1; -  VTY_DECLVAR_CONTEXT (interface, ifp); +	int idx_line = 1; +	VTY_DECLVAR_CONTEXT(interface, ifp); -  if (ifp->desc) -    XFREE (MTYPE_TMP, ifp->desc); -  ifp->desc = argv_concat(argv, argc, idx_line); +	if (ifp->desc) +		XFREE(MTYPE_TMP, ifp->desc); +	ifp->desc = argv_concat(argv, argc, idx_line); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_interface_desc, @@ -627,13 +601,13 @@ DEFUN (no_interface_desc,         NO_STR         "Interface specific description\n")  { -  VTY_DECLVAR_CONTEXT (interface, ifp); +	VTY_DECLVAR_CONTEXT(interface, ifp); -  if (ifp->desc) -    XFREE (MTYPE_TMP, ifp->desc); -  ifp->desc = NULL; +	if (ifp->desc) +		XFREE(MTYPE_TMP, ifp->desc); +	ifp->desc = NULL; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  #ifdef SUNOS_5 @@ -657,24 +631,24 @@ DEFUN (no_interface_desc,   *     if not:   *     - no idea, just get the name in its entirety.   */ -static struct interface * -if_sunwzebra_get (const char *name, size_t nlen, vrf_id_t vrf_id) +static struct interface *if_sunwzebra_get(const char *name, size_t nlen, +					  vrf_id_t vrf_id)  { -  struct interface *ifp; -  size_t seppos = 0; - -  if ( (ifp = if_lookup_by_name_len (name, nlen, vrf_id)) != NULL) -    return ifp; -   -  /* hunt the primary interface name... */ -  while (seppos < nlen && name[seppos] != ':') -    seppos++; -   -  /* Wont catch seperator as last char, e.g. 'foo0:' but thats invalid */ -  if (seppos < nlen) -    return if_get_by_name_len (name, seppos, vrf_id, 1); -  else -    return if_get_by_name_len (name, nlen, vrf_id, 1); +	struct interface *ifp; +	size_t seppos = 0; + +	if ((ifp = if_lookup_by_name_len(name, nlen, vrf_id)) != NULL) +		return ifp; + +	/* hunt the primary interface name... */ +	while (seppos < nlen && name[seppos] != ':') +		seppos++; + +	/* Wont catch seperator as last char, e.g. 'foo0:' but thats invalid */ +	if (seppos < nlen) +		return if_get_by_name_len(name, seppos, vrf_id, 1); +	else +		return if_get_by_name_len(name, nlen, vrf_id, 1);  }  #endif /* SUNOS_5 */ @@ -685,42 +659,42 @@ DEFUN (interface,         "Interface's name\n"         VRF_CMD_HELP_STR)  { -  int idx_ifname = 1; -  int idx_vrf = 3; -  const char *ifname = argv[idx_ifname]->arg; -  const char *vrfname = (argc > 2) ? argv[idx_vrf]->arg : NULL; - -  struct interface *ifp; -  size_t sl; -  vrf_id_t vrf_id = VRF_DEFAULT; - -  if ((sl = strlen(ifname)) > INTERFACE_NAMSIZ) -    { -      vty_out (vty, "%% Interface name %s is invalid: length exceeds " -		    "%d characters%s", -	       ifname, INTERFACE_NAMSIZ, VTY_NEWLINE); -      return CMD_WARNING; -    } +	int idx_ifname = 1; +	int idx_vrf = 3; +	const char *ifname = argv[idx_ifname]->arg; +	const char *vrfname = (argc > 2) ? argv[idx_vrf]->arg : NULL; + +	struct interface *ifp; +	size_t sl; +	vrf_id_t vrf_id = VRF_DEFAULT; + +	if ((sl = strlen(ifname)) > INTERFACE_NAMSIZ) { +		vty_out(vty, +			"%% Interface name %s is invalid: length exceeds " +			"%d characters%s", +			ifname, INTERFACE_NAMSIZ, VTY_NEWLINE); +		return CMD_WARNING; +	} -/*Pending: need proper vrf name based lookup/(possible creation of VRF) - Imagine forward reference of a vrf by name in this interface config */ -  if (vrfname) -    VRF_GET_ID (vrf_id, vrfname); +	/*Pending: need proper vrf name based lookup/(possible creation of VRF) +	 Imagine forward reference of a vrf by name in this interface config */ +	if (vrfname) +		VRF_GET_ID(vrf_id, vrfname);  #ifdef SUNOS_5 -  ifp = if_sunwzebra_get (ifname, sl, vrf_id); +	ifp = if_sunwzebra_get(ifname, sl, vrf_id);  #else -  ifp = if_get_by_name_len (ifname, sl, vrf_id, 1); +	ifp = if_get_by_name_len(ifname, sl, vrf_id, 1);  #endif /* SUNOS_5 */ -  if (!ifp) -    { -      vty_out (vty, "%% interface %s not in %s%s", ifname, vrfname, VTY_NEWLINE); -      return CMD_WARNING; -    } -  VTY_PUSH_CONTEXT (INTERFACE_NODE, ifp); +	if (!ifp) { +		vty_out(vty, "%% interface %s not in %s%s", ifname, vrfname, +			VTY_NEWLINE); +		return CMD_WARNING; +	} +	VTY_PUSH_CONTEXT(INTERFACE_NODE, ifp); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN_NOSH (no_interface, @@ -731,45 +705,43 @@ DEFUN_NOSH (no_interface,             "Interface's name\n"             VRF_CMD_HELP_STR)  { -  const char *ifname = argv[2]->arg; -  const char *vrfname = (argc > 3) ? argv[3]->arg : NULL; +	const char *ifname = argv[2]->arg; +	const char *vrfname = (argc > 3) ? argv[3]->arg : NULL; -  // deleting interface -  struct interface *ifp; -  vrf_id_t vrf_id = VRF_DEFAULT; +	// deleting interface +	struct interface *ifp; +	vrf_id_t vrf_id = VRF_DEFAULT; -  if (argc > 3) -    VRF_GET_ID (vrf_id, vrfname); +	if (argc > 3) +		VRF_GET_ID(vrf_id, vrfname); -  ifp = if_lookup_by_name (ifname, vrf_id); +	ifp = if_lookup_by_name(ifname, vrf_id); -  if (ifp == NULL) -    { -      vty_out (vty, "%% Interface %s does not exist%s", ifname, VTY_NEWLINE); -      return CMD_WARNING; -    } +	if (ifp == NULL) { +		vty_out(vty, "%% Interface %s does not exist%s", ifname, +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  if (CHECK_FLAG (ifp->status, ZEBRA_INTERFACE_ACTIVE))  -    { -      vty_out (vty, "%% Only inactive interfaces can be deleted%s", -	      VTY_NEWLINE); -      return CMD_WARNING; -    } +	if (CHECK_FLAG(ifp->status, ZEBRA_INTERFACE_ACTIVE)) { +		vty_out(vty, "%% Only inactive interfaces can be deleted%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  if_delete(ifp); +	if_delete(ifp); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  } -void -if_cmd_init (void) +void if_cmd_init(void)  { -  install_element (CONFIG_NODE, &interface_cmd); -  install_element (CONFIG_NODE, &no_interface_cmd); +	install_element(CONFIG_NODE, &interface_cmd); +	install_element(CONFIG_NODE, &no_interface_cmd); -  install_default (INTERFACE_NODE); -  install_element (INTERFACE_NODE, &interface_desc_cmd); -  install_element (INTERFACE_NODE, &no_interface_desc_cmd); +	install_default(INTERFACE_NODE); +	install_element(INTERFACE_NODE, &interface_desc_cmd); +	install_element(INTERFACE_NODE, &no_interface_desc_cmd);  }  #if 0 @@ -845,212 +817,199 @@ DEFUN (show_address_vrf_all,  #endif  /* Allocate connected structure. */ -struct connected * -connected_new (void) +struct connected *connected_new(void)  { -  return XCALLOC (MTYPE_CONNECTED, sizeof (struct connected)); +	return XCALLOC(MTYPE_CONNECTED, sizeof(struct connected));  }  /* Allocate nbr connected structure. */ -struct nbr_connected * -nbr_connected_new (void) +struct nbr_connected *nbr_connected_new(void)  { -  return XCALLOC (MTYPE_NBR_CONNECTED, sizeof (struct nbr_connected)); +	return XCALLOC(MTYPE_NBR_CONNECTED, sizeof(struct nbr_connected));  }  /* Free connected structure. */ -void -connected_free (struct connected *connected) +void connected_free(struct connected *connected)  { -  if (connected->address) -    prefix_free (connected->address); +	if (connected->address) +		prefix_free(connected->address); -  if (connected->destination) -    prefix_free (connected->destination); +	if (connected->destination) +		prefix_free(connected->destination); -  if (connected->label) -    XFREE (MTYPE_CONNECTED_LABEL, connected->label); +	if (connected->label) +		XFREE(MTYPE_CONNECTED_LABEL, connected->label); -  XFREE (MTYPE_CONNECTED, connected); +	XFREE(MTYPE_CONNECTED, connected);  }  /* Free nbr connected structure. */ -void -nbr_connected_free (struct nbr_connected *connected) +void nbr_connected_free(struct nbr_connected *connected)  { -  if (connected->address) -    prefix_free (connected->address); +	if (connected->address) +		prefix_free(connected->address); -  XFREE (MTYPE_NBR_CONNECTED, connected); +	XFREE(MTYPE_NBR_CONNECTED, connected);  }  /* If same interface nbr address already exists... */ -struct nbr_connected * -nbr_connected_check (struct interface *ifp, struct prefix *p) +struct nbr_connected *nbr_connected_check(struct interface *ifp, +					  struct prefix *p)  { -  struct nbr_connected *ifc; -  struct listnode *node; +	struct nbr_connected *ifc; +	struct listnode *node; -  for (ALL_LIST_ELEMENTS_RO (ifp->nbr_connected, node, ifc)) -    if (prefix_same (ifc->address, p)) -      return ifc; +	for (ALL_LIST_ELEMENTS_RO(ifp->nbr_connected, node, ifc)) +		if (prefix_same(ifc->address, p)) +			return ifc; -  return NULL; +	return NULL;  }  /* Print if_addr structure. */ -static void __attribute__ ((unused)) -connected_log (struct connected *connected, char *str) +static void __attribute__((unused)) +connected_log(struct connected *connected, char *str)  { -  struct prefix *p; -  struct interface *ifp; -  char logbuf[BUFSIZ]; -  char buf[BUFSIZ]; -   -  ifp = connected->ifp; -  p = connected->address; - -  snprintf (logbuf, BUFSIZ, "%s interface %s vrf %u %s %s/%d ", -	    str, ifp->name, ifp->vrf_id, prefix_family_str (p), -	    inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -	    p->prefixlen); - -  p = connected->destination; -  if (p) -    { -      strncat (logbuf, inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -	       BUFSIZ - strlen(logbuf)); -    } -  zlog_info("%s", logbuf); +	struct prefix *p; +	struct interface *ifp; +	char logbuf[BUFSIZ]; +	char buf[BUFSIZ]; + +	ifp = connected->ifp; +	p = connected->address; + +	snprintf(logbuf, BUFSIZ, "%s interface %s vrf %u %s %s/%d ", str, +		 ifp->name, ifp->vrf_id, prefix_family_str(p), +		 inet_ntop(p->family, &p->u.prefix, buf, BUFSIZ), p->prefixlen); + +	p = connected->destination; +	if (p) { +		strncat(logbuf, inet_ntop(p->family, &p->u.prefix, buf, BUFSIZ), +			BUFSIZ - strlen(logbuf)); +	} +	zlog_info("%s", logbuf);  }  /* Print if_addr structure. */ -static void __attribute__ ((unused)) -nbr_connected_log (struct nbr_connected *connected, char *str) +static void __attribute__((unused)) +nbr_connected_log(struct nbr_connected *connected, char *str)  { -  struct prefix *p; -  struct interface *ifp; -  char logbuf[BUFSIZ]; -  char buf[BUFSIZ]; +	struct prefix *p; +	struct interface *ifp; +	char logbuf[BUFSIZ]; +	char buf[BUFSIZ]; -  ifp = connected->ifp; -  p = connected->address; +	ifp = connected->ifp; +	p = connected->address; -  snprintf (logbuf, BUFSIZ, "%s interface %s %s %s/%d ", -	    str, ifp->name, prefix_family_str (p), -	    inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -	    p->prefixlen); +	snprintf(logbuf, BUFSIZ, "%s interface %s %s %s/%d ", str, ifp->name, +		 prefix_family_str(p), +		 inet_ntop(p->family, &p->u.prefix, buf, BUFSIZ), p->prefixlen); -  zlog_info("%s", logbuf); +	zlog_info("%s", logbuf);  }  /* If two connected address has same prefix return 1. */ -static int -connected_same_prefix (struct prefix *p1, struct prefix *p2) +static int connected_same_prefix(struct prefix *p1, struct prefix *p2)  { -  if (p1->family == p2->family) -    { -      if (p1->family == AF_INET && -	  IPV4_ADDR_SAME (&p1->u.prefix4, &p2->u.prefix4)) -	return 1; -      if (p1->family == AF_INET6 && -	  IPV6_ADDR_SAME (&p1->u.prefix6, &p2->u.prefix6)) -	return 1; -    } -  return 0; +	if (p1->family == p2->family) { +		if (p1->family == AF_INET +		    && IPV4_ADDR_SAME(&p1->u.prefix4, &p2->u.prefix4)) +			return 1; +		if (p1->family == AF_INET6 +		    && IPV6_ADDR_SAME(&p1->u.prefix6, &p2->u.prefix6)) +			return 1; +	} +	return 0;  } -struct connected * -connected_lookup_prefix_exact (struct interface *ifp, struct prefix *p) +struct connected *connected_lookup_prefix_exact(struct interface *ifp, +						struct prefix *p)  { -  struct listnode *node; -  struct listnode *next; -  struct connected *ifc; +	struct listnode *node; +	struct listnode *next; +	struct connected *ifc; -  for (node = listhead (ifp->connected); node; node = next) -    { -      ifc = listgetdata (node); -      next = node->next; +	for (node = listhead(ifp->connected); node; node = next) { +		ifc = listgetdata(node); +		next = node->next; -      if (connected_same_prefix (ifc->address, p)) -        return ifc; -    } -  return NULL; +		if (connected_same_prefix(ifc->address, p)) +			return ifc; +	} +	return NULL;  } -struct connected * -connected_delete_by_prefix (struct interface *ifp, struct prefix *p) +struct connected *connected_delete_by_prefix(struct interface *ifp, +					     struct prefix *p)  { -  struct listnode *node; -  struct listnode *next; -  struct connected *ifc; - -  /* In case of same prefix come, replace it with new one. */ -  for (node = listhead (ifp->connected); node; node = next) -    { -      ifc = listgetdata (node); -      next = node->next; - -      if (connected_same_prefix (ifc->address, p)) -	{ -	  listnode_delete (ifp->connected, ifc); -	  return ifc; +	struct listnode *node; +	struct listnode *next; +	struct connected *ifc; + +	/* In case of same prefix come, replace it with new one. */ +	for (node = listhead(ifp->connected); node; node = next) { +		ifc = listgetdata(node); +		next = node->next; + +		if (connected_same_prefix(ifc->address, p)) { +			listnode_delete(ifp->connected, ifc); +			return ifc; +		}  	} -    } -  return NULL; +	return NULL;  }  /* Find the address on our side that will be used when packets     are sent to dst. */ -struct connected * -connected_lookup_prefix (struct interface *ifp, struct prefix *addr) +struct connected *connected_lookup_prefix(struct interface *ifp, +					  struct prefix *addr)  { -  struct listnode *cnode; -  struct connected *c; -  struct connected *match; - -  match = NULL; - -  for (ALL_LIST_ELEMENTS_RO (ifp->connected, cnode, c)) -    { -      if (c->address && (c->address->family == addr->family) && -	  prefix_match(CONNECTED_PREFIX(c), addr) && -	  (!match || (c->address->prefixlen > match->address->prefixlen))) -	match = c; -    } -  return match; +	struct listnode *cnode; +	struct connected *c; +	struct connected *match; + +	match = NULL; + +	for (ALL_LIST_ELEMENTS_RO(ifp->connected, cnode, c)) { +		if (c->address && (c->address->family == addr->family) +		    && prefix_match(CONNECTED_PREFIX(c), addr) +		    && (!match +			|| (c->address->prefixlen > match->address->prefixlen))) +			match = c; +	} +	return match;  } -struct connected * -connected_add_by_prefix (struct interface *ifp, struct prefix *p,  -                         struct prefix *destination) +struct connected *connected_add_by_prefix(struct interface *ifp, +					  struct prefix *p, +					  struct prefix *destination)  { -  struct connected *ifc; +	struct connected *ifc; -  /* Allocate new connected address. */ -  ifc = connected_new (); -  ifc->ifp = ifp; +	/* Allocate new connected address. */ +	ifc = connected_new(); +	ifc->ifp = ifp; -  /* Fetch interface address */ -  ifc->address = prefix_new(); -  memcpy (ifc->address, p, sizeof(struct prefix)); +	/* Fetch interface address */ +	ifc->address = prefix_new(); +	memcpy(ifc->address, p, sizeof(struct prefix)); -  /* Fetch dest address */ -  if (destination) -    { -      ifc->destination = prefix_new(); -      memcpy (ifc->destination, destination, sizeof(struct prefix)); -    } +	/* Fetch dest address */ +	if (destination) { +		ifc->destination = prefix_new(); +		memcpy(ifc->destination, destination, sizeof(struct prefix)); +	} -  /* Add connected address to the interface. */ -  listnode_add (ifp->connected, ifc); -  return ifc; +	/* Add connected address to the interface. */ +	listnode_add(ifp->connected, ifc); +	return ifc;  } -#if 0 /* this route_table of struct connected's is unused -       * however, it would be good to use a route_table rather than -       * a list.. -       */ +#if 0  /* this route_table of struct connected's is unused                     \ +	* however, it would be good to use a route_table rather than           \ +	* a list..                                                             \ +	*/  /* Interface looking up by interface's address. */  /* Interface's IPv4 address reverse lookup table. */  struct route_table *ifaddr_ipv4_table; @@ -1127,139 +1086,135 @@ ifaddr_ipv4_lookup (struct in_addr *addr, ifindex_t ifindex)  #endif /* ifaddr_ipv4_table */  /* Initialize interface list. */ -void -if_init (struct list **intf_list) +void if_init(struct list **intf_list)  { -  *intf_list = list_new (); +	*intf_list = list_new();  #if 0    ifaddr_ipv4_table = route_table_init ();  #endif /* ifaddr_ipv4_table */ -  (*intf_list)->cmp = (int (*)(void *, void *))if_cmp_func; +	(*intf_list)->cmp = (int (*)(void *, void *))if_cmp_func;  } -void -if_terminate (struct list **intf_list) +void if_terminate(struct list **intf_list)  { -  for (;;) -    { -      struct interface *ifp; +	for (;;) { +		struct interface *ifp; -      ifp = listnode_head (*intf_list); -      if (ifp == NULL) -	break; +		ifp = listnode_head(*intf_list); +		if (ifp == NULL) +			break; -      if (ifp->node) -        { -          ifp->node->info = NULL; -          route_unlock_node (ifp->node); -        } +		if (ifp->node) { +			ifp->node->info = NULL; +			route_unlock_node(ifp->node); +		} -      if_delete (ifp); -    } +		if_delete(ifp); +	} -  list_delete (*intf_list); -  *intf_list = NULL; +	list_delete(*intf_list); +	*intf_list = NULL;  } -const char * -if_link_type_str (enum zebra_link_type llt) +const char *if_link_type_str(enum zebra_link_type llt)  { -  switch (llt) -    { +	switch (llt) {  #define llts(T,S) case (T): return (S) -      llts(ZEBRA_LLT_UNKNOWN,               "Unknown"); -      llts(ZEBRA_LLT_ETHER,                 "Ethernet"); -      llts(ZEBRA_LLT_EETHER,                "Experimental Ethernet"); -      llts(ZEBRA_LLT_AX25,                  "AX.25 Level 2"); -      llts(ZEBRA_LLT_PRONET,                "PROnet token ring"); -      llts(ZEBRA_LLT_IEEE802,               "IEEE 802.2 Ethernet/TR/TB"); -      llts(ZEBRA_LLT_ARCNET,                "ARCnet"); -      llts(ZEBRA_LLT_APPLETLK,              "AppleTalk"); -      llts(ZEBRA_LLT_DLCI,                  "Frame Relay DLCI"); -      llts(ZEBRA_LLT_ATM,                   "ATM"); -      llts(ZEBRA_LLT_METRICOM,              "Metricom STRIP"); -      llts(ZEBRA_LLT_IEEE1394,              "IEEE 1394 IPv4"); -      llts(ZEBRA_LLT_EUI64,                 "EUI-64"); -      llts(ZEBRA_LLT_INFINIBAND,            "InfiniBand"); -      llts(ZEBRA_LLT_SLIP,                  "SLIP"); -      llts(ZEBRA_LLT_CSLIP,                 "Compressed SLIP"); -      llts(ZEBRA_LLT_SLIP6,                 "SLIPv6"); -      llts(ZEBRA_LLT_CSLIP6,                "Compressed SLIPv6"); -      llts(ZEBRA_LLT_ROSE,                  "ROSE packet radio"); -      llts(ZEBRA_LLT_X25,                   "CCITT X.25"); -      llts(ZEBRA_LLT_PPP,                   "PPP"); -      llts(ZEBRA_LLT_CHDLC,                 "Cisco HDLC"); -      llts(ZEBRA_LLT_RAWHDLC,               "Raw HDLC"); -      llts(ZEBRA_LLT_LAPB,                  "LAPB"); -      llts(ZEBRA_LLT_IPIP,                  "IPIP Tunnel"); -      llts(ZEBRA_LLT_IPIP6,                 "IPIP6 Tunnel"); -      llts(ZEBRA_LLT_FRAD,                  "FRAD"); -      llts(ZEBRA_LLT_SKIP,                  "SKIP vif"); -      llts(ZEBRA_LLT_LOOPBACK,              "Loopback"); -      llts(ZEBRA_LLT_LOCALTLK,              "Localtalk"); -      llts(ZEBRA_LLT_FDDI,                  "FDDI"); -      llts(ZEBRA_LLT_SIT,                   "IPv6-in-IPv4 SIT"); -      llts(ZEBRA_LLT_IPDDP,                 "IP-in-DDP tunnel"); -      llts(ZEBRA_LLT_IPGRE,                 "GRE over IP"); -      llts(ZEBRA_LLT_PIMREG,                "PIMSM registration"); -      llts(ZEBRA_LLT_HIPPI,                 "HiPPI"); -      llts(ZEBRA_LLT_IRDA,                  "IrDA"); -      llts(ZEBRA_LLT_FCPP,                  "Fibre-Channel PtP"); -      llts(ZEBRA_LLT_FCAL,                  "Fibre-Channel Arbitrated Loop"); -      llts(ZEBRA_LLT_FCPL,                  "Fibre-Channel Public Loop"); -      llts(ZEBRA_LLT_FCFABRIC,              "Fibre-Channel Fabric"); -      llts(ZEBRA_LLT_IEEE802_TR,            "IEEE 802.2 Token Ring"); -      llts(ZEBRA_LLT_IEEE80211,             "IEEE 802.11"); -      llts(ZEBRA_LLT_IEEE80211_RADIOTAP,    "IEEE 802.11 Radiotap"); -      llts(ZEBRA_LLT_IEEE802154,            "IEEE 802.15.4"); -      llts(ZEBRA_LLT_IEEE802154_PHY,        "IEEE 802.15.4 Phy"); -      default: -        zlog_warn ("Unknown value %d", llt); -        return "Unknown type!"; +		llts(ZEBRA_LLT_UNKNOWN, "Unknown"); +		llts(ZEBRA_LLT_ETHER, "Ethernet"); +		llts(ZEBRA_LLT_EETHER, "Experimental Ethernet"); +		llts(ZEBRA_LLT_AX25, "AX.25 Level 2"); +		llts(ZEBRA_LLT_PRONET, "PROnet token ring"); +		llts(ZEBRA_LLT_IEEE802, "IEEE 802.2 Ethernet/TR/TB"); +		llts(ZEBRA_LLT_ARCNET, "ARCnet"); +		llts(ZEBRA_LLT_APPLETLK, "AppleTalk"); +		llts(ZEBRA_LLT_DLCI, "Frame Relay DLCI"); +		llts(ZEBRA_LLT_ATM, "ATM"); +		llts(ZEBRA_LLT_METRICOM, "Metricom STRIP"); +		llts(ZEBRA_LLT_IEEE1394, "IEEE 1394 IPv4"); +		llts(ZEBRA_LLT_EUI64, "EUI-64"); +		llts(ZEBRA_LLT_INFINIBAND, "InfiniBand"); +		llts(ZEBRA_LLT_SLIP, "SLIP"); +		llts(ZEBRA_LLT_CSLIP, "Compressed SLIP"); +		llts(ZEBRA_LLT_SLIP6, "SLIPv6"); +		llts(ZEBRA_LLT_CSLIP6, "Compressed SLIPv6"); +		llts(ZEBRA_LLT_ROSE, "ROSE packet radio"); +		llts(ZEBRA_LLT_X25, "CCITT X.25"); +		llts(ZEBRA_LLT_PPP, "PPP"); +		llts(ZEBRA_LLT_CHDLC, "Cisco HDLC"); +		llts(ZEBRA_LLT_RAWHDLC, "Raw HDLC"); +		llts(ZEBRA_LLT_LAPB, "LAPB"); +		llts(ZEBRA_LLT_IPIP, "IPIP Tunnel"); +		llts(ZEBRA_LLT_IPIP6, "IPIP6 Tunnel"); +		llts(ZEBRA_LLT_FRAD, "FRAD"); +		llts(ZEBRA_LLT_SKIP, "SKIP vif"); +		llts(ZEBRA_LLT_LOOPBACK, "Loopback"); +		llts(ZEBRA_LLT_LOCALTLK, "Localtalk"); +		llts(ZEBRA_LLT_FDDI, "FDDI"); +		llts(ZEBRA_LLT_SIT, "IPv6-in-IPv4 SIT"); +		llts(ZEBRA_LLT_IPDDP, "IP-in-DDP tunnel"); +		llts(ZEBRA_LLT_IPGRE, "GRE over IP"); +		llts(ZEBRA_LLT_PIMREG, "PIMSM registration"); +		llts(ZEBRA_LLT_HIPPI, "HiPPI"); +		llts(ZEBRA_LLT_IRDA, "IrDA"); +		llts(ZEBRA_LLT_FCPP, "Fibre-Channel PtP"); +		llts(ZEBRA_LLT_FCAL, "Fibre-Channel Arbitrated Loop"); +		llts(ZEBRA_LLT_FCPL, "Fibre-Channel Public Loop"); +		llts(ZEBRA_LLT_FCFABRIC, "Fibre-Channel Fabric"); +		llts(ZEBRA_LLT_IEEE802_TR, "IEEE 802.2 Token Ring"); +		llts(ZEBRA_LLT_IEEE80211, "IEEE 802.11"); +		llts(ZEBRA_LLT_IEEE80211_RADIOTAP, "IEEE 802.11 Radiotap"); +		llts(ZEBRA_LLT_IEEE802154, "IEEE 802.15.4"); +		llts(ZEBRA_LLT_IEEE802154_PHY, "IEEE 802.15.4 Phy"); +	default: +		zlog_warn("Unknown value %d", llt); +		return "Unknown type!";  #undef llts -    } -  return NULL; +	} +	return NULL;  } -struct if_link_params * -if_link_params_get (struct interface *ifp) +struct if_link_params *if_link_params_get(struct interface *ifp)  { -  int i; +	int i; -  if (ifp->link_params != NULL) -    return ifp->link_params; +	if (ifp->link_params != NULL) +		return ifp->link_params; -  struct if_link_params *iflp = XCALLOC(MTYPE_IF_LINK_PARAMS, -                                      sizeof (struct if_link_params)); -  if (iflp == NULL) return NULL; +	struct if_link_params *iflp = +		XCALLOC(MTYPE_IF_LINK_PARAMS, sizeof(struct if_link_params)); +	if (iflp == NULL) +		return NULL; -  /* Set TE metric equal to standard metric */ -  iflp->te_metric = ifp->metric; +	/* Set TE metric equal to standard metric */ +	iflp->te_metric = ifp->metric; -  /* Compute default bandwidth based on interface */ -  iflp->default_bw = ((ifp->bandwidth ? ifp->bandwidth : DEFAULT_BANDWIDTH) -		      * TE_KILO_BIT / TE_BYTE); +	/* Compute default bandwidth based on interface */ +	iflp->default_bw = +		((ifp->bandwidth ? ifp->bandwidth : DEFAULT_BANDWIDTH) +		 * TE_KILO_BIT / TE_BYTE); -  /* Set Max, Reservable and Unreserved Bandwidth */ -  iflp->max_bw = iflp->default_bw; -  iflp->max_rsv_bw = iflp->default_bw; -  for (i = 0; i < MAX_CLASS_TYPE; i++) -    iflp->unrsv_bw[i] = iflp->default_bw; +	/* Set Max, Reservable and Unreserved Bandwidth */ +	iflp->max_bw = iflp->default_bw; +	iflp->max_rsv_bw = iflp->default_bw; +	for (i = 0; i < MAX_CLASS_TYPE; i++) +		iflp->unrsv_bw[i] = iflp->default_bw; -  /* Update Link parameters status */ -  iflp->lp_status = LP_TE_METRIC | LP_MAX_BW | LP_MAX_RSV_BW | LP_UNRSV_BW; +	/* Update Link parameters status */ +	iflp->lp_status = +		LP_TE_METRIC | LP_MAX_BW | LP_MAX_RSV_BW | LP_UNRSV_BW; -  /* Finally attach newly created Link Parameters */ -  ifp->link_params = iflp; +	/* Finally attach newly created Link Parameters */ +	ifp->link_params = iflp; -  return iflp; +	return iflp;  } -void -if_link_params_free (struct interface *ifp) +void if_link_params_free(struct interface *ifp)  { -  if (ifp->link_params == NULL) return; -  XFREE(MTYPE_IF_LINK_PARAMS, ifp->link_params); -  ifp->link_params = NULL; +	if (ifp->link_params == NULL) +		return; +	XFREE(MTYPE_IF_LINK_PARAMS, ifp->link_params); +	ifp->link_params = NULL;  } @@ -37,56 +37,56 @@ DECLARE_MTYPE(CONNECTED_LABEL)   * Some of the more obviously defunct technologies left out.   */  enum zebra_link_type { -  ZEBRA_LLT_UNKNOWN = 0, -  ZEBRA_LLT_ETHER, -  ZEBRA_LLT_EETHER, -  ZEBRA_LLT_AX25, -  ZEBRA_LLT_PRONET, -  ZEBRA_LLT_IEEE802, -  ZEBRA_LLT_ARCNET, -  ZEBRA_LLT_APPLETLK, -  ZEBRA_LLT_DLCI, -  ZEBRA_LLT_ATM, -  ZEBRA_LLT_METRICOM, -  ZEBRA_LLT_IEEE1394, -  ZEBRA_LLT_EUI64, -  ZEBRA_LLT_INFINIBAND, -  ZEBRA_LLT_SLIP, -  ZEBRA_LLT_CSLIP, -  ZEBRA_LLT_SLIP6, -  ZEBRA_LLT_CSLIP6, -  ZEBRA_LLT_RSRVD, -  ZEBRA_LLT_ADAPT, -  ZEBRA_LLT_ROSE, -  ZEBRA_LLT_X25, -  ZEBRA_LLT_PPP, -  ZEBRA_LLT_CHDLC, -  ZEBRA_LLT_LAPB, -  ZEBRA_LLT_RAWHDLC, -  ZEBRA_LLT_IPIP, -  ZEBRA_LLT_IPIP6, -  ZEBRA_LLT_FRAD, -  ZEBRA_LLT_SKIP, -  ZEBRA_LLT_LOOPBACK, -  ZEBRA_LLT_LOCALTLK, -  ZEBRA_LLT_FDDI, -  ZEBRA_LLT_SIT, -  ZEBRA_LLT_IPDDP, -  ZEBRA_LLT_IPGRE, -  ZEBRA_LLT_IP6GRE, -  ZEBRA_LLT_PIMREG, -  ZEBRA_LLT_HIPPI, -  ZEBRA_LLT_ECONET, -  ZEBRA_LLT_IRDA, -  ZEBRA_LLT_FCPP, -  ZEBRA_LLT_FCAL, -  ZEBRA_LLT_FCPL, -  ZEBRA_LLT_FCFABRIC, -  ZEBRA_LLT_IEEE802_TR, -  ZEBRA_LLT_IEEE80211, -  ZEBRA_LLT_IEEE80211_RADIOTAP, -  ZEBRA_LLT_IEEE802154, -  ZEBRA_LLT_IEEE802154_PHY, +	ZEBRA_LLT_UNKNOWN = 0, +	ZEBRA_LLT_ETHER, +	ZEBRA_LLT_EETHER, +	ZEBRA_LLT_AX25, +	ZEBRA_LLT_PRONET, +	ZEBRA_LLT_IEEE802, +	ZEBRA_LLT_ARCNET, +	ZEBRA_LLT_APPLETLK, +	ZEBRA_LLT_DLCI, +	ZEBRA_LLT_ATM, +	ZEBRA_LLT_METRICOM, +	ZEBRA_LLT_IEEE1394, +	ZEBRA_LLT_EUI64, +	ZEBRA_LLT_INFINIBAND, +	ZEBRA_LLT_SLIP, +	ZEBRA_LLT_CSLIP, +	ZEBRA_LLT_SLIP6, +	ZEBRA_LLT_CSLIP6, +	ZEBRA_LLT_RSRVD, +	ZEBRA_LLT_ADAPT, +	ZEBRA_LLT_ROSE, +	ZEBRA_LLT_X25, +	ZEBRA_LLT_PPP, +	ZEBRA_LLT_CHDLC, +	ZEBRA_LLT_LAPB, +	ZEBRA_LLT_RAWHDLC, +	ZEBRA_LLT_IPIP, +	ZEBRA_LLT_IPIP6, +	ZEBRA_LLT_FRAD, +	ZEBRA_LLT_SKIP, +	ZEBRA_LLT_LOOPBACK, +	ZEBRA_LLT_LOCALTLK, +	ZEBRA_LLT_FDDI, +	ZEBRA_LLT_SIT, +	ZEBRA_LLT_IPDDP, +	ZEBRA_LLT_IPGRE, +	ZEBRA_LLT_IP6GRE, +	ZEBRA_LLT_PIMREG, +	ZEBRA_LLT_HIPPI, +	ZEBRA_LLT_ECONET, +	ZEBRA_LLT_IRDA, +	ZEBRA_LLT_FCPP, +	ZEBRA_LLT_FCAL, +	ZEBRA_LLT_FCPL, +	ZEBRA_LLT_FCFABRIC, +	ZEBRA_LLT_IEEE802_TR, +	ZEBRA_LLT_IEEE80211, +	ZEBRA_LLT_IEEE80211_RADIOTAP, +	ZEBRA_LLT_IEEE802154, +	ZEBRA_LLT_IEEE802154_PHY,  };  /* @@ -105,34 +105,33 @@ enum zebra_link_type {  typedef signed int ifindex_t;  #ifdef HAVE_PROC_NET_DEV -struct if_stats -{ -  unsigned long rx_packets;   /* total packets received       */ -  unsigned long tx_packets;   /* total packets transmitted    */ -  unsigned long rx_bytes;     /* total bytes received         */ -  unsigned long tx_bytes;     /* total bytes transmitted      */ -  unsigned long rx_errors;    /* bad packets received         */ -  unsigned long tx_errors;    /* packet transmit problems     */ -  unsigned long rx_dropped;   /* no space in linux buffers    */ -  unsigned long tx_dropped;   /* no space available in linux  */ -  unsigned long rx_multicast; /* multicast packets received   */ -  unsigned long rx_compressed; -  unsigned long tx_compressed; -  unsigned long collisions; - -  /* detailed rx_errors: */ -  unsigned long rx_length_errors; -  unsigned long rx_over_errors;       /* receiver ring buff overflow  */ -  unsigned long rx_crc_errors;        /* recved pkt with crc error    */ -  unsigned long rx_frame_errors;      /* recv'd frame alignment error */ -  unsigned long rx_fifo_errors;       /* recv'r fifo overrun          */ -  unsigned long rx_missed_errors;     /* receiver missed packet     */ -  /* detailed tx_errors */ -  unsigned long tx_aborted_errors; -  unsigned long tx_carrier_errors; -  unsigned long tx_fifo_errors; -  unsigned long tx_heartbeat_errors; -  unsigned long tx_window_errors; +struct if_stats { +	unsigned long rx_packets;   /* total packets received       */ +	unsigned long tx_packets;   /* total packets transmitted    */ +	unsigned long rx_bytes;     /* total bytes received         */ +	unsigned long tx_bytes;     /* total bytes transmitted      */ +	unsigned long rx_errors;    /* bad packets received         */ +	unsigned long tx_errors;    /* packet transmit problems     */ +	unsigned long rx_dropped;   /* no space in linux buffers    */ +	unsigned long tx_dropped;   /* no space available in linux  */ +	unsigned long rx_multicast; /* multicast packets received   */ +	unsigned long rx_compressed; +	unsigned long tx_compressed; +	unsigned long collisions; + +	/* detailed rx_errors: */ +	unsigned long rx_length_errors; +	unsigned long rx_over_errors;   /* receiver ring buff overflow  */ +	unsigned long rx_crc_errors;    /* recved pkt with crc error    */ +	unsigned long rx_frame_errors;  /* recv'd frame alignment error */ +	unsigned long rx_fifo_errors;   /* recv'r fifo overrun          */ +	unsigned long rx_missed_errors; /* receiver missed packet     */ +	/* detailed tx_errors */ +	unsigned long tx_aborted_errors; +	unsigned long tx_carrier_errors; +	unsigned long tx_fifo_errors; +	unsigned long tx_heartbeat_errors; +	unsigned long tx_window_errors;  };  #endif /* HAVE_PROC_NET_DEV */ @@ -176,178 +175,185 @@ struct if_stats  /* Link Parameters for Traffic Engineering */  struct if_link_params { -  u_int32_t lp_status;   /* Status of Link Parameters: */ -  u_int32_t te_metric;   /* Traffic Engineering metric */ -  float default_bw; -  float max_bw;          /* Maximum Bandwidth */ -  float max_rsv_bw;      /* Maximum Reservable Bandwidth */ -  float unrsv_bw[MAX_CLASS_TYPE];     /* Unreserved Bandwidth per Class Type (8) */ -  u_int32_t admin_grp;   /* Administrative group */ -  u_int32_t rmt_as;      /* Remote AS number */ -  struct in_addr rmt_ip; /* Remote IP address */ -  u_int32_t av_delay;    /* Link Average Delay */ -  u_int32_t min_delay;   /* Link Min Delay */ -  u_int32_t max_delay;   /* Link Max Delay */ -  u_int32_t delay_var;   /* Link Delay Variation */ -  float pkt_loss;        /* Link Packet Loss */ -  float res_bw;          /* Residual Bandwidth */ -  float ava_bw;          /* Available Bandwidth */ -  float use_bw;          /* Utilized Bandwidth */ +	u_int32_t lp_status; /* Status of Link Parameters: */ +	u_int32_t te_metric; /* Traffic Engineering metric */ +	float default_bw; +	float max_bw;			/* Maximum Bandwidth */ +	float max_rsv_bw;		/* Maximum Reservable Bandwidth */ +	float unrsv_bw[MAX_CLASS_TYPE]; /* Unreserved Bandwidth per Class Type +					   (8) */ +	u_int32_t admin_grp;		/* Administrative group */ +	u_int32_t rmt_as;		/* Remote AS number */ +	struct in_addr rmt_ip;		/* Remote IP address */ +	u_int32_t av_delay;		/* Link Average Delay */ +	u_int32_t min_delay;		/* Link Min Delay */ +	u_int32_t max_delay;		/* Link Max Delay */ +	u_int32_t delay_var;		/* Link Delay Variation */ +	float pkt_loss;			/* Link Packet Loss */ +	float res_bw;			/* Residual Bandwidth */ +	float ava_bw;			/* Available Bandwidth */ +	float use_bw;			/* Utilized Bandwidth */  };  #define INTERFACE_LINK_PARAMS_SIZE   sizeof(struct if_link_params)  #define HAS_LINK_PARAMS(ifp)  ((ifp)->link_params != NULL)  /* Interface structure */ -struct interface  -{ -  /* Interface name.  This should probably never be changed after the -     interface is created, because the configuration info for this interface -     is associated with this structure.  For that reason, the interface -     should also never be deleted (to avoid losing configuration info). -     To delete, just set ifindex to IFINDEX_INTERNAL to indicate that the -     interface does not exist in the kernel. -   */ -  char name[INTERFACE_NAMSIZ + 1]; - -  /* Interface index (should be IFINDEX_INTERNAL for non-kernel or -     deleted interfaces). */ -  ifindex_t ifindex; +struct interface { +	/* Interface name.  This should probably never be changed after the +	   interface is created, because the configuration info for this +	   interface +	   is associated with this structure.  For that reason, the interface +	   should also never be deleted (to avoid losing configuration info). +	   To delete, just set ifindex to IFINDEX_INTERNAL to indicate that the +	   interface does not exist in the kernel. +	 */ +	char name[INTERFACE_NAMSIZ + 1]; + +	/* Interface index (should be IFINDEX_INTERNAL for non-kernel or +	   deleted interfaces). */ +	ifindex_t ifindex;  #define IFINDEX_INTERNAL	0  #define IFINDEX_DELETED         INT_MAX -  /* Zebra internal interface status */ -  u_char status; +	/* Zebra internal interface status */ +	u_char status;  #define ZEBRA_INTERFACE_ACTIVE     (1 << 0)  #define ZEBRA_INTERFACE_SUB        (1 << 1)  #define ZEBRA_INTERFACE_LINKDETECTION (1 << 2)  #define ZEBRA_INTERFACE_VRF_LOOPBACK (1 << 3) -  /* Interface flags. */ -  uint64_t flags; +	/* Interface flags. */ +	uint64_t flags; -  /* Interface metric */ -  uint32_t metric; +	/* Interface metric */ +	uint32_t metric; -  /* Interface Speed in Mb/s */ -  uint32_t speed; +	/* Interface Speed in Mb/s */ +	uint32_t speed; -  /* Interface MTU. */ -  unsigned int mtu;    /* IPv4 MTU */ -  unsigned int mtu6;   /* IPv6 MTU - probably, but not neccessarily same as mtu */ +	/* Interface MTU. */ +	unsigned int mtu; /* IPv4 MTU */ +	unsigned int +		mtu6; /* IPv6 MTU - probably, but not neccessarily same as mtu +			 */ -  /* Link-layer information and hardware address */ -  enum zebra_link_type ll_type; -  u_char hw_addr[INTERFACE_HWADDR_MAX]; -  int hw_addr_len; +	/* Link-layer information and hardware address */ +	enum zebra_link_type ll_type; +	u_char hw_addr[INTERFACE_HWADDR_MAX]; +	int hw_addr_len; -  /* interface bandwidth, kbits */ -  unsigned int bandwidth; -   -  /* Link parameters for Traffic Engineering */ -  struct if_link_params *link_params; +	/* interface bandwidth, kbits */ +	unsigned int bandwidth; -  /* description of the interface. */ -  char *desc;			 +	/* Link parameters for Traffic Engineering */ +	struct if_link_params *link_params; -  /* Distribute list. */ -  void *distribute_in; -  void *distribute_out; +	/* description of the interface. */ +	char *desc; -  /* Connected address list. */ -  struct list *connected; +	/* Distribute list. */ +	void *distribute_in; +	void *distribute_out; -  /* Neighbor connected address list. */ -  struct list *nbr_connected; +	/* Connected address list. */ +	struct list *connected; -  /* Daemon specific interface data pointer. */ -  void *info; +	/* Neighbor connected address list. */ +	struct list *nbr_connected; -  char ptm_enable;             /* Should we look at ptm_status ? */ -  char ptm_status; +	/* Daemon specific interface data pointer. */ +	void *info; -  /* Statistics fileds. */ +	char ptm_enable; /* Should we look at ptm_status ? */ +	char ptm_status; + +/* Statistics fileds. */  #ifdef HAVE_PROC_NET_DEV -  struct if_stats stats; -#endif /* HAVE_PROC_NET_DEV */   +	struct if_stats stats; +#endif /* HAVE_PROC_NET_DEV */  #ifdef HAVE_NET_RT_IFLIST -  struct if_data stats; +	struct if_data stats;  #endif /* HAVE_NET_RT_IFLIST */ -  struct route_node *node; -  vrf_id_t vrf_id; +	struct route_node *node; +	vrf_id_t vrf_id; -  QOBJ_FIELDS +	QOBJ_FIELDS  };  DECLARE_QOBJ_TYPE(interface)  /* Connected address structure. */ -struct connected -{ -  /* Attached interface. */ -  struct interface *ifp; +struct connected { +	/* Attached interface. */ +	struct interface *ifp; -  /* Flags for configuration. */ -  u_char conf; +	/* Flags for configuration. */ +	u_char conf;  #define ZEBRA_IFC_REAL         (1 << 0)  #define ZEBRA_IFC_CONFIGURED   (1 << 1)  #define ZEBRA_IFC_QUEUED       (1 << 2) -  /* -     The ZEBRA_IFC_REAL flag should be set if and only if this address -     exists in the kernel and is actually usable. (A case where it exists but -     is not yet usable would be IPv6 with DAD) -     The ZEBRA_IFC_CONFIGURED flag should be set if and only if this address -     was configured by the user from inside quagga. -     The ZEBRA_IFC_QUEUED flag should be set if and only if the address exists -     in the kernel. It may and should be set although the address might not be -     usable yet. (compare with ZEBRA_IFC_REAL) -   */ - -  /* Flags for connected address. */ -  u_char flags; +	/* +	   The ZEBRA_IFC_REAL flag should be set if and only if this address +	   exists in the kernel and is actually usable. (A case where it exists +	   but +	   is not yet usable would be IPv6 with DAD) +	   The ZEBRA_IFC_CONFIGURED flag should be set if and only if this +	   address +	   was configured by the user from inside quagga. +	   The ZEBRA_IFC_QUEUED flag should be set if and only if the address +	   exists +	   in the kernel. It may and should be set although the address might +	   not be +	   usable yet. (compare with ZEBRA_IFC_REAL) +	 */ + +	/* Flags for connected address. */ +	u_char flags;  #define ZEBRA_IFA_SECONDARY    (1 << 0)  #define ZEBRA_IFA_PEER         (1 << 1)  #define ZEBRA_IFA_UNNUMBERED   (1 << 2) -  /* N.B. the ZEBRA_IFA_PEER flag should be set if and only if -     a peer address has been configured.  If this flag is set, -     the destination field must contain the peer address.   -     Otherwise, if this flag is not set, the destination address -     will either contain a broadcast address or be NULL. -   */ - -  /* Address of connected network. */ -  struct prefix *address; - -  /* Peer or Broadcast address, depending on whether ZEBRA_IFA_PEER is set. -     Note: destination may be NULL if ZEBRA_IFA_PEER is not set. */ -  struct prefix *destination; - -  /* Label for Linux 2.2.X and upper. */ -  char *label; +	/* N.B. the ZEBRA_IFA_PEER flag should be set if and only if +	   a peer address has been configured.  If this flag is set, +	   the destination field must contain the peer address. +	   Otherwise, if this flag is not set, the destination address +	   will either contain a broadcast address or be NULL. +	 */ + +	/* Address of connected network. */ +	struct prefix *address; + +	/* Peer or Broadcast address, depending on whether ZEBRA_IFA_PEER is +	   set. +	   Note: destination may be NULL if ZEBRA_IFA_PEER is not set. */ +	struct prefix *destination; + +	/* Label for Linux 2.2.X and upper. */ +	char *label;  };  /* Nbr Connected address structure. */ -struct nbr_connected -{ -  /* Attached interface. */ -  struct interface *ifp; +struct nbr_connected { +	/* Attached interface. */ +	struct interface *ifp; -  /* Address of connected network. */ -  struct prefix *address; +	/* Address of connected network. */ +	struct prefix *address;  };  /* Does the destination field contain a peer address? */  #define CONNECTED_PEER(C) CHECK_FLAG((C)->flags, ZEBRA_IFA_PEER)  /* Prefix to insert into the RIB */ -#define CONNECTED_PREFIX(C) \ +#define CONNECTED_PREFIX(C)                                                    \  	(CONNECTED_PEER(C) ? (C)->destination : (C)->address)  /* Identifying address.  We guess that if there's a peer address, but the     local address is in the same prefix, then the local address may be unique. */ -#define CONNECTED_ID(C)	\ -	((CONNECTED_PEER(C) && !prefix_match((C)->destination, (C)->address)) ?\ -	 (C)->destination : (C)->address) +#define CONNECTED_ID(C)                                                        \ +	((CONNECTED_PEER(C) && !prefix_match((C)->destination, (C)->address))  \ +		 ? (C)->destination                                            \ +		 : (C)->address)  /* Interface hook sort. */  #define IF_NEW_HOOK   0 @@ -391,66 +397,64 @@ struct nbr_connected  #endif /* IFF_VIRTUAL */  /* Prototypes. */ -extern int if_cmp_name_func (char *, char *); - -extern void if_update (struct interface *, const char *name, int namelen, -                       vrf_id_t vrf_id); -extern struct interface *if_create (const char *name, int namelen, -                                    vrf_id_t vrf_id); -extern struct interface *if_lookup_by_index (ifindex_t, vrf_id_t vrf_id); -extern struct interface *if_lookup_exact_address (void *matchaddr, int family, -                                                  vrf_id_t vrf_id); -extern struct connected *if_lookup_address (void *matchaddr, int family, -                                            vrf_id_t vrf_id); -extern struct interface *if_lookup_prefix (struct prefix *prefix, -                                vrf_id_t vrf_id); +extern int if_cmp_name_func(char *, char *); + +extern void if_update(struct interface *, const char *name, int namelen, +		      vrf_id_t vrf_id); +extern struct interface *if_create(const char *name, int namelen, +				   vrf_id_t vrf_id); +extern struct interface *if_lookup_by_index(ifindex_t, vrf_id_t vrf_id); +extern struct interface *if_lookup_exact_address(void *matchaddr, int family, +						 vrf_id_t vrf_id); +extern struct connected *if_lookup_address(void *matchaddr, int family, +					   vrf_id_t vrf_id); +extern struct interface *if_lookup_prefix(struct prefix *prefix, +					  vrf_id_t vrf_id);  /* These 3 functions are to be used when the ifname argument is terminated     by a '\0' character: */ -extern struct interface *if_lookup_by_name_all_vrf (const char *ifname); -extern struct interface *if_lookup_by_name (const char *ifname, -                                                vrf_id_t vrf_id); -extern struct interface *if_get_by_name (const char *ifname, -                                vrf_id_t vrf_id); +extern struct interface *if_lookup_by_name_all_vrf(const char *ifname); +extern struct interface *if_lookup_by_name(const char *ifname, vrf_id_t vrf_id); +extern struct interface *if_get_by_name(const char *ifname, vrf_id_t vrf_id);  /* For these 2 functions, the namelen argument should be the precise length     of the ifname string (not counting any optional trailing '\0' character).     In most cases, strnlen should be used to calculate the namelen value. */  extern struct interface *if_lookup_by_name_len(const char *ifname, -                                               size_t namelen, vrf_id_t vrf_id); -extern struct interface *if_get_by_name_len(const char *ifname, -				size_t namelen, vrf_id_t vrf_id, int vty); +					       size_t namelen, vrf_id_t vrf_id); +extern struct interface *if_get_by_name_len(const char *ifname, size_t namelen, +					    vrf_id_t vrf_id, int vty);  /* Delete the interface, but do not free the structure, and leave it in the -   interface list.  It is often advisable to leave the pseudo interface  +   interface list.  It is often advisable to leave the pseudo interface     structure because there may be configuration information attached. */ -extern void if_delete_retain (struct interface *); +extern void if_delete_retain(struct interface *);  /* Delete and free the interface structure: calls if_delete_retain and then     deletes it from the interface list and frees the structure. */ -extern void if_delete (struct interface *); - -extern int if_is_up (struct interface *); -extern int if_is_running (struct interface *); -extern int if_is_operative (struct interface *); -extern int if_is_no_ptm_operative (struct interface *); -extern int if_is_loopback (struct interface *); -extern int if_is_broadcast (struct interface *); -extern int if_is_pointopoint (struct interface *); -extern int if_is_multicast (struct interface *); -extern void if_add_hook (int, int (*)(struct interface *)); -extern void if_init (struct list **); -extern void if_cmd_init (void); -extern void if_terminate (struct list **); -extern void if_dump_all (void); +extern void if_delete(struct interface *); + +extern int if_is_up(struct interface *); +extern int if_is_running(struct interface *); +extern int if_is_operative(struct interface *); +extern int if_is_no_ptm_operative(struct interface *); +extern int if_is_loopback(struct interface *); +extern int if_is_broadcast(struct interface *); +extern int if_is_pointopoint(struct interface *); +extern int if_is_multicast(struct interface *); +extern void if_add_hook(int, int (*)(struct interface *)); +extern void if_init(struct list **); +extern void if_cmd_init(void); +extern void if_terminate(struct list **); +extern void if_dump_all(void);  extern const char *if_flag_dump(unsigned long); -extern const char *if_link_type_str (enum zebra_link_type); +extern const char *if_link_type_str(enum zebra_link_type);  /* Please use ifindex2ifname instead of if_indextoname where possible;     ifindex2ifname uses internal interface info, whereas if_indextoname must     make a system call. */ -extern const char *ifindex2ifname (ifindex_t, vrf_id_t vrf_id); +extern const char *ifindex2ifname(ifindex_t, vrf_id_t vrf_id);  /* Please use ifname2ifindex instead of if_nametoindex where possible;     ifname2ifindex uses internal interface info, whereas if_nametoindex must @@ -458,24 +462,23 @@ extern const char *ifindex2ifname (ifindex_t, vrf_id_t vrf_id);  extern ifindex_t ifname2ifindex(const char *ifname, vrf_id_t vrf_id);  /* Connected address functions. */ -extern struct connected *connected_new (void); -extern void connected_free (struct connected *); -extern void connected_add (struct interface *, struct connected *); -extern struct connected  *connected_add_by_prefix (struct interface *, -                                            struct prefix *, -                                            struct prefix *); -extern struct connected  *connected_delete_by_prefix (struct interface *,  -                                               struct prefix *); -extern struct connected  *connected_lookup_prefix (struct interface *, -                                                   struct prefix *); -extern struct connected  *connected_lookup_prefix_exact (struct interface *, -                                                   struct prefix *); -extern struct nbr_connected *nbr_connected_new (void); -extern void nbr_connected_free (struct nbr_connected *); -struct nbr_connected *nbr_connected_check (struct interface *, struct prefix *); +extern struct connected *connected_new(void); +extern void connected_free(struct connected *); +extern void connected_add(struct interface *, struct connected *); +extern struct connected * +connected_add_by_prefix(struct interface *, struct prefix *, struct prefix *); +extern struct connected *connected_delete_by_prefix(struct interface *, +						    struct prefix *); +extern struct connected *connected_lookup_prefix(struct interface *, +						 struct prefix *); +extern struct connected *connected_lookup_prefix_exact(struct interface *, +						       struct prefix *); +extern struct nbr_connected *nbr_connected_new(void); +extern void nbr_connected_free(struct nbr_connected *); +struct nbr_connected *nbr_connected_check(struct interface *, struct prefix *);  /* link parameters */ -struct if_link_params *if_link_params_get (struct interface *); -void if_link_params_free (struct interface *); +struct if_link_params *if_link_params_get(struct interface *); +void if_link_params_free(struct interface *);  #endif /* _ZEBRA_IF_H */ diff --git a/lib/if_rmap.c b/lib/if_rmap.c index 2afb08c7ca..1ce2a43c59 100644 --- a/lib/if_rmap.c +++ b/lib/if_rmap.c @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -27,186 +27,172 @@  #include "if.h"  #include "if_rmap.h" -DEFINE_MTYPE_STATIC(LIB, IF_RMAP,      "Interface route map") +DEFINE_MTYPE_STATIC(LIB, IF_RMAP, "Interface route map")  DEFINE_MTYPE_STATIC(LIB, IF_RMAP_NAME, "I.f. route map name")  struct hash *ifrmaphash;  /* Hook functions. */ -static void (*if_rmap_add_hook) (struct if_rmap *) = NULL; -static void (*if_rmap_delete_hook) (struct if_rmap *) = NULL; +static void (*if_rmap_add_hook)(struct if_rmap *) = NULL; +static void (*if_rmap_delete_hook)(struct if_rmap *) = NULL; -static struct if_rmap * -if_rmap_new (void) +static struct if_rmap *if_rmap_new(void)  { -  struct if_rmap *new; +	struct if_rmap *new; -  new = XCALLOC (MTYPE_IF_RMAP, sizeof (struct if_rmap)); +	new = XCALLOC(MTYPE_IF_RMAP, sizeof(struct if_rmap)); -  return new; +	return new;  } -static void -if_rmap_free (struct if_rmap *if_rmap) +static void if_rmap_free(struct if_rmap *if_rmap)  { -  if (if_rmap->ifname) -    XFREE (MTYPE_IF_RMAP_NAME, if_rmap->ifname); +	if (if_rmap->ifname) +		XFREE(MTYPE_IF_RMAP_NAME, if_rmap->ifname); -  if (if_rmap->routemap[IF_RMAP_IN]) -    XFREE (MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_IN]); -  if (if_rmap->routemap[IF_RMAP_OUT]) -    XFREE (MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_OUT]); +	if (if_rmap->routemap[IF_RMAP_IN]) +		XFREE(MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_IN]); +	if (if_rmap->routemap[IF_RMAP_OUT]) +		XFREE(MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_OUT]); -  XFREE (MTYPE_IF_RMAP, if_rmap); +	XFREE(MTYPE_IF_RMAP, if_rmap);  } -struct if_rmap * -if_rmap_lookup (const char *ifname) +struct if_rmap *if_rmap_lookup(const char *ifname)  { -  struct if_rmap key; -  struct if_rmap *if_rmap; +	struct if_rmap key; +	struct if_rmap *if_rmap; -  /* temporary copy */ -  key.ifname = (ifname) ? XSTRDUP (MTYPE_IF_RMAP_NAME, ifname) : NULL; +	/* temporary copy */ +	key.ifname = (ifname) ? XSTRDUP(MTYPE_IF_RMAP_NAME, ifname) : NULL; -  if_rmap = hash_lookup (ifrmaphash, &key); -   -  if (key.ifname) -    XFREE(MTYPE_IF_RMAP_NAME, key.ifname); +	if_rmap = hash_lookup(ifrmaphash, &key); -  return if_rmap; +	if (key.ifname) +		XFREE(MTYPE_IF_RMAP_NAME, key.ifname); + +	return if_rmap;  } -void -if_rmap_hook_add (void (*func) (struct if_rmap *)) +void if_rmap_hook_add(void (*func)(struct if_rmap *))  { -  if_rmap_add_hook = func; +	if_rmap_add_hook = func;  } -void -if_rmap_hook_delete (void (*func) (struct if_rmap *)) +void if_rmap_hook_delete(void (*func)(struct if_rmap *))  { -  if_rmap_delete_hook = func; +	if_rmap_delete_hook = func;  } -static void * -if_rmap_hash_alloc (void *arg) +static void *if_rmap_hash_alloc(void *arg)  { -  struct if_rmap *ifarg = (struct if_rmap *)arg; -  struct if_rmap *if_rmap; +	struct if_rmap *ifarg = (struct if_rmap *)arg; +	struct if_rmap *if_rmap; -  if_rmap = if_rmap_new (); -  if_rmap->ifname = XSTRDUP (MTYPE_IF_RMAP_NAME, ifarg->ifname); +	if_rmap = if_rmap_new(); +	if_rmap->ifname = XSTRDUP(MTYPE_IF_RMAP_NAME, ifarg->ifname); -  return if_rmap; +	return if_rmap;  } -static struct if_rmap * -if_rmap_get (const char *ifname) +static struct if_rmap *if_rmap_get(const char *ifname)  { -  struct if_rmap key; -  struct if_rmap *ret; +	struct if_rmap key; +	struct if_rmap *ret; -  /* temporary copy */ -  key.ifname = (ifname) ? XSTRDUP (MTYPE_IF_RMAP_NAME, ifname) : NULL; +	/* temporary copy */ +	key.ifname = (ifname) ? XSTRDUP(MTYPE_IF_RMAP_NAME, ifname) : NULL; -  ret = hash_get (ifrmaphash, &key, if_rmap_hash_alloc); +	ret = hash_get(ifrmaphash, &key, if_rmap_hash_alloc); -  if (key.ifname) -    XFREE(MTYPE_IF_RMAP_NAME, key.ifname); +	if (key.ifname) +		XFREE(MTYPE_IF_RMAP_NAME, key.ifname); -  return ret; +	return ret;  } -static unsigned int -if_rmap_hash_make (void *data) +static unsigned int if_rmap_hash_make(void *data)  { -  const struct if_rmap *if_rmap = data; +	const struct if_rmap *if_rmap = data; -  return string_hash_make (if_rmap->ifname); +	return string_hash_make(if_rmap->ifname);  } -static int -if_rmap_hash_cmp (const void *arg1, const void* arg2) +static int if_rmap_hash_cmp(const void *arg1, const void *arg2)  { -  const struct if_rmap *if_rmap1 = arg1; -  const struct if_rmap *if_rmap2 = arg2; +	const struct if_rmap *if_rmap1 = arg1; +	const struct if_rmap *if_rmap2 = arg2; -  return strcmp (if_rmap1->ifname, if_rmap2->ifname) == 0; +	return strcmp(if_rmap1->ifname, if_rmap2->ifname) == 0;  } -static struct if_rmap * -if_rmap_set (const char *ifname, enum if_rmap_type type,  -             const char *routemap_name) +static struct if_rmap *if_rmap_set(const char *ifname, enum if_rmap_type type, +				   const char *routemap_name)  { -  struct if_rmap *if_rmap; - -  if_rmap = if_rmap_get (ifname); - -  if (type == IF_RMAP_IN) -    { -      if (if_rmap->routemap[IF_RMAP_IN]) -	XFREE (MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_IN]); -      if_rmap->routemap[IF_RMAP_IN]  -        = XSTRDUP (MTYPE_IF_RMAP_NAME, routemap_name); -    } -  if (type == IF_RMAP_OUT) -    { -      if (if_rmap->routemap[IF_RMAP_OUT]) -	XFREE (MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_OUT]); -      if_rmap->routemap[IF_RMAP_OUT]  -        = XSTRDUP (MTYPE_IF_RMAP_NAME, routemap_name); -    } - -  if (if_rmap_add_hook) -    (*if_rmap_add_hook) (if_rmap); -   -  return if_rmap; +	struct if_rmap *if_rmap; + +	if_rmap = if_rmap_get(ifname); + +	if (type == IF_RMAP_IN) { +		if (if_rmap->routemap[IF_RMAP_IN]) +			XFREE(MTYPE_IF_RMAP_NAME, +			      if_rmap->routemap[IF_RMAP_IN]); +		if_rmap->routemap[IF_RMAP_IN] = +			XSTRDUP(MTYPE_IF_RMAP_NAME, routemap_name); +	} +	if (type == IF_RMAP_OUT) { +		if (if_rmap->routemap[IF_RMAP_OUT]) +			XFREE(MTYPE_IF_RMAP_NAME, +			      if_rmap->routemap[IF_RMAP_OUT]); +		if_rmap->routemap[IF_RMAP_OUT] = +			XSTRDUP(MTYPE_IF_RMAP_NAME, routemap_name); +	} + +	if (if_rmap_add_hook) +		(*if_rmap_add_hook)(if_rmap); + +	return if_rmap;  } -static int -if_rmap_unset (const char *ifname, enum if_rmap_type type,  -               const char *routemap_name) +static int if_rmap_unset(const char *ifname, enum if_rmap_type type, +			 const char *routemap_name)  { -  struct if_rmap *if_rmap; - -  if_rmap = if_rmap_lookup (ifname); -  if (!if_rmap) -    return 0; - -  if (type == IF_RMAP_IN) -    { -      if (!if_rmap->routemap[IF_RMAP_IN]) -	return 0; -      if (strcmp (if_rmap->routemap[IF_RMAP_IN], routemap_name) != 0) -	return 0; - -      XFREE (MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_IN]); -      if_rmap->routemap[IF_RMAP_IN] = NULL;       -    } - -  if (type == IF_RMAP_OUT) -    { -      if (!if_rmap->routemap[IF_RMAP_OUT]) -	return 0; -      if (strcmp (if_rmap->routemap[IF_RMAP_OUT], routemap_name) != 0) -	return 0; - -      XFREE (MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_OUT]); -      if_rmap->routemap[IF_RMAP_OUT] = NULL;       -    } - -  if (if_rmap_delete_hook) -    (*if_rmap_delete_hook) (if_rmap); - -  if (if_rmap->routemap[IF_RMAP_IN] == NULL && -      if_rmap->routemap[IF_RMAP_OUT] == NULL) -    { -      hash_release (ifrmaphash, if_rmap); -      if_rmap_free (if_rmap); -    } - -  return 1; +	struct if_rmap *if_rmap; + +	if_rmap = if_rmap_lookup(ifname); +	if (!if_rmap) +		return 0; + +	if (type == IF_RMAP_IN) { +		if (!if_rmap->routemap[IF_RMAP_IN]) +			return 0; +		if (strcmp(if_rmap->routemap[IF_RMAP_IN], routemap_name) != 0) +			return 0; + +		XFREE(MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_IN]); +		if_rmap->routemap[IF_RMAP_IN] = NULL; +	} + +	if (type == IF_RMAP_OUT) { +		if (!if_rmap->routemap[IF_RMAP_OUT]) +			return 0; +		if (strcmp(if_rmap->routemap[IF_RMAP_OUT], routemap_name) != 0) +			return 0; + +		XFREE(MTYPE_IF_RMAP_NAME, if_rmap->routemap[IF_RMAP_OUT]); +		if_rmap->routemap[IF_RMAP_OUT] = NULL; +	} + +	if (if_rmap_delete_hook) +		(*if_rmap_delete_hook)(if_rmap); + +	if (if_rmap->routemap[IF_RMAP_IN] == NULL +	    && if_rmap->routemap[IF_RMAP_OUT] == NULL) { +		hash_release(ifrmaphash, if_rmap); +		if_rmap_free(if_rmap); +	} + +	return 1;  }  DEFUN (if_rmap, @@ -218,24 +204,24 @@ DEFUN (if_rmap,         "Route map set for output filtering\n"         "Route map interface name\n")  { -  int idx_rmap_name = 1; -  int idx_in_out = 2; -  int idx_ifname = 3; -  enum if_rmap_type type; - -  if (strncmp (argv[idx_in_out]->text, "in", 1) == 0) -    type = IF_RMAP_IN; -  else if (strncmp (argv[idx_in_out]->text, "out", 1) == 0) -    type = IF_RMAP_OUT; -  else -    { -      vty_out (vty, "route-map direction must be [in|out]%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  if_rmap_set (argv[idx_ifname]->arg, type, argv[idx_rmap_name]->arg); - -  return CMD_SUCCESS; +	int idx_rmap_name = 1; +	int idx_in_out = 2; +	int idx_ifname = 3; +	enum if_rmap_type type; + +	if (strncmp(argv[idx_in_out]->text, "in", 1) == 0) +		type = IF_RMAP_IN; +	else if (strncmp(argv[idx_in_out]->text, "out", 1) == 0) +		type = IF_RMAP_OUT; +	else { +		vty_out(vty, "route-map direction must be [in|out]%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	if_rmap_set(argv[idx_ifname]->arg, type, argv[idx_rmap_name]->arg); + +	return CMD_SUCCESS;  }  DEFUN (no_if_rmap, @@ -248,81 +234,73 @@ DEFUN (no_if_rmap,         "Route map for output filtering\n"         "Route map interface name\n")  { -  int idx_routemap_name = 2; -  int idx_in_out = 3; -  int idx_ifname = 4; -  int ret; -  enum if_rmap_type type; - -  if (strncmp (argv[idx_in_out]->arg, "i", 1) == 0) -    type = IF_RMAP_IN; -  else if (strncmp (argv[idx_in_out]->arg, "o", 1) == 0) -    type = IF_RMAP_OUT; -  else -    { -      vty_out (vty, "route-map direction must be [in|out]%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  ret = if_rmap_unset (argv[idx_ifname]->arg, type, argv[idx_routemap_name]->arg); -  if (! ret) -    { -      vty_out (vty, "route-map doesn't exist%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  return CMD_SUCCESS; +	int idx_routemap_name = 2; +	int idx_in_out = 3; +	int idx_ifname = 4; +	int ret; +	enum if_rmap_type type; + +	if (strncmp(argv[idx_in_out]->arg, "i", 1) == 0) +		type = IF_RMAP_IN; +	else if (strncmp(argv[idx_in_out]->arg, "o", 1) == 0) +		type = IF_RMAP_OUT; +	else { +		vty_out(vty, "route-map direction must be [in|out]%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	ret = if_rmap_unset(argv[idx_ifname]->arg, type, +			    argv[idx_routemap_name]->arg); +	if (!ret) { +		vty_out(vty, "route-map doesn't exist%s", VTY_NEWLINE); +		return CMD_WARNING; +	} +	return CMD_SUCCESS;  }  /* Configuration write function. */ -int -config_write_if_rmap (struct vty *vty) +int config_write_if_rmap(struct vty *vty)  { -  unsigned int i; -  struct hash_backet *mp; -  int write = 0; - -  for (i = 0; i < ifrmaphash->size; i++) -    for (mp = ifrmaphash->index[i]; mp; mp = mp->next) -      { -	struct if_rmap *if_rmap; - -	if_rmap = mp->data; - -	if (if_rmap->routemap[IF_RMAP_IN]) -	  { -	    vty_out (vty, " route-map %s in %s%s",  -		     if_rmap->routemap[IF_RMAP_IN], -		     if_rmap->ifname, -		     VTY_NEWLINE); -	    write++; -	  } - -	if (if_rmap->routemap[IF_RMAP_OUT]) -	  { -	    vty_out (vty, " route-map %s out %s%s",  -		     if_rmap->routemap[IF_RMAP_OUT], -		     if_rmap->ifname, -		     VTY_NEWLINE); -	    write++; -	  } -      } -  return write; +	unsigned int i; +	struct hash_backet *mp; +	int write = 0; + +	for (i = 0; i < ifrmaphash->size; i++) +		for (mp = ifrmaphash->index[i]; mp; mp = mp->next) { +			struct if_rmap *if_rmap; + +			if_rmap = mp->data; + +			if (if_rmap->routemap[IF_RMAP_IN]) { +				vty_out(vty, " route-map %s in %s%s", +					if_rmap->routemap[IF_RMAP_IN], +					if_rmap->ifname, VTY_NEWLINE); +				write++; +			} + +			if (if_rmap->routemap[IF_RMAP_OUT]) { +				vty_out(vty, " route-map %s out %s%s", +					if_rmap->routemap[IF_RMAP_OUT], +					if_rmap->ifname, VTY_NEWLINE); +				write++; +			} +		} +	return write;  } -void -if_rmap_reset () +void if_rmap_reset()  { -  hash_clean (ifrmaphash, (void (*) (void *)) if_rmap_free); +	hash_clean(ifrmaphash, (void (*)(void *))if_rmap_free);  } -void -if_rmap_init (int node) +void if_rmap_init(int node)  { -  ifrmaphash = hash_create (if_rmap_hash_make, if_rmap_hash_cmp); -  if (node == RIPNG_NODE) { -  } else if (node == RIP_NODE) { -    install_element (RIP_NODE, &if_rmap_cmd); -    install_element (RIP_NODE, &no_if_rmap_cmd); -  } +	ifrmaphash = hash_create(if_rmap_hash_make, if_rmap_hash_cmp); +	if (node == RIPNG_NODE) { +	} else if (node == RIP_NODE) { +		install_element(RIP_NODE, &if_rmap_cmd); +		install_element(RIP_NODE, &no_if_rmap_cmd); +	}  } diff --git a/lib/if_rmap.h b/lib/if_rmap.h index e6c2966ff8..c6c5d80dc6 100644 --- a/lib/if_rmap.h +++ b/lib/if_rmap.h @@ -16,32 +16,26 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_IF_RMAP_H  #define _ZEBRA_IF_RMAP_H -enum if_rmap_type -{ -  IF_RMAP_IN, -  IF_RMAP_OUT, -  IF_RMAP_MAX -}; +enum if_rmap_type { IF_RMAP_IN, IF_RMAP_OUT, IF_RMAP_MAX }; -struct if_rmap -{ -  /* Name of the interface. */ -  char *ifname; +struct if_rmap { +	/* Name of the interface. */ +	char *ifname; -  char *routemap[IF_RMAP_MAX]; +	char *routemap[IF_RMAP_MAX];  }; -extern void if_rmap_init (int); -extern void if_rmap_reset (void); -extern void if_rmap_hook_add (void (*) (struct if_rmap *)); -extern void if_rmap_hook_delete (void (*) (struct if_rmap *)); -extern struct if_rmap *if_rmap_lookup (const char *); -extern int config_write_if_rmap (struct vty *); +extern void if_rmap_init(int); +extern void if_rmap_reset(void); +extern void if_rmap_hook_add(void (*)(struct if_rmap *)); +extern void if_rmap_hook_delete(void (*)(struct if_rmap *)); +extern struct if_rmap *if_rmap_lookup(const char *); +extern int config_write_if_rmap(struct vty *);  #endif /* _ZEBRA_IF_RMAP_H */ diff --git a/lib/imsg-buffer.c b/lib/imsg-buffer.c index a486fc17c1..4068e31c51 100644 --- a/lib/imsg-buffer.c +++ b/lib/imsg-buffer.c @@ -21,14 +21,13 @@  #include "openbsd-queue.h"  #include "imsg.h" -int	ibuf_realloc(struct ibuf *, size_t); -void	ibuf_enqueue(struct msgbuf *, struct ibuf *); -void	ibuf_dequeue(struct msgbuf *, struct ibuf *); +int ibuf_realloc(struct ibuf *, size_t); +void ibuf_enqueue(struct msgbuf *, struct ibuf *); +void ibuf_dequeue(struct msgbuf *, struct ibuf *); -struct ibuf * -ibuf_open(size_t len) +struct ibuf *ibuf_open(size_t len)  { -	struct ibuf	*buf; +	struct ibuf *buf;  	if ((buf = calloc(1, sizeof(struct ibuf))) == NULL)  		return (NULL); @@ -42,10 +41,9 @@ ibuf_open(size_t len)  	return (buf);  } -struct ibuf * -ibuf_dynamic(size_t len, size_t max) +struct ibuf *ibuf_dynamic(size_t len, size_t max)  { -	struct ibuf	*buf; +	struct ibuf *buf;  	if (max < len)  		return (NULL); @@ -59,10 +57,9 @@ ibuf_dynamic(size_t len, size_t max)  	return (buf);  } -int -ibuf_realloc(struct ibuf *buf, size_t len) +int ibuf_realloc(struct ibuf *buf, size_t len)  { -	u_char	*b; +	u_char *b;  	/* on static buffers max is eq size and so the following fails */  	if (buf->wpos + len > buf->max) { @@ -79,8 +76,7 @@ ibuf_realloc(struct ibuf *buf, size_t len)  	return (0);  } -int -ibuf_add(struct ibuf *buf, const void *data, size_t len) +int ibuf_add(struct ibuf *buf, const void *data, size_t len)  {  	if (buf->wpos + len > buf->size)  		if (ibuf_realloc(buf, len) == -1) @@ -91,10 +87,9 @@ ibuf_add(struct ibuf *buf, const void *data, size_t len)  	return (0);  } -void * -ibuf_reserve(struct ibuf *buf, size_t len) +void *ibuf_reserve(struct ibuf *buf, size_t len)  { -	void	*b; +	void *b;  	if (buf->wpos + len > buf->size)  		if (ibuf_realloc(buf, len) == -1) @@ -105,8 +100,7 @@ ibuf_reserve(struct ibuf *buf, size_t len)  	return (b);  } -void * -ibuf_seek(struct ibuf *buf, size_t pos, size_t len) +void *ibuf_seek(struct ibuf *buf, size_t pos, size_t len)  {  	/* only allowed to seek in already written parts */  	if (pos + len > buf->wpos) @@ -115,34 +109,31 @@ ibuf_seek(struct ibuf *buf, size_t pos, size_t len)  	return (buf->buf + pos);  } -size_t -ibuf_size(struct ibuf *buf) +size_t ibuf_size(struct ibuf *buf)  {  	return (buf->wpos);  } -size_t -ibuf_left(struct ibuf *buf) +size_t ibuf_left(struct ibuf *buf)  {  	return (buf->max - buf->wpos);  } -void -ibuf_close(struct msgbuf *msgbuf, struct ibuf *buf) +void ibuf_close(struct msgbuf *msgbuf, struct ibuf *buf)  {  	ibuf_enqueue(msgbuf, buf);  } -int -ibuf_write(struct msgbuf *msgbuf) +int ibuf_write(struct msgbuf *msgbuf)  { -	struct iovec	 iov[IOV_MAX]; -	struct ibuf	*buf; -	unsigned int	 i = 0; -	ssize_t	n; +	struct iovec iov[IOV_MAX]; +	struct ibuf *buf; +	unsigned int i = 0; +	ssize_t n;  	memset(&iov, 0, sizeof(iov)); -	TAILQ_FOREACH(buf, &msgbuf->bufs, entry) { +	TAILQ_FOREACH(buf, &msgbuf->bufs, entry) +	{  		if (i >= IOV_MAX)  			break;  		iov[i].iov_base = buf->buf + buf->rpos; @@ -159,7 +150,7 @@ again:  		return (-1);  	} -	if (n == 0) {			/* connection closed */ +	if (n == 0) { /* connection closed */  		errno = 0;  		return (0);  	} @@ -169,8 +160,7 @@ again:  	return (1);  } -void -ibuf_free(struct ibuf *buf) +void ibuf_free(struct ibuf *buf)  {  	if (buf == NULL)  		return; @@ -178,21 +168,19 @@ ibuf_free(struct ibuf *buf)  	free(buf);  } -void -msgbuf_init(struct msgbuf *msgbuf) +void msgbuf_init(struct msgbuf *msgbuf)  {  	msgbuf->queued = 0;  	msgbuf->fd = -1;  	TAILQ_INIT(&msgbuf->bufs);  } -void -msgbuf_drain(struct msgbuf *msgbuf, size_t n) +void msgbuf_drain(struct msgbuf *msgbuf, size_t n)  { -	struct ibuf	*buf, *next; +	struct ibuf *buf, *next;  	for (buf = TAILQ_FIRST(&msgbuf->bufs); buf != NULL && n > 0; -	    buf = next) { +	     buf = next) {  		next = TAILQ_NEXT(buf, entry);  		if (buf->rpos + n >= buf->wpos) {  			n -= buf->wpos - buf->rpos; @@ -204,33 +192,32 @@ msgbuf_drain(struct msgbuf *msgbuf, size_t n)  	}  } -void -msgbuf_clear(struct msgbuf *msgbuf) +void msgbuf_clear(struct msgbuf *msgbuf)  { -	struct ibuf	*buf; +	struct ibuf *buf;  	while ((buf = TAILQ_FIRST(&msgbuf->bufs)) != NULL)  		ibuf_dequeue(msgbuf, buf);  } -int -msgbuf_write(struct msgbuf *msgbuf) +int msgbuf_write(struct msgbuf *msgbuf)  { -	struct iovec	 iov[IOV_MAX]; -	struct ibuf	*buf; -	unsigned int	 i = 0; -	ssize_t		 n; -	struct msghdr	 msg; -	struct cmsghdr	*cmsg; +	struct iovec iov[IOV_MAX]; +	struct ibuf *buf; +	unsigned int i = 0; +	ssize_t n; +	struct msghdr msg; +	struct cmsghdr *cmsg;  	union { -		struct cmsghdr	hdr; -		char		buf[CMSG_SPACE(sizeof(int))]; +		struct cmsghdr hdr; +		char buf[CMSG_SPACE(sizeof(int))];  	} cmsgbuf;  	memset(&iov, 0, sizeof(iov));  	memset(&msg, 0, sizeof(msg));  	memset(&cmsgbuf, 0, sizeof(cmsgbuf)); -	TAILQ_FOREACH(buf, &msgbuf->bufs, entry) { +	TAILQ_FOREACH(buf, &msgbuf->bufs, entry) +	{  		if (i >= IOV_MAX)  			break;  		iov[i].iov_base = buf->buf + buf->rpos; @@ -262,7 +249,7 @@ again:  		return (-1);  	} -	if (n == 0) {			/* connection closed */ +	if (n == 0) { /* connection closed */  		errno = 0;  		return (0);  	} @@ -281,15 +268,13 @@ again:  	return (1);  } -void -ibuf_enqueue(struct msgbuf *msgbuf, struct ibuf *buf) +void ibuf_enqueue(struct msgbuf *msgbuf, struct ibuf *buf)  {  	TAILQ_INSERT_TAIL(&msgbuf->bufs, buf, entry);  	msgbuf->queued++;  } -void -ibuf_dequeue(struct msgbuf *msgbuf, struct ibuf *buf) +void ibuf_dequeue(struct msgbuf *msgbuf, struct ibuf *buf)  {  	TAILQ_REMOVE(&msgbuf->bufs, buf, entry); diff --git a/lib/imsg.c b/lib/imsg.c index fc62c13734..10650f648a 100644 --- a/lib/imsg.c +++ b/lib/imsg.c @@ -21,22 +21,21 @@  #include "openbsd-queue.h"  #include "imsg.h" -int	 imsg_fd_overhead = 0; +int imsg_fd_overhead = 0; -int	 imsg_get_fd(struct imsgbuf *); +int imsg_get_fd(struct imsgbuf *);  #ifndef __OpenBSD__  /*   * The original code calls getdtablecount() which is OpenBSD specific. Use   * available_fds() from OpenSMTPD instead.   */ -static int -available_fds(unsigned int n) +static int available_fds(unsigned int n)  { -	unsigned int	i; -	int		ret, fds[256]; +	unsigned int i; +	int ret, fds[256]; -	if (n > (sizeof(fds)/sizeof(fds[0]))) +	if (n > (sizeof(fds) / sizeof(fds[0])))  		return (1);  	ret = 0; @@ -59,8 +58,7 @@ available_fds(unsigned int n)  }  #endif -void -imsg_init(struct imsgbuf *ibuf, int fd) +void imsg_init(struct imsgbuf *ibuf, int fd)  {  	msgbuf_init(&ibuf->w);  	memset(&ibuf->r, 0, sizeof(ibuf->r)); @@ -70,19 +68,18 @@ imsg_init(struct imsgbuf *ibuf, int fd)  	TAILQ_INIT(&ibuf->fds);  } -ssize_t -imsg_read(struct imsgbuf *ibuf) +ssize_t imsg_read(struct imsgbuf *ibuf)  { -	struct msghdr		 msg; -	struct cmsghdr		*cmsg; +	struct msghdr msg; +	struct cmsghdr *cmsg;  	union {  		struct cmsghdr hdr; -		char	buf[CMSG_SPACE(sizeof(int) * 1)]; +		char buf[CMSG_SPACE(sizeof(int) * 1)];  	} cmsgbuf; -	struct iovec		 iov; -	ssize_t			 n = -1; -	int			 fd; -	struct imsg_fd		*ifd; +	struct iovec iov; +	ssize_t n = -1; +	int fd; +	struct imsg_fd *ifd;  	memset(&msg, 0, sizeof(msg));  	memset(&cmsgbuf, 0, sizeof(cmsgbuf)); @@ -99,12 +96,14 @@ imsg_read(struct imsgbuf *ibuf)  again:  #ifdef __OpenBSD__ -	if (getdtablecount() + imsg_fd_overhead + -	    (int)((CMSG_SPACE(sizeof(int))-CMSG_SPACE(0))/sizeof(int)) +	if (getdtablecount() + imsg_fd_overhead +		    + (int)((CMSG_SPACE(sizeof(int)) - CMSG_SPACE(0)) +			    / sizeof(int))  	    >= getdtablesize()) {  #else -	if (available_fds(imsg_fd_overhead + -	    (CMSG_SPACE(sizeof(int))-CMSG_SPACE(0))/sizeof(int))) { +	if (available_fds(imsg_fd_overhead +			  + (CMSG_SPACE(sizeof(int)) - CMSG_SPACE(0)) +				    / sizeof(int))) {  #endif  		errno = EAGAIN;  		free(ifd); @@ -120,9 +119,9 @@ again:  	ibuf->r.wpos += n;  	for (cmsg = CMSG_FIRSTHDR(&msg); cmsg != NULL; -	    cmsg = CMSG_NXTHDR(&msg, cmsg)) { -		if (cmsg->cmsg_level == SOL_SOCKET && -		    cmsg->cmsg_type == SCM_RIGHTS) { +	     cmsg = CMSG_NXTHDR(&msg, cmsg)) { +		if (cmsg->cmsg_level == SOL_SOCKET +		    && cmsg->cmsg_type == SCM_RIGHTS) {  			int i;  			int j; @@ -131,14 +130,15 @@ again:  			 * padding rules, our control buffer might contain  			 * more than one fd, and we must close them.  			 */ -			j = ((char *)cmsg + cmsg->cmsg_len - -			    (char *)CMSG_DATA(cmsg)) / sizeof(int); +			j = ((char *)cmsg + cmsg->cmsg_len +			     - (char *)CMSG_DATA(cmsg)) +			    / sizeof(int);  			for (i = 0; i < j; i++) {  				fd = ((int *)CMSG_DATA(cmsg))[i];  				if (ifd != NULL) {  					ifd->fd = fd;  					TAILQ_INSERT_TAIL(&ibuf->fds, ifd, -					    entry); +							  entry);  					ifd = NULL;  				} else  					close(fd); @@ -152,10 +152,9 @@ fail:  	return (n);  } -ssize_t -imsg_get(struct imsgbuf *ibuf, struct imsg *imsg) +ssize_t imsg_get(struct imsgbuf *ibuf, struct imsg *imsg)  { -	size_t			 av, left, datalen; +	size_t av, left, datalen;  	av = ibuf->r.wpos; @@ -163,8 +162,7 @@ imsg_get(struct imsgbuf *ibuf, struct imsg *imsg)  		return (0);  	memcpy(&imsg->hdr, ibuf->r.buf, sizeof(imsg->hdr)); -	if (imsg->hdr.len < IMSG_HEADER_SIZE || -	    imsg->hdr.len > MAX_IMSGSIZE) { +	if (imsg->hdr.len < IMSG_HEADER_SIZE || imsg->hdr.len > MAX_IMSGSIZE) {  		errno = ERANGE;  		return (-1);  	} @@ -183,7 +181,7 @@ imsg_get(struct imsgbuf *ibuf, struct imsg *imsg)  		imsg->fd = -1;  	if (imsg->data) -	  memcpy(imsg->data, ibuf->r.rptr, datalen); +		memcpy(imsg->data, ibuf->r.rptr, datalen);  	if (imsg->hdr.len < av) {  		left = av - imsg->hdr.len; @@ -195,11 +193,10 @@ imsg_get(struct imsgbuf *ibuf, struct imsg *imsg)  	return (datalen + IMSG_HEADER_SIZE);  } -int -imsg_compose(struct imsgbuf *ibuf, u_int32_t type, u_int32_t peerid, -    pid_t pid, int fd, const void *data, u_int16_t datalen) +int imsg_compose(struct imsgbuf *ibuf, u_int32_t type, u_int32_t peerid, +		 pid_t pid, int fd, const void *data, u_int16_t datalen)  { -	struct ibuf	*wbuf; +	struct ibuf *wbuf;  	if ((wbuf = imsg_create(ibuf, type, peerid, pid, datalen)) == NULL)  		return (-1); @@ -214,12 +211,11 @@ imsg_compose(struct imsgbuf *ibuf, u_int32_t type, u_int32_t peerid,  	return (1);  } -int -imsg_composev(struct imsgbuf *ibuf, u_int32_t type, u_int32_t peerid, -    pid_t pid, int fd, const struct iovec *iov, int iovcnt) +int imsg_composev(struct imsgbuf *ibuf, u_int32_t type, u_int32_t peerid, +		  pid_t pid, int fd, const struct iovec *iov, int iovcnt)  { -	struct ibuf	*wbuf; -	int		 i, datalen = 0; +	struct ibuf *wbuf; +	int i, datalen = 0;  	for (i = 0; i < iovcnt; i++)  		datalen += iov[i].iov_len; @@ -239,12 +235,11 @@ imsg_composev(struct imsgbuf *ibuf, u_int32_t type, u_int32_t peerid,  }  /* ARGSUSED */ -struct ibuf * -imsg_create(struct imsgbuf *ibuf, u_int32_t type, u_int32_t peerid, -    pid_t pid, u_int16_t datalen) +struct ibuf *imsg_create(struct imsgbuf *ibuf, u_int32_t type, u_int32_t peerid, +			 pid_t pid, u_int16_t datalen)  { -	struct ibuf	*wbuf; -	struct imsg_hdr	 hdr; +	struct ibuf *wbuf; +	struct imsg_hdr hdr;  	datalen += IMSG_HEADER_SIZE;  	if (datalen > MAX_IMSGSIZE) { @@ -266,8 +261,7 @@ imsg_create(struct imsgbuf *ibuf, u_int32_t type, u_int32_t peerid,  	return (wbuf);  } -int -imsg_add(struct ibuf *msg, const void *data, u_int16_t datalen) +int imsg_add(struct ibuf *msg, const void *data, u_int16_t datalen)  {  	if (datalen)  		if (ibuf_add(msg, data, datalen) == -1) { @@ -277,10 +271,9 @@ imsg_add(struct ibuf *msg, const void *data, u_int16_t datalen)  	return (datalen);  } -void -imsg_close(struct imsgbuf *ibuf, struct ibuf *msg) +void imsg_close(struct imsgbuf *ibuf, struct ibuf *msg)  { -	struct imsg_hdr	*hdr; +	struct imsg_hdr *hdr;  	hdr = (struct imsg_hdr *)msg->buf; @@ -293,17 +286,15 @@ imsg_close(struct imsgbuf *ibuf, struct ibuf *msg)  	ibuf_close(&ibuf->w, msg);  } -void -imsg_free(struct imsg *imsg) +void imsg_free(struct imsg *imsg)  {  	free(imsg->data);  } -int -imsg_get_fd(struct imsgbuf *ibuf) +int imsg_get_fd(struct imsgbuf *ibuf)  { -	int		 fd; -	struct imsg_fd	*ifd; +	int fd; +	struct imsg_fd *ifd;  	if ((ifd = TAILQ_FIRST(&ibuf->fds)) == NULL)  		return (-1); @@ -315,8 +306,7 @@ imsg_get_fd(struct imsgbuf *ibuf)  	return (fd);  } -int -imsg_flush(struct imsgbuf *ibuf) +int imsg_flush(struct imsgbuf *ibuf)  {  	while (ibuf->w.queued)  		if (msgbuf_write(&ibuf->w) <= 0) @@ -324,10 +314,9 @@ imsg_flush(struct imsgbuf *ibuf)  	return (0);  } -void -imsg_clear(struct imsgbuf *ibuf) +void imsg_clear(struct imsgbuf *ibuf)  { -	int	fd; +	int fd;  	msgbuf_clear(&ibuf->w);  	while ((fd = imsg_get_fd(ibuf)) != -1) diff --git a/lib/imsg.h b/lib/imsg.h index d053d01956..ddaf71344e 100644 --- a/lib/imsg.h +++ b/lib/imsg.h @@ -26,87 +26,87 @@  #define MAX_IMSGSIZE		16384  struct ibuf { -	TAILQ_ENTRY(ibuf)	 entry; -	u_char			*buf; -	size_t			 size; -	size_t			 max; -	size_t			 wpos; -	size_t			 rpos; -	int			 fd; +	TAILQ_ENTRY(ibuf) entry; +	u_char *buf; +	size_t size; +	size_t max; +	size_t wpos; +	size_t rpos; +	int fd;  };  struct msgbuf { -	TAILQ_HEAD(, ibuf)	 bufs; -	u_int32_t		 queued; -	int			 fd; +	TAILQ_HEAD(, ibuf) bufs; +	u_int32_t queued; +	int fd;  };  struct ibuf_read { -	u_char			 buf[IBUF_READ_SIZE]; -	u_char			*rptr; -	size_t			 wpos; +	u_char buf[IBUF_READ_SIZE]; +	u_char *rptr; +	size_t wpos;  };  struct imsg_fd { -	TAILQ_ENTRY(imsg_fd)	entry; -	int			fd; +	TAILQ_ENTRY(imsg_fd) entry; +	int fd;  };  struct imsgbuf { -	TAILQ_HEAD(, imsg_fd)	 fds; -	struct ibuf_read	 r; -	struct msgbuf		 w; -	int			 fd; -	pid_t			 pid; +	TAILQ_HEAD(, imsg_fd) fds; +	struct ibuf_read r; +	struct msgbuf w; +	int fd; +	pid_t pid;  };  #define IMSGF_HASFD	1  struct imsg_hdr { -	u_int32_t	 type; -	u_int16_t	 len; -	u_int16_t	 flags; -	u_int32_t	 peerid; -	u_int32_t	 pid; +	u_int32_t type; +	u_int16_t len; +	u_int16_t flags; +	u_int32_t peerid; +	u_int32_t pid;  };  struct imsg { -	struct imsg_hdr	 hdr; -	int		 fd; -	void		*data; +	struct imsg_hdr hdr; +	int fd; +	void *data;  };  /* buffer.c */ -struct ibuf	*ibuf_open(size_t); -struct ibuf	*ibuf_dynamic(size_t, size_t); -int		 ibuf_add(struct ibuf *, const void *, size_t); -void		*ibuf_reserve(struct ibuf *, size_t); -void		*ibuf_seek(struct ibuf *, size_t, size_t); -size_t		 ibuf_size(struct ibuf *); -size_t		 ibuf_left(struct ibuf *); -void		 ibuf_close(struct msgbuf *, struct ibuf *); -int		 ibuf_write(struct msgbuf *); -void		 ibuf_free(struct ibuf *); -void		 msgbuf_init(struct msgbuf *); -void		 msgbuf_clear(struct msgbuf *); -int		 msgbuf_write(struct msgbuf *); -void		 msgbuf_drain(struct msgbuf *, size_t); +struct ibuf *ibuf_open(size_t); +struct ibuf *ibuf_dynamic(size_t, size_t); +int ibuf_add(struct ibuf *, const void *, size_t); +void *ibuf_reserve(struct ibuf *, size_t); +void *ibuf_seek(struct ibuf *, size_t, size_t); +size_t ibuf_size(struct ibuf *); +size_t ibuf_left(struct ibuf *); +void ibuf_close(struct msgbuf *, struct ibuf *); +int ibuf_write(struct msgbuf *); +void ibuf_free(struct ibuf *); +void msgbuf_init(struct msgbuf *); +void msgbuf_clear(struct msgbuf *); +int msgbuf_write(struct msgbuf *); +void msgbuf_drain(struct msgbuf *, size_t);  /* imsg.c */ -void	 imsg_init(struct imsgbuf *, int); -ssize_t	 imsg_read(struct imsgbuf *); -ssize_t	 imsg_get(struct imsgbuf *, struct imsg *); -int	 imsg_compose(struct imsgbuf *, u_int32_t, u_int32_t, pid_t, -	    int, const void *, u_int16_t); -int	 imsg_composev(struct imsgbuf *, u_int32_t, u_int32_t,  pid_t, -	    int, const struct iovec *, int); +void imsg_init(struct imsgbuf *, int); +ssize_t imsg_read(struct imsgbuf *); +ssize_t imsg_get(struct imsgbuf *, struct imsg *); +int imsg_compose(struct imsgbuf *, u_int32_t, u_int32_t, pid_t, int, +		 const void *, u_int16_t); +int imsg_composev(struct imsgbuf *, u_int32_t, u_int32_t, pid_t, int, +		  const struct iovec *, int);  struct ibuf *imsg_create(struct imsgbuf *, u_int32_t, u_int32_t, pid_t, -	    u_int16_t); -int	 imsg_add(struct ibuf *, const void *, u_int16_t); -void	 imsg_close(struct imsgbuf *, struct ibuf *); -void	 imsg_free(struct imsg *); -int	 imsg_flush(struct imsgbuf *); -void	 imsg_clear(struct imsgbuf *); +			 u_int16_t); +int imsg_add(struct ibuf *, const void *, u_int16_t); +void imsg_close(struct imsgbuf *, struct ibuf *); +void imsg_free(struct imsg *); +int imsg_flush(struct imsgbuf *); +void imsg_clear(struct imsgbuf *);  #endif diff --git a/lib/jhash.c b/lib/jhash.c index 6154c34630..8b646b8e2d 100644 --- a/lib/jhash.c +++ b/lib/jhash.c @@ -24,118 +24,127 @@  #define JHASH_GOLDEN_RATIO  0x9e3779b9  /* NOTE: Arguments are modified. */ -#define __jhash_mix(a, b, c) \ -{ \ -  a -= b; a -= c; a ^= (c>>13); \ -  b -= c; b -= a; b ^= (a<<8); \ -  c -= a; c -= b; c ^= (b>>13); \ -  a -= b; a -= c; a ^= (c>>12);  \ -  b -= c; b -= a; b ^= (a<<16); \ -  c -= a; c -= b; c ^= (b>>5); \ -  a -= b; a -= c; a ^= (c>>3);  \ -  b -= c; b -= a; b ^= (a<<10); \ -  c -= a; c -= b; c ^= (b>>15); \ -} +#define __jhash_mix(a, b, c)                                                   \ +	{                                                                      \ +		a -= b;                                                        \ +		a -= c;                                                        \ +		a ^= (c >> 13);                                                \ +		b -= c;                                                        \ +		b -= a;                                                        \ +		b ^= (a << 8);                                                 \ +		c -= a;                                                        \ +		c -= b;                                                        \ +		c ^= (b >> 13);                                                \ +		a -= b;                                                        \ +		a -= c;                                                        \ +		a ^= (c >> 12);                                                \ +		b -= c;                                                        \ +		b -= a;                                                        \ +		b ^= (a << 16);                                                \ +		c -= a;                                                        \ +		c -= b;                                                        \ +		c ^= (b >> 5);                                                 \ +		a -= b;                                                        \ +		a -= c;                                                        \ +		a ^= (c >> 3);                                                 \ +		b -= c;                                                        \ +		b -= a;                                                        \ +		b ^= (a << 10);                                                \ +		c -= a;                                                        \ +		c -= b;                                                        \ +		c ^= (b >> 15);                                                \ +	}  /* The most generic version, hashes an arbitrary sequence   * of bytes.  No alignment or length assumptions are made about   * the input key.   */ -u_int32_t -jhash (const void *key, u_int32_t length, u_int32_t initval) +u_int32_t jhash(const void *key, u_int32_t length, u_int32_t initval)  { -  u_int32_t a, b, c, len; -  const u_int8_t *k = key; - -  len = length; -  a = b = JHASH_GOLDEN_RATIO; -  c = initval; - -  while (len >= 12) -    { -      a += -        (k[0] + ((u_int32_t) k[1] << 8) + ((u_int32_t) k[2] << 16) + -         ((u_int32_t) k[3] << 24)); -      b += -        (k[4] + ((u_int32_t) k[5] << 8) + ((u_int32_t) k[6] << 16) + -         ((u_int32_t) k[7] << 24)); -      c += -        (k[8] + ((u_int32_t) k[9] << 8) + ((u_int32_t) k[10] << 16) + -         ((u_int32_t) k[11] << 24)); - -      __jhash_mix (a, b, c); - -      k += 12; -      len -= 12; -    } - -  c += length; -  switch (len) -    { -    case 11: -      c += ((u_int32_t) k[10] << 24); -    case 10: -      c += ((u_int32_t) k[9] << 16); -    case 9: -      c += ((u_int32_t) k[8] << 8); -    case 8: -      b += ((u_int32_t) k[7] << 24); -    case 7: -      b += ((u_int32_t) k[6] << 16); -    case 6: -      b += ((u_int32_t) k[5] << 8); -    case 5: -      b += k[4]; -    case 4: -      a += ((u_int32_t) k[3] << 24); -    case 3: -      a += ((u_int32_t) k[2] << 16); -    case 2: -      a += ((u_int32_t) k[1] << 8); -    case 1: -      a += k[0]; -    }; - -  __jhash_mix (a, b, c); - -  return c; +	u_int32_t a, b, c, len; +	const u_int8_t *k = key; + +	len = length; +	a = b = JHASH_GOLDEN_RATIO; +	c = initval; + +	while (len >= 12) { +		a += (k[0] + ((u_int32_t)k[1] << 8) + ((u_int32_t)k[2] << 16) +		      + ((u_int32_t)k[3] << 24)); +		b += (k[4] + ((u_int32_t)k[5] << 8) + ((u_int32_t)k[6] << 16) +		      + ((u_int32_t)k[7] << 24)); +		c += (k[8] + ((u_int32_t)k[9] << 8) + ((u_int32_t)k[10] << 16) +		      + ((u_int32_t)k[11] << 24)); + +		__jhash_mix(a, b, c); + +		k += 12; +		len -= 12; +	} + +	c += length; +	switch (len) { +	case 11: +		c += ((u_int32_t)k[10] << 24); +	case 10: +		c += ((u_int32_t)k[9] << 16); +	case 9: +		c += ((u_int32_t)k[8] << 8); +	case 8: +		b += ((u_int32_t)k[7] << 24); +	case 7: +		b += ((u_int32_t)k[6] << 16); +	case 6: +		b += ((u_int32_t)k[5] << 8); +	case 5: +		b += k[4]; +	case 4: +		a += ((u_int32_t)k[3] << 24); +	case 3: +		a += ((u_int32_t)k[2] << 16); +	case 2: +		a += ((u_int32_t)k[1] << 8); +	case 1: +		a += k[0]; +	}; + +	__jhash_mix(a, b, c); + +	return c;  }  /* A special optimized version that handles 1 or more of u_int32_ts.   * The length parameter here is the number of u_int32_ts in the key.   */ -u_int32_t -jhash2 (const u_int32_t *k, u_int32_t length, u_int32_t initval) +u_int32_t jhash2(const u_int32_t *k, u_int32_t length, u_int32_t initval)  { -  u_int32_t a, b, c, len; - -  a = b = JHASH_GOLDEN_RATIO; -  c = initval; -  len = length; - -  while (len >= 3) -    { -      a += k[0]; -      b += k[1]; -      c += k[2]; -      __jhash_mix (a, b, c); -      k += 3; -      len -= 3; -    } - -  c += length * 4; - -  switch (len) -    { -    case 2: -      b += k[1]; -    case 1: -      a += k[0]; -    }; - -  __jhash_mix (a, b, c); - -  return c; +	u_int32_t a, b, c, len; + +	a = b = JHASH_GOLDEN_RATIO; +	c = initval; +	len = length; + +	while (len >= 3) { +		a += k[0]; +		b += k[1]; +		c += k[2]; +		__jhash_mix(a, b, c); +		k += 3; +		len -= 3; +	} + +	c += length * 4; + +	switch (len) { +	case 2: +		b += k[1]; +	case 1: +		a += k[0]; +	}; + +	__jhash_mix(a, b, c); + +	return c;  } @@ -145,26 +154,23 @@ jhash2 (const u_int32_t *k, u_int32_t length, u_int32_t initval)   * NOTE: In partilar the "c += length; __jhash_mix(a,b,c);" normally   *       done at the end is not done here.   */ -u_int32_t -jhash_3words (u_int32_t a, u_int32_t b, u_int32_t c, u_int32_t initval) +u_int32_t jhash_3words(u_int32_t a, u_int32_t b, u_int32_t c, u_int32_t initval)  { -  a += JHASH_GOLDEN_RATIO; -  b += JHASH_GOLDEN_RATIO; -  c += initval; +	a += JHASH_GOLDEN_RATIO; +	b += JHASH_GOLDEN_RATIO; +	c += initval; -  __jhash_mix (a, b, c); +	__jhash_mix(a, b, c); -  return c; +	return c;  } -u_int32_t -jhash_2words (u_int32_t a, u_int32_t b, u_int32_t initval) +u_int32_t jhash_2words(u_int32_t a, u_int32_t b, u_int32_t initval)  { -  return jhash_3words (a, b, 0, initval); +	return jhash_3words(a, b, 0, initval);  } -u_int32_t -jhash_1word (u_int32_t a, u_int32_t initval) +u_int32_t jhash_1word(u_int32_t a, u_int32_t initval)  { -  return jhash_3words (a, 0, 0, initval); +	return jhash_3words(a, 0, 0, initval);  } diff --git a/lib/jhash.h b/lib/jhash.h index 985ac94e04..74ce6a3233 100644 --- a/lib/jhash.h +++ b/lib/jhash.h @@ -29,7 +29,8 @@ extern u_int32_t jhash(const void *key, u_int32_t length, u_int32_t initval);  /* A special optimized version that handles 1 or more of u_int32_ts.   * The length parameter here is the number of u_int32_ts in the key.   */ -extern u_int32_t jhash2(const u_int32_t *k, u_int32_t length, u_int32_t initval); +extern u_int32_t jhash2(const u_int32_t *k, u_int32_t length, +			u_int32_t initval);  /* A special ultra-optimized versions that knows they are hashing exactly   * 3, 2 or 1 word(s). @@ -37,7 +38,8 @@ extern u_int32_t jhash2(const u_int32_t *k, u_int32_t length, u_int32_t initval)   * NOTE: In partilar the "c += length; __jhash_mix(a,b,c);" normally   *       done at the end is not done here.   */ -extern u_int32_t jhash_3words(u_int32_t a, u_int32_t b, u_int32_t c, u_int32_t initval); +extern u_int32_t jhash_3words(u_int32_t a, u_int32_t b, u_int32_t c, +			      u_int32_t initval);  extern u_int32_t jhash_2words(u_int32_t a, u_int32_t b, u_int32_t initval);  extern u_int32_t jhash_1word(u_int32_t a, u_int32_t initval); diff --git a/lib/json.c b/lib/json.c index ccbecb726a..7164889e4a 100644 --- a/lib/json.c +++ b/lib/json.c @@ -29,76 +29,66 @@   * is the *last* keyword on the line no matter   * what.   */ -int -use_json (const int argc, struct cmd_token *argv[]) +int use_json(const int argc, struct cmd_token *argv[])  { -  if (argc == 0) -    return 0; +	if (argc == 0) +		return 0; -  if (argv[argc-1]->arg && strcmp(argv[argc-1]->arg, "json") == 0) -    return 1; +	if (argv[argc - 1]->arg && strcmp(argv[argc - 1]->arg, "json") == 0) +		return 1; -  return 0; +	return 0;  } -void -json_object_string_add(struct json_object* obj, const char *key, -                       const char *s) +void json_object_string_add(struct json_object *obj, const char *key, +			    const char *s)  { -  json_object_object_add(obj, key, json_object_new_string(s)); +	json_object_object_add(obj, key, json_object_new_string(s));  } -void -json_object_int_add(struct json_object* obj, const char *key, int32_t i) +void json_object_int_add(struct json_object *obj, const char *key, int32_t i)  { -  json_object_object_add(obj, key, json_object_new_int(i)); +	json_object_object_add(obj, key, json_object_new_int(i));  } -void -json_object_long_add(struct json_object* obj, const char *key, int64_t i) +void json_object_long_add(struct json_object *obj, const char *key, int64_t i)  {  #if defined(HAVE_JSON_C_JSON_H) -  json_object_object_add(obj, key, json_object_new_int64(i)); +	json_object_object_add(obj, key, json_object_new_int64(i));  #else -  json_object_object_add(obj, key, json_object_new_int((int)i)); +	json_object_object_add(obj, key, json_object_new_int((int)i));  #endif  } -void -json_object_boolean_false_add(struct json_object* obj, const char *key) +void json_object_boolean_false_add(struct json_object *obj, const char *key)  { -  json_object_object_add(obj, key, json_object_new_boolean(0)); +	json_object_object_add(obj, key, json_object_new_boolean(0));  } -void -json_object_boolean_true_add(struct json_object* obj, const char *key) +void json_object_boolean_true_add(struct json_object *obj, const char *key)  { -  json_object_object_add(obj, key, json_object_new_boolean(1)); +	json_object_object_add(obj, key, json_object_new_boolean(1));  } -struct json_object* -json_object_lock(struct json_object *obj) +struct json_object *json_object_lock(struct json_object *obj)  { -  return json_object_get(obj); +	return json_object_get(obj);  } -void -json_object_free(struct json_object *obj) +void json_object_free(struct json_object *obj)  { -  json_object_put(obj); +	json_object_put(obj);  }  #if !defined(HAVE_JSON_C_JSON_H) -int -json_object_object_get_ex(struct json_object *obj, -			  const char *key, -			  struct json_object **value) +int json_object_object_get_ex(struct json_object *obj, const char *key, +			      struct json_object **value)  { -  *value = json_object_object_get(obj, key); +	*value = json_object_object_get(obj, key); -  if (*value) -    return 1; +	if (*value) +		return 1; -  return 0; +	return 0;  }  #endif diff --git a/lib/json.h b/lib/json.h index 7e98614280..fdc2e0cbbc 100644 --- a/lib/json.h +++ b/lib/json.h @@ -33,25 +33,24 @@   */  #define json_object_to_json_string_ext(A, B) json_object_to_json_string (A) -extern int json_object_object_get_ex(struct json_object *obj, -					   const char *key, -					   struct json_object **value); +extern int json_object_object_get_ex(struct json_object *obj, const char *key, +				     struct json_object **value);  #endif  #include "command.h"  extern int use_json(const int argc, struct cmd_token *argv[]); -extern void json_object_string_add(struct json_object* obj, const char *key, -                                   const char *s); -extern void json_object_int_add(struct json_object* obj, const char *key, -                                int32_t i); -extern void json_object_long_add(struct json_object* obj, const char *key, -                                 int64_t i); -extern void json_object_boolean_false_add(struct json_object* obj, -                                          const char *key); -extern void json_object_boolean_true_add(struct json_object* obj, -                                         const char *key); -extern struct json_object* json_object_lock(struct json_object *obj); +extern void json_object_string_add(struct json_object *obj, const char *key, +				   const char *s); +extern void json_object_int_add(struct json_object *obj, const char *key, +				int32_t i); +extern void json_object_long_add(struct json_object *obj, const char *key, +				 int64_t i); +extern void json_object_boolean_false_add(struct json_object *obj, +					  const char *key); +extern void json_object_boolean_true_add(struct json_object *obj, +					 const char *key); +extern struct json_object *json_object_lock(struct json_object *obj);  extern void json_object_free(struct json_object *obj);  #define JSON_STR "JavaScript Object Notation\n" diff --git a/lib/keychain.c b/lib/keychain.c index 95a2c8e599..aca3b9e2ea 100644 --- a/lib/keychain.c +++ b/lib/keychain.c @@ -25,7 +25,7 @@ Boston, MA 02111-1307, USA.  */  #include "linklist.h"  #include "keychain.h" -DEFINE_MTYPE_STATIC(LIB, KEY,      "Key") +DEFINE_MTYPE_STATIC(LIB, KEY, "Key")  DEFINE_MTYPE_STATIC(LIB, KEYCHAIN, "Key chain")  DEFINE_QOBJ_TYPE(keychain) @@ -34,210 +34,192 @@ DEFINE_QOBJ_TYPE(key)  /* Master list of key chain. */  struct list *keychain_list; -static struct keychain * -keychain_new (void) +static struct keychain *keychain_new(void)  { -  struct keychain *keychain; -  keychain = XCALLOC (MTYPE_KEYCHAIN, sizeof (struct keychain)); -  QOBJ_REG (keychain, keychain); -  return keychain; +	struct keychain *keychain; +	keychain = XCALLOC(MTYPE_KEYCHAIN, sizeof(struct keychain)); +	QOBJ_REG(keychain, keychain); +	return keychain;  } -static void -keychain_free (struct keychain *keychain) +static void keychain_free(struct keychain *keychain)  { -  QOBJ_UNREG (keychain); -  XFREE (MTYPE_KEYCHAIN, keychain); +	QOBJ_UNREG(keychain); +	XFREE(MTYPE_KEYCHAIN, keychain);  } -static struct key * -key_new (void) +static struct key *key_new(void)  { -  struct key *key = XCALLOC (MTYPE_KEY, sizeof (struct key)); -  QOBJ_REG (key, key); -  return key; +	struct key *key = XCALLOC(MTYPE_KEY, sizeof(struct key)); +	QOBJ_REG(key, key); +	return key;  } -static void -key_free (struct key *key) +static void key_free(struct key *key)  { -  QOBJ_UNREG (key); -  XFREE (MTYPE_KEY, key); +	QOBJ_UNREG(key); +	XFREE(MTYPE_KEY, key);  } -struct keychain * -keychain_lookup (const char *name) +struct keychain *keychain_lookup(const char *name)  { -  struct listnode *node; -  struct keychain *keychain; +	struct listnode *node; +	struct keychain *keychain; -  if (name == NULL) -    return NULL; +	if (name == NULL) +		return NULL; -  for (ALL_LIST_ELEMENTS_RO (keychain_list, node, keychain)) -    { -      if (strcmp (keychain->name, name) == 0) -	return keychain; -    } -  return NULL; +	for (ALL_LIST_ELEMENTS_RO(keychain_list, node, keychain)) { +		if (strcmp(keychain->name, name) == 0) +			return keychain; +	} +	return NULL;  } -static int -key_cmp_func (void *arg1, void *arg2) +static int key_cmp_func(void *arg1, void *arg2)  { -  const struct key *k1 = arg1; -  const struct key *k2 = arg2; -   -  if (k1->index > k2->index) -    return 1; -  if (k1->index < k2->index) -    return -1; -  return 0; +	const struct key *k1 = arg1; +	const struct key *k2 = arg2; + +	if (k1->index > k2->index) +		return 1; +	if (k1->index < k2->index) +		return -1; +	return 0;  } -static void -key_delete_func (struct key *key) +static void key_delete_func(struct key *key)  { -  if (key->string) -    free (key->string); -  key_free (key); +	if (key->string) +		free(key->string); +	key_free(key);  } -static struct keychain * -keychain_get (const char *name) +static struct keychain *keychain_get(const char *name)  { -  struct keychain *keychain; +	struct keychain *keychain; -  keychain = keychain_lookup (name); +	keychain = keychain_lookup(name); -  if (keychain) -    return keychain; +	if (keychain) +		return keychain; -  keychain = keychain_new (); -  keychain->name = XSTRDUP(MTYPE_KEYCHAIN, name); -  keychain->key = list_new (); -  keychain->key->cmp = (int (*)(void *, void *)) key_cmp_func; -  keychain->key->del = (void (*)(void *)) key_delete_func; -  listnode_add (keychain_list, keychain); +	keychain = keychain_new(); +	keychain->name = XSTRDUP(MTYPE_KEYCHAIN, name); +	keychain->key = list_new(); +	keychain->key->cmp = (int (*)(void *, void *))key_cmp_func; +	keychain->key->del = (void (*)(void *))key_delete_func; +	listnode_add(keychain_list, keychain); -  return keychain; +	return keychain;  } -static void -keychain_delete (struct keychain *keychain) +static void keychain_delete(struct keychain *keychain)  { -  if (keychain->name) -    XFREE(MTYPE_KEYCHAIN, keychain->name); +	if (keychain->name) +		XFREE(MTYPE_KEYCHAIN, keychain->name); -  list_delete (keychain->key); -  listnode_delete (keychain_list, keychain); -  keychain_free (keychain); +	list_delete(keychain->key); +	listnode_delete(keychain_list, keychain); +	keychain_free(keychain);  } -static struct key * -key_lookup (const struct keychain *keychain, u_int32_t index) +static struct key *key_lookup(const struct keychain *keychain, u_int32_t index)  { -  struct listnode *node; -  struct key *key; +	struct listnode *node; +	struct key *key; -  for (ALL_LIST_ELEMENTS_RO (keychain->key, node, key)) -    { -      if (key->index == index) -	return key; -    } -  return NULL; +	for (ALL_LIST_ELEMENTS_RO(keychain->key, node, key)) { +		if (key->index == index) +			return key; +	} +	return NULL;  } -struct key * -key_lookup_for_accept (const struct keychain *keychain, u_int32_t index) +struct key *key_lookup_for_accept(const struct keychain *keychain, +				  u_int32_t index)  { -  struct listnode *node; -  struct key *key; -  time_t now; - -  now = time (NULL); - -  for (ALL_LIST_ELEMENTS_RO (keychain->key, node, key)) -    { -      if (key->index >= index) -	{ -	  if (key->accept.start == 0) -	    return key; - -	  if (key->accept.start <= now) -	    if (key->accept.end >= now || key->accept.end == -1) -	      return key; +	struct listnode *node; +	struct key *key; +	time_t now; + +	now = time(NULL); + +	for (ALL_LIST_ELEMENTS_RO(keychain->key, node, key)) { +		if (key->index >= index) { +			if (key->accept.start == 0) +				return key; + +			if (key->accept.start <= now) +				if (key->accept.end >= now +				    || key->accept.end == -1) +					return key; +		}  	} -    } -  return NULL; +	return NULL;  } -struct key * -key_match_for_accept (const struct keychain *keychain, const char *auth_str) +struct key *key_match_for_accept(const struct keychain *keychain, +				 const char *auth_str)  { -  struct listnode *node; -  struct key *key; -  time_t now; - -  now = time (NULL); - -  for (ALL_LIST_ELEMENTS_RO (keychain->key, node, key)) -    { -      if (key->accept.start == 0 || -	  (key->accept.start <= now && -	   (key->accept.end >= now || key->accept.end == -1))) -	if (strncmp (key->string, auth_str, 16) == 0) -	  return key; -    } -  return NULL; +	struct listnode *node; +	struct key *key; +	time_t now; + +	now = time(NULL); + +	for (ALL_LIST_ELEMENTS_RO(keychain->key, node, key)) { +		if (key->accept.start == 0 +		    || (key->accept.start <= now +			&& (key->accept.end >= now || key->accept.end == -1))) +			if (strncmp(key->string, auth_str, 16) == 0) +				return key; +	} +	return NULL;  } -struct key * -key_lookup_for_send (const struct keychain *keychain) +struct key *key_lookup_for_send(const struct keychain *keychain)  { -  struct listnode *node; -  struct key *key; -  time_t now; +	struct listnode *node; +	struct key *key; +	time_t now; -  now = time (NULL); +	now = time(NULL); -  for (ALL_LIST_ELEMENTS_RO (keychain->key, node, key)) -    { -      if (key->send.start == 0) -	return key; +	for (ALL_LIST_ELEMENTS_RO(keychain->key, node, key)) { +		if (key->send.start == 0) +			return key; -      if (key->send.start <= now) -	if (key->send.end >= now || key->send.end == -1) -	  return key; -    } -  return NULL; +		if (key->send.start <= now) +			if (key->send.end >= now || key->send.end == -1) +				return key; +	} +	return NULL;  } -static struct key * -key_get (const struct keychain *keychain, u_int32_t index) +static struct key *key_get(const struct keychain *keychain, u_int32_t index)  { -  struct key *key; +	struct key *key; -  key = key_lookup (keychain, index); +	key = key_lookup(keychain, index); -  if (key) -    return key; +	if (key) +		return key; -  key = key_new (); -  key->index = index; -  listnode_add_sort (keychain->key, key); +	key = key_new(); +	key->index = index; +	listnode_add_sort(keychain->key, key); -  return key; +	return key;  } -static void -key_delete (struct keychain *keychain, struct key *key) +static void key_delete(struct keychain *keychain, struct key *key)  { -  listnode_delete (keychain->key, key); +	listnode_delete(keychain->key, key); -  if (key->string) -    XFREE(MTYPE_KEY, key->string); -  key_free (key); +	if (key->string) +		XFREE(MTYPE_KEY, key->string); +	key_free(key);  }  DEFUN_NOSH (key_chain, @@ -247,13 +229,13 @@ DEFUN_NOSH (key_chain,         "Key-chain management\n"         "Key-chain name\n")  { -  int idx_word = 2; -  struct keychain *keychain; +	int idx_word = 2; +	struct keychain *keychain; -  keychain = keychain_get (argv[idx_word]->arg); -  VTY_PUSH_CONTEXT (KEYCHAIN_NODE, keychain); +	keychain = keychain_get(argv[idx_word]->arg); +	VTY_PUSH_CONTEXT(KEYCHAIN_NODE, keychain); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_key_chain, @@ -264,20 +246,20 @@ DEFUN (no_key_chain,         "Key-chain management\n"         "Key-chain name\n")  { -  int idx_word = 3; -  struct keychain *keychain; +	int idx_word = 3; +	struct keychain *keychain; -  keychain = keychain_lookup (argv[idx_word]->arg); +	keychain = keychain_lookup(argv[idx_word]->arg); -  if (! keychain) -    { -      vty_out (vty, "Can't find keychain %s%s", argv[idx_word]->arg, VTY_NEWLINE); -      return CMD_WARNING; -    } +	if (!keychain) { +		vty_out(vty, "Can't find keychain %s%s", argv[idx_word]->arg, +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  keychain_delete (keychain); +	keychain_delete(keychain); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN_NOSH (key, @@ -286,16 +268,16 @@ DEFUN_NOSH (key,         "Configure a key\n"         "Key identifier number\n")  { -  int idx_number = 1; -  VTY_DECLVAR_CONTEXT (keychain, keychain); -  struct key *key; -  u_int32_t index; - -  VTY_GET_INTEGER ("key identifier", index, argv[idx_number]->arg); -  key = key_get (keychain, index); -  VTY_PUSH_CONTEXT_SUB (KEYCHAIN_KEY_NODE, key); -   -  return CMD_SUCCESS; +	int idx_number = 1; +	VTY_DECLVAR_CONTEXT(keychain, keychain); +	struct key *key; +	u_int32_t index; + +	VTY_GET_INTEGER("key identifier", index, argv[idx_number]->arg); +	key = key_get(keychain, index); +	VTY_PUSH_CONTEXT_SUB(KEYCHAIN_KEY_NODE, key); + +	return CMD_SUCCESS;  }  DEFUN (no_key, @@ -305,24 +287,23 @@ DEFUN (no_key,         "Delete a key\n"         "Key identifier number\n")  { -  int idx_number = 2; -  VTY_DECLVAR_CONTEXT (keychain, keychain); -  struct key *key; -  u_int32_t index; -   -  VTY_GET_INTEGER ("key identifier", index, argv[idx_number]->arg); -  key = key_lookup (keychain, index); -  if (! key) -    { -      vty_out (vty, "Can't find key %d%s", index, VTY_NEWLINE); -      return CMD_WARNING; -    } - -  key_delete (keychain, key); - -  vty->node = KEYCHAIN_NODE; - -  return CMD_SUCCESS; +	int idx_number = 2; +	VTY_DECLVAR_CONTEXT(keychain, keychain); +	struct key *key; +	u_int32_t index; + +	VTY_GET_INTEGER("key identifier", index, argv[idx_number]->arg); +	key = key_lookup(keychain, index); +	if (!key) { +		vty_out(vty, "Can't find key %d%s", index, VTY_NEWLINE); +		return CMD_WARNING; +	} + +	key_delete(keychain, key); + +	vty->node = KEYCHAIN_NODE; + +	return CMD_SUCCESS;  }  DEFUN (key_string, @@ -331,14 +312,14 @@ DEFUN (key_string,         "Set key string\n"         "The key\n")  { -  int idx_line = 1; -  VTY_DECLVAR_CONTEXT_SUB (key, key); +	int idx_line = 1; +	VTY_DECLVAR_CONTEXT_SUB(key, key); -  if (key->string) -    XFREE(MTYPE_KEY, key->string); -  key->string = XSTRDUP(MTYPE_KEY, argv[idx_line]->arg); +	if (key->string) +		XFREE(MTYPE_KEY, key->string); +	key->string = XSTRDUP(MTYPE_KEY, argv[idx_line]->arg); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_key_string, @@ -348,200 +329,182 @@ DEFUN (no_key_string,         "Unset key string\n"         "The key\n")  { -  VTY_DECLVAR_CONTEXT_SUB (key, key); +	VTY_DECLVAR_CONTEXT_SUB(key, key); -  if (key->string) -    { -      XFREE(MTYPE_KEY, key->string); -      key->string = NULL; -    } +	if (key->string) { +		XFREE(MTYPE_KEY, key->string); +		key->string = NULL; +	} -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* Convert HH:MM:SS MON DAY YEAR to time_t value.  -1 is returned when     given string is malformed. */ -static time_t  -key_str2time (const char *time_str, const char *day_str, const char *month_str, -	      const char *year_str) +static time_t key_str2time(const char *time_str, const char *day_str, +			   const char *month_str, const char *year_str)  { -  int i = 0; -  char *colon; -  struct tm tm; -  time_t time; -  unsigned int sec, min, hour; -  unsigned int day, month, year; - -  const char *month_name[] =  -  { -    "January", -    "February", -    "March", -    "April", -    "May", -    "June", -    "July", -    "August", -    "September", -    "October", -    "November", -    "December", -    NULL -  }; - -#define _GET_LONG_RANGE(V,STR,MMCOND) \ -{ \ -  unsigned long tmpl; \ -  char *endptr = NULL; \ -  tmpl = strtoul ((STR), &endptr, 10); \ -  if (*endptr != '\0' || tmpl == ULONG_MAX) \ -    return -1; \ -  if (MMCOND) \ -    return -1; \ -  (V) = tmpl; \ -} -#define GET_LONG_RANGE(V,STR,MIN,MAX) \ -        _GET_LONG_RANGE(V,STR,tmpl < (MIN) || tmpl > (MAX)) -#define GET_LONG_RANGE0(V,STR,MAX) \ -        _GET_LONG_RANGE(V,STR,tmpl > (MAX)) - -  /* Check hour field of time_str. */ -  colon = strchr (time_str, ':'); -  if (colon == NULL) -    return -1; -  *colon = '\0'; - -  /* Hour must be between 0 and 23. */ -  GET_LONG_RANGE0 (hour, time_str, 23); - -  /* Check min field of time_str. */ -  time_str = colon + 1; -  colon = strchr (time_str, ':'); -  if (*time_str == '\0' || colon == NULL) -    return -1; -  *colon = '\0'; - -  /* Min must be between 0 and 59. */ -  GET_LONG_RANGE0 (min, time_str, 59); - -  /* Check sec field of time_str. */ -  time_str = colon + 1; -  if (*time_str == '\0') -    return -1; -   -  /* Sec must be between 0 and 59. */ -  GET_LONG_RANGE0 (sec, time_str, 59); -   -  /* Check day_str.  Day must be <1-31>. */ -  GET_LONG_RANGE (day, day_str, 1, 31); - -  /* Check month_str.  Month must match month_name. */ -  month = 0; -  if (strlen (month_str) >= 3) -    for (i = 0; month_name[i]; i++) -      if (strncmp (month_str, month_name[i], strlen (month_str)) == 0) -	{ -	  month = i; -	  break; +	int i = 0; +	char *colon; +	struct tm tm; +	time_t time; +	unsigned int sec, min, hour; +	unsigned int day, month, year; + +	const char *month_name[] = { +		"January",  "February", "March",  "April",     "May", +		"June",     "July",     "August", "September", "October", +		"November", "December", NULL}; + +#define _GET_LONG_RANGE(V, STR, MMCOND)                                        \ +	{                                                                      \ +		unsigned long tmpl;                                            \ +		char *endptr = NULL;                                           \ +		tmpl = strtoul((STR), &endptr, 10);                            \ +		if (*endptr != '\0' || tmpl == ULONG_MAX)                      \ +			return -1;                                             \ +		if (MMCOND)                                                    \ +			return -1;                                             \ +		(V) = tmpl;                                                    \  	} -  if (! month_name[i]) -    return -1; - -  /* Check year_str.  Year must be <1993-2035>. */ -  GET_LONG_RANGE (year, year_str, 1993, 2035); -   -  memset (&tm, 0, sizeof (struct tm)); -  tm.tm_sec = sec; -  tm.tm_min = min; -  tm.tm_hour = hour; -  tm.tm_mon = month; -  tm.tm_mday = day; -  tm.tm_year = year - 1900; -     -  time = mktime (&tm); -   -  return time; +#define GET_LONG_RANGE(V, STR, MIN, MAX)                                       \ +	_GET_LONG_RANGE(V, STR, tmpl<(MIN) || tmpl>(MAX)) +#define GET_LONG_RANGE0(V, STR, MAX) _GET_LONG_RANGE(V, STR, tmpl > (MAX)) + +	/* Check hour field of time_str. */ +	colon = strchr(time_str, ':'); +	if (colon == NULL) +		return -1; +	*colon = '\0'; + +	/* Hour must be between 0 and 23. */ +	GET_LONG_RANGE0(hour, time_str, 23); + +	/* Check min field of time_str. */ +	time_str = colon + 1; +	colon = strchr(time_str, ':'); +	if (*time_str == '\0' || colon == NULL) +		return -1; +	*colon = '\0'; + +	/* Min must be between 0 and 59. */ +	GET_LONG_RANGE0(min, time_str, 59); + +	/* Check sec field of time_str. */ +	time_str = colon + 1; +	if (*time_str == '\0') +		return -1; + +	/* Sec must be between 0 and 59. */ +	GET_LONG_RANGE0(sec, time_str, 59); + +	/* Check day_str.  Day must be <1-31>. */ +	GET_LONG_RANGE(day, day_str, 1, 31); + +	/* Check month_str.  Month must match month_name. */ +	month = 0; +	if (strlen(month_str) >= 3) +		for (i = 0; month_name[i]; i++) +			if (strncmp(month_str, month_name[i], strlen(month_str)) +			    == 0) { +				month = i; +				break; +			} +	if (!month_name[i]) +		return -1; + +	/* Check year_str.  Year must be <1993-2035>. */ +	GET_LONG_RANGE(year, year_str, 1993, 2035); + +	memset(&tm, 0, sizeof(struct tm)); +	tm.tm_sec = sec; +	tm.tm_min = min; +	tm.tm_hour = hour; +	tm.tm_mon = month; +	tm.tm_mday = day; +	tm.tm_year = year - 1900; + +	time = mktime(&tm); + +	return time;  #undef GET_LONG_RANGE  } -static int -key_lifetime_set (struct vty *vty, struct key_range *krange, -		  const char *stime_str, const char *sday_str, -		  const char *smonth_str, const char *syear_str, -		  const char *etime_str, const char *eday_str, -		  const char *emonth_str, const char *eyear_str) +static int key_lifetime_set(struct vty *vty, struct key_range *krange, +			    const char *stime_str, const char *sday_str, +			    const char *smonth_str, const char *syear_str, +			    const char *etime_str, const char *eday_str, +			    const char *emonth_str, const char *eyear_str)  { -  time_t time_start; -  time_t time_end; -   -  time_start = key_str2time (stime_str, sday_str, smonth_str, syear_str); -  if (time_start < 0) -    { -      vty_out (vty, "Malformed time value%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  time_end = key_str2time (etime_str, eday_str, emonth_str, eyear_str); - -  if (time_end < 0) -    { -      vty_out (vty, "Malformed time value%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  if (time_end <= time_start) -    { -      vty_out (vty, "Expire time is not later than start time%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  krange->start = time_start; -  krange->end = time_end; - -  return CMD_SUCCESS; +	time_t time_start; +	time_t time_end; + +	time_start = key_str2time(stime_str, sday_str, smonth_str, syear_str); +	if (time_start < 0) { +		vty_out(vty, "Malformed time value%s", VTY_NEWLINE); +		return CMD_WARNING; +	} +	time_end = key_str2time(etime_str, eday_str, emonth_str, eyear_str); + +	if (time_end < 0) { +		vty_out(vty, "Malformed time value%s", VTY_NEWLINE); +		return CMD_WARNING; +	} + +	if (time_end <= time_start) { +		vty_out(vty, "Expire time is not later than start time%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	krange->start = time_start; +	krange->end = time_end; + +	return CMD_SUCCESS;  } -static int -key_lifetime_duration_set (struct vty *vty, struct key_range *krange, -			   const char *stime_str, const char *sday_str, -			   const char *smonth_str, const char *syear_str, -			   const char *duration_str) +static int key_lifetime_duration_set(struct vty *vty, struct key_range *krange, +				     const char *stime_str, +				     const char *sday_str, +				     const char *smonth_str, +				     const char *syear_str, +				     const char *duration_str)  { -  time_t time_start; -  u_int32_t duration; -     -  time_start = key_str2time (stime_str, sday_str, smonth_str, syear_str); -  if (time_start < 0) -    { -      vty_out (vty, "Malformed time value%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  krange->start = time_start; - -  VTY_GET_INTEGER ("duration", duration, duration_str); -  krange->duration = 1; -  krange->end = time_start + duration; - -  return CMD_SUCCESS; +	time_t time_start; +	u_int32_t duration; + +	time_start = key_str2time(stime_str, sday_str, smonth_str, syear_str); +	if (time_start < 0) { +		vty_out(vty, "Malformed time value%s", VTY_NEWLINE); +		return CMD_WARNING; +	} +	krange->start = time_start; + +	VTY_GET_INTEGER("duration", duration, duration_str); +	krange->duration = 1; +	krange->end = time_start + duration; + +	return CMD_SUCCESS;  } -static int -key_lifetime_infinite_set (struct vty *vty, struct key_range *krange, -			   const char *stime_str, const char *sday_str, -			   const char *smonth_str, const char *syear_str) +static int key_lifetime_infinite_set(struct vty *vty, struct key_range *krange, +				     const char *stime_str, +				     const char *sday_str, +				     const char *smonth_str, +				     const char *syear_str)  { -  time_t time_start; -     -  time_start = key_str2time (stime_str, sday_str, smonth_str, syear_str); -  if (time_start < 0) -    { -      vty_out (vty, "Malformed time value%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  krange->start = time_start; - -  krange->end = -1; - -  return CMD_SUCCESS; +	time_t time_start; + +	time_start = key_str2time(stime_str, sday_str, smonth_str, syear_str); +	if (time_start < 0) { +		vty_out(vty, "Malformed time value%s", VTY_NEWLINE); +		return CMD_WARNING; +	} +	krange->start = time_start; + +	krange->end = -1; + +	return CMD_SUCCESS;  }  DEFUN (accept_lifetime_day_month_day_month, @@ -557,18 +520,21 @@ DEFUN (accept_lifetime_day_month_day_month,         "Month of the year to expire\n"         "Year to expire\n")  { -  int idx_hhmmss = 1; -  int idx_number = 2; -  int idx_month = 3; -  int idx_number_2 = 4; -  int idx_hhmmss_2 = 5; -  int idx_number_3 = 6; -  int idx_month_2 = 7; -  int idx_number_4 = 8; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_set (vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, -			   argv[idx_number_2]->arg, argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, argv[idx_month_2]->arg, argv[idx_number_4]->arg); +	int idx_hhmmss = 1; +	int idx_number = 2; +	int idx_month = 3; +	int idx_number_2 = 4; +	int idx_hhmmss_2 = 5; +	int idx_number_3 = 6; +	int idx_month_2 = 7; +	int idx_number_4 = 8; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_set( +		vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, +		argv[idx_month_2]->arg, argv[idx_number_4]->arg);  }  DEFUN (accept_lifetime_day_month_month_day, @@ -584,18 +550,21 @@ DEFUN (accept_lifetime_day_month_month_day,         "Day of th month to expire\n"         "Year to expire\n")  { -  int idx_hhmmss = 1; -  int idx_number = 2; -  int idx_month = 3; -  int idx_number_2 = 4; -  int idx_hhmmss_2 = 5; -  int idx_month_2 = 6; -  int idx_number_3 = 7; -  int idx_number_4 = 8; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_set (vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, -			   argv[idx_number_2]->arg, argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, argv[idx_month_2]->arg, argv[idx_number_4]->arg); +	int idx_hhmmss = 1; +	int idx_number = 2; +	int idx_month = 3; +	int idx_number_2 = 4; +	int idx_hhmmss_2 = 5; +	int idx_month_2 = 6; +	int idx_number_3 = 7; +	int idx_number_4 = 8; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_set( +		vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, +		argv[idx_month_2]->arg, argv[idx_number_4]->arg);  }  DEFUN (accept_lifetime_month_day_day_month, @@ -611,18 +580,21 @@ DEFUN (accept_lifetime_month_day_day_month,         "Month of the year to expire\n"         "Year to expire\n")  { -  int idx_hhmmss = 1; -  int idx_month = 2; -  int idx_number = 3; -  int idx_number_2 = 4; -  int idx_hhmmss_2 = 5; -  int idx_number_3 = 6; -  int idx_month_2 = 7; -  int idx_number_4 = 8; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_set (vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, -			   argv[idx_number_2]->arg, argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, argv[idx_month_2]->arg, argv[idx_number_4]->arg); +	int idx_hhmmss = 1; +	int idx_month = 2; +	int idx_number = 3; +	int idx_number_2 = 4; +	int idx_hhmmss_2 = 5; +	int idx_number_3 = 6; +	int idx_month_2 = 7; +	int idx_number_4 = 8; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_set( +		vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, +		argv[idx_month_2]->arg, argv[idx_number_4]->arg);  }  DEFUN (accept_lifetime_month_day_month_day, @@ -638,18 +610,21 @@ DEFUN (accept_lifetime_month_day_month_day,         "Day of th month to expire\n"         "Year to expire\n")  { -  int idx_hhmmss = 1; -  int idx_month = 2; -  int idx_number = 3; -  int idx_number_2 = 4; -  int idx_hhmmss_2 = 5; -  int idx_month_2 = 6; -  int idx_number_3 = 7; -  int idx_number_4 = 8; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_set (vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, -			   argv[idx_number_2]->arg, argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, argv[idx_month_2]->arg, argv[idx_number_4]->arg); +	int idx_hhmmss = 1; +	int idx_month = 2; +	int idx_number = 3; +	int idx_number_2 = 4; +	int idx_hhmmss_2 = 5; +	int idx_month_2 = 6; +	int idx_number_3 = 7; +	int idx_number_4 = 8; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_set( +		vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, +		argv[idx_month_2]->arg, argv[idx_number_4]->arg);  }  DEFUN (accept_lifetime_infinite_day_month, @@ -662,14 +637,15 @@ DEFUN (accept_lifetime_infinite_day_month,         "Year to start\n"         "Never expires")  { -  int idx_hhmmss = 1; -  int idx_number = 2; -  int idx_month = 3; -  int idx_number_2 = 4; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_infinite_set (vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, -				    argv[idx_month]->arg, argv[idx_number_2]->arg); +	int idx_hhmmss = 1; +	int idx_number = 2; +	int idx_month = 3; +	int idx_number_2 = 4; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_infinite_set( +		vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg);  }  DEFUN (accept_lifetime_infinite_month_day, @@ -682,14 +658,15 @@ DEFUN (accept_lifetime_infinite_month_day,         "Year to start\n"         "Never expires")  { -  int idx_hhmmss = 1; -  int idx_month = 2; -  int idx_number = 3; -  int idx_number_2 = 4; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_infinite_set (vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, -				    argv[idx_month]->arg, argv[idx_number_2]->arg); +	int idx_hhmmss = 1; +	int idx_month = 2; +	int idx_number = 3; +	int idx_number_2 = 4; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_infinite_set( +		vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg);  }  DEFUN (accept_lifetime_duration_day_month, @@ -703,15 +680,17 @@ DEFUN (accept_lifetime_duration_day_month,         "Duration of the key\n"         "Duration seconds\n")  { -  int idx_hhmmss = 1; -  int idx_number = 2; -  int idx_month = 3; -  int idx_number_2 = 4; -  int idx_number_3 = 6; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_duration_set (vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, -				    argv[idx_month]->arg, argv[idx_number_2]->arg, argv[idx_number_3]->arg); +	int idx_hhmmss = 1; +	int idx_number = 2; +	int idx_month = 3; +	int idx_number_2 = 4; +	int idx_number_3 = 6; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_duration_set( +		vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_number_3]->arg);  }  DEFUN (accept_lifetime_duration_month_day, @@ -725,15 +704,17 @@ DEFUN (accept_lifetime_duration_month_day,         "Duration of the key\n"         "Duration seconds\n")  { -  int idx_hhmmss = 1; -  int idx_month = 2; -  int idx_number = 3; -  int idx_number_2 = 4; -  int idx_number_3 = 6; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_duration_set (vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, -				    argv[idx_month]->arg, argv[idx_number_2]->arg, argv[idx_number_3]->arg); +	int idx_hhmmss = 1; +	int idx_month = 2; +	int idx_number = 3; +	int idx_number_2 = 4; +	int idx_number_3 = 6; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_duration_set( +		vty, &key->accept, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_number_3]->arg);  }  DEFUN (send_lifetime_day_month_day_month, @@ -749,18 +730,21 @@ DEFUN (send_lifetime_day_month_day_month,         "Month of the year to expire\n"         "Year to expire\n")  { -  int idx_hhmmss = 1; -  int idx_number = 2; -  int idx_month = 3; -  int idx_number_2 = 4; -  int idx_hhmmss_2 = 5; -  int idx_number_3 = 6; -  int idx_month_2 = 7; -  int idx_number_4 = 8; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_set (vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, argv[idx_number_2]->arg, -			   argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, argv[idx_month_2]->arg, argv[idx_number_4]->arg); +	int idx_hhmmss = 1; +	int idx_number = 2; +	int idx_month = 3; +	int idx_number_2 = 4; +	int idx_hhmmss_2 = 5; +	int idx_number_3 = 6; +	int idx_month_2 = 7; +	int idx_number_4 = 8; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_set( +		vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, +		argv[idx_month_2]->arg, argv[idx_number_4]->arg);  }  DEFUN (send_lifetime_day_month_month_day, @@ -776,18 +760,21 @@ DEFUN (send_lifetime_day_month_month_day,         "Day of th month to expire\n"         "Year to expire\n")  { -  int idx_hhmmss = 1; -  int idx_number = 2; -  int idx_month = 3; -  int idx_number_2 = 4; -  int idx_hhmmss_2 = 5; -  int idx_month_2 = 6; -  int idx_number_3 = 7; -  int idx_number_4 = 8; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_set (vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, argv[idx_number_2]->arg, -			   argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, argv[idx_month_2]->arg, argv[idx_number_4]->arg); +	int idx_hhmmss = 1; +	int idx_number = 2; +	int idx_month = 3; +	int idx_number_2 = 4; +	int idx_hhmmss_2 = 5; +	int idx_month_2 = 6; +	int idx_number_3 = 7; +	int idx_number_4 = 8; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_set( +		vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, +		argv[idx_month_2]->arg, argv[idx_number_4]->arg);  }  DEFUN (send_lifetime_month_day_day_month, @@ -803,18 +790,21 @@ DEFUN (send_lifetime_month_day_day_month,         "Month of the year to expire\n"         "Year to expire\n")  { -  int idx_hhmmss = 1; -  int idx_month = 2; -  int idx_number = 3; -  int idx_number_2 = 4; -  int idx_hhmmss_2 = 5; -  int idx_number_3 = 6; -  int idx_month_2 = 7; -  int idx_number_4 = 8; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_set (vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, argv[idx_number_2]->arg, -			   argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, argv[idx_month_2]->arg, argv[idx_number_4]->arg); +	int idx_hhmmss = 1; +	int idx_month = 2; +	int idx_number = 3; +	int idx_number_2 = 4; +	int idx_hhmmss_2 = 5; +	int idx_number_3 = 6; +	int idx_month_2 = 7; +	int idx_number_4 = 8; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_set( +		vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, +		argv[idx_month_2]->arg, argv[idx_number_4]->arg);  }  DEFUN (send_lifetime_month_day_month_day, @@ -830,18 +820,21 @@ DEFUN (send_lifetime_month_day_month_day,         "Day of th month to expire\n"         "Year to expire\n")  { -  int idx_hhmmss = 1; -  int idx_month = 2; -  int idx_number = 3; -  int idx_number_2 = 4; -  int idx_hhmmss_2 = 5; -  int idx_month_2 = 6; -  int idx_number_3 = 7; -  int idx_number_4 = 8; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_set (vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, argv[idx_number_2]->arg, -			   argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, argv[idx_month_2]->arg, argv[idx_number_4]->arg); +	int idx_hhmmss = 1; +	int idx_month = 2; +	int idx_number = 3; +	int idx_number_2 = 4; +	int idx_hhmmss_2 = 5; +	int idx_month_2 = 6; +	int idx_number_3 = 7; +	int idx_number_4 = 8; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_set( +		vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_hhmmss_2]->arg, argv[idx_number_3]->arg, +		argv[idx_month_2]->arg, argv[idx_number_4]->arg);  }  DEFUN (send_lifetime_infinite_day_month, @@ -854,14 +847,15 @@ DEFUN (send_lifetime_infinite_day_month,         "Year to start\n"         "Never expires")  { -  int idx_hhmmss = 1; -  int idx_number = 2; -  int idx_month = 3; -  int idx_number_2 = 4; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_infinite_set (vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, -				    argv[idx_number_2]->arg); +	int idx_hhmmss = 1; +	int idx_number = 2; +	int idx_month = 3; +	int idx_number_2 = 4; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_infinite_set( +		vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg);  }  DEFUN (send_lifetime_infinite_month_day, @@ -874,14 +868,15 @@ DEFUN (send_lifetime_infinite_month_day,         "Year to start\n"         "Never expires")  { -  int idx_hhmmss = 1; -  int idx_month = 2; -  int idx_number = 3; -  int idx_number_2 = 4; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_infinite_set (vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, -				    argv[idx_number_2]->arg); +	int idx_hhmmss = 1; +	int idx_month = 2; +	int idx_number = 3; +	int idx_number_2 = 4; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_infinite_set( +		vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg);  }  DEFUN (send_lifetime_duration_day_month, @@ -895,15 +890,17 @@ DEFUN (send_lifetime_duration_day_month,         "Duration of the key\n"         "Duration seconds\n")  { -  int idx_hhmmss = 1; -  int idx_number = 2; -  int idx_month = 3; -  int idx_number_2 = 4; -  int idx_number_3 = 6; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_duration_set (vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, -				    argv[idx_number_2]->arg, argv[idx_number_3]->arg); +	int idx_hhmmss = 1; +	int idx_number = 2; +	int idx_month = 3; +	int idx_number_2 = 4; +	int idx_number_3 = 6; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_duration_set( +		vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_number_3]->arg);  }  DEFUN (send_lifetime_duration_month_day, @@ -917,148 +914,157 @@ DEFUN (send_lifetime_duration_month_day,         "Duration of the key\n"         "Duration seconds\n")  { -  int idx_hhmmss = 1; -  int idx_month = 2; -  int idx_number = 3; -  int idx_number_2 = 4; -  int idx_number_3 = 6; -  VTY_DECLVAR_CONTEXT_SUB (key, key); - -  return key_lifetime_duration_set (vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, argv[idx_month]->arg, -				    argv[idx_number_2]->arg, argv[idx_number_3]->arg); +	int idx_hhmmss = 1; +	int idx_month = 2; +	int idx_number = 3; +	int idx_number_2 = 4; +	int idx_number_3 = 6; +	VTY_DECLVAR_CONTEXT_SUB(key, key); + +	return key_lifetime_duration_set( +		vty, &key->send, argv[idx_hhmmss]->arg, argv[idx_number]->arg, +		argv[idx_month]->arg, argv[idx_number_2]->arg, +		argv[idx_number_3]->arg);  } -static struct cmd_node keychain_node = -{ -  KEYCHAIN_NODE, -  "%s(config-keychain)# ", -  1 -}; +static struct cmd_node keychain_node = {KEYCHAIN_NODE, "%s(config-keychain)# ", +					1}; -static struct cmd_node keychain_key_node = -{ -  KEYCHAIN_KEY_NODE, -  "%s(config-keychain-key)# ", -  1 -}; +static struct cmd_node keychain_key_node = {KEYCHAIN_KEY_NODE, +					    "%s(config-keychain-key)# ", 1}; -static int -keychain_strftime (char *buf, int bufsiz, time_t *time) +static int keychain_strftime(char *buf, int bufsiz, time_t *time)  { -  struct tm *tm; -  size_t len; +	struct tm *tm; +	size_t len; -  tm = localtime (time); +	tm = localtime(time); -  len = strftime (buf, bufsiz, "%T %b %d %Y", tm); +	len = strftime(buf, bufsiz, "%T %b %d %Y", tm); -  return len; +	return len;  } -static int -keychain_config_write (struct vty *vty) +static int keychain_config_write(struct vty *vty)  { -  struct keychain *keychain; -  struct key *key; -  struct listnode *node; -  struct listnode *knode; -  char buf[BUFSIZ]; - -  for (ALL_LIST_ELEMENTS_RO (keychain_list, node, keychain)) -    { -      vty_out (vty, "key chain %s%s", keychain->name, VTY_NEWLINE); -       -      for (ALL_LIST_ELEMENTS_RO (keychain->key, knode, key)) -	{ -	  vty_out (vty, " key %d%s", key->index, VTY_NEWLINE); - -	  if (key->string) -	    vty_out (vty, "  key-string %s%s", key->string, VTY_NEWLINE); - -	  if (key->accept.start) -	    { -	      keychain_strftime (buf, BUFSIZ, &key->accept.start); -	      vty_out (vty, "  accept-lifetime %s", buf); - -	      if (key->accept.end == -1) -		vty_out (vty, " infinite"); -	      else if (key->accept.duration) -		vty_out (vty, " duration %ld", -			 (long)(key->accept.end - key->accept.start)); -	      else -		{ -		  keychain_strftime (buf, BUFSIZ, &key->accept.end); -		  vty_out (vty, " %s", buf); -		} -	      vty_out (vty, "%s", VTY_NEWLINE); -	    } - -	  if (key->send.start) -	    { -	      keychain_strftime (buf, BUFSIZ, &key->send.start); -	      vty_out (vty, "  send-lifetime %s", buf); - -	      if (key->send.end == -1) -		vty_out (vty, " infinite"); -	      else if (key->send.duration) -		vty_out (vty, " duration %ld", (long)(key->send.end - key->send.start)); -	      else -		{ -		  keychain_strftime (buf, BUFSIZ, &key->send.end); -		  vty_out (vty, " %s", buf); +	struct keychain *keychain; +	struct key *key; +	struct listnode *node; +	struct listnode *knode; +	char buf[BUFSIZ]; + +	for (ALL_LIST_ELEMENTS_RO(keychain_list, node, keychain)) { +		vty_out(vty, "key chain %s%s", keychain->name, VTY_NEWLINE); + +		for (ALL_LIST_ELEMENTS_RO(keychain->key, knode, key)) { +			vty_out(vty, " key %d%s", key->index, VTY_NEWLINE); + +			if (key->string) +				vty_out(vty, "  key-string %s%s", key->string, +					VTY_NEWLINE); + +			if (key->accept.start) { +				keychain_strftime(buf, BUFSIZ, +						  &key->accept.start); +				vty_out(vty, "  accept-lifetime %s", buf); + +				if (key->accept.end == -1) +					vty_out(vty, " infinite"); +				else if (key->accept.duration) +					vty_out(vty, " duration %ld", +						(long)(key->accept.end +						       - key->accept.start)); +				else { +					keychain_strftime(buf, BUFSIZ, +							  &key->accept.end); +					vty_out(vty, " %s", buf); +				} +				vty_out(vty, "%s", VTY_NEWLINE); +			} + +			if (key->send.start) { +				keychain_strftime(buf, BUFSIZ, +						  &key->send.start); +				vty_out(vty, "  send-lifetime %s", buf); + +				if (key->send.end == -1) +					vty_out(vty, " infinite"); +				else if (key->send.duration) +					vty_out(vty, " duration %ld", +						(long)(key->send.end +						       - key->send.start)); +				else { +					keychain_strftime(buf, BUFSIZ, +							  &key->send.end); +					vty_out(vty, " %s", buf); +				} +				vty_out(vty, "%s", VTY_NEWLINE); +			}  		} -	      vty_out (vty, "%s", VTY_NEWLINE); -	    } +		vty_out(vty, "!%s", VTY_NEWLINE);  	} -      vty_out (vty, "!%s", VTY_NEWLINE); -    } -  return 0; +	return 0;  } -void -keychain_init () +void keychain_init()  { -  keychain_list = list_new (); - -  install_node (&keychain_node, keychain_config_write); -  install_node (&keychain_key_node, NULL); - -  install_default (KEYCHAIN_NODE); -  install_default (KEYCHAIN_KEY_NODE); - -  install_element (CONFIG_NODE, &key_chain_cmd); -  install_element (CONFIG_NODE, &no_key_chain_cmd); -  install_element (KEYCHAIN_NODE, &key_cmd); -  install_element (KEYCHAIN_NODE, &no_key_cmd); - -  install_element (KEYCHAIN_NODE, &key_chain_cmd); -  install_element (KEYCHAIN_NODE, &no_key_chain_cmd); - -  install_element (KEYCHAIN_KEY_NODE, &key_string_cmd); -  install_element (KEYCHAIN_KEY_NODE, &no_key_string_cmd); - -  install_element (KEYCHAIN_KEY_NODE, &key_chain_cmd); -  install_element (KEYCHAIN_KEY_NODE, &no_key_chain_cmd); - -  install_element (KEYCHAIN_KEY_NODE, &key_cmd); -  install_element (KEYCHAIN_KEY_NODE, &no_key_cmd); - -  install_element (KEYCHAIN_KEY_NODE, &accept_lifetime_day_month_day_month_cmd); -  install_element (KEYCHAIN_KEY_NODE, &accept_lifetime_day_month_month_day_cmd); -  install_element (KEYCHAIN_KEY_NODE, &accept_lifetime_month_day_day_month_cmd); -  install_element (KEYCHAIN_KEY_NODE, &accept_lifetime_month_day_month_day_cmd); -  install_element (KEYCHAIN_KEY_NODE, &accept_lifetime_infinite_day_month_cmd); -  install_element (KEYCHAIN_KEY_NODE, &accept_lifetime_infinite_month_day_cmd); -  install_element (KEYCHAIN_KEY_NODE, &accept_lifetime_duration_day_month_cmd); -  install_element (KEYCHAIN_KEY_NODE, &accept_lifetime_duration_month_day_cmd); - -  install_element (KEYCHAIN_KEY_NODE, &send_lifetime_day_month_day_month_cmd); -  install_element (KEYCHAIN_KEY_NODE, &send_lifetime_day_month_month_day_cmd); -  install_element (KEYCHAIN_KEY_NODE, &send_lifetime_month_day_day_month_cmd); -  install_element (KEYCHAIN_KEY_NODE, &send_lifetime_month_day_month_day_cmd); -  install_element (KEYCHAIN_KEY_NODE, &send_lifetime_infinite_day_month_cmd); -  install_element (KEYCHAIN_KEY_NODE, &send_lifetime_infinite_month_day_cmd); -  install_element (KEYCHAIN_KEY_NODE, &send_lifetime_duration_day_month_cmd); -  install_element (KEYCHAIN_KEY_NODE, &send_lifetime_duration_month_day_cmd); +	keychain_list = list_new(); + +	install_node(&keychain_node, keychain_config_write); +	install_node(&keychain_key_node, NULL); + +	install_default(KEYCHAIN_NODE); +	install_default(KEYCHAIN_KEY_NODE); + +	install_element(CONFIG_NODE, &key_chain_cmd); +	install_element(CONFIG_NODE, &no_key_chain_cmd); +	install_element(KEYCHAIN_NODE, &key_cmd); +	install_element(KEYCHAIN_NODE, &no_key_cmd); + +	install_element(KEYCHAIN_NODE, &key_chain_cmd); +	install_element(KEYCHAIN_NODE, &no_key_chain_cmd); + +	install_element(KEYCHAIN_KEY_NODE, &key_string_cmd); +	install_element(KEYCHAIN_KEY_NODE, &no_key_string_cmd); + +	install_element(KEYCHAIN_KEY_NODE, &key_chain_cmd); +	install_element(KEYCHAIN_KEY_NODE, &no_key_chain_cmd); + +	install_element(KEYCHAIN_KEY_NODE, &key_cmd); +	install_element(KEYCHAIN_KEY_NODE, &no_key_cmd); + +	install_element(KEYCHAIN_KEY_NODE, +			&accept_lifetime_day_month_day_month_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&accept_lifetime_day_month_month_day_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&accept_lifetime_month_day_day_month_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&accept_lifetime_month_day_month_day_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&accept_lifetime_infinite_day_month_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&accept_lifetime_infinite_month_day_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&accept_lifetime_duration_day_month_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&accept_lifetime_duration_month_day_cmd); + +	install_element(KEYCHAIN_KEY_NODE, +			&send_lifetime_day_month_day_month_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&send_lifetime_day_month_month_day_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&send_lifetime_month_day_day_month_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&send_lifetime_month_day_month_day_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&send_lifetime_infinite_day_month_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&send_lifetime_infinite_month_day_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&send_lifetime_duration_day_month_cmd); +	install_element(KEYCHAIN_KEY_NODE, +			&send_lifetime_duration_month_day_cmd);  } diff --git a/lib/keychain.h b/lib/keychain.h index d3f9168a0f..cb3909fdb1 100644 --- a/lib/keychain.h +++ b/lib/keychain.h @@ -24,41 +24,38 @@  #include "qobj.h" -struct keychain -{ -  char *name; +struct keychain { +	char *name; -  struct list *key; +	struct list *key; -  QOBJ_FIELDS +	QOBJ_FIELDS  };  DECLARE_QOBJ_TYPE(keychain) -struct key_range -{ -  time_t start; -  time_t end; +struct key_range { +	time_t start; +	time_t end; -  u_char duration; +	u_char duration;  }; -struct key -{ -  u_int32_t index; +struct key { +	u_int32_t index; -  char *string; +	char *string; -  struct key_range send; -  struct key_range accept; +	struct key_range send; +	struct key_range accept; -  QOBJ_FIELDS +	QOBJ_FIELDS  };  DECLARE_QOBJ_TYPE(key) -extern void keychain_init (void); -extern struct keychain *keychain_lookup (const char *); -extern struct key *key_lookup_for_accept (const struct keychain *, u_int32_t); -extern struct key *key_match_for_accept (const struct keychain *, const char *); -extern struct key *key_lookup_for_send (const struct keychain *); +extern void keychain_init(void); +extern struct keychain *keychain_lookup(const char *); +extern struct key *key_lookup_for_accept(const struct keychain *, u_int32_t); +extern struct key *key_match_for_accept(const struct keychain *, const char *); +extern struct key *key_lookup_for_send(const struct keychain *);  #endif /* _ZEBRA_KEYCHAIN_H */ diff --git a/lib/libfrr.c b/lib/libfrr.c index de83e14f0e..3db819796c 100644 --- a/lib/libfrr.c +++ b/lib/libfrr.c @@ -30,7 +30,7 @@  #include "log_int.h"  #include "module.h" -DEFINE_HOOK(frr_late_init, (struct thread_master *tm), (tm)) +DEFINE_HOOK(frr_late_init, (struct thread_master * tm), (tm))  const char frr_sysconfdir[] = SYSCONFDIR;  const char frr_vtydir[] = DAEMON_VTY_DIR; @@ -66,14 +66,13 @@ static void opt_extend(const struct optspec *os)  #define OPTION_MODULEDIR 1002  static const struct option lo_always[] = { -	{ "help",        no_argument,       NULL, 'h' }, -	{ "version",     no_argument,       NULL, 'v' }, -	{ "daemon",      no_argument,       NULL, 'd' }, -	{ "module",      no_argument,       NULL, 'M' }, -	{ "vty_socket",  required_argument, NULL, OPTION_VTYSOCK }, -	{ "moduledir",   required_argument, NULL, OPTION_MODULEDIR }, -	{ NULL } -}; +	{"help", no_argument, NULL, 'h'}, +	{"version", no_argument, NULL, 'v'}, +	{"daemon", no_argument, NULL, 'd'}, +	{"module", no_argument, NULL, 'M'}, +	{"vty_socket", required_argument, NULL, OPTION_VTYSOCK}, +	{"moduledir", required_argument, NULL, OPTION_MODULEDIR}, +	{NULL}};  static const struct optspec os_always = {  	"hvdM:",  	"  -h, --help         Display this help and exit\n" @@ -82,60 +81,47 @@ static const struct optspec os_always = {  	"  -M, --module       Load specified module\n"  	"      --vty_socket   Override vty socket path\n"  	"      --moduledir    Override modules directory\n", -	lo_always -}; +	lo_always};  static const struct option lo_cfg_pid_dry[] = { -	{ "pid_file",    required_argument, NULL, 'i' }, -	{ "config_file", required_argument, NULL, 'f' }, -	{ "dryrun",      no_argument,       NULL, 'C' }, -	{ NULL } -}; +	{"pid_file", required_argument, NULL, 'i'}, +	{"config_file", required_argument, NULL, 'f'}, +	{"dryrun", no_argument, NULL, 'C'}, +	{NULL}};  static const struct optspec os_cfg_pid_dry = {  	"f:i:C",  	"  -f, --config_file  Set configuration file name\n"  	"  -i, --pid_file     Set process identifier file name\n"  	"  -C, --dryrun       Check configuration for validity and exit\n", -	lo_cfg_pid_dry -}; +	lo_cfg_pid_dry};  static const struct option lo_zclient[] = { -	{ "socket", required_argument, NULL, 'z' }, -	{ NULL } -}; +	{"socket", required_argument, NULL, 'z'}, +	{NULL}};  static const struct optspec os_zclient = { -	"z:", -	"  -z, --socket       Set path of zebra socket\n", -	lo_zclient -}; +	"z:", "  -z, --socket       Set path of zebra socket\n", lo_zclient};  static const struct option lo_vty[] = { -	{ "vty_addr",   required_argument, NULL, 'A'}, -	{ "vty_port",   required_argument, NULL, 'P'}, -	{ NULL } -}; +	{"vty_addr", required_argument, NULL, 'A'}, +	{"vty_port", required_argument, NULL, 'P'}, +	{NULL}};  static const struct optspec os_vty = {  	"A:P:",  	"  -A, --vty_addr     Set vty's bind address\n"  	"  -P, --vty_port     Set vty's port number\n", -	lo_vty -}; +	lo_vty}; -static const struct option lo_user[] = { -	{ "user",  required_argument, NULL, 'u'}, -	{ "group", required_argument, NULL, 'g'}, -	{ NULL } -}; -static const struct optspec os_user = { -	"u:g:", -	"  -u, --user         User to run as\n" -	"  -g, --group        Group to run as\n", -	lo_user -}; +static const struct option lo_user[] = {{"user", required_argument, NULL, 'u'}, +					{"group", required_argument, NULL, 'g'}, +					{NULL}}; +static const struct optspec os_user = {"u:g:", +				       "  -u, --user         User to run as\n" +				       "  -g, --group        Group to run as\n", +				       lo_user};  static struct frr_daemon_info *di = NULL; @@ -161,15 +147,15 @@ void frr_preinit(struct frr_daemon_info *daemon, int argc, char **argv)  		opt_extend(&os_vty);  	snprintf(config_default, sizeof(config_default), "%s/%s.conf", -			frr_sysconfdir, di->name); +		 frr_sysconfdir, di->name);  	snprintf(pidfile_default, sizeof(pidfile_default), "%s/%s.pid", -			frr_vtydir, di->name); +		 frr_vtydir, di->name);  }  void frr_opt_add(const char *optstr, const struct option *longopts, -		const char *helpstr) +		 const char *helpstr)  { -	const struct optspec main_opts = { optstr, helpstr, longopts }; +	const struct optspec main_opts = {optstr, helpstr, longopts};  	opt_extend(&main_opts);  } @@ -184,11 +170,8 @@ void frr_help_exit(int status)  		di->printhelp(target);  	else  		fprintf(target, "Usage: %s [OPTION...]\n\n%s%s%s\n\n%s", -				di->progname, -				di->proghelp, -				di->copyright ? "\n\n" : "", -				di->copyright ? di->copyright : "", -				comb_helpstr); +			di->progname, di->proghelp, di->copyright ? "\n\n" : "", +			di->copyright ? di->copyright : "", comb_helpstr);  	fprintf(target, "\nReport bugs to %s\n", FRR_BUG_ADDRESS);  	exit(status);  } @@ -250,7 +233,8 @@ static int frr_opt(int opt)  		if (di->flags & FRR_NO_TCPVTY)  			return 1;  		if (vty_addr_set) { -			fprintf(stderr, "-A option specified more than once!\n"); +			fprintf(stderr, +				"-A option specified more than once!\n");  			errors++;  			break;  		} @@ -261,22 +245,25 @@ static int frr_opt(int opt)  		if (di->flags & FRR_NO_TCPVTY)  			return 1;  		if (vty_port_set) { -			fprintf(stderr, "-P option specified more than once!\n"); +			fprintf(stderr, +				"-P option specified more than once!\n");  			errors++;  			break;  		}  		vty_port_set = 1;  		di->vty_port = strtoul(optarg, &err, 0);  		if (*err || !*optarg) { -			fprintf(stderr, "invalid port number \"%s\" for -P option\n", -					optarg); +			fprintf(stderr, +				"invalid port number \"%s\" for -P option\n", +				optarg);  			errors++;  			break;  		}  		break;  	case OPTION_VTYSOCK:  		if (di->vty_sock_path) { -			fprintf(stderr, "--vty_socket option specified more than once!\n"); +			fprintf(stderr, +				"--vty_socket option specified more than once!\n");  			errors++;  			break;  		} @@ -284,7 +271,8 @@ static int frr_opt(int opt)  		break;  	case OPTION_MODULEDIR:  		if (di->module_path) { -			fprintf(stderr, "----moduledir option specified more than once!\n"); +			fprintf(stderr, +				"----moduledir option specified more than once!\n");  			errors++;  			break;  		} @@ -306,7 +294,7 @@ static int frr_opt(int opt)  	return 0;  } -int frr_getopt(int argc, char * const argv[], int *longindex) +int frr_getopt(int argc, char *const argv[], int *longindex)  {  	int opt;  	int lidx; @@ -337,10 +325,10 @@ struct thread_master *frr_init(void)  	srandom(time(NULL)); -	openzlog (di->progname, di->logname, di->instance, -			LOG_CONS|LOG_NDELAY|LOG_PID, LOG_DAEMON); +	openzlog(di->progname, di->logname, di->instance, +		 LOG_CONS | LOG_NDELAY | LOG_PID, LOG_DAEMON);  #if defined(HAVE_CUMULUS) -	zlog_set_level (ZLOG_DEST_SYSLOG, zlog_default->default_lvl); +	zlog_set_level(ZLOG_DEST_SYSLOG, zlog_default->default_lvl);  #endif  	frrmod_init(di->module); @@ -374,10 +362,11 @@ void frr_config_fork(void)  	hook_call(frr_late_init, master);  	if (di->instance) { -		snprintf(config_default, sizeof(config_default), "%s/%s-%d.conf", -				frr_sysconfdir, di->name, di->instance); -		snprintf(pidfile_default, sizeof(pidfile_default), "%s/%s-%d.pid", -				frr_vtydir, di->name, di->instance); +		snprintf(config_default, sizeof(config_default), +			 "%s/%s-%d.conf", frr_sysconfdir, di->name, +			 di->instance); +		snprintf(pidfile_default, sizeof(pidfile_default), +			 "%s/%s-%d.pid", frr_vtydir, di->name, di->instance);  	}  	vty_read_config(di->config_file, config_default); @@ -387,19 +376,19 @@ void frr_config_fork(void)  		exit(0);  	/* Daemonize. */ -	if (di->daemon_mode && daemon (0, 0) < 0) { +	if (di->daemon_mode && daemon(0, 0) < 0) {  		zlog_err("Zebra daemon failed: %s", strerror(errno));  		exit(1);  	}  	if (!di->pid_file)  		di->pid_file = pidfile_default; -	pid_output (di->pid_file); +	pid_output(di->pid_file);  }  void frr_vty_serv(void)  { -	/* allow explicit override of vty_path in the future  +	/* allow explicit override of vty_path in the future  	 * (not currently set anywhere) */  	if (!di->vty_path) {  		const char *dir; @@ -407,11 +396,10 @@ void frr_vty_serv(void)  		if (di->instance)  			snprintf(vtypath_default, sizeof(vtypath_default), -					"%s/%s-%d.vty", -					dir, di->name, di->instance); +				 "%s/%s-%d.vty", dir, di->name, di->instance);  		else  			snprintf(vtypath_default, sizeof(vtypath_default), -					"%s/%s.vty", dir, di->name); +				 "%s/%s.vty", dir, di->name);  		di->vty_path = vtypath_default;  	} @@ -427,14 +415,10 @@ void frr_run(struct thread_master *master)  	if (di->instance)  		snprintf(instanceinfo, sizeof(instanceinfo), "instance %u ", -				di->instance); - -	zlog_notice("%s %s starting: %svty@%d%s", -			di->name, -			FRR_VERSION, -			instanceinfo, -			di->vty_port, -			di->startinfo); +			 di->instance); + +	zlog_notice("%s %s starting: %svty@%d%s", di->name, FRR_VERSION, +		    instanceinfo, di->vty_port, di->startinfo);  	struct thread thread;  	while (thread_fetch(master, &thread)) diff --git a/lib/libfrr.h b/lib/libfrr.h index 0cc7ad564b..a1c3130923 100644 --- a/lib/libfrr.h +++ b/lib/libfrr.h @@ -74,30 +74,25 @@ struct frr_daemon_info {   * upcoming module support) that need to place some per-daemon things.  Each   * daemon should have one of these.   */ -#define FRR_DAEMON_INFO(execname, constname, ...) \ -	static struct frr_daemon_info execname ##_di = { \ -		.name = # execname, \ -		.logname = # constname, \ -		.module = THIS_MODULE, \ -		__VA_ARGS__ \ -	}; \ -	FRR_COREMOD_SETUP( \ -		.name = # execname, \ -		.description = # execname " daemon", \ -                .version = FRR_VERSION, \ -	) \ -	/* end */ - -extern void frr_preinit(struct frr_daemon_info *daemon, -		int argc, char **argv); -extern void frr_opt_add(const char *optstr, -		const struct option *longopts, const char *helpstr); -extern int frr_getopt(int argc, char * const argv[], int *longindex); +#define FRR_DAEMON_INFO(execname, constname, ...)                              \ +	static struct frr_daemon_info execname##_di = {.name = #execname,      \ +						       .logname = #constname,  \ +						       .module = THIS_MODULE,  \ +						       __VA_ARGS__};           \ +	FRR_COREMOD_SETUP(.name = #execname,                                   \ +			  .description = #execname " daemon",                  \ +			  .version = FRR_VERSION, )                            \ +/* end */ + +extern void frr_preinit(struct frr_daemon_info *daemon, int argc, char **argv); +extern void frr_opt_add(const char *optstr, const struct option *longopts, +			const char *helpstr); +extern int frr_getopt(int argc, char *const argv[], int *longindex);  extern void frr_help_exit(int status);  extern struct thread_master *frr_init(void); -DECLARE_HOOK(frr_late_init, (struct thread_master *tm), (tm)) +DECLARE_HOOK(frr_late_init, (struct thread_master * tm), (tm))  extern void frr_config_fork(void);  extern void frr_vty_serv(void); diff --git a/lib/linklist.c b/lib/linklist.c index 6fe91c75fc..5c33673af7 100644 --- a/lib/linklist.c +++ b/lib/linklist.c @@ -28,53 +28,48 @@ DEFINE_MTYPE_STATIC(LIB, LINK_LIST, "Link List")  DEFINE_MTYPE_STATIC(LIB, LINK_NODE, "Link Node")  /* Allocate new list. */ -struct list * -list_new (void) +struct list *list_new(void)  { -  return XCALLOC (MTYPE_LINK_LIST, sizeof (struct list)); +	return XCALLOC(MTYPE_LINK_LIST, sizeof(struct list));  }  /* Free list. */ -void -list_free (struct list *l) +void list_free(struct list *l)  { -  XFREE (MTYPE_LINK_LIST, l); +	XFREE(MTYPE_LINK_LIST, l);  }  /* Allocate new listnode.  Internal use only. */ -static struct listnode * -listnode_new (void) +static struct listnode *listnode_new(void)  { -  return XCALLOC (MTYPE_LINK_NODE, sizeof (struct listnode)); +	return XCALLOC(MTYPE_LINK_NODE, sizeof(struct listnode));  }  /* Free listnode. */ -static void -listnode_free (struct listnode *node) +static void listnode_free(struct listnode *node)  { -  XFREE (MTYPE_LINK_NODE, node); +	XFREE(MTYPE_LINK_NODE, node);  }  /* Add new data to the list. */ -void -listnode_add (struct list *list, void *val) +void listnode_add(struct list *list, void *val)  { -  struct listnode *node; -   -  assert (val != NULL); -   -  node = listnode_new (); - -  node->prev = list->tail; -  node->data = val; - -  if (list->head == NULL) -    list->head = node; -  else -    list->tail->next = node; -  list->tail = node; - -  list->count++; +	struct listnode *node; + +	assert(val != NULL); + +	node = listnode_new(); + +	node->prev = list->tail; +	node->data = val; + +	if (list->head == NULL) +		list->head = node; +	else +		list->tail->next = node; +	list->tail = node; + +	list->count++;  }  /* @@ -83,237 +78,216 @@ listnode_add (struct list *list, void *val)   * list remains sorted.  The new node is always inserted; there is no   * notion of omitting duplicates.   */ -void -listnode_add_sort (struct list *list, void *val) +void listnode_add_sort(struct list *list, void *val)  { -  struct listnode *n; -  struct listnode *new; -   -  assert (val != NULL); -   -  new = listnode_new (); -  new->data = val; - -  if (list->cmp) -    { -      for (n = list->head; n; n = n->next) -	{ -	  if ((*list->cmp) (val, n->data) < 0) -	    {	     -	      new->next = n; -	      new->prev = n->prev; - -	      if (n->prev) -		n->prev->next = new; -	      else -		list->head = new; -	      n->prev = new; -	      list->count++; -	      return; -	    } +	struct listnode *n; +	struct listnode *new; + +	assert(val != NULL); + +	new = listnode_new(); +	new->data = val; + +	if (list->cmp) { +		for (n = list->head; n; n = n->next) { +			if ((*list->cmp)(val, n->data) < 0) { +				new->next = n; +				new->prev = n->prev; + +				if (n->prev) +					n->prev->next = new; +				else +					list->head = new; +				n->prev = new; +				list->count++; +				return; +			} +		}  	} -    } -  new->prev = list->tail; +	new->prev = list->tail; -  if (list->tail) -    list->tail->next = new; -  else -    list->head = new; +	if (list->tail) +		list->tail->next = new; +	else +		list->head = new; -  list->tail = new; -  list->count++; +	list->tail = new; +	list->count++;  } -struct listnode * -listnode_add_after (struct list *list, struct listnode *pp, void *val) +struct listnode *listnode_add_after(struct list *list, struct listnode *pp, +				    void *val)  { -  struct listnode *nn; -   -  assert (val != NULL); -   -  nn = listnode_new (); -  nn->data = val; - -  if (pp == NULL) -    { -      if (list->head) -	list->head->prev = nn; -      else -	list->tail = nn; - -      nn->next = list->head; -      nn->prev = pp; - -      list->head = nn; -    } -  else -    { -      if (pp->next) -	pp->next->prev = nn; -      else -	list->tail = nn; - -      nn->next = pp->next; -      nn->prev = pp; - -      pp->next = nn; -    } -  list->count++; -  return nn; +	struct listnode *nn; + +	assert(val != NULL); + +	nn = listnode_new(); +	nn->data = val; + +	if (pp == NULL) { +		if (list->head) +			list->head->prev = nn; +		else +			list->tail = nn; + +		nn->next = list->head; +		nn->prev = pp; + +		list->head = nn; +	} else { +		if (pp->next) +			pp->next->prev = nn; +		else +			list->tail = nn; + +		nn->next = pp->next; +		nn->prev = pp; + +		pp->next = nn; +	} +	list->count++; +	return nn;  } -struct listnode * -listnode_add_before (struct list *list, struct listnode *pp, void *val) +struct listnode *listnode_add_before(struct list *list, struct listnode *pp, +				     void *val)  { -  struct listnode *nn; - -  assert (val != NULL); - -  nn = listnode_new (); -  nn->data = val; - -  if (pp == NULL) -    { -      if (list->tail) -        list->tail->next = nn; -      else -        list->head = nn; - -      nn->prev = list->tail; -      nn->next = pp; - -      list->tail = nn; -    } -  else -    { -      if (pp->prev) -	pp->prev->next = nn; -      else -	list->head = nn; - -      nn->prev = pp->prev; -      nn->next = pp; - -      pp->prev = nn; -    } -  list->count++; -  return nn; +	struct listnode *nn; + +	assert(val != NULL); + +	nn = listnode_new(); +	nn->data = val; + +	if (pp == NULL) { +		if (list->tail) +			list->tail->next = nn; +		else +			list->head = nn; + +		nn->prev = list->tail; +		nn->next = pp; + +		list->tail = nn; +	} else { +		if (pp->prev) +			pp->prev->next = nn; +		else +			list->head = nn; + +		nn->prev = pp->prev; +		nn->next = pp; + +		pp->prev = nn; +	} +	list->count++; +	return nn;  }  /* Move given listnode to tail of the list */ -void -listnode_move_to_tail (struct list *l, struct listnode *n) +void listnode_move_to_tail(struct list *l, struct listnode *n)  { -  LISTNODE_DETACH(l,n); -  LISTNODE_ATTACH(l,n); +	LISTNODE_DETACH(l, n); +	LISTNODE_ATTACH(l, n);  }  /* Delete specific date pointer from the list. */ -void -listnode_delete (struct list *list, void *val) +void listnode_delete(struct list *list, void *val)  { -  struct listnode *node; - -  assert(list); -  for (node = list->head; node; node = node->next) -    { -      if (node->data == val) -	{ -	  if (node->prev) -	    node->prev->next = node->next; -	  else -	    list->head = node->next; - -	  if (node->next) -	    node->next->prev = node->prev; -	  else -	    list->tail = node->prev; - -	  list->count--; -	  listnode_free (node); -	  return; +	struct listnode *node; + +	assert(list); +	for (node = list->head; node; node = node->next) { +		if (node->data == val) { +			if (node->prev) +				node->prev->next = node->next; +			else +				list->head = node->next; + +			if (node->next) +				node->next->prev = node->prev; +			else +				list->tail = node->prev; + +			list->count--; +			listnode_free(node); +			return; +		}  	} -    }  }  /* Return first node's data if it is there.  */ -void * -listnode_head (struct list *list) +void *listnode_head(struct list *list)  { -  struct listnode *node; +	struct listnode *node; -  assert(list); -  node = list->head; +	assert(list); +	node = list->head; -  if (node) -    return node->data; -  return NULL; +	if (node) +		return node->data; +	return NULL;  }  /* Delete all listnode from the list. */ -void -list_delete_all_node (struct list *list) +void list_delete_all_node(struct list *list)  { -  struct listnode *node; -  struct listnode *next; - -  assert(list); -  for (node = list->head; node; node = next) -    { -      next = node->next; -      if (list->del) -	(*list->del) (node->data); -      listnode_free (node); -    } -  list->head = list->tail = NULL; -  list->count = 0; +	struct listnode *node; +	struct listnode *next; + +	assert(list); +	for (node = list->head; node; node = next) { +		next = node->next; +		if (list->del) +			(*list->del)(node->data); +		listnode_free(node); +	} +	list->head = list->tail = NULL; +	list->count = 0;  }  /* Delete all listnode then free list itself. */ -void -list_delete (struct list *list) +void list_delete(struct list *list)  { -  assert(list); -  list_delete_all_node (list); -  list_free (list); +	assert(list); +	list_delete_all_node(list); +	list_free(list);  }  /* Lookup the node which has given data. */ -struct listnode * -listnode_lookup (struct list *list, void *data) +struct listnode *listnode_lookup(struct list *list, void *data)  { -  struct listnode *node; +	struct listnode *node; -  assert(list); -  for (node = listhead(list); node; node = listnextnode (node)) -    if (data == listgetdata (node)) -      return node; -  return NULL; +	assert(list); +	for (node = listhead(list); node; node = listnextnode(node)) +		if (data == listgetdata(node)) +			return node; +	return NULL;  }  /* Delete the node from list.  For ospfd and ospf6d. */ -void -list_delete_node (struct list *list, struct listnode *node) +void list_delete_node(struct list *list, struct listnode *node)  { -  if (node->prev) -    node->prev->next = node->next; -  else -    list->head = node->next; -  if (node->next) -    node->next->prev = node->prev; -  else -    list->tail = node->prev; -  list->count--; -  listnode_free (node); +	if (node->prev) +		node->prev->next = node->next; +	else +		list->head = node->next; +	if (node->next) +		node->next->prev = node->prev; +	else +		list->tail = node->prev; +	list->count--; +	listnode_free(node);  }  /* ospf_spf.c */ -void -list_add_list (struct list *l, struct list *m) +void list_add_list(struct list *l, struct list *m)  { -  struct listnode *n; +	struct listnode *n; -  for (n = listhead (m); n; n = listnextnode (n)) -    listnode_add (l, n->data); +	for (n = listhead(m); n; n = listnextnode(n)) +		listnode_add(l, n->data);  } diff --git a/lib/linklist.h b/lib/linklist.h index cd6e2f13aa..d357002646 100644 --- a/lib/linklist.h +++ b/lib/linklist.h @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_LINKLIST_H @@ -25,33 +25,31 @@  /* listnodes must always contain data to be valid. Adding an empty node   * to a list is invalid   */ -struct listnode  -{ -  struct listnode *next; -  struct listnode *prev; -   -  /* private member, use getdata() to retrieve, do not access directly */ -  void *data; +struct listnode { +	struct listnode *next; +	struct listnode *prev; + +	/* private member, use getdata() to retrieve, do not access directly */ +	void *data;  }; -struct list  -{ -  struct listnode *head; -  struct listnode *tail; +struct list { +	struct listnode *head; +	struct listnode *tail; -  /* invariant: count is the number of listnodes in the list */ -  unsigned int count; +	/* invariant: count is the number of listnodes in the list */ +	unsigned int count; -  /* -   * Returns -1 if val1 < val2, 0 if equal?, 1 if val1 > val2. -   * Used as definition of sorted for listnode_add_sort -   */ -  int (*cmp) (void *val1, void *val2); +	/* +	 * Returns -1 if val1 < val2, 0 if equal?, 1 if val1 > val2. +	 * Used as definition of sorted for listnode_add_sort +	 */ +	int (*cmp)(void *val1, void *val2); -  /* callback to free user-owned data when listnode is deleted. supplying -   * this callback is very much encouraged! -   */ -  void (*del) (void *val); +	/* callback to free user-owned data when listnode is deleted. supplying +	 * this callback is very much encouraged! +	 */ +	void (*del)(void *val);  };  #define listnextnode(X) ((X) ? ((X)->next) : NULL) @@ -62,36 +60,39 @@ struct list  #define listgetdata(X) (assert((X)->data != NULL), (X)->data)  /* Prototypes. */ -extern struct list *list_new(void); /* encouraged: set list.del callback on new lists */ -extern void list_free (struct list *); - -extern void listnode_add (struct list *, void *); -extern void listnode_add_sort (struct list *, void *); -extern struct listnode *listnode_add_after (struct list *, struct listnode *, void *); -extern struct listnode *listnode_add_before (struct list *, struct listnode *, void *); -extern void listnode_move_to_tail (struct list *, struct listnode *); -extern void listnode_delete (struct list *, void *); -extern struct listnode *listnode_lookup (struct list *, void *); -extern void *listnode_head (struct list *); - -extern void list_delete (struct list *); -extern void list_delete_all_node (struct list *); +extern struct list * +list_new(void); /* encouraged: set list.del callback on new lists */ +extern void list_free(struct list *); + +extern void listnode_add(struct list *, void *); +extern void listnode_add_sort(struct list *, void *); +extern struct listnode *listnode_add_after(struct list *, struct listnode *, +					   void *); +extern struct listnode *listnode_add_before(struct list *, struct listnode *, +					    void *); +extern void listnode_move_to_tail(struct list *, struct listnode *); +extern void listnode_delete(struct list *, void *); +extern struct listnode *listnode_lookup(struct list *, void *); +extern void *listnode_head(struct list *); + +extern void list_delete(struct list *); +extern void list_delete_all_node(struct list *);  /* For ospfd and ospf6d. */ -extern void list_delete_node (struct list *, struct listnode *); +extern void list_delete_node(struct list *, struct listnode *);  /* For ospf_spf.c */ -extern void list_add_list (struct list *, struct list *); +extern void list_add_list(struct list *, struct list *); -/* List iteration macro.  +/* List iteration macro.   * Usage: for (ALL_LIST_ELEMENTS (...) { ... }   * It is safe to delete the listnode using this macro.   */ -#define ALL_LIST_ELEMENTS(list,node,nextnode,data) \ -  (node) = listhead(list), ((data) = NULL); \ -  (node) != NULL && \ -    ((data) = listgetdata(node),(nextnode) = node->next, 1); \ -  (node) = (nextnode), ((data) = NULL) +#define ALL_LIST_ELEMENTS(list, node, nextnode, data)                          \ +	(node) = listhead(list), ((data) = NULL);                              \ +	(node) != NULL                                                         \ +		&& ((data) = listgetdata(node), (nextnode) = node->next, 1);   \ +	(node) = (nextnode), ((data) = NULL)  /* read-only list iteration macro.   * Usage: as per ALL_LIST_ELEMENTS, but not safe to delete the listnode Only @@ -99,40 +100,40 @@ extern void list_add_list (struct list *, struct list *);   * deleted in the body of the loop. Does not have forward-reference overhead   * of previous macro.   */ -#define ALL_LIST_ELEMENTS_RO(list,node,data) \ -  (node) = listhead(list), ((data) = NULL);\ -  (node) != NULL && ((data) = listgetdata(node), 1); \ -  (node) = listnextnode(node), ((data) = NULL) +#define ALL_LIST_ELEMENTS_RO(list, node, data)                                 \ +	(node) = listhead(list), ((data) = NULL);                              \ +	(node) != NULL && ((data) = listgetdata(node), 1);                     \ +	(node) = listnextnode(node), ((data) = NULL)  /* these *do not* cleanup list nodes and referenced data, as the functions   * do - these macros simply {de,at}tach a listnode from/to a list.   */ -  +  /* List node attach macro.  */ -#define LISTNODE_ATTACH(L,N) \ -  do { \ -    (N)->prev = (L)->tail; \ -    (N)->next = NULL; \ -    if ((L)->head == NULL) \ -      (L)->head = (N); \ -    else \ -      (L)->tail->next = (N); \ -    (L)->tail = (N); \ -    (L)->count++; \ -  } while (0) +#define LISTNODE_ATTACH(L, N)                                                  \ +	do {                                                                   \ +		(N)->prev = (L)->tail;                                         \ +		(N)->next = NULL;                                              \ +		if ((L)->head == NULL)                                         \ +			(L)->head = (N);                                       \ +		else                                                           \ +			(L)->tail->next = (N);                                 \ +		(L)->tail = (N);                                               \ +		(L)->count++;                                                  \ +	} while (0)  /* List node detach macro.  */ -#define LISTNODE_DETACH(L,N) \ -  do { \ -    if ((N)->prev) \ -      (N)->prev->next = (N)->next; \ -    else \ -      (L)->head = (N)->next; \ -    if ((N)->next) \ -      (N)->next->prev = (N)->prev; \ -    else \ -      (L)->tail = (N)->prev; \ -    (L)->count--; \ -  } while (0) +#define LISTNODE_DETACH(L, N)                                                  \ +	do {                                                                   \ +		if ((N)->prev)                                                 \ +			(N)->prev->next = (N)->next;                           \ +		else                                                           \ +			(L)->head = (N)->next;                                 \ +		if ((N)->next)                                                 \ +			(N)->next->prev = (N)->prev;                           \ +		else                                                           \ +			(L)->tail = (N)->prev;                                 \ +		(L)->count--;                                                  \ +	} while (0)  #endif /* _ZEBRA_LINKLIST_H */ @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #define FRR_DEFINE_DESC_TABLE @@ -39,21 +39,13 @@  DEFINE_MTYPE_STATIC(LIB, ZLOG, "Logging") -static int logfile_fd = -1;	/* Used in signal handler. */ +static int logfile_fd = -1; /* Used in signal handler. */  struct zlog *zlog_default = NULL; -const char *zlog_priority[] = -{ -  "emergencies", -  "alerts", -  "critical", -  "errors", -  "warnings", -  "notifications", -  "informational", -  "debugging", -  NULL, +const char *zlog_priority[] = { +	"emergencies",   "alerts",	"critical",  "errors", "warnings", +	"notifications", "informational", "debugging", NULL,  };  /* @@ -78,12 +70,12 @@ const char *zlog_priority[] =   * to go through and fix and test this code for correctness.   * So just wrapper the bad behavior and move on.   */ -static void write_wrapper (int fd, const void *buf, size_t count) +static void write_wrapper(int fd, const void *buf, size_t count)  { -  if (write (fd, buf, count) <= 0) -    return; +	if (write(fd, buf, count) <= 0) +		return; -  return; +	return;  }  /** @@ -98,448 +90,423 @@ static void write_wrapper (int fd, const void *buf, size_t count)   * @param nf the message to return if not found   * @return the message   */ -const char * -lookup_msg(const struct message *mz, int kz, const char *nf) +const char *lookup_msg(const struct message *mz, int kz, const char *nf)  { -  static struct message nt = { 0 }; -  const char *rz = nf ? nf : "(no message found)"; -  const struct message *pnt; -  for (pnt = mz; memcmp(pnt, &nt, sizeof(struct message)); pnt++) -    if (pnt->key == kz) { -      rz = pnt->str ? pnt->str : rz; -      break; -    } -  return rz; +	static struct message nt = {0}; +	const char *rz = nf ? nf : "(no message found)"; +	const struct message *pnt; +	for (pnt = mz; memcmp(pnt, &nt, sizeof(struct message)); pnt++) +		if (pnt->key == kz) { +			rz = pnt->str ? pnt->str : rz; +			break; +		} +	return rz;  }  /* For time string format. */ -size_t -quagga_timestamp(int timestamp_precision, char *buf, size_t buflen) +size_t quagga_timestamp(int timestamp_precision, char *buf, size_t buflen)  { -  static struct { -    time_t last; -    size_t len; -    char buf[28]; -  } cache; -  struct timeval clock; - -  gettimeofday(&clock, NULL); - -  /* first, we update the cache if the time has changed */ -  if (cache.last != clock.tv_sec) -    { -      struct tm *tm; -      cache.last = clock.tv_sec; -      tm = localtime(&cache.last); -      cache.len = strftime(cache.buf, sizeof(cache.buf), -      			   "%Y/%m/%d %H:%M:%S", tm); -    } -  /* note: it's not worth caching the subsecond part, because -     chances are that back-to-back calls are not sufficiently close together -     for the clock not to have ticked forward */ - -  if (buflen > cache.len) -    { -      memcpy(buf, cache.buf, cache.len); -      if ((timestamp_precision > 0) && -	  (buflen > cache.len+1+timestamp_precision)) -	{ -	  /* should we worry about locale issues? */ -	  static const int divisor[] = {0, 100000, 10000, 1000, 100, 10, 1}; -	  int prec; -	  char *p = buf+cache.len+1+(prec = timestamp_precision); -	  *p-- = '\0'; -	  while (prec > 6) -	    /* this is unlikely to happen, but protect anyway */ -	    { -	      *p-- = '0'; -	      prec--; -	    } -	  clock.tv_usec /= divisor[prec]; -	  do -	    { -	      *p-- = '0'+(clock.tv_usec % 10); -	      clock.tv_usec /= 10; -	    } -	  while (--prec > 0); -	  *p = '.'; -	  return cache.len+1+timestamp_precision; +	static struct { +		time_t last; +		size_t len; +		char buf[28]; +	} cache; +	struct timeval clock; + +	gettimeofday(&clock, NULL); + +	/* first, we update the cache if the time has changed */ +	if (cache.last != clock.tv_sec) { +		struct tm *tm; +		cache.last = clock.tv_sec; +		tm = localtime(&cache.last); +		cache.len = strftime(cache.buf, sizeof(cache.buf), +				     "%Y/%m/%d %H:%M:%S", tm); +	} +	/* note: it's not worth caching the subsecond part, because +	   chances are that back-to-back calls are not sufficiently close +	   together +	   for the clock not to have ticked forward */ + +	if (buflen > cache.len) { +		memcpy(buf, cache.buf, cache.len); +		if ((timestamp_precision > 0) +		    && (buflen > cache.len + 1 + timestamp_precision)) { +			/* should we worry about locale issues? */ +			static const int divisor[] = {0,   100000, 10000, 1000, +						      100, 10,     1}; +			int prec; +			char *p = buf + cache.len + 1 +				  + (prec = timestamp_precision); +			*p-- = '\0'; +			while (prec > 6) +			/* this is unlikely to happen, but protect anyway */ +			{ +				*p-- = '0'; +				prec--; +			} +			clock.tv_usec /= divisor[prec]; +			do { +				*p-- = '0' + (clock.tv_usec % 10); +				clock.tv_usec /= 10; +			} while (--prec > 0); +			*p = '.'; +			return cache.len + 1 + timestamp_precision; +		} +		buf[cache.len] = '\0'; +		return cache.len;  	} -      buf[cache.len] = '\0'; -      return cache.len; -    } -  if (buflen > 0) -    buf[0] = '\0'; -  return 0; +	if (buflen > 0) +		buf[0] = '\0'; +	return 0;  }  /* Utility routine for current time printing. */ -static void -time_print(FILE *fp, struct timestamp_control *ctl) +static void time_print(FILE *fp, struct timestamp_control *ctl)  { -  if (!ctl->already_rendered) -    { -      ctl->len = quagga_timestamp(ctl->precision, ctl->buf, sizeof(ctl->buf)); -      ctl->already_rendered = 1; -    } -  fprintf(fp, "%s ", ctl->buf); +	if (!ctl->already_rendered) { +		ctl->len = quagga_timestamp(ctl->precision, ctl->buf, +					    sizeof(ctl->buf)); +		ctl->already_rendered = 1; +	} +	fprintf(fp, "%s ", ctl->buf);  } -   +  /* va_list version of zlog. */ -void -vzlog (int priority, const char *format, va_list args) +void vzlog(int priority, const char *format, va_list args)  { -  char proto_str[32]; -  int original_errno = errno; -  struct timestamp_control tsctl; -  tsctl.already_rendered = 0; -  struct zlog *zl = zlog_default; - -  /* When zlog_default is also NULL, use stderr for logging. */ -  if (zl == NULL) -    { -      tsctl.precision = 0; -      time_print(stderr, &tsctl); -      fprintf (stderr, "%s: ", "unknown"); -      vfprintf (stderr, format, args); -      fprintf (stderr, "\n"); -      fflush (stderr); - -      /* In this case we return at here. */ -      errno = original_errno; -      return; -    } -  tsctl.precision = zl->timestamp_precision; - -  /* Syslog output */ -  if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG]) -    { -      va_list ac; -      va_copy(ac, args); -      vsyslog (priority|zlog_default->facility, format, ac); -      va_end(ac); -    } - -  if (zl->instance) -   sprintf (proto_str, "%s[%d]: ", zl->protoname, zl->instance); -  else -   sprintf (proto_str, "%s: ", zl->protoname); - -  /* File output. */ -  if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp) -    { -      va_list ac; -      time_print (zl->fp, &tsctl); -      if (zl->record_priority) -	fprintf (zl->fp, "%s: ", zlog_priority[priority]); -      fprintf (zl->fp, "%s", proto_str); -      va_copy(ac, args); -      vfprintf (zl->fp, format, ac); -      va_end(ac); -      fprintf (zl->fp, "\n"); -      fflush (zl->fp); -    } - -  /* stdout output. */ -  if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT]) -    { -      va_list ac; -      time_print (stdout, &tsctl); -      if (zl->record_priority) -	fprintf (stdout, "%s: ", zlog_priority[priority]); -      fprintf (stdout, "%s", proto_str); -      va_copy(ac, args); -      vfprintf (stdout, format, ac); -      va_end(ac); -      fprintf (stdout, "\n"); -      fflush (stdout); -    } - -  /* Terminal monitor. */ -  if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR]) -    vty_log ((zl->record_priority ? zlog_priority[priority] : NULL), -	     proto_str, format, &tsctl, args); - -  errno = original_errno; +	char proto_str[32]; +	int original_errno = errno; +	struct timestamp_control tsctl; +	tsctl.already_rendered = 0; +	struct zlog *zl = zlog_default; + +	/* When zlog_default is also NULL, use stderr for logging. */ +	if (zl == NULL) { +		tsctl.precision = 0; +		time_print(stderr, &tsctl); +		fprintf(stderr, "%s: ", "unknown"); +		vfprintf(stderr, format, args); +		fprintf(stderr, "\n"); +		fflush(stderr); + +		/* In this case we return at here. */ +		errno = original_errno; +		return; +	} +	tsctl.precision = zl->timestamp_precision; + +	/* Syslog output */ +	if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG]) { +		va_list ac; +		va_copy(ac, args); +		vsyslog(priority | zlog_default->facility, format, ac); +		va_end(ac); +	} + +	if (zl->instance) +		sprintf(proto_str, "%s[%d]: ", zl->protoname, zl->instance); +	else +		sprintf(proto_str, "%s: ", zl->protoname); + +	/* File output. */ +	if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp) { +		va_list ac; +		time_print(zl->fp, &tsctl); +		if (zl->record_priority) +			fprintf(zl->fp, "%s: ", zlog_priority[priority]); +		fprintf(zl->fp, "%s", proto_str); +		va_copy(ac, args); +		vfprintf(zl->fp, format, ac); +		va_end(ac); +		fprintf(zl->fp, "\n"); +		fflush(zl->fp); +	} + +	/* stdout output. */ +	if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT]) { +		va_list ac; +		time_print(stdout, &tsctl); +		if (zl->record_priority) +			fprintf(stdout, "%s: ", zlog_priority[priority]); +		fprintf(stdout, "%s", proto_str); +		va_copy(ac, args); +		vfprintf(stdout, format, ac); +		va_end(ac); +		fprintf(stdout, "\n"); +		fflush(stdout); +	} + +	/* Terminal monitor. */ +	if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR]) +		vty_log((zl->record_priority ? zlog_priority[priority] : NULL), +			proto_str, format, &tsctl, args); + +	errno = original_errno;  } -int  -vzlog_test (int priority) +int vzlog_test(int priority)  { -  struct zlog *zl = zlog_default; - -  /* When zlog_default is also NULL, use stderr for logging. */ -  if (zl == NULL) -    { -      return 1; -    } - -  /* Syslog output */ -  if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG]) -    { -      return 1; -    } - -  /* File output. */ -  if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp) -    { -      return 1; -    } - -  /* stdout output. */ -  if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT]) -    { -      return 1; -    } - -  /* Terminal monitor. */ -  if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR]) -    return 1; -     -  return 0; +	struct zlog *zl = zlog_default; + +	/* When zlog_default is also NULL, use stderr for logging. */ +	if (zl == NULL) { +		return 1; +	} + +	/* Syslog output */ +	if (priority <= zl->maxlvl[ZLOG_DEST_SYSLOG]) { +		return 1; +	} + +	/* File output. */ +	if ((priority <= zl->maxlvl[ZLOG_DEST_FILE]) && zl->fp) { +		return 1; +	} + +	/* stdout output. */ +	if (priority <= zl->maxlvl[ZLOG_DEST_STDOUT]) { +		return 1; +	} + +	/* Terminal monitor. */ +	if (priority <= zl->maxlvl[ZLOG_DEST_MONITOR]) +		return 1; + +	return 0;  } -static char * -str_append(char *dst, int len, const char *src) +static char *str_append(char *dst, int len, const char *src)  { -  while ((len-- > 0) && *src) -    *dst++ = *src++; -  return dst; +	while ((len-- > 0) && *src) +		*dst++ = *src++; +	return dst;  } -static char * -num_append(char *s, int len, u_long x) +static char *num_append(char *s, int len, u_long x)  { -  char buf[30]; -  char *t; - -  if (!x) -    return str_append(s,len,"0"); -  *(t = &buf[sizeof(buf)-1]) = '\0'; -  while (x && (t > buf)) -    { -      *--t = '0'+(x % 10); -      x /= 10; -    } -  return str_append(s,len,t); +	char buf[30]; +	char *t; + +	if (!x) +		return str_append(s, len, "0"); +	*(t = &buf[sizeof(buf) - 1]) = '\0'; +	while (x && (t > buf)) { +		*--t = '0' + (x % 10); +		x /= 10; +	} +	return str_append(s, len, t);  }  #if defined(SA_SIGINFO) || defined(HAVE_STACK_TRACE) -static char * -hex_append(char *s, int len, u_long x) +static char *hex_append(char *s, int len, u_long x)  { -  char buf[30]; -  char *t; - -  if (!x) -    return str_append(s,len,"0"); -  *(t = &buf[sizeof(buf)-1]) = '\0'; -  while (x && (t > buf)) -    { -      u_int cc = (x % 16); -      *--t = ((cc < 10) ? ('0'+cc) : ('a'+cc-10)); -      x /= 16; -    } -  return str_append(s,len,t); +	char buf[30]; +	char *t; + +	if (!x) +		return str_append(s, len, "0"); +	*(t = &buf[sizeof(buf) - 1]) = '\0'; +	while (x && (t > buf)) { +		u_int cc = (x % 16); +		*--t = ((cc < 10) ? ('0' + cc) : ('a' + cc - 10)); +		x /= 16; +	} +	return str_append(s, len, t);  }  #endif  /* Needs to be enhanced to support Solaris. */ -static int -syslog_connect(void) +static int syslog_connect(void)  {  #ifdef SUNOS_5 -  return -1; +	return -1;  #else -  int fd; -  char *s; -  struct sockaddr_un addr; +	int fd; +	char *s; +	struct sockaddr_un addr; -  if ((fd = socket(AF_UNIX,SOCK_DGRAM,0)) < 0) -    return -1; -  addr.sun_family = AF_UNIX; +	if ((fd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) +		return -1; +	addr.sun_family = AF_UNIX;  #ifdef _PATH_LOG  #define SYSLOG_SOCKET_PATH _PATH_LOG  #else  #define SYSLOG_SOCKET_PATH "/dev/log"  #endif -  s = str_append(addr.sun_path,sizeof(addr.sun_path),SYSLOG_SOCKET_PATH); +	s = str_append(addr.sun_path, sizeof(addr.sun_path), +		       SYSLOG_SOCKET_PATH);  #undef SYSLOG_SOCKET_PATH -  *s = '\0'; -  if (connect(fd,(struct sockaddr *)&addr,sizeof(addr)) < 0) -    { -      close(fd); -      return -1; -    } -  return fd; +	*s = '\0'; +	if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { +		close(fd); +		return -1; +	} +	return fd;  #endif  } -static void -syslog_sigsafe(int priority, const char *msg, size_t msglen) +static void syslog_sigsafe(int priority, const char *msg, size_t msglen)  { -  static int syslog_fd = -1; -  char buf[sizeof("<1234567890>ripngd[1234567890]: ")+msglen+50]; -  char *s; +	static int syslog_fd = -1; +	char buf[sizeof("<1234567890>ripngd[1234567890]: ") + msglen + 50]; +	char *s; -  if ((syslog_fd < 0) && ((syslog_fd = syslog_connect()) < 0)) -    return; +	if ((syslog_fd < 0) && ((syslog_fd = syslog_connect()) < 0)) +		return;  #define LOC s,buf+sizeof(buf)-s -  s = buf; -  s = str_append(LOC,"<"); -  s = num_append(LOC,priority); -  s = str_append(LOC,">"); -  /* forget about the timestamp, too difficult in a signal handler */ -  s = str_append(LOC,zlog_default->ident); -  if (zlog_default->syslog_options & LOG_PID) -    { -      s = str_append(LOC,"["); -      s = num_append(LOC,getpid()); -      s = str_append(LOC,"]"); -    } -  s = str_append(LOC,": "); -  s = str_append(LOC,msg); -  write_wrapper (syslog_fd,buf,s-buf); +	s = buf; +	s = str_append(LOC, "<"); +	s = num_append(LOC, priority); +	s = str_append(LOC, ">"); +	/* forget about the timestamp, too difficult in a signal handler */ +	s = str_append(LOC, zlog_default->ident); +	if (zlog_default->syslog_options & LOG_PID) { +		s = str_append(LOC, "["); +		s = num_append(LOC, getpid()); +		s = str_append(LOC, "]"); +	} +	s = str_append(LOC, ": "); +	s = str_append(LOC, msg); +	write_wrapper(syslog_fd, buf, s - buf);  #undef LOC  } -static int -open_crashlog(void) +static int open_crashlog(void)  {  #define CRASHLOG_PREFIX "/var/tmp/quagga."  #define CRASHLOG_SUFFIX "crashlog" -  if (zlog_default && zlog_default->ident) -    { -      /* Avoid strlen since it is not async-signal-safe. */ -      const char *p; -      size_t ilen; - -      for (p = zlog_default->ident, ilen = 0; *p; p++) -	ilen++; -      { -	char buf[sizeof(CRASHLOG_PREFIX)+ilen+sizeof(CRASHLOG_SUFFIX)+3]; -	char *s = buf; +	if (zlog_default && zlog_default->ident) { +		/* Avoid strlen since it is not async-signal-safe. */ +		const char *p; +		size_t ilen; + +		for (p = zlog_default->ident, ilen = 0; *p; p++) +			ilen++; +		{ +			char buf[sizeof(CRASHLOG_PREFIX) + ilen +				 + sizeof(CRASHLOG_SUFFIX) + 3]; +			char *s = buf;  #define LOC s,buf+sizeof(buf)-s -	s = str_append(LOC, CRASHLOG_PREFIX); -	s = str_append(LOC, zlog_default->ident); -	s = str_append(LOC, "."); -	s = str_append(LOC, CRASHLOG_SUFFIX); +			s = str_append(LOC, CRASHLOG_PREFIX); +			s = str_append(LOC, zlog_default->ident); +			s = str_append(LOC, "."); +			s = str_append(LOC, CRASHLOG_SUFFIX);  #undef LOC -	*s = '\0'; -	return open(buf, O_WRONLY|O_CREAT|O_EXCL, LOGFILE_MASK); -      } -    } -  return open(CRASHLOG_PREFIX CRASHLOG_SUFFIX, O_WRONLY|O_CREAT|O_EXCL, -	      LOGFILE_MASK); +			*s = '\0'; +			return open(buf, O_WRONLY | O_CREAT | O_EXCL, +				    LOGFILE_MASK); +		} +	} +	return open(CRASHLOG_PREFIX CRASHLOG_SUFFIX, +		    O_WRONLY | O_CREAT | O_EXCL, LOGFILE_MASK);  #undef CRASHLOG_SUFFIX  #undef CRASHLOG_PREFIX  }  /* Note: the goal here is to use only async-signal-safe functions. */ -void -zlog_signal(int signo, const char *action +void zlog_signal(int signo, const char *action  #ifdef SA_SIGINFO -	    , siginfo_t *siginfo, void *program_counter +		 , +		 siginfo_t *siginfo, void *program_counter  #endif -	   ) +		 )  { -  time_t now; -  char buf[sizeof("DEFAULT: Received signal S at T (si_addr 0xP, PC 0xP); aborting...")+100]; -  char *s = buf; -  char *msgstart = buf; +	time_t now; +	char buf[sizeof("DEFAULT: Received signal S at T (si_addr 0xP, PC 0xP); aborting...") +		 + 100]; +	char *s = buf; +	char *msgstart = buf;  #define LOC s,buf+sizeof(buf)-s -  time(&now); -  if (zlog_default) -    { -      s = str_append(LOC,zlog_default->protoname); -      *s++ = ':'; -      *s++ = ' '; -      msgstart = s; -    } -  s = str_append(LOC,"Received signal "); -  s = num_append(LOC,signo); -  s = str_append(LOC," at "); -  s = num_append(LOC,now); +	time(&now); +	if (zlog_default) { +		s = str_append(LOC, zlog_default->protoname); +		*s++ = ':'; +		*s++ = ' '; +		msgstart = s; +	} +	s = str_append(LOC, "Received signal "); +	s = num_append(LOC, signo); +	s = str_append(LOC, " at "); +	s = num_append(LOC, now);  #ifdef SA_SIGINFO -  s = str_append(LOC," (si_addr 0x"); -  s = hex_append(LOC,(u_long)(siginfo->si_addr)); -  if (program_counter) -    { -      s = str_append(LOC,", PC 0x"); -      s = hex_append(LOC,(u_long)program_counter); -    } -  s = str_append(LOC,"); "); -#else /* SA_SIGINFO */ -  s = str_append(LOC,"; "); +	s = str_append(LOC, " (si_addr 0x"); +	s = hex_append(LOC, (u_long)(siginfo->si_addr)); +	if (program_counter) { +		s = str_append(LOC, ", PC 0x"); +		s = hex_append(LOC, (u_long)program_counter); +	} +	s = str_append(LOC, "); "); +#else  /* SA_SIGINFO */ +	s = str_append(LOC, "; ");  #endif /* SA_SIGINFO */ -  s = str_append(LOC,action); -  if (s < buf+sizeof(buf)) -    *s++ = '\n'; +	s = str_append(LOC, action); +	if (s < buf + sizeof(buf)) +		*s++ = '\n'; -  /* N.B. implicit priority is most severe */ +/* N.B. implicit priority is most severe */  #define PRI LOG_CRIT  #define DUMP(FD) write_wrapper(FD, buf, s-buf); -  /* If no file logging configured, try to write to fallback log file. */ -  if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0)) -    DUMP(logfile_fd) -  if (!zlog_default) -    DUMP(STDERR_FILENO) -  else -    { -      if (PRI <= zlog_default->maxlvl[ZLOG_DEST_STDOUT]) -        DUMP(STDOUT_FILENO) -      /* Remove trailing '\n' for monitor and syslog */ -      *--s = '\0'; -      if (PRI <= zlog_default->maxlvl[ZLOG_DEST_MONITOR]) -        vty_log_fixed(buf,s-buf); -      if (PRI <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG]) -	syslog_sigsafe(PRI|zlog_default->facility,msgstart,s-msgstart); -    } +	/* If no file logging configured, try to write to fallback log file. */ +	if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0)) +		DUMP(logfile_fd) +	if (!zlog_default) +		DUMP(STDERR_FILENO) +	else { +		if (PRI <= zlog_default->maxlvl[ZLOG_DEST_STDOUT]) +			DUMP(STDOUT_FILENO) +		/* Remove trailing '\n' for monitor and syslog */ +		*--s = '\0'; +		if (PRI <= zlog_default->maxlvl[ZLOG_DEST_MONITOR]) +			vty_log_fixed(buf, s - buf); +		if (PRI <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG]) +			syslog_sigsafe(PRI | zlog_default->facility, msgstart, +				       s - msgstart); +	}  #undef DUMP -  zlog_backtrace_sigsafe(PRI, +	zlog_backtrace_sigsafe(PRI,  #ifdef SA_SIGINFO -  			 program_counter +			       program_counter  #else -			 NULL +			       NULL  #endif -			); - -  s = buf; -  if (!thread_current) -    s = str_append (LOC, "no thread information available\n"); -  else -    { -      s = str_append (LOC, "in thread "); -      s = str_append (LOC, thread_current->funcname); -      s = str_append (LOC, " scheduled from "); -      s = str_append (LOC, thread_current->schedfrom); -      s = str_append (LOC, ":"); -      s = num_append (LOC, thread_current->schedfrom_line); -      s = str_append (LOC, "\n"); -    } +			       ); + +	s = buf; +	if (!thread_current) +		s = str_append(LOC, "no thread information available\n"); +	else { +		s = str_append(LOC, "in thread "); +		s = str_append(LOC, thread_current->funcname); +		s = str_append(LOC, " scheduled from "); +		s = str_append(LOC, thread_current->schedfrom); +		s = str_append(LOC, ":"); +		s = num_append(LOC, thread_current->schedfrom_line); +		s = str_append(LOC, "\n"); +	}  #define DUMP(FD) write_wrapper(FD, buf, s-buf); -  /* If no file logging configured, try to write to fallback log file. */ -  if (logfile_fd >= 0) -    DUMP(logfile_fd) -  if (!zlog_default) -    DUMP(STDERR_FILENO) -  else -    { -      if (PRI <= zlog_default->maxlvl[ZLOG_DEST_STDOUT]) -        DUMP(STDOUT_FILENO) -      /* Remove trailing '\n' for monitor and syslog */ -      *--s = '\0'; -      if (PRI <= zlog_default->maxlvl[ZLOG_DEST_MONITOR]) -        vty_log_fixed(buf,s-buf); -      if (PRI <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG]) -	syslog_sigsafe(PRI|zlog_default->facility,msgstart,s-msgstart); -    } +	/* If no file logging configured, try to write to fallback log file. */ +	if (logfile_fd >= 0) +		DUMP(logfile_fd) +	if (!zlog_default) +		DUMP(STDERR_FILENO) +	else { +		if (PRI <= zlog_default->maxlvl[ZLOG_DEST_STDOUT]) +			DUMP(STDOUT_FILENO) +		/* Remove trailing '\n' for monitor and syslog */ +		*--s = '\0'; +		if (PRI <= zlog_default->maxlvl[ZLOG_DEST_MONITOR]) +			vty_log_fixed(buf, s - buf); +		if (PRI <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG]) +			syslog_sigsafe(PRI | zlog_default->facility, msgstart, +				       s - msgstart); +	}  #undef DUMP  #undef PRI @@ -548,144 +515,143 @@ zlog_signal(int signo, const char *action  /* Log a backtrace using only async-signal-safe functions.     Needs to be enhanced to support syslog logging. */ -void -zlog_backtrace_sigsafe(int priority, void *program_counter) +void zlog_backtrace_sigsafe(int priority, void *program_counter)  {  #ifdef HAVE_STACK_TRACE -  static const char pclabel[] = "Program counter: "; -  void *array[64]; -  int size; -  char buf[100]; -  char *s, **bt = NULL; +	static const char pclabel[] = "Program counter: "; +	void *array[64]; +	int size; +	char buf[100]; +	char *s, **bt = NULL;  #define LOC s,buf+sizeof(buf)-s  #ifdef HAVE_GLIBC_BACKTRACE -  size = backtrace(array, array_size(array)); -  if (size <= 0 || (size_t)size > array_size(array)) -    return; - -#define DUMP(FD) { \ -  if (program_counter) \ -    { \ -      write_wrapper(FD, pclabel, sizeof(pclabel)-1); \ -      backtrace_symbols_fd(&program_counter, 1, FD); \ -    } \ -  write_wrapper(FD, buf, s-buf);	\ -  backtrace_symbols_fd(array, size, FD); \ -} +	size = backtrace(array, array_size(array)); +	if (size <= 0 || (size_t)size > array_size(array)) +		return; + +#define DUMP(FD)                                                               \ +	{                                                                      \ +		if (program_counter) {                                         \ +			write_wrapper(FD, pclabel, sizeof(pclabel) - 1);       \ +			backtrace_symbols_fd(&program_counter, 1, FD);         \ +		}                                                              \ +		write_wrapper(FD, buf, s - buf);                               \ +		backtrace_symbols_fd(array, size, FD);                         \ +	}  #elif defined(HAVE_PRINTSTACK) -#define DUMP(FD) { \ -  if (program_counter) \ -    write_wrapper((FD), pclabel, sizeof(pclabel)-1); \ -  write_wrapper((FD), buf, s-buf); \ -  printstack((FD)); \ -} +#define DUMP(FD)                                                               \ +	{                                                                      \ +		if (program_counter)                                           \ +			write_wrapper((FD), pclabel, sizeof(pclabel) - 1);     \ +		write_wrapper((FD), buf, s - buf);                             \ +		printstack((FD));                                              \ +	}  #endif /* HAVE_GLIBC_BACKTRACE, HAVE_PRINTSTACK */ -  s = buf; -  s = str_append(LOC,"Backtrace for "); -  s = num_append(LOC,size); -  s = str_append(LOC," stack frames:\n"); - -  if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0)) -    DUMP(logfile_fd) -  if (!zlog_default) -    DUMP(STDERR_FILENO) -  else -    { -      if (priority <= zlog_default->maxlvl[ZLOG_DEST_STDOUT]) -	DUMP(STDOUT_FILENO) -      /* Remove trailing '\n' for monitor and syslog */ -      *--s = '\0'; -      if (priority <= zlog_default->maxlvl[ZLOG_DEST_MONITOR]) -	vty_log_fixed(buf,s-buf); -      if (priority <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG]) -	syslog_sigsafe(priority|zlog_default->facility,buf,s-buf); -      { -	int i; +	s = buf; +	s = str_append(LOC, "Backtrace for "); +	s = num_append(LOC, size); +	s = str_append(LOC, " stack frames:\n"); + +	if ((logfile_fd >= 0) || ((logfile_fd = open_crashlog()) >= 0)) +		DUMP(logfile_fd) +	if (!zlog_default) +		DUMP(STDERR_FILENO) +	else { +		if (priority <= zlog_default->maxlvl[ZLOG_DEST_STDOUT]) +			DUMP(STDOUT_FILENO) +		/* Remove trailing '\n' for monitor and syslog */ +		*--s = '\0'; +		if (priority <= zlog_default->maxlvl[ZLOG_DEST_MONITOR]) +			vty_log_fixed(buf, s - buf); +		if (priority <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG]) +			syslog_sigsafe(priority | zlog_default->facility, buf, +				       s - buf); +		{ +			int i;  #ifdef HAVE_GLIBC_BACKTRACE -        bt = backtrace_symbols(array, size); +			bt = backtrace_symbols(array, size);  #endif -	/* Just print the function addresses. */ -	for (i = 0; i < size; i++) -	  { -	    s = buf; -	    if (bt)  -	      s = str_append(LOC, bt[i]); -	    else { -	      s = str_append(LOC,"[bt "); -	      s = num_append(LOC,i); -	      s = str_append(LOC,"] 0x"); -	      s = hex_append(LOC,(u_long)(array[i])); -	    } -	    *s = '\0'; -	    if (priority <= zlog_default->maxlvl[ZLOG_DEST_MONITOR]) -	      vty_log_fixed(buf,s-buf); -	    if (priority <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG]) -	      syslog_sigsafe(priority|zlog_default->facility,buf,s-buf); -	  } -	  if (bt) -	    free(bt); -      } -    } +			/* Just print the function addresses. */ +			for (i = 0; i < size; i++) { +				s = buf; +				if (bt) +					s = str_append(LOC, bt[i]); +				else { +					s = str_append(LOC, "[bt "); +					s = num_append(LOC, i); +					s = str_append(LOC, "] 0x"); +					s = hex_append(LOC, (u_long)(array[i])); +				} +				*s = '\0'; +				if (priority +				    <= zlog_default->maxlvl[ZLOG_DEST_MONITOR]) +					vty_log_fixed(buf, s - buf); +				if (priority +				    <= zlog_default->maxlvl[ZLOG_DEST_SYSLOG]) +					syslog_sigsafe( +						priority +							| zlog_default +								  ->facility, +						buf, s - buf); +			} +			if (bt) +				free(bt); +		} +	}  #undef DUMP  #undef LOC  #endif /* HAVE_STRACK_TRACE */  } -void -zlog_backtrace(int priority) +void zlog_backtrace(int priority)  {  #ifndef HAVE_GLIBC_BACKTRACE -  zlog(priority, "No backtrace available on this platform."); +	zlog(priority, "No backtrace available on this platform.");  #else -  void *array[20]; -  int size, i; -  char **strings; - -  size = backtrace(array, array_size(array)); -  if (size <= 0 || (size_t)size > array_size(array)) -    { -      zlog_err("Cannot get backtrace, returned invalid # of frames %d " -	       "(valid range is between 1 and %lu)", -	       size, (unsigned long)(array_size(array))); -      return; -    } -  zlog(priority, "Backtrace for %d stack frames:", size); -  if (!(strings = backtrace_symbols(array, size))) -    { -      zlog_err("Cannot get backtrace symbols (out of memory?)"); -      for (i = 0; i < size; i++) -	zlog(priority, "[bt %d] %p",i,array[i]); -    } -  else -    { -      for (i = 0; i < size; i++) -	zlog(priority, "[bt %d] %s",i,strings[i]); -      free(strings); -    } +	void *array[20]; +	int size, i; +	char **strings; + +	size = backtrace(array, array_size(array)); +	if (size <= 0 || (size_t)size > array_size(array)) { +		zlog_err( +			"Cannot get backtrace, returned invalid # of frames %d " +			"(valid range is between 1 and %lu)", +			size, (unsigned long)(array_size(array))); +		return; +	} +	zlog(priority, "Backtrace for %d stack frames:", size); +	if (!(strings = backtrace_symbols(array, size))) { +		zlog_err("Cannot get backtrace symbols (out of memory?)"); +		for (i = 0; i < size; i++) +			zlog(priority, "[bt %d] %p", i, array[i]); +	} else { +		for (i = 0; i < size; i++) +			zlog(priority, "[bt %d] %s", i, strings[i]); +		free(strings); +	}  #endif /* HAVE_GLIBC_BACKTRACE */  } -void -zlog (int priority, const char *format, ...) +void zlog(int priority, const char *format, ...)  { -  va_list args; +	va_list args; -  va_start(args, format); -  vzlog (priority, format, args); -  va_end (args); +	va_start(args, format); +	vzlog(priority, format, args); +	va_end(args);  } -#define ZLOG_FUNC(FUNCNAME,PRIORITY) \ -void \ -FUNCNAME(const char *format, ...) \ -{ \ -  va_list args; \ -  va_start(args, format); \ -  vzlog (PRIORITY, format, args); \ -  va_end(args); \ -} +#define ZLOG_FUNC(FUNCNAME, PRIORITY)                                          \ +	void FUNCNAME(const char *format, ...)                                 \ +	{                                                                      \ +		va_list args;                                                  \ +		va_start(args, format);                                        \ +		vzlog(PRIORITY, format, args);                                 \ +		va_end(args);                                                  \ +	}  ZLOG_FUNC(zlog_err, LOG_ERR) @@ -699,440 +665,425 @@ ZLOG_FUNC(zlog_debug, LOG_DEBUG)  #undef ZLOG_FUNC -void zlog_thread_info (int log_level) +void zlog_thread_info(int log_level)  { -  if (thread_current) -    zlog(log_level, "Current thread function %s, scheduled from " -	 "file %s, line %u", thread_current->funcname, -	 thread_current->schedfrom, thread_current->schedfrom_line); -  else -    zlog(log_level, "Current thread not known/applicable"); +	if (thread_current) +		zlog(log_level, +		     "Current thread function %s, scheduled from " +		     "file %s, line %u", +		     thread_current->funcname, thread_current->schedfrom, +		     thread_current->schedfrom_line); +	else +		zlog(log_level, "Current thread not known/applicable");  } -void -_zlog_assert_failed (const char *assertion, const char *file, -		     unsigned int line, const char *function) +void _zlog_assert_failed(const char *assertion, const char *file, +			 unsigned int line, const char *function)  { -  /* Force fallback file logging? */ -  if (zlog_default && !zlog_default->fp && -      ((logfile_fd = open_crashlog()) >= 0) && -      ((zlog_default->fp = fdopen(logfile_fd, "w")) != NULL)) -    zlog_default->maxlvl[ZLOG_DEST_FILE] = LOG_ERR; -  zlog(LOG_CRIT, "Assertion `%s' failed in file %s, line %u, function %s", -       assertion,file,line,(function ? function : "?")); -  zlog_backtrace(LOG_CRIT); -  zlog_thread_info(LOG_CRIT); -  log_memstats_stderr ("log"); -  abort(); +	/* Force fallback file logging? */ +	if (zlog_default && !zlog_default->fp +	    && ((logfile_fd = open_crashlog()) >= 0) +	    && ((zlog_default->fp = fdopen(logfile_fd, "w")) != NULL)) +		zlog_default->maxlvl[ZLOG_DEST_FILE] = LOG_ERR; +	zlog(LOG_CRIT, "Assertion `%s' failed in file %s, line %u, function %s", +	     assertion, file, line, (function ? function : "?")); +	zlog_backtrace(LOG_CRIT); +	zlog_thread_info(LOG_CRIT); +	log_memstats_stderr("log"); +	abort();  } -void -memory_oom (size_t size, const char *name) +void memory_oom(size_t size, const char *name)  { -	zlog_err("out of memory: failed to allocate %zu bytes for %s" -		 "object", size, name); +	zlog_err( +		"out of memory: failed to allocate %zu bytes for %s" +		"object", +		size, name);  	zlog_backtrace(LOG_ERR);  	abort();  }  /* Open log stream */ -void -openzlog (const char *progname, const char *protoname, u_short instance, -	  int syslog_flags, int syslog_facility) +void openzlog(const char *progname, const char *protoname, u_short instance, +	      int syslog_flags, int syslog_facility)  { -  struct zlog *zl; -  u_int i; +	struct zlog *zl; +	u_int i; -  zl = XCALLOC(MTYPE_ZLOG, sizeof (struct zlog)); +	zl = XCALLOC(MTYPE_ZLOG, sizeof(struct zlog)); -  zl->ident = progname; -  zl->protoname = protoname; -  zl->instance = instance; -  zl->facility = syslog_facility; -  zl->syslog_options = syslog_flags; +	zl->ident = progname; +	zl->protoname = protoname; +	zl->instance = instance; +	zl->facility = syslog_facility; +	zl->syslog_options = syslog_flags; -  /* Set default logging levels. */ -  for (i = 0; i < array_size(zl->maxlvl); i++) -    zl->maxlvl[i] = ZLOG_DISABLED; -  zl->maxlvl[ZLOG_DEST_MONITOR] = LOG_DEBUG; -  zl->default_lvl = LOG_DEBUG; +	/* Set default logging levels. */ +	for (i = 0; i < array_size(zl->maxlvl); i++) +		zl->maxlvl[i] = ZLOG_DISABLED; +	zl->maxlvl[ZLOG_DEST_MONITOR] = LOG_DEBUG; +	zl->default_lvl = LOG_DEBUG; -  openlog (progname, syslog_flags, zl->facility); -  zlog_default = zl; +	openlog(progname, syslog_flags, zl->facility); +	zlog_default = zl;  } -void -closezlog (void) +void closezlog(void)  { -  struct zlog *zl = zlog_default; +	struct zlog *zl = zlog_default; -  closelog(); +	closelog(); -  if (zl->fp != NULL) -    fclose (zl->fp); +	if (zl->fp != NULL) +		fclose(zl->fp); -  if (zl->filename != NULL) -    XFREE(MTYPE_ZLOG, zl->filename); +	if (zl->filename != NULL) +		XFREE(MTYPE_ZLOG, zl->filename); -  XFREE (MTYPE_ZLOG, zl); -  zlog_default = NULL; +	XFREE(MTYPE_ZLOG, zl); +	zlog_default = NULL;  } -const char * -zlog_protoname (void) +const char *zlog_protoname(void)  { -  return zlog_default ? zlog_default->protoname : "NONE"; +	return zlog_default ? zlog_default->protoname : "NONE";  }  /* Called from command.c. */ -void -zlog_set_level (zlog_dest_t dest, int log_level) +void zlog_set_level(zlog_dest_t dest, int log_level)  { -  zlog_default->maxlvl[dest] = log_level; +	zlog_default->maxlvl[dest] = log_level;  } -int -zlog_set_file (const char *filename, int log_level) +int zlog_set_file(const char *filename, int log_level)  { -  struct zlog *zl = zlog_default; -  FILE *fp; -  mode_t oldumask; - -  /* There is opend file.  */ -  zlog_reset_file (); - -  /* Open file. */ -  oldumask = umask (0777 & ~LOGFILE_MASK); -  fp = fopen (filename, "a"); -  umask(oldumask); -  if (fp == NULL) -    return 0; - -  /* Set flags. */ -  zl->filename = XSTRDUP(MTYPE_ZLOG, filename); -  zl->maxlvl[ZLOG_DEST_FILE] = log_level; -  zl->fp = fp; -  logfile_fd = fileno(fp); - -  return 1; +	struct zlog *zl = zlog_default; +	FILE *fp; +	mode_t oldumask; + +	/* There is opend file.  */ +	zlog_reset_file(); + +	/* Open file. */ +	oldumask = umask(0777 & ~LOGFILE_MASK); +	fp = fopen(filename, "a"); +	umask(oldumask); +	if (fp == NULL) +		return 0; + +	/* Set flags. */ +	zl->filename = XSTRDUP(MTYPE_ZLOG, filename); +	zl->maxlvl[ZLOG_DEST_FILE] = log_level; +	zl->fp = fp; +	logfile_fd = fileno(fp); + +	return 1;  }  /* Reset opend file. */ -int -zlog_reset_file (void) +int zlog_reset_file(void)  { -  struct zlog *zl = zlog_default; +	struct zlog *zl = zlog_default; -  if (zl->fp) -    fclose (zl->fp); -  zl->fp = NULL; -  logfile_fd = -1; -  zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED; +	if (zl->fp) +		fclose(zl->fp); +	zl->fp = NULL; +	logfile_fd = -1; +	zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED; -  if (zl->filename) -    XFREE(MTYPE_ZLOG, zl->filename); -  zl->filename = NULL; +	if (zl->filename) +		XFREE(MTYPE_ZLOG, zl->filename); +	zl->filename = NULL; -  return 1; +	return 1;  }  /* Reopen log file. */ -int -zlog_rotate (void) +int zlog_rotate(void)  { -  struct zlog *zl = zlog_default; -  int level; - -  if (zl->fp) -    fclose (zl->fp); -  zl->fp = NULL; -  logfile_fd = -1; -  level = zl->maxlvl[ZLOG_DEST_FILE]; -  zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED; - -  if (zl->filename) -    { -      mode_t oldumask; -      int save_errno; - -      oldumask = umask (0777 & ~LOGFILE_MASK); -      zl->fp = fopen (zl->filename, "a"); -      save_errno = errno; -      umask(oldumask); -      if (zl->fp == NULL) -        { -	  zlog_err("Log rotate failed: cannot open file %s for append: %s", -	  	   zl->filename, safe_strerror(save_errno)); -	  return -1; -        }	 -      logfile_fd = fileno(zl->fp); -      zl->maxlvl[ZLOG_DEST_FILE] = level; -    } - -  return 1; +	struct zlog *zl = zlog_default; +	int level; + +	if (zl->fp) +		fclose(zl->fp); +	zl->fp = NULL; +	logfile_fd = -1; +	level = zl->maxlvl[ZLOG_DEST_FILE]; +	zl->maxlvl[ZLOG_DEST_FILE] = ZLOG_DISABLED; + +	if (zl->filename) { +		mode_t oldumask; +		int save_errno; + +		oldumask = umask(0777 & ~LOGFILE_MASK); +		zl->fp = fopen(zl->filename, "a"); +		save_errno = errno; +		umask(oldumask); +		if (zl->fp == NULL) { +			zlog_err( +				"Log rotate failed: cannot open file %s for append: %s", +				zl->filename, safe_strerror(save_errno)); +			return -1; +		} +		logfile_fd = fileno(zl->fp); +		zl->maxlvl[ZLOG_DEST_FILE] = level; +	} + +	return 1;  }  /* Wrapper around strerror to handle case where it returns NULL. */ -const char * -safe_strerror(int errnum) +const char *safe_strerror(int errnum)  { -  const char *s = strerror(errnum); -  return (s != NULL) ? s : "Unknown error"; +	const char *s = strerror(errnum); +	return (s != NULL) ? s : "Unknown error";  }  #define DESC_ENTRY(T) [(T)] = { (T), (#T), '\0' }  static const struct zebra_desc_table command_types[] = { -  DESC_ENTRY	(ZEBRA_INTERFACE_ADD), -  DESC_ENTRY	(ZEBRA_INTERFACE_DELETE), -  DESC_ENTRY	(ZEBRA_INTERFACE_ADDRESS_ADD), -  DESC_ENTRY	(ZEBRA_INTERFACE_ADDRESS_DELETE), -  DESC_ENTRY	(ZEBRA_INTERFACE_UP), -  DESC_ENTRY	(ZEBRA_INTERFACE_DOWN), -  DESC_ENTRY	(ZEBRA_IPV4_ROUTE_ADD), -  DESC_ENTRY	(ZEBRA_IPV4_ROUTE_DELETE), -  DESC_ENTRY	(ZEBRA_IPV6_ROUTE_ADD), -  DESC_ENTRY	(ZEBRA_IPV6_ROUTE_DELETE), -  DESC_ENTRY	(ZEBRA_REDISTRIBUTE_ADD), -  DESC_ENTRY	(ZEBRA_REDISTRIBUTE_DELETE), -  DESC_ENTRY	(ZEBRA_REDISTRIBUTE_DEFAULT_ADD), -  DESC_ENTRY	(ZEBRA_REDISTRIBUTE_DEFAULT_DELETE), -  DESC_ENTRY	(ZEBRA_ROUTER_ID_ADD), -  DESC_ENTRY	(ZEBRA_ROUTER_ID_DELETE), -  DESC_ENTRY	(ZEBRA_ROUTER_ID_UPDATE), -  DESC_ENTRY	(ZEBRA_HELLO), -  DESC_ENTRY	(ZEBRA_NEXTHOP_REGISTER), -  DESC_ENTRY	(ZEBRA_NEXTHOP_UNREGISTER), -  DESC_ENTRY	(ZEBRA_NEXTHOP_UPDATE), -  DESC_ENTRY    (ZEBRA_INTERFACE_NBR_ADDRESS_ADD), -  DESC_ENTRY    (ZEBRA_INTERFACE_NBR_ADDRESS_DELETE), -  DESC_ENTRY    (ZEBRA_INTERFACE_BFD_DEST_UPDATE), -  DESC_ENTRY    (ZEBRA_IMPORT_ROUTE_REGISTER), -  DESC_ENTRY    (ZEBRA_IMPORT_ROUTE_UNREGISTER), -  DESC_ENTRY    (ZEBRA_IMPORT_CHECK_UPDATE), -  DESC_ENTRY    (ZEBRA_IPV4_ROUTE_IPV6_NEXTHOP_ADD), -  DESC_ENTRY    (ZEBRA_BFD_DEST_REGISTER), -  DESC_ENTRY    (ZEBRA_BFD_DEST_DEREGISTER), -  DESC_ENTRY    (ZEBRA_BFD_DEST_UPDATE), -  DESC_ENTRY    (ZEBRA_BFD_DEST_REPLAY), -  DESC_ENTRY    (ZEBRA_REDISTRIBUTE_IPV4_ADD), -  DESC_ENTRY    (ZEBRA_REDISTRIBUTE_IPV4_DEL), -  DESC_ENTRY    (ZEBRA_REDISTRIBUTE_IPV6_ADD), -  DESC_ENTRY    (ZEBRA_REDISTRIBUTE_IPV6_DEL), -  DESC_ENTRY    (ZEBRA_VRF_UNREGISTER), -  DESC_ENTRY    (ZEBRA_VRF_ADD), -  DESC_ENTRY    (ZEBRA_VRF_DELETE), -  DESC_ENTRY    (ZEBRA_INTERFACE_VRF_UPDATE), -  DESC_ENTRY    (ZEBRA_BFD_CLIENT_REGISTER), -  DESC_ENTRY    (ZEBRA_INTERFACE_ENABLE_RADV), -  DESC_ENTRY    (ZEBRA_INTERFACE_DISABLE_RADV), -  DESC_ENTRY    (ZEBRA_IPV4_NEXTHOP_LOOKUP_MRIB), -  DESC_ENTRY    (ZEBRA_INTERFACE_LINK_PARAMS), -  DESC_ENTRY	(ZEBRA_MPLS_LABELS_ADD), -  DESC_ENTRY	(ZEBRA_MPLS_LABELS_DELETE), -  DESC_ENTRY	(ZEBRA_IPV4_NEXTHOP_ADD), -  DESC_ENTRY	(ZEBRA_IPV4_NEXTHOP_DELETE), -  DESC_ENTRY	(ZEBRA_IPV6_NEXTHOP_ADD), -  DESC_ENTRY	(ZEBRA_IPV6_NEXTHOP_DELETE), -  DESC_ENTRY    (ZEBRA_IPMR_ROUTE_STATS), -  DESC_ENTRY    (ZEBRA_LABEL_MANAGER_CONNECT), -  DESC_ENTRY    (ZEBRA_GET_LABEL_CHUNK), -  DESC_ENTRY    (ZEBRA_RELEASE_LABEL_CHUNK), -  DESC_ENTRY    (ZEBRA_PW_ADD), -  DESC_ENTRY    (ZEBRA_PW_DELETE), -  DESC_ENTRY    (ZEBRA_PW_SET), -  DESC_ENTRY    (ZEBRA_PW_UNSET), -  DESC_ENTRY    (ZEBRA_PW_STATUS_UPDATE), +	DESC_ENTRY(ZEBRA_INTERFACE_ADD), +	DESC_ENTRY(ZEBRA_INTERFACE_DELETE), +	DESC_ENTRY(ZEBRA_INTERFACE_ADDRESS_ADD), +	DESC_ENTRY(ZEBRA_INTERFACE_ADDRESS_DELETE), +	DESC_ENTRY(ZEBRA_INTERFACE_UP), +	DESC_ENTRY(ZEBRA_INTERFACE_DOWN), +	DESC_ENTRY(ZEBRA_IPV4_ROUTE_ADD), +	DESC_ENTRY(ZEBRA_IPV4_ROUTE_DELETE), +	DESC_ENTRY(ZEBRA_IPV6_ROUTE_ADD), +	DESC_ENTRY(ZEBRA_IPV6_ROUTE_DELETE), +	DESC_ENTRY(ZEBRA_REDISTRIBUTE_ADD), +	DESC_ENTRY(ZEBRA_REDISTRIBUTE_DELETE), +	DESC_ENTRY(ZEBRA_REDISTRIBUTE_DEFAULT_ADD), +	DESC_ENTRY(ZEBRA_REDISTRIBUTE_DEFAULT_DELETE), +	DESC_ENTRY(ZEBRA_ROUTER_ID_ADD), +	DESC_ENTRY(ZEBRA_ROUTER_ID_DELETE), +	DESC_ENTRY(ZEBRA_ROUTER_ID_UPDATE), +	DESC_ENTRY(ZEBRA_HELLO), +	DESC_ENTRY(ZEBRA_NEXTHOP_REGISTER), +	DESC_ENTRY(ZEBRA_NEXTHOP_UNREGISTER), +	DESC_ENTRY(ZEBRA_NEXTHOP_UPDATE), +	DESC_ENTRY(ZEBRA_INTERFACE_NBR_ADDRESS_ADD), +	DESC_ENTRY(ZEBRA_INTERFACE_NBR_ADDRESS_DELETE), +	DESC_ENTRY(ZEBRA_INTERFACE_BFD_DEST_UPDATE), +	DESC_ENTRY(ZEBRA_IMPORT_ROUTE_REGISTER), +	DESC_ENTRY(ZEBRA_IMPORT_ROUTE_UNREGISTER), +	DESC_ENTRY(ZEBRA_IMPORT_CHECK_UPDATE), +	DESC_ENTRY(ZEBRA_IPV4_ROUTE_IPV6_NEXTHOP_ADD), +	DESC_ENTRY(ZEBRA_BFD_DEST_REGISTER), +	DESC_ENTRY(ZEBRA_BFD_DEST_DEREGISTER), +	DESC_ENTRY(ZEBRA_BFD_DEST_UPDATE), +	DESC_ENTRY(ZEBRA_BFD_DEST_REPLAY), +	DESC_ENTRY(ZEBRA_REDISTRIBUTE_IPV4_ADD), +	DESC_ENTRY(ZEBRA_REDISTRIBUTE_IPV4_DEL), +	DESC_ENTRY(ZEBRA_REDISTRIBUTE_IPV6_ADD), +	DESC_ENTRY(ZEBRA_REDISTRIBUTE_IPV6_DEL), +	DESC_ENTRY(ZEBRA_VRF_UNREGISTER), +	DESC_ENTRY(ZEBRA_VRF_ADD), +	DESC_ENTRY(ZEBRA_VRF_DELETE), +	DESC_ENTRY(ZEBRA_INTERFACE_VRF_UPDATE), +	DESC_ENTRY(ZEBRA_BFD_CLIENT_REGISTER), +	DESC_ENTRY(ZEBRA_INTERFACE_ENABLE_RADV), +	DESC_ENTRY(ZEBRA_INTERFACE_DISABLE_RADV), +	DESC_ENTRY(ZEBRA_IPV4_NEXTHOP_LOOKUP_MRIB), +	DESC_ENTRY(ZEBRA_INTERFACE_LINK_PARAMS), +	DESC_ENTRY(ZEBRA_MPLS_LABELS_ADD), +	DESC_ENTRY(ZEBRA_MPLS_LABELS_DELETE), +	DESC_ENTRY(ZEBRA_IPV4_NEXTHOP_ADD), +	DESC_ENTRY(ZEBRA_IPV4_NEXTHOP_DELETE), +	DESC_ENTRY(ZEBRA_IPV6_NEXTHOP_ADD), +	DESC_ENTRY(ZEBRA_IPV6_NEXTHOP_DELETE), +	DESC_ENTRY(ZEBRA_IPMR_ROUTE_STATS), +	DESC_ENTRY(ZEBRA_LABEL_MANAGER_CONNECT), +	DESC_ENTRY(ZEBRA_GET_LABEL_CHUNK), +	DESC_ENTRY(ZEBRA_RELEASE_LABEL_CHUNK), +	DESC_ENTRY(ZEBRA_PW_ADD), +	DESC_ENTRY(ZEBRA_PW_DELETE), +	DESC_ENTRY(ZEBRA_PW_SET), +	DESC_ENTRY(ZEBRA_PW_UNSET), +	DESC_ENTRY(ZEBRA_PW_STATUS_UPDATE),  };  #undef DESC_ENTRY -static const struct zebra_desc_table unknown = { 0, "unknown", '?' }; +static const struct zebra_desc_table unknown = {0, "unknown", '?'}; -static const struct zebra_desc_table * -zroute_lookup(u_int zroute) +static const struct zebra_desc_table *zroute_lookup(u_int zroute)  { -  u_int i; - -  if (zroute >= array_size(route_types)) -    { -      zlog_err("unknown zebra route type: %u", zroute); -      return &unknown; -    } -  if (zroute == route_types[zroute].type) -    return &route_types[zroute]; -  for (i = 0; i < array_size(route_types); i++) -    { -      if (zroute == route_types[i].type) -        { -	  zlog_warn("internal error: route type table out of order " -		    "while searching for %u, please notify developers", zroute); -	  return &route_types[i]; -        } -    } -  zlog_err("internal error: cannot find route type %u in table!", zroute); -  return &unknown; +	u_int i; + +	if (zroute >= array_size(route_types)) { +		zlog_err("unknown zebra route type: %u", zroute); +		return &unknown; +	} +	if (zroute == route_types[zroute].type) +		return &route_types[zroute]; +	for (i = 0; i < array_size(route_types); i++) { +		if (zroute == route_types[i].type) { +			zlog_warn( +				"internal error: route type table out of order " +				"while searching for %u, please notify developers", +				zroute); +			return &route_types[i]; +		} +	} +	zlog_err("internal error: cannot find route type %u in table!", zroute); +	return &unknown;  } -const char * -zebra_route_string(u_int zroute) +const char *zebra_route_string(u_int zroute)  { -  return zroute_lookup(zroute)->string; +	return zroute_lookup(zroute)->string;  } -char -zebra_route_char(u_int zroute) +char zebra_route_char(u_int zroute)  { -  return zroute_lookup(zroute)->chr; +	return zroute_lookup(zroute)->chr;  } -const char * -zserv_command_string (unsigned int command) +const char *zserv_command_string(unsigned int command)  { -  if (command >= array_size(command_types)) -    { -      zlog_err ("unknown zserv command type: %u", command); -      return unknown.string; -    } -  return command_types[command].string; +	if (command >= array_size(command_types)) { +		zlog_err("unknown zserv command type: %u", command); +		return unknown.string; +	} +	return command_types[command].string;  } -int -proto_name2num(const char *s) +int proto_name2num(const char *s)  { -   unsigned i; +	unsigned i; -   for (i=0; i<array_size(route_types); ++i) -     if (strcasecmp(s, route_types[i].string) == 0) -       return route_types[i].type; -   return -1; +	for (i = 0; i < array_size(route_types); ++i) +		if (strcasecmp(s, route_types[i].string) == 0) +			return route_types[i].type; +	return -1;  } -int -proto_redistnum(int afi, const char *s) +int proto_redistnum(int afi, const char *s)  { -  if (! s) -    return -1; - -  if (afi == AFI_IP) -    { -      if (strmatch (s, "kernel")) -	return ZEBRA_ROUTE_KERNEL; -      else if (strmatch (s, "connected")) -	return ZEBRA_ROUTE_CONNECT; -      else if (strmatch (s, "static")) -	return ZEBRA_ROUTE_STATIC; -      else if (strmatch (s, "rip")) -	return ZEBRA_ROUTE_RIP; -      else if (strmatch (s, "ospf")) -	return ZEBRA_ROUTE_OSPF; -      else if (strmatch (s, "isis")) -	return ZEBRA_ROUTE_ISIS; -      else if (strmatch (s, "bgp")) -	return ZEBRA_ROUTE_BGP; -      else if (strmatch (s, "table")) -	return ZEBRA_ROUTE_TABLE; -      else if (strmatch (s, "vnc")) -	return ZEBRA_ROUTE_VNC; -      else if (strmatch (s, "vnc-direct")) -	return ZEBRA_ROUTE_VNC_DIRECT; -      else if (strmatch (s, "nhrp")) -	return ZEBRA_ROUTE_NHRP; -    } -  if (afi == AFI_IP6) -    { -      if (strmatch (s, "kernel")) -	return ZEBRA_ROUTE_KERNEL; -      else if (strmatch (s, "connected")) -	return ZEBRA_ROUTE_CONNECT; -      else if (strmatch (s, "static")) -	return ZEBRA_ROUTE_STATIC; -      else if (strmatch (s, "ripng")) -	return ZEBRA_ROUTE_RIPNG; -      else if (strmatch (s, "ospf6")) -	return ZEBRA_ROUTE_OSPF6; -      else if (strmatch (s, "isis")) -	return ZEBRA_ROUTE_ISIS; -      else if (strmatch (s, "bgp")) -	return ZEBRA_ROUTE_BGP; -      else if (strmatch (s, "table")) -	return ZEBRA_ROUTE_TABLE; -      else if (strmatch (s, "vnc")) -	return ZEBRA_ROUTE_VNC; -      else if (strmatch (s, "vnc-direct")) -	return ZEBRA_ROUTE_VNC_DIRECT; -      else if (strmatch (s, "nhrp")) -	return ZEBRA_ROUTE_NHRP; -    } -  return -1; +	if (!s) +		return -1; + +	if (afi == AFI_IP) { +		if (strmatch(s, "kernel")) +			return ZEBRA_ROUTE_KERNEL; +		else if (strmatch(s, "connected")) +			return ZEBRA_ROUTE_CONNECT; +		else if (strmatch(s, "static")) +			return ZEBRA_ROUTE_STATIC; +		else if (strmatch(s, "rip")) +			return ZEBRA_ROUTE_RIP; +		else if (strmatch(s, "ospf")) +			return ZEBRA_ROUTE_OSPF; +		else if (strmatch(s, "isis")) +			return ZEBRA_ROUTE_ISIS; +		else if (strmatch(s, "bgp")) +			return ZEBRA_ROUTE_BGP; +		else if (strmatch(s, "table")) +			return ZEBRA_ROUTE_TABLE; +		else if (strmatch(s, "vnc")) +			return ZEBRA_ROUTE_VNC; +		else if (strmatch(s, "vnc-direct")) +			return ZEBRA_ROUTE_VNC_DIRECT; +		else if (strmatch(s, "nhrp")) +			return ZEBRA_ROUTE_NHRP; +	} +	if (afi == AFI_IP6) { +		if (strmatch(s, "kernel")) +			return ZEBRA_ROUTE_KERNEL; +		else if (strmatch(s, "connected")) +			return ZEBRA_ROUTE_CONNECT; +		else if (strmatch(s, "static")) +			return ZEBRA_ROUTE_STATIC; +		else if (strmatch(s, "ripng")) +			return ZEBRA_ROUTE_RIPNG; +		else if (strmatch(s, "ospf6")) +			return ZEBRA_ROUTE_OSPF6; +		else if (strmatch(s, "isis")) +			return ZEBRA_ROUTE_ISIS; +		else if (strmatch(s, "bgp")) +			return ZEBRA_ROUTE_BGP; +		else if (strmatch(s, "table")) +			return ZEBRA_ROUTE_TABLE; +		else if (strmatch(s, "vnc")) +			return ZEBRA_ROUTE_VNC; +		else if (strmatch(s, "vnc-direct")) +			return ZEBRA_ROUTE_VNC_DIRECT; +		else if (strmatch(s, "nhrp")) +			return ZEBRA_ROUTE_NHRP; +	} +	return -1;  } -void -zlog_hexdump (const void *mem, unsigned int len) { -  unsigned long i = 0; -  unsigned int j = 0; -  unsigned int columns = 8; -  char buf[(len * 4) + ((len/4) * 20) + 30]; -  char *s = buf; - -  for (i = 0; i < len + ((len % columns) ? (columns - len % columns) : 0); i++) -    { -      /* print offset */ -      if (i % columns == 0) -        s += sprintf(s, "0x%016lx: ", (unsigned long)mem + i); - -      /* print hex data */ -      if (i < len) -        s += sprintf(s, "%02x ", 0xFF & ((const char*)mem)[i]); - -      /* end of block, just aligning for ASCII dump */ -      else -        s += sprintf(s, "   "); - -      /* print ASCII dump */ -      if (i % columns == (columns - 1)) -        { -          for (j = i - (columns - 1); j <= i; j++) -            { -              if (j >= len) /* end of block, not really printing */ -                s += sprintf(s, " "); - -              else if(isprint((int)((const char *)mem)[j])) /* printable char */ -                s += sprintf(s, "%c", 0xFF & ((const char *)mem)[j]); - -              else /* other char */ -                s += sprintf(s, "."); -            } -          s += sprintf(s, "\n"); -        } -    } -    zlog_debug("\n%s", buf); +void zlog_hexdump(const void *mem, unsigned int len) +{ +	unsigned long i = 0; +	unsigned int j = 0; +	unsigned int columns = 8; +	char buf[(len * 4) + ((len / 4) * 20) + 30]; +	char *s = buf; + +	for (i = 0; i < len + ((len % columns) ? (columns - len % columns) : 0); +	     i++) { +		/* print offset */ +		if (i % columns == 0) +			s += sprintf(s, "0x%016lx: ", (unsigned long)mem + i); + +		/* print hex data */ +		if (i < len) +			s += sprintf(s, "%02x ", 0xFF & ((const char *)mem)[i]); + +		/* end of block, just aligning for ASCII dump */ +		else +			s += sprintf(s, "   "); + +		/* print ASCII dump */ +		if (i % columns == (columns - 1)) { +			for (j = i - (columns - 1); j <= i; j++) { +				if (j >= len) /* end of block, not really +						 printing */ +					s += sprintf(s, " "); + +				else if ( +					isprint((int)((const char *)mem) +							[j])) /* printable char +								 */ +					s += sprintf( +						s, "%c", +						0xFF & ((const char *)mem)[j]); + +				else /* other char */ +					s += sprintf(s, "."); +			} +			s += sprintf(s, "\n"); +		} +	} +	zlog_debug("\n%s", buf);  } -const char * -zlog_sanitize (char *buf, size_t bufsz, const void *in, size_t inlen) +const char *zlog_sanitize(char *buf, size_t bufsz, const void *in, size_t inlen)  { -  const char *inbuf = in; -  char *pos = buf, *end = buf + bufsz; -  const char *iend = inbuf + inlen; - -  memset (buf, 0, bufsz); -  for (; inbuf < iend; inbuf++) -    { -      /* don't write partial escape sequence */ -      if (end - pos < 5) -        break; - -      if (*inbuf == '\n') -        snprintf (pos, end - pos, "\\n"); -      else if (*inbuf == '\r') -        snprintf (pos, end - pos, "\\r"); -      else if (*inbuf == '\t') -        snprintf (pos, end - pos, "\\t"); -      else if (*inbuf < ' ' || *inbuf == '"' || *inbuf >= 127) -        snprintf (pos, end - pos, "\\x%02hhx", *inbuf); -      else -        *pos = *inbuf; - -      pos += strlen (pos); -    } -  return buf; +	const char *inbuf = in; +	char *pos = buf, *end = buf + bufsz; +	const char *iend = inbuf + inlen; + +	memset(buf, 0, bufsz); +	for (; inbuf < iend; inbuf++) { +		/* don't write partial escape sequence */ +		if (end - pos < 5) +			break; + +		if (*inbuf == '\n') +			snprintf(pos, end - pos, "\\n"); +		else if (*inbuf == '\r') +			snprintf(pos, end - pos, "\\r"); +		else if (*inbuf == '\t') +			snprintf(pos, end - pos, "\\t"); +		else if (*inbuf < ' ' || *inbuf == '"' || *inbuf >= 127) +			snprintf(pos, end - pos, "\\x%02hhx", *inbuf); +		else +			*pos = *inbuf; + +		pos += strlen(pos); +	} +	return buf;  } @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_LOG_H @@ -46,30 +46,28 @@     to that logging destination. */  #define ZLOG_DISABLED	(LOG_EMERG-1) -typedef enum -{ -  ZLOG_DEST_SYSLOG = 0, -  ZLOG_DEST_STDOUT, -  ZLOG_DEST_MONITOR, -  ZLOG_DEST_FILE +typedef enum { +	ZLOG_DEST_SYSLOG = 0, +	ZLOG_DEST_STDOUT, +	ZLOG_DEST_MONITOR, +	ZLOG_DEST_FILE  } zlog_dest_t;  #define ZLOG_NUM_DESTS		(ZLOG_DEST_FILE+1)  /* Message structure. */ -struct message -{ -  int key; -  const char *str; +struct message { +	int key; +	const char *str;  };  /* Open zlog function */ -extern void openzlog (const char *progname, const char *protoname, -                      u_short instance, int syslog_options, int syslog_facility); +extern void openzlog(const char *progname, const char *protoname, +		     u_short instance, int syslog_options, int syslog_facility);  /* Close zlog function. */ -extern void closezlog (void); +extern void closezlog(void); -extern const char *zlog_protoname (void); +extern const char *zlog_protoname(void);  /* GCC have printf type attribute check.  */  #ifdef __GNUC__ @@ -79,29 +77,29 @@ extern const char *zlog_protoname (void);  #endif /* __GNUC__ */  /* Handy zlog functions. */ -extern void zlog_err (const char *format, ...) PRINTF_ATTRIBUTE(1, 2); -extern void zlog_warn (const char *format, ...) PRINTF_ATTRIBUTE(1, 2); -extern void zlog_info (const char *format, ...) PRINTF_ATTRIBUTE(1, 2); -extern void zlog_notice (const char *format, ...) PRINTF_ATTRIBUTE(1, 2); -extern void zlog_debug (const char *format, ...) PRINTF_ATTRIBUTE(1, 2); +extern void zlog_err(const char *format, ...) PRINTF_ATTRIBUTE(1, 2); +extern void zlog_warn(const char *format, ...) PRINTF_ATTRIBUTE(1, 2); +extern void zlog_info(const char *format, ...) PRINTF_ATTRIBUTE(1, 2); +extern void zlog_notice(const char *format, ...) PRINTF_ATTRIBUTE(1, 2); +extern void zlog_debug(const char *format, ...) PRINTF_ATTRIBUTE(1, 2); -extern void zlog_thread_info (int log_level); +extern void zlog_thread_info(int log_level);  /* Set logging level for the given destination.  If the log_level     argument is ZLOG_DISABLED, then the destination is disabled.     This function should not be used for file logging (use zlog_set_file     or zlog_reset_file instead). */ -extern void zlog_set_level (zlog_dest_t, int log_level); +extern void zlog_set_level(zlog_dest_t, int log_level);  /* Set logging to the given filename at the specified level. */ -extern int zlog_set_file (const char *filename, int log_level); +extern int zlog_set_file(const char *filename, int log_level);  /* Disable file logging. */ -extern int zlog_reset_file (void); +extern int zlog_reset_file(void);  /* Rotate log. */ -extern int zlog_rotate (void); +extern int zlog_rotate(void); -const char *lookup_msg (const struct message *mz, int kz, const char *nf); +const char *lookup_msg(const struct message *mz, int kz, const char *nf);  /* Safe version of strerror -- never returns NULL. */  extern const char *safe_strerror(int errnum); @@ -109,9 +107,10 @@ extern const char *safe_strerror(int errnum);  /* To be called when a fatal signal is caught. */  extern void zlog_signal(int signo, const char *action  #ifdef SA_SIGINFO -			, siginfo_t *siginfo, void *program_counter +			, +			siginfo_t *siginfo, void *program_counter  #endif -		       ); +			);  /* Log a backtrace. */  extern void zlog_backtrace(int priority); @@ -133,49 +132,51 @@ extern size_t quagga_timestamp(int timestamp_precision /* # subsecond digits */,  			       char *buf, size_t buflen);  extern void zlog_hexdump(const void *mem, unsigned int len); -extern const char *zlog_sanitize(char *buf, size_t bufsz, const void *in, size_t inlen); +extern const char *zlog_sanitize(char *buf, size_t bufsz, const void *in, +				 size_t inlen); -extern int vzlog_test (int priority); +extern int vzlog_test(int priority);  /* structure useful for avoiding repeated rendering of the same timestamp */  struct timestamp_control { -   size_t len;		/* length of rendered timestamp */ -   int precision;	/* configuration parameter */ -   int already_rendered; /* should be initialized to 0 */ -   char buf[QUAGGA_TIMESTAMP_LEN];	/* will contain the rendered timestamp */ +	size_t len;			/* length of rendered timestamp */ +	int precision;			/* configuration parameter */ +	int already_rendered;		/* should be initialized to 0 */ +	char buf[QUAGGA_TIMESTAMP_LEN]; /* will contain the rendered timestamp +					   */  };  /* Defines for use in command construction: */ -#define LOG_LEVEL_DESC \ -  "System is unusable\n" \ -  "Immediate action needed\n" \ -  "Critical conditions\n" \ -  "Error conditions\n" \ -  "Warning conditions\n" \ -  "Normal but significant conditions\n" \ -  "Informational messages\n" \ -  "Debugging messages\n" - -#define LOG_FACILITY_DESC \ -       "Kernel\n" \ -       "User process\n" \ -       "Mail system\n" \ -       "System daemons\n" \ -       "Authorization system\n" \ -       "Syslog itself\n" \ -       "Line printer system\n" \ -       "USENET news\n" \ -       "Unix-to-Unix copy system\n" \ -       "Cron/at facility\n" \ -       "Local use\n" \ -       "Local use\n" \ -       "Local use\n" \ -       "Local use\n" \ -       "Local use\n" \ -       "Local use\n" \ -       "Local use\n" \ -       "Local use\n" +#define LOG_LEVEL_DESC                                                         \ +	"System is unusable\n"                                                 \ +	"Immediate action needed\n"                                            \ +	"Critical conditions\n"                                                \ +	"Error conditions\n"                                                   \ +	"Warning conditions\n"                                                 \ +	"Normal but significant conditions\n"                                  \ +	"Informational messages\n"                                             \ +	"Debugging messages\n" + +#define LOG_FACILITY_DESC                                                      \ +	"Kernel\n"                                                             \ +	"User process\n"                                                       \ +	"Mail system\n"                                                        \ +	"System daemons\n"                                                     \ +	"Authorization system\n"                                               \ +	"Syslog itself\n"                                                      \ +	"Line printer system\n"                                                \ +	"USENET news\n"                                                        \ +	"Unix-to-Unix copy system\n"                                           \ +	"Cron/at facility\n"                                                   \ +	"Local use\n"                                                          \ +	"Local use\n"                                                          \ +	"Local use\n"                                                          \ +	"Local use\n"                                                          \ +	"Local use\n"                                                          \ +	"Local use\n"                                                          \ +	"Local use\n"                                                          \ +	"Local use\n"  #endif /* _ZEBRA_LOG_H */ diff --git a/lib/log_int.h b/lib/log_int.h index c21d723ac6..01197a1f57 100644 --- a/lib/log_int.h +++ b/lib/log_int.h @@ -25,21 +25,20 @@  #include "log.h" -struct zlog -{ -  const char *ident;	/* daemon name (first arg to openlog) */ -  const char *protoname; -  u_short instance; -  int maxlvl[ZLOG_NUM_DESTS];   /* maximum priority to send to associated -                                   logging destination */ -  int default_lvl;      /* maxlvl to use if none is specified */ -  FILE *fp; -  char *filename; -  int facility;         /* as per syslog facility */ -  int record_priority;  /* should messages logged through stdio include the -                           priority of the message? */ -  int syslog_options;   /* 2nd arg to openlog */ -  int timestamp_precision;      /* # of digits of subsecond precision */ +struct zlog { +	const char *ident; /* daemon name (first arg to openlog) */ +	const char *protoname; +	u_short instance; +	int maxlvl[ZLOG_NUM_DESTS]; /* maximum priority to send to associated +				       logging destination */ +	int default_lvl;	    /* maxlvl to use if none is specified */ +	FILE *fp; +	char *filename; +	int facility;	/* as per syslog facility */ +	int record_priority; /* should messages logged through stdio include the +				priority of the message? */ +	int syslog_options;  /* 2nd arg to openlog */ +	int timestamp_precision; /* # of digits of subsecond precision */  };  /* Default logging strucutre. */ @@ -48,10 +47,7 @@ extern struct zlog *zlog_default;  extern const char *zlog_priority[];  /* Generic function for zlog. */ -extern void vzlog (int priority, const char *format, va_list args); -extern void zlog (int priority, const char *format, ...) -  PRINTF_ATTRIBUTE(2, 3); +extern void vzlog(int priority, const char *format, va_list args); +extern void zlog(int priority, const char *format, ...) PRINTF_ATTRIBUTE(2, 3);  #endif /* _ZEBRA_LOG_PRIVATE_H */ - - @@ -49,29 +49,33 @@  #define H(X, Y, Z) ((X) ^ (Y) ^ (Z))  #define I(X, Y, Z) ((Y) ^ ((X) | (~Z))) -#define ROUND1(a, b, c, d, k, s, i) { \ -	(a) = (a) + F((b), (c), (d)) + X[(k)] + T[(i)]; \ -	(a) = SHIFT((a), (s)); \ -	(a) = (b) + (a); \ -} +#define ROUND1(a, b, c, d, k, s, i)                                            \ +	{                                                                      \ +		(a) = (a) + F((b), (c), (d)) + X[(k)] + T[(i)];                \ +		(a) = SHIFT((a), (s));                                         \ +		(a) = (b) + (a);                                               \ +	} -#define ROUND2(a, b, c, d, k, s, i) { \ -	(a) = (a) + G((b), (c), (d)) + X[(k)] + T[(i)]; \ -	(a) = SHIFT((a), (s)); \ -	(a) = (b) + (a); \ -} +#define ROUND2(a, b, c, d, k, s, i)                                            \ +	{                                                                      \ +		(a) = (a) + G((b), (c), (d)) + X[(k)] + T[(i)];                \ +		(a) = SHIFT((a), (s));                                         \ +		(a) = (b) + (a);                                               \ +	} -#define ROUND3(a, b, c, d, k, s, i) { \ -	(a) = (a) + H((b), (c), (d)) + X[(k)] + T[(i)]; \ -	(a) = SHIFT((a), (s)); \ -	(a) = (b) + (a); \ -} +#define ROUND3(a, b, c, d, k, s, i)                                            \ +	{                                                                      \ +		(a) = (a) + H((b), (c), (d)) + X[(k)] + T[(i)];                \ +		(a) = SHIFT((a), (s));                                         \ +		(a) = (b) + (a);                                               \ +	} -#define ROUND4(a, b, c, d, k, s, i) { \ -	(a) = (a) + I((b), (c), (d)) + X[(k)] + T[(i)]; \ -	(a) = SHIFT((a), (s)); \ -	(a) = (b) + (a); \ -} +#define ROUND4(a, b, c, d, k, s, i)                                            \ +	{                                                                      \ +		(a) = (a) + I((b), (c), (d)) + X[(k)] + T[(i)];                \ +		(a) = SHIFT((a), (s));                                         \ +		(a) = (b) + (a);                                               \ +	}  #define Sa	 7  #define Sb	12 @@ -100,40 +104,30 @@  /* Integer part of 4294967296 times abs(sin(i)), where i is in radians. */  static const uint32_t T[65] = { -	0, -	0xd76aa478, 	0xe8c7b756,	0x242070db,	0xc1bdceee, -	0xf57c0faf,	0x4787c62a, 	0xa8304613,	0xfd469501, -	0x698098d8,	0x8b44f7af,	0xffff5bb1,	0x895cd7be, -	0x6b901122, 	0xfd987193, 	0xa679438e,	0x49b40821, - -	0xf61e2562,	0xc040b340, 	0x265e5a51, 	0xe9b6c7aa, -	0xd62f105d,	0x2441453,	0xd8a1e681,	0xe7d3fbc8, -	0x21e1cde6,	0xc33707d6, 	0xf4d50d87, 	0x455a14ed, -	0xa9e3e905,	0xfcefa3f8, 	0x676f02d9, 	0x8d2a4c8a, - -	0xfffa3942,	0x8771f681, 	0x6d9d6122, 	0xfde5380c, -	0xa4beea44, 	0x4bdecfa9, 	0xf6bb4b60, 	0xbebfbc70, -	0x289b7ec6, 	0xeaa127fa, 	0xd4ef3085,	0x4881d05, -	0xd9d4d039, 	0xe6db99e5, 	0x1fa27cf8, 	0xc4ac5665, - -	0xf4292244, 	0x432aff97, 	0xab9423a7, 	0xfc93a039, -	0x655b59c3, 	0x8f0ccc92, 	0xffeff47d, 	0x85845dd1, -	0x6fa87e4f, 	0xfe2ce6e0, 	0xa3014314, 	0x4e0811a1, -	0xf7537e82, 	0xbd3af235, 	0x2ad7d2bb, 	0xeb86d391, +	0,	  0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, +	0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, +	0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + +	0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x2441453, +	0xd8a1e681, 0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, +	0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + +	0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, 0xa4beea44, 0x4bdecfa9, +	0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, +	0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + +	0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, +	0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, +	0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,  };  static const uint8_t md5_paddat[MD5_BUFLEN] = { -	0x80,	0,	0,	0,	0,	0,	0,	0, -	0,	0,	0,	0,	0,	0,	0,	0, -	0,	0,	0,	0,	0,	0,	0,	0, -	0,	0,	0,	0,	0,	0,	0,	0, -	0,	0,	0,	0,	0,	0,	0,	0, -	0,	0,	0,	0,	0,	0,	0,	0, -	0,	0,	0,	0,	0,	0,	0,	0, -	0,	0,	0,	0,	0,	0,	0,	0,	 +	0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +	0,    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, +	0,    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  }; -static void md5_calc (const uint8_t *, md5_ctxt *); +static void md5_calc(const uint8_t *, md5_ctxt *);  void md5_init(md5_ctxt *ctxt)  { @@ -143,7 +137,7 @@ void md5_init(md5_ctxt *ctxt)  	ctxt->md5_stb = MD5_B0;  	ctxt->md5_stc = MD5_C0;  	ctxt->md5_std = MD5_D0; -	memset (ctxt->md5_buf, 0, sizeof(ctxt->md5_buf)); +	memset(ctxt->md5_buf, 0, sizeof(ctxt->md5_buf));  }  void md5_loop(md5_ctxt *ctxt, const void *vinput, uint len) @@ -155,17 +149,17 @@ void md5_loop(md5_ctxt *ctxt, const void *vinput, uint len)  	gap = MD5_BUFLEN - ctxt->md5_i;  	if (len >= gap) { -		memcpy (ctxt->md5_buf + ctxt->md5_i, input, gap); +		memcpy(ctxt->md5_buf + ctxt->md5_i, input, gap);  		md5_calc(ctxt->md5_buf, ctxt);  		for (i = gap; i + MD5_BUFLEN <= len; i += MD5_BUFLEN) {  			md5_calc((input + i), ctxt);  		} -		 +  		ctxt->md5_i = len - i; -		memcpy (ctxt->md5_buf, (input + i), ctxt->md5_i); +		memcpy(ctxt->md5_buf, (input + i), ctxt->md5_i);  	} else { -		memcpy (ctxt->md5_buf + ctxt->md5_i, input, len); +		memcpy(ctxt->md5_buf + ctxt->md5_i, input, len);  		ctxt->md5_i += len;  	}  } @@ -174,33 +168,32 @@ void md5_pad(md5_ctxt *ctxt)  {  	uint gap; -	/* Don't count up padding. Keep md5_n. */	 +	/* Don't count up padding. Keep md5_n. */  	gap = MD5_BUFLEN - ctxt->md5_i;  	if (gap > 8) { -		memcpy (ctxt->md5_buf + ctxt->md5_i, md5_paddat,  -			gap - sizeof(ctxt->md5_n)); +		memcpy(ctxt->md5_buf + ctxt->md5_i, md5_paddat, +		       gap - sizeof(ctxt->md5_n));  	} else {  		/* including gap == 8 */ -		memcpy (ctxt->md5_buf + ctxt->md5_i, md5_paddat, gap); -		md5_calc (ctxt->md5_buf, ctxt); -		memcpy (ctxt->md5_buf, md5_paddat + gap, -			MD5_BUFLEN - sizeof(ctxt->md5_n)); +		memcpy(ctxt->md5_buf + ctxt->md5_i, md5_paddat, gap); +		md5_calc(ctxt->md5_buf, ctxt); +		memcpy(ctxt->md5_buf, md5_paddat + gap, +		       MD5_BUFLEN - sizeof(ctxt->md5_n));  	} -	/* 8 byte word */	 +	/* 8 byte word */  	if (BYTE_ORDER == LITTLE_ENDIAN) -	  memcpy (&ctxt->md5_buf[56], &ctxt->md5_n8[0], 8); -	else -	  { -	    ctxt->md5_buf[56] = ctxt->md5_n8[7]; -	    ctxt->md5_buf[57] = ctxt->md5_n8[6]; -	    ctxt->md5_buf[58] = ctxt->md5_n8[5]; -	    ctxt->md5_buf[59] = ctxt->md5_n8[4]; -	    ctxt->md5_buf[60] = ctxt->md5_n8[3]; -	    ctxt->md5_buf[61] = ctxt->md5_n8[2]; -	    ctxt->md5_buf[62] = ctxt->md5_n8[1]; -	    ctxt->md5_buf[63] = ctxt->md5_n8[0]; -	  } +		memcpy(&ctxt->md5_buf[56], &ctxt->md5_n8[0], 8); +	else { +		ctxt->md5_buf[56] = ctxt->md5_n8[7]; +		ctxt->md5_buf[57] = ctxt->md5_n8[6]; +		ctxt->md5_buf[58] = ctxt->md5_n8[5]; +		ctxt->md5_buf[59] = ctxt->md5_n8[4]; +		ctxt->md5_buf[60] = ctxt->md5_n8[3]; +		ctxt->md5_buf[61] = ctxt->md5_n8[2]; +		ctxt->md5_buf[62] = ctxt->md5_n8[1]; +		ctxt->md5_buf[63] = ctxt->md5_n8[0]; +	}  	md5_calc(ctxt->md5_buf, ctxt);  } @@ -208,21 +201,28 @@ void md5_result(uint8_t *digest, md5_ctxt *ctxt)  {  	/* 4 byte words */  	if (BYTE_ORDER == LITTLE_ENDIAN) -	  memcpy (digest, &ctxt->md5_st8[0], 16); -	else if (BYTE_ORDER == BIG_ENDIAN) -	  { -	    digest[ 0] = ctxt->md5_st8[ 3]; digest[ 1] = ctxt->md5_st8[ 2]; -	    digest[ 2] = ctxt->md5_st8[ 1]; digest[ 3] = ctxt->md5_st8[ 0]; -	    digest[ 4] = ctxt->md5_st8[ 7]; digest[ 5] = ctxt->md5_st8[ 6]; -	    digest[ 6] = ctxt->md5_st8[ 5]; digest[ 7] = ctxt->md5_st8[ 4]; -	    digest[ 8] = ctxt->md5_st8[11]; digest[ 9] = ctxt->md5_st8[10]; -	    digest[10] = ctxt->md5_st8[ 9]; digest[11] = ctxt->md5_st8[ 8]; -	    digest[12] = ctxt->md5_st8[15]; digest[13] = ctxt->md5_st8[14]; -	    digest[14] = ctxt->md5_st8[13]; digest[15] = ctxt->md5_st8[12]; -	  } +		memcpy(digest, &ctxt->md5_st8[0], 16); +	else if (BYTE_ORDER == BIG_ENDIAN) { +		digest[0] = ctxt->md5_st8[3]; +		digest[1] = ctxt->md5_st8[2]; +		digest[2] = ctxt->md5_st8[1]; +		digest[3] = ctxt->md5_st8[0]; +		digest[4] = ctxt->md5_st8[7]; +		digest[5] = ctxt->md5_st8[6]; +		digest[6] = ctxt->md5_st8[5]; +		digest[7] = ctxt->md5_st8[4]; +		digest[8] = ctxt->md5_st8[11]; +		digest[9] = ctxt->md5_st8[10]; +		digest[10] = ctxt->md5_st8[9]; +		digest[11] = ctxt->md5_st8[8]; +		digest[12] = ctxt->md5_st8[15]; +		digest[13] = ctxt->md5_st8[14]; +		digest[14] = ctxt->md5_st8[13]; +		digest[15] = ctxt->md5_st8[12]; +	}  } -static void md5_calc(const uint8_t *b64, md5_ctxt * ctxt) +static void md5_calc(const uint8_t *b64, md5_ctxt *ctxt)  {  	uint32_t A = ctxt->md5_sta;  	uint32_t B = ctxt->md5_stb; @@ -233,65 +233,144 @@ static void md5_calc(const uint8_t *b64, md5_ctxt * ctxt)  #elif (BYTE_ORDER == BIG_ENDIAN)  	uint32_t X[16]; -	if (BYTE_ORDER == BIG_ENDIAN) -	  { -	    /* 4 byte words */ -	    /* what a brute force but fast! */ -	    uint8_t *y = (uint8_t *)X; -	    y[ 0] = b64[ 3]; y[ 1] = b64[ 2]; y[ 2] = b64[ 1]; y[ 3] = b64[ 0]; -	    y[ 4] = b64[ 7]; y[ 5] = b64[ 6]; y[ 6] = b64[ 5]; y[ 7] = b64[ 4]; -	    y[ 8] = b64[11]; y[ 9] = b64[10]; y[10] = b64[ 9]; y[11] = b64[ 8]; -	    y[12] = b64[15]; y[13] = b64[14]; y[14] = b64[13]; y[15] = b64[12]; -	    y[16] = b64[19]; y[17] = b64[18]; y[18] = b64[17]; y[19] = b64[16]; -	    y[20] = b64[23]; y[21] = b64[22]; y[22] = b64[21]; y[23] = b64[20]; -	    y[24] = b64[27]; y[25] = b64[26]; y[26] = b64[25]; y[27] = b64[24]; -	    y[28] = b64[31]; y[29] = b64[30]; y[30] = b64[29]; y[31] = b64[28]; -	    y[32] = b64[35]; y[33] = b64[34]; y[34] = b64[33]; y[35] = b64[32]; -	    y[36] = b64[39]; y[37] = b64[38]; y[38] = b64[37]; y[39] = b64[36]; -	    y[40] = b64[43]; y[41] = b64[42]; y[42] = b64[41]; y[43] = b64[40]; -	    y[44] = b64[47]; y[45] = b64[46]; y[46] = b64[45]; y[47] = b64[44]; -	    y[48] = b64[51]; y[49] = b64[50]; y[50] = b64[49]; y[51] = b64[48]; -	    y[52] = b64[55]; y[53] = b64[54]; y[54] = b64[53]; y[55] = b64[52]; -	    y[56] = b64[59]; y[57] = b64[58]; y[58] = b64[57]; y[59] = b64[56]; -	    y[60] = b64[63]; y[61] = b64[62]; y[62] = b64[61]; y[63] = b64[60]; -	  } +	if (BYTE_ORDER == BIG_ENDIAN) { +		/* 4 byte words */ +		/* what a brute force but fast! */ +		uint8_t *y = (uint8_t *)X; +		y[0] = b64[3]; +		y[1] = b64[2]; +		y[2] = b64[1]; +		y[3] = b64[0]; +		y[4] = b64[7]; +		y[5] = b64[6]; +		y[6] = b64[5]; +		y[7] = b64[4]; +		y[8] = b64[11]; +		y[9] = b64[10]; +		y[10] = b64[9]; +		y[11] = b64[8]; +		y[12] = b64[15]; +		y[13] = b64[14]; +		y[14] = b64[13]; +		y[15] = b64[12]; +		y[16] = b64[19]; +		y[17] = b64[18]; +		y[18] = b64[17]; +		y[19] = b64[16]; +		y[20] = b64[23]; +		y[21] = b64[22]; +		y[22] = b64[21]; +		y[23] = b64[20]; +		y[24] = b64[27]; +		y[25] = b64[26]; +		y[26] = b64[25]; +		y[27] = b64[24]; +		y[28] = b64[31]; +		y[29] = b64[30]; +		y[30] = b64[29]; +		y[31] = b64[28]; +		y[32] = b64[35]; +		y[33] = b64[34]; +		y[34] = b64[33]; +		y[35] = b64[32]; +		y[36] = b64[39]; +		y[37] = b64[38]; +		y[38] = b64[37]; +		y[39] = b64[36]; +		y[40] = b64[43]; +		y[41] = b64[42]; +		y[42] = b64[41]; +		y[43] = b64[40]; +		y[44] = b64[47]; +		y[45] = b64[46]; +		y[46] = b64[45]; +		y[47] = b64[44]; +		y[48] = b64[51]; +		y[49] = b64[50]; +		y[50] = b64[49]; +		y[51] = b64[48]; +		y[52] = b64[55]; +		y[53] = b64[54]; +		y[54] = b64[53]; +		y[55] = b64[52]; +		y[56] = b64[59]; +		y[57] = b64[58]; +		y[58] = b64[57]; +		y[59] = b64[56]; +		y[60] = b64[63]; +		y[61] = b64[62]; +		y[62] = b64[61]; +		y[63] = b64[60]; +	}  #endif -	ROUND1(A, B, C, D,  0, Sa,  1); ROUND1(D, A, B, C,  1, Sb,  2); -	ROUND1(C, D, A, B,  2, Sc,  3); ROUND1(B, C, D, A,  3, Sd,  4); -	ROUND1(A, B, C, D,  4, Sa,  5); ROUND1(D, A, B, C,  5, Sb,  6); -	ROUND1(C, D, A, B,  6, Sc,  7); ROUND1(B, C, D, A,  7, Sd,  8); -	ROUND1(A, B, C, D,  8, Sa,  9); ROUND1(D, A, B, C,  9, Sb, 10); -	ROUND1(C, D, A, B, 10, Sc, 11); ROUND1(B, C, D, A, 11, Sd, 12); -	ROUND1(A, B, C, D, 12, Sa, 13); ROUND1(D, A, B, C, 13, Sb, 14); -	ROUND1(C, D, A, B, 14, Sc, 15); ROUND1(B, C, D, A, 15, Sd, 16); -	 -	ROUND2(A, B, C, D,  1, Se, 17); ROUND2(D, A, B, C,  6, Sf, 18); -	ROUND2(C, D, A, B, 11, Sg, 19); ROUND2(B, C, D, A,  0, Sh, 20); -	ROUND2(A, B, C, D,  5, Se, 21); ROUND2(D, A, B, C, 10, Sf, 22); -	ROUND2(C, D, A, B, 15, Sg, 23); ROUND2(B, C, D, A,  4, Sh, 24); -	ROUND2(A, B, C, D,  9, Se, 25); ROUND2(D, A, B, C, 14, Sf, 26); -	ROUND2(C, D, A, B,  3, Sg, 27); ROUND2(B, C, D, A,  8, Sh, 28); -	ROUND2(A, B, C, D, 13, Se, 29); ROUND2(D, A, B, C,  2, Sf, 30); -	ROUND2(C, D, A, B,  7, Sg, 31); ROUND2(B, C, D, A, 12, Sh, 32); - -	ROUND3(A, B, C, D,  5, Si, 33); ROUND3(D, A, B, C,  8, Sj, 34); -	ROUND3(C, D, A, B, 11, Sk, 35); ROUND3(B, C, D, A, 14, Sl, 36); -	ROUND3(A, B, C, D,  1, Si, 37); ROUND3(D, A, B, C,  4, Sj, 38); -	ROUND3(C, D, A, B,  7, Sk, 39); ROUND3(B, C, D, A, 10, Sl, 40); -	ROUND3(A, B, C, D, 13, Si, 41); ROUND3(D, A, B, C,  0, Sj, 42); -	ROUND3(C, D, A, B,  3, Sk, 43); ROUND3(B, C, D, A,  6, Sl, 44); -	ROUND3(A, B, C, D,  9, Si, 45); ROUND3(D, A, B, C, 12, Sj, 46); -	ROUND3(C, D, A, B, 15, Sk, 47); ROUND3(B, C, D, A,  2, Sl, 48); -	 -	ROUND4(A, B, C, D,  0, Sm, 49); ROUND4(D, A, B, C,  7, Sn, 50);	 -	ROUND4(C, D, A, B, 14, So, 51); ROUND4(B, C, D, A,  5, Sp, 52);	 -	ROUND4(A, B, C, D, 12, Sm, 53); ROUND4(D, A, B, C,  3, Sn, 54);	 -	ROUND4(C, D, A, B, 10, So, 55); ROUND4(B, C, D, A,  1, Sp, 56);	 -	ROUND4(A, B, C, D,  8, Sm, 57); ROUND4(D, A, B, C, 15, Sn, 58);	 -	ROUND4(C, D, A, B,  6, So, 59); ROUND4(B, C, D, A, 13, Sp, 60);	 -	ROUND4(A, B, C, D,  4, Sm, 61); ROUND4(D, A, B, C, 11, Sn, 62);	 -	ROUND4(C, D, A, B,  2, So, 63); ROUND4(B, C, D, A,  9, Sp, 64); +	ROUND1(A, B, C, D, 0, Sa, 1); +	ROUND1(D, A, B, C, 1, Sb, 2); +	ROUND1(C, D, A, B, 2, Sc, 3); +	ROUND1(B, C, D, A, 3, Sd, 4); +	ROUND1(A, B, C, D, 4, Sa, 5); +	ROUND1(D, A, B, C, 5, Sb, 6); +	ROUND1(C, D, A, B, 6, Sc, 7); +	ROUND1(B, C, D, A, 7, Sd, 8); +	ROUND1(A, B, C, D, 8, Sa, 9); +	ROUND1(D, A, B, C, 9, Sb, 10); +	ROUND1(C, D, A, B, 10, Sc, 11); +	ROUND1(B, C, D, A, 11, Sd, 12); +	ROUND1(A, B, C, D, 12, Sa, 13); +	ROUND1(D, A, B, C, 13, Sb, 14); +	ROUND1(C, D, A, B, 14, Sc, 15); +	ROUND1(B, C, D, A, 15, Sd, 16); + +	ROUND2(A, B, C, D, 1, Se, 17); +	ROUND2(D, A, B, C, 6, Sf, 18); +	ROUND2(C, D, A, B, 11, Sg, 19); +	ROUND2(B, C, D, A, 0, Sh, 20); +	ROUND2(A, B, C, D, 5, Se, 21); +	ROUND2(D, A, B, C, 10, Sf, 22); +	ROUND2(C, D, A, B, 15, Sg, 23); +	ROUND2(B, C, D, A, 4, Sh, 24); +	ROUND2(A, B, C, D, 9, Se, 25); +	ROUND2(D, A, B, C, 14, Sf, 26); +	ROUND2(C, D, A, B, 3, Sg, 27); +	ROUND2(B, C, D, A, 8, Sh, 28); +	ROUND2(A, B, C, D, 13, Se, 29); +	ROUND2(D, A, B, C, 2, Sf, 30); +	ROUND2(C, D, A, B, 7, Sg, 31); +	ROUND2(B, C, D, A, 12, Sh, 32); + +	ROUND3(A, B, C, D, 5, Si, 33); +	ROUND3(D, A, B, C, 8, Sj, 34); +	ROUND3(C, D, A, B, 11, Sk, 35); +	ROUND3(B, C, D, A, 14, Sl, 36); +	ROUND3(A, B, C, D, 1, Si, 37); +	ROUND3(D, A, B, C, 4, Sj, 38); +	ROUND3(C, D, A, B, 7, Sk, 39); +	ROUND3(B, C, D, A, 10, Sl, 40); +	ROUND3(A, B, C, D, 13, Si, 41); +	ROUND3(D, A, B, C, 0, Sj, 42); +	ROUND3(C, D, A, B, 3, Sk, 43); +	ROUND3(B, C, D, A, 6, Sl, 44); +	ROUND3(A, B, C, D, 9, Si, 45); +	ROUND3(D, A, B, C, 12, Sj, 46); +	ROUND3(C, D, A, B, 15, Sk, 47); +	ROUND3(B, C, D, A, 2, Sl, 48); + +	ROUND4(A, B, C, D, 0, Sm, 49); +	ROUND4(D, A, B, C, 7, Sn, 50); +	ROUND4(C, D, A, B, 14, So, 51); +	ROUND4(B, C, D, A, 5, Sp, 52); +	ROUND4(A, B, C, D, 12, Sm, 53); +	ROUND4(D, A, B, C, 3, Sn, 54); +	ROUND4(C, D, A, B, 10, So, 55); +	ROUND4(B, C, D, A, 1, Sp, 56); +	ROUND4(A, B, C, D, 8, Sm, 57); +	ROUND4(D, A, B, C, 15, Sn, 58); +	ROUND4(C, D, A, B, 6, So, 59); +	ROUND4(B, C, D, A, 13, Sp, 60); +	ROUND4(A, B, C, D, 4, Sm, 61); +	ROUND4(D, A, B, C, 11, Sn, 62); +	ROUND4(C, D, A, B, 2, So, 63); +	ROUND4(B, C, D, A, 9, Sp, 64);  	ctxt->md5_sta += A;  	ctxt->md5_stb += B; @@ -300,74 +379,73 @@ static void md5_calc(const uint8_t *b64, md5_ctxt * ctxt)  }  /* From RFC 2104 */ -void -hmac_md5(text, text_len, key, key_len, digest) -unsigned char*  text;			/* pointer to data stream */ -int             text_len;		/* length of data stream */ -unsigned char*  key;			/* pointer to authentication key */ -int             key_len;		/* length of authentication key */ -uint8_t*        digest;		        /* caller digest to be filled in */ +void hmac_md5(text, text_len, key, key_len, +	      digest) unsigned char *text; /* pointer to data stream */ +int text_len;				   /* length of data stream */ +unsigned char *key;			   /* pointer to authentication key */ +int key_len;				   /* length of authentication key */ +uint8_t *digest;			   /* caller digest to be filled in */  { -    MD5_CTX context; -    unsigned char k_ipad[65];    /* inner padding - -				 * key XORd with ipad -				 */ -    unsigned char k_opad[65];    /* outer padding - -				 * key XORd with opad -				 */ -    unsigned char tk[16]; -    int i; -    /* if key is longer than 64 bytes reset it to key=MD5(key) */ -    if (key_len > 64) { - -       MD5_CTX      tctx; - -       MD5Init(&tctx); -       MD5Update(&tctx, key, key_len); -       MD5Final(tk, &tctx); - -       key = tk; -       key_len = 16; -    } - -    /* -     * the HMAC_MD5 transform looks like: -     * -     * MD5(K XOR opad, MD5(K XOR ipad, text)) -     * -     * where K is an n byte key -     * ipad is the byte 0x36 repeated 64 times -     * opad is the byte 0x5c repeated 64 times -     * and text is the data being protected -     */ - -    /* start out by storing key in pads */ -    bzero( k_ipad, sizeof k_ipad); -    bzero( k_opad, sizeof k_opad); -    bcopy( key, k_ipad, key_len); -    bcopy( key, k_opad, key_len); - -    /* XOR key with ipad and opad values */ -    for (i=0; i<64; i++) { -       k_ipad[i] ^= 0x36; -       k_opad[i] ^= 0x5c; -    } -    /* -     * perform inner MD5 -     */ -    MD5Init(&context);			/* init context for 1st -					 * pass */ -    MD5Update(&context, k_ipad, 64);	/* start with inner pad */ -    MD5Update(&context, text, text_len); /* then text of datagram */ -    MD5Final((uint8_t *)digest, &context);	/* finish up 1st pass */ -    /* -     * perform outer MD5 -     */ -    MD5Init(&context);			/* init context for 2nd -					 * pass */ -    MD5Update(&context, k_opad, 64);	/* start with outer pad */ -    MD5Update(&context, digest, 16);	/* then results of 1st -					 * hash */ -    MD5Final((uint8_t *)digest, &context);	/* finish up 2nd pass */ +	MD5_CTX context; +	unsigned char k_ipad[65]; /* inner padding - +				  * key XORd with ipad +				  */ +	unsigned char k_opad[65]; /* outer padding - +				  * key XORd with opad +				  */ +	unsigned char tk[16]; +	int i; +	/* if key is longer than 64 bytes reset it to key=MD5(key) */ +	if (key_len > 64) { + +		MD5_CTX tctx; + +		MD5Init(&tctx); +		MD5Update(&tctx, key, key_len); +		MD5Final(tk, &tctx); + +		key = tk; +		key_len = 16; +	} + +	/* +	 * the HMAC_MD5 transform looks like: +	 * +	 * MD5(K XOR opad, MD5(K XOR ipad, text)) +	 * +	 * where K is an n byte key +	 * ipad is the byte 0x36 repeated 64 times +	 * opad is the byte 0x5c repeated 64 times +	 * and text is the data being protected +	 */ + +	/* start out by storing key in pads */ +	bzero(k_ipad, sizeof k_ipad); +	bzero(k_opad, sizeof k_opad); +	bcopy(key, k_ipad, key_len); +	bcopy(key, k_opad, key_len); + +	/* XOR key with ipad and opad values */ +	for (i = 0; i < 64; i++) { +		k_ipad[i] ^= 0x36; +		k_opad[i] ^= 0x5c; +	} +	/* +	 * perform inner MD5 +	 */ +	MD5Init(&context);		       /* init context for 1st +						* pass */ +	MD5Update(&context, k_ipad, 64);       /* start with inner pad */ +	MD5Update(&context, text, text_len);   /* then text of datagram */ +	MD5Final((uint8_t *)digest, &context); /* finish up 1st pass */ +	/* +	 * perform outer MD5 +	 */ +	MD5Init(&context);		       /* init context for 2nd +						* pass */ +	MD5Update(&context, k_opad, 64);       /* start with outer pad */ +	MD5Update(&context, digest, 16);       /* then results of 1st +						* hash */ +	MD5Final((uint8_t *)digest, &context); /* finish up 2nd pass */  } @@ -46,8 +46,8 @@  typedef struct {  	union { -		uint32_t	md5_state32[4]; -		uint8_t	md5_state8[16]; +		uint32_t md5_state32[4]; +		uint8_t md5_state8[16];  	} md5_st;  #define md5_sta		md5_st.md5_state32[0] @@ -57,33 +57,33 @@ typedef struct {  #define md5_st8		md5_st.md5_state8  	union { -		uint64_t	md5_count64; -		uint8_t	md5_count8[8]; +		uint64_t md5_count64; +		uint8_t md5_count8[8];  	} md5_count;  #define md5_n	md5_count.md5_count64  #define md5_n8	md5_count.md5_count8 -	uint	md5_i; -	uint8_t	md5_buf[MD5_BUFLEN]; +	uint md5_i; +	uint8_t md5_buf[MD5_BUFLEN];  } md5_ctxt; -extern void md5_init (md5_ctxt *); -extern void md5_loop (md5_ctxt *, const void *, u_int); -extern void md5_pad (md5_ctxt *); -extern void md5_result (uint8_t *, md5_ctxt *); +extern void md5_init(md5_ctxt *); +extern void md5_loop(md5_ctxt *, const void *, u_int); +extern void md5_pad(md5_ctxt *); +extern void md5_result(uint8_t *, md5_ctxt *);  /* compatibility */  #define MD5_CTX		md5_ctxt  #define MD5Init(x)	md5_init((x))  #define MD5Update(x, y, z)	md5_loop((x), (y), (z)) -#define MD5Final(x, y) \ -do {				\ -	md5_pad((y));		\ -	md5_result((x), (y));	\ -} while (0) +#define MD5Final(x, y)                                                         \ +	do {                                                                   \ +		md5_pad((y));                                                  \ +		md5_result((x), (y));                                          \ +	} while (0)  /* From RFC 2104 */ -void hmac_md5(unsigned char* text, int text_len, unsigned char* key, -              int key_len, uint8_t *digest); +void hmac_md5(unsigned char *text, int text_len, unsigned char *key, +	      int key_len, uint8_t *digest);  #endif /* ! _LIBZEBRA_MD5_H_*/ diff --git a/lib/memory.c b/lib/memory.c index ad55366f64..9de856a2e2 100644 --- a/lib/memory.c +++ b/lib/memory.c @@ -27,119 +27,103 @@ struct memgroup **mg_insert = &mg_first;  DEFINE_MGROUP(LIB, "libfrr")  DEFINE_MTYPE(LIB, TMP, "Temporary memory") -static inline void -mt_count_alloc (struct memtype *mt, size_t size) +static inline void mt_count_alloc(struct memtype *mt, size_t size)  { -  mt->n_alloc++; +	mt->n_alloc++; -  if (mt->size == 0) -    mt->size = size; -  else if (mt->size != size) -    mt->size = SIZE_VAR; +	if (mt->size == 0) +		mt->size = size; +	else if (mt->size != size) +		mt->size = SIZE_VAR;  } -static inline void -mt_count_free (struct memtype *mt) +static inline void mt_count_free(struct memtype *mt)  { -  assert(mt->n_alloc); -  mt->n_alloc--; +	assert(mt->n_alloc); +	mt->n_alloc--;  } -static inline void * -mt_checkalloc (struct memtype *mt, void *ptr, size_t size) +static inline void *mt_checkalloc(struct memtype *mt, void *ptr, size_t size)  { -  if (__builtin_expect(ptr == NULL, 0)) -    { -      memory_oom (size, mt->name); -      return NULL; -    } -  mt_count_alloc (mt, size); -  return ptr; +	if (__builtin_expect(ptr == NULL, 0)) { +		memory_oom(size, mt->name); +		return NULL; +	} +	mt_count_alloc(mt, size); +	return ptr;  } -void * -qmalloc (struct memtype *mt, size_t size) +void *qmalloc(struct memtype *mt, size_t size)  { -  return mt_checkalloc (mt, malloc (size), size); +	return mt_checkalloc(mt, malloc(size), size);  } -void * -qcalloc (struct memtype *mt, size_t size) +void *qcalloc(struct memtype *mt, size_t size)  { -  return mt_checkalloc (mt, calloc (size, 1), size); +	return mt_checkalloc(mt, calloc(size, 1), size);  } -void * -qrealloc (struct memtype *mt, void *ptr, size_t size) +void *qrealloc(struct memtype *mt, void *ptr, size_t size)  { -  if (ptr) -    mt_count_free (mt); -  return mt_checkalloc (mt, ptr ? realloc (ptr, size) : malloc (size), size); +	if (ptr) +		mt_count_free(mt); +	return mt_checkalloc(mt, ptr ? realloc(ptr, size) : malloc(size), size);  } -void * -qstrdup (struct memtype *mt, const char *str) +void *qstrdup(struct memtype *mt, const char *str)  { -  return mt_checkalloc (mt, strdup (str), strlen (str) + 1); +	return mt_checkalloc(mt, strdup(str), strlen(str) + 1);  } -void -qfree (struct memtype *mt, void *ptr) +void qfree(struct memtype *mt, void *ptr)  { -  if (ptr) -    mt_count_free (mt); -  free (ptr); +	if (ptr) +		mt_count_free(mt); +	free(ptr);  } -int -qmem_walk (qmem_walk_fn *func, void *arg) +int qmem_walk(qmem_walk_fn *func, void *arg)  { -  struct memgroup *mg; -  struct memtype *mt; -  int rv; - -  for (mg = mg_first; mg; mg = mg->next) -    { -      if ((rv = func (arg, mg, NULL))) -        return rv; -      for (mt = mg->types; mt; mt = mt->next) -        if ((rv = func (arg, mg, mt))) -          return rv; -    } -  return 0; +	struct memgroup *mg; +	struct memtype *mt; +	int rv; + +	for (mg = mg_first; mg; mg = mg->next) { +		if ((rv = func(arg, mg, NULL))) +			return rv; +		for (mt = mg->types; mt; mt = mt->next) +			if ((rv = func(arg, mg, mt))) +				return rv; +	} +	return 0;  } -struct exit_dump_args -{ -  const char *prefix; -  int error; +struct exit_dump_args { +	const char *prefix; +	int error;  }; -static int -qmem_exit_walker (void *arg, struct memgroup *mg, struct memtype *mt) +static int qmem_exit_walker(void *arg, struct memgroup *mg, struct memtype *mt)  { -  struct exit_dump_args *eda = arg; - -  if (!mt) -    { -      fprintf (stderr, "%s: showing active allocations in memory group %s\n", -               eda->prefix, mg->name); -    } -  else if (mt->n_alloc) -    { -      char size[32]; -      eda->error++; -      snprintf (size, sizeof (size), "%10zu", mt->size); -      fprintf (stderr, "%s: memstats:  %-30s: %6zu * %s\n", -               eda->prefix, mt->name, mt->n_alloc, -               mt->size == SIZE_VAR ? "(variably sized)" : size); -    } -  return 0; +	struct exit_dump_args *eda = arg; + +	if (!mt) { +		fprintf(stderr, +			"%s: showing active allocations in memory group %s\n", +			eda->prefix, mg->name); +	} else if (mt->n_alloc) { +		char size[32]; +		eda->error++; +		snprintf(size, sizeof(size), "%10zu", mt->size); +		fprintf(stderr, "%s: memstats:  %-30s: %6zu * %s\n", +			eda->prefix, mt->name, mt->n_alloc, +			mt->size == SIZE_VAR ? "(variably sized)" : size); +	} +	return 0;  } -void -log_memstats_stderr (const char *prefix) +void log_memstats_stderr(const char *prefix)  { -  struct exit_dump_args eda = { .prefix = prefix, .error = 0 }; -  qmem_walk (qmem_exit_walker, &eda); +	struct exit_dump_args eda = {.prefix = prefix, .error = 0}; +	qmem_walk(qmem_exit_walker, &eda);  } diff --git a/lib/memory.h b/lib/memory.h index 477a6162dc..b47c7d6894 100644 --- a/lib/memory.h +++ b/lib/memory.h @@ -22,41 +22,39 @@  #define array_size(ar) (sizeof(ar) / sizeof(ar[0]))  #define SIZE_VAR ~0UL -struct memtype -{ -  struct memtype *next, **ref; -  const char *name; -  size_t n_alloc; -  size_t size; +struct memtype { +	struct memtype *next, **ref; +	const char *name; +	size_t n_alloc; +	size_t size;  }; -struct memgroup -{ -  struct memgroup *next, **ref; -  struct memtype *types, **insert; -  const char *name; +struct memgroup { +	struct memgroup *next, **ref; +	struct memtype *types, **insert; +	const char *name;  };  #if defined(__clang__) -# if __clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 5) +#if __clang_major__ > 3 || (__clang_major__ == 3 && __clang_minor__ >= 5)  #  define _RET_NONNULL  , returns_nonnull -# endif +#endif  # define _CONSTRUCTOR(x) constructor(x)  #elif defined(__GNUC__) -# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9) +#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)  #  define _RET_NONNULL  , returns_nonnull -# endif -# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3) +#endif +#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)  #  define _CONSTRUCTOR(x) constructor(x)  #  define _DESTRUCTOR(x)  destructor(x)  #  define _ALLOC_SIZE(x)  alloc_size(x) -# endif +#endif  #endif  #ifdef __sun  /* Solaris doesn't do constructor priorities due to linker restrictions */ -# undef _CONSTRUCTOR -# undef _DESTRUCTOR +#undef _CONSTRUCTOR +#undef _DESTRUCTOR  #endif  #ifndef _RET_NONNULL @@ -97,81 +95,91 @@ struct memgroup   *         but MGROUP_* aren't.   */ -#define DECLARE_MGROUP(name) \ -	extern struct memgroup _mg_##name; -#define DEFINE_MGROUP(mname, desc) \ -	struct memgroup _mg_##mname \ -	__attribute__ ((section (".data.mgroups"))) = { \ -		.name = desc, \ -		.types = NULL, .next = NULL, .insert = NULL, .ref = NULL, \ -	}; \ -	static void _mginit_##mname (void) \ -	  __attribute__ ((_CONSTRUCTOR (1000))); \ -	static void _mginit_##mname (void) \ -	{	extern struct memgroup **mg_insert; \ -		_mg_##mname.ref = mg_insert; \ -		*mg_insert = &_mg_##mname; \ -		mg_insert =  &_mg_##mname.next; } \ -	static void _mgfini_##mname (void) \ -	  __attribute__ ((_DESTRUCTOR (1000))); \ -	static void _mgfini_##mname (void) \ -	{	if (_mg_##mname.next) \ -			_mg_##mname.next->ref = _mg_##mname.ref; \ -		*_mg_##mname.ref = _mg_##mname.next; } - - -#define DECLARE_MTYPE(name) \ -	extern struct memtype _mt_##name; \ -	static struct memtype * const MTYPE_ ## name = &_mt_##name; - -#define DEFINE_MTYPE_ATTR(group, mname, attr, desc) \ -	attr struct memtype _mt_##mname \ -	__attribute__ ((section (".data.mtypes"))) = { \ -		.name = desc, \ -		.next = NULL, .n_alloc = 0, .size = 0, .ref = NULL, \ -	}; \ -	static void _mtinit_##mname (void) \ -	  __attribute__ ((_CONSTRUCTOR (1001))); \ -	static void _mtinit_##mname (void) \ -	{	if (_mg_##group.insert == NULL) \ -			_mg_##group.insert = &_mg_##group.types; \ -		_mt_##mname.ref = _mg_##group.insert; \ -		*_mg_##group.insert = &_mt_##mname; \ -		_mg_##group.insert =  &_mt_##mname.next; } \ -	static void _mtfini_##mname (void) \ -	  __attribute__ ((_DESTRUCTOR (1001))); \ -	static void _mtfini_##mname (void) \ -	{	if (_mt_##mname.next) \ -			_mt_##mname.next->ref = _mt_##mname.ref; \ -		*_mt_##mname.ref = _mt_##mname.next; } - -#define DEFINE_MTYPE(group, name, desc) \ -	DEFINE_MTYPE_ATTR(group, name, , desc) -#define DEFINE_MTYPE_STATIC(group, name, desc) \ -	DEFINE_MTYPE_ATTR(group, name, static, desc) \ -	static struct memtype * const MTYPE_ ## name = &_mt_##name; +#define DECLARE_MGROUP(name) extern struct memgroup _mg_##name; +#define DEFINE_MGROUP(mname, desc)                                             \ +	struct memgroup _mg_##mname                                            \ +		__attribute__((section(".data.mgroups"))) = {                  \ +			.name = desc,                                          \ +			.types = NULL,                                         \ +			.next = NULL,                                          \ +			.insert = NULL,                                        \ +			.ref = NULL,                                           \ +	};                                                                     \ +	static void _mginit_##mname(void) __attribute__((_CONSTRUCTOR(1000))); \ +	static void _mginit_##mname(void)                                      \ +	{                                                                      \ +		extern struct memgroup **mg_insert;                            \ +		_mg_##mname.ref = mg_insert;                                   \ +		*mg_insert = &_mg_##mname;                                     \ +		mg_insert = &_mg_##mname.next;                                 \ +	}                                                                      \ +	static void _mgfini_##mname(void) __attribute__((_DESTRUCTOR(1000)));  \ +	static void _mgfini_##mname(void)                                      \ +	{                                                                      \ +		if (_mg_##mname.next)                                          \ +			_mg_##mname.next->ref = _mg_##mname.ref;               \ +		*_mg_##mname.ref = _mg_##mname.next;                           \ +	} + + +#define DECLARE_MTYPE(name)                                                    \ +	extern struct memtype _mt_##name;                                      \ +	static struct memtype *const MTYPE_##name = &_mt_##name; + +#define DEFINE_MTYPE_ATTR(group, mname, attr, desc)                            \ +	attr struct memtype _mt_##mname                                        \ +		__attribute__((section(".data.mtypes"))) = {                   \ +			.name = desc,                                          \ +			.next = NULL,                                          \ +			.n_alloc = 0,                                          \ +			.size = 0,                                             \ +			.ref = NULL,                                           \ +	};                                                                     \ +	static void _mtinit_##mname(void) __attribute__((_CONSTRUCTOR(1001))); \ +	static void _mtinit_##mname(void)                                      \ +	{                                                                      \ +		if (_mg_##group.insert == NULL)                                \ +			_mg_##group.insert = &_mg_##group.types;               \ +		_mt_##mname.ref = _mg_##group.insert;                          \ +		*_mg_##group.insert = &_mt_##mname;                            \ +		_mg_##group.insert = &_mt_##mname.next;                        \ +	}                                                                      \ +	static void _mtfini_##mname(void) __attribute__((_DESTRUCTOR(1001)));  \ +	static void _mtfini_##mname(void)                                      \ +	{                                                                      \ +		if (_mt_##mname.next)                                          \ +			_mt_##mname.next->ref = _mt_##mname.ref;               \ +		*_mt_##mname.ref = _mt_##mname.next;                           \ +	} + +#define DEFINE_MTYPE(group, name, desc) DEFINE_MTYPE_ATTR(group, name, , desc) +#define DEFINE_MTYPE_STATIC(group, name, desc)                                 \ +	DEFINE_MTYPE_ATTR(group, name, static, desc)                           \ +	static struct memtype *const MTYPE_##name = &_mt_##name;  DECLARE_MGROUP(LIB)  DECLARE_MTYPE(TMP) -extern void *qmalloc (struct memtype *mt, size_t size) -	__attribute__ ((malloc, _ALLOC_SIZE(2), nonnull (1) _RET_NONNULL)); -extern void *qcalloc (struct memtype *mt, size_t size) -	__attribute__ ((malloc, _ALLOC_SIZE(2), nonnull (1) _RET_NONNULL)); -extern void *qrealloc (struct memtype *mt, void *ptr, size_t size) -	__attribute__ ((_ALLOC_SIZE(3), nonnull (1) _RET_NONNULL)); -extern void *qstrdup (struct memtype *mt, const char *str) -	__attribute__ ((malloc, nonnull (1) _RET_NONNULL)); -extern void qfree (struct memtype *mt, void *ptr) -	__attribute__ ((nonnull (1))); +extern void *qmalloc(struct memtype *mt, size_t size) +	__attribute__((malloc, _ALLOC_SIZE(2), nonnull(1) _RET_NONNULL)); +extern void *qcalloc(struct memtype *mt, size_t size) +	__attribute__((malloc, _ALLOC_SIZE(2), nonnull(1) _RET_NONNULL)); +extern void *qrealloc(struct memtype *mt, void *ptr, size_t size) +	__attribute__((_ALLOC_SIZE(3), nonnull(1) _RET_NONNULL)); +extern void *qstrdup(struct memtype *mt, const char *str) +	__attribute__((malloc, nonnull(1) _RET_NONNULL)); +extern void qfree(struct memtype *mt, void *ptr) __attribute__((nonnull(1)));  #define XMALLOC(mtype, size)		qmalloc(mtype, size)  #define XCALLOC(mtype, size)		qcalloc(mtype, size)  #define XREALLOC(mtype, ptr, size)	qrealloc(mtype, ptr, size)  #define XSTRDUP(mtype, str)		qstrdup(mtype, str) -#define XFREE(mtype, ptr)		do { qfree(mtype, ptr); ptr = NULL; } \ -					while (0) +#define XFREE(mtype, ptr)                                                      \ +	do {                                                                   \ +		qfree(mtype, ptr);                                             \ +		ptr = NULL;                                                    \ +	} while (0)  static inline size_t mtype_stats_alloc(struct memtype *mt)  { @@ -183,10 +191,10 @@ static inline size_t mtype_stats_alloc(struct memtype *mt)   *   * return value: 0: continue, !0: abort walk.  qmem_walk will return the   * last value from qmem_walk_fn. */ -typedef int qmem_walk_fn (void *arg, struct memgroup *mg, struct memtype *mt); -extern int qmem_walk (qmem_walk_fn *func, void *arg); -extern void log_memstats_stderr (const char *); +typedef int qmem_walk_fn(void *arg, struct memgroup *mg, struct memtype *mt); +extern int qmem_walk(qmem_walk_fn *func, void *arg); +extern void log_memstats_stderr(const char *); -extern void memory_oom (size_t size, const char *name); +extern void memory_oom(size_t size, const char *name);  #endif /* _QUAGGA_MEMORY_H */ diff --git a/lib/memory_vty.c b/lib/memory_vty.c index 6d63bc2d53..46dfa65739 100644 --- a/lib/memory_vty.c +++ b/lib/memory_vty.c @@ -38,43 +38,37 @@  #include "command.h"  #ifdef HAVE_MALLINFO -static int -show_memory_mallinfo (struct vty *vty) +static int show_memory_mallinfo(struct vty *vty)  { -  struct mallinfo minfo = mallinfo(); -  char buf[MTYPE_MEMSTR_LEN]; -   -  vty_out (vty, "System allocator statistics:%s", VTY_NEWLINE); -  vty_out (vty, "  Total heap allocated:  %s%s", -           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.arena), -           VTY_NEWLINE); -  vty_out (vty, "  Holding block headers: %s%s", -           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.hblkhd), -           VTY_NEWLINE); -  vty_out (vty, "  Used small blocks:     %s%s", -           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.usmblks), -           VTY_NEWLINE); -  vty_out (vty, "  Used ordinary blocks:  %s%s", -           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.uordblks), -           VTY_NEWLINE); -  vty_out (vty, "  Free small blocks:     %s%s", -           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.fsmblks), -           VTY_NEWLINE); -  vty_out (vty, "  Free ordinary blocks:  %s%s", -           mtype_memstr (buf, MTYPE_MEMSTR_LEN, minfo.fordblks), -           VTY_NEWLINE); -  vty_out (vty, "  Ordinary blocks:       %ld%s", -           (unsigned long)minfo.ordblks, -           VTY_NEWLINE); -  vty_out (vty, "  Small blocks:          %ld%s", -           (unsigned long)minfo.smblks, -           VTY_NEWLINE); -  vty_out (vty, "  Holding blocks:        %ld%s", -           (unsigned long)minfo.hblks, -           VTY_NEWLINE); -  vty_out (vty, "(see system documentation for 'mallinfo' for meaning)%s", -           VTY_NEWLINE); -  return 1; +	struct mallinfo minfo = mallinfo(); +	char buf[MTYPE_MEMSTR_LEN]; + +	vty_out(vty, "System allocator statistics:%s", VTY_NEWLINE); +	vty_out(vty, "  Total heap allocated:  %s%s", +		mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.arena), VTY_NEWLINE); +	vty_out(vty, "  Holding block headers: %s%s", +		mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.hblkhd), VTY_NEWLINE); +	vty_out(vty, "  Used small blocks:     %s%s", +		mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.usmblks), +		VTY_NEWLINE); +	vty_out(vty, "  Used ordinary blocks:  %s%s", +		mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.uordblks), +		VTY_NEWLINE); +	vty_out(vty, "  Free small blocks:     %s%s", +		mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.fsmblks), +		VTY_NEWLINE); +	vty_out(vty, "  Free ordinary blocks:  %s%s", +		mtype_memstr(buf, MTYPE_MEMSTR_LEN, minfo.fordblks), +		VTY_NEWLINE); +	vty_out(vty, "  Ordinary blocks:       %ld%s", +		(unsigned long)minfo.ordblks, VTY_NEWLINE); +	vty_out(vty, "  Small blocks:          %ld%s", +		(unsigned long)minfo.smblks, VTY_NEWLINE); +	vty_out(vty, "  Holding blocks:        %ld%s", +		(unsigned long)minfo.hblks, VTY_NEWLINE); +	vty_out(vty, "(see system documentation for 'mallinfo' for meaning)%s", +		VTY_NEWLINE); +	return 1;  }  #endif /* HAVE_MALLINFO */ @@ -82,16 +76,18 @@ static int qmem_walker(void *arg, struct memgroup *mg, struct memtype *mt)  {  	struct vty *vty = arg;  	if (!mt) -		vty_out (vty, "--- qmem %s ---%s", mg->name, VTY_NEWLINE); +		vty_out(vty, "--- qmem %s ---%s", mg->name, VTY_NEWLINE);  	else {  		if (mt->n_alloc != 0) {  			char size[32];  			snprintf(size, sizeof(size), "%6zu", mt->size); -			vty_out (vty, "%-30s: %10zu  %s%s", -				 mt->name, mt->n_alloc, -				 mt->size == 0 ? "" : -				 mt->size == SIZE_VAR ? "(variably sized)" : -				 size, VTY_NEWLINE); +			vty_out(vty, "%-30s: %10zu  %s%s", mt->name, +				mt->n_alloc, +				mt->size == 0 ? "" +					      : mt->size == SIZE_VAR +							? "(variably sized)" +							: size, +				VTY_NEWLINE);  		}  	}  	return 0; @@ -105,11 +101,11 @@ DEFUN (show_memory,         "Memory statistics\n")  {  #ifdef HAVE_MALLINFO -  show_memory_mallinfo (vty); +	show_memory_mallinfo(vty);  #endif /* HAVE_MALLINFO */ -  qmem_walk(qmem_walker, vty); -  return CMD_SUCCESS; +	qmem_walk(qmem_walker, vty); +	return CMD_SUCCESS;  }  DEFUN (show_modules, @@ -118,49 +114,47 @@ DEFUN (show_modules,         "Show running system information\n"         "Loaded modules\n")  { -  struct frrmod_runtime *plug = frrmod_list; - -  vty_out (vty, "%-12s %-25s %s%s%s", -                "Module Name", "Version", "Description", -                VTY_NEWLINE, VTY_NEWLINE); -  while (plug) -    { -      const struct frrmod_info *i = plug->info; - -      vty_out (vty, "%-12s %-25s %s%s", i->name, i->version, i->description, -                    VTY_NEWLINE); -      if (plug->dl_handle) -        { +	struct frrmod_runtime *plug = frrmod_list; + +	vty_out(vty, "%-12s %-25s %s%s%s", "Module Name", "Version", +		"Description", VTY_NEWLINE, VTY_NEWLINE); +	while (plug) { +		const struct frrmod_info *i = plug->info; + +		vty_out(vty, "%-12s %-25s %s%s", i->name, i->version, +			i->description, VTY_NEWLINE); +		if (plug->dl_handle) {  #ifdef HAVE_DLINFO_ORIGIN -          char origin[MAXPATHLEN] = ""; -          dlinfo (plug->dl_handle, RTLD_DI_ORIGIN, &origin); -# ifdef HAVE_DLINFO_LINKMAP -          const char *name; -          struct link_map *lm = NULL; -          dlinfo (plug->dl_handle, RTLD_DI_LINKMAP, &lm); -          if (lm) -            { -              name = strrchr(lm->l_name, '/'); -              name = name ? name + 1 : lm->l_name; -              vty_out (vty, "\tfrom: %s/%s%s", origin, name, VTY_NEWLINE); -            } -# else -          vty_out (vty, "\tfrom: %s %s", origin, plug->load_name, VTY_NEWLINE); -# endif +			char origin[MAXPATHLEN] = ""; +			dlinfo(plug->dl_handle, RTLD_DI_ORIGIN, &origin); +#ifdef HAVE_DLINFO_LINKMAP +			const char *name; +			struct link_map *lm = NULL; +			dlinfo(plug->dl_handle, RTLD_DI_LINKMAP, &lm); +			if (lm) { +				name = strrchr(lm->l_name, '/'); +				name = name ? name + 1 : lm->l_name; +				vty_out(vty, "\tfrom: %s/%s%s", origin, name, +					VTY_NEWLINE); +			} +#else +			vty_out(vty, "\tfrom: %s %s", origin, plug->load_name, +				VTY_NEWLINE); +#endif  #else -          vty_out (vty, "\tfrom: %s%s", plug->load_name, VTY_NEWLINE); +			vty_out(vty, "\tfrom: %s%s", plug->load_name, +				VTY_NEWLINE);  #endif -        } -      plug = plug->next; -    } -  return CMD_SUCCESS; +		} +		plug = plug->next; +	} +	return CMD_SUCCESS;  } -void -memory_init (void) +void memory_init(void)  { -  install_element (VIEW_NODE, &show_memory_cmd); -  install_element (VIEW_NODE, &show_modules_cmd); +	install_element(VIEW_NODE, &show_memory_cmd); +	install_element(VIEW_NODE, &show_modules_cmd);  }  /* Stats querying from users */ @@ -171,44 +165,39 @@ memory_init (void)   * The pointer returned may be NULL (indicating an error)   * or point to the given buffer, or point to static storage.   */ -const char * -mtype_memstr (char *buf, size_t len, unsigned long bytes) +const char *mtype_memstr(char *buf, size_t len, unsigned long bytes)  { -  unsigned int m, k; - -  /* easy cases */ -  if (!bytes) -    return "0 bytes"; -  if (bytes == 1) -    return "1 byte"; - -  /* -   * When we pass the 2gb barrier mallinfo() can no longer report -   * correct data so it just does something odd... -   * Reporting like Terrabytes of data.  Which makes users... -   * edgy.. yes edgy that's the term for it. -   * So let's just give up gracefully -   */ -  if (bytes > 0x7fffffff) -    return "> 2GB"; - -  m = bytes >> 20; -  k = bytes >> 10; - - if (m > 10) -    { -      if (bytes & (1 << 19)) -        m++; -      snprintf (buf, len, "%d MiB", m); -    } -  else if (k > 10) -    { -      if (bytes & (1 << 9)) -        k++; -      snprintf (buf, len, "%d KiB", k); -    } -  else -    snprintf (buf, len, "%ld bytes", bytes); -   -  return buf; +	unsigned int m, k; + +	/* easy cases */ +	if (!bytes) +		return "0 bytes"; +	if (bytes == 1) +		return "1 byte"; + +	/* +	 * When we pass the 2gb barrier mallinfo() can no longer report +	 * correct data so it just does something odd... +	 * Reporting like Terrabytes of data.  Which makes users... +	 * edgy.. yes edgy that's the term for it. +	 * So let's just give up gracefully +	 */ +	if (bytes > 0x7fffffff) +		return "> 2GB"; + +	m = bytes >> 20; +	k = bytes >> 10; + +	if (m > 10) { +		if (bytes & (1 << 19)) +			m++; +		snprintf(buf, len, "%d MiB", m); +	} else if (k > 10) { +		if (bytes & (1 << 9)) +			k++; +		snprintf(buf, len, "%d KiB", k); +	} else +		snprintf(buf, len, "%ld bytes", bytes); + +	return buf;  } diff --git a/lib/memory_vty.h b/lib/memory_vty.h index 565a75aa98..7388a07b85 100644 --- a/lib/memory_vty.h +++ b/lib/memory_vty.h @@ -23,9 +23,9 @@ Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  #include "memory.h" -extern void memory_init (void); +extern void memory_init(void);  /* Human friendly string for given byte count */  #define MTYPE_MEMSTR_LEN 20 -extern const char *mtype_memstr (char *, size_t, unsigned long); +extern const char *mtype_memstr(char *, size_t, unsigned long);  #endif /* _ZEBRA_MEMORY_VTY_H */ diff --git a/lib/module.c b/lib/module.c index c7dd5538cd..6759a36122 100644 --- a/lib/module.c +++ b/lib/module.c @@ -68,8 +68,8 @@ void frrmod_init(struct frrmod_runtime *modinfo)  	execname = modinfo->info->name;  } -struct frrmod_runtime *frrmod_load(const char *spec, -		const char *dir, char *err, size_t err_len) +struct frrmod_runtime *frrmod_load(const char *spec, const char *dir, char *err, +				   size_t err_len)  {  	void *handle = NULL;  	char name[PATH_MAX], fullpath[PATH_MAX], *args; @@ -83,13 +83,13 @@ struct frrmod_runtime *frrmod_load(const char *spec,  	if (!strchr(name, '/')) {  		if (!handle && execname) { -			snprintf(fullpath, sizeof(fullpath), "%s/%s_%s.so", -					dir, execname, name); +			snprintf(fullpath, sizeof(fullpath), "%s/%s_%s.so", dir, +				 execname, name);  			handle = dlopen(fullpath, RTLD_NOW | RTLD_GLOBAL);  		}  		if (!handle) { -			snprintf(fullpath, sizeof(fullpath), "%s/%s.so", -					dir, name); +			snprintf(fullpath, sizeof(fullpath), "%s/%s.so", dir, +				 name);  			handle = dlopen(fullpath, RTLD_NOW | RTLD_GLOBAL);  		}  	} @@ -100,8 +100,8 @@ struct frrmod_runtime *frrmod_load(const char *spec,  	if (!handle) {  		if (err)  			snprintf(err, err_len, -					"loading module \"%s\" failed: %s", -					name, dlerror()); +				 "loading module \"%s\" failed: %s", name, +				 dlerror());  		return NULL;  	} @@ -110,8 +110,8 @@ struct frrmod_runtime *frrmod_load(const char *spec,  		dlclose(handle);  		if (err)  			snprintf(err, err_len, -					"\"%s\" is not a Quagga module: %s", -					name, dlerror()); +				 "\"%s\" is not a Quagga module: %s", name, +				 dlerror());  		return NULL;  	}  	rtinfo = *rtinfop; @@ -124,9 +124,8 @@ struct frrmod_runtime *frrmod_load(const char *spec,  	if (rtinfo->finished_loading) {  		dlclose(handle);  		if (err) -			snprintf(err, err_len, -					"module \"%s\" already loaded", -					name); +			snprintf(err, err_len, "module \"%s\" already loaded", +				 name);  		goto out_fail;  	} @@ -134,8 +133,7 @@ struct frrmod_runtime *frrmod_load(const char *spec,  		dlclose(handle);  		if (err)  			snprintf(err, err_len, -					"module \"%s\" initialisation failed", -					name); +				 "module \"%s\" initialisation failed", name);  		goto out_fail;  	} diff --git a/lib/module.h b/lib/module.h index 01819f91e1..e66e5cd650 100644 --- a/lib/module.h +++ b/lib/module.h @@ -27,9 +27,9 @@  #include <stdbool.h>  #if !defined(__GNUC__) -# error module code needs GCC visibility extensions +#error module code needs GCC visibility extensions  #elif __GNUC__ < 4 -# error module code needs GCC visibility extensions +#error module code needs GCC visibility extensions  #else  # define DSO_PUBLIC __attribute__ ((visibility ("default")))  # define DSO_SELF   __attribute__ ((visibility ("protected"))) @@ -82,20 +82,20 @@ union _frrmod_runtime_u {  extern union _frrmod_runtime_u _frrmod_this_module;  #define THIS_MODULE (&_frrmod_this_module.r) -#define FRR_COREMOD_SETUP(...) \ -	static const struct frrmod_info _frrmod_info = { __VA_ARGS__ }; \ -	DSO_LOCAL union _frrmod_runtime_u _frrmod_this_module = { \ -		.r.info = &_frrmod_info, \ +#define FRR_COREMOD_SETUP(...)                                                 \ +	static const struct frrmod_info _frrmod_info = {__VA_ARGS__};          \ +	DSO_LOCAL union _frrmod_runtime_u _frrmod_this_module = {              \ +		.r.info = &_frrmod_info,                                       \  	}; -#define FRR_MODULE_SETUP(...) \ -	FRR_COREMOD_SETUP(__VA_ARGS__) \ +#define FRR_MODULE_SETUP(...)                                                  \ +	FRR_COREMOD_SETUP(__VA_ARGS__)                                         \  	DSO_SELF struct frrmod_runtime *frr_module = &_frrmod_this_module.r;  extern struct frrmod_runtime *frrmod_list;  extern void frrmod_init(struct frrmod_runtime *modinfo); -extern struct frrmod_runtime *frrmod_load(const char *spec, -		const char *dir, char *err, size_t err_len); +extern struct frrmod_runtime *frrmod_load(const char *spec, const char *dir, +					  char *err, size_t err_len);  #if 0  /* not implemented yet */  extern void frrmod_unload(struct frrmod_runtime *module); diff --git a/lib/monotime.h b/lib/monotime.h index ad44bf511a..7bd3386498 100644 --- a/lib/monotime.h +++ b/lib/monotime.h @@ -23,28 +23,30 @@  #ifndef TIMESPEC_TO_TIMEVAL  /* should be in sys/time.h on BSD & Linux libcs */ -#define TIMESPEC_TO_TIMEVAL(tv, ts) do {        \ -        (tv)->tv_sec = (ts)->tv_sec;            \ -        (tv)->tv_usec = (ts)->tv_nsec / 1000;   \ -        } while (0) +#define TIMESPEC_TO_TIMEVAL(tv, ts)                                            \ +	do {                                                                   \ +		(tv)->tv_sec = (ts)->tv_sec;                                   \ +		(tv)->tv_usec = (ts)->tv_nsec / 1000;                          \ +	} while (0)  #endif  #ifndef TIMEVAL_TO_TIMESPEC  /* should be in sys/time.h on BSD & Linux libcs */ -#define TIMEVAL_TO_TIMESPEC(tv, ts) do {        \ -        (ts)->tv_sec = (tv)->tv_sec;            \ -        (ts)->tv_nsec = (tv)->tv_usec * 1000;   \ -        } while (0) +#define TIMEVAL_TO_TIMESPEC(tv, ts)                                            \ +	do {                                                                   \ +		(ts)->tv_sec = (tv)->tv_sec;                                   \ +		(ts)->tv_nsec = (tv)->tv_usec * 1000;                          \ +	} while (0)  #endif  static inline time_t monotime(struct timeval *tvo)  { -        struct timespec ts; +	struct timespec ts; -        clock_gettime(CLOCK_MONOTONIC, &ts); -        if (tvo) { -                TIMESPEC_TO_TIMEVAL(tvo, &ts); -        } -        return ts.tv_sec; +	clock_gettime(CLOCK_MONOTONIC, &ts); +	if (tvo) { +		TIMESPEC_TO_TIMEVAL(tvo, &ts); +	} +	return ts.tv_sec;  }  /* the following two return microseconds, not time_t! @@ -53,25 +55,25 @@ static inline time_t monotime(struct timeval *tvo)   * code more readable   */  static inline int64_t monotime_since(const struct timeval *ref, -                                     struct timeval *out) +				     struct timeval *out)  { -        struct timeval tv; -        monotime(&tv); -        timersub(&tv, ref, &tv); -        if (out) -                *out = tv; -        return (int64_t)tv.tv_sec * 1000000LL + tv.tv_usec; +	struct timeval tv; +	monotime(&tv); +	timersub(&tv, ref, &tv); +	if (out) +		*out = tv; +	return (int64_t)tv.tv_sec * 1000000LL + tv.tv_usec;  }  static inline int64_t monotime_until(const struct timeval *ref, -                                     struct timeval *out) +				     struct timeval *out)  { -        struct timeval tv; -        monotime(&tv); -        timersub(ref, &tv, &tv); -        if (out) -                *out = tv; -        return (int64_t)tv.tv_sec * 1000000LL + tv.tv_usec; +	struct timeval tv; +	monotime(&tv); +	timersub(ref, &tv, &tv); +	if (out) +		*out = tv; +	return (int64_t)tv.tv_sec * 1000000LL + tv.tv_usec;  }  #endif /* _FRR_MONOTIME_H */ diff --git a/lib/mpls.h b/lib/mpls.h index 13a46e1012..7fee811074 100644 --- a/lib/mpls.h +++ b/lib/mpls.h @@ -41,11 +41,12 @@  #define MPLS_MIN_UNRESERVED_LABEL          16  #define MPLS_MAX_UNRESERVED_LABEL          1048575 -#define IS_MPLS_RESERVED_LABEL(label) \ -        (label >= MPLS_MIN_RESERVED_LABEL && label <= MPLS_MAX_RESERVED_LABEL) +#define IS_MPLS_RESERVED_LABEL(label)                                          \ +	(label >= MPLS_MIN_RESERVED_LABEL && label <= MPLS_MAX_RESERVED_LABEL) -#define IS_MPLS_UNRESERVED_LABEL(label) \ -        (label >= MPLS_MIN_UNRESERVED_LABEL && label <= MPLS_MAX_UNRESERVED_LABEL) +#define IS_MPLS_UNRESERVED_LABEL(label)                                        \ +	(label >= MPLS_MIN_UNRESERVED_LABEL                                    \ +	 && label <= MPLS_MAX_UNRESERVED_LABEL)  /* Definitions for a MPLS label stack entry (RFC 3032). This encodes the   * label, EXP, BOS and TTL fields. @@ -61,14 +62,11 @@ typedef unsigned int mpls_lse_t;  #define MPLS_LS_TTL_MASK               0x000000FF  #define MPLS_LS_TTL_SHIFT              0 -#define MPLS_LABEL_VALUE(lse) \ -        ((lse & MPLS_LS_LABEL_MASK) >> MPLS_LS_LABEL_SHIFT) -#define MPLS_LABEL_EXP(lse) \ -        ((lse & MPLS_LS_EXP_MASK) >> MPLS_LS_EXP_SHIFT) -#define MPLS_LABEL_BOS(lse) \ -        ((lse & MPLS_LS_S_MASK) >> MPLS_LS_S_SHIFT) -#define MPLS_LABEL_TTL(lse) \ -        ((lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT) +#define MPLS_LABEL_VALUE(lse)                                                  \ +	((lse & MPLS_LS_LABEL_MASK) >> MPLS_LS_LABEL_SHIFT) +#define MPLS_LABEL_EXP(lse) ((lse & MPLS_LS_EXP_MASK) >> MPLS_LS_EXP_SHIFT) +#define MPLS_LABEL_BOS(lse) ((lse & MPLS_LS_S_MASK) >> MPLS_LS_S_SHIFT) +#define MPLS_LABEL_TTL(lse) ((lse & MPLS_LS_TTL_MASK) >> MPLS_LS_TTL_SHIFT)  #define IS_MPLS_LABEL_BOS(ls)          (MPLS_LABEL_BOS(ls) == 1) @@ -81,11 +79,10 @@ typedef unsigned int mpls_label_t;  #define MPLS_INVALID_LABEL                 0xFFFFFFFF  /* LSP types. */ -enum lsp_types_t -{ -  ZEBRA_LSP_NONE = 0,        /* No LSP. */ -  ZEBRA_LSP_STATIC = 1,      /* Static LSP. */ -  ZEBRA_LSP_LDP = 2          /* LDP LSP. */ +enum lsp_types_t { +	ZEBRA_LSP_NONE = 0,   /* No LSP. */ +	ZEBRA_LSP_STATIC = 1, /* Static LSP. */ +	ZEBRA_LSP_LDP = 2     /* LDP LSP. */  };  /* Functions for basic label operations. */ @@ -93,72 +90,69 @@ enum lsp_types_t  /* Encode a label stack entry from fields; convert to network byte-order as   * the Netlink interface expects MPLS labels to be in this format.   */ -static inline mpls_lse_t -mpls_lse_encode (mpls_label_t label, u_int32_t ttl, -                 u_int32_t exp, u_int32_t bos) +static inline mpls_lse_t mpls_lse_encode(mpls_label_t label, u_int32_t ttl, +					 u_int32_t exp, u_int32_t bos)  { -  mpls_lse_t lse; -  lse = htonl ((label << MPLS_LS_LABEL_SHIFT) | -               (exp << MPLS_LS_EXP_SHIFT) | -               (bos ? (1 << MPLS_LS_S_SHIFT) : 0) | -               (ttl << MPLS_LS_TTL_SHIFT)); -  return lse; +	mpls_lse_t lse; +	lse = htonl((label << MPLS_LS_LABEL_SHIFT) | (exp << MPLS_LS_EXP_SHIFT) +		    | (bos ? (1 << MPLS_LS_S_SHIFT) : 0) +		    | (ttl << MPLS_LS_TTL_SHIFT)); +	return lse;  }  /* Extract the fields from a label stack entry after converting to host-byte   * order. This is expected to be called only for messages received over the   * Netlink interface.   */ -static inline void -mpls_lse_decode (mpls_lse_t lse, mpls_label_t *label, -                 u_int32_t *ttl, u_int32_t *exp, u_int32_t *bos) +static inline void mpls_lse_decode(mpls_lse_t lse, mpls_label_t *label, +				   u_int32_t *ttl, u_int32_t *exp, +				   u_int32_t *bos)  { -  mpls_lse_t local_lse; +	mpls_lse_t local_lse; -  local_lse = ntohl (lse); -  *label = MPLS_LABEL_VALUE(local_lse); -  *exp = MPLS_LABEL_EXP(local_lse); -  *bos = MPLS_LABEL_BOS(local_lse); -  *ttl = MPLS_LABEL_TTL(local_lse); +	local_lse = ntohl(lse); +	*label = MPLS_LABEL_VALUE(local_lse); +	*exp = MPLS_LABEL_EXP(local_lse); +	*bos = MPLS_LABEL_BOS(local_lse); +	*ttl = MPLS_LABEL_TTL(local_lse);  }  /* Printable string for labels (with consideration for reserved values). */ -static inline char * -label2str (mpls_label_t label, char *buf, size_t len) +static inline char *label2str(mpls_label_t label, char *buf, size_t len)  { -  switch(label) { -  case MPLS_V4_EXP_NULL_LABEL: -    strlcpy(buf, "IPv4 Explicit Null", len); -    return(buf); -  case MPLS_RA_LABEL: -    strlcpy(buf, "Router Alert", len); -    return(buf); -  case MPLS_V6_EXP_NULL_LABEL: -    strlcpy(buf, "IPv6 Explict Null", len); -    return(buf); -  case MPLS_IMP_NULL_LABEL: -    strlcpy(buf, "implicit-null", len); -    return(buf); -  case MPLS_ENTROPY_LABEL_INDICATOR: -    strlcpy(buf, "Entropy Label Indicator", len); -    return(buf); -  case MPLS_GAL_LABEL: -    strlcpy(buf, "Generic Associated Channel", len); -    return(buf); -  case MPLS_OAM_ALERT_LABEL: -    strlcpy(buf, "OAM Alert", len); -    return(buf); -  case MPLS_EXTENSION_LABEL: -    strlcpy(buf, "Extension", len); -    return(buf); -  default: -    if (label < 16) -      snprintf(buf, len, "Reserved (%u)", label); -    else -      snprintf(buf, len, "%u", label); -    return(buf); -  } +	switch (label) { +	case MPLS_V4_EXP_NULL_LABEL: +		strlcpy(buf, "IPv4 Explicit Null", len); +		return (buf); +	case MPLS_RA_LABEL: +		strlcpy(buf, "Router Alert", len); +		return (buf); +	case MPLS_V6_EXP_NULL_LABEL: +		strlcpy(buf, "IPv6 Explict Null", len); +		return (buf); +	case MPLS_IMP_NULL_LABEL: +		strlcpy(buf, "implicit-null", len); +		return (buf); +	case MPLS_ENTROPY_LABEL_INDICATOR: +		strlcpy(buf, "Entropy Label Indicator", len); +		return (buf); +	case MPLS_GAL_LABEL: +		strlcpy(buf, "Generic Associated Channel", len); +		return (buf); +	case MPLS_OAM_ALERT_LABEL: +		strlcpy(buf, "OAM Alert", len); +		return (buf); +	case MPLS_EXTENSION_LABEL: +		strlcpy(buf, "Extension", len); +		return (buf); +	default: +		if (label < 16) +			snprintf(buf, len, "Reserved (%u)", label); +		else +			snprintf(buf, len, "%u", label); +		return (buf); +	}  }  /* constants used by ldpd */ @@ -166,7 +160,7 @@ label2str (mpls_label_t label, char *buf, size_t len)  #define MPLS_LABEL_RTALERT	1               /* Router Alert Label       */  #define MPLS_LABEL_IPV6NULL	2               /* IPv6 Explicit NULL Label */  #define MPLS_LABEL_IMPLNULL	3               /* Implicit NULL Label      */ -/*      MPLS_LABEL_RESERVED	4-15 */		/* Values 4-15 are reserved */ +	/*      MPLS_LABEL_RESERVED	4-15 */ /* Values 4-15 are reserved */  #define MPLS_LABEL_RESERVED_MAX 15  #define MPLS_LABEL_MAX		((1 << 20) - 1) diff --git a/lib/network.c b/lib/network.c index 2b6f2fbab5..6a76fbb6dd 100644 --- a/lib/network.c +++ b/lib/network.c @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -25,108 +25,97 @@  #include "network.h"  /* Read nbytes from fd and store into ptr. */ -int -readn (int fd, u_char *ptr, int nbytes) +int readn(int fd, u_char *ptr, int nbytes)  { -  int nleft; -  int nread; +	int nleft; +	int nread; -  nleft = nbytes; +	nleft = nbytes; -  while (nleft > 0)  -    { -      nread = read (fd, ptr, nleft); +	while (nleft > 0) { +		nread = read(fd, ptr, nleft); -      if (nread < 0)  -	return (nread); -      else -	if (nread == 0)  -	  break; +		if (nread < 0) +			return (nread); +		else if (nread == 0) +			break; -      nleft -= nread; -      ptr += nread; -    } +		nleft -= nread; +		ptr += nread; +	} -  return nbytes - nleft; -}   +	return nbytes - nleft; +}  /* Write nbytes from ptr to fd. */ -int -writen(int fd, const u_char *ptr, int nbytes) +int writen(int fd, const u_char *ptr, int nbytes)  { -  int nleft; -  int nwritten; +	int nleft; +	int nwritten; -  nleft = nbytes; +	nleft = nbytes; -  while (nleft > 0)  -    { -      nwritten = write(fd, ptr, nleft); +	while (nleft > 0) { +		nwritten = write(fd, ptr, nleft); -      if (nwritten < 0) -	{ -	  if (!ERRNO_IO_RETRY(errno)) -	    return nwritten; -	} -      if (nwritten == 0)  -	return (nwritten); +		if (nwritten < 0) { +			if (!ERRNO_IO_RETRY(errno)) +				return nwritten; +		} +		if (nwritten == 0) +			return (nwritten); -      nleft -= nwritten; -      ptr += nwritten; -    } -  return nbytes - nleft; +		nleft -= nwritten; +		ptr += nwritten; +	} +	return nbytes - nleft;  } -int -set_nonblocking(int fd) +int set_nonblocking(int fd)  { -  int flags; - -  /* According to the Single UNIX Spec, the return value for F_GETFL should -     never be negative. */ -  if ((flags = fcntl(fd, F_GETFL)) < 0) -    { -      zlog_warn("fcntl(F_GETFL) failed for fd %d: %s", -      		fd, safe_strerror(errno)); -      return -1; -    } -  if (fcntl(fd, F_SETFL, (flags | O_NONBLOCK)) < 0) -    { -      zlog_warn("fcntl failed setting fd %d non-blocking: %s", -      		fd, safe_strerror(errno)); -      return -1; -    } -  return 0; +	int flags; + +	/* According to the Single UNIX Spec, the return value for F_GETFL +	   should +	   never be negative. */ +	if ((flags = fcntl(fd, F_GETFL)) < 0) { +		zlog_warn("fcntl(F_GETFL) failed for fd %d: %s", fd, +			  safe_strerror(errno)); +		return -1; +	} +	if (fcntl(fd, F_SETFL, (flags | O_NONBLOCK)) < 0) { +		zlog_warn("fcntl failed setting fd %d non-blocking: %s", fd, +			  safe_strerror(errno)); +		return -1; +	} +	return 0;  } -int -set_cloexec(int fd) +int set_cloexec(int fd)  { -  int flags; -  flags = fcntl(fd, F_GETFD, 0); -  if (flags == -1) -    return -1; - -  flags |= FD_CLOEXEC; -  if (fcntl(fd, F_SETFD, flags) == -1) -    return -1; -  return 0; +	int flags; +	flags = fcntl(fd, F_GETFD, 0); +	if (flags == -1) +		return -1; + +	flags |= FD_CLOEXEC; +	if (fcntl(fd, F_SETFD, flags) == -1) +		return -1; +	return 0;  } -float -htonf (float host) +float htonf(float host)  { -  u_int32_t lu1, lu2; -  float convert; +	u_int32_t lu1, lu2; +	float convert; -  memcpy (&lu1, &host, sizeof (u_int32_t)); -  lu2 = htonl (lu1); -  memcpy (&convert, &lu2, sizeof (u_int32_t)); -  return convert; +	memcpy(&lu1, &host, sizeof(u_int32_t)); +	lu2 = htonl(lu1); +	memcpy(&convert, &lu2, sizeof(u_int32_t)); +	return convert;  } -float -ntohf (float net) +float ntohf(float net)  { -  return htonf (net); +	return htonf(net);  } diff --git a/lib/network.h b/lib/network.h index a9126caf7f..e89e07ec85 100644 --- a/lib/network.h +++ b/lib/network.h @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_NETWORK_H @@ -26,8 +26,8 @@  /* Both readn and writen are deprecated and will be removed.  They are not     suitable for use with non-blocking file descriptors.   */ -extern int readn (int, u_char *, int); -extern int writen (int, const u_char *, int); +extern int readn(int, u_char *, int); +extern int writen(int, const u_char *, int);  /* Set the file descriptor to use non-blocking I/O.  Returns 0 for success,     -1 on error. */ @@ -36,10 +36,10 @@ extern int set_nonblocking(int fd);  extern int set_cloexec(int fd);  /* Does the I/O error indicate that the operation should be retried later? */ -#define ERRNO_IO_RETRY(EN) \ +#define ERRNO_IO_RETRY(EN)                                                     \  	(((EN) == EAGAIN) || ((EN) == EWOULDBLOCK) || ((EN) == EINTR)) -extern float htonf (float); -extern float ntohf (float); +extern float htonf(float); +extern float ntohf(float);  #endif /* _ZEBRA_NETWORK_H */ diff --git a/lib/nexthop.c b/lib/nexthop.c index 7b8ac95e83..147b2a1479 100644 --- a/lib/nexthop.c +++ b/lib/nexthop.c @@ -33,190 +33,174 @@  #include "nexthop.h"  #include "mpls.h" -DEFINE_MTYPE_STATIC(LIB, NEXTHOP,	"Nexthop") -DEFINE_MTYPE_STATIC(LIB, NH_LABEL,	"Nexthop label") +DEFINE_MTYPE_STATIC(LIB, NEXTHOP, "Nexthop") +DEFINE_MTYPE_STATIC(LIB, NH_LABEL, "Nexthop label")  /* check if nexthops are same, non-recursive */ -int -nexthop_same_no_recurse (struct nexthop *next1, struct nexthop *next2) +int nexthop_same_no_recurse(struct nexthop *next1, struct nexthop *next2)  { -  if (next1->type != next2->type) -    return 0; - -  switch (next1->type) -    { -    case NEXTHOP_TYPE_IPV4: -    case NEXTHOP_TYPE_IPV4_IFINDEX: -      if (! IPV4_ADDR_SAME (&next1->gate.ipv4, &next2->gate.ipv4)) -	return 0; -      if (next1->ifindex && (next1->ifindex != next2->ifindex)) -	return 0; -      break; -    case NEXTHOP_TYPE_IFINDEX: -      if (next1->ifindex != next2->ifindex) -	return 0; -      break; -    case NEXTHOP_TYPE_IPV6: -      if (! IPV6_ADDR_SAME (&next1->gate.ipv6, &next2->gate.ipv6)) -	return 0; -      break; -    case NEXTHOP_TYPE_IPV6_IFINDEX: -      if (! IPV6_ADDR_SAME (&next1->gate.ipv6, &next2->gate.ipv6)) -	return 0; -      if (next1->ifindex != next2->ifindex) -	return 0; -      break; -    default: -      /* do nothing */ -      break; -    } -  return 1; +	if (next1->type != next2->type) +		return 0; + +	switch (next1->type) { +	case NEXTHOP_TYPE_IPV4: +	case NEXTHOP_TYPE_IPV4_IFINDEX: +		if (!IPV4_ADDR_SAME(&next1->gate.ipv4, &next2->gate.ipv4)) +			return 0; +		if (next1->ifindex && (next1->ifindex != next2->ifindex)) +			return 0; +		break; +	case NEXTHOP_TYPE_IFINDEX: +		if (next1->ifindex != next2->ifindex) +			return 0; +		break; +	case NEXTHOP_TYPE_IPV6: +		if (!IPV6_ADDR_SAME(&next1->gate.ipv6, &next2->gate.ipv6)) +			return 0; +		break; +	case NEXTHOP_TYPE_IPV6_IFINDEX: +		if (!IPV6_ADDR_SAME(&next1->gate.ipv6, &next2->gate.ipv6)) +			return 0; +		if (next1->ifindex != next2->ifindex) +			return 0; +		break; +	default: +		/* do nothing */ +		break; +	} +	return 1;  }  /*   * nexthop_type_to_str   */ -const char * -nexthop_type_to_str (enum nexthop_types_t nh_type) +const char *nexthop_type_to_str(enum nexthop_types_t nh_type)  { -  static const char *desc[] = { -    "none", -    "Directly connected", -    "IPv4 nexthop", -    "IPv4 nexthop with ifindex", -    "IPv6 nexthop", -    "IPv6 nexthop with ifindex", -    "Null0 nexthop", -  }; - -  return desc[nh_type]; +	static const char *desc[] = { +		"none",		 "Directly connected", +		"IPv4 nexthop",  "IPv4 nexthop with ifindex", +		"IPv6 nexthop",  "IPv6 nexthop with ifindex", +		"Null0 nexthop", +	}; + +	return desc[nh_type];  } -struct nexthop * -nexthop_new (void) +struct nexthop *nexthop_new(void)  { -  return XCALLOC (MTYPE_NEXTHOP, sizeof (struct nexthop)); +	return XCALLOC(MTYPE_NEXTHOP, sizeof(struct nexthop));  }  /* Add nexthop to the end of a nexthop list.  */ -void -nexthop_add (struct nexthop **target, struct nexthop *nexthop) +void nexthop_add(struct nexthop **target, struct nexthop *nexthop)  { -  struct nexthop *last; - -  for (last = *target; last && last->next; last = last->next) -    ; -  if (last) -    last->next = nexthop; -  else -    *target = nexthop; -  nexthop->prev = last; +	struct nexthop *last; + +	for (last = *target; last && last->next; last = last->next) +		; +	if (last) +		last->next = nexthop; +	else +		*target = nexthop; +	nexthop->prev = last;  } -void -copy_nexthops (struct nexthop **tnh, struct nexthop *nh) +void copy_nexthops(struct nexthop **tnh, struct nexthop *nh)  { -  struct nexthop *nexthop; -  struct nexthop *nh1; - -  for (nh1 = nh; nh1; nh1 = nh1->next) -    { -      nexthop = nexthop_new(); -      nexthop->flags = nh->flags; -      nexthop->type = nh->type; -      nexthop->ifindex = nh->ifindex; -      memcpy(&(nexthop->gate), &(nh->gate), sizeof(union g_addr)); -      memcpy(&(nexthop->src), &(nh->src), sizeof(union g_addr)); -      if (nh->nh_label) -        nexthop_add_labels (nexthop, nh->nh_label_type, -			    nh->nh_label->num_labels, &nh->nh_label->label[0]); -      nexthop_add(tnh, nexthop); - -      if (CHECK_FLAG(nh1->flags, NEXTHOP_FLAG_RECURSIVE)) -	copy_nexthops(&nexthop->resolved, nh1->resolved); -    } +	struct nexthop *nexthop; +	struct nexthop *nh1; + +	for (nh1 = nh; nh1; nh1 = nh1->next) { +		nexthop = nexthop_new(); +		nexthop->flags = nh->flags; +		nexthop->type = nh->type; +		nexthop->ifindex = nh->ifindex; +		memcpy(&(nexthop->gate), &(nh->gate), sizeof(union g_addr)); +		memcpy(&(nexthop->src), &(nh->src), sizeof(union g_addr)); +		if (nh->nh_label) +			nexthop_add_labels(nexthop, nh->nh_label_type, +					   nh->nh_label->num_labels, +					   &nh->nh_label->label[0]); +		nexthop_add(tnh, nexthop); + +		if (CHECK_FLAG(nh1->flags, NEXTHOP_FLAG_RECURSIVE)) +			copy_nexthops(&nexthop->resolved, nh1->resolved); +	}  }  /* Free nexthop. */ -void -nexthop_free (struct nexthop *nexthop) +void nexthop_free(struct nexthop *nexthop)  { -  nexthop_del_labels (nexthop); -  if (nexthop->resolved) -    nexthops_free(nexthop->resolved); -  XFREE (MTYPE_NEXTHOP, nexthop); +	nexthop_del_labels(nexthop); +	if (nexthop->resolved) +		nexthops_free(nexthop->resolved); +	XFREE(MTYPE_NEXTHOP, nexthop);  }  /* Frees a list of nexthops */ -void -nexthops_free (struct nexthop *nexthop) +void nexthops_free(struct nexthop *nexthop)  { -  struct nexthop *nh, *next; +	struct nexthop *nh, *next; -  for (nh = nexthop; nh; nh = next) -    { -      next = nh->next; -      nexthop_free (nh); -    } +	for (nh = nexthop; nh; nh = next) { +		next = nh->next; +		nexthop_free(nh); +	}  }  /* Update nexthop with label information. */ -void -nexthop_add_labels (struct nexthop *nexthop, enum lsp_types_t type, -		    u_int8_t num_labels, mpls_label_t *label) +void nexthop_add_labels(struct nexthop *nexthop, enum lsp_types_t type, +			u_int8_t num_labels, mpls_label_t *label)  { -  struct nexthop_label *nh_label; -  int i; - -  nexthop->nh_label_type = type; -  nh_label = XCALLOC (MTYPE_NH_LABEL, sizeof (struct nexthop_label) + -		      num_labels * sizeof (mpls_label_t)); -  nh_label->num_labels = num_labels; -  for (i = 0; i < num_labels; i++) -    nh_label->label[i] = *(label + i); -  nexthop->nh_label = nh_label; +	struct nexthop_label *nh_label; +	int i; + +	nexthop->nh_label_type = type; +	nh_label = XCALLOC(MTYPE_NH_LABEL, +			   sizeof(struct nexthop_label) +				   + num_labels * sizeof(mpls_label_t)); +	nh_label->num_labels = num_labels; +	for (i = 0; i < num_labels; i++) +		nh_label->label[i] = *(label + i); +	nexthop->nh_label = nh_label;  }  /* Free label information of nexthop, if present. */ -void -nexthop_del_labels (struct nexthop *nexthop) +void nexthop_del_labels(struct nexthop *nexthop)  { -  if (nexthop->nh_label) -    { -      XFREE (MTYPE_NH_LABEL, nexthop->nh_label); -      nexthop->nh_label_type = ZEBRA_LSP_NONE; -    } +	if (nexthop->nh_label) { +		XFREE(MTYPE_NH_LABEL, nexthop->nh_label); +		nexthop->nh_label_type = ZEBRA_LSP_NONE; +	}  } -const char * -nexthop2str (struct nexthop *nexthop, char *str, int size) +const char *nexthop2str(struct nexthop *nexthop, char *str, int size)  { -  switch (nexthop->type) -    { -      case NEXTHOP_TYPE_IFINDEX: -        snprintf (str, size, "if %u", nexthop->ifindex); -        break; -      case NEXTHOP_TYPE_IPV4: -        snprintf (str, size, "%s", inet_ntoa (nexthop->gate.ipv4)); -        break; -      case NEXTHOP_TYPE_IPV4_IFINDEX: -        snprintf (str, size, "%s if %u", -                  inet_ntoa (nexthop->gate.ipv4), nexthop->ifindex); -        break; -      case NEXTHOP_TYPE_IPV6: -        snprintf (str, size, "%s", inet6_ntoa (nexthop->gate.ipv6)); -        break; -      case NEXTHOP_TYPE_IPV6_IFINDEX: -        snprintf (str, size, "%s if %u", -                  inet6_ntoa (nexthop->gate.ipv6), nexthop->ifindex); -        break; -      case NEXTHOP_TYPE_BLACKHOLE: -        snprintf (str, size, "blackhole"); -        break; -      default: -        snprintf (str, size, "unknown"); -        break; -    } - -  return str; +	switch (nexthop->type) { +	case NEXTHOP_TYPE_IFINDEX: +		snprintf(str, size, "if %u", nexthop->ifindex); +		break; +	case NEXTHOP_TYPE_IPV4: +		snprintf(str, size, "%s", inet_ntoa(nexthop->gate.ipv4)); +		break; +	case NEXTHOP_TYPE_IPV4_IFINDEX: +		snprintf(str, size, "%s if %u", inet_ntoa(nexthop->gate.ipv4), +			 nexthop->ifindex); +		break; +	case NEXTHOP_TYPE_IPV6: +		snprintf(str, size, "%s", inet6_ntoa(nexthop->gate.ipv6)); +		break; +	case NEXTHOP_TYPE_IPV6_IFINDEX: +		snprintf(str, size, "%s if %u", inet6_ntoa(nexthop->gate.ipv6), +			 nexthop->ifindex); +		break; +	case NEXTHOP_TYPE_BLACKHOLE: +		snprintf(str, size, "blackhole"); +		break; +	default: +		snprintf(str, size, "unknown"); +		break; +	} + +	return str;  } diff --git a/lib/nexthop.h b/lib/nexthop.h index e66e0eee20..627ca85415 100644 --- a/lib/nexthop.h +++ b/lib/nexthop.h @@ -31,40 +31,37 @@  #define NEXTHOP_STRLEN (INET6_ADDRSTRLEN + 30)  union g_addr { -  struct in_addr ipv4; -  struct in6_addr ipv6; +	struct in_addr ipv4; +	struct in6_addr ipv6;  }; -enum nexthop_types_t -{ -  NEXTHOP_TYPE_IFINDEX = 1,      /* Directly connected.  */ -  NEXTHOP_TYPE_IPV4,             /* IPv4 nexthop.  */ -  NEXTHOP_TYPE_IPV4_IFINDEX,     /* IPv4 nexthop with ifindex.  */ -  NEXTHOP_TYPE_IPV6,             /* IPv6 nexthop.  */ -  NEXTHOP_TYPE_IPV6_IFINDEX,     /* IPv6 nexthop with ifindex.  */ -  NEXTHOP_TYPE_BLACKHOLE,        /* Null0 nexthop.  */ +enum nexthop_types_t { +	NEXTHOP_TYPE_IFINDEX = 1,  /* Directly connected.  */ +	NEXTHOP_TYPE_IPV4,	 /* IPv4 nexthop.  */ +	NEXTHOP_TYPE_IPV4_IFINDEX, /* IPv4 nexthop with ifindex.  */ +	NEXTHOP_TYPE_IPV6,	 /* IPv6 nexthop.  */ +	NEXTHOP_TYPE_IPV6_IFINDEX, /* IPv6 nexthop with ifindex.  */ +	NEXTHOP_TYPE_BLACKHOLE,    /* Null0 nexthop.  */  };  /* Nexthop label structure. */ -struct nexthop_label -{ -  u_int8_t num_labels; -  u_int8_t reserved[3]; -  mpls_label_t label[0]; /* 1 or more labels. */ +struct nexthop_label { +	u_int8_t num_labels; +	u_int8_t reserved[3]; +	mpls_label_t label[0]; /* 1 or more labels. */  };  /* Nexthop structure. */ -struct nexthop -{ -  struct nexthop *next; -  struct nexthop *prev; +struct nexthop { +	struct nexthop *next; +	struct nexthop *prev; -  /* Interface index. */ -  ifindex_t ifindex; +	/* Interface index. */ +	ifindex_t ifindex; -  enum nexthop_types_t type; +	enum nexthop_types_t type; -  u_char flags; +	u_char flags;  #define NEXTHOP_FLAG_ACTIVE     (1 << 0) /* This nexthop is alive. */  #define NEXTHOP_FLAG_FIB        (1 << 1) /* FIB nexthop. */  #define NEXTHOP_FLAG_RECURSIVE  (1 << 2) /* Recursive nexthop. */ @@ -72,51 +69,52 @@ struct nexthop  #define NEXTHOP_FLAG_MATCHED    (1 << 4) /* Already matched vs a nexthop */  #define NEXTHOP_FLAG_FILTERED   (1 << 5) /* rmap filtered, used by static only */ -  /* Nexthop address */ -  union g_addr gate; -  union g_addr src; -  union g_addr rmap_src;	/* Src is set via routemap */ +	/* Nexthop address */ +	union g_addr gate; +	union g_addr src; +	union g_addr rmap_src; /* Src is set via routemap */ -  /* Nexthops obtained by recursive resolution. -   * -   * If the nexthop struct needs to be resolved recursively, -   * NEXTHOP_FLAG_RECURSIVE will be set in flags and the nexthops -   * obtained by recursive resolution will be added to `resolved'. -   * Only one level of recursive resolution is currently supported. */ -  struct nexthop *resolved; +	/* Nexthops obtained by recursive resolution. +	 * +	 * If the nexthop struct needs to be resolved recursively, +	 * NEXTHOP_FLAG_RECURSIVE will be set in flags and the nexthops +	 * obtained by recursive resolution will be added to `resolved'. +	 * Only one level of recursive resolution is currently supported. */ +	struct nexthop *resolved; -  /* Type of label(s), if any */ -  enum lsp_types_t nh_label_type; +	/* Type of label(s), if any */ +	enum lsp_types_t nh_label_type; -  /* Label(s) associated with this nexthop. */ -  struct nexthop_label *nh_label; +	/* Label(s) associated with this nexthop. */ +	struct nexthop_label *nh_label;  };  extern int zebra_rnh_ip_default_route;  extern int zebra_rnh_ipv6_default_route; -static inline int -nh_resolve_via_default(int family) +static inline int nh_resolve_via_default(int family)  { -  if (((family == AF_INET) && zebra_rnh_ip_default_route) || -      ((family == AF_INET6) && zebra_rnh_ipv6_default_route)) -    return 1; -  else -    return 0; +	if (((family == AF_INET) && zebra_rnh_ip_default_route) +	    || ((family == AF_INET6) && zebra_rnh_ipv6_default_route)) +		return 1; +	else +		return 0;  } -struct nexthop *nexthop_new (void); -void nexthop_add (struct nexthop **target, struct nexthop *nexthop); +struct nexthop *nexthop_new(void); +void nexthop_add(struct nexthop **target, struct nexthop *nexthop); -void copy_nexthops (struct nexthop **tnh, struct nexthop *nh); -void nexthop_free (struct nexthop *nexthop); -void nexthops_free (struct nexthop *nexthop); +void copy_nexthops(struct nexthop **tnh, struct nexthop *nh); +void nexthop_free(struct nexthop *nexthop); +void nexthops_free(struct nexthop *nexthop); -void nexthop_add_labels (struct nexthop *, enum lsp_types_t, u_int8_t, mpls_label_t *); -void nexthop_del_labels (struct nexthop *); +void nexthop_add_labels(struct nexthop *, enum lsp_types_t, u_int8_t, +			mpls_label_t *); +void nexthop_del_labels(struct nexthop *); -extern const char *nexthop_type_to_str (enum nexthop_types_t nh_type); -extern int nexthop_same_no_recurse (struct nexthop *next1, struct nexthop *next2); +extern const char *nexthop_type_to_str(enum nexthop_types_t nh_type); +extern int nexthop_same_no_recurse(struct nexthop *next1, +				   struct nexthop *next2); -extern const char * nexthop2str (struct nexthop *nexthop, char *str, int size); +extern const char *nexthop2str(struct nexthop *nexthop, char *str, int size);  #endif /*_LIB_NEXTHOP_H */ @@ -23,7 +23,7 @@  #include <zebra.h>  #ifdef HAVE_NETNS -#undef  _GNU_SOURCE +#undef _GNU_SOURCE  #define _GNU_SOURCE  #include <sched.h> @@ -37,15 +37,15 @@  #include "command.h"  #include "vty.h" -DEFINE_MTYPE_STATIC(LIB, NS,        "Logical-Router") -DEFINE_MTYPE_STATIC(LIB, NS_NAME,   "Logical-Router Name") +DEFINE_MTYPE_STATIC(LIB, NS, "Logical-Router") +DEFINE_MTYPE_STATIC(LIB, NS_NAME, "Logical-Router Name") -static __inline int ns_compare (struct ns *, struct ns *); -static struct ns *ns_lookup (ns_id_t); +static __inline int ns_compare(struct ns *, struct ns *); +static struct ns *ns_lookup(ns_id_t); -RB_GENERATE (ns_head, ns, entry, ns_compare) +RB_GENERATE(ns_head, ns, entry, ns_compare) -struct ns_head ns_tree = RB_INITIALIZER (&ns_tree); +struct ns_head ns_tree = RB_INITIALIZER(&ns_tree);  #ifndef CLONE_NEWNET  #define CLONE_NEWNET 0x40000000 /* New network namespace (lo, device, names sockets, etc) */ @@ -55,10 +55,10 @@ struct ns_head ns_tree = RB_INITIALIZER (&ns_tree);  static inline int setns(int fd, int nstype)  {  #ifdef __NR_setns -  return syscall(__NR_setns, fd, nstype); +	return syscall(__NR_setns, fd, nstype);  #else -  errno = ENOSYS; -  return -1; +	errno = ENOSYS; +	return -1;  #endif  }  #endif /* HAVE_SETNS */ @@ -68,7 +68,7 @@ static inline int setns(int fd, int nstype)  #define NS_DEFAULT_NAME    "/proc/self/ns/net"  static int have_netns_enabled = -1; -#else /* !HAVE_NETNS */ +#else  /* !HAVE_NETNS */  #define NS_DEFAULT_NAME    "Default-logical-router" @@ -77,105 +77,100 @@ static int have_netns_enabled = -1;  static int have_netns(void)  {  #ifdef HAVE_NETNS -  if (have_netns_enabled < 0) -    { -        int fd = open (NS_DEFAULT_NAME, O_RDONLY); - -        if (fd < 0) -          have_netns_enabled = 0; -        else -          { -            have_netns_enabled = 1; -            close(fd); -          } -    } -  return have_netns_enabled; +	if (have_netns_enabled < 0) { +		int fd = open(NS_DEFAULT_NAME, O_RDONLY); + +		if (fd < 0) +			have_netns_enabled = 0; +		else { +			have_netns_enabled = 1; +			close(fd); +		} +	} +	return have_netns_enabled;  #else -  return 0; +	return 0;  #endif  }  /* Holding NS hooks  */ -struct ns_master -{ -  int (*ns_new_hook) (ns_id_t, void **); -  int (*ns_delete_hook) (ns_id_t, void **); -  int (*ns_enable_hook) (ns_id_t, void **); -  int (*ns_disable_hook) (ns_id_t, void **); -} ns_master = {0,}; - -static int ns_is_enabled (struct ns *ns); -static int ns_enable (struct ns *ns); -static void ns_disable (struct ns *ns); - -static __inline int -ns_compare(struct ns *a, struct ns *b) +struct ns_master { +	int (*ns_new_hook)(ns_id_t, void **); +	int (*ns_delete_hook)(ns_id_t, void **); +	int (*ns_enable_hook)(ns_id_t, void **); +	int (*ns_disable_hook)(ns_id_t, void **); +} ns_master = { +	0, +}; + +static int ns_is_enabled(struct ns *ns); +static int ns_enable(struct ns *ns); +static void ns_disable(struct ns *ns); + +static __inline int ns_compare(struct ns *a, struct ns *b)  { -  return (a->ns_id - b->ns_id); +	return (a->ns_id - b->ns_id);  }  /* Get a NS. If not found, create one. */ -static struct ns * -ns_get (ns_id_t ns_id) +static struct ns *ns_get(ns_id_t ns_id)  { -  struct ns *ns; +	struct ns *ns; -  ns = ns_lookup (ns_id); -  if (ns) -    return (ns); +	ns = ns_lookup(ns_id); +	if (ns) +		return (ns); -  ns = XCALLOC (MTYPE_NS, sizeof (struct ns)); -  ns->ns_id = ns_id; -  ns->fd = -1; -  RB_INSERT (ns_head, &ns_tree, ns); +	ns = XCALLOC(MTYPE_NS, sizeof(struct ns)); +	ns->ns_id = ns_id; +	ns->fd = -1; +	RB_INSERT(ns_head, &ns_tree, ns); -  /* -   * Initialize interfaces. -   * -   * I'm not sure if this belongs here or in -   * the vrf code. -   */ -  // if_init (&ns->iflist); +	/* +	 * Initialize interfaces. +	 * +	 * I'm not sure if this belongs here or in +	 * the vrf code. +	 */ +	// if_init (&ns->iflist); -  zlog_info ("NS %u is created.", ns_id); +	zlog_info("NS %u is created.", ns_id); -  if (ns_master.ns_new_hook) -    (*ns_master.ns_new_hook) (ns_id, &ns->info); +	if (ns_master.ns_new_hook) +		(*ns_master.ns_new_hook)(ns_id, &ns->info); -  return ns; +	return ns;  }  /* Delete a NS. This is called in ns_terminate(). */ -static void -ns_delete (struct ns *ns) +static void ns_delete(struct ns *ns)  { -  zlog_info ("NS %u is to be deleted.", ns->ns_id); +	zlog_info("NS %u is to be deleted.", ns->ns_id); -  ns_disable (ns); +	ns_disable(ns); -  if (ns_master.ns_delete_hook) -    (*ns_master.ns_delete_hook) (ns->ns_id, &ns->info); +	if (ns_master.ns_delete_hook) +		(*ns_master.ns_delete_hook)(ns->ns_id, &ns->info); -  /* -   * I'm not entirely sure if the vrf->iflist -   * needs to be moved into here or not. -   */ -  //if_terminate (&ns->iflist); +	/* +	 * I'm not entirely sure if the vrf->iflist +	 * needs to be moved into here or not. +	 */ +	// if_terminate (&ns->iflist); -  RB_REMOVE (ns_head, &ns_tree, ns); -  if (ns->name) -    XFREE (MTYPE_NS_NAME, ns->name); +	RB_REMOVE(ns_head, &ns_tree, ns); +	if (ns->name) +		XFREE(MTYPE_NS_NAME, ns->name); -  XFREE (MTYPE_NS, ns); +	XFREE(MTYPE_NS, ns);  }  /* Look up a NS by identifier. */ -static struct ns * -ns_lookup (ns_id_t ns_id) +static struct ns *ns_lookup(ns_id_t ns_id)  { -  struct ns ns; -  ns.ns_id = ns_id; -  return (RB_FIND (ns_head, &ns_tree, &ns)); +	struct ns ns; +	ns.ns_id = ns_id; +	return (RB_FIND(ns_head, &ns_tree, &ns));  }  /* @@ -183,13 +178,12 @@ ns_lookup (ns_id_t ns_id)   * is ready to allocate resources. Currently there's only one   * type of resource: socket.   */ -static int -ns_is_enabled (struct ns *ns) +static int ns_is_enabled(struct ns *ns)  { -  if (have_netns()) -      return ns && ns->fd >= 0; -  else -      return ns && ns->fd == -2 && ns->ns_id == NS_DEFAULT; +	if (have_netns()) +		return ns && ns->fd >= 0; +	else +		return ns && ns->fd == -2 && ns->ns_id == NS_DEFAULT;  }  /* @@ -199,36 +193,34 @@ ns_is_enabled (struct ns *ns)   *   * RETURN: 1 - enabled successfully; otherwise, 0.   */ -static int -ns_enable (struct ns *ns) +static int ns_enable(struct ns *ns)  { -  if (!ns_is_enabled (ns)) -    { -      if (have_netns()) { -        ns->fd = open (ns->name, O_RDONLY); -      } else { -        ns->fd = -2; /* Remember that ns_enable_hook has been called */ -        errno = -ENOTSUP; -      } - -      if (!ns_is_enabled (ns)) -        { -          zlog_err ("Can not enable NS %u: %s!", -                    ns->ns_id, safe_strerror (errno)); -          return 0; -        } - -      if (have_netns()) -        zlog_info ("NS %u is associated with NETNS %s.", -                   ns->ns_id, ns->name); - -      zlog_info ("NS %u is enabled.", ns->ns_id); -      if (ns_master.ns_enable_hook) -        (*ns_master.ns_enable_hook) (ns->ns_id, &ns->info); -    } - -  return 1; +	if (!ns_is_enabled(ns)) { +		if (have_netns()) { +			ns->fd = open(ns->name, O_RDONLY); +		} else { +			ns->fd = -2; /* Remember that ns_enable_hook has been +					called */ +			errno = -ENOTSUP; +		} + +		if (!ns_is_enabled(ns)) { +			zlog_err("Can not enable NS %u: %s!", ns->ns_id, +				 safe_strerror(errno)); +			return 0; +		} + +		if (have_netns()) +			zlog_info("NS %u is associated with NETNS %s.", +				  ns->ns_id, ns->name); + +		zlog_info("NS %u is enabled.", ns->ns_id); +		if (ns_master.ns_enable_hook) +			(*ns_master.ns_enable_hook)(ns->ns_id, &ns->info); +	} + +	return 1;  }  /* @@ -236,72 +228,67 @@ ns_enable (struct ns *ns)   * The NS_DELETE_HOOK callback will be called to inform   * that they must release the resources in the NS.   */ -static void -ns_disable (struct ns *ns) +static void ns_disable(struct ns *ns)  { -  if (ns_is_enabled (ns)) -    { -      zlog_info ("NS %u is to be disabled.", ns->ns_id); +	if (ns_is_enabled(ns)) { +		zlog_info("NS %u is to be disabled.", ns->ns_id); -      if (ns_master.ns_disable_hook) -        (*ns_master.ns_disable_hook) (ns->ns_id, &ns->info); +		if (ns_master.ns_disable_hook) +			(*ns_master.ns_disable_hook)(ns->ns_id, &ns->info); -      if (have_netns()) -        close (ns->fd); +		if (have_netns()) +			close(ns->fd); -      ns->fd = -1; -    } +		ns->fd = -1; +	}  }  /* Add a NS hook. Please add hooks before calling ns_init(). */ -void -ns_add_hook (int type, int (*func)(ns_id_t, void **)) +void ns_add_hook(int type, int (*func)(ns_id_t, void **))  { -  switch (type) { -  case NS_NEW_HOOK: -    ns_master.ns_new_hook = func; -    break; -  case NS_DELETE_HOOK: -    ns_master.ns_delete_hook = func; -    break; -  case NS_ENABLE_HOOK: -    ns_master.ns_enable_hook = func; -    break; -  case NS_DISABLE_HOOK: -    ns_master.ns_disable_hook = func; -    break; -  default: -    break; -  } +	switch (type) { +	case NS_NEW_HOOK: +		ns_master.ns_new_hook = func; +		break; +	case NS_DELETE_HOOK: +		ns_master.ns_delete_hook = func; +		break; +	case NS_ENABLE_HOOK: +		ns_master.ns_enable_hook = func; +		break; +	case NS_DISABLE_HOOK: +		ns_master.ns_disable_hook = func; +		break; +	default: +		break; +	}  }  /*   * NS realization with NETNS   */ -static char * -ns_netns_pathname (struct vty *vty, const char *name) +static char *ns_netns_pathname(struct vty *vty, const char *name)  { -  static char pathname[PATH_MAX]; -  char *result; - -  if (name[0] == '/') /* absolute pathname */ -    result = realpath (name, pathname); -  else /* relevant pathname */ -    { -      char tmp_name[PATH_MAX]; -      snprintf (tmp_name, PATH_MAX, "%s/%s", NS_RUN_DIR, name); -      result = realpath (tmp_name, pathname); -    } - -  if (! result) -    { -      vty_out (vty, "Invalid pathname: %s%s", safe_strerror (errno), -               VTY_NEWLINE); -      return NULL; -    } -  return pathname; +	static char pathname[PATH_MAX]; +	char *result; + +	if (name[0] == '/') /* absolute pathname */ +		result = realpath(name, pathname); +	else /* relevant pathname */ +	{ +		char tmp_name[PATH_MAX]; +		snprintf(tmp_name, PATH_MAX, "%s/%s", NS_RUN_DIR, name); +		result = realpath(tmp_name, pathname); +	} + +	if (!result) { +		vty_out(vty, "Invalid pathname: %s%s", safe_strerror(errno), +			VTY_NEWLINE); +		return NULL; +	} +	return pathname;  }  DEFUN_NOSH (ns_netns, @@ -312,36 +299,34 @@ DEFUN_NOSH (ns_netns,         "The Name Space\n"         "The file name in " NS_RUN_DIR ", or a full pathname\n")  { -  int idx_number = 1; -  int idx_name = 3; -  ns_id_t ns_id = NS_DEFAULT; -  struct ns *ns = NULL; -  char *pathname = ns_netns_pathname (vty, argv[idx_name]->arg); - -  if (!pathname) -    return CMD_WARNING; - -  VTY_GET_INTEGER ("NS ID", ns_id, argv[idx_number]->arg); -  ns = ns_get (ns_id); - -  if (ns->name && strcmp (ns->name, pathname) != 0) -    { -      vty_out (vty, "NS %u is already configured with NETNS %s%s", -               ns->ns_id, ns->name, VTY_NEWLINE); -      return CMD_WARNING; -    } - -  if (!ns->name) -    ns->name = XSTRDUP (MTYPE_NS_NAME, pathname); - -  if (!ns_enable (ns)) -    { -      vty_out (vty, "Can not associate NS %u with NETNS %s%s", -               ns->ns_id, ns->name, VTY_NEWLINE); -      return CMD_WARNING; -    } - -  return CMD_SUCCESS; +	int idx_number = 1; +	int idx_name = 3; +	ns_id_t ns_id = NS_DEFAULT; +	struct ns *ns = NULL; +	char *pathname = ns_netns_pathname(vty, argv[idx_name]->arg); + +	if (!pathname) +		return CMD_WARNING; + +	VTY_GET_INTEGER("NS ID", ns_id, argv[idx_number]->arg); +	ns = ns_get(ns_id); + +	if (ns->name && strcmp(ns->name, pathname) != 0) { +		vty_out(vty, "NS %u is already configured with NETNS %s%s", +			ns->ns_id, ns->name, VTY_NEWLINE); +		return CMD_WARNING; +	} + +	if (!ns->name) +		ns->name = XSTRDUP(MTYPE_NS_NAME, pathname); + +	if (!ns_enable(ns)) { +		vty_out(vty, "Can not associate NS %u with NETNS %s%s", +			ns->ns_id, ns->name, VTY_NEWLINE); +		return CMD_WARNING; +	} + +	return CMD_SUCCESS;  }  DEFUN (no_ns_netns, @@ -353,136 +338,119 @@ DEFUN (no_ns_netns,         "The Name Space\n"         "The file name in " NS_RUN_DIR ", or a full pathname\n")  { -  int idx_number = 2; -  int idx_name = 4; -  ns_id_t ns_id = NS_DEFAULT; -  struct ns *ns = NULL; -  char *pathname = ns_netns_pathname (vty, argv[idx_name]->arg); - -  if (!pathname) -    return CMD_WARNING; - -  VTY_GET_INTEGER ("NS ID", ns_id, argv[idx_number]->arg); -  ns = ns_lookup (ns_id); - -  if (!ns) -    { -      vty_out (vty, "NS %u is not found%s", ns_id, VTY_NEWLINE); -      return CMD_SUCCESS; -    } - -  if (ns->name && strcmp (ns->name, pathname) != 0) -    { -      vty_out (vty, "Incorrect NETNS file name%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  ns_disable (ns); - -  if (ns->name) -    { -      XFREE (MTYPE_NS_NAME, ns->name); -      ns->name = NULL; -    } - -  return CMD_SUCCESS; +	int idx_number = 2; +	int idx_name = 4; +	ns_id_t ns_id = NS_DEFAULT; +	struct ns *ns = NULL; +	char *pathname = ns_netns_pathname(vty, argv[idx_name]->arg); + +	if (!pathname) +		return CMD_WARNING; + +	VTY_GET_INTEGER("NS ID", ns_id, argv[idx_number]->arg); +	ns = ns_lookup(ns_id); + +	if (!ns) { +		vty_out(vty, "NS %u is not found%s", ns_id, VTY_NEWLINE); +		return CMD_SUCCESS; +	} + +	if (ns->name && strcmp(ns->name, pathname) != 0) { +		vty_out(vty, "Incorrect NETNS file name%s", VTY_NEWLINE); +		return CMD_WARNING; +	} + +	ns_disable(ns); + +	if (ns->name) { +		XFREE(MTYPE_NS_NAME, ns->name); +		ns->name = NULL; +	} + +	return CMD_SUCCESS;  }  /* NS node. */ -static struct cmd_node ns_node = -{ -  NS_NODE, -  "",       /* NS node has no interface. */ -  1 -}; +static struct cmd_node ns_node = {NS_NODE, "", /* NS node has no interface. */ +				  1};  /* NS configuration write function. */ -static int -ns_config_write (struct vty *vty) +static int ns_config_write(struct vty *vty)  { -  struct ns *ns; -  int write = 0; +	struct ns *ns; +	int write = 0; -  RB_FOREACH (ns, ns_head, &ns_tree) { -      if (ns->ns_id == NS_DEFAULT || ns->name == NULL) -	continue; +	RB_FOREACH(ns, ns_head, &ns_tree) +	{ +		if (ns->ns_id == NS_DEFAULT || ns->name == NULL) +			continue; -      vty_out (vty, "logical-router %u netns %s%s", ns->ns_id, ns->name, -	       VTY_NEWLINE); -      write = 1; -  } +		vty_out(vty, "logical-router %u netns %s%s", ns->ns_id, +			ns->name, VTY_NEWLINE); +		write = 1; +	} -  return write; +	return write;  }  /* Initialize NS module. */ -void -ns_init (void) +void ns_init(void)  { -  struct ns *default_ns; - -  /* The default NS always exists. */ -  default_ns = ns_get (NS_DEFAULT); -  if (!default_ns) -    { -      zlog_err ("ns_init: failed to create the default NS!"); -      exit (1); -    } - -  /* Set the default NS name. */ -  default_ns->name = XSTRDUP (MTYPE_NS_NAME, NS_DEFAULT_NAME); - -  /* Enable the default NS. */ -  if (!ns_enable (default_ns)) -    { -      zlog_err ("ns_init: failed to enable the default NS!"); -      exit (1); -    } - -  if (have_netns()) -    { -      /* Install NS commands. */ -      install_node (&ns_node, ns_config_write); -      install_element (CONFIG_NODE, &ns_netns_cmd); -      install_element (CONFIG_NODE, &no_ns_netns_cmd); -    } +	struct ns *default_ns; + +	/* The default NS always exists. */ +	default_ns = ns_get(NS_DEFAULT); +	if (!default_ns) { +		zlog_err("ns_init: failed to create the default NS!"); +		exit(1); +	} + +	/* Set the default NS name. */ +	default_ns->name = XSTRDUP(MTYPE_NS_NAME, NS_DEFAULT_NAME); + +	/* Enable the default NS. */ +	if (!ns_enable(default_ns)) { +		zlog_err("ns_init: failed to enable the default NS!"); +		exit(1); +	} + +	if (have_netns()) { +		/* Install NS commands. */ +		install_node(&ns_node, ns_config_write); +		install_element(CONFIG_NODE, &ns_netns_cmd); +		install_element(CONFIG_NODE, &no_ns_netns_cmd); +	}  }  /* Terminate NS module. */ -void -ns_terminate (void) +void ns_terminate(void)  { -  struct ns *ns; +	struct ns *ns; -  while ((ns = RB_ROOT (&ns_tree)) != NULL) -    ns_delete (ns); +	while ((ns = RB_ROOT(&ns_tree)) != NULL) +		ns_delete(ns);  }  /* Create a socket for the NS. */ -int -ns_socket (int domain, int type, int protocol, ns_id_t ns_id) +int ns_socket(int domain, int type, int protocol, ns_id_t ns_id)  { -  struct ns *ns = ns_lookup (ns_id); -  int ret = -1; - -  if (!ns_is_enabled (ns)) -    { -      errno = ENOSYS; -      return -1; -    } - -  if (have_netns()) -    { -      ret = (ns_id != NS_DEFAULT) ? setns (ns->fd, CLONE_NEWNET) : 0; -      if (ret >= 0) -        { -          ret = socket (domain, type, protocol); -          if (ns_id != NS_DEFAULT) -            setns (ns_lookup (NS_DEFAULT)->fd, CLONE_NEWNET); -        } -    } -  else -    ret = socket (domain, type, protocol); - -  return ret; +	struct ns *ns = ns_lookup(ns_id); +	int ret = -1; + +	if (!ns_is_enabled(ns)) { +		errno = ENOSYS; +		return -1; +	} + +	if (have_netns()) { +		ret = (ns_id != NS_DEFAULT) ? setns(ns->fd, CLONE_NEWNET) : 0; +		if (ret >= 0) { +			ret = socket(domain, type, protocol); +			if (ns_id != NS_DEFAULT) +				setns(ns_lookup(NS_DEFAULT)->fd, CLONE_NEWNET); +		} +	} else +		ret = socket(domain, type, protocol); + +	return ret;  } @@ -34,27 +34,26 @@ typedef u_int16_t ns_id_t;  /* Default netns directory (Linux) */  #define NS_RUN_DIR         "/var/run/netns" -struct ns -{ -  RB_ENTRY(ns) entry; +struct ns { +	RB_ENTRY(ns) entry; -  /* Identifier, same as the vector index */ -  ns_id_t ns_id; +	/* Identifier, same as the vector index */ +	ns_id_t ns_id; -  /* Name */ -  char *name; +	/* Name */ +	char *name; -  /* File descriptor */ -  int fd; +	/* File descriptor */ +	int fd; -  /* Master list of interfaces belonging to this NS */ -  struct list *iflist; +	/* Master list of interfaces belonging to this NS */ +	struct list *iflist; -  /* User data */ -  void *info; +	/* User data */ +	void *info;  }; -RB_HEAD (ns_head, ns); -RB_PROTOTYPE (ns_head, ns, entry, ns_compare) +RB_HEAD(ns_head, ns); +RB_PROTOTYPE(ns_head, ns, entry, ns_compare)  extern struct ns_head ns_tree; @@ -75,21 +74,20 @@ extern struct ns_head ns_tree;   *          - param 2: the address of the user data pointer (the user data   *                     can be stored in or freed from there)   */ -extern void ns_add_hook (int, int (*)(ns_id_t, void **)); +extern void ns_add_hook(int, int (*)(ns_id_t, void **));  /*   * NS initializer/destructor   */  /* Please add hooks before calling ns_init(). */ -extern void ns_init (void); -extern void ns_terminate (void); +extern void ns_init(void); +extern void ns_terminate(void);  /*   * NS utilities   */  /* Create a socket serving for the given NS */ -extern int ns_socket (int, int, int, ns_id_t); +extern int ns_socket(int, int, int, ns_id_t);  #endif /*_ZEBRA_NS_H*/ - diff --git a/lib/openbsd-queue.h b/lib/openbsd-queue.h index 5e81fdd13d..e09cc3d4e5 100644 --- a/lib/openbsd-queue.h +++ b/lib/openbsd-queue.h @@ -32,7 +32,7 @@   *	@(#)queue.h	8.5 (Berkeley) 8/20/94   */ -#ifndef	_SYS_QUEUE_H_ +#ifndef _SYS_QUEUE_H_  #define	_SYS_QUEUE_H_  /* @@ -88,18 +88,20 @@  /*   * Singly-linked List definitions.   */ -#define SLIST_HEAD(name, type)						\ -struct name {								\ -	struct type *slh_first;	/* first element */			\ -} +#define SLIST_HEAD(name, type)                                                 \ +	struct name {                                                          \ +		struct type *slh_first; /* first element */                    \ +	} -#define	SLIST_HEAD_INITIALIZER(head)					\ -	{ NULL } +#define SLIST_HEAD_INITIALIZER(head)                                           \ +	{                                                                      \ +		NULL                                                           \ +	} -#define SLIST_ENTRY(type)						\ -struct {								\ -	struct type *sle_next;	/* next element */			\ -} +#define SLIST_ENTRY(type)                                                      \ +	struct {                                                               \ +		struct type *sle_next; /* next element */                      \ +	}  /*   * Singly-linked List access methods. @@ -109,71 +111,77 @@ struct {								\  #define	SLIST_EMPTY(head)	(SLIST_FIRST(head) == SLIST_END(head))  #define	SLIST_NEXT(elm, field)	((elm)->field.sle_next) -#define	SLIST_FOREACH(var, head, field)					\ -	for((var) = SLIST_FIRST(head);					\ -	    (var) != SLIST_END(head);					\ -	    (var) = SLIST_NEXT(var, field)) +#define SLIST_FOREACH(var, head, field)                                        \ +	for ((var) = SLIST_FIRST(head); (var) != SLIST_END(head);              \ +	     (var) = SLIST_NEXT(var, field)) -#define	SLIST_FOREACH_SAFE(var, head, field, tvar)			\ -	for ((var) = SLIST_FIRST(head);				\ -	    (var) && ((tvar) = SLIST_NEXT(var, field), 1);		\ -	    (var) = (tvar)) +#define SLIST_FOREACH_SAFE(var, head, field, tvar)                             \ +	for ((var) = SLIST_FIRST(head);                                        \ +	     (var) && ((tvar) = SLIST_NEXT(var, field), 1); (var) = (tvar))  /*   * Singly-linked List functions.   */ -#define	SLIST_INIT(head) {						\ -	SLIST_FIRST(head) = SLIST_END(head);				\ -} - -#define	SLIST_INSERT_AFTER(slistelm, elm, field) do {			\ -	(elm)->field.sle_next = (slistelm)->field.sle_next;		\ -	(slistelm)->field.sle_next = (elm);				\ -} while (0) - -#define	SLIST_INSERT_HEAD(head, elm, field) do {			\ -	(elm)->field.sle_next = (head)->slh_first;			\ -	(head)->slh_first = (elm);					\ -} while (0) - -#define	SLIST_REMOVE_AFTER(elm, field) do {				\ -	(elm)->field.sle_next = (elm)->field.sle_next->field.sle_next;	\ -} while (0) - -#define	SLIST_REMOVE_HEAD(head, field) do {				\ -	(head)->slh_first = (head)->slh_first->field.sle_next;		\ -} while (0) - -#define SLIST_REMOVE(head, elm, type, field) do {			\ -	if ((head)->slh_first == (elm)) {				\ -		SLIST_REMOVE_HEAD((head), field);			\ -	} else {							\ -		struct type *curelm = (head)->slh_first;		\ -									\ -		while (curelm->field.sle_next != (elm))			\ -			curelm = curelm->field.sle_next;		\ -		curelm->field.sle_next =				\ -		    curelm->field.sle_next->field.sle_next;		\ -	}								\ -	_Q_INVALIDATE((elm)->field.sle_next);				\ -} while (0) +#define SLIST_INIT(head)                                                       \ +	{                                                                      \ +		SLIST_FIRST(head) = SLIST_END(head);                           \ +	} + +#define SLIST_INSERT_AFTER(slistelm, elm, field)                               \ +	do {                                                                   \ +		(elm)->field.sle_next = (slistelm)->field.sle_next;            \ +		(slistelm)->field.sle_next = (elm);                            \ +	} while (0) + +#define SLIST_INSERT_HEAD(head, elm, field)                                    \ +	do {                                                                   \ +		(elm)->field.sle_next = (head)->slh_first;                     \ +		(head)->slh_first = (elm);                                     \ +	} while (0) + +#define SLIST_REMOVE_AFTER(elm, field)                                         \ +	do {                                                                   \ +		(elm)->field.sle_next = (elm)->field.sle_next->field.sle_next; \ +	} while (0) + +#define SLIST_REMOVE_HEAD(head, field)                                         \ +	do {                                                                   \ +		(head)->slh_first = (head)->slh_first->field.sle_next;         \ +	} while (0) + +#define SLIST_REMOVE(head, elm, type, field)                                   \ +	do {                                                                   \ +		if ((head)->slh_first == (elm)) {                              \ +			SLIST_REMOVE_HEAD((head), field);                      \ +		} else {                                                       \ +			struct type *curelm = (head)->slh_first;               \ +                                                                               \ +			while (curelm->field.sle_next != (elm))                \ +				curelm = curelm->field.sle_next;               \ +			curelm->field.sle_next =                               \ +				curelm->field.sle_next->field.sle_next;        \ +		}                                                              \ +		_Q_INVALIDATE((elm)->field.sle_next);                          \ +	} while (0)  /*   * List definitions.   */ -#define LIST_HEAD(name, type)						\ -struct name {								\ -	struct type *lh_first;	/* first element */			\ -} - -#define LIST_HEAD_INITIALIZER(head)					\ -	{ NULL } - -#define LIST_ENTRY(type)						\ -struct {								\ -	struct type *le_next;	/* next element */			\ -	struct type **le_prev;	/* address of previous next element */	\ -} +#define LIST_HEAD(name, type)                                                  \ +	struct name {                                                          \ +		struct type *lh_first; /* first element */                     \ +	} + +#define LIST_HEAD_INITIALIZER(head)                                            \ +	{                                                                      \ +		NULL                                                           \ +	} + +#define LIST_ENTRY(type)                                                       \ +	struct {                                                               \ +		struct type *le_next;  /* next element */                      \ +		struct type **le_prev; /* address of previous next element */  \ +	}  /*   * List access methods. @@ -183,80 +191,87 @@ struct {								\  #define	LIST_EMPTY(head)		(LIST_FIRST(head) == LIST_END(head))  #define	LIST_NEXT(elm, field)		((elm)->field.le_next) -#define LIST_FOREACH(var, head, field)					\ -	for((var) = LIST_FIRST(head);					\ -	    (var)!= LIST_END(head);					\ -	    (var) = LIST_NEXT(var, field)) +#define LIST_FOREACH(var, head, field)                                         \ +	for ((var) = LIST_FIRST(head); (var) != LIST_END(head);                \ +	     (var) = LIST_NEXT(var, field)) -#define	LIST_FOREACH_SAFE(var, head, field, tvar)			\ -	for ((var) = LIST_FIRST(head);				\ -	    (var) && ((tvar) = LIST_NEXT(var, field), 1);		\ -	    (var) = (tvar)) +#define LIST_FOREACH_SAFE(var, head, field, tvar)                              \ +	for ((var) = LIST_FIRST(head);                                         \ +	     (var) && ((tvar) = LIST_NEXT(var, field), 1); (var) = (tvar))  /*   * List functions.   */ -#define	LIST_INIT(head) do {						\ -	LIST_FIRST(head) = LIST_END(head);				\ -} while (0) - -#define LIST_INSERT_AFTER(listelm, elm, field) do {			\ -	if (((elm)->field.le_next = (listelm)->field.le_next) != NULL)	\ -		(listelm)->field.le_next->field.le_prev =		\ -		    &(elm)->field.le_next;				\ -	(listelm)->field.le_next = (elm);				\ -	(elm)->field.le_prev = &(listelm)->field.le_next;		\ -} while (0) - -#define	LIST_INSERT_BEFORE(listelm, elm, field) do {			\ -	(elm)->field.le_prev = (listelm)->field.le_prev;		\ -	(elm)->field.le_next = (listelm);				\ -	*(listelm)->field.le_prev = (elm);				\ -	(listelm)->field.le_prev = &(elm)->field.le_next;		\ -} while (0) - -#define LIST_INSERT_HEAD(head, elm, field) do {				\ -	if (((elm)->field.le_next = (head)->lh_first) != NULL)		\ -		(head)->lh_first->field.le_prev = &(elm)->field.le_next;\ -	(head)->lh_first = (elm);					\ -	(elm)->field.le_prev = &(head)->lh_first;			\ -} while (0) - -#define LIST_REMOVE(elm, field) do {					\ -	if ((elm)->field.le_next != NULL)				\ -		(elm)->field.le_next->field.le_prev =			\ -		    (elm)->field.le_prev;				\ -	*(elm)->field.le_prev = (elm)->field.le_next;			\ -	_Q_INVALIDATE((elm)->field.le_prev);				\ -	_Q_INVALIDATE((elm)->field.le_next);				\ -} while (0) - -#define LIST_REPLACE(elm, elm2, field) do {				\ -	if (((elm2)->field.le_next = (elm)->field.le_next) != NULL)	\ -		(elm2)->field.le_next->field.le_prev =			\ -		    &(elm2)->field.le_next;				\ -	(elm2)->field.le_prev = (elm)->field.le_prev;			\ -	*(elm2)->field.le_prev = (elm2);				\ -	_Q_INVALIDATE((elm)->field.le_prev);				\ -	_Q_INVALIDATE((elm)->field.le_next);				\ -} while (0) +#define LIST_INIT(head)                                                        \ +	do {                                                                   \ +		LIST_FIRST(head) = LIST_END(head);                             \ +	} while (0) + +#define LIST_INSERT_AFTER(listelm, elm, field)                                 \ +	do {                                                                   \ +		if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ +			(listelm)->field.le_next->field.le_prev =              \ +				&(elm)->field.le_next;                         \ +		(listelm)->field.le_next = (elm);                              \ +		(elm)->field.le_prev = &(listelm)->field.le_next;              \ +	} while (0) + +#define LIST_INSERT_BEFORE(listelm, elm, field)                                \ +	do {                                                                   \ +		(elm)->field.le_prev = (listelm)->field.le_prev;               \ +		(elm)->field.le_next = (listelm);                              \ +		*(listelm)->field.le_prev = (elm);                             \ +		(listelm)->field.le_prev = &(elm)->field.le_next;              \ +	} while (0) + +#define LIST_INSERT_HEAD(head, elm, field)                                     \ +	do {                                                                   \ +		if (((elm)->field.le_next = (head)->lh_first) != NULL)         \ +			(head)->lh_first->field.le_prev =                      \ +				&(elm)->field.le_next;                         \ +		(head)->lh_first = (elm);                                      \ +		(elm)->field.le_prev = &(head)->lh_first;                      \ +	} while (0) + +#define LIST_REMOVE(elm, field)                                                \ +	do {                                                                   \ +		if ((elm)->field.le_next != NULL)                              \ +			(elm)->field.le_next->field.le_prev =                  \ +				(elm)->field.le_prev;                          \ +		*(elm)->field.le_prev = (elm)->field.le_next;                  \ +		_Q_INVALIDATE((elm)->field.le_prev);                           \ +		_Q_INVALIDATE((elm)->field.le_next);                           \ +	} while (0) + +#define LIST_REPLACE(elm, elm2, field)                                         \ +	do {                                                                   \ +		if (((elm2)->field.le_next = (elm)->field.le_next) != NULL)    \ +			(elm2)->field.le_next->field.le_prev =                 \ +				&(elm2)->field.le_next;                        \ +		(elm2)->field.le_prev = (elm)->field.le_prev;                  \ +		*(elm2)->field.le_prev = (elm2);                               \ +		_Q_INVALIDATE((elm)->field.le_prev);                           \ +		_Q_INVALIDATE((elm)->field.le_next);                           \ +	} while (0)  /*   * Simple queue definitions.   */ -#define SIMPLEQ_HEAD(name, type)					\ -struct name {								\ -	struct type *sqh_first;	/* first element */			\ -	struct type **sqh_last;	/* addr of last next element */		\ -} - -#define SIMPLEQ_HEAD_INITIALIZER(head)					\ -	{ NULL, &(head).sqh_first } - -#define SIMPLEQ_ENTRY(type)						\ -struct {								\ -	struct type *sqe_next;	/* next element */			\ -} +#define SIMPLEQ_HEAD(name, type)                                               \ +	struct name {                                                          \ +		struct type *sqh_first; /* first element */                    \ +		struct type **sqh_last; /* addr of last next element */        \ +	} + +#define SIMPLEQ_HEAD_INITIALIZER(head)                                         \ +	{                                                                      \ +		NULL, &(head).sqh_first                                        \ +	} + +#define SIMPLEQ_ENTRY(type)                                                    \ +	struct {                                                               \ +		struct type *sqe_next; /* next element */                      \ +	}  /*   * Simple queue access methods. @@ -266,158 +281,179 @@ struct {								\  #define	SIMPLEQ_EMPTY(head)	    (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head))  #define	SIMPLEQ_NEXT(elm, field)    ((elm)->field.sqe_next) -#define SIMPLEQ_FOREACH(var, head, field)				\ -	for((var) = SIMPLEQ_FIRST(head);				\ -	    (var) != SIMPLEQ_END(head);					\ -	    (var) = SIMPLEQ_NEXT(var, field)) +#define SIMPLEQ_FOREACH(var, head, field)                                      \ +	for ((var) = SIMPLEQ_FIRST(head); (var) != SIMPLEQ_END(head);          \ +	     (var) = SIMPLEQ_NEXT(var, field)) -#define	SIMPLEQ_FOREACH_SAFE(var, head, field, tvar)			\ -	for ((var) = SIMPLEQ_FIRST(head);				\ -	    (var) && ((tvar) = SIMPLEQ_NEXT(var, field), 1);		\ -	    (var) = (tvar)) +#define SIMPLEQ_FOREACH_SAFE(var, head, field, tvar)                           \ +	for ((var) = SIMPLEQ_FIRST(head);                                      \ +	     (var) && ((tvar) = SIMPLEQ_NEXT(var, field), 1); (var) = (tvar))  /*   * Simple queue functions.   */ -#define	SIMPLEQ_INIT(head) do {						\ -	(head)->sqh_first = NULL;					\ -	(head)->sqh_last = &(head)->sqh_first;				\ -} while (0) - -#define SIMPLEQ_INSERT_HEAD(head, elm, field) do {			\ -	if (((elm)->field.sqe_next = (head)->sqh_first) == NULL)	\ -		(head)->sqh_last = &(elm)->field.sqe_next;		\ -	(head)->sqh_first = (elm);					\ -} while (0) - -#define SIMPLEQ_INSERT_TAIL(head, elm, field) do {			\ -	(elm)->field.sqe_next = NULL;					\ -	*(head)->sqh_last = (elm);					\ -	(head)->sqh_last = &(elm)->field.sqe_next;			\ -} while (0) - -#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do {		\ -	if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ -		(head)->sqh_last = &(elm)->field.sqe_next;		\ -	(listelm)->field.sqe_next = (elm);				\ -} while (0) - -#define SIMPLEQ_REMOVE_HEAD(head, field) do {			\ -	if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ -		(head)->sqh_last = &(head)->sqh_first;			\ -} while (0) - -#define SIMPLEQ_REMOVE_AFTER(head, elm, field) do {			\ -	if (((elm)->field.sqe_next = (elm)->field.sqe_next->field.sqe_next) \ -	    == NULL)							\ -		(head)->sqh_last = &(elm)->field.sqe_next;		\ -} while (0) - -#define SIMPLEQ_CONCAT(head1, head2) do {				\ -	if (!SIMPLEQ_EMPTY((head2))) {					\ -		*(head1)->sqh_last = (head2)->sqh_first;		\ -		(head1)->sqh_last = (head2)->sqh_last;			\ -		SIMPLEQ_INIT((head2));					\ -	}								\ -} while (0) +#define SIMPLEQ_INIT(head)                                                     \ +	do {                                                                   \ +		(head)->sqh_first = NULL;                                      \ +		(head)->sqh_last = &(head)->sqh_first;                         \ +	} while (0) + +#define SIMPLEQ_INSERT_HEAD(head, elm, field)                                  \ +	do {                                                                   \ +		if (((elm)->field.sqe_next = (head)->sqh_first) == NULL)       \ +			(head)->sqh_last = &(elm)->field.sqe_next;             \ +		(head)->sqh_first = (elm);                                     \ +	} while (0) + +#define SIMPLEQ_INSERT_TAIL(head, elm, field)                                  \ +	do {                                                                   \ +		(elm)->field.sqe_next = NULL;                                  \ +		*(head)->sqh_last = (elm);                                     \ +		(head)->sqh_last = &(elm)->field.sqe_next;                     \ +	} while (0) + +#define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field)                        \ +	do {                                                                   \ +		if (((elm)->field.sqe_next = (listelm)->field.sqe_next)        \ +		    == NULL)                                                   \ +			(head)->sqh_last = &(elm)->field.sqe_next;             \ +		(listelm)->field.sqe_next = (elm);                             \ +	} while (0) + +#define SIMPLEQ_REMOVE_HEAD(head, field)                                       \ +	do {                                                                   \ +		if (((head)->sqh_first = (head)->sqh_first->field.sqe_next)    \ +		    == NULL)                                                   \ +			(head)->sqh_last = &(head)->sqh_first;                 \ +	} while (0) + +#define SIMPLEQ_REMOVE_AFTER(head, elm, field)                                 \ +	do {                                                                   \ +		if (((elm)->field.sqe_next =                                   \ +			     (elm)->field.sqe_next->field.sqe_next)            \ +		    == NULL)                                                   \ +			(head)->sqh_last = &(elm)->field.sqe_next;             \ +	} while (0) + +#define SIMPLEQ_CONCAT(head1, head2)                                           \ +	do {                                                                   \ +		if (!SIMPLEQ_EMPTY((head2))) {                                 \ +			*(head1)->sqh_last = (head2)->sqh_first;               \ +			(head1)->sqh_last = (head2)->sqh_last;                 \ +			SIMPLEQ_INIT((head2));                                 \ +		}                                                              \ +	} while (0)  /*   * XOR Simple queue definitions.   */ -#define XSIMPLEQ_HEAD(name, type)					\ -struct name {								\ -	struct type *sqx_first;	/* first element */			\ -	struct type **sqx_last;	/* addr of last next element */		\ -	unsigned long sqx_cookie;					\ -} - -#define XSIMPLEQ_ENTRY(type)						\ -struct {								\ -	struct type *sqx_next;	/* next element */			\ -} +#define XSIMPLEQ_HEAD(name, type)                                              \ +	struct name {                                                          \ +		struct type *sqx_first; /* first element */                    \ +		struct type **sqx_last; /* addr of last next element */        \ +		unsigned long sqx_cookie;                                      \ +	} + +#define XSIMPLEQ_ENTRY(type)                                                   \ +	struct {                                                               \ +		struct type *sqx_next; /* next element */                      \ +	}  /*   * XOR Simple queue access methods.   */ -#define XSIMPLEQ_XOR(head, ptr)	    ((__typeof(ptr))((head)->sqx_cookie ^ \ -					(unsigned long)(ptr))) +#define XSIMPLEQ_XOR(head, ptr)                                                \ +	((__typeof(ptr))((head)->sqx_cookie ^ (unsigned long)(ptr)))  #define	XSIMPLEQ_FIRST(head)	    XSIMPLEQ_XOR(head, ((head)->sqx_first))  #define	XSIMPLEQ_END(head)	    NULL  #define	XSIMPLEQ_EMPTY(head)	    (XSIMPLEQ_FIRST(head) == XSIMPLEQ_END(head))  #define	XSIMPLEQ_NEXT(head, elm, field)    XSIMPLEQ_XOR(head, ((elm)->field.sqx_next)) +#define XSIMPLEQ_FOREACH(var, head, field)                                     \ +	for ((var) = XSIMPLEQ_FIRST(head); (var) != XSIMPLEQ_END(head);        \ +	     (var) = XSIMPLEQ_NEXT(head, var, field)) -#define XSIMPLEQ_FOREACH(var, head, field)				\ -	for ((var) = XSIMPLEQ_FIRST(head);				\ -	    (var) != XSIMPLEQ_END(head);				\ -	    (var) = XSIMPLEQ_NEXT(head, var, field)) - -#define	XSIMPLEQ_FOREACH_SAFE(var, head, field, tvar)			\ -	for ((var) = XSIMPLEQ_FIRST(head);				\ -	    (var) && ((tvar) = XSIMPLEQ_NEXT(head, var, field), 1);	\ -	    (var) = (tvar)) +#define XSIMPLEQ_FOREACH_SAFE(var, head, field, tvar)                          \ +	for ((var) = XSIMPLEQ_FIRST(head);                                     \ +	     (var) && ((tvar) = XSIMPLEQ_NEXT(head, var, field), 1);           \ +	     (var) = (tvar))  /*   * XOR Simple queue functions.   */ -#define	XSIMPLEQ_INIT(head) do {					\ -	arc4random_buf(&(head)->sqx_cookie, sizeof((head)->sqx_cookie)); \ -	(head)->sqx_first = XSIMPLEQ_XOR(head, NULL);			\ -	(head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first);	\ -} while (0) - -#define XSIMPLEQ_INSERT_HEAD(head, elm, field) do {			\ -	if (((elm)->field.sqx_next = (head)->sqx_first) ==		\ -	    XSIMPLEQ_XOR(head, NULL))					\ +#define XSIMPLEQ_INIT(head)                                                    \ +	do {                                                                   \ +		arc4random_buf(&(head)->sqx_cookie,                            \ +			       sizeof((head)->sqx_cookie));                    \ +		(head)->sqx_first = XSIMPLEQ_XOR(head, NULL);                  \ +		(head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first);     \ +	} while (0) + +#define XSIMPLEQ_INSERT_HEAD(head, elm, field)                                 \ +	do {                                                                   \ +		if (((elm)->field.sqx_next = (head)->sqx_first)                \ +		    == XSIMPLEQ_XOR(head, NULL))                               \ +			(head)->sqx_last =                                     \ +				XSIMPLEQ_XOR(head, &(elm)->field.sqx_next);    \ +		(head)->sqx_first = XSIMPLEQ_XOR(head, (elm));                 \ +	} while (0) + +#define XSIMPLEQ_INSERT_TAIL(head, elm, field)                                 \ +	do {                                                                   \ +		(elm)->field.sqx_next = XSIMPLEQ_XOR(head, NULL);              \ +		*(XSIMPLEQ_XOR(head, (head)->sqx_last)) =                      \ +			XSIMPLEQ_XOR(head, (elm));                             \  		(head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ -	(head)->sqx_first = XSIMPLEQ_XOR(head, (elm));			\ -} while (0) - -#define XSIMPLEQ_INSERT_TAIL(head, elm, field) do {			\ -	(elm)->field.sqx_next = XSIMPLEQ_XOR(head, NULL);		\ -	*(XSIMPLEQ_XOR(head, (head)->sqx_last)) = XSIMPLEQ_XOR(head, (elm)); \ -	(head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next);	\ -} while (0) - -#define XSIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do {		\ -	if (((elm)->field.sqx_next = (listelm)->field.sqx_next) ==	\ -	    XSIMPLEQ_XOR(head, NULL))					\ -		(head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ -	(listelm)->field.sqx_next = XSIMPLEQ_XOR(head, (elm));		\ -} while (0) - -#define XSIMPLEQ_REMOVE_HEAD(head, field) do {				\ -	if (((head)->sqx_first = XSIMPLEQ_XOR(head,			\ -	    (head)->sqx_first)->field.sqx_next) == XSIMPLEQ_XOR(head, NULL)) \ -		(head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \ -} while (0) - -#define XSIMPLEQ_REMOVE_AFTER(head, elm, field) do {			\ -	if (((elm)->field.sqx_next = XSIMPLEQ_XOR(head,			\ -	    (elm)->field.sqx_next)->field.sqx_next)			\ -	    == XSIMPLEQ_XOR(head, NULL))				\ -		(head)->sqx_last = 					\ -		    XSIMPLEQ_XOR(head, &(elm)->field.sqx_next);		\ -} while (0) +	} while (0) + +#define XSIMPLEQ_INSERT_AFTER(head, listelm, elm, field)                       \ +	do {                                                                   \ +		if (((elm)->field.sqx_next = (listelm)->field.sqx_next)        \ +		    == XSIMPLEQ_XOR(head, NULL))                               \ +			(head)->sqx_last =                                     \ +				XSIMPLEQ_XOR(head, &(elm)->field.sqx_next);    \ +		(listelm)->field.sqx_next = XSIMPLEQ_XOR(head, (elm));         \ +	} while (0) + +#define XSIMPLEQ_REMOVE_HEAD(head, field)                                      \ +	do {                                                                   \ +		if (((head)->sqx_first = XSIMPLEQ_XOR(head, (head)->sqx_first) \ +						 ->field.sqx_next)             \ +		    == XSIMPLEQ_XOR(head, NULL))                               \ +			(head)->sqx_last =                                     \ +				XSIMPLEQ_XOR(head, &(head)->sqx_first);        \ +	} while (0) + +#define XSIMPLEQ_REMOVE_AFTER(head, elm, field)                                \ +	do {                                                                   \ +		if (((elm)->field.sqx_next =                                   \ +			     XSIMPLEQ_XOR(head, (elm)->field.sqx_next)         \ +				     ->field.sqx_next)                         \ +		    == XSIMPLEQ_XOR(head, NULL))                               \ +			(head)->sqx_last =                                     \ +				XSIMPLEQ_XOR(head, &(elm)->field.sqx_next);    \ +	} while (0)  /*   * Tail queue definitions.   */ -#define TAILQ_HEAD(name, type)						\ -struct name {								\ -	struct type *tqh_first;	/* first element */			\ -	struct type **tqh_last;	/* addr of last next element */		\ -} - -#define TAILQ_HEAD_INITIALIZER(head)					\ -	{ NULL, &(head).tqh_first } - -#define TAILQ_ENTRY(type)						\ -struct {								\ -	struct type *tqe_next;	/* next element */			\ -	struct type **tqe_prev;	/* address of previous next element */	\ -} +#define TAILQ_HEAD(name, type)                                                 \ +	struct name {                                                          \ +		struct type *tqh_first; /* first element */                    \ +		struct type **tqh_last; /* addr of last next element */        \ +	} + +#define TAILQ_HEAD_INITIALIZER(head)                                           \ +	{                                                                      \ +		NULL, &(head).tqh_first                                        \ +	} + +#define TAILQ_ENTRY(type)                                                      \ +	struct {                                                               \ +		struct type *tqe_next;  /* next element */                     \ +		struct type **tqe_prev; /* address of previous next element */ \ +	}  /*   * Tail queue access methods. @@ -425,109 +461,115 @@ struct {								\  #define	TAILQ_FIRST(head)		((head)->tqh_first)  #define	TAILQ_END(head)			NULL  #define	TAILQ_NEXT(elm, field)		((elm)->field.tqe_next) -#define TAILQ_LAST(head, headname)					\ +#define TAILQ_LAST(head, headname)                                             \  	(*(((struct headname *)((head)->tqh_last))->tqh_last))  /* XXX */ -#define TAILQ_PREV(elm, headname, field)				\ +#define TAILQ_PREV(elm, headname, field)                                       \  	(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) -#define	TAILQ_EMPTY(head)						\ -	(TAILQ_FIRST(head) == TAILQ_END(head)) +#define TAILQ_EMPTY(head) (TAILQ_FIRST(head) == TAILQ_END(head)) -#define TAILQ_FOREACH(var, head, field)					\ -	for((var) = TAILQ_FIRST(head);					\ -	    (var) != TAILQ_END(head);					\ -	    (var) = TAILQ_NEXT(var, field)) +#define TAILQ_FOREACH(var, head, field)                                        \ +	for ((var) = TAILQ_FIRST(head); (var) != TAILQ_END(head);              \ +	     (var) = TAILQ_NEXT(var, field)) -#define	TAILQ_FOREACH_SAFE(var, head, field, tvar)			\ -	for ((var) = TAILQ_FIRST(head);					\ -	    (var) != TAILQ_END(head) &&					\ -	    ((tvar) = TAILQ_NEXT(var, field), 1);			\ -	    (var) = (tvar)) +#define TAILQ_FOREACH_SAFE(var, head, field, tvar)                             \ +	for ((var) = TAILQ_FIRST(head);                                        \ +	     (var) != TAILQ_END(head) && ((tvar) = TAILQ_NEXT(var, field), 1); \ +	     (var) = (tvar)) -#define TAILQ_FOREACH_REVERSE(var, head, headname, field)		\ -	for((var) = TAILQ_LAST(head, headname);				\ -	    (var) != TAILQ_END(head);					\ -	    (var) = TAILQ_PREV(var, headname, field)) +#define TAILQ_FOREACH_REVERSE(var, head, headname, field)                      \ +	for ((var) = TAILQ_LAST(head, headname); (var) != TAILQ_END(head);     \ +	     (var) = TAILQ_PREV(var, headname, field)) -#define	TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar)	\ -	for ((var) = TAILQ_LAST(head, headname);			\ -	    (var) != TAILQ_END(head) &&					\ -	    ((tvar) = TAILQ_PREV(var, headname, field), 1);		\ -	    (var) = (tvar)) +#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar)           \ +	for ((var) = TAILQ_LAST(head, headname);                               \ +	     (var) != TAILQ_END(head)                                          \ +	     && ((tvar) = TAILQ_PREV(var, headname, field), 1);                \ +	     (var) = (tvar))  /*   * Tail queue functions.   */ -#define	TAILQ_INIT(head) do {						\ -	(head)->tqh_first = NULL;					\ -	(head)->tqh_last = &(head)->tqh_first;				\ -} while (0) - -#define TAILQ_INSERT_HEAD(head, elm, field) do {			\ -	if (((elm)->field.tqe_next = (head)->tqh_first) != NULL)	\ -		(head)->tqh_first->field.tqe_prev =			\ -		    &(elm)->field.tqe_next;				\ -	else								\ -		(head)->tqh_last = &(elm)->field.tqe_next;		\ -	(head)->tqh_first = (elm);					\ -	(elm)->field.tqe_prev = &(head)->tqh_first;			\ -} while (0) - -#define TAILQ_INSERT_TAIL(head, elm, field) do {			\ -	(elm)->field.tqe_next = NULL;					\ -	(elm)->field.tqe_prev = (head)->tqh_last;			\ -	*(head)->tqh_last = (elm);					\ -	(head)->tqh_last = &(elm)->field.tqe_next;			\ -} while (0) - -#define TAILQ_INSERT_AFTER(head, listelm, elm, field) do {		\ -	if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ -		(elm)->field.tqe_next->field.tqe_prev =			\ -		    &(elm)->field.tqe_next;				\ -	else								\ -		(head)->tqh_last = &(elm)->field.tqe_next;		\ -	(listelm)->field.tqe_next = (elm);				\ -	(elm)->field.tqe_prev = &(listelm)->field.tqe_next;		\ -} while (0) - -#define	TAILQ_INSERT_BEFORE(listelm, elm, field) do {			\ -	(elm)->field.tqe_prev = (listelm)->field.tqe_prev;		\ -	(elm)->field.tqe_next = (listelm);				\ -	*(listelm)->field.tqe_prev = (elm);				\ -	(listelm)->field.tqe_prev = &(elm)->field.tqe_next;		\ -} while (0) - -#define TAILQ_REMOVE(head, elm, field) do {				\ -	if (((elm)->field.tqe_next) != NULL)				\ -		(elm)->field.tqe_next->field.tqe_prev =			\ -		    (elm)->field.tqe_prev;				\ -	else								\ -		(head)->tqh_last = (elm)->field.tqe_prev;		\ -	*(elm)->field.tqe_prev = (elm)->field.tqe_next;			\ -	_Q_INVALIDATE((elm)->field.tqe_prev);				\ -	_Q_INVALIDATE((elm)->field.tqe_next);				\ -} while (0) - -#define TAILQ_REPLACE(head, elm, elm2, field) do {			\ -	if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL)	\ -		(elm2)->field.tqe_next->field.tqe_prev =		\ -		    &(elm2)->field.tqe_next;				\ -	else								\ -		(head)->tqh_last = &(elm2)->field.tqe_next;		\ -	(elm2)->field.tqe_prev = (elm)->field.tqe_prev;			\ -	*(elm2)->field.tqe_prev = (elm2);				\ -	_Q_INVALIDATE((elm)->field.tqe_prev);				\ -	_Q_INVALIDATE((elm)->field.tqe_next);				\ -} while (0) - -#define TAILQ_CONCAT(head1, head2, field) do {				\ -	if (!TAILQ_EMPTY(head2)) {					\ -		*(head1)->tqh_last = (head2)->tqh_first;		\ -		(head2)->tqh_first->field.tqe_prev = (head1)->tqh_last;	\ -		(head1)->tqh_last = (head2)->tqh_last;			\ -		TAILQ_INIT((head2));					\ -	}								\ -} while (0) - -#endif	/* !_SYS_QUEUE_H_ */ +#define TAILQ_INIT(head)                                                       \ +	do {                                                                   \ +		(head)->tqh_first = NULL;                                      \ +		(head)->tqh_last = &(head)->tqh_first;                         \ +	} while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field)                                    \ +	do {                                                                   \ +		if (((elm)->field.tqe_next = (head)->tqh_first) != NULL)       \ +			(head)->tqh_first->field.tqe_prev =                    \ +				&(elm)->field.tqe_next;                        \ +		else                                                           \ +			(head)->tqh_last = &(elm)->field.tqe_next;             \ +		(head)->tqh_first = (elm);                                     \ +		(elm)->field.tqe_prev = &(head)->tqh_first;                    \ +	} while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field)                                    \ +	do {                                                                   \ +		(elm)->field.tqe_next = NULL;                                  \ +		(elm)->field.tqe_prev = (head)->tqh_last;                      \ +		*(head)->tqh_last = (elm);                                     \ +		(head)->tqh_last = &(elm)->field.tqe_next;                     \ +	} while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field)                          \ +	do {                                                                   \ +		if (((elm)->field.tqe_next = (listelm)->field.tqe_next)        \ +		    != NULL)                                                   \ +			(elm)->field.tqe_next->field.tqe_prev =                \ +				&(elm)->field.tqe_next;                        \ +		else                                                           \ +			(head)->tqh_last = &(elm)->field.tqe_next;             \ +		(listelm)->field.tqe_next = (elm);                             \ +		(elm)->field.tqe_prev = &(listelm)->field.tqe_next;            \ +	} while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field)                               \ +	do {                                                                   \ +		(elm)->field.tqe_prev = (listelm)->field.tqe_prev;             \ +		(elm)->field.tqe_next = (listelm);                             \ +		*(listelm)->field.tqe_prev = (elm);                            \ +		(listelm)->field.tqe_prev = &(elm)->field.tqe_next;            \ +	} while (0) + +#define TAILQ_REMOVE(head, elm, field)                                         \ +	do {                                                                   \ +		if (((elm)->field.tqe_next) != NULL)                           \ +			(elm)->field.tqe_next->field.tqe_prev =                \ +				(elm)->field.tqe_prev;                         \ +		else                                                           \ +			(head)->tqh_last = (elm)->field.tqe_prev;              \ +		*(elm)->field.tqe_prev = (elm)->field.tqe_next;                \ +		_Q_INVALIDATE((elm)->field.tqe_prev);                          \ +		_Q_INVALIDATE((elm)->field.tqe_next);                          \ +	} while (0) + +#define TAILQ_REPLACE(head, elm, elm2, field)                                  \ +	do {                                                                   \ +		if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL)  \ +			(elm2)->field.tqe_next->field.tqe_prev =               \ +				&(elm2)->field.tqe_next;                       \ +		else                                                           \ +			(head)->tqh_last = &(elm2)->field.tqe_next;            \ +		(elm2)->field.tqe_prev = (elm)->field.tqe_prev;                \ +		*(elm2)->field.tqe_prev = (elm2);                              \ +		_Q_INVALIDATE((elm)->field.tqe_prev);                          \ +		_Q_INVALIDATE((elm)->field.tqe_next);                          \ +	} while (0) + +#define TAILQ_CONCAT(head1, head2, field)                                      \ +	do {                                                                   \ +		if (!TAILQ_EMPTY(head2)) {                                     \ +			*(head1)->tqh_last = (head2)->tqh_first;               \ +			(head2)->tqh_first->field.tqe_prev =                   \ +				(head1)->tqh_last;                             \ +			(head1)->tqh_last = (head2)->tqh_last;                 \ +			TAILQ_INIT((head2));                                   \ +		}                                                              \ +	} while (0) + +#endif /* !_SYS_QUEUE_H_ */ diff --git a/lib/openbsd-tree.h b/lib/openbsd-tree.h index e6502b1e74..aa80c1134a 100644 --- a/lib/openbsd-tree.h +++ b/lib/openbsd-tree.h @@ -24,7 +24,7 @@   * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.   */ -#ifndef	_SYS_TREE_H_ +#ifndef _SYS_TREE_H_  #define	_SYS_TREE_H_  /* @@ -54,23 +54,26 @@   * The maximum height of a red-black tree is 2lg (n+1).   */ -#define SPLAY_HEAD(name, type)						\ -struct name {								\ -	struct type *sph_root; /* root of the tree */			\ -} +#define SPLAY_HEAD(name, type)                                                 \ +	struct name {                                                          \ +		struct type *sph_root; /* root of the tree */                  \ +	} -#define SPLAY_INITIALIZER(root)						\ -	{ NULL } +#define SPLAY_INITIALIZER(root)                                                \ +	{                                                                      \ +		NULL                                                           \ +	} -#define SPLAY_INIT(root) do {						\ -	(root)->sph_root = NULL;					\ -} while (0) +#define SPLAY_INIT(root)                                                       \ +	do {                                                                   \ +		(root)->sph_root = NULL;                                       \ +	} while (0) -#define SPLAY_ENTRY(type)						\ -struct {								\ -	struct type *spe_left; /* left element */			\ -	struct type *spe_right; /* right element */			\ -} +#define SPLAY_ENTRY(type)                                                      \ +	struct {                                                               \ +		struct type *spe_left;  /* left element */                     \ +		struct type *spe_right; /* right element */                    \ +	}  #define SPLAY_LEFT(elm, field)		(elm)->field.spe_left  #define SPLAY_RIGHT(elm, field)		(elm)->field.spe_right @@ -78,197 +81,220 @@ struct {								\  #define SPLAY_EMPTY(head)		(SPLAY_ROOT(head) == NULL)  /* SPLAY_ROTATE_{LEFT,RIGHT} expect that tmp hold SPLAY_{RIGHT,LEFT} */ -#define SPLAY_ROTATE_RIGHT(head, tmp, field) do {			\ -	SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field);	\ -	SPLAY_RIGHT(tmp, field) = (head)->sph_root;			\ -	(head)->sph_root = tmp;						\ -} while (0) - -#define SPLAY_ROTATE_LEFT(head, tmp, field) do {			\ -	SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field);	\ -	SPLAY_LEFT(tmp, field) = (head)->sph_root;			\ -	(head)->sph_root = tmp;						\ -} while (0) - -#define SPLAY_LINKLEFT(head, tmp, field) do {				\ -	SPLAY_LEFT(tmp, field) = (head)->sph_root;			\ -	tmp = (head)->sph_root;						\ -	(head)->sph_root = SPLAY_LEFT((head)->sph_root, field);		\ -} while (0) - -#define SPLAY_LINKRIGHT(head, tmp, field) do {				\ -	SPLAY_RIGHT(tmp, field) = (head)->sph_root;			\ -	tmp = (head)->sph_root;						\ -	(head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);	\ -} while (0) - -#define SPLAY_ASSEMBLE(head, node, left, right, field) do {		\ -	SPLAY_RIGHT(left, field) = SPLAY_LEFT((head)->sph_root, field);	\ -	SPLAY_LEFT(right, field) = SPLAY_RIGHT((head)->sph_root, field);\ -	SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(node, field);	\ -	SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(node, field);	\ -} while (0) +#define SPLAY_ROTATE_RIGHT(head, tmp, field)                                   \ +	do {                                                                   \ +		SPLAY_LEFT((head)->sph_root, field) = SPLAY_RIGHT(tmp, field); \ +		SPLAY_RIGHT(tmp, field) = (head)->sph_root;                    \ +		(head)->sph_root = tmp;                                        \ +	} while (0) + +#define SPLAY_ROTATE_LEFT(head, tmp, field)                                    \ +	do {                                                                   \ +		SPLAY_RIGHT((head)->sph_root, field) = SPLAY_LEFT(tmp, field); \ +		SPLAY_LEFT(tmp, field) = (head)->sph_root;                     \ +		(head)->sph_root = tmp;                                        \ +	} while (0) + +#define SPLAY_LINKLEFT(head, tmp, field)                                       \ +	do {                                                                   \ +		SPLAY_LEFT(tmp, field) = (head)->sph_root;                     \ +		tmp = (head)->sph_root;                                        \ +		(head)->sph_root = SPLAY_LEFT((head)->sph_root, field);        \ +	} while (0) + +#define SPLAY_LINKRIGHT(head, tmp, field)                                      \ +	do {                                                                   \ +		SPLAY_RIGHT(tmp, field) = (head)->sph_root;                    \ +		tmp = (head)->sph_root;                                        \ +		(head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);       \ +	} while (0) + +#define SPLAY_ASSEMBLE(head, node, left, right, field)                         \ +	do {                                                                   \ +		SPLAY_RIGHT(left, field) =                                     \ +			SPLAY_LEFT((head)->sph_root, field);                   \ +		SPLAY_LEFT(right, field) =                                     \ +			SPLAY_RIGHT((head)->sph_root, field);                  \ +		SPLAY_LEFT((head)->sph_root, field) =                          \ +			SPLAY_RIGHT(node, field);                              \ +		SPLAY_RIGHT((head)->sph_root, field) =                         \ +			SPLAY_LEFT(node, field);                               \ +	} while (0)  /* Generates prototypes and inline functions */ -#define SPLAY_PROTOTYPE(name, type, field, cmp)				\ -void name##_SPLAY(struct name *, struct type *);			\ -void name##_SPLAY_MINMAX(struct name *, int);				\ -struct type *name##_SPLAY_INSERT(struct name *, struct type *);		\ -struct type *name##_SPLAY_REMOVE(struct name *, struct type *);		\ -									\ -/* Finds the node with the same key as elm */				\ -static __inline struct type *						\ -name##_SPLAY_FIND(struct name *head, struct type *elm)			\ -{									\ -	if (SPLAY_EMPTY(head))						\ -		return(NULL);						\ -	name##_SPLAY(head, elm);					\ -	if ((cmp)(elm, (head)->sph_root) == 0)				\ -		return (head->sph_root);				\ -	return (NULL);							\ -}									\ -									\ -static __inline struct type *						\ -name##_SPLAY_NEXT(struct name *head, struct type *elm)			\ -{									\ -	name##_SPLAY(head, elm);					\ -	if (SPLAY_RIGHT(elm, field) != NULL) {				\ -		elm = SPLAY_RIGHT(elm, field);				\ -		while (SPLAY_LEFT(elm, field) != NULL) {		\ -			elm = SPLAY_LEFT(elm, field);			\ -		}							\ -	} else								\ -		elm = NULL;						\ -	return (elm);							\ -}									\ -									\ -static __inline struct type *						\ -name##_SPLAY_MIN_MAX(struct name *head, int val)			\ -{									\ -	name##_SPLAY_MINMAX(head, val);					\ -        return (SPLAY_ROOT(head));					\ -} +#define SPLAY_PROTOTYPE(name, type, field, cmp)                                \ +	void name##_SPLAY(struct name *, struct type *);                       \ +	void name##_SPLAY_MINMAX(struct name *, int);                          \ +	struct type *name##_SPLAY_INSERT(struct name *, struct type *);        \ +	struct type *name##_SPLAY_REMOVE(struct name *, struct type *);        \ +                                                                               \ +	/* Finds the node with the same key as elm */                          \ +	static __inline struct type *name##_SPLAY_FIND(struct name *head,      \ +						       struct type *elm)       \ +	{                                                                      \ +		if (SPLAY_EMPTY(head))                                         \ +			return (NULL);                                         \ +		name##_SPLAY(head, elm);                                       \ +		if ((cmp)(elm, (head)->sph_root) == 0)                         \ +			return (head->sph_root);                               \ +		return (NULL);                                                 \ +	}                                                                      \ +                                                                               \ +	static __inline struct type *name##_SPLAY_NEXT(struct name *head,      \ +						       struct type *elm)       \ +	{                                                                      \ +		name##_SPLAY(head, elm);                                       \ +		if (SPLAY_RIGHT(elm, field) != NULL) {                         \ +			elm = SPLAY_RIGHT(elm, field);                         \ +			while (SPLAY_LEFT(elm, field) != NULL) {               \ +				elm = SPLAY_LEFT(elm, field);                  \ +			}                                                      \ +		} else                                                         \ +			elm = NULL;                                            \ +		return (elm);                                                  \ +	}                                                                      \ +                                                                               \ +	static __inline struct type *name##_SPLAY_MIN_MAX(struct name *head,   \ +							  int val)             \ +	{                                                                      \ +		name##_SPLAY_MINMAX(head, val);                                \ +		return (SPLAY_ROOT(head));                                     \ +	}  /* Main splay operation.   * Moves node close to the key of elm to top   */ -#define SPLAY_GENERATE(name, type, field, cmp)				\ -struct type *								\ -name##_SPLAY_INSERT(struct name *head, struct type *elm)		\ -{									\ -    if (SPLAY_EMPTY(head)) {						\ -	    SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) = NULL;	\ -    } else {								\ -	    int __comp;							\ -	    name##_SPLAY(head, elm);					\ -	    __comp = (cmp)(elm, (head)->sph_root);			\ -	    if(__comp < 0) {						\ -		    SPLAY_LEFT(elm, field) = SPLAY_LEFT((head)->sph_root, field);\ -		    SPLAY_RIGHT(elm, field) = (head)->sph_root;		\ -		    SPLAY_LEFT((head)->sph_root, field) = NULL;		\ -	    } else if (__comp > 0) {					\ -		    SPLAY_RIGHT(elm, field) = SPLAY_RIGHT((head)->sph_root, field);\ -		    SPLAY_LEFT(elm, field) = (head)->sph_root;		\ -		    SPLAY_RIGHT((head)->sph_root, field) = NULL;	\ -	    } else							\ -		    return ((head)->sph_root);				\ -    }									\ -    (head)->sph_root = (elm);						\ -    return (NULL);							\ -}									\ -									\ -struct type *								\ -name##_SPLAY_REMOVE(struct name *head, struct type *elm)		\ -{									\ -	struct type *__tmp;						\ -	if (SPLAY_EMPTY(head))						\ -		return (NULL);						\ -	name##_SPLAY(head, elm);					\ -	if ((cmp)(elm, (head)->sph_root) == 0) {			\ -		if (SPLAY_LEFT((head)->sph_root, field) == NULL) {	\ -			(head)->sph_root = SPLAY_RIGHT((head)->sph_root, field);\ -		} else {						\ -			__tmp = SPLAY_RIGHT((head)->sph_root, field);	\ -			(head)->sph_root = SPLAY_LEFT((head)->sph_root, field);\ -			name##_SPLAY(head, elm);			\ -			SPLAY_RIGHT((head)->sph_root, field) = __tmp;	\ -		}							\ -		return (elm);						\ -	}								\ -	return (NULL);							\ -}									\ -									\ -void									\ -name##_SPLAY(struct name *head, struct type *elm)			\ -{									\ -	struct type __node, *__left, *__right, *__tmp;			\ -	int __comp;							\ -\ -	SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\ -	__left = __right = &__node;					\ -\ -	while ((__comp = (cmp)(elm, (head)->sph_root))) {		\ -		if (__comp < 0) {					\ -			__tmp = SPLAY_LEFT((head)->sph_root, field);	\ -			if (__tmp == NULL)				\ -				break;					\ -			if ((cmp)(elm, __tmp) < 0){			\ -				SPLAY_ROTATE_RIGHT(head, __tmp, field);	\ -				if (SPLAY_LEFT((head)->sph_root, field) == NULL)\ -					break;				\ -			}						\ -			SPLAY_LINKLEFT(head, __right, field);		\ -		} else if (__comp > 0) {				\ -			__tmp = SPLAY_RIGHT((head)->sph_root, field);	\ -			if (__tmp == NULL)				\ -				break;					\ -			if ((cmp)(elm, __tmp) > 0){			\ -				SPLAY_ROTATE_LEFT(head, __tmp, field);	\ -				if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\ -					break;				\ -			}						\ -			SPLAY_LINKRIGHT(head, __left, field);		\ -		}							\ -	}								\ -	SPLAY_ASSEMBLE(head, &__node, __left, __right, field);		\ -}									\ -									\ -/* Splay with either the minimum or the maximum element			\ - * Used to find minimum or maximum element in tree.			\ - */									\ -void name##_SPLAY_MINMAX(struct name *head, int __comp) \ -{									\ -	struct type __node, *__left, *__right, *__tmp;			\ -\ -	SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) = NULL;\ -	__left = __right = &__node;					\ -\ -	while (1) {							\ -		if (__comp < 0) {					\ -			__tmp = SPLAY_LEFT((head)->sph_root, field);	\ -			if (__tmp == NULL)				\ -				break;					\ -			if (__comp < 0){				\ -				SPLAY_ROTATE_RIGHT(head, __tmp, field);	\ -				if (SPLAY_LEFT((head)->sph_root, field) == NULL)\ -					break;				\ -			}						\ -			SPLAY_LINKLEFT(head, __right, field);		\ -		} else if (__comp > 0) {				\ -			__tmp = SPLAY_RIGHT((head)->sph_root, field);	\ -			if (__tmp == NULL)				\ -				break;					\ -			if (__comp > 0) {				\ -				SPLAY_ROTATE_LEFT(head, __tmp, field);	\ -				if (SPLAY_RIGHT((head)->sph_root, field) == NULL)\ -					break;				\ -			}						\ -			SPLAY_LINKRIGHT(head, __left, field);		\ -		}							\ -	}								\ -	SPLAY_ASSEMBLE(head, &__node, __left, __right, field);		\ -} +#define SPLAY_GENERATE(name, type, field, cmp)                                 \ +	struct type *name##_SPLAY_INSERT(struct name *head, struct type *elm)  \ +	{                                                                      \ +		if (SPLAY_EMPTY(head)) {                                       \ +			SPLAY_LEFT(elm, field) = SPLAY_RIGHT(elm, field) =     \ +				NULL;                                          \ +		} else {                                                       \ +			int __comp;                                            \ +			name##_SPLAY(head, elm);                               \ +			__comp = (cmp)(elm, (head)->sph_root);                 \ +			if (__comp < 0) {                                      \ +				SPLAY_LEFT(elm, field) =                       \ +					SPLAY_LEFT((head)->sph_root, field);   \ +				SPLAY_RIGHT(elm, field) = (head)->sph_root;    \ +				SPLAY_LEFT((head)->sph_root, field) = NULL;    \ +			} else if (__comp > 0) {                               \ +				SPLAY_RIGHT(elm, field) =                      \ +					SPLAY_RIGHT((head)->sph_root, field);  \ +				SPLAY_LEFT(elm, field) = (head)->sph_root;     \ +				SPLAY_RIGHT((head)->sph_root, field) = NULL;   \ +			} else                                                 \ +				return ((head)->sph_root);                     \ +		}                                                              \ +		(head)->sph_root = (elm);                                      \ +		return (NULL);                                                 \ +	}                                                                      \ +                                                                               \ +	struct type *name##_SPLAY_REMOVE(struct name *head, struct type *elm)  \ +	{                                                                      \ +		struct type *__tmp;                                            \ +		if (SPLAY_EMPTY(head))                                         \ +			return (NULL);                                         \ +		name##_SPLAY(head, elm);                                       \ +		if ((cmp)(elm, (head)->sph_root) == 0) {                       \ +			if (SPLAY_LEFT((head)->sph_root, field) == NULL) {     \ +				(head)->sph_root =                             \ +					SPLAY_RIGHT((head)->sph_root, field);  \ +			} else {                                               \ +				__tmp = SPLAY_RIGHT((head)->sph_root, field);  \ +				(head)->sph_root =                             \ +					SPLAY_LEFT((head)->sph_root, field);   \ +				name##_SPLAY(head, elm);                       \ +				SPLAY_RIGHT((head)->sph_root, field) = __tmp;  \ +			}                                                      \ +			return (elm);                                          \ +		}                                                              \ +		return (NULL);                                                 \ +	}                                                                      \ +                                                                               \ +	void name##_SPLAY(struct name *head, struct type *elm)                 \ +	{                                                                      \ +		struct type __node, *__left, *__right, *__tmp;                 \ +		int __comp;                                                    \ +                                                                               \ +		SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) =     \ +			NULL;                                                  \ +		__left = __right = &__node;                                    \ +                                                                               \ +		while ((__comp = (cmp)(elm, (head)->sph_root))) {              \ +			if (__comp < 0) {                                      \ +				__tmp = SPLAY_LEFT((head)->sph_root, field);   \ +				if (__tmp == NULL)                             \ +					break;                                 \ +				if ((cmp)(elm, __tmp) < 0) {                   \ +					SPLAY_ROTATE_RIGHT(head, __tmp,        \ +							   field);             \ +					if (SPLAY_LEFT((head)->sph_root,       \ +						       field)                  \ +					    == NULL)                           \ +						break;                         \ +				}                                              \ +				SPLAY_LINKLEFT(head, __right, field);          \ +			} else if (__comp > 0) {                               \ +				__tmp = SPLAY_RIGHT((head)->sph_root, field);  \ +				if (__tmp == NULL)                             \ +					break;                                 \ +				if ((cmp)(elm, __tmp) > 0) {                   \ +					SPLAY_ROTATE_LEFT(head, __tmp, field); \ +					if (SPLAY_RIGHT((head)->sph_root,      \ +							field)                 \ +					    == NULL)                           \ +						break;                         \ +				}                                              \ +				SPLAY_LINKRIGHT(head, __left, field);          \ +			}                                                      \ +		}                                                              \ +		SPLAY_ASSEMBLE(head, &__node, __left, __right, field);         \ +	}                                                                      \ +                                                                               \ +	/* Splay with either the minimum or the maximum element                \ +	 * Used to find minimum or maximum element in tree.                    \ +	 */                                                                    \ +	void name##_SPLAY_MINMAX(struct name *head, int __comp)                \ +	{                                                                      \ +		struct type __node, *__left, *__right, *__tmp;                 \ +                                                                               \ +		SPLAY_LEFT(&__node, field) = SPLAY_RIGHT(&__node, field) =     \ +			NULL;                                                  \ +		__left = __right = &__node;                                    \ +                                                                               \ +		while (1) {                                                    \ +			if (__comp < 0) {                                      \ +				__tmp = SPLAY_LEFT((head)->sph_root, field);   \ +				if (__tmp == NULL)                             \ +					break;                                 \ +				if (__comp < 0) {                              \ +					SPLAY_ROTATE_RIGHT(head, __tmp,        \ +							   field);             \ +					if (SPLAY_LEFT((head)->sph_root,       \ +						       field)                  \ +					    == NULL)                           \ +						break;                         \ +				}                                              \ +				SPLAY_LINKLEFT(head, __right, field);          \ +			} else if (__comp > 0) {                               \ +				__tmp = SPLAY_RIGHT((head)->sph_root, field);  \ +				if (__tmp == NULL)                             \ +					break;                                 \ +				if (__comp > 0) {                              \ +					SPLAY_ROTATE_LEFT(head, __tmp, field); \ +					if (SPLAY_RIGHT((head)->sph_root,      \ +							field)                 \ +					    == NULL)                           \ +						break;                         \ +				}                                              \ +				SPLAY_LINKRIGHT(head, __left, field);          \ +			}                                                      \ +		}                                                              \ +		SPLAY_ASSEMBLE(head, &__node, __left, __right, field);         \ +	}  #define SPLAY_NEGINF	-1  #define SPLAY_INF	1 @@ -277,38 +303,40 @@ void name##_SPLAY_MINMAX(struct name *head, int __comp) \  #define SPLAY_REMOVE(name, x, y)	name##_SPLAY_REMOVE(x, y)  #define SPLAY_FIND(name, x, y)		name##_SPLAY_FIND(x, y)  #define SPLAY_NEXT(name, x, y)		name##_SPLAY_NEXT(x, y) -#define SPLAY_MIN(name, x)		(SPLAY_EMPTY(x) ? NULL	\ -					: name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF)) -#define SPLAY_MAX(name, x)		(SPLAY_EMPTY(x) ? NULL	\ -					: name##_SPLAY_MIN_MAX(x, SPLAY_INF)) - -#define SPLAY_FOREACH(x, name, head)					\ -	for ((x) = SPLAY_MIN(name, head);				\ -	     (x) != NULL;						\ +#define SPLAY_MIN(name, x)                                                     \ +	(SPLAY_EMPTY(x) ? NULL : name##_SPLAY_MIN_MAX(x, SPLAY_NEGINF)) +#define SPLAY_MAX(name, x)                                                     \ +	(SPLAY_EMPTY(x) ? NULL : name##_SPLAY_MIN_MAX(x, SPLAY_INF)) + +#define SPLAY_FOREACH(x, name, head)                                           \ +	for ((x) = SPLAY_MIN(name, head); (x) != NULL;                         \  	     (x) = SPLAY_NEXT(name, head, x))  /* Macros that define a red-black tree */ -#define RB_HEAD(name, type)						\ -struct name {								\ -	struct type *rbh_root; /* root of the tree */			\ -} +#define RB_HEAD(name, type)                                                    \ +	struct name {                                                          \ +		struct type *rbh_root; /* root of the tree */                  \ +	} -#define RB_INITIALIZER(root)						\ -	{ NULL } +#define RB_INITIALIZER(root)                                                   \ +	{                                                                      \ +		NULL                                                           \ +	} -#define RB_INIT(root) do {						\ -	(root)->rbh_root = NULL;					\ -} while (0) +#define RB_INIT(root)                                                          \ +	do {                                                                   \ +		(root)->rbh_root = NULL;                                       \ +	} while (0)  #define RB_BLACK	0  #define RB_RED		1 -#define RB_ENTRY(type)							\ -struct {								\ -	struct type *rbe_left;		/* left element */		\ -	struct type *rbe_right;		/* right element */		\ -	struct type *rbe_parent;	/* parent element */		\ -	int rbe_color;			/* node color */		\ -} +#define RB_ENTRY(type)                                                         \ +	struct {                                                               \ +		struct type *rbe_left;   /* left element */                    \ +		struct type *rbe_right;  /* right element */                   \ +		struct type *rbe_parent; /* parent element */                  \ +		int rbe_color;		 /* node color */                      \ +	}  #define RB_LEFT(elm, field)		(elm)->field.rbe_left  #define RB_RIGHT(elm, field)		(elm)->field.rbe_right @@ -317,401 +345,441 @@ struct {								\  #define RB_ROOT(head)			(head)->rbh_root  #define RB_EMPTY(head)			(RB_ROOT(head) == NULL) -#define RB_SET(elm, parent, field) do {					\ -	RB_PARENT(elm, field) = parent;					\ -	RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL;		\ -	RB_COLOR(elm, field) = RB_RED;					\ -} while (0) +#define RB_SET(elm, parent, field)                                             \ +	do {                                                                   \ +		RB_PARENT(elm, field) = parent;                                \ +		RB_LEFT(elm, field) = RB_RIGHT(elm, field) = NULL;             \ +		RB_COLOR(elm, field) = RB_RED;                                 \ +	} while (0) -#define RB_SET_BLACKRED(black, red, field) do {				\ -	RB_COLOR(black, field) = RB_BLACK;				\ -	RB_COLOR(red, field) = RB_RED;					\ -} while (0) +#define RB_SET_BLACKRED(black, red, field)                                     \ +	do {                                                                   \ +		RB_COLOR(black, field) = RB_BLACK;                             \ +		RB_COLOR(red, field) = RB_RED;                                 \ +	} while (0)  #ifndef RB_AUGMENT  #define RB_AUGMENT(x)	do {} while (0)  #endif -#define RB_ROTATE_LEFT(head, elm, tmp, field) do {			\ -	(tmp) = RB_RIGHT(elm, field);					\ -	if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field))) {		\ -		RB_PARENT(RB_LEFT(tmp, field), field) = (elm);		\ -	}								\ -	RB_AUGMENT(elm);						\ -	if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {		\ -		if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))	\ -			RB_LEFT(RB_PARENT(elm, field), field) = (tmp);	\ -		else							\ -			RB_RIGHT(RB_PARENT(elm, field), field) = (tmp);	\ -	} else								\ -		(head)->rbh_root = (tmp);				\ -	RB_LEFT(tmp, field) = (elm);					\ -	RB_PARENT(elm, field) = (tmp);					\ -	RB_AUGMENT(tmp);						\ -	if ((RB_PARENT(tmp, field)))					\ -		RB_AUGMENT(RB_PARENT(tmp, field));			\ -} while (0) - -#define RB_ROTATE_RIGHT(head, elm, tmp, field) do {			\ -	(tmp) = RB_LEFT(elm, field);					\ -	if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field))) {		\ -		RB_PARENT(RB_RIGHT(tmp, field), field) = (elm);		\ -	}								\ -	RB_AUGMENT(elm);						\ -	if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {		\ -		if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))	\ -			RB_LEFT(RB_PARENT(elm, field), field) = (tmp);	\ -		else							\ -			RB_RIGHT(RB_PARENT(elm, field), field) = (tmp);	\ -	} else								\ -		(head)->rbh_root = (tmp);				\ -	RB_RIGHT(tmp, field) = (elm);					\ -	RB_PARENT(elm, field) = (tmp);					\ -	RB_AUGMENT(tmp);						\ -	if ((RB_PARENT(tmp, field)))					\ -		RB_AUGMENT(RB_PARENT(tmp, field));			\ -} while (0) +#define RB_ROTATE_LEFT(head, elm, tmp, field)                                  \ +	do {                                                                   \ +		(tmp) = RB_RIGHT(elm, field);                                  \ +		if ((RB_RIGHT(elm, field) = RB_LEFT(tmp, field))) {            \ +			RB_PARENT(RB_LEFT(tmp, field), field) = (elm);         \ +		}                                                              \ +		RB_AUGMENT(elm);                                               \ +		if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {         \ +			if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))    \ +				RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ +			else                                                   \ +				RB_RIGHT(RB_PARENT(elm, field), field) =       \ +					(tmp);                                 \ +		} else                                                         \ +			(head)->rbh_root = (tmp);                              \ +		RB_LEFT(tmp, field) = (elm);                                   \ +		RB_PARENT(elm, field) = (tmp);                                 \ +		RB_AUGMENT(tmp);                                               \ +		if ((RB_PARENT(tmp, field)))                                   \ +			RB_AUGMENT(RB_PARENT(tmp, field));                     \ +	} while (0) + +#define RB_ROTATE_RIGHT(head, elm, tmp, field)                                 \ +	do {                                                                   \ +		(tmp) = RB_LEFT(elm, field);                                   \ +		if ((RB_LEFT(elm, field) = RB_RIGHT(tmp, field))) {            \ +			RB_PARENT(RB_RIGHT(tmp, field), field) = (elm);        \ +		}                                                              \ +		RB_AUGMENT(elm);                                               \ +		if ((RB_PARENT(tmp, field) = RB_PARENT(elm, field))) {         \ +			if ((elm) == RB_LEFT(RB_PARENT(elm, field), field))    \ +				RB_LEFT(RB_PARENT(elm, field), field) = (tmp); \ +			else                                                   \ +				RB_RIGHT(RB_PARENT(elm, field), field) =       \ +					(tmp);                                 \ +		} else                                                         \ +			(head)->rbh_root = (tmp);                              \ +		RB_RIGHT(tmp, field) = (elm);                                  \ +		RB_PARENT(elm, field) = (tmp);                                 \ +		RB_AUGMENT(tmp);                                               \ +		if ((RB_PARENT(tmp, field)))                                   \ +			RB_AUGMENT(RB_PARENT(tmp, field));                     \ +	} while (0)  /* Generates prototypes and inline functions */ -#define	RB_PROTOTYPE(name, type, field, cmp)				\ -	RB_PROTOTYPE_INTERNAL(name, type, field, cmp,) -#define	RB_PROTOTYPE_STATIC(name, type, field, cmp)			\ -	RB_PROTOTYPE_INTERNAL(name, type, field, cmp, __attribute__((__unused__)) static) -#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr)		\ -attr void name##_RB_INSERT_COLOR(struct name *, struct type *);		\ -attr void name##_RB_REMOVE_COLOR(struct name *, struct type *, struct type *);\ -attr struct type *name##_RB_REMOVE(struct name *, struct type *);	\ -attr struct type *name##_RB_INSERT(struct name *, struct type *);	\ -attr struct type *name##_RB_FIND(struct name *, struct type *);		\ -attr struct type *name##_RB_NFIND(struct name *, struct type *);	\ -attr struct type *name##_RB_NEXT(struct type *);			\ -attr struct type *name##_RB_PREV(struct type *);			\ -attr struct type *name##_RB_MINMAX(struct name *, int);			\ -									\ +#define RB_PROTOTYPE(name, type, field, cmp)                                   \ +	RB_PROTOTYPE_INTERNAL(name, type, field, cmp, ) +#define RB_PROTOTYPE_STATIC(name, type, field, cmp)                            \ +	RB_PROTOTYPE_INTERNAL(name, type, field, cmp,                          \ +			      __attribute__((__unused__)) static) +#define RB_PROTOTYPE_INTERNAL(name, type, field, cmp, attr)                    \ +	attr void name##_RB_INSERT_COLOR(struct name *, struct type *);        \ +	attr void name##_RB_REMOVE_COLOR(struct name *, struct type *,         \ +					 struct type *);                       \ +	attr struct type *name##_RB_REMOVE(struct name *, struct type *);      \ +	attr struct type *name##_RB_INSERT(struct name *, struct type *);      \ +	attr struct type *name##_RB_FIND(struct name *, struct type *);        \ +	attr struct type *name##_RB_NFIND(struct name *, struct type *);       \ +	attr struct type *name##_RB_NEXT(struct type *);                       \ +	attr struct type *name##_RB_PREV(struct type *);                       \ +	attr struct type *name##_RB_MINMAX(struct name *, int); +  /* Main rb operation.   * Moves node close to the key of elm to top   */ -#define	RB_GENERATE(name, type, field, cmp)				\ -	RB_GENERATE_INTERNAL(name, type, field, cmp,) -#define	RB_GENERATE_STATIC(name, type, field, cmp)			\ -	RB_GENERATE_INTERNAL(name, type, field, cmp, __attribute__((__unused__)) static) -#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr)		\ -attr void								\ -name##_RB_INSERT_COLOR(struct name *head, struct type *elm)		\ -{									\ -	struct type *parent, *gparent, *tmp;				\ -	while ((parent = RB_PARENT(elm, field)) &&			\ -	    RB_COLOR(parent, field) == RB_RED) {			\ -		gparent = RB_PARENT(parent, field);			\ -		if (parent == RB_LEFT(gparent, field)) {		\ -			tmp = RB_RIGHT(gparent, field);			\ -			if (tmp && RB_COLOR(tmp, field) == RB_RED) {	\ -				RB_COLOR(tmp, field) = RB_BLACK;	\ -				RB_SET_BLACKRED(parent, gparent, field);\ -				elm = gparent;				\ -				continue;				\ -			}						\ -			if (RB_RIGHT(parent, field) == elm) {		\ -				RB_ROTATE_LEFT(head, parent, tmp, field);\ -				tmp = parent;				\ -				parent = elm;				\ -				elm = tmp;				\ -			}						\ -			RB_SET_BLACKRED(parent, gparent, field);	\ -			RB_ROTATE_RIGHT(head, gparent, tmp, field);	\ -		} else {						\ -			tmp = RB_LEFT(gparent, field);			\ -			if (tmp && RB_COLOR(tmp, field) == RB_RED) {	\ -				RB_COLOR(tmp, field) = RB_BLACK;	\ -				RB_SET_BLACKRED(parent, gparent, field);\ -				elm = gparent;				\ -				continue;				\ -			}						\ -			if (RB_LEFT(parent, field) == elm) {		\ -				RB_ROTATE_RIGHT(head, parent, tmp, field);\ -				tmp = parent;				\ -				parent = elm;				\ -				elm = tmp;				\ -			}						\ -			RB_SET_BLACKRED(parent, gparent, field);	\ -			RB_ROTATE_LEFT(head, gparent, tmp, field);	\ -		}							\ -	}								\ -	RB_COLOR(head->rbh_root, field) = RB_BLACK;			\ -}									\ -									\ -attr void								\ -name##_RB_REMOVE_COLOR(struct name *head, struct type *parent, struct type *elm) \ -{									\ -	struct type *tmp;						\ -	while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK) &&	\ -	    elm != RB_ROOT(head)) {					\ -		if (RB_LEFT(parent, field) == elm) {			\ -			tmp = RB_RIGHT(parent, field);			\ -			if (RB_COLOR(tmp, field) == RB_RED) {		\ -				RB_SET_BLACKRED(tmp, parent, field);	\ -				RB_ROTATE_LEFT(head, parent, tmp, field);\ -				tmp = RB_RIGHT(parent, field);		\ -			}						\ -			if ((RB_LEFT(tmp, field) == NULL ||		\ -			    RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\ -			    (RB_RIGHT(tmp, field) == NULL ||		\ -			    RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\ -				RB_COLOR(tmp, field) = RB_RED;		\ -				elm = parent;				\ -				parent = RB_PARENT(elm, field);		\ -			} else {					\ -				if (RB_RIGHT(tmp, field) == NULL ||	\ -				    RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK) {\ -					struct type *oleft;		\ -					if ((oleft = RB_LEFT(tmp, field)))\ -						RB_COLOR(oleft, field) = RB_BLACK;\ -					RB_COLOR(tmp, field) = RB_RED;	\ -					RB_ROTATE_RIGHT(head, tmp, oleft, field);\ -					tmp = RB_RIGHT(parent, field);	\ -				}					\ -				RB_COLOR(tmp, field) = RB_COLOR(parent, field);\ -				RB_COLOR(parent, field) = RB_BLACK;	\ -				if (RB_RIGHT(tmp, field))		\ -					RB_COLOR(RB_RIGHT(tmp, field), field) = RB_BLACK;\ -				RB_ROTATE_LEFT(head, parent, tmp, field);\ -				elm = RB_ROOT(head);			\ -				break;					\ -			}						\ -		} else {						\ -			tmp = RB_LEFT(parent, field);			\ -			if (RB_COLOR(tmp, field) == RB_RED) {		\ -				RB_SET_BLACKRED(tmp, parent, field);	\ -				RB_ROTATE_RIGHT(head, parent, tmp, field);\ -				tmp = RB_LEFT(parent, field);		\ -			}						\ -			if ((RB_LEFT(tmp, field) == NULL ||		\ -			    RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) &&\ -			    (RB_RIGHT(tmp, field) == NULL ||		\ -			    RB_COLOR(RB_RIGHT(tmp, field), field) == RB_BLACK)) {\ -				RB_COLOR(tmp, field) = RB_RED;		\ -				elm = parent;				\ -				parent = RB_PARENT(elm, field);		\ -			} else {					\ -				if (RB_LEFT(tmp, field) == NULL ||	\ -				    RB_COLOR(RB_LEFT(tmp, field), field) == RB_BLACK) {\ -					struct type *oright;		\ -					if ((oright = RB_RIGHT(tmp, field)))\ -						RB_COLOR(oright, field) = RB_BLACK;\ -					RB_COLOR(tmp, field) = RB_RED;	\ -					RB_ROTATE_LEFT(head, tmp, oright, field);\ -					tmp = RB_LEFT(parent, field);	\ -				}					\ -				RB_COLOR(tmp, field) = RB_COLOR(parent, field);\ -				RB_COLOR(parent, field) = RB_BLACK;	\ -				if (RB_LEFT(tmp, field))		\ -					RB_COLOR(RB_LEFT(tmp, field), field) = RB_BLACK;\ -				RB_ROTATE_RIGHT(head, parent, tmp, field);\ -				elm = RB_ROOT(head);			\ -				break;					\ -			}						\ -		}							\ -	}								\ -	if (elm)							\ -		RB_COLOR(elm, field) = RB_BLACK;			\ -}									\ -									\ -attr struct type *							\ -name##_RB_REMOVE(struct name *head, struct type *elm)			\ -{									\ -	struct type *child, *parent, *old = elm;			\ -	int color;							\ -	if (RB_LEFT(elm, field) == NULL)				\ -		child = RB_RIGHT(elm, field);				\ -	else if (RB_RIGHT(elm, field) == NULL)				\ -		child = RB_LEFT(elm, field);				\ -	else {								\ -		struct type *left;					\ -		elm = RB_RIGHT(elm, field);				\ -		while ((left = RB_LEFT(elm, field)))			\ -			elm = left;					\ -		child = RB_RIGHT(elm, field);				\ -		parent = RB_PARENT(elm, field);				\ -		color = RB_COLOR(elm, field);				\ -		if (child)						\ -			RB_PARENT(child, field) = parent;		\ -		if (parent) {						\ -			if (RB_LEFT(parent, field) == elm)		\ -				RB_LEFT(parent, field) = child;		\ -			else						\ -				RB_RIGHT(parent, field) = child;	\ -			RB_AUGMENT(parent);				\ -		} else							\ -			RB_ROOT(head) = child;				\ -		if (RB_PARENT(elm, field) == old)			\ -			parent = elm;					\ -		(elm)->field = (old)->field;				\ -		if (RB_PARENT(old, field)) {				\ -			if (RB_LEFT(RB_PARENT(old, field), field) == old)\ -				RB_LEFT(RB_PARENT(old, field), field) = elm;\ -			else						\ -				RB_RIGHT(RB_PARENT(old, field), field) = elm;\ -			RB_AUGMENT(RB_PARENT(old, field));		\ -		} else							\ -			RB_ROOT(head) = elm;				\ -		RB_PARENT(RB_LEFT(old, field), field) = elm;		\ -		if (RB_RIGHT(old, field))				\ -			RB_PARENT(RB_RIGHT(old, field), field) = elm;	\ -		if (parent) {						\ -			left = parent;					\ -			do {						\ -				RB_AUGMENT(left);			\ -			} while ((left = RB_PARENT(left, field)));	\ -		}							\ -		goto color;						\ -	}								\ -	parent = RB_PARENT(elm, field);					\ -	color = RB_COLOR(elm, field);					\ -	if (child)							\ -		RB_PARENT(child, field) = parent;			\ -	if (parent) {							\ -		if (RB_LEFT(parent, field) == elm)			\ -			RB_LEFT(parent, field) = child;			\ -		else							\ -			RB_RIGHT(parent, field) = child;		\ -		RB_AUGMENT(parent);					\ -	} else								\ -		RB_ROOT(head) = child;					\ -color:									\ -	if (color == RB_BLACK)						\ -		name##_RB_REMOVE_COLOR(head, parent, child);		\ -	return (old);							\ -}									\ -									\ -/* Inserts a node into the RB tree */					\ -attr struct type *							\ -name##_RB_INSERT(struct name *head, struct type *elm)			\ -{									\ -	struct type *tmp;						\ -	struct type *parent = NULL;					\ -	int comp = 0;							\ -	tmp = RB_ROOT(head);						\ -	while (tmp) {							\ -		parent = tmp;						\ -		comp = (cmp)(elm, parent);				\ -		if (comp < 0)						\ -			tmp = RB_LEFT(tmp, field);			\ -		else if (comp > 0)					\ -			tmp = RB_RIGHT(tmp, field);			\ -		else							\ -			return (tmp);					\ -	}								\ -	RB_SET(elm, parent, field);					\ -	if (parent != NULL) {						\ -		if (comp < 0)						\ -			RB_LEFT(parent, field) = elm;			\ -		else							\ -			RB_RIGHT(parent, field) = elm;			\ -		RB_AUGMENT(parent);					\ -	} else								\ -		RB_ROOT(head) = elm;					\ -	name##_RB_INSERT_COLOR(head, elm);				\ -	return (NULL);							\ -}									\ -									\ -/* Finds the node with the same key as elm */				\ -attr struct type *							\ -name##_RB_FIND(struct name *head, struct type *elm)			\ -{									\ -	struct type *tmp = RB_ROOT(head);				\ -	int comp;							\ -	while (tmp) {							\ -		comp = cmp(elm, tmp);					\ -		if (comp < 0)						\ -			tmp = RB_LEFT(tmp, field);			\ -		else if (comp > 0)					\ -			tmp = RB_RIGHT(tmp, field);			\ -		else							\ -			return (tmp);					\ -	}								\ -	return (NULL);							\ -}									\ -									\ -/* Finds the first node greater than or equal to the search key */	\ -attr struct type *							\ -name##_RB_NFIND(struct name *head, struct type *elm)			\ -{									\ -	struct type *tmp = RB_ROOT(head);				\ -	struct type *res = NULL;					\ -	int comp;							\ -	while (tmp) {							\ -		comp = cmp(elm, tmp);					\ -		if (comp < 0) {						\ -			res = tmp;					\ -			tmp = RB_LEFT(tmp, field);			\ -		}							\ -		else if (comp > 0)					\ -			tmp = RB_RIGHT(tmp, field);			\ -		else							\ -			return (tmp);					\ -	}								\ -	return (res);							\ -}									\ -									\ -/* ARGSUSED */								\ -attr struct type *							\ -name##_RB_NEXT(struct type *elm)					\ -{									\ -	if (RB_RIGHT(elm, field)) {					\ -		elm = RB_RIGHT(elm, field);				\ -		while (RB_LEFT(elm, field))				\ -			elm = RB_LEFT(elm, field);			\ -	} else {							\ -		if (RB_PARENT(elm, field) &&				\ -		    (elm == RB_LEFT(RB_PARENT(elm, field), field)))	\ -			elm = RB_PARENT(elm, field);			\ -		else {							\ -			while (RB_PARENT(elm, field) &&			\ -			    (elm == RB_RIGHT(RB_PARENT(elm, field), field)))\ -				elm = RB_PARENT(elm, field);		\ -			elm = RB_PARENT(elm, field);			\ -		}							\ -	}								\ -	return (elm);							\ -}									\ -									\ -/* ARGSUSED */								\ -attr struct type *							\ -name##_RB_PREV(struct type *elm)					\ -{									\ -	if (RB_LEFT(elm, field)) {					\ -		elm = RB_LEFT(elm, field);				\ -		while (RB_RIGHT(elm, field))				\ -			elm = RB_RIGHT(elm, field);			\ -	} else {							\ -		if (RB_PARENT(elm, field) &&				\ -		    (elm == RB_RIGHT(RB_PARENT(elm, field), field)))	\ -			elm = RB_PARENT(elm, field);			\ -		else {							\ -			while (RB_PARENT(elm, field) &&			\ -			    (elm == RB_LEFT(RB_PARENT(elm, field), field)))\ -				elm = RB_PARENT(elm, field);		\ -			elm = RB_PARENT(elm, field);			\ -		}							\ -	}								\ -	return (elm);							\ -}									\ -									\ -attr struct type *							\ -name##_RB_MINMAX(struct name *head, int val)				\ -{									\ -	struct type *tmp = RB_ROOT(head);				\ -	struct type *parent = NULL;					\ -	while (tmp) {							\ -		parent = tmp;						\ -		if (val < 0)						\ -			tmp = RB_LEFT(tmp, field);			\ -		else							\ -			tmp = RB_RIGHT(tmp, field);			\ -	}								\ -	return (parent);						\ -} +#define RB_GENERATE(name, type, field, cmp)                                    \ +	RB_GENERATE_INTERNAL(name, type, field, cmp, ) +#define RB_GENERATE_STATIC(name, type, field, cmp)                             \ +	RB_GENERATE_INTERNAL(name, type, field, cmp,                           \ +			     __attribute__((__unused__)) static) +#define RB_GENERATE_INTERNAL(name, type, field, cmp, attr)                     \ +	attr void name##_RB_INSERT_COLOR(struct name *head, struct type *elm)  \ +	{                                                                      \ +		struct type *parent, *gparent, *tmp;                           \ +		while ((parent = RB_PARENT(elm, field))                        \ +		       && RB_COLOR(parent, field) == RB_RED) {                 \ +			gparent = RB_PARENT(parent, field);                    \ +			if (parent == RB_LEFT(gparent, field)) {               \ +				tmp = RB_RIGHT(gparent, field);                \ +				if (tmp && RB_COLOR(tmp, field) == RB_RED) {   \ +					RB_COLOR(tmp, field) = RB_BLACK;       \ +					RB_SET_BLACKRED(parent, gparent,       \ +							field);                \ +					elm = gparent;                         \ +					continue;                              \ +				}                                              \ +				if (RB_RIGHT(parent, field) == elm) {          \ +					RB_ROTATE_LEFT(head, parent, tmp,      \ +						       field);                 \ +					tmp = parent;                          \ +					parent = elm;                          \ +					elm = tmp;                             \ +				}                                              \ +				RB_SET_BLACKRED(parent, gparent, field);       \ +				RB_ROTATE_RIGHT(head, gparent, tmp, field);    \ +			} else {                                               \ +				tmp = RB_LEFT(gparent, field);                 \ +				if (tmp && RB_COLOR(tmp, field) == RB_RED) {   \ +					RB_COLOR(tmp, field) = RB_BLACK;       \ +					RB_SET_BLACKRED(parent, gparent,       \ +							field);                \ +					elm = gparent;                         \ +					continue;                              \ +				}                                              \ +				if (RB_LEFT(parent, field) == elm) {           \ +					RB_ROTATE_RIGHT(head, parent, tmp,     \ +							field);                \ +					tmp = parent;                          \ +					parent = elm;                          \ +					elm = tmp;                             \ +				}                                              \ +				RB_SET_BLACKRED(parent, gparent, field);       \ +				RB_ROTATE_LEFT(head, gparent, tmp, field);     \ +			}                                                      \ +		}                                                              \ +		RB_COLOR(head->rbh_root, field) = RB_BLACK;                    \ +	}                                                                      \ +                                                                               \ +	attr void name##_RB_REMOVE_COLOR(                                      \ +		struct name *head, struct type *parent, struct type *elm)      \ +	{                                                                      \ +		struct type *tmp;                                              \ +		while ((elm == NULL || RB_COLOR(elm, field) == RB_BLACK)       \ +		       && elm != RB_ROOT(head)) {                              \ +			if (RB_LEFT(parent, field) == elm) {                   \ +				tmp = RB_RIGHT(parent, field);                 \ +				if (RB_COLOR(tmp, field) == RB_RED) {          \ +					RB_SET_BLACKRED(tmp, parent, field);   \ +					RB_ROTATE_LEFT(head, parent, tmp,      \ +						       field);                 \ +					tmp = RB_RIGHT(parent, field);         \ +				}                                              \ +				if ((RB_LEFT(tmp, field) == NULL               \ +				     || RB_COLOR(RB_LEFT(tmp, field), field)   \ +						== RB_BLACK)                   \ +				    && (RB_RIGHT(tmp, field) == NULL           \ +					|| RB_COLOR(RB_RIGHT(tmp, field),      \ +						    field)                     \ +						   == RB_BLACK)) {             \ +					RB_COLOR(tmp, field) = RB_RED;         \ +					elm = parent;                          \ +					parent = RB_PARENT(elm, field);        \ +				} else {                                       \ +					if (RB_RIGHT(tmp, field) == NULL       \ +					    || RB_COLOR(RB_RIGHT(tmp, field),  \ +							field)                 \ +						       == RB_BLACK) {          \ +						struct type *oleft;            \ +						if ((oleft = RB_LEFT(tmp,      \ +								     field)))  \ +							RB_COLOR(oleft,        \ +								 field) =      \ +								RB_BLACK;      \ +						RB_COLOR(tmp, field) = RB_RED; \ +						RB_ROTATE_RIGHT(head, tmp,     \ +								oleft, field); \ +						tmp = RB_RIGHT(parent, field); \ +					}                                      \ +					RB_COLOR(tmp, field) =                 \ +						RB_COLOR(parent, field);       \ +					RB_COLOR(parent, field) = RB_BLACK;    \ +					if (RB_RIGHT(tmp, field))              \ +						RB_COLOR(RB_RIGHT(tmp, field), \ +							 field) = RB_BLACK;    \ +					RB_ROTATE_LEFT(head, parent, tmp,      \ +						       field);                 \ +					elm = RB_ROOT(head);                   \ +					break;                                 \ +				}                                              \ +			} else {                                               \ +				tmp = RB_LEFT(parent, field);                  \ +				if (RB_COLOR(tmp, field) == RB_RED) {          \ +					RB_SET_BLACKRED(tmp, parent, field);   \ +					RB_ROTATE_RIGHT(head, parent, tmp,     \ +							field);                \ +					tmp = RB_LEFT(parent, field);          \ +				}                                              \ +				if ((RB_LEFT(tmp, field) == NULL               \ +				     || RB_COLOR(RB_LEFT(tmp, field), field)   \ +						== RB_BLACK)                   \ +				    && (RB_RIGHT(tmp, field) == NULL           \ +					|| RB_COLOR(RB_RIGHT(tmp, field),      \ +						    field)                     \ +						   == RB_BLACK)) {             \ +					RB_COLOR(tmp, field) = RB_RED;         \ +					elm = parent;                          \ +					parent = RB_PARENT(elm, field);        \ +				} else {                                       \ +					if (RB_LEFT(tmp, field) == NULL        \ +					    || RB_COLOR(RB_LEFT(tmp, field),   \ +							field)                 \ +						       == RB_BLACK) {          \ +						struct type *oright;           \ +						if ((oright = RB_RIGHT(        \ +							     tmp, field)))     \ +							RB_COLOR(oright,       \ +								 field) =      \ +								RB_BLACK;      \ +						RB_COLOR(tmp, field) = RB_RED; \ +						RB_ROTATE_LEFT(head, tmp,      \ +							       oright, field); \ +						tmp = RB_LEFT(parent, field);  \ +					}                                      \ +					RB_COLOR(tmp, field) =                 \ +						RB_COLOR(parent, field);       \ +					RB_COLOR(parent, field) = RB_BLACK;    \ +					if (RB_LEFT(tmp, field))               \ +						RB_COLOR(RB_LEFT(tmp, field),  \ +							 field) = RB_BLACK;    \ +					RB_ROTATE_RIGHT(head, parent, tmp,     \ +							field);                \ +					elm = RB_ROOT(head);                   \ +					break;                                 \ +				}                                              \ +			}                                                      \ +		}                                                              \ +		if (elm)                                                       \ +			RB_COLOR(elm, field) = RB_BLACK;                       \ +	}                                                                      \ +                                                                               \ +	attr struct type *name##_RB_REMOVE(struct name *head,                  \ +					   struct type *elm)                   \ +	{                                                                      \ +		struct type *child, *parent, *old = elm;                       \ +		int color;                                                     \ +		if (RB_LEFT(elm, field) == NULL)                               \ +			child = RB_RIGHT(elm, field);                          \ +		else if (RB_RIGHT(elm, field) == NULL)                         \ +			child = RB_LEFT(elm, field);                           \ +		else {                                                         \ +			struct type *left;                                     \ +			elm = RB_RIGHT(elm, field);                            \ +			while ((left = RB_LEFT(elm, field)))                   \ +				elm = left;                                    \ +			child = RB_RIGHT(elm, field);                          \ +			parent = RB_PARENT(elm, field);                        \ +			color = RB_COLOR(elm, field);                          \ +			if (child)                                             \ +				RB_PARENT(child, field) = parent;              \ +			if (parent) {                                          \ +				if (RB_LEFT(parent, field) == elm)             \ +					RB_LEFT(parent, field) = child;        \ +				else                                           \ +					RB_RIGHT(parent, field) = child;       \ +				RB_AUGMENT(parent);                            \ +			} else                                                 \ +				RB_ROOT(head) = child;                         \ +			if (RB_PARENT(elm, field) == old)                      \ +				parent = elm;                                  \ +			(elm)->field = (old)->field;                           \ +			if (RB_PARENT(old, field)) {                           \ +				if (RB_LEFT(RB_PARENT(old, field), field)      \ +				    == old)                                    \ +					RB_LEFT(RB_PARENT(old, field),         \ +						field) = elm;                  \ +				else                                           \ +					RB_RIGHT(RB_PARENT(old, field),        \ +						 field) = elm;                 \ +				RB_AUGMENT(RB_PARENT(old, field));             \ +			} else                                                 \ +				RB_ROOT(head) = elm;                           \ +			RB_PARENT(RB_LEFT(old, field), field) = elm;           \ +			if (RB_RIGHT(old, field))                              \ +				RB_PARENT(RB_RIGHT(old, field), field) = elm;  \ +			if (parent) {                                          \ +				left = parent;                                 \ +				do {                                           \ +					RB_AUGMENT(left);                      \ +				} while ((left = RB_PARENT(left, field)));     \ +			}                                                      \ +			goto color;                                            \ +		}                                                              \ +		parent = RB_PARENT(elm, field);                                \ +		color = RB_COLOR(elm, field);                                  \ +		if (child)                                                     \ +			RB_PARENT(child, field) = parent;                      \ +		if (parent) {                                                  \ +			if (RB_LEFT(parent, field) == elm)                     \ +				RB_LEFT(parent, field) = child;                \ +			else                                                   \ +				RB_RIGHT(parent, field) = child;               \ +			RB_AUGMENT(parent);                                    \ +		} else                                                         \ +			RB_ROOT(head) = child;                                 \ +	color:                                                                 \ +		if (color == RB_BLACK)                                         \ +			name##_RB_REMOVE_COLOR(head, parent, child);           \ +		return (old);                                                  \ +	}                                                                      \ +                                                                               \ +	/* Inserts a node into the RB tree */                                  \ +	attr struct type *name##_RB_INSERT(struct name *head,                  \ +					   struct type *elm)                   \ +	{                                                                      \ +		struct type *tmp;                                              \ +		struct type *parent = NULL;                                    \ +		int comp = 0;                                                  \ +		tmp = RB_ROOT(head);                                           \ +		while (tmp) {                                                  \ +			parent = tmp;                                          \ +			comp = (cmp)(elm, parent);                             \ +			if (comp < 0)                                          \ +				tmp = RB_LEFT(tmp, field);                     \ +			else if (comp > 0)                                     \ +				tmp = RB_RIGHT(tmp, field);                    \ +			else                                                   \ +				return (tmp);                                  \ +		}                                                              \ +		RB_SET(elm, parent, field);                                    \ +		if (parent != NULL) {                                          \ +			if (comp < 0)                                          \ +				RB_LEFT(parent, field) = elm;                  \ +			else                                                   \ +				RB_RIGHT(parent, field) = elm;                 \ +			RB_AUGMENT(parent);                                    \ +		} else                                                         \ +			RB_ROOT(head) = elm;                                   \ +		name##_RB_INSERT_COLOR(head, elm);                             \ +		return (NULL);                                                 \ +	}                                                                      \ +                                                                               \ +	/* Finds the node with the same key as elm */                          \ +	attr struct type *name##_RB_FIND(struct name *head, struct type *elm)  \ +	{                                                                      \ +		struct type *tmp = RB_ROOT(head);                              \ +		int comp;                                                      \ +		while (tmp) {                                                  \ +			comp = cmp(elm, tmp);                                  \ +			if (comp < 0)                                          \ +				tmp = RB_LEFT(tmp, field);                     \ +			else if (comp > 0)                                     \ +				tmp = RB_RIGHT(tmp, field);                    \ +			else                                                   \ +				return (tmp);                                  \ +		}                                                              \ +		return (NULL);                                                 \ +	}                                                                      \ +                                                                               \ +	/* Finds the first node greater than or equal to the search key */     \ +	attr struct type *name##_RB_NFIND(struct name *head, struct type *elm) \ +	{                                                                      \ +		struct type *tmp = RB_ROOT(head);                              \ +		struct type *res = NULL;                                       \ +		int comp;                                                      \ +		while (tmp) {                                                  \ +			comp = cmp(elm, tmp);                                  \ +			if (comp < 0) {                                        \ +				res = tmp;                                     \ +				tmp = RB_LEFT(tmp, field);                     \ +			} else if (comp > 0)                                   \ +				tmp = RB_RIGHT(tmp, field);                    \ +			else                                                   \ +				return (tmp);                                  \ +		}                                                              \ +		return (res);                                                  \ +	}                                                                      \ +                                                                               \ +	/* ARGSUSED */                                                         \ +	attr struct type *name##_RB_NEXT(struct type *elm)                     \ +	{                                                                      \ +		if (RB_RIGHT(elm, field)) {                                    \ +			elm = RB_RIGHT(elm, field);                            \ +			while (RB_LEFT(elm, field))                            \ +				elm = RB_LEFT(elm, field);                     \ +		} else {                                                       \ +			if (RB_PARENT(elm, field)                              \ +			    && (elm == RB_LEFT(RB_PARENT(elm, field), field))) \ +				elm = RB_PARENT(elm, field);                   \ +			else {                                                 \ +				while (RB_PARENT(elm, field)                   \ +				       && (elm                                 \ +					   == RB_RIGHT(RB_PARENT(elm, field),  \ +						       field)))                \ +					elm = RB_PARENT(elm, field);           \ +				elm = RB_PARENT(elm, field);                   \ +			}                                                      \ +		}                                                              \ +		return (elm);                                                  \ +	}                                                                      \ +                                                                               \ +	/* ARGSUSED */                                                         \ +	attr struct type *name##_RB_PREV(struct type *elm)                     \ +	{                                                                      \ +		if (RB_LEFT(elm, field)) {                                     \ +			elm = RB_LEFT(elm, field);                             \ +			while (RB_RIGHT(elm, field))                           \ +				elm = RB_RIGHT(elm, field);                    \ +		} else {                                                       \ +			if (RB_PARENT(elm, field)                              \ +			    && (elm                                            \ +				== RB_RIGHT(RB_PARENT(elm, field), field)))    \ +				elm = RB_PARENT(elm, field);                   \ +			else {                                                 \ +				while (RB_PARENT(elm, field)                   \ +				       && (elm                                 \ +					   == RB_LEFT(RB_PARENT(elm, field),   \ +						      field)))                 \ +					elm = RB_PARENT(elm, field);           \ +				elm = RB_PARENT(elm, field);                   \ +			}                                                      \ +		}                                                              \ +		return (elm);                                                  \ +	}                                                                      \ +                                                                               \ +	attr struct type *name##_RB_MINMAX(struct name *head, int val)         \ +	{                                                                      \ +		struct type *tmp = RB_ROOT(head);                              \ +		struct type *parent = NULL;                                    \ +		while (tmp) {                                                  \ +			parent = tmp;                                          \ +			if (val < 0)                                           \ +				tmp = RB_LEFT(tmp, field);                     \ +			else                                                   \ +				tmp = RB_RIGHT(tmp, field);                    \ +		}                                                              \ +		return (parent);                                               \ +	}  #define RB_NEGINF	-1  #define RB_INF	1 @@ -725,24 +793,18 @@ name##_RB_MINMAX(struct name *head, int val)				\  #define RB_MIN(name, x)		name##_RB_MINMAX(x, RB_NEGINF)  #define RB_MAX(name, x)		name##_RB_MINMAX(x, RB_INF) -#define RB_FOREACH(x, name, head)					\ -	for ((x) = RB_MIN(name, head);					\ -	     (x) != NULL;						\ -	     (x) = name##_RB_NEXT(x)) +#define RB_FOREACH(x, name, head)                                              \ +	for ((x) = RB_MIN(name, head); (x) != NULL; (x) = name##_RB_NEXT(x)) -#define RB_FOREACH_SAFE(x, name, head, y)				\ -	for ((x) = RB_MIN(name, head);					\ -	    ((x) != NULL) && ((y) = name##_RB_NEXT(x), 1);		\ -	     (x) = (y)) +#define RB_FOREACH_SAFE(x, name, head, y)                                      \ +	for ((x) = RB_MIN(name, head);                                         \ +	     ((x) != NULL) && ((y) = name##_RB_NEXT(x), 1); (x) = (y)) -#define RB_FOREACH_REVERSE(x, name, head)				\ -	for ((x) = RB_MAX(name, head);					\ -	     (x) != NULL;						\ -	     (x) = name##_RB_PREV(x)) +#define RB_FOREACH_REVERSE(x, name, head)                                      \ +	for ((x) = RB_MAX(name, head); (x) != NULL; (x) = name##_RB_PREV(x)) -#define RB_FOREACH_REVERSE_SAFE(x, name, head, y)			\ -	for ((x) = RB_MAX(name, head);					\ -	    ((x) != NULL) && ((y) = name##_RB_PREV(x), 1);		\ -	     (x) = (y)) +#define RB_FOREACH_REVERSE_SAFE(x, name, head, y)                              \ +	for ((x) = RB_MAX(name, head);                                         \ +	     ((x) != NULL) && ((y) = name##_RB_PREV(x), 1); (x) = (y)) -#endif	/* _SYS_TREE_H_ */ +#endif /* _SYS_TREE_H_ */ diff --git a/lib/pid_output.c b/lib/pid_output.c index ba1f37476e..a43c05c430 100644 --- a/lib/pid_output.c +++ b/lib/pid_output.c @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -28,53 +28,50 @@  #define PIDFILE_MASK 0644 -pid_t -pid_output (const char *path) +pid_t pid_output(const char *path)  { -  int tmp; -  int fd; -  pid_t pid; -  char buf[16]; -  struct flock lock;   -  mode_t oldumask; +	int tmp; +	int fd; +	pid_t pid; +	char buf[16]; +	struct flock lock; +	mode_t oldumask; -  pid = getpid (); +	pid = getpid(); -  oldumask = umask(0777 & ~PIDFILE_MASK); -  fd = open (path, O_RDWR | O_CREAT, PIDFILE_MASK); -  if (fd < 0) -    { -      zlog_err("Can't create pid lock file %s (%s), exiting", -	       path, safe_strerror(errno)); -      umask(oldumask); -      exit(1); -    } -  else -    { -      size_t pidsize; +	oldumask = umask(0777 & ~PIDFILE_MASK); +	fd = open(path, O_RDWR | O_CREAT, PIDFILE_MASK); +	if (fd < 0) { +		zlog_err("Can't create pid lock file %s (%s), exiting", path, +			 safe_strerror(errno)); +		umask(oldumask); +		exit(1); +	} else { +		size_t pidsize; -      umask(oldumask); -      memset (&lock, 0, sizeof(lock)); +		umask(oldumask); +		memset(&lock, 0, sizeof(lock)); -      set_cloexec(fd); +		set_cloexec(fd); -      lock.l_type = F_WRLCK; -      lock.l_whence = SEEK_SET; +		lock.l_type = F_WRLCK; +		lock.l_whence = SEEK_SET; -      if (fcntl(fd, F_SETLK, &lock) < 0) -        { -          zlog_err("Could not lock pid_file %s, exiting", path); -          exit(1); -        } +		if (fcntl(fd, F_SETLK, &lock) < 0) { +			zlog_err("Could not lock pid_file %s, exiting", path); +			exit(1); +		} -      sprintf (buf, "%d\n", (int) pid); -      pidsize = strlen(buf); -      if ((tmp = write (fd, buf, pidsize)) != (int)pidsize) -        zlog_err("Could not write pid %d to pid_file %s, rc was %d: %s", -	         (int)pid,path,tmp,safe_strerror(errno)); -      else if (ftruncate(fd, pidsize) < 0) -        zlog_err("Could not truncate pid_file %s to %u bytes: %s", -	         path,(u_int)pidsize,safe_strerror(errno)); -    } -  return pid; +		sprintf(buf, "%d\n", (int)pid); +		pidsize = strlen(buf); +		if ((tmp = write(fd, buf, pidsize)) != (int)pidsize) +			zlog_err( +				"Could not write pid %d to pid_file %s, rc was %d: %s", +				(int)pid, path, tmp, safe_strerror(errno)); +		else if (ftruncate(fd, pidsize) < 0) +			zlog_err( +				"Could not truncate pid_file %s to %u bytes: %s", +				path, (u_int)pidsize, safe_strerror(errno)); +	} +	return pid;  } diff --git a/lib/plist.c b/lib/plist.c index 3714969696..2af13244ff 100644 --- a/lib/plist.c +++ b/lib/plist.c @@ -33,10 +33,10 @@  #include "plist_int.h" -DEFINE_MTYPE_STATIC(LIB, PREFIX_LIST,       "Prefix List") -DEFINE_MTYPE_STATIC(LIB, MPREFIX_LIST_STR,  "Prefix List Str") +DEFINE_MTYPE_STATIC(LIB, PREFIX_LIST, "Prefix List") +DEFINE_MTYPE_STATIC(LIB, MPREFIX_LIST_STR, "Prefix List Str")  DEFINE_MTYPE_STATIC(LIB, PREFIX_LIST_ENTRY, "Prefix List Entry") -DEFINE_MTYPE_STATIC(LIB, PREFIX_LIST_TRIE,  "Prefix List Trie Table") +DEFINE_MTYPE_STATIC(LIB, PREFIX_LIST_TRIE, "Prefix List Trie Table")  /* not currently changeable, code assumes bytes further down */  #define PLC_BITS	8 @@ -59,1358 +59,1247 @@ struct pltrie_table {  };  /* List of struct prefix_list. */ -struct prefix_list_list -{ -  struct prefix_list *head; -  struct prefix_list *tail; +struct prefix_list_list { +	struct prefix_list *head; +	struct prefix_list *tail;  };  /* Master structure of prefix_list. */ -struct prefix_master -{ -  /* List of prefix_list which name is number. */ -  struct prefix_list_list num; +struct prefix_master { +	/* List of prefix_list which name is number. */ +	struct prefix_list_list num; -  /* List of prefix_list which name is string. */ -  struct prefix_list_list str; +	/* List of prefix_list which name is string. */ +	struct prefix_list_list str; -  /* Whether sequential number is used. */ -  int seqnum; +	/* Whether sequential number is used. */ +	int seqnum; -  /* The latest update. */ -  struct prefix_list *recent; +	/* The latest update. */ +	struct prefix_list *recent; -  /* Hook function which is executed when new prefix_list is added. */ -  void (*add_hook) (struct prefix_list *); +	/* Hook function which is executed when new prefix_list is added. */ +	void (*add_hook)(struct prefix_list *); -  /* Hook function which is executed when prefix_list is deleted. */ -  void (*delete_hook) (struct prefix_list *); +	/* Hook function which is executed when prefix_list is deleted. */ +	void (*delete_hook)(struct prefix_list *); -  /* number of bytes that have a trie level */ -  size_t trie_depth; +	/* number of bytes that have a trie level */ +	size_t trie_depth;  };  /* Static structure of IPv4 prefix_list's master. */ -static struct prefix_master prefix_master_ipv4 =  -{  -  {NULL, NULL}, -  {NULL, NULL}, -  1, -  NULL, -  NULL, -  NULL, -  PLC_MAXLEVELV4, +static struct prefix_master prefix_master_ipv4 = { +	{NULL, NULL}, {NULL, NULL}, 1, NULL, NULL, NULL, PLC_MAXLEVELV4,  };  /* Static structure of IPv6 prefix-list's master. */ -static struct prefix_master prefix_master_ipv6 =  -{  -  {NULL, NULL}, -  {NULL, NULL}, -  1, -  NULL, -  NULL, -  NULL, -  PLC_MAXLEVELV6, +static struct prefix_master prefix_master_ipv6 = { +	{NULL, NULL}, {NULL, NULL}, 1, NULL, NULL, NULL, PLC_MAXLEVELV6,  };  /* Static structure of BGP ORF prefix_list's master. */ -static struct prefix_master prefix_master_orf_v4 = -{ -  {NULL, NULL}, -  {NULL, NULL}, -  1, -  NULL, -  NULL, -  NULL, -  PLC_MAXLEVELV4, +static struct prefix_master prefix_master_orf_v4 = { +	{NULL, NULL}, {NULL, NULL}, 1, NULL, NULL, NULL, PLC_MAXLEVELV4,  };  /* Static structure of BGP ORF prefix_list's master. */ -static struct prefix_master prefix_master_orf_v6 = -{ -  {NULL, NULL}, -  {NULL, NULL}, -  1, -  NULL, -  NULL, -  NULL, -  PLC_MAXLEVELV6, +static struct prefix_master prefix_master_orf_v6 = { +	{NULL, NULL}, {NULL, NULL}, 1, NULL, NULL, NULL, PLC_MAXLEVELV6,  }; -static struct prefix_master * -prefix_master_get (afi_t afi, int orf) +static struct prefix_master *prefix_master_get(afi_t afi, int orf)  { -  if (afi == AFI_IP) -    return orf ? &prefix_master_orf_v4 : &prefix_master_ipv4; -  if (afi == AFI_IP6) -    return orf ? &prefix_master_orf_v6 : &prefix_master_ipv6; -  return NULL; +	if (afi == AFI_IP) +		return orf ? &prefix_master_orf_v4 : &prefix_master_ipv4; +	if (afi == AFI_IP6) +		return orf ? &prefix_master_orf_v6 : &prefix_master_ipv6; +	return NULL;  } -const char *prefix_list_name (struct prefix_list *plist) +const char *prefix_list_name(struct prefix_list *plist)  { -  return plist->name; +	return plist->name;  }  /* Lookup prefix_list from list of prefix_list by name. */ -static struct prefix_list * -prefix_list_lookup_do (afi_t afi, int orf, const char *name) +static struct prefix_list *prefix_list_lookup_do(afi_t afi, int orf, +						 const char *name)  { -  struct prefix_list *plist; -  struct prefix_master *master; +	struct prefix_list *plist; +	struct prefix_master *master; -  if (name == NULL) -    return NULL; +	if (name == NULL) +		return NULL; -  master = prefix_master_get (afi, orf); -  if (master == NULL) -    return NULL; +	master = prefix_master_get(afi, orf); +	if (master == NULL) +		return NULL; -  for (plist = master->num.head; plist; plist = plist->next) -    if (strcmp (plist->name, name) == 0) -      return plist; +	for (plist = master->num.head; plist; plist = plist->next) +		if (strcmp(plist->name, name) == 0) +			return plist; -  for (plist = master->str.head; plist; plist = plist->next) -    if (strcmp (plist->name, name) == 0) -      return plist; +	for (plist = master->str.head; plist; plist = plist->next) +		if (strcmp(plist->name, name) == 0) +			return plist; -  return NULL; +	return NULL;  } -struct prefix_list * -prefix_list_lookup (afi_t afi, const char *name) +struct prefix_list *prefix_list_lookup(afi_t afi, const char *name)  { -  return prefix_list_lookup_do (afi, 0, name); +	return prefix_list_lookup_do(afi, 0, name);  } -struct prefix_list * -prefix_bgp_orf_lookup (afi_t afi, const char *name) +struct prefix_list *prefix_bgp_orf_lookup(afi_t afi, const char *name)  { -  return prefix_list_lookup_do (afi, 1, name); +	return prefix_list_lookup_do(afi, 1, name);  } -static struct prefix_list * -prefix_list_new (void) +static struct prefix_list *prefix_list_new(void)  { -  struct prefix_list *new; +	struct prefix_list *new; -  new = XCALLOC (MTYPE_PREFIX_LIST, sizeof (struct prefix_list)); -  return new; +	new = XCALLOC(MTYPE_PREFIX_LIST, sizeof(struct prefix_list)); +	return new;  } -static void -prefix_list_free (struct prefix_list *plist) +static void prefix_list_free(struct prefix_list *plist)  { -  XFREE (MTYPE_PREFIX_LIST, plist); +	XFREE(MTYPE_PREFIX_LIST, plist);  } -static struct prefix_list_entry * -prefix_list_entry_new (void) +static struct prefix_list_entry *prefix_list_entry_new(void)  { -  struct prefix_list_entry *new; +	struct prefix_list_entry *new; -  new = XCALLOC (MTYPE_PREFIX_LIST_ENTRY, sizeof (struct prefix_list_entry)); -  return new; +	new = XCALLOC(MTYPE_PREFIX_LIST_ENTRY, +		      sizeof(struct prefix_list_entry)); +	return new;  } -static void -prefix_list_entry_free (struct prefix_list_entry *pentry) +static void prefix_list_entry_free(struct prefix_list_entry *pentry)  { -  XFREE (MTYPE_PREFIX_LIST_ENTRY, pentry); +	XFREE(MTYPE_PREFIX_LIST_ENTRY, pentry);  }  /* Insert new prefix list to list of prefix_list.  Each prefix_list     is sorted by the name. */ -static struct prefix_list * -prefix_list_insert (afi_t afi, int orf, const char *name) -{ -  unsigned int i; -  long number; -  struct prefix_list *plist; -  struct prefix_list *point; -  struct prefix_list_list *list; -  struct prefix_master *master; - -  master = prefix_master_get (afi, orf); -  if (master == NULL) -    return NULL; - -  /* Allocate new prefix_list and copy given name. */ -  plist = prefix_list_new (); -  plist->name = XSTRDUP (MTYPE_MPREFIX_LIST_STR, name); -  plist->master = master; -  plist->trie = XCALLOC (MTYPE_PREFIX_LIST_TRIE, sizeof (struct pltrie_table)); - -  /* If name is made by all digit character.  We treat it as -     number. */ -  for (number = 0, i = 0; i < strlen (name); i++) -    { -      if (isdigit ((int) name[i])) -	number = (number * 10) + (name[i] - '0'); -      else -	break; -    } - -  /* In case of name is all digit character */ -  if (i == strlen (name)) -    { -      plist->type = PREFIX_TYPE_NUMBER; - -      /* Set prefix_list to number list. */ -      list = &master->num; - -      for (point = list->head; point; point = point->next) -	if (atol (point->name) >= number) -	  break; -    } -  else -    { -      plist->type = PREFIX_TYPE_STRING; - -      /* Set prefix_list to string list. */ -      list = &master->str; -   -      /* Set point to insertion point. */ -      for (point = list->head; point; point = point->next) -	if (strcmp (point->name, name) >= 0) -	  break; -    } - -  /* In case of this is the first element of master. */ -  if (list->head == NULL) -    { -      list->head = list->tail = plist; -      return plist; -    } - -  /* In case of insertion is made at the tail of access_list. */ -  if (point == NULL) -    { -      plist->prev = list->tail; -      list->tail->next = plist; -      list->tail = plist; -      return plist; -    } - -  /* In case of insertion is made at the head of access_list. */ -  if (point == list->head) -    { -      plist->next = list->head; -      list->head->prev = plist; -      list->head = plist; -      return plist; -    } - -  /* Insertion is made at middle of the access_list. */ -  plist->next = point; -  plist->prev = point->prev; - -  if (point->prev) -    point->prev->next = plist; -  point->prev = plist; - -  return plist; -} - -static struct prefix_list * -prefix_list_get (afi_t afi, int orf, const char *name) -{ -  struct prefix_list *plist; - -  plist = prefix_list_lookup_do (afi, orf, name); - -  if (plist == NULL) -    plist = prefix_list_insert (afi, orf, name); -  return plist; -} - -static void prefix_list_trie_del (struct prefix_list *plist, -                                  struct prefix_list_entry *pentry); +static struct prefix_list *prefix_list_insert(afi_t afi, int orf, +					      const char *name) +{ +	unsigned int i; +	long number; +	struct prefix_list *plist; +	struct prefix_list *point; +	struct prefix_list_list *list; +	struct prefix_master *master; + +	master = prefix_master_get(afi, orf); +	if (master == NULL) +		return NULL; + +	/* Allocate new prefix_list and copy given name. */ +	plist = prefix_list_new(); +	plist->name = XSTRDUP(MTYPE_MPREFIX_LIST_STR, name); +	plist->master = master; +	plist->trie = +		XCALLOC(MTYPE_PREFIX_LIST_TRIE, sizeof(struct pltrie_table)); + +	/* If name is made by all digit character.  We treat it as +	   number. */ +	for (number = 0, i = 0; i < strlen(name); i++) { +		if (isdigit((int)name[i])) +			number = (number * 10) + (name[i] - '0'); +		else +			break; +	} -/* Delete prefix-list from prefix_list_master and free it. */ -static void -prefix_list_delete (struct prefix_list *plist) +	/* In case of name is all digit character */ +	if (i == strlen(name)) { +		plist->type = PREFIX_TYPE_NUMBER; + +		/* Set prefix_list to number list. */ +		list = &master->num; + +		for (point = list->head; point; point = point->next) +			if (atol(point->name) >= number) +				break; +	} else { +		plist->type = PREFIX_TYPE_STRING; + +		/* Set prefix_list to string list. */ +		list = &master->str; + +		/* Set point to insertion point. */ +		for (point = list->head; point; point = point->next) +			if (strcmp(point->name, name) >= 0) +				break; +	} + +	/* In case of this is the first element of master. */ +	if (list->head == NULL) { +		list->head = list->tail = plist; +		return plist; +	} + +	/* In case of insertion is made at the tail of access_list. */ +	if (point == NULL) { +		plist->prev = list->tail; +		list->tail->next = plist; +		list->tail = plist; +		return plist; +	} + +	/* In case of insertion is made at the head of access_list. */ +	if (point == list->head) { +		plist->next = list->head; +		list->head->prev = plist; +		list->head = plist; +		return plist; +	} + +	/* Insertion is made at middle of the access_list. */ +	plist->next = point; +	plist->prev = point->prev; + +	if (point->prev) +		point->prev->next = plist; +	point->prev = plist; + +	return plist; +} + +static struct prefix_list *prefix_list_get(afi_t afi, int orf, const char *name)  { -  struct prefix_list_list *list; -  struct prefix_master *master; -  struct prefix_list_entry *pentry; -  struct prefix_list_entry *next; +	struct prefix_list *plist; -  /* If prefix-list contain prefix_list_entry free all of it. */ -  for (pentry = plist->head; pentry; pentry = next) -    { -      next = pentry->next; -      prefix_list_trie_del (plist, pentry); -      prefix_list_entry_free (pentry); -      plist->count--; -    } +	plist = prefix_list_lookup_do(afi, orf, name); -  master = plist->master; +	if (plist == NULL) +		plist = prefix_list_insert(afi, orf, name); +	return plist; +} + +static void prefix_list_trie_del(struct prefix_list *plist, +				 struct prefix_list_entry *pentry); + +/* Delete prefix-list from prefix_list_master and free it. */ +static void prefix_list_delete(struct prefix_list *plist) +{ +	struct prefix_list_list *list; +	struct prefix_master *master; +	struct prefix_list_entry *pentry; +	struct prefix_list_entry *next; + +	/* If prefix-list contain prefix_list_entry free all of it. */ +	for (pentry = plist->head; pentry; pentry = next) { +		next = pentry->next; +		prefix_list_trie_del(plist, pentry); +		prefix_list_entry_free(pentry); +		plist->count--; +	} -  if (plist->type == PREFIX_TYPE_NUMBER) -    list = &master->num; -  else -    list = &master->str; +	master = plist->master; -  if (plist->next) -    plist->next->prev = plist->prev; -  else -    list->tail = plist->prev; +	if (plist->type == PREFIX_TYPE_NUMBER) +		list = &master->num; +	else +		list = &master->str; -  if (plist->prev) -    plist->prev->next = plist->next; -  else -    list->head = plist->next; +	if (plist->next) +		plist->next->prev = plist->prev; +	else +		list->tail = plist->prev; -  if (plist->desc) -    XFREE (MTYPE_TMP, plist->desc); +	if (plist->prev) +		plist->prev->next = plist->next; +	else +		list->head = plist->next; -  /* Make sure master's recent changed prefix-list information is -     cleared. */ -  master->recent = NULL; +	if (plist->desc) +		XFREE(MTYPE_TMP, plist->desc); -  route_map_notify_dependencies(plist->name, RMAP_EVENT_PLIST_DELETED); +	/* Make sure master's recent changed prefix-list information is +	   cleared. */ +	master->recent = NULL; -  if (master->delete_hook) -    (*master->delete_hook) (plist); +	route_map_notify_dependencies(plist->name, RMAP_EVENT_PLIST_DELETED); -  if (plist->name) -    XFREE (MTYPE_MPREFIX_LIST_STR, plist->name); +	if (master->delete_hook) +		(*master->delete_hook)(plist); -  XFREE (MTYPE_PREFIX_LIST_TRIE, plist->trie); +	if (plist->name) +		XFREE(MTYPE_MPREFIX_LIST_STR, plist->name); -  prefix_list_free (plist); +	XFREE(MTYPE_PREFIX_LIST_TRIE, plist->trie); +	prefix_list_free(plist);  }  static struct prefix_list_entry * -prefix_list_entry_make (struct prefix *prefix, enum prefix_list_type type, -			int seq, int le, int ge, int any) +prefix_list_entry_make(struct prefix *prefix, enum prefix_list_type type, +		       int seq, int le, int ge, int any)  { -  struct prefix_list_entry *pentry; +	struct prefix_list_entry *pentry; -  pentry = prefix_list_entry_new (); +	pentry = prefix_list_entry_new(); -  if (any) -    pentry->any = 1; +	if (any) +		pentry->any = 1; -  prefix_copy (&pentry->prefix, prefix); -  pentry->type = type; -  pentry->seq = seq; -  pentry->le = le; -  pentry->ge = ge; +	prefix_copy(&pentry->prefix, prefix); +	pentry->type = type; +	pentry->seq = seq; +	pentry->le = le; +	pentry->ge = ge; -  return pentry; +	return pentry;  }  /* Add hook function. */ -void -prefix_list_add_hook (void (*func) (struct prefix_list *plist)) +void prefix_list_add_hook(void (*func)(struct prefix_list *plist))  { -  prefix_master_ipv4.add_hook = func; -  prefix_master_ipv6.add_hook = func; +	prefix_master_ipv4.add_hook = func; +	prefix_master_ipv6.add_hook = func;  }  /* Delete hook function. */ -void -prefix_list_delete_hook (void (*func) (struct prefix_list *plist)) +void prefix_list_delete_hook(void (*func)(struct prefix_list *plist))  { -  prefix_master_ipv4.delete_hook = func; -  prefix_master_ipv6.delete_hook = func; +	prefix_master_ipv4.delete_hook = func; +	prefix_master_ipv6.delete_hook = func;  }  /* Calculate new sequential number. */ -static int -prefix_new_seq_get (struct prefix_list *plist) +static int prefix_new_seq_get(struct prefix_list *plist)  { -  int maxseq; -  int newseq; -  struct prefix_list_entry *pentry; +	int maxseq; +	int newseq; +	struct prefix_list_entry *pentry; + +	maxseq = newseq = 0; -  maxseq = newseq = 0; +	for (pentry = plist->head; pentry; pentry = pentry->next) { +		if (maxseq < pentry->seq) +			maxseq = pentry->seq; +	} -  for (pentry = plist->head; pentry; pentry = pentry->next) -    { -      if (maxseq < pentry->seq) -	maxseq = pentry->seq; -    } +	newseq = ((maxseq / 5) * 5) + 5; -  newseq = ((maxseq / 5) * 5) + 5; -   -  return newseq; +	return newseq;  }  /* Return prefix list entry which has same seq number. */ -static struct prefix_list_entry * -prefix_seq_check (struct prefix_list *plist, int seq) +static struct prefix_list_entry *prefix_seq_check(struct prefix_list *plist, +						  int seq)  { -  struct prefix_list_entry *pentry; +	struct prefix_list_entry *pentry; -  for (pentry = plist->head; pentry; pentry = pentry->next) -    if (pentry->seq == seq) -      return pentry; -  return NULL; +	for (pentry = plist->head; pentry; pentry = pentry->next) +		if (pentry->seq == seq) +			return pentry; +	return NULL;  }  static struct prefix_list_entry * -prefix_list_entry_lookup (struct prefix_list *plist, struct prefix *prefix, -			  enum prefix_list_type type, int seq, int le, int ge) +prefix_list_entry_lookup(struct prefix_list *plist, struct prefix *prefix, +			 enum prefix_list_type type, int seq, int le, int ge)  { -  struct prefix_list_entry *pentry; +	struct prefix_list_entry *pentry; -  for (pentry = plist->head; pentry; pentry = pentry->next) -    if (prefix_same (&pentry->prefix, prefix) && pentry->type == type) -      { -	if (seq >= 0 && pentry->seq != seq) -	  continue; +	for (pentry = plist->head; pentry; pentry = pentry->next) +		if (prefix_same(&pentry->prefix, prefix) +		    && pentry->type == type) { +			if (seq >= 0 && pentry->seq != seq) +				continue; -	if (pentry->le != le) -	  continue; -	if (pentry->ge != ge) -	  continue; +			if (pentry->le != le) +				continue; +			if (pentry->ge != ge) +				continue; -	return pentry; -      } +			return pentry; +		} -  return NULL; +	return NULL;  } -static void -trie_walk_affected (size_t validbits, struct pltrie_table *table, uint8_t byte, -                    struct prefix_list_entry *object, -                    void (*fn)(struct prefix_list_entry *object, -                               struct prefix_list_entry **updptr)) +static void trie_walk_affected(size_t validbits, struct pltrie_table *table, +			       uint8_t byte, struct prefix_list_entry *object, +			       void (*fn)(struct prefix_list_entry *object, +					  struct prefix_list_entry **updptr))  { -  uint8_t mask; -  uint16_t bwalk; +	uint8_t mask; +	uint16_t bwalk; -  if (validbits > PLC_BITS) -    { -      fn (object, &table->entries[byte].final_chain); -      return; -    } +	if (validbits > PLC_BITS) { +		fn(object, &table->entries[byte].final_chain); +		return; +	} + +	mask = (1 << (8 - validbits)) - 1; +	for (bwalk = byte & ~mask; bwalk <= byte + mask; bwalk++) { +		fn(object, &table->entries[bwalk].up_chain); +	} +} -  mask = (1 << (8 - validbits)) - 1; -  for (bwalk = byte & ~mask; bwalk <= byte + mask; bwalk++) -    { -      fn (object, &table->entries[bwalk].up_chain); -    } +static void trie_uninstall_fn(struct prefix_list_entry *object, +			      struct prefix_list_entry **updptr) +{ +	for (; *updptr; updptr = &(*updptr)->next_best) +		if (*updptr == object) { +			*updptr = object->next_best; +			break; +		}  } -static void trie_uninstall_fn (struct prefix_list_entry *object, -                               struct prefix_list_entry **updptr) +static int trie_table_empty(struct pltrie_table *table)  { -  for (; *updptr; updptr = &(*updptr)->next_best) -    if (*updptr == object) -      { -        *updptr = object->next_best; -        break; -      } +	size_t i; +	for (i = 0; i < PLC_LEN; i++) +		if (table->entries[i].next_table || table->entries[i].up_chain) +			return 0; +	return 1;  } -static int -trie_table_empty (struct pltrie_table *table) +static void prefix_list_trie_del(struct prefix_list *plist, +				 struct prefix_list_entry *pentry)  { -  size_t i; -  for (i = 0; i < PLC_LEN; i++) -    if (table->entries[i].next_table || table->entries[i].up_chain) -      return 0; -  return 1; +	size_t depth, maxdepth = plist->master->trie_depth; +	uint8_t *bytes = &pentry->prefix.u.prefix; +	size_t validbits = pentry->prefix.prefixlen; +	struct pltrie_table *table, **tables[PLC_MAXLEVEL]; + +	table = plist->trie; +	for (depth = 0; validbits > PLC_BITS && depth < maxdepth - 1; depth++) { +		uint8_t byte = bytes[depth]; +		assert(table->entries[byte].next_table); + +		tables[depth + 1] = &table->entries[byte].next_table; +		table = table->entries[byte].next_table; + +		validbits -= PLC_BITS; +	} + +	trie_walk_affected(validbits, table, bytes[depth], pentry, +			   trie_uninstall_fn); + +	for (; depth > 0; depth--) +		if (trie_table_empty(*tables[depth])) { +			XFREE(MTYPE_PREFIX_LIST_TRIE, *tables[depth]); +			*tables[depth] = NULL; +		}  } -static void -prefix_list_trie_del (struct prefix_list *plist, -		      struct prefix_list_entry *pentry) + +static void prefix_list_entry_delete(struct prefix_list *plist, +				     struct prefix_list_entry *pentry, +				     int update_list)  { -  size_t depth, maxdepth = plist->master->trie_depth; -  uint8_t *bytes = &pentry->prefix.u.prefix; -  size_t validbits = pentry->prefix.prefixlen; -  struct pltrie_table *table, **tables[PLC_MAXLEVEL]; +	if (plist == NULL || pentry == NULL) +		return; + +	prefix_list_trie_del(plist, pentry); -  table = plist->trie; -  for (depth = 0; validbits > PLC_BITS && depth < maxdepth - 1; depth++) -    { -      uint8_t byte = bytes[depth]; -      assert (table->entries[byte].next_table); +	if (pentry->prev) +		pentry->prev->next = pentry->next; +	else +		plist->head = pentry->next; +	if (pentry->next) +		pentry->next->prev = pentry->prev; +	else +		plist->tail = pentry->prev; -      tables[depth + 1] = &table->entries[byte].next_table; -      table = table->entries[byte].next_table; +	prefix_list_entry_free(pentry); -      validbits -= PLC_BITS; -    } +	plist->count--; -  trie_walk_affected (validbits, table, bytes[depth], pentry, trie_uninstall_fn); +	if (update_list) { +		route_map_notify_dependencies(plist->name, +					      RMAP_EVENT_PLIST_DELETED); +		if (plist->master->delete_hook) +			(*plist->master->delete_hook)(plist); -  for (; depth > 0; depth--) -    if (trie_table_empty (*tables[depth])) -      { -        XFREE (MTYPE_PREFIX_LIST_TRIE, *tables[depth]); -        *tables[depth] = NULL; -      } +		if (plist->head == NULL && plist->tail == NULL +		    && plist->desc == NULL) +			prefix_list_delete(plist); +		else +			plist->master->recent = plist; +	}  } +static void trie_install_fn(struct prefix_list_entry *object, +			    struct prefix_list_entry **updptr) +{ +	while (*updptr) { +		if (*updptr == object) +			return; +		if ((*updptr)->prefix.prefixlen < object->prefix.prefixlen) +			break; +		if ((*updptr)->seq > object->seq) +			break; +		updptr = &(*updptr)->next_best; +	} + +	if (!object->next_best) +		object->next_best = *updptr; +	else +		assert(object->next_best == *updptr || !*updptr); + +	*updptr = object; +} -static void -prefix_list_entry_delete (struct prefix_list *plist,  -			  struct prefix_list_entry *pentry, -			  int update_list) +static void prefix_list_trie_add(struct prefix_list *plist, +				 struct prefix_list_entry *pentry)  { -  if (plist == NULL || pentry == NULL) -    return; +	size_t depth = plist->master->trie_depth; +	uint8_t *bytes = &pentry->prefix.u.prefix; +	size_t validbits = pentry->prefix.prefixlen; +	struct pltrie_table *table; -  prefix_list_trie_del (plist, pentry); +	table = plist->trie; +	while (validbits > PLC_BITS && depth > 1) { +		if (!table->entries[*bytes].next_table) +			table->entries[*bytes].next_table = +				XCALLOC(MTYPE_PREFIX_LIST_TRIE, +					sizeof(struct pltrie_table)); +		table = table->entries[*bytes].next_table; +		bytes++; +		depth--; +		validbits -= PLC_BITS; +	} + +	trie_walk_affected(validbits, table, *bytes, pentry, trie_install_fn); +} + +static void prefix_list_entry_add(struct prefix_list *plist, +				  struct prefix_list_entry *pentry) +{ +	struct prefix_list_entry *replace; +	struct prefix_list_entry *point; -  if (pentry->prev) -    pentry->prev->next = pentry->next; -  else -    plist->head = pentry->next; -  if (pentry->next) -    pentry->next->prev = pentry->prev; -  else -    plist->tail = pentry->prev; +	/* Automatic asignment of seq no. */ +	if (pentry->seq == -1) +		pentry->seq = prefix_new_seq_get(plist); + +	if (plist->tail && pentry->seq > plist->tail->seq) +		point = NULL; +	else { +		/* Is there any same seq prefix list entry? */ +		replace = prefix_seq_check(plist, pentry->seq); +		if (replace) +			prefix_list_entry_delete(plist, replace, 0); + +		/* Check insert point. */ +		for (point = plist->head; point; point = point->next) +			if (point->seq >= pentry->seq) +				break; +	} + +	/* In case of this is the first element of the list. */ +	pentry->next = point; + +	if (point) { +		if (point->prev) +			point->prev->next = pentry; +		else +			plist->head = pentry; + +		pentry->prev = point->prev; +		point->prev = pentry; +	} else { +		if (plist->tail) +			plist->tail->next = pentry; +		else +			plist->head = pentry; + +		pentry->prev = plist->tail; +		plist->tail = pentry; +	} -  prefix_list_entry_free (pentry); +	prefix_list_trie_add(plist, pentry); -  plist->count--; +	/* Increment count. */ +	plist->count++; -  if (update_list) -    { -      route_map_notify_dependencies(plist->name, RMAP_EVENT_PLIST_DELETED); -      if (plist->master->delete_hook) -	(*plist->master->delete_hook) (plist); +	/* Run hook function. */ +	if (plist->master->add_hook) +		(*plist->master->add_hook)(plist); -      if (plist->head == NULL && plist->tail == NULL && plist->desc == NULL) -	prefix_list_delete (plist); -      else +	route_map_notify_dependencies(plist->name, RMAP_EVENT_PLIST_ADDED);  	plist->master->recent = plist; -    } -} - -static void trie_install_fn (struct prefix_list_entry *object, -                             struct prefix_list_entry **updptr) -{ -  while (*updptr) -    { -      if (*updptr == object) -        return; -      if ((*updptr)->prefix.prefixlen < object->prefix.prefixlen) -        break; -      if ((*updptr)->seq > object->seq) -        break; -      updptr = &(*updptr)->next_best; -    } - -  if (!object->next_best) -    object->next_best = *updptr; -  else -    assert (object->next_best == *updptr || !*updptr); - -  *updptr = object; -} - -static void -prefix_list_trie_add (struct prefix_list *plist, -		      struct prefix_list_entry *pentry) -{ -  size_t depth = plist->master->trie_depth; -  uint8_t *bytes = &pentry->prefix.u.prefix; -  size_t validbits = pentry->prefix.prefixlen; -  struct pltrie_table *table; - -  table = plist->trie; -  while (validbits > PLC_BITS && depth > 1) -    { -      if (!table->entries[*bytes].next_table) -        table->entries[*bytes].next_table = XCALLOC (MTYPE_PREFIX_LIST_TRIE, -                sizeof(struct pltrie_table)); -      table = table->entries[*bytes].next_table; -      bytes++; -      depth--; -      validbits -= PLC_BITS; -    } - -  trie_walk_affected (validbits, table, *bytes, pentry, trie_install_fn); -} - -static void -prefix_list_entry_add (struct prefix_list *plist, -		       struct prefix_list_entry *pentry) -{ -  struct prefix_list_entry *replace; -  struct prefix_list_entry *point; - -  /* Automatic asignment of seq no. */ -  if (pentry->seq == -1) -    pentry->seq = prefix_new_seq_get (plist); - -  if (plist->tail && pentry->seq > plist->tail->seq) -    point = NULL; -  else -    { -      /* Is there any same seq prefix list entry? */ -      replace = prefix_seq_check (plist, pentry->seq); -      if (replace) -        prefix_list_entry_delete (plist, replace, 0); - -      /* Check insert point. */ -      for (point = plist->head; point; point = point->next) -        if (point->seq >= pentry->seq) -          break; -    } - -  /* In case of this is the first element of the list. */ -  pentry->next = point; - -  if (point) -    { -      if (point->prev) -	point->prev->next = pentry; -      else -	plist->head = pentry; - -      pentry->prev = point->prev; -      point->prev = pentry; -    } -  else -    { -      if (plist->tail) -	plist->tail->next = pentry; -      else -	plist->head = pentry; - -      pentry->prev = plist->tail; -      plist->tail = pentry; -    } - -  prefix_list_trie_add (plist, pentry); - -  /* Increment count. */ -  plist->count++; - -  /* Run hook function. */ -  if (plist->master->add_hook) -    (*plist->master->add_hook) (plist); - -  route_map_notify_dependencies(plist->name, RMAP_EVENT_PLIST_ADDED); -  plist->master->recent = plist;  }  /* Return string of prefix_list_type. */ -static const char * -prefix_list_type_str (struct prefix_list_entry *pentry) -{ -  switch (pentry->type) -    { -    case PREFIX_PERMIT: -      return "permit"; -    case PREFIX_DENY: -      return "deny"; -    default: -      return ""; -    } -} - -static int -prefix_list_entry_match (struct prefix_list_entry *pentry, struct prefix *p) -{ -  int ret; - -  ret = prefix_match (&pentry->prefix, p); -  if (! ret) -    return 0; -   -  /* In case of le nor ge is specified, exact match is performed. */ -  if (! pentry->le && ! pentry->ge) -    { -      if (pentry->prefix.prefixlen != p->prefixlen) -	return 0; -    } -  else -    {   -      if (pentry->le) -	if (p->prefixlen > pentry->le) -	  return 0; - -      if (pentry->ge) -	if (p->prefixlen < pentry->ge) -	  return 0; -    } -  return 1; -} - -enum prefix_list_type -prefix_list_apply (struct prefix_list *plist, void *object) -{ -  struct prefix_list_entry *pentry, *pbest = NULL; - -  struct prefix *p = (struct prefix *) object; -  uint8_t *byte = &p->u.prefix; -  size_t depth; -  size_t validbits = p->prefixlen; -  struct pltrie_table *table; - -  if (plist == NULL) -    return PREFIX_DENY; - -  if (plist->count == 0) -    return PREFIX_PERMIT; - -  depth = plist->master->trie_depth; -  table = plist->trie; -  while (1) -    { -      for (pentry = table->entries[*byte].up_chain; pentry; pentry = pentry->next_best) -        { -          if (pbest && pbest->seq < pentry->seq) -            continue; -          if (prefix_list_entry_match (pentry, p)) -            pbest = pentry; -        } - -      if (validbits <= PLC_BITS) -        break; -      validbits -= PLC_BITS; - -      if (--depth) -        { -          if (!table->entries[*byte].next_table) -            break; - -          table = table->entries[*byte].next_table; -          byte++; -          continue; -        } - -      for (pentry = table->entries[*byte].final_chain; pentry; pentry = pentry->next_best) -        { -          if (pbest && pbest->seq < pentry->seq) -            continue; -          if (prefix_list_entry_match (pentry, p)) -            pbest = pentry; -        } -      break; -    } - -  if (pbest == NULL) -    return PREFIX_DENY; - -  return pbest->type; -} - -static void __attribute__ ((unused)) -prefix_list_print (struct prefix_list *plist) -{ -  struct prefix_list_entry *pentry; - -  if (plist == NULL) -    return; - -  printf ("ip prefix-list %s: %d entries\n", plist->name, plist->count); - -  for (pentry = plist->head; pentry; pentry = pentry->next) -    { -      if (pentry->any) -	printf ("any %s\n", prefix_list_type_str (pentry)); -      else -	{ -	  struct prefix *p; -	  char buf[BUFSIZ]; -	   -	  p = &pentry->prefix; -	   -	  printf ("  seq %u %s %s/%d", -		  pentry->seq, -		  prefix_list_type_str (pentry), -		  inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -		  p->prefixlen); -	  if (pentry->ge) -	    printf (" ge %d", pentry->ge); -	  if (pentry->le) -	    printf (" le %d", pentry->le); -	  printf ("\n"); +static const char *prefix_list_type_str(struct prefix_list_entry *pentry) +{ +	switch (pentry->type) { +	case PREFIX_PERMIT: +		return "permit"; +	case PREFIX_DENY: +		return "deny"; +	default: +		return ""; +	} +} + +static int prefix_list_entry_match(struct prefix_list_entry *pentry, +				   struct prefix *p) +{ +	int ret; + +	ret = prefix_match(&pentry->prefix, p); +	if (!ret) +		return 0; + +	/* In case of le nor ge is specified, exact match is performed. */ +	if (!pentry->le && !pentry->ge) { +		if (pentry->prefix.prefixlen != p->prefixlen) +			return 0; +	} else { +		if (pentry->le) +			if (p->prefixlen > pentry->le) +				return 0; + +		if (pentry->ge) +			if (p->prefixlen < pentry->ge) +				return 0; +	} +	return 1; +} + +enum prefix_list_type prefix_list_apply(struct prefix_list *plist, void *object) +{ +	struct prefix_list_entry *pentry, *pbest = NULL; + +	struct prefix *p = (struct prefix *)object; +	uint8_t *byte = &p->u.prefix; +	size_t depth; +	size_t validbits = p->prefixlen; +	struct pltrie_table *table; + +	if (plist == NULL) +		return PREFIX_DENY; + +	if (plist->count == 0) +		return PREFIX_PERMIT; + +	depth = plist->master->trie_depth; +	table = plist->trie; +	while (1) { +		for (pentry = table->entries[*byte].up_chain; pentry; +		     pentry = pentry->next_best) { +			if (pbest && pbest->seq < pentry->seq) +				continue; +			if (prefix_list_entry_match(pentry, p)) +				pbest = pentry; +		} + +		if (validbits <= PLC_BITS) +			break; +		validbits -= PLC_BITS; + +		if (--depth) { +			if (!table->entries[*byte].next_table) +				break; + +			table = table->entries[*byte].next_table; +			byte++; +			continue; +		} + +		for (pentry = table->entries[*byte].final_chain; pentry; +		     pentry = pentry->next_best) { +			if (pbest && pbest->seq < pentry->seq) +				continue; +			if (prefix_list_entry_match(pentry, p)) +				pbest = pentry; +		} +		break; +	} + +	if (pbest == NULL) +		return PREFIX_DENY; + +	return pbest->type; +} + +static void __attribute__((unused)) prefix_list_print(struct prefix_list *plist) +{ +	struct prefix_list_entry *pentry; + +	if (plist == NULL) +		return; + +	printf("ip prefix-list %s: %d entries\n", plist->name, plist->count); + +	for (pentry = plist->head; pentry; pentry = pentry->next) { +		if (pentry->any) +			printf("any %s\n", prefix_list_type_str(pentry)); +		else { +			struct prefix *p; +			char buf[BUFSIZ]; + +			p = &pentry->prefix; + +			printf("  seq %u %s %s/%d", pentry->seq, +			       prefix_list_type_str(pentry), +			       inet_ntop(p->family, &p->u.prefix, buf, BUFSIZ), +			       p->prefixlen); +			if (pentry->ge) +				printf(" ge %d", pentry->ge); +			if (pentry->le) +				printf(" le %d", pentry->le); +			printf("\n"); +		}  	} -    }  }  /* Retrun 1 when plist already include pentry policy. */  static struct prefix_list_entry * -prefix_entry_dup_check (struct prefix_list *plist, -			struct prefix_list_entry *new) -{ -  size_t depth, maxdepth = plist->master->trie_depth; -  uint8_t byte, *bytes = &new->prefix.u.prefix; -  size_t validbits = new->prefix.prefixlen; -  struct pltrie_table *table; -  struct prefix_list_entry *pentry; -  int seq = 0; - -  if (new->seq == -1) -    seq = prefix_new_seq_get (plist); -  else -    seq = new->seq; - -  table = plist->trie; -  for (depth = 0; validbits > PLC_BITS && depth < maxdepth - 1; depth++) -    { -      byte = bytes[depth]; -      if (!table->entries[byte].next_table) -        return NULL; - -      table = table->entries[byte].next_table; -      validbits -= PLC_BITS; -    } - -  byte = bytes[depth]; -  if (validbits > PLC_BITS) -    pentry = table->entries[byte].final_chain; -  else -    pentry = table->entries[byte].up_chain; - -  for (; pentry; pentry = pentry->next_best) -    { -      if (prefix_same (&pentry->prefix, &new->prefix) -	  && pentry->type == new->type -	  && pentry->le == new->le -	  && pentry->ge == new->ge -	  && pentry->seq != seq) -	return pentry; -    } -  return NULL; -} - -static int -vty_invalid_prefix_range (struct vty *vty, const char *prefix) -{ -  vty_out (vty, "%% Invalid prefix range for %s, make sure: len < ge-value <= le-value%s", -           prefix, VTY_NEWLINE); -  return CMD_WARNING; -} - -static int -vty_prefix_list_install (struct vty *vty, afi_t afi, const char *name,  -                         const char *seq, const char *typestr, -			 const char *prefix, const char *ge, const char *le) -{ -  int ret; -  enum prefix_list_type type; -  struct prefix_list *plist; -  struct prefix_list_entry *pentry; -  struct prefix_list_entry *dup; -  struct prefix p, p_tmp; -  int any = 0; -  int seqnum = -1; -  int lenum = 0; -  int genum = 0; - -  /* Sequential number. */ -  if (seq) -    seqnum = atoi (seq); - -  /* ge and le number */ -  if (ge) -    genum = atoi (ge); -  if (le) -    lenum = atoi (le); - -  /* Check filter type. */ -  if (strncmp ("permit", typestr, 1) == 0) -    type = PREFIX_PERMIT; -  else if (strncmp ("deny", typestr, 1) == 0) -    type = PREFIX_DENY; -  else -    { -      vty_out (vty, "%% prefix type must be permit or deny%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  /* "any" is special token for matching any IPv4 addresses.  */ -  switch (afi) -    { -    case AFI_IP: -      if (strncmp ("any", prefix, strlen (prefix)) == 0) -	{ -	  ret = str2prefix_ipv4 ("0.0.0.0/0", (struct prefix_ipv4 *) &p); -	  genum = 0; -	  lenum = IPV4_MAX_BITLEN; -	  any = 1; +prefix_entry_dup_check(struct prefix_list *plist, struct prefix_list_entry *new) +{ +	size_t depth, maxdepth = plist->master->trie_depth; +	uint8_t byte, *bytes = &new->prefix.u.prefix; +	size_t validbits = new->prefix.prefixlen; +	struct pltrie_table *table; +	struct prefix_list_entry *pentry; +	int seq = 0; + +	if (new->seq == -1) +		seq = prefix_new_seq_get(plist); +	else +		seq = new->seq; + +	table = plist->trie; +	for (depth = 0; validbits > PLC_BITS && depth < maxdepth - 1; depth++) { +		byte = bytes[depth]; +		if (!table->entries[byte].next_table) +			return NULL; + +		table = table->entries[byte].next_table; +		validbits -= PLC_BITS;  	} -      else -	ret = str2prefix_ipv4 (prefix, (struct prefix_ipv4 *) &p); -      if (ret <= 0) -	{ -	  vty_out (vty, "%% Malformed IPv4 prefix%s", VTY_NEWLINE); -	  return CMD_WARNING; +	byte = bytes[depth]; +	if (validbits > PLC_BITS) +		pentry = table->entries[byte].final_chain; +	else +		pentry = table->entries[byte].up_chain; + +	for (; pentry; pentry = pentry->next_best) { +		if (prefix_same(&pentry->prefix, &new->prefix) +		    && pentry->type == new->type && pentry->le == new->le +		    && pentry->ge == new->ge && pentry->seq != seq) +			return pentry;  	} +	return NULL; +} + +static int vty_invalid_prefix_range(struct vty *vty, const char *prefix) +{ +	vty_out(vty, +		"%% Invalid prefix range for %s, make sure: len < ge-value <= le-value%s", +		prefix, VTY_NEWLINE); +	return CMD_WARNING; +} -      /* make a copy to verify prefix matches mask length */ -      prefix_copy (&p_tmp, &p); -      apply_mask_ipv4 ((struct prefix_ipv4 *) &p_tmp); - -      break; -    case AFI_IP6: -      if (strncmp ("any", prefix, strlen (prefix)) == 0) -	{ -	  ret = str2prefix_ipv6 ("::/0", (struct prefix_ipv6 *) &p); -	  genum = 0; -	  lenum = IPV6_MAX_BITLEN; -	  any = 1; +static int vty_prefix_list_install(struct vty *vty, afi_t afi, const char *name, +				   const char *seq, const char *typestr, +				   const char *prefix, const char *ge, +				   const char *le) +{ +	int ret; +	enum prefix_list_type type; +	struct prefix_list *plist; +	struct prefix_list_entry *pentry; +	struct prefix_list_entry *dup; +	struct prefix p, p_tmp; +	int any = 0; +	int seqnum = -1; +	int lenum = 0; +	int genum = 0; + +	/* Sequential number. */ +	if (seq) +		seqnum = atoi(seq); + +	/* ge and le number */ +	if (ge) +		genum = atoi(ge); +	if (le) +		lenum = atoi(le); + +	/* Check filter type. */ +	if (strncmp("permit", typestr, 1) == 0) +		type = PREFIX_PERMIT; +	else if (strncmp("deny", typestr, 1) == 0) +		type = PREFIX_DENY; +	else { +		vty_out(vty, "%% prefix type must be permit or deny%s", +			VTY_NEWLINE); +		return CMD_WARNING;  	} -      else -	ret = str2prefix_ipv6 (prefix, (struct prefix_ipv6 *) &p); -      if (ret <= 0) -	{ -	  vty_out (vty, "%% Malformed IPv6 prefix%s", VTY_NEWLINE); -	  return CMD_WARNING; +	/* "any" is special token for matching any IPv4 addresses.  */ +	switch (afi) { +	case AFI_IP: +		if (strncmp("any", prefix, strlen(prefix)) == 0) { +			ret = str2prefix_ipv4("0.0.0.0/0", +					      (struct prefix_ipv4 *)&p); +			genum = 0; +			lenum = IPV4_MAX_BITLEN; +			any = 1; +		} else +			ret = str2prefix_ipv4(prefix, (struct prefix_ipv4 *)&p); + +		if (ret <= 0) { +			vty_out(vty, "%% Malformed IPv4 prefix%s", VTY_NEWLINE); +			return CMD_WARNING; +		} + +		/* make a copy to verify prefix matches mask length */ +		prefix_copy(&p_tmp, &p); +		apply_mask_ipv4((struct prefix_ipv4 *)&p_tmp); + +		break; +	case AFI_IP6: +		if (strncmp("any", prefix, strlen(prefix)) == 0) { +			ret = str2prefix_ipv6("::/0", (struct prefix_ipv6 *)&p); +			genum = 0; +			lenum = IPV6_MAX_BITLEN; +			any = 1; +		} else +			ret = str2prefix_ipv6(prefix, (struct prefix_ipv6 *)&p); + +		if (ret <= 0) { +			vty_out(vty, "%% Malformed IPv6 prefix%s", VTY_NEWLINE); +			return CMD_WARNING; +		} + +		/* make a copy to verify prefix matches mask length */ +		prefix_copy(&p_tmp, &p); +		apply_mask_ipv6((struct prefix_ipv6 *)&p_tmp); + +		break; +	case AFI_L2VPN: +	default: +		vty_out(vty, "%% Unrecognized AFI (%d)%s", afi, VTY_NEWLINE); +		return CMD_WARNING; +		break;  	} -      /* make a copy to verify prefix matches mask length */ -      prefix_copy (&p_tmp, &p); -      apply_mask_ipv6 ((struct prefix_ipv6 *) &p_tmp); - -      break; -    case AFI_L2VPN: -    default: -      vty_out (vty, "%% Unrecognized AFI (%d)%s", afi, VTY_NEWLINE); -      return CMD_WARNING; -      break; -    } - -  /* If prefix has bits not under the mask, adjust it to fit */ -  if (!prefix_same (&p_tmp, &p)) -    { -      char buf[PREFIX2STR_BUFFER]; -      char buf_tmp[PREFIX2STR_BUFFER]; -      prefix2str(&p, buf, sizeof(buf)); -      prefix2str(&p_tmp, buf_tmp, sizeof(buf_tmp)); -      zlog_warn ("Prefix-list %s prefix changed from %s to %s to match length", -                 name, buf, buf_tmp); -      p = p_tmp; -    } - -  /* ge and le check. */ -  if (genum && (genum <= p.prefixlen)) -    return vty_invalid_prefix_range (vty, prefix); - -  if (lenum && (lenum <= p.prefixlen)) -    return vty_invalid_prefix_range (vty, prefix); - -  if (lenum && (genum > lenum)) -    return vty_invalid_prefix_range (vty, prefix); - -  if (genum && (lenum == (afi == AFI_IP ? 32 : 128))) -    lenum = 0; - -  /* Get prefix_list with name. */ -  plist = prefix_list_get (afi, 0, name); - -  /* Make prefix entry. */ -  pentry = prefix_list_entry_make (&p, type, seqnum, lenum, genum, any); -     -  /* Check same policy. */ -  dup = prefix_entry_dup_check (plist, pentry); - -  if (dup) -    { -      prefix_list_entry_free (pentry); -      return CMD_SUCCESS; -    } - -  /* Install new filter to the access_list. */ -  prefix_list_entry_add (plist, pentry); - -  return CMD_SUCCESS; -} - -static int -vty_prefix_list_uninstall (struct vty *vty, afi_t afi, const char *name,  -                           const char *seq, const char *typestr, -			   const char *prefix, const char *ge, const char *le) -{ -  int ret; -  enum prefix_list_type type; -  struct prefix_list *plist; -  struct prefix_list_entry *pentry; -  struct prefix p; -  int seqnum = -1; -  int lenum = 0; -  int genum = 0; - -  /* Check prefix list name. */ -  plist = prefix_list_lookup (afi, name); -  if (! plist) -    { -      vty_out (vty, "%% Can't find specified prefix-list%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  /* Only prefix-list name specified, delete the entire prefix-list. */ -  if (seq == NULL && typestr == NULL && prefix == NULL &&  -      ge == NULL && le == NULL) -    { -      prefix_list_delete (plist); -      return CMD_SUCCESS; -    } - -  /* We must have, at a minimum, both the type and prefix here */ -  if ((typestr == NULL) || (prefix == NULL)) -    { -      vty_out (vty, "%% Both prefix and type required%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  /* Check sequence number. */ -  if (seq) -    seqnum = atoi (seq); - -  /* ge and le number */ -  if (ge) -    genum = atoi (ge); -  if (le) -    lenum = atoi (le); - -  /* Check of filter type. */ -  if (strncmp ("permit", typestr, 1) == 0) -    type = PREFIX_PERMIT; -  else if (strncmp ("deny", typestr, 1) == 0) -    type = PREFIX_DENY; -  else -    { -      vty_out (vty, "%% prefix type must be permit or deny%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  /* "any" is special token for matching any IPv4 addresses.  */ -  if (afi == AFI_IP) -    { -      if (strncmp ("any", prefix, strlen (prefix)) == 0) -	{ -	  ret = str2prefix_ipv4 ("0.0.0.0/0", (struct prefix_ipv4 *) &p); -	  genum = 0; -	  lenum = IPV4_MAX_BITLEN; +	/* If prefix has bits not under the mask, adjust it to fit */ +	if (!prefix_same(&p_tmp, &p)) { +		char buf[PREFIX2STR_BUFFER]; +		char buf_tmp[PREFIX2STR_BUFFER]; +		prefix2str(&p, buf, sizeof(buf)); +		prefix2str(&p_tmp, buf_tmp, sizeof(buf_tmp)); +		zlog_warn( +			"Prefix-list %s prefix changed from %s to %s to match length", +			name, buf, buf_tmp); +		p = p_tmp;  	} -      else -	ret = str2prefix_ipv4 (prefix, (struct prefix_ipv4 *) &p); -      if (ret <= 0) -	{ -	  vty_out (vty, "%% Malformed IPv4 prefix%s", VTY_NEWLINE); -	  return CMD_WARNING; +	/* ge and le check. */ +	if (genum && (genum <= p.prefixlen)) +		return vty_invalid_prefix_range(vty, prefix); + +	if (lenum && (lenum <= p.prefixlen)) +		return vty_invalid_prefix_range(vty, prefix); + +	if (lenum && (genum > lenum)) +		return vty_invalid_prefix_range(vty, prefix); + +	if (genum && (lenum == (afi == AFI_IP ? 32 : 128))) +		lenum = 0; + +	/* Get prefix_list with name. */ +	plist = prefix_list_get(afi, 0, name); + +	/* Make prefix entry. */ +	pentry = prefix_list_entry_make(&p, type, seqnum, lenum, genum, any); + +	/* Check same policy. */ +	dup = prefix_entry_dup_check(plist, pentry); + +	if (dup) { +		prefix_list_entry_free(pentry); +		return CMD_SUCCESS;  	} -    } -  else if (afi == AFI_IP6) -    { -      if (strncmp ("any", prefix, strlen (prefix)) == 0) -	{ -	  ret = str2prefix_ipv6 ("::/0", (struct prefix_ipv6 *) &p); -	  genum = 0; -	  lenum = IPV6_MAX_BITLEN; + +	/* Install new filter to the access_list. */ +	prefix_list_entry_add(plist, pentry); + +	return CMD_SUCCESS; +} + +static int vty_prefix_list_uninstall(struct vty *vty, afi_t afi, +				     const char *name, const char *seq, +				     const char *typestr, const char *prefix, +				     const char *ge, const char *le) +{ +	int ret; +	enum prefix_list_type type; +	struct prefix_list *plist; +	struct prefix_list_entry *pentry; +	struct prefix p; +	int seqnum = -1; +	int lenum = 0; +	int genum = 0; + +	/* Check prefix list name. */ +	plist = prefix_list_lookup(afi, name); +	if (!plist) { +		vty_out(vty, "%% Can't find specified prefix-list%s", +			VTY_NEWLINE); +		return CMD_WARNING;  	} -      else -	ret = str2prefix_ipv6 (prefix, (struct prefix_ipv6 *) &p); -      if (ret <= 0) -	{ -	  vty_out (vty, "%% Malformed IPv6 prefix%s", VTY_NEWLINE); -	  return CMD_WARNING; +	/* Only prefix-list name specified, delete the entire prefix-list. */ +	if (seq == NULL && typestr == NULL && prefix == NULL && ge == NULL +	    && le == NULL) { +		prefix_list_delete(plist); +		return CMD_SUCCESS;  	} -    } -  /* Lookup prefix entry. */ -  pentry = prefix_list_entry_lookup(plist, &p, type, seqnum, lenum, genum); +	/* We must have, at a minimum, both the type and prefix here */ +	if ((typestr == NULL) || (prefix == NULL)) { +		vty_out(vty, "%% Both prefix and type required%s", VTY_NEWLINE); +		return CMD_WARNING; +	} -  if (pentry == NULL) -    { -      vty_out (vty, "%% Can't find specified prefix-list%s", VTY_NEWLINE); -      return CMD_WARNING; -    } +	/* Check sequence number. */ +	if (seq) +		seqnum = atoi(seq); + +	/* ge and le number */ +	if (ge) +		genum = atoi(ge); +	if (le) +		lenum = atoi(le); + +	/* Check of filter type. */ +	if (strncmp("permit", typestr, 1) == 0) +		type = PREFIX_PERMIT; +	else if (strncmp("deny", typestr, 1) == 0) +		type = PREFIX_DENY; +	else { +		vty_out(vty, "%% prefix type must be permit or deny%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  /* Install new filter to the access_list. */ -  prefix_list_entry_delete (plist, pentry, 1); +	/* "any" is special token for matching any IPv4 addresses.  */ +	if (afi == AFI_IP) { +		if (strncmp("any", prefix, strlen(prefix)) == 0) { +			ret = str2prefix_ipv4("0.0.0.0/0", +					      (struct prefix_ipv4 *)&p); +			genum = 0; +			lenum = IPV4_MAX_BITLEN; +		} else +			ret = str2prefix_ipv4(prefix, (struct prefix_ipv4 *)&p); + +		if (ret <= 0) { +			vty_out(vty, "%% Malformed IPv4 prefix%s", VTY_NEWLINE); +			return CMD_WARNING; +		} +	} else if (afi == AFI_IP6) { +		if (strncmp("any", prefix, strlen(prefix)) == 0) { +			ret = str2prefix_ipv6("::/0", (struct prefix_ipv6 *)&p); +			genum = 0; +			lenum = IPV6_MAX_BITLEN; +		} else +			ret = str2prefix_ipv6(prefix, (struct prefix_ipv6 *)&p); + +		if (ret <= 0) { +			vty_out(vty, "%% Malformed IPv6 prefix%s", VTY_NEWLINE); +			return CMD_WARNING; +		} +	} -  return CMD_SUCCESS; +	/* Lookup prefix entry. */ +	pentry = +		prefix_list_entry_lookup(plist, &p, type, seqnum, lenum, genum); + +	if (pentry == NULL) { +		vty_out(vty, "%% Can't find specified prefix-list%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	/* Install new filter to the access_list. */ +	prefix_list_entry_delete(plist, pentry, 1); + +	return CMD_SUCCESS;  } -static int -vty_prefix_list_desc_unset (struct vty *vty, afi_t afi, const char *name) +static int vty_prefix_list_desc_unset(struct vty *vty, afi_t afi, +				      const char *name)  { -  struct prefix_list *plist; +	struct prefix_list *plist; -  plist = prefix_list_lookup (afi, name); -  if (! plist) -    { -      vty_out (vty, "%% Can't find specified prefix-list%s", VTY_NEWLINE); -      return CMD_WARNING; -    } +	plist = prefix_list_lookup(afi, name); +	if (!plist) { +		vty_out(vty, "%% Can't find specified prefix-list%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  if (plist->desc) -    { -      XFREE (MTYPE_TMP, plist->desc); -      plist->desc = NULL; -    } +	if (plist->desc) { +		XFREE(MTYPE_TMP, plist->desc); +		plist->desc = NULL; +	} -  if (plist->head == NULL && plist->tail == NULL && plist->desc == NULL) -    prefix_list_delete (plist); +	if (plist->head == NULL && plist->tail == NULL && plist->desc == NULL) +		prefix_list_delete(plist); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  } -enum display_type -{ -  normal_display, -  summary_display, -  detail_display, -  sequential_display, -  longer_display, -  first_match_display +enum display_type { +	normal_display, +	summary_display, +	detail_display, +	sequential_display, +	longer_display, +	first_match_display  }; -static void -vty_show_prefix_entry (struct vty *vty, afi_t afi, struct prefix_list *plist, -		       struct prefix_master *master, enum display_type dtype, -		       int seqnum) -{ -  struct prefix_list_entry *pentry; - -  /* Print the name of the protocol */ -  vty_out(vty, "%s: ", zlog_protoname()); -                                                                            -  if (dtype == normal_display) -    { -      vty_out (vty, "ip%s prefix-list %s: %d entries%s", -	       afi == AFI_IP ? "" : "v6", -	       plist->name, plist->count, VTY_NEWLINE); -      if (plist->desc) -	vty_out (vty, "   Description: %s%s", plist->desc, VTY_NEWLINE); -    } -  else if (dtype == summary_display || dtype == detail_display) -    { -      vty_out (vty, "ip%s prefix-list %s:%s", -	       afi == AFI_IP ? "" : "v6", plist->name, VTY_NEWLINE); - -      if (plist->desc) -	vty_out (vty, "   Description: %s%s", plist->desc, VTY_NEWLINE); - -      vty_out (vty, "   count: %d, range entries: %d, sequences: %u - %u%s", -	       plist->count, plist->rangecount,  -	       plist->head ? plist->head->seq : 0,  -	       plist->tail ? plist->tail->seq : 0, -	       VTY_NEWLINE); -    } - -  if (dtype != summary_display) -    { -      for (pentry = plist->head; pentry; pentry = pentry->next) -	{ -	  if (dtype == sequential_display && pentry->seq != seqnum) -	    continue; -	     -	  vty_out (vty, "   "); - -	  if (master->seqnum) -	    vty_out (vty, "seq %u ", pentry->seq); - -	  vty_out (vty, "%s ", prefix_list_type_str (pentry)); - -	  if (pentry->any) -	    vty_out (vty, "any"); -	  else -	    { -	      struct prefix *p = &pentry->prefix; -	      char buf[BUFSIZ]; - -	      vty_out (vty, "%s/%d", -		       inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -		       p->prefixlen); - -	      if (pentry->ge) -		vty_out (vty, " ge %d", pentry->ge); -	      if (pentry->le) -		vty_out (vty, " le %d", pentry->le); -	    } - -	  if (dtype == detail_display || dtype == sequential_display) -	    vty_out (vty, " (hit count: %ld, refcount: %ld)",  -		     pentry->hitcnt, pentry->refcnt); -	   -	  vty_out (vty, "%s", VTY_NEWLINE); +static void vty_show_prefix_entry(struct vty *vty, afi_t afi, +				  struct prefix_list *plist, +				  struct prefix_master *master, +				  enum display_type dtype, int seqnum) +{ +	struct prefix_list_entry *pentry; + +	/* Print the name of the protocol */ +	vty_out(vty, "%s: ", zlog_protoname()); + +	if (dtype == normal_display) { +		vty_out(vty, "ip%s prefix-list %s: %d entries%s", +			afi == AFI_IP ? "" : "v6", plist->name, plist->count, +			VTY_NEWLINE); +		if (plist->desc) +			vty_out(vty, "   Description: %s%s", plist->desc, +				VTY_NEWLINE); +	} else if (dtype == summary_display || dtype == detail_display) { +		vty_out(vty, "ip%s prefix-list %s:%s", +			afi == AFI_IP ? "" : "v6", plist->name, VTY_NEWLINE); + +		if (plist->desc) +			vty_out(vty, "   Description: %s%s", plist->desc, +				VTY_NEWLINE); + +		vty_out(vty, +			"   count: %d, range entries: %d, sequences: %u - %u%s", +			plist->count, plist->rangecount, +			plist->head ? plist->head->seq : 0, +			plist->tail ? plist->tail->seq : 0, VTY_NEWLINE);  	} -    } -} -static int -vty_show_prefix_list (struct vty *vty, afi_t afi, const char *name, -		      const char *seq, enum display_type dtype) -{ -  struct prefix_list *plist; -  struct prefix_master *master; -  int seqnum = 0; +	if (dtype != summary_display) { +		for (pentry = plist->head; pentry; pentry = pentry->next) { +			if (dtype == sequential_display +			    && pentry->seq != seqnum) +				continue; -  master = prefix_master_get (afi, 0); -  if (master == NULL) -    return CMD_WARNING; +			vty_out(vty, "   "); -  if (seq) -    seqnum = atoi (seq); +			if (master->seqnum) +				vty_out(vty, "seq %u ", pentry->seq); -  if (name) -    { -      plist = prefix_list_lookup (afi, name); -      if (! plist) -	{ -	  vty_out (vty, "%% Can't find specified prefix-list%s", VTY_NEWLINE); -	  return CMD_WARNING; -	} -      vty_show_prefix_entry (vty, afi, plist, master, dtype, seqnum); -    } -  else -    { -      if (dtype == detail_display || dtype == summary_display) -	{ -	  if (master->recent) -	    vty_out (vty, "Prefix-list with the last deletion/insertion: %s%s", -		     master->recent->name, VTY_NEWLINE); -	} +			vty_out(vty, "%s ", prefix_list_type_str(pentry)); + +			if (pentry->any) +				vty_out(vty, "any"); +			else { +				struct prefix *p = &pentry->prefix; +				char buf[BUFSIZ]; + +				vty_out(vty, "%s/%d", +					inet_ntop(p->family, &p->u.prefix, buf, +						  BUFSIZ), +					p->prefixlen); + +				if (pentry->ge) +					vty_out(vty, " ge %d", pentry->ge); +				if (pentry->le) +					vty_out(vty, " le %d", pentry->le); +			} + +			if (dtype == detail_display +			    || dtype == sequential_display) +				vty_out(vty, " (hit count: %ld, refcount: %ld)", +					pentry->hitcnt, pentry->refcnt); -      for (plist = master->num.head; plist; plist = plist->next) -	vty_show_prefix_entry (vty, afi, plist, master, dtype, seqnum); - -      for (plist = master->str.head; plist; plist = plist->next) -	vty_show_prefix_entry (vty, afi, plist, master, dtype, seqnum); -    } - -  return CMD_SUCCESS; -} - -static int -vty_show_prefix_list_prefix (struct vty *vty, afi_t afi, const char *name,  -			     const char *prefix, enum display_type type) -{ -  struct prefix_list *plist; -  struct prefix_list_entry *pentry; -  struct prefix p; -  int ret; -  int match; - -  plist = prefix_list_lookup (afi, name); -  if (! plist) -    { -      vty_out (vty, "%% Can't find specified prefix-list%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  ret = str2prefix (prefix, &p); -  if (ret <= 0) -    { -      vty_out (vty, "%% prefix is malformed%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  for (pentry = plist->head; pentry; pentry = pentry->next) -    { -      match = 0; - -      if (type == normal_display || type == first_match_display) -	if (prefix_same (&p, &pentry->prefix)) -	  match = 1; - -      if (type == longer_display) -	if (prefix_match (&p, &pentry->prefix)) -	  match = 1; - -      if (match) -	{ -	  vty_out (vty, "   seq %u %s ", -		   pentry->seq, -		   prefix_list_type_str (pentry)); - -	  if (pentry->any) -	    vty_out (vty, "any"); -	  else -	    { -	      struct prefix *p = &pentry->prefix; -	      char buf[BUFSIZ]; -	       -	      vty_out (vty, "%s/%d", -		       inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -		       p->prefixlen); - -	      if (pentry->ge) -		vty_out (vty, " ge %d", pentry->ge); -	      if (pentry->le) -		vty_out (vty, " le %d", pentry->le); -	    } -	   -	  if (type == normal_display || type == first_match_display) -	    vty_out (vty, " (hit count: %ld, refcount: %ld)",  -		     pentry->hitcnt, pentry->refcnt); - -	  vty_out (vty, "%s", VTY_NEWLINE); - -	  if (type == first_match_display) -	    return CMD_SUCCESS; +			vty_out(vty, "%s", VTY_NEWLINE); +		}  	} -    } -  return CMD_SUCCESS;  } -static int -vty_clear_prefix_list (struct vty *vty, afi_t afi, const char *name,  -                       const char *prefix) -{ -  struct prefix_master *master; -  struct prefix_list *plist; -  struct prefix_list_entry *pentry; -  int ret; -  struct prefix p; +static int vty_show_prefix_list(struct vty *vty, afi_t afi, const char *name, +				const char *seq, enum display_type dtype) +{ +	struct prefix_list *plist; +	struct prefix_master *master; +	int seqnum = 0; + +	master = prefix_master_get(afi, 0); +	if (master == NULL) +		return CMD_WARNING; + +	if (seq) +		seqnum = atoi(seq); + +	if (name) { +		plist = prefix_list_lookup(afi, name); +		if (!plist) { +			vty_out(vty, "%% Can't find specified prefix-list%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} +		vty_show_prefix_entry(vty, afi, plist, master, dtype, seqnum); +	} else { +		if (dtype == detail_display || dtype == summary_display) { +			if (master->recent) +				vty_out(vty, +					"Prefix-list with the last deletion/insertion: %s%s", +					master->recent->name, VTY_NEWLINE); +		} + +		for (plist = master->num.head; plist; plist = plist->next) +			vty_show_prefix_entry(vty, afi, plist, master, dtype, +					      seqnum); + +		for (plist = master->str.head; plist; plist = plist->next) +			vty_show_prefix_entry(vty, afi, plist, master, dtype, +					      seqnum); +	} -  master = prefix_master_get (afi, 0); -  if (master == NULL) -    return CMD_WARNING; +	return CMD_SUCCESS; +} -  if (name == NULL && prefix == NULL) -    { -      for (plist = master->num.head; plist; plist = plist->next) -	for (pentry = plist->head; pentry; pentry = pentry->next) -	  pentry->hitcnt = 0; +static int vty_show_prefix_list_prefix(struct vty *vty, afi_t afi, +				       const char *name, const char *prefix, +				       enum display_type type) +{ +	struct prefix_list *plist; +	struct prefix_list_entry *pentry; +	struct prefix p; +	int ret; +	int match; -      for (plist = master->str.head; plist; plist = plist->next) -	for (pentry = plist->head; pentry; pentry = pentry->next) -	  pentry->hitcnt = 0; -    } -  else -    { -      plist = prefix_list_lookup (afi, name); -      if (! plist) -	{ -	  vty_out (vty, "%% Can't find specified prefix-list%s", VTY_NEWLINE); -	  return CMD_WARNING; +	plist = prefix_list_lookup(afi, name); +	if (!plist) { +		vty_out(vty, "%% Can't find specified prefix-list%s", +			VTY_NEWLINE); +		return CMD_WARNING;  	} -      if (prefix) -	{ -	  ret = str2prefix (prefix, &p); -	  if (ret <= 0) -	    { -	      vty_out (vty, "%% prefix is malformed%s", VTY_NEWLINE); -	      return CMD_WARNING; -	    } +	ret = str2prefix(prefix, &p); +	if (ret <= 0) { +		vty_out(vty, "%% prefix is malformed%s", VTY_NEWLINE); +		return CMD_WARNING;  	} -      for (pentry = plist->head; pentry; pentry = pentry->next) -	{ -	  if (prefix) -	    { -	      if (prefix_match (&pentry->prefix, &p)) -		pentry->hitcnt = 0; -	    } -	  else -	    pentry->hitcnt = 0; +	for (pentry = plist->head; pentry; pentry = pentry->next) { +		match = 0; + +		if (type == normal_display || type == first_match_display) +			if (prefix_same(&p, &pentry->prefix)) +				match = 1; + +		if (type == longer_display) +			if (prefix_match(&p, &pentry->prefix)) +				match = 1; + +		if (match) { +			vty_out(vty, "   seq %u %s ", pentry->seq, +				prefix_list_type_str(pentry)); + +			if (pentry->any) +				vty_out(vty, "any"); +			else { +				struct prefix *p = &pentry->prefix; +				char buf[BUFSIZ]; + +				vty_out(vty, "%s/%d", +					inet_ntop(p->family, &p->u.prefix, buf, +						  BUFSIZ), +					p->prefixlen); + +				if (pentry->ge) +					vty_out(vty, " ge %d", pentry->ge); +				if (pentry->le) +					vty_out(vty, " le %d", pentry->le); +			} + +			if (type == normal_display +			    || type == first_match_display) +				vty_out(vty, " (hit count: %ld, refcount: %ld)", +					pentry->hitcnt, pentry->refcnt); + +			vty_out(vty, "%s", VTY_NEWLINE); + +			if (type == first_match_display) +				return CMD_SUCCESS; +		}  	} -    } -  return CMD_SUCCESS; +	return CMD_SUCCESS; +} + +static int vty_clear_prefix_list(struct vty *vty, afi_t afi, const char *name, +				 const char *prefix) +{ +	struct prefix_master *master; +	struct prefix_list *plist; +	struct prefix_list_entry *pentry; +	int ret; +	struct prefix p; + +	master = prefix_master_get(afi, 0); +	if (master == NULL) +		return CMD_WARNING; + +	if (name == NULL && prefix == NULL) { +		for (plist = master->num.head; plist; plist = plist->next) +			for (pentry = plist->head; pentry; +			     pentry = pentry->next) +				pentry->hitcnt = 0; + +		for (plist = master->str.head; plist; plist = plist->next) +			for (pentry = plist->head; pentry; +			     pentry = pentry->next) +				pentry->hitcnt = 0; +	} else { +		plist = prefix_list_lookup(afi, name); +		if (!plist) { +			vty_out(vty, "%% Can't find specified prefix-list%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} + +		if (prefix) { +			ret = str2prefix(prefix, &p); +			if (ret <= 0) { +				vty_out(vty, "%% prefix is malformed%s", +					VTY_NEWLINE); +				return CMD_WARNING; +			} +		} + +		for (pentry = plist->head; pentry; pentry = pentry->next) { +			if (prefix) { +				if (prefix_match(&pentry->prefix, &p)) +					pentry->hitcnt = 0; +			} else +				pentry->hitcnt = 0; +		} +	} +	return CMD_SUCCESS;  }  DEFUN (ip_prefix_list, @@ -1424,11 +1313,12 @@ DEFUN (ip_prefix_list,         "IP prefix <network>/<length>, e.g., 35.0.0.0/8\n"         "Any prefix match. Same as \"0.0.0.0/0 le 32\"\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv4_any = 4; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, NULL,  -				  argv[idx_permit_deny]->arg, argv[idx_ipv4_any]->arg, NULL, NULL); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv4_any = 4; +	return vty_prefix_list_install(vty, AFI_IP, argv[idx_word]->arg, NULL, +				       argv[idx_permit_deny]->arg, +				       argv[idx_ipv4_any]->arg, NULL, NULL);  }  DEFUN (ip_prefix_list_ge, @@ -1443,12 +1333,14 @@ DEFUN (ip_prefix_list_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv4_prefixlen = 4; -  int idx_number = 6; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg,  -				 argv[idx_ipv4_prefixlen]->arg, argv[idx_number]->arg, NULL); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv4_prefixlen = 4; +	int idx_number = 6; +	return vty_prefix_list_install(vty, AFI_IP, argv[idx_word]->arg, NULL, +				       argv[idx_permit_deny]->arg, +				       argv[idx_ipv4_prefixlen]->arg, +				       argv[idx_number]->arg, NULL);  }  DEFUN (ip_prefix_list_ge_le, @@ -1465,13 +1357,15 @@ DEFUN (ip_prefix_list_ge_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv4_prefixlen = 4; -  int idx_number = 6; -  int idx_number_2 = 8; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg,  -				  argv[idx_ipv4_prefixlen]->arg, argv[idx_number]->arg, argv[idx_number_2]->arg); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv4_prefixlen = 4; +	int idx_number = 6; +	int idx_number_2 = 8; +	return vty_prefix_list_install( +		vty, AFI_IP, argv[idx_word]->arg, NULL, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number]->arg, argv[idx_number_2]->arg);  }  DEFUN (ip_prefix_list_le, @@ -1486,12 +1380,14 @@ DEFUN (ip_prefix_list_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv4_prefixlen = 4; -  int idx_number = 6; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				  argv[idx_ipv4_prefixlen]->arg, NULL, argv[idx_number]->arg); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv4_prefixlen = 4; +	int idx_number = 6; +	return vty_prefix_list_install(vty, AFI_IP, argv[idx_word]->arg, NULL, +				       argv[idx_permit_deny]->arg, +				       argv[idx_ipv4_prefixlen]->arg, NULL, +				       argv[idx_number]->arg);  }  DEFUN (ip_prefix_list_le_ge, @@ -1508,13 +1404,15 @@ DEFUN (ip_prefix_list_le_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv4_prefixlen = 4; -  int idx_number = 6; -  int idx_number_2 = 8; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				  argv[idx_ipv4_prefixlen]->arg, argv[idx_number_2]->arg, argv[idx_number]->arg); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv4_prefixlen = 4; +	int idx_number = 6; +	int idx_number_2 = 8; +	return vty_prefix_list_install( +		vty, AFI_IP, argv[idx_word]->arg, NULL, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number_2]->arg, argv[idx_number]->arg);  }  DEFUN (ip_prefix_list_seq, @@ -1530,12 +1428,14 @@ DEFUN (ip_prefix_list_seq,         "IP prefix <network>/<length>, e.g., 35.0.0.0/8\n"         "Any prefix match. Same as \"0.0.0.0/0 le 32\"\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv4_any = 6; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv4_any]->arg, NULL, NULL); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv4_any = 6; +	return vty_prefix_list_install(vty, AFI_IP, argv[idx_word]->arg, +				       argv[idx_number]->arg, +				       argv[idx_permit_deny]->arg, +				       argv[idx_ipv4_any]->arg, NULL, NULL);  }  DEFUN (ip_prefix_list_seq_ge, @@ -1552,13 +1452,15 @@ DEFUN (ip_prefix_list_seq_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv4_prefixlen = 6; -  int idx_number_2 = 8; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv4_prefixlen]->arg, argv[idx_number_2]->arg, NULL); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv4_prefixlen = 6; +	int idx_number_2 = 8; +	return vty_prefix_list_install( +		vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number_2]->arg, NULL);  }  DEFUN (ip_prefix_list_seq_ge_le, @@ -1577,14 +1479,16 @@ DEFUN (ip_prefix_list_seq_ge_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv4_prefixlen = 6; -  int idx_number_2 = 8; -  int idx_number_3 = 10; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv4_prefixlen]->arg, argv[idx_number_2]->arg, argv[idx_number_3]->arg); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv4_prefixlen = 6; +	int idx_number_2 = 8; +	int idx_number_3 = 10; +	return vty_prefix_list_install( +		vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number_2]->arg, argv[idx_number_3]->arg);  }  DEFUN (ip_prefix_list_seq_le, @@ -1601,13 +1505,15 @@ DEFUN (ip_prefix_list_seq_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv4_prefixlen = 6; -  int idx_number_2 = 8; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv4_prefixlen]->arg, NULL, argv[idx_number_2]->arg); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv4_prefixlen = 6; +	int idx_number_2 = 8; +	return vty_prefix_list_install( +		vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, NULL, +		argv[idx_number_2]->arg);  }  DEFUN (ip_prefix_list_seq_le_ge, @@ -1626,14 +1532,16 @@ DEFUN (ip_prefix_list_seq_le_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv4_prefixlen = 6; -  int idx_number_2 = 8; -  int idx_number_3 = 10; -  return vty_prefix_list_install (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv4_prefixlen]->arg, argv[idx_number_3]->arg, argv[idx_number_2]->arg); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv4_prefixlen = 6; +	int idx_number_2 = 8; +	int idx_number_3 = 10; +	return vty_prefix_list_install( +		vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number_3]->arg, argv[idx_number_2]->arg);  }  DEFUN (no_ip_prefix_list, @@ -1644,9 +1552,9 @@ DEFUN (no_ip_prefix_list,         PREFIX_LIST_STR         "Name of a prefix list\n")  { -  int idx_word = 3; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, NULL, NULL, -				    NULL, NULL, NULL); +	int idx_word = 3; +	return vty_prefix_list_uninstall(vty, AFI_IP, argv[idx_word]->arg, NULL, +					 NULL, NULL, NULL, NULL);  }  DEFUN (no_ip_prefix_list_prefix, @@ -1661,11 +1569,12 @@ DEFUN (no_ip_prefix_list_prefix,         "IP prefix <network>/<length>, e.g., 35.0.0.0/8\n"         "Any prefix match.  Same as \"0.0.0.0/0 le 32\"\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv4_any = 5; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_any]->arg, NULL, NULL); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv4_any = 5; +	return vty_prefix_list_uninstall(vty, AFI_IP, argv[idx_word]->arg, NULL, +					 argv[idx_permit_deny]->arg, +					 argv[idx_ipv4_any]->arg, NULL, NULL);  }  DEFUN (no_ip_prefix_list_ge, @@ -1681,12 +1590,14 @@ DEFUN (no_ip_prefix_list_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv4_prefixlen = 5; -  int idx_number = 7; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_prefixlen]->arg, argv[idx_number]->arg, NULL); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv4_prefixlen = 5; +	int idx_number = 7; +	return vty_prefix_list_uninstall(vty, AFI_IP, argv[idx_word]->arg, NULL, +					 argv[idx_permit_deny]->arg, +					 argv[idx_ipv4_prefixlen]->arg, +					 argv[idx_number]->arg, NULL);  }  DEFUN (no_ip_prefix_list_ge_le, @@ -1704,13 +1615,15 @@ DEFUN (no_ip_prefix_list_ge_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv4_prefixlen = 5; -  int idx_number = 7; -  int idx_number_2 = 9; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_prefixlen]->arg, argv[idx_number]->arg, argv[idx_number_2]->arg); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv4_prefixlen = 5; +	int idx_number = 7; +	int idx_number_2 = 9; +	return vty_prefix_list_uninstall( +		vty, AFI_IP, argv[idx_word]->arg, NULL, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number]->arg, argv[idx_number_2]->arg);  }  DEFUN (no_ip_prefix_list_le, @@ -1726,12 +1639,14 @@ DEFUN (no_ip_prefix_list_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv4_prefixlen = 5; -  int idx_number = 7; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_prefixlen]->arg, NULL, argv[idx_number]->arg); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv4_prefixlen = 5; +	int idx_number = 7; +	return vty_prefix_list_uninstall(vty, AFI_IP, argv[idx_word]->arg, NULL, +					 argv[idx_permit_deny]->arg, +					 argv[idx_ipv4_prefixlen]->arg, NULL, +					 argv[idx_number]->arg);  }  DEFUN (no_ip_prefix_list_le_ge, @@ -1749,13 +1664,15 @@ DEFUN (no_ip_prefix_list_le_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv4_prefixlen = 5; -  int idx_number = 7; -  int idx_number_2 = 9; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_prefixlen]->arg, argv[idx_number_2]->arg, argv[idx_number]->arg); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv4_prefixlen = 5; +	int idx_number = 7; +	int idx_number_2 = 9; +	return vty_prefix_list_uninstall( +		vty, AFI_IP, argv[idx_word]->arg, NULL, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number_2]->arg, argv[idx_number]->arg);  }  DEFUN (no_ip_prefix_list_seq, @@ -1772,12 +1689,14 @@ DEFUN (no_ip_prefix_list_seq,         "IP prefix <network>/<length>, e.g., 35.0.0.0/8\n"         "Any prefix match.  Same as \"0.0.0.0/0 le 32\"\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv4_any = 7; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_any]->arg, NULL, NULL); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv4_any = 7; +	return vty_prefix_list_uninstall(vty, AFI_IP, argv[idx_word]->arg, +					 argv[idx_number]->arg, +					 argv[idx_permit_deny]->arg, +					 argv[idx_ipv4_any]->arg, NULL, NULL);  }  DEFUN (no_ip_prefix_list_seq_ge, @@ -1795,13 +1714,15 @@ DEFUN (no_ip_prefix_list_seq_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv4_prefixlen = 7; -  int idx_number_2 = 9; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_prefixlen]->arg, argv[idx_number_2]->arg, NULL); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv4_prefixlen = 7; +	int idx_number_2 = 9; +	return vty_prefix_list_uninstall( +		vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number_2]->arg, NULL);  }  DEFUN (no_ip_prefix_list_seq_ge_le, @@ -1821,14 +1742,16 @@ DEFUN (no_ip_prefix_list_seq_ge_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv4_prefixlen = 7; -  int idx_number_2 = 9; -  int idx_number_3 = 11; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_prefixlen]->arg, argv[idx_number_2]->arg, argv[idx_number_3]->arg); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv4_prefixlen = 7; +	int idx_number_2 = 9; +	int idx_number_3 = 11; +	return vty_prefix_list_uninstall( +		vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number_2]->arg, argv[idx_number_3]->arg);  }  DEFUN (no_ip_prefix_list_seq_le, @@ -1846,13 +1769,15 @@ DEFUN (no_ip_prefix_list_seq_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv4_prefixlen = 7; -  int idx_number_2 = 9; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_prefixlen]->arg, NULL, argv[idx_number_2]->arg); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv4_prefixlen = 7; +	int idx_number_2 = 9; +	return vty_prefix_list_uninstall( +		vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, NULL, +		argv[idx_number_2]->arg);  }  DEFUN (no_ip_prefix_list_seq_le_ge, @@ -1872,14 +1797,16 @@ DEFUN (no_ip_prefix_list_seq_le_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv4_prefixlen = 7; -  int idx_number_2 = 9; -  int idx_number_3 = 11; -  return vty_prefix_list_uninstall (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv4_prefixlen]->arg, argv[idx_number_3]->arg, argv[idx_number_2]->arg); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv4_prefixlen = 7; +	int idx_number_2 = 9; +	int idx_number_3 = 11; +	return vty_prefix_list_uninstall( +		vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv4_prefixlen]->arg, +		argv[idx_number_3]->arg, argv[idx_number_2]->arg);  }  DEFUN (ip_prefix_list_sequence_number, @@ -1889,8 +1816,8 @@ DEFUN (ip_prefix_list_sequence_number,         PREFIX_LIST_STR         "Include/exclude sequence numbers in NVGEN\n")  { -  prefix_master_ipv4.seqnum = 1; -  return CMD_SUCCESS; +	prefix_master_ipv4.seqnum = 1; +	return CMD_SUCCESS;  }  DEFUN (no_ip_prefix_list_sequence_number, @@ -1901,8 +1828,8 @@ DEFUN (no_ip_prefix_list_sequence_number,         PREFIX_LIST_STR         "Include/exclude sequence numbers in NVGEN\n")  { -  prefix_master_ipv4.seqnum = 0; -  return CMD_SUCCESS; +	prefix_master_ipv4.seqnum = 0; +	return CMD_SUCCESS;  }  DEFUN (ip_prefix_list_description, @@ -1914,20 +1841,19 @@ DEFUN (ip_prefix_list_description,         "Prefix-list specific description\n"         "Up to 80 characters describing this prefix-list\n")  { -  int idx_word = 2; -  int idx_line = 4; -  struct prefix_list *plist; +	int idx_word = 2; +	int idx_line = 4; +	struct prefix_list *plist; + +	plist = prefix_list_get(AFI_IP, 0, argv[idx_word]->arg); -  plist = prefix_list_get (AFI_IP, 0, argv[idx_word]->arg); -   -  if (plist->desc) -    { -      XFREE (MTYPE_TMP, plist->desc); -      plist->desc = NULL; -    } -  plist->desc = argv_concat(argv, argc, idx_line); +	if (plist->desc) { +		XFREE(MTYPE_TMP, plist->desc); +		plist->desc = NULL; +	} +	plist->desc = argv_concat(argv, argc, idx_line); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_ip_prefix_list_description, @@ -1939,8 +1865,8 @@ DEFUN (no_ip_prefix_list_description,         "Name of a prefix list\n"         "Prefix-list specific description\n")  { -  int idx_word = 3; -  return vty_prefix_list_desc_unset (vty, AFI_IP, argv[idx_word]->arg); +	int idx_word = 3; +	return vty_prefix_list_desc_unset(vty, AFI_IP, argv[idx_word]->arg);  }  /* ALIAS_FIXME */ @@ -1954,7 +1880,7 @@ DEFUN (no_ip_prefix_list_description_comment,         "Prefix-list specific description\n"         "Up to 80 characters describing this prefix-list\n")  { -  return no_ip_prefix_list_description (self, vty, argc, argv); +	return no_ip_prefix_list_description(self, vty, argc, argv);  }  DEFUN (show_ip_prefix_list, @@ -1964,7 +1890,7 @@ DEFUN (show_ip_prefix_list,         IP_STR         PREFIX_LIST_STR)  { -  return vty_show_prefix_list (vty, AFI_IP, NULL, NULL, normal_display); +	return vty_show_prefix_list(vty, AFI_IP, NULL, NULL, normal_display);  }  DEFUN (show_ip_prefix_list_name, @@ -1975,8 +1901,9 @@ DEFUN (show_ip_prefix_list_name,         PREFIX_LIST_STR         "Name of a prefix list\n")  { -  int idx_word = 3; -  return vty_show_prefix_list (vty, AFI_IP, argv[idx_word]->arg, NULL, normal_display); +	int idx_word = 3; +	return vty_show_prefix_list(vty, AFI_IP, argv[idx_word]->arg, NULL, +				    normal_display);  }  DEFUN (show_ip_prefix_list_name_seq, @@ -1989,9 +1916,10 @@ DEFUN (show_ip_prefix_list_name_seq,         "sequence number of an entry\n"         "Sequence number\n")  { -  int idx_word = 3; -  int idx_number = 5; -  return vty_show_prefix_list (vty, AFI_IP, argv[idx_word]->arg, argv[idx_number]->arg, sequential_display); +	int idx_word = 3; +	int idx_number = 5; +	return vty_show_prefix_list(vty, AFI_IP, argv[idx_word]->arg, +				    argv[idx_number]->arg, sequential_display);  }  DEFUN (show_ip_prefix_list_prefix, @@ -2003,9 +1931,11 @@ DEFUN (show_ip_prefix_list_prefix,         "Name of a prefix list\n"         "IP prefix <network>/<length>, e.g., 35.0.0.0/8\n")  { -  int idx_word = 3; -  int idx_ipv4_prefixlen = 4; -  return vty_show_prefix_list_prefix (vty, AFI_IP, argv[idx_word]->arg, argv[idx_ipv4_prefixlen]->arg, normal_display); +	int idx_word = 3; +	int idx_ipv4_prefixlen = 4; +	return vty_show_prefix_list_prefix(vty, AFI_IP, argv[idx_word]->arg, +					   argv[idx_ipv4_prefixlen]->arg, +					   normal_display);  }  DEFUN (show_ip_prefix_list_prefix_longer, @@ -2018,9 +1948,11 @@ DEFUN (show_ip_prefix_list_prefix_longer,         "IP prefix <network>/<length>, e.g., 35.0.0.0/8\n"         "Lookup longer prefix\n")  { -  int idx_word = 3; -  int idx_ipv4_prefixlen = 4; -  return vty_show_prefix_list_prefix (vty, AFI_IP, argv[idx_word]->arg, argv[idx_ipv4_prefixlen]->arg, longer_display); +	int idx_word = 3; +	int idx_ipv4_prefixlen = 4; +	return vty_show_prefix_list_prefix(vty, AFI_IP, argv[idx_word]->arg, +					   argv[idx_ipv4_prefixlen]->arg, +					   longer_display);  }  DEFUN (show_ip_prefix_list_prefix_first_match, @@ -2033,9 +1965,11 @@ DEFUN (show_ip_prefix_list_prefix_first_match,         "IP prefix <network>/<length>, e.g., 35.0.0.0/8\n"         "First matched prefix\n")  { -  int idx_word = 3; -  int idx_ipv4_prefixlen = 4; -  return vty_show_prefix_list_prefix (vty, AFI_IP, argv[idx_word]->arg, argv[idx_ipv4_prefixlen]->arg, first_match_display); +	int idx_word = 3; +	int idx_ipv4_prefixlen = 4; +	return vty_show_prefix_list_prefix(vty, AFI_IP, argv[idx_word]->arg, +					   argv[idx_ipv4_prefixlen]->arg, +					   first_match_display);  }  DEFUN (show_ip_prefix_list_summary, @@ -2046,7 +1980,7 @@ DEFUN (show_ip_prefix_list_summary,         PREFIX_LIST_STR         "Summary of prefix lists\n")  { -  return vty_show_prefix_list (vty, AFI_IP, NULL, NULL, summary_display); +	return vty_show_prefix_list(vty, AFI_IP, NULL, NULL, summary_display);  }  DEFUN (show_ip_prefix_list_summary_name, @@ -2058,8 +1992,9 @@ DEFUN (show_ip_prefix_list_summary_name,         "Summary of prefix lists\n"         "Name of a prefix list\n")  { -  int idx_word = 4; -  return vty_show_prefix_list (vty, AFI_IP, argv[idx_word]->arg, NULL, summary_display); +	int idx_word = 4; +	return vty_show_prefix_list(vty, AFI_IP, argv[idx_word]->arg, NULL, +				    summary_display);  } @@ -2071,7 +2006,7 @@ DEFUN (show_ip_prefix_list_detail,         PREFIX_LIST_STR         "Detail of prefix lists\n")  { -  return vty_show_prefix_list (vty, AFI_IP, NULL, NULL, detail_display); +	return vty_show_prefix_list(vty, AFI_IP, NULL, NULL, detail_display);  }  DEFUN (show_ip_prefix_list_detail_name, @@ -2083,8 +2018,9 @@ DEFUN (show_ip_prefix_list_detail_name,         "Detail of prefix lists\n"         "Name of a prefix list\n")  { -  int idx_word = 4; -  return vty_show_prefix_list (vty, AFI_IP, argv[idx_word]->arg, NULL, detail_display); +	int idx_word = 4; +	return vty_show_prefix_list(vty, AFI_IP, argv[idx_word]->arg, NULL, +				    detail_display);  }  DEFUN (clear_ip_prefix_list, @@ -2094,7 +2030,7 @@ DEFUN (clear_ip_prefix_list,         IP_STR         PREFIX_LIST_STR)  { -  return vty_clear_prefix_list (vty, AFI_IP, NULL, NULL); +	return vty_clear_prefix_list(vty, AFI_IP, NULL, NULL);  }  DEFUN (clear_ip_prefix_list_name, @@ -2105,8 +2041,8 @@ DEFUN (clear_ip_prefix_list_name,         PREFIX_LIST_STR         "Name of a prefix list\n")  { -  int idx_word = 3; -  return vty_clear_prefix_list (vty, AFI_IP, argv[idx_word]->arg, NULL); +	int idx_word = 3; +	return vty_clear_prefix_list(vty, AFI_IP, argv[idx_word]->arg, NULL);  }  DEFUN (clear_ip_prefix_list_name_prefix, @@ -2118,9 +2054,10 @@ DEFUN (clear_ip_prefix_list_name_prefix,         "Name of a prefix list\n"         "IP prefix <network>/<length>, e.g., 35.0.0.0/8\n")  { -  int idx_word = 3; -  int idx_ipv4_prefixlen = 4; -  return vty_clear_prefix_list (vty, AFI_IP, argv[idx_word]->arg, argv[idx_ipv4_prefixlen]->arg); +	int idx_word = 3; +	int idx_ipv4_prefixlen = 4; +	return vty_clear_prefix_list(vty, AFI_IP, argv[idx_word]->arg, +				     argv[idx_ipv4_prefixlen]->arg);  }  DEFUN (ipv6_prefix_list, @@ -2134,11 +2071,12 @@ DEFUN (ipv6_prefix_list,         "IPv6 prefix <network>/<length>, e.g., 3ffe::/16\n"         "Any prefix match.  Same as \"::0/0 le 128\"\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv6_any = 4; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, NULL,  -				  argv[idx_permit_deny]->arg, argv[idx_ipv6_any]->arg, NULL, NULL); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv6_any = 4; +	return vty_prefix_list_install(vty, AFI_IP6, argv[idx_word]->arg, NULL, +				       argv[idx_permit_deny]->arg, +				       argv[idx_ipv6_any]->arg, NULL, NULL);  }  DEFUN (ipv6_prefix_list_ge, @@ -2153,12 +2091,14 @@ DEFUN (ipv6_prefix_list_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv6_prefixlen = 4; -  int idx_number = 6; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg,  -				 argv[idx_ipv6_prefixlen]->arg, argv[idx_number]->arg, NULL); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv6_prefixlen = 4; +	int idx_number = 6; +	return vty_prefix_list_install(vty, AFI_IP6, argv[idx_word]->arg, NULL, +				       argv[idx_permit_deny]->arg, +				       argv[idx_ipv6_prefixlen]->arg, +				       argv[idx_number]->arg, NULL);  }  DEFUN (ipv6_prefix_list_ge_le, @@ -2174,15 +2114,16 @@ DEFUN (ipv6_prefix_list_ge_le,         "Minimum prefix length\n"         "Maximum prefix length to be matched\n"         "Maximum prefix length\n") -  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv6_prefixlen = 4; -  int idx_number = 6; -  int idx_number_2 = 8; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg,  -				  argv[idx_ipv6_prefixlen]->arg, argv[idx_number]->arg, argv[idx_number_2]->arg); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv6_prefixlen = 4; +	int idx_number = 6; +	int idx_number_2 = 8; +	return vty_prefix_list_install( +		vty, AFI_IP6, argv[idx_word]->arg, NULL, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number]->arg, argv[idx_number_2]->arg);  }  DEFUN (ipv6_prefix_list_le, @@ -2197,12 +2138,14 @@ DEFUN (ipv6_prefix_list_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv6_prefixlen = 4; -  int idx_number = 6; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				  argv[idx_ipv6_prefixlen]->arg, NULL, argv[idx_number]->arg); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv6_prefixlen = 4; +	int idx_number = 6; +	return vty_prefix_list_install(vty, AFI_IP6, argv[idx_word]->arg, NULL, +				       argv[idx_permit_deny]->arg, +				       argv[idx_ipv6_prefixlen]->arg, NULL, +				       argv[idx_number]->arg);  }  DEFUN (ipv6_prefix_list_le_ge, @@ -2219,13 +2162,15 @@ DEFUN (ipv6_prefix_list_le_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_ipv6_prefixlen = 4; -  int idx_number = 6; -  int idx_number_2 = 8; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				  argv[idx_ipv6_prefixlen]->arg, argv[idx_number_2]->arg, argv[idx_number]->arg); +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_ipv6_prefixlen = 4; +	int idx_number = 6; +	int idx_number_2 = 8; +	return vty_prefix_list_install( +		vty, AFI_IP6, argv[idx_word]->arg, NULL, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number_2]->arg, argv[idx_number]->arg);  }  DEFUN (ipv6_prefix_list_seq, @@ -2241,12 +2186,14 @@ DEFUN (ipv6_prefix_list_seq,         "IPv6 prefix <network>/<length>, e.g., 3ffe::/16\n"         "Any prefix match.  Same as \"::0/0 le 128\"\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv6_any = 6; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv6_any]->arg, NULL, NULL); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv6_any = 6; +	return vty_prefix_list_install(vty, AFI_IP6, argv[idx_word]->arg, +				       argv[idx_number]->arg, +				       argv[idx_permit_deny]->arg, +				       argv[idx_ipv6_any]->arg, NULL, NULL);  }  DEFUN (ipv6_prefix_list_seq_ge, @@ -2263,13 +2210,15 @@ DEFUN (ipv6_prefix_list_seq_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv6_prefixlen = 6; -  int idx_number_2 = 8; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv6_prefixlen]->arg, argv[idx_number_2]->arg, NULL); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv6_prefixlen = 6; +	int idx_number_2 = 8; +	return vty_prefix_list_install( +		vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number_2]->arg, NULL);  }  DEFUN (ipv6_prefix_list_seq_ge_le, @@ -2288,14 +2237,16 @@ DEFUN (ipv6_prefix_list_seq_ge_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv6_prefixlen = 6; -  int idx_number_2 = 8; -  int idx_number_3 = 10; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv6_prefixlen]->arg, argv[idx_number_2]->arg, argv[idx_number_3]->arg); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv6_prefixlen = 6; +	int idx_number_2 = 8; +	int idx_number_3 = 10; +	return vty_prefix_list_install( +		vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number_2]->arg, argv[idx_number_3]->arg);  }  DEFUN (ipv6_prefix_list_seq_le, @@ -2312,13 +2263,15 @@ DEFUN (ipv6_prefix_list_seq_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv6_prefixlen = 6; -  int idx_number_2 = 8; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv6_prefixlen]->arg, NULL, argv[idx_number_2]->arg); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv6_prefixlen = 6; +	int idx_number_2 = 8; +	return vty_prefix_list_install( +		vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, NULL, +		argv[idx_number_2]->arg);  }  DEFUN (ipv6_prefix_list_seq_le_ge, @@ -2337,14 +2290,16 @@ DEFUN (ipv6_prefix_list_seq_le_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 2; -  int idx_number = 4; -  int idx_permit_deny = 5; -  int idx_ipv6_prefixlen = 6; -  int idx_number_2 = 8; -  int idx_number_3 = 10; -  return vty_prefix_list_install (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				  argv[idx_ipv6_prefixlen]->arg, argv[idx_number_3]->arg, argv[idx_number_2]->arg); +	int idx_word = 2; +	int idx_number = 4; +	int idx_permit_deny = 5; +	int idx_ipv6_prefixlen = 6; +	int idx_number_2 = 8; +	int idx_number_3 = 10; +	return vty_prefix_list_install( +		vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number_3]->arg, argv[idx_number_2]->arg);  }  DEFUN (no_ipv6_prefix_list, @@ -2355,9 +2310,9 @@ DEFUN (no_ipv6_prefix_list,         PREFIX_LIST_STR         "Name of a prefix list\n")  { -  int idx_word = 3; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, NULL, NULL, -				    NULL, NULL, NULL); +	int idx_word = 3; +	return vty_prefix_list_uninstall(vty, AFI_IP6, argv[idx_word]->arg, +					 NULL, NULL, NULL, NULL, NULL);  }  DEFUN (no_ipv6_prefix_list_prefix, @@ -2372,11 +2327,12 @@ DEFUN (no_ipv6_prefix_list_prefix,         "IPv6 prefix <network>/<length>, e.g., 3ffe::/16\n"         "Any prefix match.  Same as \"::0/0 le 128\"\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv6_any = 5; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_any]->arg, NULL, NULL); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv6_any = 5; +	return vty_prefix_list_uninstall(vty, AFI_IP6, argv[idx_word]->arg, +					 NULL, argv[idx_permit_deny]->arg, +					 argv[idx_ipv6_any]->arg, NULL, NULL);  }  DEFUN (no_ipv6_prefix_list_ge, @@ -2392,12 +2348,14 @@ DEFUN (no_ipv6_prefix_list_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv6_prefixlen = 5; -  int idx_number = 7; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_prefixlen]->arg, argv[idx_number]->arg, NULL); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv6_prefixlen = 5; +	int idx_number = 7; +	return vty_prefix_list_uninstall(vty, AFI_IP6, argv[idx_word]->arg, +					 NULL, argv[idx_permit_deny]->arg, +					 argv[idx_ipv6_prefixlen]->arg, +					 argv[idx_number]->arg, NULL);  }  DEFUN (no_ipv6_prefix_list_ge_le, @@ -2415,13 +2373,15 @@ DEFUN (no_ipv6_prefix_list_ge_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv6_prefixlen = 5; -  int idx_number = 7; -  int idx_number_2 = 9; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_prefixlen]->arg, argv[idx_number]->arg, argv[idx_number_2]->arg); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv6_prefixlen = 5; +	int idx_number = 7; +	int idx_number_2 = 9; +	return vty_prefix_list_uninstall( +		vty, AFI_IP6, argv[idx_word]->arg, NULL, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number]->arg, argv[idx_number_2]->arg);  }  DEFUN (no_ipv6_prefix_list_le, @@ -2437,12 +2397,14 @@ DEFUN (no_ipv6_prefix_list_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv6_prefixlen = 5; -  int idx_number = 7; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_prefixlen]->arg, NULL, argv[idx_number]->arg); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv6_prefixlen = 5; +	int idx_number = 7; +	return vty_prefix_list_uninstall(vty, AFI_IP6, argv[idx_word]->arg, +					 NULL, argv[idx_permit_deny]->arg, +					 argv[idx_ipv6_prefixlen]->arg, NULL, +					 argv[idx_number]->arg);  }  DEFUN (no_ipv6_prefix_list_le_ge, @@ -2460,13 +2422,15 @@ DEFUN (no_ipv6_prefix_list_le_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 3; -  int idx_permit_deny = 4; -  int idx_ipv6_prefixlen = 5; -  int idx_number = 7; -  int idx_number_2 = 9; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, NULL, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_prefixlen]->arg, argv[idx_number_2]->arg, argv[idx_number]->arg); +	int idx_word = 3; +	int idx_permit_deny = 4; +	int idx_ipv6_prefixlen = 5; +	int idx_number = 7; +	int idx_number_2 = 9; +	return vty_prefix_list_uninstall( +		vty, AFI_IP6, argv[idx_word]->arg, NULL, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number_2]->arg, argv[idx_number]->arg);  }  DEFUN (no_ipv6_prefix_list_seq, @@ -2483,12 +2447,14 @@ DEFUN (no_ipv6_prefix_list_seq,         "IPv6 prefix <network>/<length>, e.g., 3ffe::/16\n"         "Any prefix match.  Same as \"::0/0 le 128\"\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv6_any = 7; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_any]->arg, NULL, NULL); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv6_any = 7; +	return vty_prefix_list_uninstall(vty, AFI_IP6, argv[idx_word]->arg, +					 argv[idx_number]->arg, +					 argv[idx_permit_deny]->arg, +					 argv[idx_ipv6_any]->arg, NULL, NULL);  }  DEFUN (no_ipv6_prefix_list_seq_ge, @@ -2506,13 +2472,15 @@ DEFUN (no_ipv6_prefix_list_seq_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv6_prefixlen = 7; -  int idx_number_2 = 9; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_prefixlen]->arg, argv[idx_number_2]->arg, NULL); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv6_prefixlen = 7; +	int idx_number_2 = 9; +	return vty_prefix_list_uninstall( +		vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number_2]->arg, NULL);  }  DEFUN (no_ipv6_prefix_list_seq_ge_le, @@ -2532,14 +2500,16 @@ DEFUN (no_ipv6_prefix_list_seq_ge_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv6_prefixlen = 7; -  int idx_number_2 = 9; -  int idx_number_3 = 11; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_prefixlen]->arg, argv[idx_number_2]->arg, argv[idx_number_3]->arg); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv6_prefixlen = 7; +	int idx_number_2 = 9; +	int idx_number_3 = 11; +	return vty_prefix_list_uninstall( +		vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number_2]->arg, argv[idx_number_3]->arg);  }  DEFUN (no_ipv6_prefix_list_seq_le, @@ -2557,13 +2527,15 @@ DEFUN (no_ipv6_prefix_list_seq_le,         "Maximum prefix length to be matched\n"         "Maximum prefix length\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv6_prefixlen = 7; -  int idx_number_2 = 9; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_prefixlen]->arg, NULL, argv[idx_number_2]->arg); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv6_prefixlen = 7; +	int idx_number_2 = 9; +	return vty_prefix_list_uninstall( +		vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, NULL, +		argv[idx_number_2]->arg);  }  DEFUN (no_ipv6_prefix_list_seq_le_ge, @@ -2583,14 +2555,16 @@ DEFUN (no_ipv6_prefix_list_seq_le_ge,         "Minimum prefix length to be matched\n"         "Minimum prefix length\n")  { -  int idx_word = 3; -  int idx_number = 5; -  int idx_permit_deny = 6; -  int idx_ipv6_prefixlen = 7; -  int idx_number_2 = 9; -  int idx_number_3 = 11; -  return vty_prefix_list_uninstall (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, argv[idx_permit_deny]->arg, -				    argv[idx_ipv6_prefixlen]->arg, argv[idx_number_3]->arg, argv[idx_number_2]->arg); +	int idx_word = 3; +	int idx_number = 5; +	int idx_permit_deny = 6; +	int idx_ipv6_prefixlen = 7; +	int idx_number_2 = 9; +	int idx_number_3 = 11; +	return vty_prefix_list_uninstall( +		vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, +		argv[idx_permit_deny]->arg, argv[idx_ipv6_prefixlen]->arg, +		argv[idx_number_3]->arg, argv[idx_number_2]->arg);  }  DEFUN (ipv6_prefix_list_sequence_number, @@ -2600,8 +2574,8 @@ DEFUN (ipv6_prefix_list_sequence_number,         PREFIX_LIST_STR         "Include/exclude sequence numbers in NVGEN\n")  { -  prefix_master_ipv6.seqnum = 1; -  return CMD_SUCCESS; +	prefix_master_ipv6.seqnum = 1; +	return CMD_SUCCESS;  }  DEFUN (no_ipv6_prefix_list_sequence_number, @@ -2612,8 +2586,8 @@ DEFUN (no_ipv6_prefix_list_sequence_number,         PREFIX_LIST_STR         "Include/exclude sequence numbers in NVGEN\n")  { -  prefix_master_ipv6.seqnum = 0; -  return CMD_SUCCESS; +	prefix_master_ipv6.seqnum = 0; +	return CMD_SUCCESS;  }  DEFUN (ipv6_prefix_list_description, @@ -2625,20 +2599,19 @@ DEFUN (ipv6_prefix_list_description,         "Prefix-list specific description\n"         "Up to 80 characters describing this prefix-list\n")  { -  int idx_word = 2; -  int iddx_line = 4; -  struct prefix_list *plist; +	int idx_word = 2; +	int iddx_line = 4; +	struct prefix_list *plist; + +	plist = prefix_list_get(AFI_IP6, 0, argv[idx_word]->arg); -  plist = prefix_list_get (AFI_IP6, 0, argv[idx_word]->arg); -   -  if (plist->desc) -    { -      XFREE (MTYPE_TMP, plist->desc); -      plist->desc = NULL; -    } -  plist->desc = argv_concat(argv, argc, iddx_line); +	if (plist->desc) { +		XFREE(MTYPE_TMP, plist->desc); +		plist->desc = NULL; +	} +	plist->desc = argv_concat(argv, argc, iddx_line); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_ipv6_prefix_list_description, @@ -2650,8 +2623,8 @@ DEFUN (no_ipv6_prefix_list_description,         "Name of a prefix list\n"         "Prefix-list specific description\n")  { -  int idx_word = 3; -  return vty_prefix_list_desc_unset (vty, AFI_IP6, argv[idx_word]->arg); +	int idx_word = 3; +	return vty_prefix_list_desc_unset(vty, AFI_IP6, argv[idx_word]->arg);  }  /* ALIAS_FIXME */ @@ -2665,7 +2638,7 @@ DEFUN (no_ipv6_prefix_list_description_comment,         "Prefix-list specific description\n"         "Up to 80 characters describing this prefix-list\n")  { -  return no_ipv6_prefix_list_description (self, vty, argc, argv); +	return no_ipv6_prefix_list_description(self, vty, argc, argv);  } @@ -2676,7 +2649,7 @@ DEFUN (show_ipv6_prefix_list,         IPV6_STR         PREFIX_LIST_STR)  { -  return vty_show_prefix_list (vty, AFI_IP6, NULL, NULL, normal_display); +	return vty_show_prefix_list(vty, AFI_IP6, NULL, NULL, normal_display);  }  DEFUN (show_ipv6_prefix_list_name, @@ -2687,8 +2660,9 @@ DEFUN (show_ipv6_prefix_list_name,         PREFIX_LIST_STR         "Name of a prefix list\n")  { -  int idx_word = 3; -  return vty_show_prefix_list (vty, AFI_IP6, argv[idx_word]->arg, NULL, normal_display); +	int idx_word = 3; +	return vty_show_prefix_list(vty, AFI_IP6, argv[idx_word]->arg, NULL, +				    normal_display);  }  DEFUN (show_ipv6_prefix_list_name_seq, @@ -2701,9 +2675,10 @@ DEFUN (show_ipv6_prefix_list_name_seq,         "sequence number of an entry\n"         "Sequence number\n")  { -  int idx_word = 3; -  int idx_number = 5; -  return vty_show_prefix_list (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_number]->arg, sequential_display); +	int idx_word = 3; +	int idx_number = 5; +	return vty_show_prefix_list(vty, AFI_IP6, argv[idx_word]->arg, +				    argv[idx_number]->arg, sequential_display);  }  DEFUN (show_ipv6_prefix_list_prefix, @@ -2715,9 +2690,11 @@ DEFUN (show_ipv6_prefix_list_prefix,         "Name of a prefix list\n"         "IPv6 prefix <network>/<length>, e.g., 3ffe::/16\n")  { -  int idx_word = 3; -  int idx_ipv6_prefixlen = 4; -  return vty_show_prefix_list_prefix (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_ipv6_prefixlen]->arg, normal_display); +	int idx_word = 3; +	int idx_ipv6_prefixlen = 4; +	return vty_show_prefix_list_prefix(vty, AFI_IP6, argv[idx_word]->arg, +					   argv[idx_ipv6_prefixlen]->arg, +					   normal_display);  }  DEFUN (show_ipv6_prefix_list_prefix_longer, @@ -2730,9 +2707,11 @@ DEFUN (show_ipv6_prefix_list_prefix_longer,         "IPv6 prefix <network>/<length>, e.g., 3ffe::/16\n"         "Lookup longer prefix\n")  { -  int idx_word = 3; -  int idx_ipv6_prefixlen = 4; -  return vty_show_prefix_list_prefix (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_ipv6_prefixlen]->arg, longer_display); +	int idx_word = 3; +	int idx_ipv6_prefixlen = 4; +	return vty_show_prefix_list_prefix(vty, AFI_IP6, argv[idx_word]->arg, +					   argv[idx_ipv6_prefixlen]->arg, +					   longer_display);  }  DEFUN (show_ipv6_prefix_list_prefix_first_match, @@ -2745,9 +2724,11 @@ DEFUN (show_ipv6_prefix_list_prefix_first_match,         "IPv6 prefix <network>/<length>, e.g., 3ffe::/16\n"         "First matched prefix\n")  { -  int idx_word = 3; -  int idx_ipv6_prefixlen = 4; -  return vty_show_prefix_list_prefix (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_ipv6_prefixlen]->arg, first_match_display); +	int idx_word = 3; +	int idx_ipv6_prefixlen = 4; +	return vty_show_prefix_list_prefix(vty, AFI_IP6, argv[idx_word]->arg, +					   argv[idx_ipv6_prefixlen]->arg, +					   first_match_display);  }  DEFUN (show_ipv6_prefix_list_summary, @@ -2758,7 +2739,7 @@ DEFUN (show_ipv6_prefix_list_summary,         PREFIX_LIST_STR         "Summary of prefix lists\n")  { -  return vty_show_prefix_list (vty, AFI_IP6, NULL, NULL, summary_display); +	return vty_show_prefix_list(vty, AFI_IP6, NULL, NULL, summary_display);  }  DEFUN (show_ipv6_prefix_list_summary_name, @@ -2770,8 +2751,9 @@ DEFUN (show_ipv6_prefix_list_summary_name,         "Summary of prefix lists\n"         "Name of a prefix list\n")  { -  int idx_word = 4; -  return vty_show_prefix_list (vty, AFI_IP6, argv[idx_word]->arg, NULL, summary_display); +	int idx_word = 4; +	return vty_show_prefix_list(vty, AFI_IP6, argv[idx_word]->arg, NULL, +				    summary_display);  }  DEFUN (show_ipv6_prefix_list_detail, @@ -2782,7 +2764,7 @@ DEFUN (show_ipv6_prefix_list_detail,         PREFIX_LIST_STR         "Detail of prefix lists\n")  { -  return vty_show_prefix_list (vty, AFI_IP6, NULL, NULL, detail_display); +	return vty_show_prefix_list(vty, AFI_IP6, NULL, NULL, detail_display);  }  DEFUN (show_ipv6_prefix_list_detail_name, @@ -2794,8 +2776,9 @@ DEFUN (show_ipv6_prefix_list_detail_name,         "Detail of prefix lists\n"         "Name of a prefix list\n")  { -  int idx_word = 4; -  return vty_show_prefix_list (vty, AFI_IP6, argv[idx_word]->arg, NULL, detail_display); +	int idx_word = 4; +	return vty_show_prefix_list(vty, AFI_IP6, argv[idx_word]->arg, NULL, +				    detail_display);  }  DEFUN (clear_ipv6_prefix_list, @@ -2805,7 +2788,7 @@ DEFUN (clear_ipv6_prefix_list,         IPV6_STR         PREFIX_LIST_STR)  { -  return vty_clear_prefix_list (vty, AFI_IP6, NULL, NULL); +	return vty_clear_prefix_list(vty, AFI_IP6, NULL, NULL);  }  DEFUN (clear_ipv6_prefix_list_name, @@ -2816,8 +2799,8 @@ DEFUN (clear_ipv6_prefix_list_name,         PREFIX_LIST_STR         "Name of a prefix list\n")  { -  int idx_word = 3; -  return vty_clear_prefix_list (vty, AFI_IP6, argv[idx_word]->arg, NULL); +	int idx_word = 3; +	return vty_clear_prefix_list(vty, AFI_IP6, argv[idx_word]->arg, NULL);  }  DEFUN (clear_ipv6_prefix_list_name_prefix, @@ -2829,461 +2812,439 @@ DEFUN (clear_ipv6_prefix_list_name_prefix,         "Name of a prefix list\n"         "IPv6 prefix <network>/<length>, e.g., 3ffe::/16\n")  { -  int idx_word = 3; -  int idx_ipv6_prefixlen = 4; -  return vty_clear_prefix_list (vty, AFI_IP6, argv[idx_word]->arg, argv[idx_ipv6_prefixlen]->arg); +	int idx_word = 3; +	int idx_ipv6_prefixlen = 4; +	return vty_clear_prefix_list(vty, AFI_IP6, argv[idx_word]->arg, +				     argv[idx_ipv6_prefixlen]->arg);  }  /* Configuration write function. */ -static int -config_write_prefix_afi (afi_t afi, struct vty *vty) -{ -  struct prefix_list *plist; -  struct prefix_list_entry *pentry; -  struct prefix_master *master; -  int write = 0; - -  master = prefix_master_get (afi, 0); -  if (master == NULL) -    return 0; - -  if (! master->seqnum) -    { -      vty_out (vty, "no ip%s prefix-list sequence-number%s",  -	       afi == AFI_IP ? "" : "v6", VTY_NEWLINE); -      vty_out (vty, "!%s", VTY_NEWLINE); -    } - -  for (plist = master->num.head; plist; plist = plist->next) -    { -      if (plist->desc) -	{ -	  vty_out (vty, "ip%s prefix-list %s description %s%s", -		   afi == AFI_IP ? "" : "v6", -		   plist->name, plist->desc, VTY_NEWLINE); -	  write++; -	} +static int config_write_prefix_afi(afi_t afi, struct vty *vty) +{ +	struct prefix_list *plist; +	struct prefix_list_entry *pentry; +	struct prefix_master *master; +	int write = 0; -      for (pentry = plist->head; pentry; pentry = pentry->next) -	{ -	  vty_out (vty, "ip%s prefix-list %s ", -		   afi == AFI_IP ? "" : "v6", -		   plist->name); - -	  if (master->seqnum) -	    vty_out (vty, "seq %u ", pentry->seq); -	 -	  vty_out (vty, "%s ", prefix_list_type_str (pentry)); - -	  if (pentry->any) -	    vty_out (vty, "any"); -	  else -	    { -	      struct prefix *p = &pentry->prefix; -	      char buf[BUFSIZ]; - -	      vty_out (vty, "%s/%d", -		       inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -		       p->prefixlen); - -	      if (pentry->ge) -		vty_out (vty, " ge %d", pentry->ge); -	      if (pentry->le) -		vty_out (vty, " le %d", pentry->le); -	    } -	  vty_out (vty, "%s", VTY_NEWLINE); -	  write++; +	master = prefix_master_get(afi, 0); +	if (master == NULL) +		return 0; + +	if (!master->seqnum) { +		vty_out(vty, "no ip%s prefix-list sequence-number%s", +			afi == AFI_IP ? "" : "v6", VTY_NEWLINE); +		vty_out(vty, "!%s", VTY_NEWLINE);  	} -      /* vty_out (vty, "!%s", VTY_NEWLINE); */ -    } - -  for (plist = master->str.head; plist; plist = plist->next) -    { -      if (plist->desc) -	{ -	  vty_out (vty, "ip%s prefix-list %s description %s%s", -		   afi == AFI_IP ? "" : "v6", -		   plist->name, plist->desc, VTY_NEWLINE); -	  write++; + +	for (plist = master->num.head; plist; plist = plist->next) { +		if (plist->desc) { +			vty_out(vty, "ip%s prefix-list %s description %s%s", +				afi == AFI_IP ? "" : "v6", plist->name, +				plist->desc, VTY_NEWLINE); +			write++; +		} + +		for (pentry = plist->head; pentry; pentry = pentry->next) { +			vty_out(vty, "ip%s prefix-list %s ", +				afi == AFI_IP ? "" : "v6", plist->name); + +			if (master->seqnum) +				vty_out(vty, "seq %u ", pentry->seq); + +			vty_out(vty, "%s ", prefix_list_type_str(pentry)); + +			if (pentry->any) +				vty_out(vty, "any"); +			else { +				struct prefix *p = &pentry->prefix; +				char buf[BUFSIZ]; + +				vty_out(vty, "%s/%d", +					inet_ntop(p->family, &p->u.prefix, buf, +						  BUFSIZ), +					p->prefixlen); + +				if (pentry->ge) +					vty_out(vty, " ge %d", pentry->ge); +				if (pentry->le) +					vty_out(vty, " le %d", pentry->le); +			} +			vty_out(vty, "%s", VTY_NEWLINE); +			write++; +		} +		/* vty_out (vty, "!%s", VTY_NEWLINE); */  	} -      for (pentry = plist->head; pentry; pentry = pentry->next) -	{ -	  vty_out (vty, "ip%s prefix-list %s ", -		   afi == AFI_IP ? "" : "v6", -		   plist->name); - -	  if (master->seqnum) -	    vty_out (vty, "seq %u ", pentry->seq); - -	  vty_out (vty, "%s", prefix_list_type_str (pentry)); - -	  if (pentry->any) -	    vty_out (vty, " any"); -	  else -	    { -	      struct prefix *p = &pentry->prefix; -	      char buf[BUFSIZ]; - -	      vty_out (vty, " %s/%d", -		       inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -		       p->prefixlen); - -	      if (pentry->ge) -		vty_out (vty, " ge %d", pentry->ge); -	      if (pentry->le) -		vty_out (vty, " le %d", pentry->le); -	    } -	  vty_out (vty, "%s", VTY_NEWLINE); -	  write++; +	for (plist = master->str.head; plist; plist = plist->next) { +		if (plist->desc) { +			vty_out(vty, "ip%s prefix-list %s description %s%s", +				afi == AFI_IP ? "" : "v6", plist->name, +				plist->desc, VTY_NEWLINE); +			write++; +		} + +		for (pentry = plist->head; pentry; pentry = pentry->next) { +			vty_out(vty, "ip%s prefix-list %s ", +				afi == AFI_IP ? "" : "v6", plist->name); + +			if (master->seqnum) +				vty_out(vty, "seq %u ", pentry->seq); + +			vty_out(vty, "%s", prefix_list_type_str(pentry)); + +			if (pentry->any) +				vty_out(vty, " any"); +			else { +				struct prefix *p = &pentry->prefix; +				char buf[BUFSIZ]; + +				vty_out(vty, " %s/%d", +					inet_ntop(p->family, &p->u.prefix, buf, +						  BUFSIZ), +					p->prefixlen); + +				if (pentry->ge) +					vty_out(vty, " ge %d", pentry->ge); +				if (pentry->le) +					vty_out(vty, " le %d", pentry->le); +			} +			vty_out(vty, "%s", VTY_NEWLINE); +			write++; +		}  	} -    } -   -  return write; + +	return write;  } -struct stream * -prefix_bgp_orf_entry (struct stream *s, struct prefix_list *plist, -		      u_char init_flag, u_char permit_flag, u_char deny_flag) +struct stream *prefix_bgp_orf_entry(struct stream *s, struct prefix_list *plist, +				    u_char init_flag, u_char permit_flag, +				    u_char deny_flag)  { -  struct prefix_list_entry *pentry; +	struct prefix_list_entry *pentry; -  if (! plist) -    return s; +	if (!plist) +		return s; -  for (pentry = plist->head; pentry; pentry = pentry->next) -    { -      u_char flag = init_flag; -      struct prefix *p = &pentry->prefix; +	for (pentry = plist->head; pentry; pentry = pentry->next) { +		u_char flag = init_flag; +		struct prefix *p = &pentry->prefix; -      flag |= (pentry->type == PREFIX_PERMIT ? -               permit_flag : deny_flag); -      stream_putc (s, flag); -      stream_putl (s, (u_int32_t)pentry->seq); -      stream_putc (s, (u_char)pentry->ge); -      stream_putc (s, (u_char)pentry->le); -      stream_put_prefix (s, p); -    } +		flag |= (pentry->type == PREFIX_PERMIT ? permit_flag +						       : deny_flag); +		stream_putc(s, flag); +		stream_putl(s, (u_int32_t)pentry->seq); +		stream_putc(s, (u_char)pentry->ge); +		stream_putc(s, (u_char)pentry->le); +		stream_put_prefix(s, p); +	} -  return s; +	return s;  } -int -prefix_bgp_orf_set (char *name, afi_t afi, struct orf_prefix *orfp, -		    int permit, int set) +int prefix_bgp_orf_set(char *name, afi_t afi, struct orf_prefix *orfp, +		       int permit, int set)  { -  struct prefix_list *plist; -  struct prefix_list_entry *pentry; +	struct prefix_list *plist; +	struct prefix_list_entry *pentry; -  /* ge and le value check */  -  if (orfp->ge && orfp->ge <= orfp->p.prefixlen) -    return CMD_WARNING; -  if (orfp->le && orfp->le <= orfp->p.prefixlen) -    return CMD_WARNING; -  if (orfp->le && orfp->ge > orfp->le) -    return CMD_WARNING; +	/* ge and le value check */ +	if (orfp->ge && orfp->ge <= orfp->p.prefixlen) +		return CMD_WARNING; +	if (orfp->le && orfp->le <= orfp->p.prefixlen) +		return CMD_WARNING; +	if (orfp->le && orfp->ge > orfp->le) +		return CMD_WARNING; -  if (orfp->ge && orfp->le == (afi == AFI_IP ? 32 : 128)) -    orfp->le = 0; +	if (orfp->ge && orfp->le == (afi == AFI_IP ? 32 : 128)) +		orfp->le = 0; -  plist = prefix_list_get (afi, 1, name); -  if (! plist) -    return CMD_WARNING; +	plist = prefix_list_get(afi, 1, name); +	if (!plist) +		return CMD_WARNING; -  if (set) -    { -      pentry = prefix_list_entry_make (&orfp->p, -				       (permit ? PREFIX_PERMIT : PREFIX_DENY), -				       orfp->seq, orfp->le, orfp->ge, 0); +	if (set) { +		pentry = prefix_list_entry_make( +			&orfp->p, (permit ? PREFIX_PERMIT : PREFIX_DENY), +			orfp->seq, orfp->le, orfp->ge, 0); -      if (prefix_entry_dup_check (plist, pentry)) -	{ -	  prefix_list_entry_free (pentry); -	  return CMD_WARNING; -	} +		if (prefix_entry_dup_check(plist, pentry)) { +			prefix_list_entry_free(pentry); +			return CMD_WARNING; +		} -      prefix_list_entry_add (plist, pentry); -    } -  else -    { -      pentry = prefix_list_entry_lookup (plist, &orfp->p, -					 (permit ? PREFIX_PERMIT : PREFIX_DENY), -					 orfp->seq, orfp->le, orfp->ge); +		prefix_list_entry_add(plist, pentry); +	} else { +		pentry = prefix_list_entry_lookup( +			plist, &orfp->p, (permit ? PREFIX_PERMIT : PREFIX_DENY), +			orfp->seq, orfp->le, orfp->ge); -      if (! pentry) -	return CMD_WARNING; +		if (!pentry) +			return CMD_WARNING; -      prefix_list_entry_delete (plist, pentry, 1); -    } +		prefix_list_entry_delete(plist, pentry, 1); +	} -  return CMD_SUCCESS; +	return CMD_SUCCESS;  } -void -prefix_bgp_orf_remove_all (afi_t afi, char *name) +void prefix_bgp_orf_remove_all(afi_t afi, char *name)  { -  struct prefix_list *plist; +	struct prefix_list *plist; -  plist = prefix_bgp_orf_lookup (afi, name); -  if (plist) -    prefix_list_delete (plist); +	plist = prefix_bgp_orf_lookup(afi, name); +	if (plist) +		prefix_list_delete(plist);  }  /* return prefix count */ -int -prefix_bgp_show_prefix_list (struct vty *vty, afi_t afi, char *name, u_char use_json) -{ -  struct prefix_list *plist; -  struct prefix_list_entry *pentry; -  json_object *json = NULL; -  json_object *json_prefix = NULL; -  json_object *json_list = NULL; - -  plist = prefix_bgp_orf_lookup (afi, name); -  if (! plist) -    return 0; - -  if (! vty) -    return plist->count; - -  if(use_json) -    { -      json = json_object_new_object(); -      json_prefix = json_object_new_object(); -      json_list = json_object_new_object(); - -      json_object_int_add(json_prefix, "prefixListCounter", plist->count); -      json_object_string_add(json_prefix, "prefixListName", plist->name); - -      for (pentry = plist->head; pentry; pentry = pentry->next) -        { -          struct prefix *p = &pentry->prefix; -          char buf_a[BUFSIZ]; -          char buf_b[BUFSIZ]; - -          sprintf(buf_a, "%s/%d", inet_ntop (p->family, &p->u.prefix, buf_b, BUFSIZ), -                            p->prefixlen); - -          json_object_int_add(json_list, "seq", pentry->seq); -          json_object_string_add(json_list, "seqPrefixListType", prefix_list_type_str (pentry)); - -          if (pentry->ge) -            json_object_int_add(json_list, "ge", pentry->ge); -          if (pentry->le) -            json_object_int_add(json_list, "le", pentry->le); - -          json_object_object_add(json_prefix, buf_a, json_list); -        } -      if (afi == AFI_IP) -        json_object_object_add(json, "ipPrefixList", json_prefix); -      else -        json_object_object_add(json, "ipv6PrefixList", json_prefix); - -      vty_out (vty, "%s%s", json_object_to_json_string_ext(json, JSON_C_TO_STRING_PRETTY), VTY_NEWLINE); -      json_object_free(json); -    } -  else -    { -      vty_out (vty, "ip%s prefix-list %s: %d entries%s", -               afi == AFI_IP ? "" : "v6", -               plist->name, plist->count, VTY_NEWLINE); - -      for (pentry = plist->head; pentry; pentry = pentry->next) -        { -          struct prefix *p = &pentry->prefix; -          char buf[BUFSIZ]; - -          vty_out (vty, "   seq %u %s %s/%d", pentry->seq, -                   prefix_list_type_str (pentry), -                   inet_ntop (p->family, &p->u.prefix, buf, BUFSIZ), -                   p->prefixlen); - -          if (pentry->ge) -            vty_out (vty, " ge %d", pentry->ge); -          if (pentry->le) -            vty_out (vty, " le %d", pentry->le); - -          vty_out (vty, "%s", VTY_NEWLINE); -        } -    } -  return plist->count; -} - -static void -prefix_list_reset_afi (afi_t afi, int orf) -{ -  struct prefix_list *plist; -  struct prefix_list *next; -  struct prefix_master *master; - -  master = prefix_master_get (afi, orf); -  if (master == NULL) -    return; - -  for (plist = master->num.head; plist; plist = next) -    { -      next = plist->next; -      prefix_list_delete (plist); -    } -  for (plist = master->str.head; plist; plist = next) -    { -      next = plist->next; -      prefix_list_delete (plist); -    } - -  assert (master->num.head == NULL); -  assert (master->num.tail == NULL); - -  assert (master->str.head == NULL); -  assert (master->str.tail == NULL); - -  master->seqnum = 1; -  master->recent = NULL; +int prefix_bgp_show_prefix_list(struct vty *vty, afi_t afi, char *name, +				u_char use_json) +{ +	struct prefix_list *plist; +	struct prefix_list_entry *pentry; +	json_object *json = NULL; +	json_object *json_prefix = NULL; +	json_object *json_list = NULL; + +	plist = prefix_bgp_orf_lookup(afi, name); +	if (!plist) +		return 0; + +	if (!vty) +		return plist->count; + +	if (use_json) { +		json = json_object_new_object(); +		json_prefix = json_object_new_object(); +		json_list = json_object_new_object(); + +		json_object_int_add(json_prefix, "prefixListCounter", +				    plist->count); +		json_object_string_add(json_prefix, "prefixListName", +				       plist->name); + +		for (pentry = plist->head; pentry; pentry = pentry->next) { +			struct prefix *p = &pentry->prefix; +			char buf_a[BUFSIZ]; +			char buf_b[BUFSIZ]; + +			sprintf(buf_a, "%s/%d", +				inet_ntop(p->family, &p->u.prefix, buf_b, +					  BUFSIZ), +				p->prefixlen); + +			json_object_int_add(json_list, "seq", pentry->seq); +			json_object_string_add(json_list, "seqPrefixListType", +					       prefix_list_type_str(pentry)); + +			if (pentry->ge) +				json_object_int_add(json_list, "ge", +						    pentry->ge); +			if (pentry->le) +				json_object_int_add(json_list, "le", +						    pentry->le); + +			json_object_object_add(json_prefix, buf_a, json_list); +		} +		if (afi == AFI_IP) +			json_object_object_add(json, "ipPrefixList", +					       json_prefix); +		else +			json_object_object_add(json, "ipv6PrefixList", +					       json_prefix); + +		vty_out(vty, "%s%s", json_object_to_json_string_ext( +					     json, JSON_C_TO_STRING_PRETTY), +			VTY_NEWLINE); +		json_object_free(json); +	} else { +		vty_out(vty, "ip%s prefix-list %s: %d entries%s", +			afi == AFI_IP ? "" : "v6", plist->name, plist->count, +			VTY_NEWLINE); + +		for (pentry = plist->head; pentry; pentry = pentry->next) { +			struct prefix *p = &pentry->prefix; +			char buf[BUFSIZ]; + +			vty_out(vty, "   seq %u %s %s/%d", pentry->seq, +				prefix_list_type_str(pentry), +				inet_ntop(p->family, &p->u.prefix, buf, BUFSIZ), +				p->prefixlen); + +			if (pentry->ge) +				vty_out(vty, " ge %d", pentry->ge); +			if (pentry->le) +				vty_out(vty, " le %d", pentry->le); + +			vty_out(vty, "%s", VTY_NEWLINE); +		} +	} +	return plist->count;  } - -/* Prefix-list node. */ -static struct cmd_node prefix_node = +static void prefix_list_reset_afi(afi_t afi, int orf)  { -  PREFIX_NODE, -  "",				/* Prefix list has no interface. */ -  1 -}; +	struct prefix_list *plist; +	struct prefix_list *next; +	struct prefix_master *master; + +	master = prefix_master_get(afi, orf); +	if (master == NULL) +		return; -static int -config_write_prefix_ipv4 (struct vty *vty) -{ -  return config_write_prefix_afi (AFI_IP, vty); -} - -static void -prefix_list_init_ipv4 (void) -{ -  install_node (&prefix_node, config_write_prefix_ipv4); - -  install_element (CONFIG_NODE, &ip_prefix_list_cmd); -  install_element (CONFIG_NODE, &ip_prefix_list_ge_cmd); -  install_element (CONFIG_NODE, &ip_prefix_list_ge_le_cmd); -  install_element (CONFIG_NODE, &ip_prefix_list_le_cmd); -  install_element (CONFIG_NODE, &ip_prefix_list_le_ge_cmd); -  install_element (CONFIG_NODE, &ip_prefix_list_seq_cmd); -  install_element (CONFIG_NODE, &ip_prefix_list_seq_ge_cmd); -  install_element (CONFIG_NODE, &ip_prefix_list_seq_ge_le_cmd); -  install_element (CONFIG_NODE, &ip_prefix_list_seq_le_cmd); -  install_element (CONFIG_NODE, &ip_prefix_list_seq_le_ge_cmd); - -  install_element (CONFIG_NODE, &no_ip_prefix_list_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_prefix_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_ge_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_ge_le_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_le_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_le_ge_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_seq_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_seq_ge_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_seq_ge_le_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_seq_le_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_seq_le_ge_cmd); - -  install_element (CONFIG_NODE, &ip_prefix_list_description_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_description_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_description_comment_cmd); - -  install_element (CONFIG_NODE, &ip_prefix_list_sequence_number_cmd); -  install_element (CONFIG_NODE, &no_ip_prefix_list_sequence_number_cmd); - -  install_element (VIEW_NODE, &show_ip_prefix_list_cmd); -  install_element (VIEW_NODE, &show_ip_prefix_list_name_cmd); -  install_element (VIEW_NODE, &show_ip_prefix_list_name_seq_cmd); -  install_element (VIEW_NODE, &show_ip_prefix_list_prefix_cmd); -  install_element (VIEW_NODE, &show_ip_prefix_list_prefix_longer_cmd); -  install_element (VIEW_NODE, &show_ip_prefix_list_prefix_first_match_cmd); -  install_element (VIEW_NODE, &show_ip_prefix_list_summary_cmd); -  install_element (VIEW_NODE, &show_ip_prefix_list_summary_name_cmd); -  install_element (VIEW_NODE, &show_ip_prefix_list_detail_cmd); -  install_element (VIEW_NODE, &show_ip_prefix_list_detail_name_cmd); - -  install_element (ENABLE_NODE, &clear_ip_prefix_list_cmd); -  install_element (ENABLE_NODE, &clear_ip_prefix_list_name_cmd); -  install_element (ENABLE_NODE, &clear_ip_prefix_list_name_prefix_cmd); +	for (plist = master->num.head; plist; plist = next) { +		next = plist->next; +		prefix_list_delete(plist); +	} +	for (plist = master->str.head; plist; plist = next) { +		next = plist->next; +		prefix_list_delete(plist); +	} + +	assert(master->num.head == NULL); +	assert(master->num.tail == NULL); + +	assert(master->str.head == NULL); +	assert(master->str.tail == NULL); + +	master->seqnum = 1; +	master->recent = NULL;  } +  /* Prefix-list node. */ -static struct cmd_node prefix_ipv6_node = -{ -  PREFIX_IPV6_NODE, -  "",				/* Prefix list has no interface. */ -  1 -}; +static struct cmd_node prefix_node = {PREFIX_NODE, +				      "", /* Prefix list has no interface. */ +				      1}; + +static int config_write_prefix_ipv4(struct vty *vty) +{ +	return config_write_prefix_afi(AFI_IP, vty); +} + +static void prefix_list_init_ipv4(void) +{ +	install_node(&prefix_node, config_write_prefix_ipv4); + +	install_element(CONFIG_NODE, &ip_prefix_list_cmd); +	install_element(CONFIG_NODE, &ip_prefix_list_ge_cmd); +	install_element(CONFIG_NODE, &ip_prefix_list_ge_le_cmd); +	install_element(CONFIG_NODE, &ip_prefix_list_le_cmd); +	install_element(CONFIG_NODE, &ip_prefix_list_le_ge_cmd); +	install_element(CONFIG_NODE, &ip_prefix_list_seq_cmd); +	install_element(CONFIG_NODE, &ip_prefix_list_seq_ge_cmd); +	install_element(CONFIG_NODE, &ip_prefix_list_seq_ge_le_cmd); +	install_element(CONFIG_NODE, &ip_prefix_list_seq_le_cmd); +	install_element(CONFIG_NODE, &ip_prefix_list_seq_le_ge_cmd); + +	install_element(CONFIG_NODE, &no_ip_prefix_list_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_prefix_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_ge_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_ge_le_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_le_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_le_ge_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_seq_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_seq_ge_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_seq_ge_le_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_seq_le_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_seq_le_ge_cmd); + +	install_element(CONFIG_NODE, &ip_prefix_list_description_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_description_cmd); +	install_element(CONFIG_NODE, +			&no_ip_prefix_list_description_comment_cmd); + +	install_element(CONFIG_NODE, &ip_prefix_list_sequence_number_cmd); +	install_element(CONFIG_NODE, &no_ip_prefix_list_sequence_number_cmd); + +	install_element(VIEW_NODE, &show_ip_prefix_list_cmd); +	install_element(VIEW_NODE, &show_ip_prefix_list_name_cmd); +	install_element(VIEW_NODE, &show_ip_prefix_list_name_seq_cmd); +	install_element(VIEW_NODE, &show_ip_prefix_list_prefix_cmd); +	install_element(VIEW_NODE, &show_ip_prefix_list_prefix_longer_cmd); +	install_element(VIEW_NODE, &show_ip_prefix_list_prefix_first_match_cmd); +	install_element(VIEW_NODE, &show_ip_prefix_list_summary_cmd); +	install_element(VIEW_NODE, &show_ip_prefix_list_summary_name_cmd); +	install_element(VIEW_NODE, &show_ip_prefix_list_detail_cmd); +	install_element(VIEW_NODE, &show_ip_prefix_list_detail_name_cmd); + +	install_element(ENABLE_NODE, &clear_ip_prefix_list_cmd); +	install_element(ENABLE_NODE, &clear_ip_prefix_list_name_cmd); +	install_element(ENABLE_NODE, &clear_ip_prefix_list_name_prefix_cmd); +} -static int -config_write_prefix_ipv6 (struct vty *vty) -{ -  return config_write_prefix_afi (AFI_IP6, vty); -} - -static void -prefix_list_init_ipv6 (void) -{ -  install_node (&prefix_ipv6_node, config_write_prefix_ipv6); - -  install_element (CONFIG_NODE, &ipv6_prefix_list_cmd); -  install_element (CONFIG_NODE, &ipv6_prefix_list_ge_cmd); -  install_element (CONFIG_NODE, &ipv6_prefix_list_ge_le_cmd); -  install_element (CONFIG_NODE, &ipv6_prefix_list_le_cmd); -  install_element (CONFIG_NODE, &ipv6_prefix_list_le_ge_cmd); -  install_element (CONFIG_NODE, &ipv6_prefix_list_seq_cmd); -  install_element (CONFIG_NODE, &ipv6_prefix_list_seq_ge_cmd); -  install_element (CONFIG_NODE, &ipv6_prefix_list_seq_ge_le_cmd); -  install_element (CONFIG_NODE, &ipv6_prefix_list_seq_le_cmd); -  install_element (CONFIG_NODE, &ipv6_prefix_list_seq_le_ge_cmd); - -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_prefix_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_ge_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_ge_le_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_le_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_le_ge_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_seq_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_seq_ge_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_seq_ge_le_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_seq_le_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_seq_le_ge_cmd); - -  install_element (CONFIG_NODE, &ipv6_prefix_list_description_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_description_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_description_comment_cmd); - -  install_element (CONFIG_NODE, &ipv6_prefix_list_sequence_number_cmd); -  install_element (CONFIG_NODE, &no_ipv6_prefix_list_sequence_number_cmd); - -  install_element (VIEW_NODE, &show_ipv6_prefix_list_cmd); -  install_element (VIEW_NODE, &show_ipv6_prefix_list_name_cmd); -  install_element (VIEW_NODE, &show_ipv6_prefix_list_name_seq_cmd); -  install_element (VIEW_NODE, &show_ipv6_prefix_list_prefix_cmd); -  install_element (VIEW_NODE, &show_ipv6_prefix_list_prefix_longer_cmd); -  install_element (VIEW_NODE, &show_ipv6_prefix_list_prefix_first_match_cmd); -  install_element (VIEW_NODE, &show_ipv6_prefix_list_summary_cmd); -  install_element (VIEW_NODE, &show_ipv6_prefix_list_summary_name_cmd); -  install_element (VIEW_NODE, &show_ipv6_prefix_list_detail_cmd); -  install_element (VIEW_NODE, &show_ipv6_prefix_list_detail_name_cmd); - -  install_element (ENABLE_NODE, &clear_ipv6_prefix_list_cmd); -  install_element (ENABLE_NODE, &clear_ipv6_prefix_list_name_cmd); -  install_element (ENABLE_NODE, &clear_ipv6_prefix_list_name_prefix_cmd); -} - -void -prefix_list_init () -{ -  prefix_list_init_ipv4 (); -  prefix_list_init_ipv6 (); -} - -void -prefix_list_reset () -{ -  prefix_list_reset_afi (AFI_IP,  0); -  prefix_list_reset_afi (AFI_IP6, 0); -  prefix_list_reset_afi (AFI_IP,  1); -  prefix_list_reset_afi (AFI_IP6, 1); +/* Prefix-list node. */ +static struct cmd_node prefix_ipv6_node = { +	PREFIX_IPV6_NODE, "", /* Prefix list has no interface. */ +	1}; + +static int config_write_prefix_ipv6(struct vty *vty) +{ +	return config_write_prefix_afi(AFI_IP6, vty); +} + +static void prefix_list_init_ipv6(void) +{ +	install_node(&prefix_ipv6_node, config_write_prefix_ipv6); + +	install_element(CONFIG_NODE, &ipv6_prefix_list_cmd); +	install_element(CONFIG_NODE, &ipv6_prefix_list_ge_cmd); +	install_element(CONFIG_NODE, &ipv6_prefix_list_ge_le_cmd); +	install_element(CONFIG_NODE, &ipv6_prefix_list_le_cmd); +	install_element(CONFIG_NODE, &ipv6_prefix_list_le_ge_cmd); +	install_element(CONFIG_NODE, &ipv6_prefix_list_seq_cmd); +	install_element(CONFIG_NODE, &ipv6_prefix_list_seq_ge_cmd); +	install_element(CONFIG_NODE, &ipv6_prefix_list_seq_ge_le_cmd); +	install_element(CONFIG_NODE, &ipv6_prefix_list_seq_le_cmd); +	install_element(CONFIG_NODE, &ipv6_prefix_list_seq_le_ge_cmd); + +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_prefix_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_ge_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_ge_le_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_le_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_le_ge_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_seq_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_seq_ge_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_seq_ge_le_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_seq_le_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_seq_le_ge_cmd); + +	install_element(CONFIG_NODE, &ipv6_prefix_list_description_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_description_cmd); +	install_element(CONFIG_NODE, +			&no_ipv6_prefix_list_description_comment_cmd); + +	install_element(CONFIG_NODE, &ipv6_prefix_list_sequence_number_cmd); +	install_element(CONFIG_NODE, &no_ipv6_prefix_list_sequence_number_cmd); + +	install_element(VIEW_NODE, &show_ipv6_prefix_list_cmd); +	install_element(VIEW_NODE, &show_ipv6_prefix_list_name_cmd); +	install_element(VIEW_NODE, &show_ipv6_prefix_list_name_seq_cmd); +	install_element(VIEW_NODE, &show_ipv6_prefix_list_prefix_cmd); +	install_element(VIEW_NODE, &show_ipv6_prefix_list_prefix_longer_cmd); +	install_element(VIEW_NODE, +			&show_ipv6_prefix_list_prefix_first_match_cmd); +	install_element(VIEW_NODE, &show_ipv6_prefix_list_summary_cmd); +	install_element(VIEW_NODE, &show_ipv6_prefix_list_summary_name_cmd); +	install_element(VIEW_NODE, &show_ipv6_prefix_list_detail_cmd); +	install_element(VIEW_NODE, &show_ipv6_prefix_list_detail_name_cmd); + +	install_element(ENABLE_NODE, &clear_ipv6_prefix_list_cmd); +	install_element(ENABLE_NODE, &clear_ipv6_prefix_list_name_cmd); +	install_element(ENABLE_NODE, &clear_ipv6_prefix_list_name_prefix_cmd); +} + +void prefix_list_init() +{ +	prefix_list_init_ipv4(); +	prefix_list_init_ipv6(); +} + +void prefix_list_reset() +{ +	prefix_list_reset_afi(AFI_IP, 0); +	prefix_list_reset_afi(AFI_IP6, 0); +	prefix_list_reset_afi(AFI_IP, 1); +	prefix_list_reset_afi(AFI_IP6, 1);  } diff --git a/lib/plist.h b/lib/plist.h index 89d9a874f0..c930515102 100644 --- a/lib/plist.h +++ b/lib/plist.h @@ -28,38 +28,36 @@  #include "stream.h"  #include "vty.h" -enum prefix_list_type  -{ -  PREFIX_DENY, -  PREFIX_PERMIT, +enum prefix_list_type { +	PREFIX_DENY, +	PREFIX_PERMIT,  };  struct prefix_list; -struct orf_prefix -{ -  u_int32_t seq; -  u_char ge; -  u_char le; -  struct prefix p; +struct orf_prefix { +	u_int32_t seq; +	u_char ge; +	u_char le; +	struct prefix p;  };  /* Prototypes. */ -extern void prefix_list_init (void); -extern void prefix_list_reset (void); -extern void prefix_list_add_hook (void (*func) (struct prefix_list *)); -extern void prefix_list_delete_hook (void (*func) (struct prefix_list *)); - -extern const char *prefix_list_name (struct prefix_list *); -extern struct prefix_list *prefix_list_lookup (afi_t, const char *); -extern enum prefix_list_type prefix_list_apply (struct prefix_list *, void *); - -extern struct prefix_list *prefix_bgp_orf_lookup (afi_t, const char *); -extern struct stream * prefix_bgp_orf_entry (struct stream *, -                                             struct prefix_list *, -                                             u_char, u_char, u_char); -extern int prefix_bgp_orf_set (char *, afi_t, struct orf_prefix *, int, int); -extern void prefix_bgp_orf_remove_all (afi_t, char *); -extern int prefix_bgp_show_prefix_list (struct vty *, afi_t, char *, u_char); +extern void prefix_list_init(void); +extern void prefix_list_reset(void); +extern void prefix_list_add_hook(void (*func)(struct prefix_list *)); +extern void prefix_list_delete_hook(void (*func)(struct prefix_list *)); + +extern const char *prefix_list_name(struct prefix_list *); +extern struct prefix_list *prefix_list_lookup(afi_t, const char *); +extern enum prefix_list_type prefix_list_apply(struct prefix_list *, void *); + +extern struct prefix_list *prefix_bgp_orf_lookup(afi_t, const char *); +extern struct stream *prefix_bgp_orf_entry(struct stream *, +					   struct prefix_list *, u_char, u_char, +					   u_char); +extern int prefix_bgp_orf_set(char *, afi_t, struct orf_prefix *, int, int); +extern void prefix_bgp_orf_remove_all(afi_t, char *); +extern int prefix_bgp_show_prefix_list(struct vty *, afi_t, char *, u_char);  #endif /* _QUAGGA_PLIST_H */ diff --git a/lib/plist_int.h b/lib/plist_int.h index e6e5901dbf..83b90bc0c2 100644 --- a/lib/plist_int.h +++ b/lib/plist_int.h @@ -23,56 +23,50 @@  #ifndef _QUAGGA_PLIST_INT_H  #define _QUAGGA_PLIST_INT_H -enum prefix_name_type -{ -  PREFIX_TYPE_STRING, -  PREFIX_TYPE_NUMBER -}; +enum prefix_name_type { PREFIX_TYPE_STRING, PREFIX_TYPE_NUMBER };  struct pltrie_table; -struct prefix_list -{ -  char *name; -  char *desc; +struct prefix_list { +	char *name; +	char *desc; -  struct prefix_master *master; +	struct prefix_master *master; -  enum prefix_name_type type; +	enum prefix_name_type type; -  int count; -  int rangecount; +	int count; +	int rangecount; -  struct prefix_list_entry *head; -  struct prefix_list_entry *tail; +	struct prefix_list_entry *head; +	struct prefix_list_entry *tail; -  struct pltrie_table *trie; +	struct pltrie_table *trie; -  struct prefix_list *next; -  struct prefix_list *prev; +	struct prefix_list *next; +	struct prefix_list *prev;  };  /* Each prefix-list's entry. */ -struct prefix_list_entry -{ -  int seq; +struct prefix_list_entry { +	int seq; -  int le; -  int ge; +	int le; +	int ge; -  enum prefix_list_type type; +	enum prefix_list_type type; -  int any; -  struct prefix prefix; +	int any; +	struct prefix prefix; -  unsigned long refcnt; -  unsigned long hitcnt; +	unsigned long refcnt; +	unsigned long hitcnt; -  struct prefix_list_entry *next; -  struct prefix_list_entry *prev; +	struct prefix_list_entry *next; +	struct prefix_list_entry *prev; -  /* up the chain for best match search */ -  struct prefix_list_entry *next_best; +	/* up the chain for best match search */ +	struct prefix_list_entry *next_best;  };  #endif /* _QUAGGA_PLIST_INT_H */ diff --git a/lib/pqueue.c b/lib/pqueue.c index 0f870564da..5077287da7 100644 --- a/lib/pqueue.c +++ b/lib/pqueue.c @@ -23,7 +23,7 @@ Boston, MA 02111-1307, USA.  */  #include "memory.h"  #include "pqueue.h" -DEFINE_MTYPE_STATIC(LIB, PQUEUE,      "Priority queue") +DEFINE_MTYPE_STATIC(LIB, PQUEUE, "Priority queue")  DEFINE_MTYPE_STATIC(LIB, PQUEUE_DATA, "Priority queue data")  /* priority queue using heap sort */ @@ -45,146 +45,136 @@ DEFINE_MTYPE_STATIC(LIB, PQUEUE_DATA, "Priority queue data")  #define RIGHT_OF(x) (2 * x + 2)  #define HAVE_CHILD(x,q) (x < (q)->size / 2) -void -trickle_up (int index, struct pqueue *queue) +void trickle_up(int index, struct pqueue *queue)  { -  void *tmp; - -  /* Save current node as tmp node.  */ -  tmp = queue->array[index]; - -  /* Continue until the node reaches top or the place where the parent -     node should be upper than the tmp node.  */ -  while (index > 0 && -         (*queue->cmp) (tmp, queue->array[PARENT_OF (index)]) < 0) -    { -      /* actually trickle up */ -      queue->array[index] = queue->array[PARENT_OF (index)]; -      if (queue->update != NULL) -	(*queue->update) (queue->array[index], index); -      index = PARENT_OF (index); -    } - -  /* Restore the tmp node to appropriate place.  */ -  queue->array[index] = tmp; -  if (queue->update != NULL) -    (*queue->update) (tmp, index); +	void *tmp; + +	/* Save current node as tmp node.  */ +	tmp = queue->array[index]; + +	/* Continue until the node reaches top or the place where the parent +	   node should be upper than the tmp node.  */ +	while (index > 0 +	       && (*queue->cmp)(tmp, queue->array[PARENT_OF(index)]) < 0) { +		/* actually trickle up */ +		queue->array[index] = queue->array[PARENT_OF(index)]; +		if (queue->update != NULL) +			(*queue->update)(queue->array[index], index); +		index = PARENT_OF(index); +	} + +	/* Restore the tmp node to appropriate place.  */ +	queue->array[index] = tmp; +	if (queue->update != NULL) +		(*queue->update)(tmp, index);  } -void -trickle_down (int index, struct pqueue *queue) +void trickle_down(int index, struct pqueue *queue)  { -  void *tmp; -  int which; - -  /* Save current node as tmp node.  */ -  tmp = queue->array[index]; - -  /* Continue until the node have at least one (left) child.  */ -  while (HAVE_CHILD (index, queue)) -    { -      /* If right child exists, and if the right child is more proper -         to be moved upper.  */ -      if (RIGHT_OF (index) < queue->size && -          (*queue->cmp) (queue->array[LEFT_OF (index)], -                         queue->array[RIGHT_OF (index)]) > 0) -        which = RIGHT_OF (index); -      else -        which = LEFT_OF (index); - -      /* If the tmp node should be upper than the child, break.  */ -      if ((*queue->cmp) (queue->array[which], tmp) > 0) -        break; - -      /* Actually trickle down the tmp node.  */ -      queue->array[index] = queue->array[which]; -       if (queue->update != NULL) -	 (*queue->update) (queue->array[index], index); -      index = which; -    } - -  /* Restore the tmp node to appropriate place.  */ -  queue->array[index] = tmp; -  if (queue->update != NULL) -    (*queue->update) (tmp, index); +	void *tmp; +	int which; + +	/* Save current node as tmp node.  */ +	tmp = queue->array[index]; + +	/* Continue until the node have at least one (left) child.  */ +	while (HAVE_CHILD(index, queue)) { +		/* If right child exists, and if the right child is more proper +		   to be moved upper.  */ +		if (RIGHT_OF(index) < queue->size +		    && (*queue->cmp)(queue->array[LEFT_OF(index)], +				     queue->array[RIGHT_OF(index)]) +			       > 0) +			which = RIGHT_OF(index); +		else +			which = LEFT_OF(index); + +		/* If the tmp node should be upper than the child, break.  */ +		if ((*queue->cmp)(queue->array[which], tmp) > 0) +			break; + +		/* Actually trickle down the tmp node.  */ +		queue->array[index] = queue->array[which]; +		if (queue->update != NULL) +			(*queue->update)(queue->array[index], index); +		index = which; +	} + +	/* Restore the tmp node to appropriate place.  */ +	queue->array[index] = tmp; +	if (queue->update != NULL) +		(*queue->update)(tmp, index);  } -struct pqueue * -pqueue_create (void) +struct pqueue *pqueue_create(void)  { -  struct pqueue *queue; +	struct pqueue *queue; -  queue = XCALLOC (MTYPE_PQUEUE, sizeof (struct pqueue)); +	queue = XCALLOC(MTYPE_PQUEUE, sizeof(struct pqueue)); -  queue->array = XCALLOC (MTYPE_PQUEUE_DATA,  -                          DATA_SIZE * PQUEUE_INIT_ARRAYSIZE); -  queue->array_size = PQUEUE_INIT_ARRAYSIZE; +	queue->array = +		XCALLOC(MTYPE_PQUEUE_DATA, DATA_SIZE * PQUEUE_INIT_ARRAYSIZE); +	queue->array_size = PQUEUE_INIT_ARRAYSIZE; -  /* By default we want nothing to happen when a node changes. */ -  queue->update = NULL; -  return queue; +	/* By default we want nothing to happen when a node changes. */ +	queue->update = NULL; +	return queue;  } -void -pqueue_delete (struct pqueue *queue) +void pqueue_delete(struct pqueue *queue)  { -  XFREE (MTYPE_PQUEUE_DATA, queue->array); -  XFREE (MTYPE_PQUEUE, queue); +	XFREE(MTYPE_PQUEUE_DATA, queue->array); +	XFREE(MTYPE_PQUEUE, queue);  } -static int -pqueue_expand (struct pqueue *queue) +static int pqueue_expand(struct pqueue *queue)  { -  void **newarray; +	void **newarray; -  newarray = XCALLOC (MTYPE_PQUEUE_DATA, queue->array_size * DATA_SIZE * 2); -  if (newarray == NULL) -    return 0; +	newarray = +		XCALLOC(MTYPE_PQUEUE_DATA, queue->array_size * DATA_SIZE * 2); +	if (newarray == NULL) +		return 0; -  memcpy (newarray, queue->array, queue->array_size * DATA_SIZE); +	memcpy(newarray, queue->array, queue->array_size * DATA_SIZE); -  XFREE (MTYPE_PQUEUE_DATA, queue->array); -  queue->array = newarray; -  queue->array_size *= 2; +	XFREE(MTYPE_PQUEUE_DATA, queue->array); +	queue->array = newarray; +	queue->array_size *= 2; -  return 1; +	return 1;  } -void -pqueue_enqueue (void *data, struct pqueue *queue) +void pqueue_enqueue(void *data, struct pqueue *queue)  { -  if (queue->size + 2 >= queue->array_size && ! pqueue_expand (queue)) -    return; - -  queue->array[queue->size] = data; -  if (queue->update != NULL) -    (*queue->update) (data, queue->size); -  trickle_up (queue->size, queue); -  queue->size ++; +	if (queue->size + 2 >= queue->array_size && !pqueue_expand(queue)) +		return; + +	queue->array[queue->size] = data; +	if (queue->update != NULL) +		(*queue->update)(data, queue->size); +	trickle_up(queue->size, queue); +	queue->size++;  } -void * -pqueue_dequeue (struct pqueue *queue) +void *pqueue_dequeue(struct pqueue *queue)  { -  void *data = queue->array[0]; -  queue->array[0] =  queue->array[--queue->size]; -  trickle_down (0, queue); -  return data; +	void *data = queue->array[0]; +	queue->array[0] = queue->array[--queue->size]; +	trickle_down(0, queue); +	return data;  } -void -pqueue_remove_at (int index, struct pqueue *queue) +void pqueue_remove_at(int index, struct pqueue *queue)  { -  queue->array[index] = queue->array[--queue->size]; - -  if (index > 0 -      && (*queue->cmp) (queue->array[index], -                        queue->array[PARENT_OF(index)]) < 0) -    { -      trickle_up (index, queue); -    } -  else -    { -      trickle_down (index, queue); -    } +	queue->array[index] = queue->array[--queue->size]; + +	if (index > 0 +	    && (*queue->cmp)(queue->array[index], +			     queue->array[PARENT_OF(index)]) +		       < 0) { +		trickle_up(index, queue); +	} else { +		trickle_down(index, queue); +	}  } diff --git a/lib/pqueue.h b/lib/pqueue.h index 8bb6961d86..f1c1f6feda 100644 --- a/lib/pqueue.h +++ b/lib/pqueue.h @@ -21,26 +21,25 @@ Boston, MA 02111-1307, USA.  */  #ifndef _ZEBRA_PQUEUE_H  #define _ZEBRA_PQUEUE_H -struct pqueue -{ -  void **array; -  int array_size; -  int size; - -  int (*cmp) (void *, void *); -  void (*update) (void * node, int actual_position); +struct pqueue { +	void **array; +	int array_size; +	int size; + +	int (*cmp)(void *, void *); +	void (*update)(void *node, int actual_position);  };  #define PQUEUE_INIT_ARRAYSIZE  32 -extern struct pqueue *pqueue_create (void); -extern void pqueue_delete (struct pqueue *queue); +extern struct pqueue *pqueue_create(void); +extern void pqueue_delete(struct pqueue *queue); -extern void pqueue_enqueue (void *data, struct pqueue *queue); -extern void *pqueue_dequeue (struct pqueue *queue); -extern void pqueue_remove_at (int index, struct pqueue *queue); +extern void pqueue_enqueue(void *data, struct pqueue *queue); +extern void *pqueue_dequeue(struct pqueue *queue); +extern void pqueue_remove_at(int index, struct pqueue *queue); -extern void trickle_down (int index, struct pqueue *queue); -extern void trickle_up (int index, struct pqueue *queue); +extern void trickle_down(int index, struct pqueue *queue); +extern void trickle_up(int index, struct pqueue *queue);  #endif /* _ZEBRA_PQUEUE_H */ diff --git a/lib/prefix.c b/lib/prefix.c index 0cc759bb7c..1a36cf288a 100644 --- a/lib/prefix.c +++ b/lib/prefix.c @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -32,140 +32,395 @@ DEFINE_MTYPE_STATIC(LIB, PREFIX, "Prefix")  /* Maskbit. */  static const u_char maskbit[] = {0x00, 0x80, 0xc0, 0xe0, 0xf0, -			         0xf8, 0xfc, 0xfe, 0xff}; - -static const struct in6_addr maskbytes6[] = -{ -  /* /0   */ { { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /1   */ { { { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /2   */ { { { 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /3   */ { { { 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /4   */ { { { 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /5   */ { { { 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /6   */ { { { 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /7   */ { { { 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /8   */ { { { 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /9   */ { { { 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /10  */ { { { 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /11  */ { { { 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /12  */ { { { 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /13  */ { { { 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /14  */ { { { 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /15  */ { { { 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /16  */ { { { 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /17  */ { { { 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /18  */ { { { 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /19  */ { { { 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /20  */ { { { 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /21  */ { { { 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /22  */ { { { 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /23  */ { { { 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /24  */ { { { 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /25  */ { { { 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /26  */ { { { 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /27  */ { { { 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /28  */ { { { 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /29  */ { { { 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /30  */ { { { 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /31  */ { { { 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /32  */ { { { 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /33  */ { { { 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /34  */ { { { 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /35  */ { { { 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /36  */ { { { 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /37  */ { { { 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /38  */ { { { 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /39  */ { { { 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /40  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /41  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /42  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /43  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /44  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /45  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /46  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /47  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /48  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /49  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /50  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /51  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /52  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /53  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /54  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /55  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /56  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /57  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /58  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /59  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /60  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /61  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /62  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /63  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /64  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /65  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /66  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /67  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /68  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /69  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /70  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /71  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /72  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /73  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /74  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /75  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /76  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /77  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /78  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /79  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /80  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /81  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /82  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /83  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /84  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /85  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /86  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /87  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /88  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /89  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /90  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /91  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /92  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /93  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /94  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /95  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /96  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00 } } }, -  /* /97  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00 } } }, -  /* /98  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00 } } }, -  /* /99  */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00 } } }, -  /* /100 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00 } } }, -  /* /101 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00 } } }, -  /* /102 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00 } } }, -  /* /103 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00 } } }, -  /* /104 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00 } } }, -  /* /105 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00 } } }, -  /* /106 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00 } } }, -  /* /107 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00 } } }, -  /* /108 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00 } } }, -  /* /109 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00 } } }, -  /* /110 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00 } } }, -  /* /111 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00 } } }, -  /* /112 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00 } } }, -  /* /113 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00 } } }, -  /* /114 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00 } } }, -  /* /115 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00 } } }, -  /* /116 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00 } } }, -  /* /117 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00 } } }, -  /* /118 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00 } } }, -  /* /119 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00 } } }, -  /* /120 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00 } } }, -  /* /121 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80 } } }, -  /* /122 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0 } } }, -  /* /123 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0 } } }, -  /* /124 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0 } } }, -  /* /125 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8 } } }, -  /* /126 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc } } }, -  /* /127 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe } } }, -  /* /128 */ { { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } } } -}; +				 0xf8, 0xfc, 0xfe, 0xff}; + +static const struct in6_addr maskbytes6[] = { +	/* /0   */ {{{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +		      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /1   */ +	{{{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /2   */ +	{{{0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /3   */ +	{{{0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /4   */ +	{{{0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /5   */ +	{{{0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /6   */ +	{{{0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /7   */ +	{{{0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /8   */ +	{{{0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /9   */ +	{{{0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /10  */ +	{{{0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /11  */ +	{{{0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /12  */ +	{{{0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /13  */ +	{{{0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /14  */ +	{{{0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /15  */ +	{{{0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /16  */ +	{{{0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /17  */ +	{{{0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /18  */ +	{{{0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /19  */ +	{{{0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /20  */ +	{{{0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /21  */ +	{{{0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /22  */ +	{{{0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /23  */ +	{{{0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /24  */ +	{{{0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /25  */ +	{{{0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /26  */ +	{{{0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /27  */ +	{{{0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /28  */ +	{{{0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /29  */ +	{{{0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /30  */ +	{{{0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /31  */ +	{{{0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /32  */ +	{{{0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /33  */ +	{{{0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /34  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /35  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /36  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /37  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /38  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /39  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /40  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /41  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /42  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /43  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /44  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /45  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /46  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /47  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /48  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /49  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /50  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /51  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /52  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /53  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /54  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /55  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /56  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /57  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /58  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /59  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /60  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /61  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /62  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /63  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /64  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /65  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /66  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /67  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /68  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /69  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /70  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /71  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /72  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /73  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /74  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /75  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /76  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /77  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /78  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /79  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /80  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /81  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /82  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /83  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xe0, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /84  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /85  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /86  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfc, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /87  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /88  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0x00, 0x00, 0x00, 0x00, 0x00}}}, +	/* /89  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0x80, 0x00, 0x00, 0x00, 0x00}}}, +	/* /90  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xc0, 0x00, 0x00, 0x00, 0x00}}}, +	/* /91  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xe0, 0x00, 0x00, 0x00, 0x00}}}, +	/* /92  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xf0, 0x00, 0x00, 0x00, 0x00}}}, +	/* /93  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xf8, 0x00, 0x00, 0x00, 0x00}}}, +	/* /94  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xfc, 0x00, 0x00, 0x00, 0x00}}}, +	/* /95  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xfe, 0x00, 0x00, 0x00, 0x00}}}, +	/* /96  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0x00, 0x00, 0x00, 0x00}}}, +	/* /97  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0x80, 0x00, 0x00, 0x00}}}, +	/* /98  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xc0, 0x00, 0x00, 0x00}}}, +	/* /99  */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xe0, 0x00, 0x00, 0x00}}}, +	/* /100 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xf0, 0x00, 0x00, 0x00}}}, +	/* /101 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xf8, 0x00, 0x00, 0x00}}}, +	/* /102 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xfc, 0x00, 0x00, 0x00}}}, +	/* /103 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xfe, 0x00, 0x00, 0x00}}}, +	/* /104 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0x00, 0x00, 0x00}}}, +	/* /105 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0x80, 0x00, 0x00}}}, +	/* /106 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xc0, 0x00, 0x00}}}, +	/* /107 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xe0, 0x00, 0x00}}}, +	/* /108 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xf0, 0x00, 0x00}}}, +	/* /109 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xf8, 0x00, 0x00}}}, +	/* /110 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xfc, 0x00, 0x00}}}, +	/* /111 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xfe, 0x00, 0x00}}}, +	/* /112 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0x00, 0x00}}}, +	/* /113 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0x80, 0x00}}}, +	/* /114 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xc0, 0x00}}}, +	/* /115 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xe0, 0x00}}}, +	/* /116 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xf0, 0x00}}}, +	/* /117 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xf8, 0x00}}}, +	/* /118 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xfc, 0x00}}}, +	/* /119 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xfe, 0x00}}}, +	/* /120 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xff, 0x00}}}, +	/* /121 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xff, 0x80}}}, +	/* /122 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xff, 0xc0}}}, +	/* /123 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xff, 0xe0}}}, +	/* /124 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xff, 0xf0}}}, +	/* /125 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xff, 0xf8}}}, +	/* /126 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xff, 0xfc}}}, +	/* /127 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xff, 0xfe}}}, +	/* /128 */ +	{{{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, +	   0xff, 0xff, 0xff, 0xff, 0xff}}}};  /* Number of bits in prefix type. */  #ifndef PNBBY @@ -174,151 +429,139 @@ static const struct in6_addr maskbytes6[] =  #define MASKBIT(offset)  ((0xff << (PNBBY - (offset))) & 0xff) -unsigned int -prefix_bit (const u_char *prefix, const u_char prefixlen) +unsigned int prefix_bit(const u_char *prefix, const u_char prefixlen)  { -  unsigned int offset = prefixlen / 8; -  unsigned int shift  = 7 - (prefixlen % 8); -   -  return (prefix[offset] >> shift) & 1; +	unsigned int offset = prefixlen / 8; +	unsigned int shift = 7 - (prefixlen % 8); + +	return (prefix[offset] >> shift) & 1;  } -unsigned int -prefix6_bit (const struct in6_addr *prefix, const u_char prefixlen) +unsigned int prefix6_bit(const struct in6_addr *prefix, const u_char prefixlen)  { -  return prefix_bit((const u_char *) &prefix->s6_addr, prefixlen); +	return prefix_bit((const u_char *)&prefix->s6_addr, prefixlen);  } -int -str2family(const char *string) +int str2family(const char *string)  { -  if (!strcmp("ipv4", string)) -    return AF_INET; -  else if (!strcmp("ipv6", string)) -    return AF_INET6; -  else if (!strcmp("ethernet", string)) -    return AF_ETHERNET; -  return -1; +	if (!strcmp("ipv4", string)) +		return AF_INET; +	else if (!strcmp("ipv6", string)) +		return AF_INET6; +	else if (!strcmp("ethernet", string)) +		return AF_ETHERNET; +	return -1;  }  /* Address Famiy Identifier to Address Family converter. */ -int -afi2family (afi_t afi) +int afi2family(afi_t afi)  { -  if (afi == AFI_IP) -    return AF_INET; -  else if (afi == AFI_IP6) -    return AF_INET6; -  else if (afi == AFI_L2VPN) -    return AF_ETHERNET; -  return 0; +	if (afi == AFI_IP) +		return AF_INET; +	else if (afi == AFI_IP6) +		return AF_INET6; +	else if (afi == AFI_L2VPN) +		return AF_ETHERNET; +	return 0;  } -afi_t -family2afi (int family) +afi_t family2afi(int family)  { -  if (family == AF_INET) -    return AFI_IP; -  else if (family == AF_INET6) -    return AFI_IP6; -  else if (family == AF_ETHERNET) -    return AFI_L2VPN; -  return 0; +	if (family == AF_INET) +		return AFI_IP; +	else if (family == AF_INET6) +		return AFI_IP6; +	else if (family == AF_ETHERNET) +		return AFI_L2VPN; +	return 0;  } -const char * -afi2str(afi_t afi) +const char *afi2str(afi_t afi)  { -  switch (afi) { -    case AFI_IP: -	return "IPv4"; -    case AFI_IP6: -	return "IPv6"; -    case AFI_L2VPN: -	return "l2vpn"; -    case AFI_MAX: -        return "bad-value"; -    default: -	break; -  } -  return NULL; +	switch (afi) { +	case AFI_IP: +		return "IPv4"; +	case AFI_IP6: +		return "IPv6"; +	case AFI_L2VPN: +		return "l2vpn"; +	case AFI_MAX: +		return "bad-value"; +	default: +		break; +	} +	return NULL;  } -const char * -safi2str(safi_t safi) +const char *safi2str(safi_t safi)  { -  switch (safi) { -    case SAFI_UNICAST: -	return "unicast"; -    case SAFI_MULTICAST: -	return "multicast"; -    case SAFI_ENCAP: -	return "encap"; -    case SAFI_MPLS_VPN: -	return "vpn"; -    case SAFI_EVPN: -	return "evpn"; -  } -  return NULL; +	switch (safi) { +	case SAFI_UNICAST: +		return "unicast"; +	case SAFI_MULTICAST: +		return "multicast"; +	case SAFI_ENCAP: +		return "encap"; +	case SAFI_MPLS_VPN: +		return "vpn"; +	case SAFI_EVPN: +		return "evpn"; +	} +	return NULL;  }  /* If n includes p prefix then return 1 else return 0. */ -int -prefix_match (const struct prefix *n, const struct prefix *p) +int prefix_match(const struct prefix *n, const struct prefix *p)  { -  int offset; -  int shift; -  const u_char *np, *pp; - -  /* If n's prefix is longer than p's one return 0. */ -  if (n->prefixlen > p->prefixlen) -    return 0; - -  /* Set both prefix's head pointer. */ -  np = (const u_char *)&n->u.prefix; -  pp = (const u_char *)&p->u.prefix; -   -  offset = n->prefixlen / PNBBY; -  shift =  n->prefixlen % PNBBY; - -  if (shift) -    if (maskbit[shift] & (np[offset] ^ pp[offset])) -      return 0; -   -  while (offset--) -    if (np[offset] != pp[offset]) -      return 0; -  return 1; +	int offset; +	int shift; +	const u_char *np, *pp; + +	/* If n's prefix is longer than p's one return 0. */ +	if (n->prefixlen > p->prefixlen) +		return 0; + +	/* Set both prefix's head pointer. */ +	np = (const u_char *)&n->u.prefix; +	pp = (const u_char *)&p->u.prefix; + +	offset = n->prefixlen / PNBBY; +	shift = n->prefixlen % PNBBY; + +	if (shift) +		if (maskbit[shift] & (np[offset] ^ pp[offset])) +			return 0; + +	while (offset--) +		if (np[offset] != pp[offset]) +			return 0; +	return 1;  }  /* Copy prefix from src to dest. */ -void -prefix_copy (struct prefix *dest, const struct prefix *src) +void prefix_copy(struct prefix *dest, const struct prefix *src)  { -  dest->family = src->family; -  dest->prefixlen = src->prefixlen; - -  if (src->family == AF_INET) -    dest->u.prefix4 = src->u.prefix4; -  else if (src->family == AF_INET6) -    dest->u.prefix6 = src->u.prefix6; -  else if (src->family == AF_ETHERNET) -    { -      memcpy (&dest->u.prefix_evpn, &src->u.prefix_evpn, sizeof (struct evpn_addr)); -    } -  else if (src->family == AF_UNSPEC) -    { -      dest->u.lp.id = src->u.lp.id; -      dest->u.lp.adv_router = src->u.lp.adv_router; -    } -  else -    { -      zlog_err("prefix_copy(): Unknown address family %d", src->family); -      assert (0); -    } +	dest->family = src->family; +	dest->prefixlen = src->prefixlen; + +	if (src->family == AF_INET) +		dest->u.prefix4 = src->u.prefix4; +	else if (src->family == AF_INET6) +		dest->u.prefix6 = src->u.prefix6; +	else if (src->family == AF_ETHERNET) { +		memcpy(&dest->u.prefix_evpn, &src->u.prefix_evpn, +		       sizeof(struct evpn_addr)); +	} else if (src->family == AF_UNSPEC) { +		dest->u.lp.id = src->u.lp.id; +		dest->u.lp.adv_router = src->u.lp.adv_router; +	} else { +		zlog_err("prefix_copy(): Unknown address family %d", +			 src->family); +		assert(0); +	}  } -/*  +/*   * Return 1 if the address/netmask contained in the prefix structure   * is the same, and else return 0.  For this routine, 'same' requires   * that not only the prefix length and the network part be the same, @@ -326,28 +569,29 @@ prefix_copy (struct prefix *dest, const struct prefix *src)   * the same.  Note that this routine has the same return value sense   * as '==' (which is different from prefix_cmp).   */ -int -prefix_same (const struct prefix *p1, const struct prefix *p2) +int prefix_same(const struct prefix *p1, const struct prefix *p2)  { -  if ((p1 && !p2) || (!p1 && p2)) -    return 0; - -  if (!p1 && !p2) -    return 1; - -  if (p1->family == p2->family && p1->prefixlen == p2->prefixlen) -    { -      if (p1->family == AF_INET) -	if (IPV4_ADDR_SAME (&p1->u.prefix4.s_addr, &p2->u.prefix4.s_addr)) -	  return 1; -      if (p1->family == AF_INET6 ) -	if (IPV6_ADDR_SAME (&p1->u.prefix6.s6_addr, &p2->u.prefix6.s6_addr)) -	  return 1; -      if (p1->family == AF_ETHERNET ) -        if (!memcmp (&p1->u.prefix_evpn, &p2->u.prefix_evpn, sizeof (struct evpn_addr))) -          return 1; -    } -  return 0; +	if ((p1 && !p2) || (!p1 && p2)) +		return 0; + +	if (!p1 && !p2) +		return 1; + +	if (p1->family == p2->family && p1->prefixlen == p2->prefixlen) { +		if (p1->family == AF_INET) +			if (IPV4_ADDR_SAME(&p1->u.prefix4.s_addr, +					   &p2->u.prefix4.s_addr)) +				return 1; +		if (p1->family == AF_INET6) +			if (IPV6_ADDR_SAME(&p1->u.prefix6.s6_addr, +					   &p2->u.prefix6.s6_addr)) +				return 1; +		if (p1->family == AF_ETHERNET) +			if (!memcmp(&p1->u.prefix_evpn, &p2->u.prefix_evpn, +				    sizeof(struct evpn_addr))) +				return 1; +	} +	return 0;  }  /* @@ -360,31 +604,30 @@ prefix_same (const struct prefix *p1, const struct prefix *p2)   * this routine has the same return sense as strcmp (which is different   * from prefix_same).   */ -int -prefix_cmp (const struct prefix *p1, const struct prefix *p2) +int prefix_cmp(const struct prefix *p1, const struct prefix *p2)  { -  int offset; -  int shift; +	int offset; +	int shift; -  /* Set both prefix's head pointer. */ -  const u_char *pp1 = (const u_char *)&p1->u.prefix; -  const u_char *pp2 = (const u_char *)&p2->u.prefix; +	/* Set both prefix's head pointer. */ +	const u_char *pp1 = (const u_char *)&p1->u.prefix; +	const u_char *pp2 = (const u_char *)&p2->u.prefix; -  if (p1->family != p2->family || p1->prefixlen != p2->prefixlen) -    return 1; +	if (p1->family != p2->family || p1->prefixlen != p2->prefixlen) +		return 1; -  offset = p1->prefixlen / PNBBY; -  shift = p1->prefixlen % PNBBY; +	offset = p1->prefixlen / PNBBY; +	shift = p1->prefixlen % PNBBY; -  if (shift) -    if (maskbit[shift] & (pp1[offset] ^ pp2[offset])) -      return 1; +	if (shift) +		if (maskbit[shift] & (pp1[offset] ^ pp2[offset])) +			return 1; -  while (offset--) -    if (pp1[offset] != pp2[offset]) -      return 1; +	while (offset--) +		if (pp1[offset] != pp2[offset]) +			return 1; -  return 0; +	return 0;  }  /* @@ -393,686 +636,640 @@ prefix_cmp (const struct prefix *p1, const struct prefix *p2)   * address families don't match, return -1; otherwise the return value is   * in range 0 ... maximum prefix length for the address family.   */ -int -prefix_common_bits (const struct prefix *p1, const struct prefix *p2) +int prefix_common_bits(const struct prefix *p1, const struct prefix *p2)  { -  int pos, bit; -  int length = 0; -  u_char xor; - -  /* Set both prefix's head pointer. */ -  const u_char *pp1 = (const u_char *)&p1->u.prefix; -  const u_char *pp2 = (const u_char *)&p2->u.prefix; - -  if (p1->family == AF_INET) -    length = IPV4_MAX_BYTELEN; -  if (p1->family == AF_INET6) -    length = IPV6_MAX_BYTELEN; -  if (p1->family == AF_ETHERNET) -    length = 8 * sizeof (struct evpn_addr); - -  if (p1->family != p2->family || !length) -    return -1; - -  for (pos = 0; pos < length; pos++) -    if (pp1[pos] != pp2[pos]) -      break; -  if (pos == length) -    return pos * 8; - -  xor = pp1[pos] ^ pp2[pos]; -  for (bit = 0; bit < 8; bit++) -    if (xor & (1 << (7 - bit))) -      break; - -  return pos * 8 + bit; +	int pos, bit; +	int length = 0; +	u_char xor ; + +	/* Set both prefix's head pointer. */ +	const u_char *pp1 = (const u_char *)&p1->u.prefix; +	const u_char *pp2 = (const u_char *)&p2->u.prefix; + +	if (p1->family == AF_INET) +		length = IPV4_MAX_BYTELEN; +	if (p1->family == AF_INET6) +		length = IPV6_MAX_BYTELEN; +	if (p1->family == AF_ETHERNET) +		length = 8 * sizeof(struct evpn_addr); + +	if (p1->family != p2->family || !length) +		return -1; + +	for (pos = 0; pos < length; pos++) +		if (pp1[pos] != pp2[pos]) +			break; +	if (pos == length) +		return pos * 8; + +	xor = pp1[pos] ^ pp2[pos]; +	for (bit = 0; bit < 8; bit++) +		if (xor&(1 << (7 - bit))) +			break; + +	return pos * 8 + bit;  }  /* Return prefix family type string. */ -const char * -prefix_family_str (const struct prefix *p) +const char *prefix_family_str(const struct prefix *p)  { -  if (p->family == AF_INET) -    return "inet"; -  if (p->family == AF_INET6) -    return "inet6"; -  if (p->family == AF_ETHERNET) -    return "ether"; -  return "unspec"; +	if (p->family == AF_INET) +		return "inet"; +	if (p->family == AF_INET6) +		return "inet6"; +	if (p->family == AF_ETHERNET) +		return "ether"; +	return "unspec";  }  /* Allocate new prefix_ipv4 structure. */ -struct prefix_ipv4 * -prefix_ipv4_new () +struct prefix_ipv4 *prefix_ipv4_new()  { -  struct prefix_ipv4 *p; - -  /* Call prefix_new to allocate a full-size struct prefix to avoid problems -     where the struct prefix_ipv4 is cast to struct prefix and unallocated -     bytes were being referenced (e.g. in structure assignments). */ -  p = (struct prefix_ipv4 *)prefix_new(); -  p->family = AF_INET; -  return p; +	struct prefix_ipv4 *p; + +	/* Call prefix_new to allocate a full-size struct prefix to avoid +	   problems +	   where the struct prefix_ipv4 is cast to struct prefix and unallocated +	   bytes were being referenced (e.g. in structure assignments). */ +	p = (struct prefix_ipv4 *)prefix_new(); +	p->family = AF_INET; +	return p;  }  /* Free prefix_ipv4 structure. */ -void -prefix_ipv4_free (struct prefix_ipv4 *p) +void prefix_ipv4_free(struct prefix_ipv4 *p)  { -  prefix_free((struct prefix *)p); +	prefix_free((struct prefix *)p);  }  /* When string format is invalid return 0. */ -int -str2prefix_ipv4 (const char *str, struct prefix_ipv4 *p) +int str2prefix_ipv4(const char *str, struct prefix_ipv4 *p)  { -  int ret; -  int plen; -  char *pnt; -  char *cp; - -  /* Find slash inside string. */ -  pnt = strchr (str, '/'); - -  /* String doesn't contail slash. */ -  if (pnt == NULL)  -    { -      /* Convert string to prefix. */ -      ret = inet_aton (str, &p->prefix); -      if (ret == 0) -	return 0; - -      /* If address doesn't contain slash we assume it host address. */ -      p->family = AF_INET; -      p->prefixlen = IPV4_MAX_BITLEN; - -      return ret; -    } -  else -    { -      cp = XMALLOC (MTYPE_TMP, (pnt - str) + 1); -      strncpy (cp, str, pnt - str); -      *(cp + (pnt - str)) = '\0'; -      ret = inet_aton (cp, &p->prefix); -      XFREE (MTYPE_TMP, cp); - -      /* Get prefix length. */ -      plen = (u_char) atoi (++pnt); -      if (plen > IPV4_MAX_PREFIXLEN) -	return 0; - -      p->family = AF_INET; -      p->prefixlen = plen; -    } +	int ret; +	int plen; +	char *pnt; +	char *cp; + +	/* Find slash inside string. */ +	pnt = strchr(str, '/'); + +	/* String doesn't contail slash. */ +	if (pnt == NULL) { +		/* Convert string to prefix. */ +		ret = inet_aton(str, &p->prefix); +		if (ret == 0) +			return 0; + +		/* If address doesn't contain slash we assume it host address. +		 */ +		p->family = AF_INET; +		p->prefixlen = IPV4_MAX_BITLEN; + +		return ret; +	} else { +		cp = XMALLOC(MTYPE_TMP, (pnt - str) + 1); +		strncpy(cp, str, pnt - str); +		*(cp + (pnt - str)) = '\0'; +		ret = inet_aton(cp, &p->prefix); +		XFREE(MTYPE_TMP, cp); + +		/* Get prefix length. */ +		plen = (u_char)atoi(++pnt); +		if (plen > IPV4_MAX_PREFIXLEN) +			return 0; + +		p->family = AF_INET; +		p->prefixlen = plen; +	} -  return ret; +	return ret;  }  /* When string format is invalid return 0. */ -int -str2prefix_eth (const char *str, struct prefix_eth *p) +int str2prefix_eth(const char *str, struct prefix_eth *p)  { -  int		ret = 0; -  int		plen = 48; -  char		*pnt; -  char		*cp = NULL; -  const char	*str_addr = str; -  unsigned int	a[6]; -  int		i; - -  /* Find slash inside string. */ -  pnt = strchr (str, '/'); - -  if (pnt) -    { -      /* Get prefix length. */ -      plen = (u_char) atoi (++pnt); -      if (plen > 48) -	{ -	  ret = 0; -	  goto done; +	int ret = 0; +	int plen = 48; +	char *pnt; +	char *cp = NULL; +	const char *str_addr = str; +	unsigned int a[6]; +	int i; + +	/* Find slash inside string. */ +	pnt = strchr(str, '/'); + +	if (pnt) { +		/* Get prefix length. */ +		plen = (u_char)atoi(++pnt); +		if (plen > 48) { +			ret = 0; +			goto done; +		} + +		cp = XMALLOC(MTYPE_TMP, (pnt - str) + 1); +		strncpy(cp, str, pnt - str); +		*(cp + (pnt - str)) = '\0'; + +		str_addr = cp;  	} -      cp = XMALLOC (MTYPE_TMP, (pnt - str) + 1); -      strncpy (cp, str, pnt - str); -      *(cp + (pnt - str)) = '\0'; - -      str_addr = cp; -    } - -  /* Convert string to prefix. */ -  if (sscanf(str_addr, "%2x:%2x:%2x:%2x:%2x:%2x", -    a+0, a+1, a+2, a+3, a+4, a+5) != 6) -    { -      ret = 0; -      goto done; -    } -  for (i = 0; i < 6; ++i) -    { -      p->eth_addr.octet[i] = a[i] & 0xff; -    } -  p->prefixlen = plen; -  p->family = AF_ETHERNET; -  ret = 1; +	/* Convert string to prefix. */ +	if (sscanf(str_addr, "%2x:%2x:%2x:%2x:%2x:%2x", a + 0, a + 1, a + 2, +		   a + 3, a + 4, a + 5) +	    != 6) { +		ret = 0; +		goto done; +	} +	for (i = 0; i < 6; ++i) { +		p->eth_addr.octet[i] = a[i] & 0xff; +	} +	p->prefixlen = plen; +	p->family = AF_ETHERNET; +	ret = 1;  done: -  if (cp) -    XFREE (MTYPE_TMP, cp); +	if (cp) +		XFREE(MTYPE_TMP, cp); -  return ret; +	return ret;  }  /* Convert masklen into IP address's netmask (network byte order). */ -void -masklen2ip (const int masklen, struct in_addr *netmask) +void masklen2ip(const int masklen, struct in_addr *netmask)  { -  assert (masklen >= 0 && masklen <= IPV4_MAX_BITLEN); +	assert(masklen >= 0 && masklen <= IPV4_MAX_BITLEN); -  /* left shift is only defined for less than the size of the type. -   * we unconditionally use long long in case the target platform -   * has defined behaviour for << 32 (or has a 64-bit left shift) */ +	/* left shift is only defined for less than the size of the type. +	 * we unconditionally use long long in case the target platform +	 * has defined behaviour for << 32 (or has a 64-bit left shift) */ -  if (sizeof(unsigned long long) > 4) -    netmask->s_addr = htonl(0xffffffffULL << (32 - masklen)); -  else -    netmask->s_addr = htonl(masklen ? 0xffffffffU << (32 - masklen) : 0); +	if (sizeof(unsigned long long) > 4) +		netmask->s_addr = htonl(0xffffffffULL << (32 - masklen)); +	else +		netmask->s_addr = +			htonl(masklen ? 0xffffffffU << (32 - masklen) : 0);  }  /* Convert IP address's netmask into integer. We assume netmask is     sequential one. Argument netmask should be network byte order. */ -u_char -ip_masklen (struct in_addr netmask) +u_char ip_masklen(struct in_addr netmask)  { -  uint32_t tmp = ~ntohl(netmask.s_addr); -  if (tmp) -    /* clz: count leading zeroes. sadly, the behaviour of this builtin -     * is undefined for a 0 argument, even though most CPUs give 32 */ -    return __builtin_clz(tmp); -  else -    return 32; +	uint32_t tmp = ~ntohl(netmask.s_addr); +	if (tmp) +		/* clz: count leading zeroes. sadly, the behaviour of this +		 * builtin +		 * is undefined for a 0 argument, even though most CPUs give 32 +		 */ +		return __builtin_clz(tmp); +	else +		return 32;  }  /* Apply mask to IPv4 prefix (network byte order). */ -void -apply_mask_ipv4 (struct prefix_ipv4 *p) +void apply_mask_ipv4(struct prefix_ipv4 *p)  { -  struct in_addr mask; -  masklen2ip(p->prefixlen, &mask); -  p->prefix.s_addr &= mask.s_addr; +	struct in_addr mask; +	masklen2ip(p->prefixlen, &mask); +	p->prefix.s_addr &= mask.s_addr;  }  /* If prefix is 0.0.0.0/0 then return 1 else return 0. */ -int -prefix_ipv4_any (const struct prefix_ipv4 *p) +int prefix_ipv4_any(const struct prefix_ipv4 *p)  { -  return (p->prefix.s_addr == 0 && p->prefixlen == 0); +	return (p->prefix.s_addr == 0 && p->prefixlen == 0);  }  /* Allocate a new ip version 6 route */ -struct prefix_ipv6 * -prefix_ipv6_new (void) +struct prefix_ipv6 *prefix_ipv6_new(void)  { -  struct prefix_ipv6 *p; +	struct prefix_ipv6 *p; -  /* Allocate a full-size struct prefix to avoid problems with structure -     size mismatches. */ -  p = (struct prefix_ipv6 *)prefix_new(); -  p->family = AF_INET6; -  return p; +	/* Allocate a full-size struct prefix to avoid problems with structure +	   size mismatches. */ +	p = (struct prefix_ipv6 *)prefix_new(); +	p->family = AF_INET6; +	return p;  }  /* Free prefix for IPv6. */ -void -prefix_ipv6_free (struct prefix_ipv6 *p) +void prefix_ipv6_free(struct prefix_ipv6 *p)  { -  prefix_free((struct prefix *)p); +	prefix_free((struct prefix *)p);  }  /* If given string is valid return pin6 else return NULL */ -int -str2prefix_ipv6 (const char *str, struct prefix_ipv6 *p) +int str2prefix_ipv6(const char *str, struct prefix_ipv6 *p)  { -  char *pnt; -  char *cp; -  int ret; - -  pnt = strchr (str, '/'); - -  /* If string doesn't contain `/' treat it as host route. */ -  if (pnt == NULL)  -    { -      ret = inet_pton (AF_INET6, str, &p->prefix); -      if (ret == 0) -	return 0; -      p->prefixlen = IPV6_MAX_BITLEN; -    } -  else  -    { -      int plen; - -      cp = XMALLOC (MTYPE_TMP, (pnt - str) + 1); -      strncpy (cp, str, pnt - str); -      *(cp + (pnt - str)) = '\0'; -      ret = inet_pton (AF_INET6, cp, &p->prefix); -      XFREE (MTYPE_TMP, cp); -      if (ret == 0) -	return 0; -      plen = (u_char) atoi (++pnt); -      if (plen > IPV6_MAX_BITLEN) -	return 0; -      p->prefixlen = plen; -    } -  p->family = AF_INET6; +	char *pnt; +	char *cp; +	int ret; + +	pnt = strchr(str, '/'); + +	/* If string doesn't contain `/' treat it as host route. */ +	if (pnt == NULL) { +		ret = inet_pton(AF_INET6, str, &p->prefix); +		if (ret == 0) +			return 0; +		p->prefixlen = IPV6_MAX_BITLEN; +	} else { +		int plen; + +		cp = XMALLOC(MTYPE_TMP, (pnt - str) + 1); +		strncpy(cp, str, pnt - str); +		*(cp + (pnt - str)) = '\0'; +		ret = inet_pton(AF_INET6, cp, &p->prefix); +		XFREE(MTYPE_TMP, cp); +		if (ret == 0) +			return 0; +		plen = (u_char)atoi(++pnt); +		if (plen > IPV6_MAX_BITLEN) +			return 0; +		p->prefixlen = plen; +	} +	p->family = AF_INET6; -  return ret; +	return ret;  }  /* Convert struct in6_addr netmask into integer.   * FIXME return u_char as ip_maskleni() does. */ -int -ip6_masklen (struct in6_addr netmask) +int ip6_masklen(struct in6_addr netmask)  { -  int len = 0; -  unsigned char val; -  unsigned char *pnt; -   -  pnt = (unsigned char *) & netmask; - -  while ((*pnt == 0xff) && len < IPV6_MAX_BITLEN) -    { -      len += 8; -      pnt++; -    }  -   -  if (len < IPV6_MAX_BITLEN) -    { -      val = *pnt; -      while (val)  -	{ -	  len++; -	  val <<= 1; +	int len = 0; +	unsigned char val; +	unsigned char *pnt; + +	pnt = (unsigned char *)&netmask; + +	while ((*pnt == 0xff) && len < IPV6_MAX_BITLEN) { +		len += 8; +		pnt++; +	} + +	if (len < IPV6_MAX_BITLEN) { +		val = *pnt; +		while (val) { +			len++; +			val <<= 1; +		}  	} -    } -  return len; +	return len;  } -void -masklen2ip6 (const int masklen, struct in6_addr *netmask) +void masklen2ip6(const int masklen, struct in6_addr *netmask)  { -  assert (masklen >= 0 && masklen <= IPV6_MAX_BITLEN); -  memcpy (netmask, maskbytes6 + masklen, sizeof (struct in6_addr)); +	assert(masklen >= 0 && masklen <= IPV6_MAX_BITLEN); +	memcpy(netmask, maskbytes6 + masklen, sizeof(struct in6_addr));  } -void -apply_mask_ipv6 (struct prefix_ipv6 *p) +void apply_mask_ipv6(struct prefix_ipv6 *p)  { -  u_char *pnt; -  int index; -  int offset; +	u_char *pnt; +	int index; +	int offset; -  index = p->prefixlen / 8; +	index = p->prefixlen / 8; -  if (index < 16) -    { -      pnt = (u_char *) &p->prefix; -      offset = p->prefixlen % 8; +	if (index < 16) { +		pnt = (u_char *)&p->prefix; +		offset = p->prefixlen % 8; -      pnt[index] &= maskbit[offset]; -      index++; +		pnt[index] &= maskbit[offset]; +		index++; -      while (index < 16) -	pnt[index++] = 0; -    } +		while (index < 16) +			pnt[index++] = 0; +	}  } -void -apply_mask (struct prefix *p) +void apply_mask(struct prefix *p)  { -  switch (p->family) -    { -      case AF_INET: -        apply_mask_ipv4 ((struct prefix_ipv4 *)p); -        break; -      case AF_INET6: -        apply_mask_ipv6 ((struct prefix_ipv6 *)p); -        break; -      default: -        break; -    } -  return; +	switch (p->family) { +	case AF_INET: +		apply_mask_ipv4((struct prefix_ipv4 *)p); +		break; +	case AF_INET6: +		apply_mask_ipv6((struct prefix_ipv6 *)p); +		break; +	default: +		break; +	} +	return;  }  /* Utility function of convert between struct prefix <=> union sockunion.   * FIXME This function isn't used anywhere. */ -struct prefix * -sockunion2prefix (const union sockunion *dest, -		  const union sockunion *mask) +struct prefix *sockunion2prefix(const union sockunion *dest, +				const union sockunion *mask)  { -  if (dest->sa.sa_family == AF_INET) -    { -      struct prefix_ipv4 *p; - -      p = prefix_ipv4_new (); -      p->family = AF_INET; -      p->prefix = dest->sin.sin_addr; -      p->prefixlen = ip_masklen (mask->sin.sin_addr); -      return (struct prefix *) p; -    } -  if (dest->sa.sa_family == AF_INET6) -    { -      struct prefix_ipv6 *p; - -      p = prefix_ipv6_new (); -      p->family = AF_INET6; -      p->prefixlen = ip6_masklen (mask->sin6.sin6_addr); -      memcpy (&p->prefix, &dest->sin6.sin6_addr, sizeof (struct in6_addr)); -      return (struct prefix *) p; -    } -  return NULL; +	if (dest->sa.sa_family == AF_INET) { +		struct prefix_ipv4 *p; + +		p = prefix_ipv4_new(); +		p->family = AF_INET; +		p->prefix = dest->sin.sin_addr; +		p->prefixlen = ip_masklen(mask->sin.sin_addr); +		return (struct prefix *)p; +	} +	if (dest->sa.sa_family == AF_INET6) { +		struct prefix_ipv6 *p; + +		p = prefix_ipv6_new(); +		p->family = AF_INET6; +		p->prefixlen = ip6_masklen(mask->sin6.sin6_addr); +		memcpy(&p->prefix, &dest->sin6.sin6_addr, +		       sizeof(struct in6_addr)); +		return (struct prefix *)p; +	} +	return NULL;  }  /* Utility function of convert between struct prefix <=> union sockunion. */ -struct prefix * -sockunion2hostprefix (const union sockunion *su, struct prefix *prefix) +struct prefix *sockunion2hostprefix(const union sockunion *su, +				    struct prefix *prefix)  { -  if (su->sa.sa_family == AF_INET) -    { -      struct prefix_ipv4 *p; - -      p = prefix ? (struct prefix_ipv4 *) prefix : prefix_ipv4_new (); -      p->family = AF_INET; -      p->prefix = su->sin.sin_addr; -      p->prefixlen = IPV4_MAX_BITLEN; -      return (struct prefix *) p; -    } -  if (su->sa.sa_family == AF_INET6) -    { -      struct prefix_ipv6 *p; - -      p = prefix ? (struct prefix_ipv6 *) prefix : prefix_ipv6_new (); -      p->family = AF_INET6; -      p->prefixlen = IPV6_MAX_BITLEN; -      memcpy (&p->prefix, &su->sin6.sin6_addr, sizeof (struct in6_addr)); -      return (struct prefix *) p; -    } -  return NULL; +	if (su->sa.sa_family == AF_INET) { +		struct prefix_ipv4 *p; + +		p = prefix ? (struct prefix_ipv4 *)prefix : prefix_ipv4_new(); +		p->family = AF_INET; +		p->prefix = su->sin.sin_addr; +		p->prefixlen = IPV4_MAX_BITLEN; +		return (struct prefix *)p; +	} +	if (su->sa.sa_family == AF_INET6) { +		struct prefix_ipv6 *p; + +		p = prefix ? (struct prefix_ipv6 *)prefix : prefix_ipv6_new(); +		p->family = AF_INET6; +		p->prefixlen = IPV6_MAX_BITLEN; +		memcpy(&p->prefix, &su->sin6.sin6_addr, +		       sizeof(struct in6_addr)); +		return (struct prefix *)p; +	} +	return NULL;  } -void -prefix2sockunion (const struct prefix *p, union sockunion *su) +void prefix2sockunion(const struct prefix *p, union sockunion *su)  { -  memset (su, 0, sizeof (*su)); - -  su->sa.sa_family = p->family; -  if (p->family == AF_INET) -    su->sin.sin_addr = p->u.prefix4; -  if (p->family == AF_INET6) -    memcpy (&su->sin6.sin6_addr, &p->u.prefix6, sizeof (struct in6_addr)); +	memset(su, 0, sizeof(*su)); + +	su->sa.sa_family = p->family; +	if (p->family == AF_INET) +		su->sin.sin_addr = p->u.prefix4; +	if (p->family == AF_INET6) +		memcpy(&su->sin6.sin6_addr, &p->u.prefix6, +		       sizeof(struct in6_addr));  } -int -prefix_blen (const struct prefix *p) +int prefix_blen(const struct prefix *p)  { -  switch (p->family)  -    { -    case AF_INET: -      return IPV4_MAX_BYTELEN; -      break; -    case AF_INET6: -      return IPV6_MAX_BYTELEN; -      break; -    case AF_ETHERNET: -      return ETHER_ADDR_LEN; -    } -  return 0; +	switch (p->family) { +	case AF_INET: +		return IPV4_MAX_BYTELEN; +		break; +	case AF_INET6: +		return IPV6_MAX_BYTELEN; +		break; +	case AF_ETHERNET: +		return ETHER_ADDR_LEN; +	} +	return 0;  }  /* Generic function for conversion string to struct prefix. */ -int -str2prefix (const char *str, struct prefix *p) +int str2prefix(const char *str, struct prefix *p)  { -  int ret; +	int ret; -  /* First we try to convert string to struct prefix_ipv4. */ -  ret = str2prefix_ipv4 (str, (struct prefix_ipv4 *) p); -  if (ret) -    return ret; +	/* First we try to convert string to struct prefix_ipv4. */ +	ret = str2prefix_ipv4(str, (struct prefix_ipv4 *)p); +	if (ret) +		return ret; -  /* Next we try to convert string to struct prefix_ipv6. */ -  ret = str2prefix_ipv6 (str, (struct prefix_ipv6 *) p); -  if (ret) -    return ret; +	/* Next we try to convert string to struct prefix_ipv6. */ +	ret = str2prefix_ipv6(str, (struct prefix_ipv6 *)p); +	if (ret) +		return ret; -  /* Next we try to convert string to struct prefix_eth. */ -  ret = str2prefix_eth (str, (struct prefix_eth *) p); -  if (ret) -    return ret; +	/* Next we try to convert string to struct prefix_eth. */ +	ret = str2prefix_eth(str, (struct prefix_eth *)p); +	if (ret) +		return ret; -  return 0; +	return 0;  } -const char * -prefix2str (union prefixconstptr pu, char *str, int size) +const char *prefix2str(union prefixconstptr pu, char *str, int size)  { -  const struct prefix *p = pu.p; -  char buf[PREFIX2STR_BUFFER]; - -  switch (p->family) -    { -      case AF_INET: -      case AF_INET6: -        snprintf (str, size, "%s/%d", -                  inet_ntop (p->family, &p->u.prefix, buf, PREFIX2STR_BUFFER), -                  p->prefixlen); -        break; - -      case AF_ETHERNET: -        if (p->u.prefix_evpn.route_type == 5) -          { -            u_char family; -            family = (p->u.prefix_evpn.flags & (IP_ADDR_V4 | IP_PREFIX_V4)) ? -              AF_INET : AF_INET6; -            snprintf (str, size, "[%d]:[%u][%s]/%d", -                      p->u.prefix_evpn.route_type, -                      p->u.prefix_evpn.eth_tag, -                      inet_ntop (family, &p->u.prefix_evpn.ip.addr, -                                 buf, PREFIX2STR_BUFFER), -                      p->prefixlen); -          } -        else -          { -            sprintf (str, "UNK AF_ETHER prefix"); -            snprintf(str, size, "%02x:%02x:%02x:%02x:%02x:%02x/%d", -                     p->u.prefix_eth.octet[0], p->u.prefix_eth.octet[1], -                     p->u.prefix_eth.octet[2], p->u.prefix_eth.octet[3], -                     p->u.prefix_eth.octet[4], p->u.prefix_eth.octet[5], -                     p->prefixlen); -          } -        break; -      default: -        sprintf (str, "UNK prefix"); -        break; -    } - -  return str; +	const struct prefix *p = pu.p; +	char buf[PREFIX2STR_BUFFER]; + +	switch (p->family) { +	case AF_INET: +	case AF_INET6: +		snprintf(str, size, "%s/%d", inet_ntop(p->family, &p->u.prefix, +						       buf, PREFIX2STR_BUFFER), +			 p->prefixlen); +		break; + +	case AF_ETHERNET: +		if (p->u.prefix_evpn.route_type == 5) { +			u_char family; +			family = (p->u.prefix_evpn.flags +				  & (IP_ADDR_V4 | IP_PREFIX_V4)) +					 ? AF_INET +					 : AF_INET6; +			snprintf(str, size, "[%d]:[%u][%s]/%d", +				 p->u.prefix_evpn.route_type, +				 p->u.prefix_evpn.eth_tag, +				 inet_ntop(family, &p->u.prefix_evpn.ip.addr, +					   buf, PREFIX2STR_BUFFER), +				 p->prefixlen); +		} else { +			sprintf(str, "UNK AF_ETHER prefix"); +			snprintf(str, size, "%02x:%02x:%02x:%02x:%02x:%02x/%d", +				 p->u.prefix_eth.octet[0], +				 p->u.prefix_eth.octet[1], +				 p->u.prefix_eth.octet[2], +				 p->u.prefix_eth.octet[3], +				 p->u.prefix_eth.octet[4], +				 p->u.prefix_eth.octet[5], p->prefixlen); +		} +		break; +	default: +		sprintf(str, "UNK prefix"); +		break; +	} + +	return str;  } -struct prefix * -prefix_new () +struct prefix *prefix_new()  { -  struct prefix *p; +	struct prefix *p; -  p = XCALLOC (MTYPE_PREFIX, sizeof *p); -  return p; +	p = XCALLOC(MTYPE_PREFIX, sizeof *p); +	return p;  }  /* Free prefix structure. */ -void -prefix_free (struct prefix *p) +void prefix_free(struct prefix *p)  { -  XFREE (MTYPE_PREFIX, p); +	XFREE(MTYPE_PREFIX, p);  }  /* Utility function.  Check the string only contains digit   * character.   * FIXME str.[c|h] would be better place for this function. */ -int -all_digit (const char *str) +int all_digit(const char *str)  { -  for (; *str != '\0'; str++) -    if (!isdigit ((int) *str)) -      return 0; -  return 1; +	for (; *str != '\0'; str++) +		if (!isdigit((int)*str)) +			return 0; +	return 1;  }  /* Utility function to convert ipv4 prefixes to Classful prefixes */ -void apply_classful_mask_ipv4 (struct prefix_ipv4 *p) +void apply_classful_mask_ipv4(struct prefix_ipv4 *p)  { -  u_int32_t destination; -   -  destination = ntohl (p->prefix.s_addr); -   -  if (p->prefixlen == IPV4_MAX_PREFIXLEN); -  /* do nothing for host routes */ -  else if (IN_CLASSC (destination))  -    { -      p->prefixlen=24; -      apply_mask_ipv4(p); -    } -  else if (IN_CLASSB(destination))  -    { -      p->prefixlen=16; -      apply_mask_ipv4(p); -    } -  else  -    { -      p->prefixlen=8; -      apply_mask_ipv4(p); -    } +	u_int32_t destination; + +	destination = ntohl(p->prefix.s_addr); + +	if (p->prefixlen == IPV4_MAX_PREFIXLEN) +		; +	/* do nothing for host routes */ +	else if (IN_CLASSC(destination)) { +		p->prefixlen = 24; +		apply_mask_ipv4(p); +	} else if (IN_CLASSB(destination)) { +		p->prefixlen = 16; +		apply_mask_ipv4(p); +	} else { +		p->prefixlen = 8; +		apply_mask_ipv4(p); +	}  } -in_addr_t -ipv4_network_addr (in_addr_t hostaddr, int masklen) +in_addr_t ipv4_network_addr(in_addr_t hostaddr, int masklen)  { -  struct in_addr mask; +	struct in_addr mask; -  masklen2ip (masklen, &mask); -  return hostaddr & mask.s_addr; +	masklen2ip(masklen, &mask); +	return hostaddr & mask.s_addr;  } -in_addr_t -ipv4_broadcast_addr (in_addr_t hostaddr, int masklen) +in_addr_t ipv4_broadcast_addr(in_addr_t hostaddr, int masklen)  { -  struct in_addr mask; - -  masklen2ip (masklen, &mask); -  return (masklen != IPV4_MAX_PREFIXLEN-1) ? -	 /* normal case */ -         (hostaddr | ~mask.s_addr) : -	 /* special case for /31 */ -         (hostaddr ^ ~mask.s_addr); +	struct in_addr mask; + +	masklen2ip(masklen, &mask); +	return (masklen != IPV4_MAX_PREFIXLEN - 1) ? +						   /* normal case */ +		       (hostaddr | ~mask.s_addr) +						   : +						   /* special case for /31 */ +		       (hostaddr ^ ~mask.s_addr);  } -/* Utility function to convert ipv4 netmask to prefixes  +/* Utility function to convert ipv4 netmask to prefixes     ex.) "1.1.0.0" "255.255.0.0" => "1.1.0.0/16"     ex.) "1.0.0.0" NULL => "1.0.0.0/8"                   */ -int -netmask_str2prefix_str (const char *net_str, const char *mask_str, -			char *prefix_str) +int netmask_str2prefix_str(const char *net_str, const char *mask_str, +			   char *prefix_str)  { -  struct in_addr network; -  struct in_addr mask; -  u_char prefixlen; -  u_int32_t destination; -  int ret; - -  ret = inet_aton (net_str, &network); -  if (! ret) -    return 0; - -  if (mask_str) -    { -      ret = inet_aton (mask_str, &mask); -      if (! ret) -        return 0; - -      prefixlen = ip_masklen (mask); -    } -  else  -    { -      destination = ntohl (network.s_addr); - -      if (network.s_addr == 0) -	prefixlen = 0; -      else if (IN_CLASSC (destination)) -	prefixlen = 24; -      else if (IN_CLASSB (destination)) -	prefixlen = 16; -      else if (IN_CLASSA (destination)) -	prefixlen = 8; -      else -	return 0; -    } +	struct in_addr network; +	struct in_addr mask; +	u_char prefixlen; +	u_int32_t destination; +	int ret; + +	ret = inet_aton(net_str, &network); +	if (!ret) +		return 0; + +	if (mask_str) { +		ret = inet_aton(mask_str, &mask); +		if (!ret) +			return 0; + +		prefixlen = ip_masklen(mask); +	} else { +		destination = ntohl(network.s_addr); + +		if (network.s_addr == 0) +			prefixlen = 0; +		else if (IN_CLASSC(destination)) +			prefixlen = 24; +		else if (IN_CLASSB(destination)) +			prefixlen = 16; +		else if (IN_CLASSA(destination)) +			prefixlen = 8; +		else +			return 0; +	} -  sprintf (prefix_str, "%s/%d", net_str, prefixlen); +	sprintf(prefix_str, "%s/%d", net_str, prefixlen); -  return 1; +	return 1;  }  /* Utility function for making IPv6 address string. */ -const char * -inet6_ntoa (struct in6_addr addr) +const char *inet6_ntoa(struct in6_addr addr)  { -  static char buf[INET6_ADDRSTRLEN]; +	static char buf[INET6_ADDRSTRLEN]; -  inet_ntop (AF_INET6, &addr, buf, INET6_ADDRSTRLEN); -  return buf; +	inet_ntop(AF_INET6, &addr, buf, INET6_ADDRSTRLEN); +	return buf;  }  /* converts to internal representation of mac address - * returns 1 on success, 0 otherwise  + * returns 1 on success, 0 otherwise   * format accepted: AA:BB:CC:DD:EE:FF   * if mac parameter is null, then check only   */  int prefix_str2mac(const char *str, struct ethaddr *mac)  { -  unsigned int a[6]; -  int i; - -  if (!str) -    return 0; -   -  if (sscanf (str, "%2x:%2x:%2x:%2x:%2x:%2x", -              a + 0, a + 1, a + 2, a + 3, a + 4, a + 5) != 6) -    { -      /* error in incoming str length */ -      return 0; -    } -  /* valid mac address */ -  if (!mac) -    return 1; -  for (i = 0; i < 6; ++i) -    mac->octet[i] = a[i] & 0xff; -  return 1; +	unsigned int a[6]; +	int i; + +	if (!str) +		return 0; + +	if (sscanf(str, "%2x:%2x:%2x:%2x:%2x:%2x", a + 0, a + 1, a + 2, a + 3, +		   a + 4, a + 5) +	    != 6) { +		/* error in incoming str length */ +		return 0; +	} +	/* valid mac address */ +	if (!mac) +		return 1; +	for (i = 0; i < 6; ++i) +		mac->octet[i] = a[i] & 0xff; +	return 1;  }  char *prefix_mac2str(const struct ethaddr *mac, char *buf, int size)  { -  char *ptr; -   -  if (!mac) -    return NULL; -  if (!buf) -    ptr = (char *)XMALLOC(MTYPE_TMP, ETHER_ADDR_STRLEN* sizeof(char)); -  else -    { -      assert (size >= ETHER_ADDR_STRLEN); -      ptr = buf; -    } -  snprintf(ptr, (ETHER_ADDR_STRLEN), -           "%02x:%02x:%02x:%02x:%02x:%02x", (uint8_t) mac->octet[0], -           (uint8_t) mac->octet[1], (uint8_t) mac->octet[2], (uint8_t) mac->octet[3], -           (uint8_t) mac->octet[4], (uint8_t) mac->octet[5]); -  return ptr; +	char *ptr; + +	if (!mac) +		return NULL; +	if (!buf) +		ptr = (char *)XMALLOC(MTYPE_TMP, +				      ETHER_ADDR_STRLEN * sizeof(char)); +	else { +		assert(size >= ETHER_ADDR_STRLEN); +		ptr = buf; +	} +	snprintf(ptr, (ETHER_ADDR_STRLEN), "%02x:%02x:%02x:%02x:%02x:%02x", +		 (uint8_t)mac->octet[0], (uint8_t)mac->octet[1], +		 (uint8_t)mac->octet[2], (uint8_t)mac->octet[3], +		 (uint8_t)mac->octet[4], (uint8_t)mac->octet[5]); +	return ptr;  } diff --git a/lib/prefix.h b/lib/prefix.h index eb3ae3dafb..9dd1091ff4 100644 --- a/lib/prefix.h +++ b/lib/prefix.h @@ -17,20 +17,20 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_PREFIX_H  #define _ZEBRA_PREFIX_H  #ifdef SUNOS_5 -# include <sys/ethernet.h> +#include <sys/ethernet.h>  #else -# ifdef GNU_LINUX -#  include <net/ethernet.h> -# else -#  include <netinet/if_ether.h> -# endif +#ifdef GNU_LINUX +#include <net/ethernet.h> +#else +#include <netinet/if_ether.h> +#endif  #endif  #include "sockunion.h" @@ -48,11 +48,11 @@   * own to simplify internal handling   */  struct ethaddr { -    u_char octet[ETHER_ADDR_LEN]; -} __attribute__ ((packed)); +	u_char octet[ETHER_ADDR_LEN]; +} __attribute__((packed)); -/* length is the number of valuable bits of prefix structure  +/* length is the number of valuable bits of prefix structure  * 18 bytes is current length in structure, if address is ipv4  * 30 bytes is in case of ipv6  */ @@ -60,32 +60,29 @@ struct ethaddr {  #define PREFIX_LEN_ROUTE_TYPE_5_IPV6 (30*8)  /* EVPN address (RFC 7432) */ -struct evpn_addr -{ -  u_char route_type; -  u_char flags; +struct evpn_addr { +	u_char route_type; +	u_char flags;  #define IP_ADDR_NONE      0x0  #define IP_ADDR_V4        0x1  #define IP_ADDR_V6        0x2  #define IP_PREFIX_V4      0x4  #define IP_PREFIX_V6      0x8 -  struct ethaddr mac; -  uint32_t eth_tag; -  u_char ip_prefix_length; -  union -  { -    u_char addr; -    struct in_addr v4_addr; -    struct in6_addr v6_addr; -  } ip; +	struct ethaddr mac; +	uint32_t eth_tag; +	u_char ip_prefix_length; +	union { +		u_char addr; +		struct in_addr v4_addr; +		struct in6_addr v6_addr; +	} ip;  };  /* EVPN prefix structure. */ -struct prefix_evpn -{ -  u_char family; -  u_char prefixlen; -  struct evpn_addr prefix __attribute__ ((aligned (8))); +struct prefix_evpn { +	u_char family; +	u_char prefixlen; +	struct evpn_addr prefix __attribute__((aligned(8)));  };  /* @@ -107,81 +104,71 @@ struct prefix_evpn  #endif  /* IPv4 and IPv6 unified prefix structure. */ -struct prefix -{ -  u_char family; -  u_char prefixlen; -  union  -  { -    u_char prefix; -    struct in_addr prefix4; -    struct in6_addr prefix6; -    struct  -    { -      struct in_addr id; -      struct in_addr adv_router; -    } lp; -    struct ethaddr prefix_eth;	/* AF_ETHERNET */ -    u_char val[8]; -    uintptr_t ptr; -    struct evpn_addr prefix_evpn; -  } u __attribute__ ((aligned (8))); +struct prefix { +	u_char family; +	u_char prefixlen; +	union { +		u_char prefix; +		struct in_addr prefix4; +		struct in6_addr prefix6; +		struct { +			struct in_addr id; +			struct in_addr adv_router; +		} lp; +		struct ethaddr prefix_eth; /* AF_ETHERNET */ +		u_char val[8]; +		uintptr_t ptr; +		struct evpn_addr prefix_evpn; +	} u __attribute__((aligned(8)));  };  /* IPv4 prefix structure. */ -struct prefix_ipv4 -{ -  u_char family; -  u_char prefixlen; -  struct in_addr prefix __attribute__ ((aligned (8))); +struct prefix_ipv4 { +	u_char family; +	u_char prefixlen; +	struct in_addr prefix __attribute__((aligned(8)));  };  /* IPv6 prefix structure. */ -struct prefix_ipv6 -{ -  u_char family; -  u_char prefixlen; -  struct in6_addr prefix __attribute__ ((aligned (8))); +struct prefix_ipv6 { +	u_char family; +	u_char prefixlen; +	struct in6_addr prefix __attribute__((aligned(8)));  }; -struct prefix_ls -{ -  u_char family; -  u_char prefixlen; -  struct in_addr id __attribute__ ((aligned (8))); -  struct in_addr adv_router; +struct prefix_ls { +	u_char family; +	u_char prefixlen; +	struct in_addr id __attribute__((aligned(8))); +	struct in_addr adv_router;  };  /* Prefix for routing distinguisher. */ -struct prefix_rd -{ -  u_char family; -  u_char prefixlen; -  u_char val[8] __attribute__ ((aligned (8))); +struct prefix_rd { +	u_char family; +	u_char prefixlen; +	u_char val[8] __attribute__((aligned(8)));  };  /* Prefix for ethernet. */ -struct prefix_eth -{ -  u_char family; -  u_char prefixlen; -  struct ethaddr eth_addr __attribute__ ((aligned (8))); /* AF_ETHERNET */ +struct prefix_eth { +	u_char family; +	u_char prefixlen; +	struct ethaddr eth_addr __attribute__((aligned(8))); /* AF_ETHERNET */  };  /* Prefix for a generic pointer */ -struct prefix_ptr -{ -  u_char family; -  u_char prefixlen; -  uintptr_t prefix __attribute__ ((aligned (8))); +struct prefix_ptr { +	u_char family; +	u_char prefixlen; +	uintptr_t prefix __attribute__((aligned(8)));  }; -struct prefix_sg -{ -  u_char family; -  u_char prefixlen; -  struct in_addr src __attribute ((aligned (8))); -  struct in_addr grp; +struct prefix_sg { +	u_char family; +	u_char prefixlen; +	struct in_addr src __attribute((aligned(8))); +	struct in_addr grp;  };  /* helper to get type safety/avoid casts on calls @@ -189,21 +176,19 @@ struct prefix_sg   * side, which strips type safety since the cast will accept any pointer   * type.)   */ -union prefixptr -{ -  struct prefix *p; -  struct prefix_ipv4 *p4; -  struct prefix_ipv6 *p6; -  struct prefix_evpn *evp; -} __attribute__ ((transparent_union)); - -union prefixconstptr -{ -  const struct prefix *p; -  const struct prefix_ipv4 *p4; -  const struct prefix_ipv6 *p6; -  const struct prefix_evpn *evp; -} __attribute__ ((transparent_union)); +union prefixptr { +	struct prefix *p; +	struct prefix_ipv4 *p4; +	struct prefix_ipv6 *p6; +	struct prefix_evpn *evp; +} __attribute__((transparent_union)); + +union prefixconstptr { +	const struct prefix *p; +	const struct prefix_ipv4 *p4; +	const struct prefix_ipv6 *p6; +	const struct prefix_evpn *evp; +} __attribute__((transparent_union));  #ifndef INET_ADDRSTRLEN  #define INET_ADDRSTRLEN 16 @@ -259,114 +244,116 @@ union prefixconstptr  /* Prototypes. */  extern int str2family(const char *); -extern int afi2family (afi_t); -extern afi_t family2afi (int); +extern int afi2family(afi_t); +extern afi_t family2afi(int);  extern const char *safi2str(safi_t safi);  extern const char *afi2str(afi_t afi);  /* Check bit of the prefix. */ -extern unsigned int prefix_bit (const u_char *prefix, const u_char prefixlen); -extern unsigned int prefix6_bit (const struct in6_addr *prefix, const u_char prefixlen); +extern unsigned int prefix_bit(const u_char *prefix, const u_char prefixlen); +extern unsigned int prefix6_bit(const struct in6_addr *prefix, +				const u_char prefixlen); -extern struct prefix *prefix_new (void); -extern void prefix_free (struct prefix *); -extern const char *prefix_family_str (const struct prefix *); -extern int prefix_blen (const struct prefix *); -extern int str2prefix (const char *, struct prefix *); +extern struct prefix *prefix_new(void); +extern void prefix_free(struct prefix *); +extern const char *prefix_family_str(const struct prefix *); +extern int prefix_blen(const struct prefix *); +extern int str2prefix(const char *, struct prefix *);  #define PREFIX2STR_BUFFER  PREFIX_STRLEN -extern const char *prefix2str (union prefixconstptr, char *, int); -extern int prefix_match (const struct prefix *, const struct prefix *); -extern int prefix_same (const struct prefix *, const struct prefix *); -extern int prefix_cmp (const struct prefix *, const struct prefix *); -extern int prefix_common_bits (const struct prefix *, const struct prefix *); -extern void prefix_copy (struct prefix *dest, const struct prefix *src); -extern void apply_mask (struct prefix *); +extern const char *prefix2str(union prefixconstptr, char *, int); +extern int prefix_match(const struct prefix *, const struct prefix *); +extern int prefix_same(const struct prefix *, const struct prefix *); +extern int prefix_cmp(const struct prefix *, const struct prefix *); +extern int prefix_common_bits(const struct prefix *, const struct prefix *); +extern void prefix_copy(struct prefix *dest, const struct prefix *src); +extern void apply_mask(struct prefix *); -extern struct prefix *sockunion2prefix (const union sockunion *dest, -                                        const union sockunion *mask); -extern struct prefix *sockunion2hostprefix (const union sockunion *, struct prefix *p); -extern void prefix2sockunion (const struct prefix *, union sockunion *); +extern struct prefix *sockunion2prefix(const union sockunion *dest, +				       const union sockunion *mask); +extern struct prefix *sockunion2hostprefix(const union sockunion *, +					   struct prefix *p); +extern void prefix2sockunion(const struct prefix *, union sockunion *); -extern int str2prefix_eth (const char *, struct prefix_eth *); +extern int str2prefix_eth(const char *, struct prefix_eth *); -extern struct prefix_ipv4 *prefix_ipv4_new (void); -extern void prefix_ipv4_free (struct prefix_ipv4 *); -extern int str2prefix_ipv4 (const char *, struct prefix_ipv4 *); -extern void apply_mask_ipv4 (struct prefix_ipv4 *); +extern struct prefix_ipv4 *prefix_ipv4_new(void); +extern void prefix_ipv4_free(struct prefix_ipv4 *); +extern int str2prefix_ipv4(const char *, struct prefix_ipv4 *); +extern void apply_mask_ipv4(struct prefix_ipv4 *); -#define PREFIX_COPY_IPV4(DST, SRC)	\ +#define PREFIX_COPY_IPV4(DST, SRC)                                             \  	*((struct prefix_ipv4 *)(DST)) = *((const struct prefix_ipv4 *)(SRC)); -extern int prefix_ipv4_any (const struct prefix_ipv4 *); -extern void apply_classful_mask_ipv4 (struct prefix_ipv4 *); +extern int prefix_ipv4_any(const struct prefix_ipv4 *); +extern void apply_classful_mask_ipv4(struct prefix_ipv4 *); -extern u_char ip_masklen (struct in_addr); -extern void masklen2ip (const int, struct in_addr *); +extern u_char ip_masklen(struct in_addr); +extern void masklen2ip(const int, struct in_addr *);  /* returns the network portion of the host address */ -extern in_addr_t ipv4_network_addr (in_addr_t hostaddr, int masklen); +extern in_addr_t ipv4_network_addr(in_addr_t hostaddr, int masklen);  /* given the address of a host on a network and the network mask length,   * calculate the broadcast address for that network;   * special treatment for /31: returns the address of the other host   * on the network by flipping the host bit */ -extern in_addr_t ipv4_broadcast_addr (in_addr_t hostaddr, int masklen); +extern in_addr_t ipv4_broadcast_addr(in_addr_t hostaddr, int masklen); -extern int netmask_str2prefix_str (const char *, const char *, char *); +extern int netmask_str2prefix_str(const char *, const char *, char *); -extern struct prefix_ipv6 *prefix_ipv6_new (void); -extern void prefix_ipv6_free (struct prefix_ipv6 *); -extern int str2prefix_ipv6 (const char *, struct prefix_ipv6 *); -extern void apply_mask_ipv6 (struct prefix_ipv6 *); +extern struct prefix_ipv6 *prefix_ipv6_new(void); +extern void prefix_ipv6_free(struct prefix_ipv6 *); +extern int str2prefix_ipv6(const char *, struct prefix_ipv6 *); +extern void apply_mask_ipv6(struct prefix_ipv6 *); -#define PREFIX_COPY_IPV6(DST, SRC)	\ +#define PREFIX_COPY_IPV6(DST, SRC)                                             \  	*((struct prefix_ipv6 *)(DST)) = *((const struct prefix_ipv6 *)(SRC)); -extern int ip6_masklen (struct in6_addr); -extern void masklen2ip6 (const int, struct in6_addr *); +extern int ip6_masklen(struct in6_addr); +extern void masklen2ip6(const int, struct in6_addr *); -extern const char *inet6_ntoa (struct in6_addr); +extern const char *inet6_ntoa(struct in6_addr);  extern int prefix_str2mac(const char *str, struct ethaddr *mac);  extern char *prefix_mac2str(const struct ethaddr *mac, char *buf, int size); -static inline int ipv6_martian (struct in6_addr *addr) +static inline int ipv6_martian(struct in6_addr *addr)  { -  struct in6_addr localhost_addr; +	struct in6_addr localhost_addr; -  inet_pton (AF_INET6, "::1", &localhost_addr); +	inet_pton(AF_INET6, "::1", &localhost_addr); -  if (IPV6_ADDR_SAME(&localhost_addr, addr)) -    return 1; +	if (IPV6_ADDR_SAME(&localhost_addr, addr)) +		return 1; -  return 0; +	return 0;  } -extern int all_digit (const char *); +extern int all_digit(const char *);  /* NOTE: This routine expects the address argument in network byte order. */ -static inline int ipv4_martian (struct in_addr *addr) +static inline int ipv4_martian(struct in_addr *addr)  { -  in_addr_t ip = ntohl(addr->s_addr); +	in_addr_t ip = ntohl(addr->s_addr); -  if (IPV4_NET0(ip) || IPV4_NET127(ip) || IPV4_CLASS_DE(ip)) { -    return 1; -  } -  return 0; +	if (IPV4_NET0(ip) || IPV4_NET127(ip) || IPV4_CLASS_DE(ip)) { +		return 1; +	} +	return 0;  } -static inline int -is_default_prefix (struct prefix *p) +static inline int is_default_prefix(struct prefix *p)  { -  if (!p) -    return 0; +	if (!p) +		return 0; -  if (((p->family == AF_INET) && (p->u.prefix4.s_addr == INADDR_ANY)) -      || ((p->family == AF_INET6) && -          !memcmp(&p->u.prefix6, &in6addr_any, sizeof (struct in6_addr)))) -    return 1; +	if (((p->family == AF_INET) && (p->u.prefix4.s_addr == INADDR_ANY)) +	    || ((p->family == AF_INET6) +		&& !memcmp(&p->u.prefix6, &in6addr_any, +			   sizeof(struct in6_addr)))) +		return 1; -  return 0; +	return 0;  }  #endif /* _ZEBRA_PREFIX_H */ diff --git a/lib/privs.c b/lib/privs.c index c25310c8d3..d3b64cccb6 100644 --- a/lib/privs.c +++ b/lib/privs.c @@ -1,4 +1,4 @@ -/*  +/*   * Zebra privileges.   *   * Copyright (C) 2003 Paul Jakma. @@ -19,7 +19,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h>  #include "log.h" @@ -40,18 +40,18 @@ DEFINE_MTYPE_STATIC(LIB, PRIVS, "Privilege information")   * sets are mostly opaque, to hold a set of privileges, related in some way.   * storage binds together a set of sets we're interested in.   * (in reality: cap_value_t and priv_t are ints) - */  + */  #ifdef HAVE_LCAPS  /* Linux doesn't have a 'set' type: a set of related privileges */  struct _pset { -  int num; -  cap_value_t *caps; +	int num; +	cap_value_t *caps;  };  typedef cap_value_t pvalue_t;  typedef struct _pset pset_t;  typedef cap_t pstorage_t; -#elif defined (HAVE_SOLARIS_CAPABILITIES) +#elif defined(HAVE_SOLARIS_CAPABILITIES)  typedef priv_t pvalue_t;  typedef priv_set_t pset_t;  typedef priv_set_t *pstorage_t; @@ -66,799 +66,816 @@ typedef priv_set_t *pstorage_t;  static zebra_privs_current_t zprivs_null_state = ZPRIVS_RAISED;  /* internal privileges state */ -static struct _zprivs_t -{ +static struct _zprivs_t {  #ifdef HAVE_CAPABILITIES -  pstorage_t caps;		/* working storage        */ -  pset_t *syscaps_p;		/* system-type requested permitted caps    */ -  pset_t *syscaps_i;     	/* system-type requested inheritable caps  */ -#endif /* HAVE_CAPABILITIES */ -  uid_t zuid,                 /* uid to run as            */ -        zsuid;                /* saved uid                */ -  gid_t zgid;                 /* gid to run as            */ -  gid_t vtygrp;               /* gid for vty sockets      */ +	pstorage_t caps;   /* working storage        */ +	pset_t *syscaps_p; /* system-type requested permitted caps    */ +	pset_t *syscaps_i; /* system-type requested inheritable caps  */ +#endif			   /* HAVE_CAPABILITIES */ +	uid_t zuid,	/* uid to run as            */ +		zsuid;     /* saved uid                */ +	gid_t zgid;	/* gid to run as            */ +	gid_t vtygrp;      /* gid for vty sockets      */  } zprivs_state;  /* externally exported but not directly accessed functions */  #ifdef HAVE_CAPABILITIES -int zprivs_change_caps (zebra_privs_ops_t); -zebra_privs_current_t zprivs_state_caps (void); +int zprivs_change_caps(zebra_privs_ops_t); +zebra_privs_current_t zprivs_state_caps(void);  #endif /* HAVE_CAPABILITIES */ -int zprivs_change_uid (zebra_privs_ops_t); -zebra_privs_current_t zprivs_state_uid (void); -int zprivs_change_null (zebra_privs_ops_t); -zebra_privs_current_t zprivs_state_null (void); +int zprivs_change_uid(zebra_privs_ops_t); +zebra_privs_current_t zprivs_state_uid(void); +int zprivs_change_null(zebra_privs_ops_t); +zebra_privs_current_t zprivs_state_null(void);  #ifdef HAVE_CAPABILITIES  /* internal capability API */ -static pset_t *zcaps2sys (zebra_capabilities_t *, int); -static void zprivs_caps_init (struct zebra_privs_t *); -static void zprivs_caps_terminate (void); +static pset_t *zcaps2sys(zebra_capabilities_t *, int); +static void zprivs_caps_init(struct zebra_privs_t *); +static void zprivs_caps_terminate(void);  /* Map of Quagga abstract capabilities to system capabilities */ -static struct -{ -  int num; -  pvalue_t *system_caps; -} cap_map [ZCAP_MAX] = -{ +static struct { +	int num; +	pvalue_t *system_caps; +} cap_map[ZCAP_MAX] = {  #ifdef HAVE_LCAPS /* Quagga -> Linux capabilities mappings */ -  [ZCAP_SETID] = 	{ 2, (pvalue_t []) { CAP_SETGID, -                                             CAP_SETUID 		}, }, -  [ZCAP_BIND] =		{ 1, (pvalue_t []) { CAP_NET_BIND_SERVICE	}, }, -  [ZCAP_NET_ADMIN] =	{ 1, (pvalue_t []) { CAP_NET_ADMIN		}, }, -  [ZCAP_NET_RAW] = 	{ 1, (pvalue_t []) { CAP_NET_RAW		}, }, -  [ZCAP_CHROOT] = 	{ 1, (pvalue_t []) { CAP_SYS_CHROOT,		}, }, -  [ZCAP_NICE] = 	{ 1, (pvalue_t []) { CAP_SYS_NICE 		}, }, -  [ZCAP_PTRACE] =  	{ 1, (pvalue_t []) { CAP_SYS_PTRACE 		}, }, -  [ZCAP_DAC_OVERRIDE] = { 1, (pvalue_t []) { CAP_DAC_OVERRIDE 		}, }, -  [ZCAP_READ_SEARCH] =  { 1, (pvalue_t []) { CAP_DAC_READ_SEARCH 	}, }, -  [ZCAP_SYS_ADMIN] =	{ 1, (pvalue_t []) { CAP_SYS_ADMIN 		}, }, -  [ZCAP_FOWNER] = 	{ 1, (pvalue_t []) { CAP_FOWNER			}, }, +		[ZCAP_SETID] = +			{ +				2, (pvalue_t[]){CAP_SETGID, CAP_SETUID}, +			}, +		[ZCAP_BIND] = +			{ +				1, (pvalue_t[]){CAP_NET_BIND_SERVICE}, +			}, +		[ZCAP_NET_ADMIN] = +			{ +				1, (pvalue_t[]){CAP_NET_ADMIN}, +			}, +		[ZCAP_NET_RAW] = +			{ +				1, (pvalue_t[]){CAP_NET_RAW}, +			}, +		[ZCAP_CHROOT] = +			{ +				1, +				(pvalue_t[]){ +					CAP_SYS_CHROOT, +				}, +			}, +		[ZCAP_NICE] = +			{ +				1, (pvalue_t[]){CAP_SYS_NICE}, +			}, +		[ZCAP_PTRACE] = +			{ +				1, (pvalue_t[]){CAP_SYS_PTRACE}, +			}, +		[ZCAP_DAC_OVERRIDE] = +			{ +				1, (pvalue_t[]){CAP_DAC_OVERRIDE}, +			}, +		[ZCAP_READ_SEARCH] = +			{ +				1, (pvalue_t[]){CAP_DAC_READ_SEARCH}, +			}, +		[ZCAP_SYS_ADMIN] = +			{ +				1, (pvalue_t[]){CAP_SYS_ADMIN}, +			}, +		[ZCAP_FOWNER] = +			{ +				1, (pvalue_t[]){CAP_FOWNER}, +			},  #elif defined(HAVE_SOLARIS_CAPABILITIES) /* HAVE_LCAPS */ -  /* Quagga -> Solaris privilege mappings */ -  [ZCAP_SETID] =	{ 1, (pvalue_t []) { PRIV_PROC_SETID		}, }, -  [ZCAP_BIND] = 	{ 1, (pvalue_t []) { PRIV_NET_PRIVADDR		}, }, -  /* IP_CONFIG is a subset of NET_CONFIG and is allowed in zones */ +		/* Quagga -> Solaris privilege mappings */ +		[ZCAP_SETID] = +			{ +				1, (pvalue_t[]){PRIV_PROC_SETID}, +			}, +		[ZCAP_BIND] = +			{ +				1, (pvalue_t[]){PRIV_NET_PRIVADDR}, +			}, +/* IP_CONFIG is a subset of NET_CONFIG and is allowed in zones */  #ifdef PRIV_SYS_IP_CONFIG -  [ZCAP_NET_ADMIN] =	{ 1, (pvalue_t []) { PRIV_SYS_IP_CONFIG	}, }, +		[ZCAP_NET_ADMIN] = +			{ +				1, (pvalue_t[]){PRIV_SYS_IP_CONFIG}, +			},  #else -  [ZCAP_NET_ADMIN] =	{ 1, (pvalue_t []) { PRIV_SYS_NET_CONFIG	}, }, +		[ZCAP_NET_ADMIN] = +			{ +				1, (pvalue_t[]){PRIV_SYS_NET_CONFIG}, +			},  #endif -  [ZCAP_NET_RAW] = 	{ 2, (pvalue_t []) { PRIV_NET_RAWACCESS, -                                             PRIV_NET_ICMPACCESS 	}, }, -  [ZCAP_CHROOT] = 	{ 1, (pvalue_t []) { PRIV_PROC_CHROOT		}, }, -  [ZCAP_NICE] = 	{ 1, (pvalue_t []) { PRIV_PROC_PRIOCNTL		}, }, -  [ZCAP_PTRACE] =	{ 1, (pvalue_t []) { PRIV_PROC_SESSION		}, }, -  [ZCAP_DAC_OVERRIDE] = { 5, (pvalue_t []) { PRIV_FILE_DAC_EXECUTE, -                                             PRIV_FILE_DAC_READ, -                                             PRIV_FILE_DAC_SEARCH, -                                             PRIV_FILE_DAC_WRITE, -                                             PRIV_FILE_DAC_SEARCH	}, }, -  [ZCAP_READ_SEARCH] =	{ 2, (pvalue_t []) { PRIV_FILE_DAC_SEARCH, -                                             PRIV_FILE_DAC_READ		}, }, -  [ZCAP_SYS_ADMIN] =	{ 1, (pvalue_t []) { PRIV_SYS_ADMIN		}, }, -  [ZCAP_FOWNER] =	{ 1, (pvalue_t []) { PRIV_FILE_OWNER		}, }, +		[ZCAP_NET_RAW] = +			{ +				2, (pvalue_t[]){PRIV_NET_RAWACCESS, +						PRIV_NET_ICMPACCESS}, +			}, +		[ZCAP_CHROOT] = +			{ +				1, (pvalue_t[]){PRIV_PROC_CHROOT}, +			}, +		[ZCAP_NICE] = +			{ +				1, (pvalue_t[]){PRIV_PROC_PRIOCNTL}, +			}, +		[ZCAP_PTRACE] = +			{ +				1, (pvalue_t[]){PRIV_PROC_SESSION}, +			}, +		[ZCAP_DAC_OVERRIDE] = +			{ +				5, (pvalue_t[]){PRIV_FILE_DAC_EXECUTE, +						PRIV_FILE_DAC_READ, +						PRIV_FILE_DAC_SEARCH, +						PRIV_FILE_DAC_WRITE, +						PRIV_FILE_DAC_SEARCH}, +			}, +		[ZCAP_READ_SEARCH] = +			{ +				2, (pvalue_t[]){PRIV_FILE_DAC_SEARCH, +						PRIV_FILE_DAC_READ}, +			}, +		[ZCAP_SYS_ADMIN] = +			{ +				1, (pvalue_t[]){PRIV_SYS_ADMIN}, +			}, +		[ZCAP_FOWNER] = +			{ +				1, (pvalue_t[]){PRIV_FILE_OWNER}, +			},  #endif /* HAVE_SOLARIS_CAPABILITIES */  };  #ifdef HAVE_LCAPS  /* Linux forms of capabilities methods */  /* convert zebras privileges to system capabilities */ -static pset_t * -zcaps2sys (zebra_capabilities_t *zcaps, int num) +static pset_t *zcaps2sys(zebra_capabilities_t *zcaps, int num)  { -  pset_t *syscaps; -  int i, j = 0, count = 0; -   -  if (!num) -    return NULL; -   -  /* first count up how many system caps we have */ -  for (i= 0; i < num; i++) -    count += cap_map[zcaps[i]].num; -   -  if ( (syscaps = XCALLOC (MTYPE_PRIVS, (sizeof(pset_t) * num))) == NULL) -    { -      fprintf (stderr, "%s: could not allocate syscaps!", __func__); -      return NULL; -    } -   -  syscaps->caps = XCALLOC (MTYPE_PRIVS, (sizeof (pvalue_t) * count)); -   -  if (!syscaps->caps) -    { -      fprintf (stderr, "%s: could not XCALLOC caps!", __func__); -      return NULL; -    } -   -  /* copy the capabilities over */ -  count = 0; -  for (i=0; i < num; i++) -    for (j = 0; j < cap_map[zcaps[i]].num; j++) -      syscaps->caps[count++] = cap_map[zcaps[i]].system_caps[j]; -   -  /* iterations above should be exact same as previous count, obviously.. */ -  syscaps->num = count; -   -  return syscaps; +	pset_t *syscaps; +	int i, j = 0, count = 0; + +	if (!num) +		return NULL; + +	/* first count up how many system caps we have */ +	for (i = 0; i < num; i++) +		count += cap_map[zcaps[i]].num; + +	if ((syscaps = XCALLOC(MTYPE_PRIVS, (sizeof(pset_t) * num))) == NULL) { +		fprintf(stderr, "%s: could not allocate syscaps!", __func__); +		return NULL; +	} + +	syscaps->caps = XCALLOC(MTYPE_PRIVS, (sizeof(pvalue_t) * count)); + +	if (!syscaps->caps) { +		fprintf(stderr, "%s: could not XCALLOC caps!", __func__); +		return NULL; +	} + +	/* copy the capabilities over */ +	count = 0; +	for (i = 0; i < num; i++) +		for (j = 0; j < cap_map[zcaps[i]].num; j++) +			syscaps->caps[count++] = +				cap_map[zcaps[i]].system_caps[j]; + +	/* iterations above should be exact same as previous count, obviously.. +	 */ +	syscaps->num = count; + +	return syscaps;  }  /* set or clear the effective capabilities to/from permitted */ -int  -zprivs_change_caps (zebra_privs_ops_t op) +int zprivs_change_caps(zebra_privs_ops_t op)  { -  cap_flag_value_t cflag; -   -  /* should be no possibility of being called without valid caps */ -  assert (zprivs_state.syscaps_p && zprivs_state.caps); -  if (! (zprivs_state.syscaps_p && zprivs_state.caps)) -    exit (1); -     -  if (op == ZPRIVS_RAISE) -    cflag = CAP_SET; -  else if (op == ZPRIVS_LOWER) -    cflag = CAP_CLEAR; -  else -    return -1; - -  if ( !cap_set_flag (zprivs_state.caps, CAP_EFFECTIVE, -                       zprivs_state.syscaps_p->num,  -                       zprivs_state.syscaps_p->caps,  -                       cflag)) -    return cap_set_proc (zprivs_state.caps); -  return -1; +	cap_flag_value_t cflag; + +	/* should be no possibility of being called without valid caps */ +	assert(zprivs_state.syscaps_p && zprivs_state.caps); +	if (!(zprivs_state.syscaps_p && zprivs_state.caps)) +		exit(1); + +	if (op == ZPRIVS_RAISE) +		cflag = CAP_SET; +	else if (op == ZPRIVS_LOWER) +		cflag = CAP_CLEAR; +	else +		return -1; + +	if (!cap_set_flag(zprivs_state.caps, CAP_EFFECTIVE, +			  zprivs_state.syscaps_p->num, +			  zprivs_state.syscaps_p->caps, cflag)) +		return cap_set_proc(zprivs_state.caps); +	return -1;  } -zebra_privs_current_t -zprivs_state_caps (void) +zebra_privs_current_t zprivs_state_caps(void)  { -  int i; -  cap_flag_value_t val; - -  /* should be no possibility of being called without valid caps */ -  assert (zprivs_state.syscaps_p && zprivs_state.caps); -  if (! (zprivs_state.syscaps_p && zprivs_state.caps)) -    exit (1); -   -  for (i=0; i < zprivs_state.syscaps_p->num; i++) -    { -      if ( cap_get_flag (zprivs_state.caps, zprivs_state.syscaps_p->caps[i],  -                         CAP_EFFECTIVE, &val) ) -        { -          zlog_warn ("zprivs_state_caps: could not cap_get_flag, %s", -                     safe_strerror (errno) ); -          return ZPRIVS_UNKNOWN; -        } -      if (val == CAP_SET) -        return ZPRIVS_RAISED; -    } -  return ZPRIVS_LOWERED; +	int i; +	cap_flag_value_t val; + +	/* should be no possibility of being called without valid caps */ +	assert(zprivs_state.syscaps_p && zprivs_state.caps); +	if (!(zprivs_state.syscaps_p && zprivs_state.caps)) +		exit(1); + +	for (i = 0; i < zprivs_state.syscaps_p->num; i++) { +		if (cap_get_flag(zprivs_state.caps, +				 zprivs_state.syscaps_p->caps[i], CAP_EFFECTIVE, +				 &val)) { +			zlog_warn( +				"zprivs_state_caps: could not cap_get_flag, %s", +				safe_strerror(errno)); +			return ZPRIVS_UNKNOWN; +		} +		if (val == CAP_SET) +			return ZPRIVS_RAISED; +	} +	return ZPRIVS_LOWERED;  } -static void -zprivs_caps_init (struct zebra_privs_t *zprivs) +static void zprivs_caps_init(struct zebra_privs_t *zprivs)  { -  zprivs_state.syscaps_p = zcaps2sys (zprivs->caps_p, zprivs->cap_num_p); -  zprivs_state.syscaps_i = zcaps2sys (zprivs->caps_i, zprivs->cap_num_i); - -  /* Tell kernel we want caps maintained across uid changes */ -  if ( prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1 ) -    { -      fprintf (stderr, "privs_init: could not set PR_SET_KEEPCAPS, %s\n", -                safe_strerror (errno) ); -      exit(1); -    } - -  /* we have caps, we have no need to ever change back the original user */ -    /* only change uid if we don't have the correct one */ -    if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) -    { -      if ( setreuid (zprivs_state.zuid, zprivs_state.zuid) ) -        { -          fprintf (stderr, "zprivs_init (cap): could not setreuid, %s\n",  -                     safe_strerror (errno)); -          exit (1); -        } -    } - -  if ( !zprivs_state.syscaps_p ) -    return; -   -  if ( !(zprivs_state.caps = cap_init()) ) -    { -      fprintf (stderr, "privs_init: failed to cap_init, %s\n",  -               safe_strerror (errno)); -      exit (1); -    } - -  if ( cap_clear (zprivs_state.caps) ) -    { -      fprintf (stderr, "privs_init: failed to cap_clear, %s\n",  -               safe_strerror (errno)); -      exit (1); -    } -   -  /* set permitted caps */ -  cap_set_flag(zprivs_state.caps, CAP_PERMITTED,  -               zprivs_state.syscaps_p->num, -               zprivs_state.syscaps_p->caps, -               CAP_SET); -     -  /* set inheritable caps, if any */ -  if (zprivs_state.syscaps_i && zprivs_state.syscaps_i->num) -    { -      cap_set_flag(zprivs_state.caps, CAP_INHERITABLE,  -                   zprivs_state.syscaps_i->num,  -                   zprivs_state.syscaps_i->caps,  -                   CAP_SET); -    } -   -  /* apply caps. CAP_EFFECTIVE is cleared. we'll raise the caps as  -   * and when, and only when, they are needed. -   */ -  if ( cap_set_proc (zprivs_state.caps) )  -    { -      cap_t current_caps; -      char *current_caps_text = NULL; -      char *wanted_caps_text = NULL; - -      fprintf(stderr, "privs_init: initial cap_set_proc failed: %s\n", -              safe_strerror(errno)); - -      current_caps = cap_get_proc(); -      if (current_caps) -        { -          current_caps_text = cap_to_text(current_caps, NULL); -          cap_free(current_caps); -        } - -      wanted_caps_text = cap_to_text(zprivs_state.caps, NULL); -      fprintf(stderr, "Wanted caps: %s\n", wanted_caps_text ? wanted_caps_text : "???"); -      fprintf(stderr, "Have   caps: %s\n", current_caps_text ? current_caps_text : "???"); -      if (current_caps_text) -          cap_free(current_caps_text); -      if (wanted_caps_text) -          cap_free(wanted_caps_text); - -      exit (1); -    } -   -  /* set methods for the caller to use */ -  zprivs->change = zprivs_change_caps; -  zprivs->current_state = zprivs_state_caps; +	zprivs_state.syscaps_p = zcaps2sys(zprivs->caps_p, zprivs->cap_num_p); +	zprivs_state.syscaps_i = zcaps2sys(zprivs->caps_i, zprivs->cap_num_i); + +	/* Tell kernel we want caps maintained across uid changes */ +	if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) == -1) { +		fprintf(stderr, +			"privs_init: could not set PR_SET_KEEPCAPS, %s\n", +			safe_strerror(errno)); +		exit(1); +	} + +	/* we have caps, we have no need to ever change back the original user +	 */ +	/* only change uid if we don't have the correct one */ +	if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) { +		if (setreuid(zprivs_state.zuid, zprivs_state.zuid)) { +			fprintf(stderr, +				"zprivs_init (cap): could not setreuid, %s\n", +				safe_strerror(errno)); +			exit(1); +		} +	} + +	if (!zprivs_state.syscaps_p) +		return; + +	if (!(zprivs_state.caps = cap_init())) { +		fprintf(stderr, "privs_init: failed to cap_init, %s\n", +			safe_strerror(errno)); +		exit(1); +	} + +	if (cap_clear(zprivs_state.caps)) { +		fprintf(stderr, "privs_init: failed to cap_clear, %s\n", +			safe_strerror(errno)); +		exit(1); +	} + +	/* set permitted caps */ +	cap_set_flag(zprivs_state.caps, CAP_PERMITTED, +		     zprivs_state.syscaps_p->num, zprivs_state.syscaps_p->caps, +		     CAP_SET); + +	/* set inheritable caps, if any */ +	if (zprivs_state.syscaps_i && zprivs_state.syscaps_i->num) { +		cap_set_flag(zprivs_state.caps, CAP_INHERITABLE, +			     zprivs_state.syscaps_i->num, +			     zprivs_state.syscaps_i->caps, CAP_SET); +	} + +	/* apply caps. CAP_EFFECTIVE is cleared. we'll raise the caps as +	 * and when, and only when, they are needed. +	 */ +	if (cap_set_proc(zprivs_state.caps)) { +		cap_t current_caps; +		char *current_caps_text = NULL; +		char *wanted_caps_text = NULL; + +		fprintf(stderr, "privs_init: initial cap_set_proc failed: %s\n", +			safe_strerror(errno)); + +		current_caps = cap_get_proc(); +		if (current_caps) { +			current_caps_text = cap_to_text(current_caps, NULL); +			cap_free(current_caps); +		} + +		wanted_caps_text = cap_to_text(zprivs_state.caps, NULL); +		fprintf(stderr, "Wanted caps: %s\n", +			wanted_caps_text ? wanted_caps_text : "???"); +		fprintf(stderr, "Have   caps: %s\n", +			current_caps_text ? current_caps_text : "???"); +		if (current_caps_text) +			cap_free(current_caps_text); +		if (wanted_caps_text) +			cap_free(wanted_caps_text); + +		exit(1); +	} + +	/* set methods for the caller to use */ +	zprivs->change = zprivs_change_caps; +	zprivs->current_state = zprivs_state_caps;  } -static void -zprivs_caps_terminate (void) +static void zprivs_caps_terminate(void)  { -  /* clear all capabilities */ -  if (zprivs_state.caps) -      cap_clear (zprivs_state.caps); - -  /* and boom, capabilities are gone forever */ -  if ( cap_set_proc (zprivs_state.caps) )  -    { -      fprintf (stderr, "privs_terminate: cap_set_proc failed, %s", -                safe_strerror (errno) ); -      exit (1); -    }   - -  /* free up private state */ -  if (zprivs_state.syscaps_p->num) -    { -      XFREE (MTYPE_PRIVS, zprivs_state.syscaps_p->caps); -      XFREE (MTYPE_PRIVS, zprivs_state.syscaps_p); -    } -   -  if (zprivs_state.syscaps_i && zprivs_state.syscaps_i->num) -    { -      XFREE (MTYPE_PRIVS, zprivs_state.syscaps_i->caps); -      XFREE (MTYPE_PRIVS, zprivs_state.syscaps_i); -    } -   -  cap_free (zprivs_state.caps); +	/* clear all capabilities */ +	if (zprivs_state.caps) +		cap_clear(zprivs_state.caps); + +	/* and boom, capabilities are gone forever */ +	if (cap_set_proc(zprivs_state.caps)) { +		fprintf(stderr, "privs_terminate: cap_set_proc failed, %s", +			safe_strerror(errno)); +		exit(1); +	} + +	/* free up private state */ +	if (zprivs_state.syscaps_p->num) { +		XFREE(MTYPE_PRIVS, zprivs_state.syscaps_p->caps); +		XFREE(MTYPE_PRIVS, zprivs_state.syscaps_p); +	} + +	if (zprivs_state.syscaps_i && zprivs_state.syscaps_i->num) { +		XFREE(MTYPE_PRIVS, zprivs_state.syscaps_i->caps); +		XFREE(MTYPE_PRIVS, zprivs_state.syscaps_i); +	} + +	cap_free(zprivs_state.caps);  } -#elif defined (HAVE_SOLARIS_CAPABILITIES) /* !HAVE_LCAPS */ +#elif defined(HAVE_SOLARIS_CAPABILITIES) /* !HAVE_LCAPS */ -/* Solaris specific capability/privilege methods  +/* Solaris specific capability/privilege methods   *   * Resources:   * - the 'privileges' man page   * - http://cvs.opensolaris.org - * - http://blogs.sun.com/roller/page/gbrunett?entry=privilege_enabling_set_id_programs1 + * - + * http://blogs.sun.com/roller/page/gbrunett?entry=privilege_enabling_set_id_programs1   */ -static pset_t * -zprivs_caps_minimal () +static pset_t *zprivs_caps_minimal()  { -  pset_t *minimal; +	pset_t *minimal; -  if ((minimal = priv_str_to_set("basic", ",", NULL)) == NULL) -    { -      fprintf (stderr, "%s: couldn't get basic set!\n", __func__); -      exit (1); -    } +	if ((minimal = priv_str_to_set("basic", ",", NULL)) == NULL) { +		fprintf(stderr, "%s: couldn't get basic set!\n", __func__); +		exit(1); +	} -   /* create a minimal privilege set from the basic set */ -  (void) priv_delset(minimal, PRIV_PROC_EXEC); -  (void) priv_delset(minimal, PRIV_PROC_INFO); -  (void) priv_delset(minimal, PRIV_PROC_SESSION); -  (void) priv_delset(minimal, PRIV_FILE_LINK_ANY); +	/* create a minimal privilege set from the basic set */ +	(void)priv_delset(minimal, PRIV_PROC_EXEC); +	(void)priv_delset(minimal, PRIV_PROC_INFO); +	(void)priv_delset(minimal, PRIV_PROC_SESSION); +	(void)priv_delset(minimal, PRIV_FILE_LINK_ANY); -  return  minimal; +	return minimal;  }  /* convert zebras privileges to system capabilities */ -static pset_t * -zcaps2sys (zebra_capabilities_t *zcaps, int num) +static pset_t *zcaps2sys(zebra_capabilities_t *zcaps, int num)  { -  pset_t *syscaps; -  int i, j = 0; -   -  if ((syscaps = priv_allocset()) == NULL) -    { -      fprintf (stderr, "%s: could not allocate syscaps!\n", __func__); -      exit (1); -    } -     -  priv_emptyset (syscaps); -   -  for (i=0; i < num; i++) -    for (j = 0; j < cap_map[zcaps[i]].num; j++) -      priv_addset (syscaps, cap_map[zcaps[i]].system_caps[j]); -   -  return syscaps; +	pset_t *syscaps; +	int i, j = 0; + +	if ((syscaps = priv_allocset()) == NULL) { +		fprintf(stderr, "%s: could not allocate syscaps!\n", __func__); +		exit(1); +	} + +	priv_emptyset(syscaps); + +	for (i = 0; i < num; i++) +		for (j = 0; j < cap_map[zcaps[i]].num; j++) +			priv_addset(syscaps, cap_map[zcaps[i]].system_caps[j]); + +	return syscaps;  }  /* callback exported to users to RAISE and LOWER effective privileges   * from nothing to the given permitted set and back down   */ -int  -zprivs_change_caps (zebra_privs_ops_t op) +int zprivs_change_caps(zebra_privs_ops_t op)  { -  pset_t *privset; -   -  /* should be no possibility of being called without valid caps */ -  assert (zprivs_state.syscaps_p); -  if (!zprivs_state.syscaps_p) -    { -      fprintf (stderr, "%s: Eek, missing privileged caps!", __func__); -      exit (1); -    } - -  assert (zprivs_state.caps); -  if (!zprivs_state.caps) -    { -      fprintf (stderr, "%s: Eek, missing caps!", __func__); -      exit (1); -    } - -  /* to raise: copy original permitted as our working effective set -   * to lower: copy regular effective set stored in zprivs_state.caps -   */ -  if (op == ZPRIVS_RAISE) -    privset = zprivs_state.syscaps_p; -  else if (op == ZPRIVS_LOWER) -    privset = zprivs_state.caps; -  else -    return -1; -   -  if (setppriv (PRIV_SET, PRIV_EFFECTIVE, privset) != 0) -    return -1; -   -  return 0; +	pset_t *privset; + +	/* should be no possibility of being called without valid caps */ +	assert(zprivs_state.syscaps_p); +	if (!zprivs_state.syscaps_p) { +		fprintf(stderr, "%s: Eek, missing privileged caps!", __func__); +		exit(1); +	} + +	assert(zprivs_state.caps); +	if (!zprivs_state.caps) { +		fprintf(stderr, "%s: Eek, missing caps!", __func__); +		exit(1); +	} + +	/* to raise: copy original permitted as our working effective set +	 * to lower: copy regular effective set stored in zprivs_state.caps +	 */ +	if (op == ZPRIVS_RAISE) +		privset = zprivs_state.syscaps_p; +	else if (op == ZPRIVS_LOWER) +		privset = zprivs_state.caps; +	else +		return -1; + +	if (setppriv(PRIV_SET, PRIV_EFFECTIVE, privset) != 0) +		return -1; + +	return 0;  }  /* Retrieve current privilege state, is it RAISED or LOWERED? */ -zebra_privs_current_t  -zprivs_state_caps (void) +zebra_privs_current_t zprivs_state_caps(void)  { -  zebra_privs_current_t result; -  pset_t *effective; -   -  if ( (effective = priv_allocset()) == NULL) -    { -      fprintf (stderr, "%s: failed to get priv_allocset! %s\n", __func__, -               safe_strerror (errno)); -      return ZPRIVS_UNKNOWN; -    } -   -  if (getppriv (PRIV_EFFECTIVE, effective)) -    { -      fprintf (stderr, "%s: failed to get state! %s\n", __func__, -               safe_strerror (errno)); -      result = ZPRIVS_UNKNOWN; -    } -  else -    { -      if (priv_isequalset (effective, zprivs_state.syscaps_p)) -        result = ZPRIVS_RAISED; -      else if (priv_isequalset (effective, zprivs_state.caps)) -        result = ZPRIVS_LOWERED; -      else -        result = ZPRIVS_UNKNOWN; -    } -   -  priv_freeset (effective); -  return result; +	zebra_privs_current_t result; +	pset_t *effective; + +	if ((effective = priv_allocset()) == NULL) { +		fprintf(stderr, "%s: failed to get priv_allocset! %s\n", +			__func__, safe_strerror(errno)); +		return ZPRIVS_UNKNOWN; +	} + +	if (getppriv(PRIV_EFFECTIVE, effective)) { +		fprintf(stderr, "%s: failed to get state! %s\n", __func__, +			safe_strerror(errno)); +		result = ZPRIVS_UNKNOWN; +	} else { +		if (priv_isequalset(effective, zprivs_state.syscaps_p)) +			result = ZPRIVS_RAISED; +		else if (priv_isequalset(effective, zprivs_state.caps)) +			result = ZPRIVS_LOWERED; +		else +			result = ZPRIVS_UNKNOWN; +	} + +	priv_freeset(effective); +	return result;  } -static void -zprivs_caps_init (struct zebra_privs_t *zprivs) +static void zprivs_caps_init(struct zebra_privs_t *zprivs)  { -  pset_t *basic; -  pset_t *minimal; -   -  /* the specified sets */ -  zprivs_state.syscaps_p = zcaps2sys (zprivs->caps_p, zprivs->cap_num_p); -  zprivs_state.syscaps_i = zcaps2sys (zprivs->caps_i, zprivs->cap_num_i); -   -  /* nonsensical to have gotten here but not have capabilities */ -  if (!zprivs_state.syscaps_p) -    { -      fprintf (stderr, "%s: capabilities enabled, " -                       "but no valid capabilities supplied\n", -                       __func__); -    } -   -  /* We retain the basic set in our permitted set, as Linux has no -   * equivalent. The basic set on Linux hence is implicit, always -   * there. -   */ -  if ((basic = priv_str_to_set("basic", ",", NULL)) == NULL) -    { -      fprintf (stderr, "%s: couldn't get basic set!\n", __func__); -      exit (1); -    } -  -  /* Add the basic set to the permitted set */ -  priv_union (basic, zprivs_state.syscaps_p); -  priv_freeset (basic); -   -  /* Hey kernel, we know about privileges!  -   * this isn't strictly required, use of setppriv should have same effect -   */ -  if (setpflags (PRIV_AWARE, 1)) -    { -      fprintf (stderr, "%s: error setting PRIV_AWARE!, %s\n", __func__, -               safe_strerror (errno) ); -      exit (1); -    } -   -  /* need either valid or empty sets for both p and i.. */ -  assert (zprivs_state.syscaps_i && zprivs_state.syscaps_p); -   -  /* we have caps, we have no need to ever change back the original user -   * change real, effective and saved to the specified user. -   */ -   /* only change uid if we don't have the correct one */ -   if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) -    { -      if ( setreuid (zprivs_state.zuid, zprivs_state.zuid) ) -        { -          fprintf (stderr, "%s: could not setreuid, %s\n",  -                   __func__, safe_strerror (errno)); -          exit (1); -        } -    } -   -  /* set the permitted set */ -  if (setppriv (PRIV_SET, PRIV_PERMITTED, zprivs_state.syscaps_p)) -    { -      fprintf (stderr, "%s: error setting permitted set!, %s\n", __func__, -               safe_strerror (errno) ); -      exit (1); -    } -   -  /* set the inheritable set */ -  if (setppriv (PRIV_SET, PRIV_INHERITABLE, zprivs_state.syscaps_i)) -    { -      fprintf (stderr, "%s: error setting inheritable set!, %s\n", __func__, -               safe_strerror (errno) ); -      exit (1); -    } - -  /* we need a minimal basic set for 'effective', potentially for inheritable too */ -  minimal = zprivs_caps_minimal(); - -  /* now set the effective set with a subset of basic privileges */ -  if (setppriv (PRIV_SET, PRIV_EFFECTIVE, minimal)) -    { -      fprintf (stderr, "%s: error setting effective set!, %s\n", __func__, -               safe_strerror (errno) ); -      exit (1); -    } -   -  /* we'll use the minimal set as our working-storage privset */ -  zprivs_state.caps = minimal; -   -  /* set methods for the caller to use */ -  zprivs->change = zprivs_change_caps; -  zprivs->current_state = zprivs_state_caps; +	pset_t *basic; +	pset_t *minimal; + +	/* the specified sets */ +	zprivs_state.syscaps_p = zcaps2sys(zprivs->caps_p, zprivs->cap_num_p); +	zprivs_state.syscaps_i = zcaps2sys(zprivs->caps_i, zprivs->cap_num_i); + +	/* nonsensical to have gotten here but not have capabilities */ +	if (!zprivs_state.syscaps_p) { +		fprintf(stderr, +			"%s: capabilities enabled, " +			"but no valid capabilities supplied\n", +			__func__); +	} + +	/* We retain the basic set in our permitted set, as Linux has no +	 * equivalent. The basic set on Linux hence is implicit, always +	 * there. +	 */ +	if ((basic = priv_str_to_set("basic", ",", NULL)) == NULL) { +		fprintf(stderr, "%s: couldn't get basic set!\n", __func__); +		exit(1); +	} + +	/* Add the basic set to the permitted set */ +	priv_union(basic, zprivs_state.syscaps_p); +	priv_freeset(basic); + +	/* Hey kernel, we know about privileges! +	 * this isn't strictly required, use of setppriv should have same effect +	 */ +	if (setpflags(PRIV_AWARE, 1)) { +		fprintf(stderr, "%s: error setting PRIV_AWARE!, %s\n", __func__, +			safe_strerror(errno)); +		exit(1); +	} + +	/* need either valid or empty sets for both p and i.. */ +	assert(zprivs_state.syscaps_i && zprivs_state.syscaps_p); + +	/* we have caps, we have no need to ever change back the original user +	 * change real, effective and saved to the specified user. +	 */ +	/* only change uid if we don't have the correct one */ +	if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) { +		if (setreuid(zprivs_state.zuid, zprivs_state.zuid)) { +			fprintf(stderr, "%s: could not setreuid, %s\n", +				__func__, safe_strerror(errno)); +			exit(1); +		} +	} + +	/* set the permitted set */ +	if (setppriv(PRIV_SET, PRIV_PERMITTED, zprivs_state.syscaps_p)) { +		fprintf(stderr, "%s: error setting permitted set!, %s\n", +			__func__, safe_strerror(errno)); +		exit(1); +	} + +	/* set the inheritable set */ +	if (setppriv(PRIV_SET, PRIV_INHERITABLE, zprivs_state.syscaps_i)) { +		fprintf(stderr, "%s: error setting inheritable set!, %s\n", +			__func__, safe_strerror(errno)); +		exit(1); +	} + +	/* we need a minimal basic set for 'effective', potentially for +	 * inheritable too */ +	minimal = zprivs_caps_minimal(); + +	/* now set the effective set with a subset of basic privileges */ +	if (setppriv(PRIV_SET, PRIV_EFFECTIVE, minimal)) { +		fprintf(stderr, "%s: error setting effective set!, %s\n", +			__func__, safe_strerror(errno)); +		exit(1); +	} + +	/* we'll use the minimal set as our working-storage privset */ +	zprivs_state.caps = minimal; + +	/* set methods for the caller to use */ +	zprivs->change = zprivs_change_caps; +	zprivs->current_state = zprivs_state_caps;  } -static void -zprivs_caps_terminate (void) +static void zprivs_caps_terminate(void)  { -  assert (zprivs_state.caps); -   -  /* clear all capabilities by using working-storage privset */ -  setppriv (PRIV_SET, PRIV_EFFECTIVE, zprivs_state.caps); -  setppriv (PRIV_SET, PRIV_PERMITTED, zprivs_state.caps); -  setppriv (PRIV_SET, PRIV_INHERITABLE, zprivs_state.caps); -   -  /* free up private state */ -  if (zprivs_state.syscaps_p) -    priv_freeset (zprivs_state.syscaps_p); -  if (zprivs_state.syscaps_i) -    priv_freeset (zprivs_state.syscaps_i); -   -  priv_freeset (zprivs_state.caps); +	assert(zprivs_state.caps); + +	/* clear all capabilities by using working-storage privset */ +	setppriv(PRIV_SET, PRIV_EFFECTIVE, zprivs_state.caps); +	setppriv(PRIV_SET, PRIV_PERMITTED, zprivs_state.caps); +	setppriv(PRIV_SET, PRIV_INHERITABLE, zprivs_state.caps); + +	/* free up private state */ +	if (zprivs_state.syscaps_p) +		priv_freeset(zprivs_state.syscaps_p); +	if (zprivs_state.syscaps_i) +		priv_freeset(zprivs_state.syscaps_i); + +	priv_freeset(zprivs_state.caps);  }  #else /* !HAVE_LCAPS && ! HAVE_SOLARIS_CAPABILITIES */  #error "Neither Solaris nor Linux capabilities, dazed and confused..."  #endif /* HAVE_LCAPS */  #endif /* HAVE_CAPABILITIES */ -int -zprivs_change_uid (zebra_privs_ops_t op) +int zprivs_change_uid(zebra_privs_ops_t op)  { -  if (zprivs_state.zsuid == zprivs_state.zuid) -    return 0; -  if (op == ZPRIVS_RAISE) -    return seteuid (zprivs_state.zsuid); -  else if (op == ZPRIVS_LOWER) -    return seteuid (zprivs_state.zuid); -  else -    return -1; +	if (zprivs_state.zsuid == zprivs_state.zuid) +		return 0; +	if (op == ZPRIVS_RAISE) +		return seteuid(zprivs_state.zsuid); +	else if (op == ZPRIVS_LOWER) +		return seteuid(zprivs_state.zuid); +	else +		return -1;  } -zebra_privs_current_t -zprivs_state_uid (void) +zebra_privs_current_t zprivs_state_uid(void)  { -  return ( (zprivs_state.zuid == geteuid()) ? ZPRIVS_LOWERED : ZPRIVS_RAISED); +	return ((zprivs_state.zuid == geteuid()) ? ZPRIVS_LOWERED +						 : ZPRIVS_RAISED);  } -int -zprivs_change_null (zebra_privs_ops_t op) +int zprivs_change_null(zebra_privs_ops_t op)  { -  return 0; +	return 0;  } -zebra_privs_current_t -zprivs_state_null (void) +zebra_privs_current_t zprivs_state_null(void)  { -  return zprivs_null_state; +	return zprivs_null_state;  }  #ifndef HAVE_GETGROUPLIST  /* Solaris 11 has no getgrouplist() */ -static int -getgrouplist(const char *user, gid_t group, gid_t *groups, int *ngroups) +static int getgrouplist(const char *user, gid_t group, gid_t *groups, +			int *ngroups)  { -  struct group *grp; -  size_t usridx; -  int pos = 0, ret; - -  if (pos < *ngroups) -    groups[pos] = group; -  pos++; - -  setgrent(); -  while ((grp = getgrent())) -    { -      if (grp->gr_gid == group) -        continue; -      for (usridx = 0; grp->gr_mem[usridx] != NULL; usridx++) -        if (!strcmp (grp->gr_mem[usridx], user)) -          { -            if (pos < *ngroups) -              groups[pos] = grp->gr_gid; -            pos++; -            break; -          } -    } -  endgrent(); - -  ret = (pos <= *ngroups) ? pos : -1; -  *ngroups = pos; -  return ret; +	struct group *grp; +	size_t usridx; +	int pos = 0, ret; + +	if (pos < *ngroups) +		groups[pos] = group; +	pos++; + +	setgrent(); +	while ((grp = getgrent())) { +		if (grp->gr_gid == group) +			continue; +		for (usridx = 0; grp->gr_mem[usridx] != NULL; usridx++) +			if (!strcmp(grp->gr_mem[usridx], user)) { +				if (pos < *ngroups) +					groups[pos] = grp->gr_gid; +				pos++; +				break; +			} +	} +	endgrent(); + +	ret = (pos <= *ngroups) ? pos : -1; +	*ngroups = pos; +	return ret;  }  #endif /* HAVE_GETGROUPLIST */ -void -zprivs_init(struct zebra_privs_t *zprivs) +void zprivs_init(struct zebra_privs_t *zprivs)  { -  struct passwd *pwentry = NULL; -  struct group *grentry = NULL; -  gid_t groups[NGROUPS_MAX]; -  int i, ngroups = 0; -  int found = 0; - -  if (!zprivs) -    { -      fprintf (stderr, "zprivs_init: called with NULL arg!\n"); -      exit (1); -    } - -  if (zprivs->vty_group) -    { -      /* in a "NULL" setup, this is allowed to fail too, but still try. */ -      if ((grentry = getgrnam (zprivs->vty_group))) -        zprivs_state.vtygrp = grentry->gr_gid; -      else -        zprivs_state.vtygrp = (gid_t)-1; -    } - -  /* NULL privs */ -  if (! (zprivs->user || zprivs->group  -         || zprivs->cap_num_p || zprivs->cap_num_i) ) -    { -      zprivs->change = zprivs_change_null; -      zprivs->current_state = zprivs_state_null; -      return; -    } - -  if (zprivs->user) -    { -      if ( (pwentry = getpwnam (zprivs->user)) == NULL ) -        { -          /* cant use log.h here as it depends on vty */ -          fprintf (stderr, "privs_init: could not lookup user %s\n", -                   zprivs->user); -          exit (1); -        } - -      zprivs_state.zuid = pwentry->pw_uid; -      zprivs_state.zgid = pwentry->pw_gid; -    } - -  grentry = NULL; - -  if (zprivs->group) -    { -      if ( (grentry = getgrnam (zprivs->group)) == NULL ) -        { -          fprintf (stderr, "privs_init: could not lookup group %s\n", -                   zprivs->group); -          exit (1); -        } - -      zprivs_state.zgid = grentry->gr_gid; -    } - -  if (zprivs->user) -    { -      ngroups = sizeof(groups); -      if (getgrouplist (zprivs->user, zprivs_state.zgid, groups, &ngroups) < 0) -        { -          /* cant use log.h here as it depends on vty */ -          fprintf (stderr, "privs_init: could not getgrouplist for user %s\n", -                   zprivs->user); -          exit (1); -        } -    } - -  if (zprivs->vty_group) -    /* Add the vty_group to the supplementary groups so it can be chowned to */ -    { -      if (zprivs_state.vtygrp == (gid_t)-1) -        { -          fprintf (stderr, "privs_init: could not lookup vty group %s\n", -                   zprivs->vty_group); -          exit (1); -        } - -      for ( i = 0; i < ngroups; i++ ) -        if ( groups[i] == zprivs_state.vtygrp ) -          { -            found++; -            break; -          } - -      if (!found) -        { -          fprintf (stderr, "privs_init: user(%s) is not part of vty group specified(%s)\n", -                   zprivs->user, zprivs->vty_group); -          exit (1); -        } -      if ( i >= ngroups && ngroups < (int) ZEBRA_NUM_OF(groups) ) -        { -          groups[i] = zprivs_state.vtygrp; -        } -    } - -  /* add groups only if we changed uid - otherwise skip */ -  if ((ngroups) && (zprivs_state.zsuid != zprivs_state.zuid)) -    { -      if ( setgroups (ngroups, groups) ) -        { -          fprintf (stderr, "privs_init: could not setgroups, %s\n", -                   safe_strerror (errno) ); -          exit (1); -        } -    } - -  /* change gid only if we changed uid - otherwise skip */ -  if ((zprivs_state.zgid) && (zprivs_state.zsuid != zprivs_state.zuid)) -    { -      /* change group now, forever. uid we do later */ -      if ( setregid (zprivs_state.zgid, zprivs_state.zgid) ) -        { -          fprintf (stderr, "zprivs_init: could not setregid, %s\n", -                    safe_strerror (errno) ); -          exit (1); -        } -    } -   +	struct passwd *pwentry = NULL; +	struct group *grentry = NULL; +	gid_t groups[NGROUPS_MAX]; +	int i, ngroups = 0; +	int found = 0; + +	if (!zprivs) { +		fprintf(stderr, "zprivs_init: called with NULL arg!\n"); +		exit(1); +	} + +	if (zprivs->vty_group) { +		/* in a "NULL" setup, this is allowed to fail too, but still +		 * try. */ +		if ((grentry = getgrnam(zprivs->vty_group))) +			zprivs_state.vtygrp = grentry->gr_gid; +		else +			zprivs_state.vtygrp = (gid_t)-1; +	} + +	/* NULL privs */ +	if (!(zprivs->user || zprivs->group || zprivs->cap_num_p +	      || zprivs->cap_num_i)) { +		zprivs->change = zprivs_change_null; +		zprivs->current_state = zprivs_state_null; +		return; +	} + +	if (zprivs->user) { +		if ((pwentry = getpwnam(zprivs->user)) == NULL) { +			/* cant use log.h here as it depends on vty */ +			fprintf(stderr, +				"privs_init: could not lookup user %s\n", +				zprivs->user); +			exit(1); +		} + +		zprivs_state.zuid = pwentry->pw_uid; +		zprivs_state.zgid = pwentry->pw_gid; +	} + +	grentry = NULL; + +	if (zprivs->group) { +		if ((grentry = getgrnam(zprivs->group)) == NULL) { +			fprintf(stderr, +				"privs_init: could not lookup group %s\n", +				zprivs->group); +			exit(1); +		} + +		zprivs_state.zgid = grentry->gr_gid; +	} + +	if (zprivs->user) { +		ngroups = sizeof(groups); +		if (getgrouplist(zprivs->user, zprivs_state.zgid, groups, +				 &ngroups) +		    < 0) { +			/* cant use log.h here as it depends on vty */ +			fprintf(stderr, +				"privs_init: could not getgrouplist for user %s\n", +				zprivs->user); +			exit(1); +		} +	} + +	if (zprivs->vty_group) +	/* Add the vty_group to the supplementary groups so it can be chowned to +	   */ +	{ +		if (zprivs_state.vtygrp == (gid_t)-1) { +			fprintf(stderr, +				"privs_init: could not lookup vty group %s\n", +				zprivs->vty_group); +			exit(1); +		} + +		for (i = 0; i < ngroups; i++) +			if (groups[i] == zprivs_state.vtygrp) { +				found++; +				break; +			} + +		if (!found) { +			fprintf(stderr, +				"privs_init: user(%s) is not part of vty group specified(%s)\n", +				zprivs->user, zprivs->vty_group); +			exit(1); +		} +		if (i >= ngroups && ngroups < (int)ZEBRA_NUM_OF(groups)) { +			groups[i] = zprivs_state.vtygrp; +		} +	} + +	/* add groups only if we changed uid - otherwise skip */ +	if ((ngroups) && (zprivs_state.zsuid != zprivs_state.zuid)) { +		if (setgroups(ngroups, groups)) { +			fprintf(stderr, "privs_init: could not setgroups, %s\n", +				safe_strerror(errno)); +			exit(1); +		} +	} + +	/* change gid only if we changed uid - otherwise skip */ +	if ((zprivs_state.zgid) && (zprivs_state.zsuid != zprivs_state.zuid)) { +		/* change group now, forever. uid we do later */ +		if (setregid(zprivs_state.zgid, zprivs_state.zgid)) { +			fprintf(stderr, "zprivs_init: could not setregid, %s\n", +				safe_strerror(errno)); +			exit(1); +		} +	} +  #ifdef HAVE_CAPABILITIES -  zprivs_caps_init (zprivs); -#else /* !HAVE_CAPABILITIES */ -  /* we dont have caps. we'll need to maintain rid and saved uid -   * and change euid back to saved uid (who we presume has all neccessary -   * privileges) whenever we are asked to raise our privileges. -   * -   * This is not worth that much security wise, but all we can do. -   */ -  zprivs_state.zsuid = geteuid();   -  /* only change uid if we don't have the correct one */ -  if (( zprivs_state.zuid ) && (zprivs_state.zsuid != zprivs_state.zuid)) -    { -      if ( setreuid (-1, zprivs_state.zuid) ) -        { -          fprintf (stderr, "privs_init (uid): could not setreuid, %s\n",  -                   safe_strerror (errno)); -          exit (1); -        } -    } -   -  zprivs->change = zprivs_change_uid; -  zprivs->current_state = zprivs_state_uid; +	zprivs_caps_init(zprivs); +#else  /* !HAVE_CAPABILITIES */ +	/* we dont have caps. we'll need to maintain rid and saved uid +	 * and change euid back to saved uid (who we presume has all neccessary +	 * privileges) whenever we are asked to raise our privileges. +	 * +	 * This is not worth that much security wise, but all we can do. +	 */ +	zprivs_state.zsuid = geteuid(); +	/* only change uid if we don't have the correct one */ +	if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) { +		if (setreuid(-1, zprivs_state.zuid)) { +			fprintf(stderr, +				"privs_init (uid): could not setreuid, %s\n", +				safe_strerror(errno)); +			exit(1); +		} +	} + +	zprivs->change = zprivs_change_uid; +	zprivs->current_state = zprivs_state_uid;  #endif /* HAVE_CAPABILITIES */  } -void  -zprivs_terminate (struct zebra_privs_t *zprivs) +void zprivs_terminate(struct zebra_privs_t *zprivs)  { -  if (!zprivs) -    { -      fprintf (stderr, "%s: no privs struct given, terminating", __func__); -      exit (0); -    } -   +	if (!zprivs) { +		fprintf(stderr, "%s: no privs struct given, terminating", +			__func__); +		exit(0); +	} +  #ifdef HAVE_CAPABILITIES -  zprivs_caps_terminate(); -#else /* !HAVE_CAPABILITIES */ -  /* only change uid if we don't have the correct one */ -  if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) -    { -      if ( setreuid (zprivs_state.zuid, zprivs_state.zuid) ) -        { -          fprintf (stderr, "privs_terminate: could not setreuid, %s",  -                     safe_strerror (errno) ); -          exit (1); -        } -     } +	zprivs_caps_terminate(); +#else  /* !HAVE_CAPABILITIES */ +	/* only change uid if we don't have the correct one */ +	if ((zprivs_state.zuid) && (zprivs_state.zsuid != zprivs_state.zuid)) { +		if (setreuid(zprivs_state.zuid, zprivs_state.zuid)) { +			fprintf(stderr, +				"privs_terminate: could not setreuid, %s", +				safe_strerror(errno)); +			exit(1); +		} +	}  #endif /* HAVE_LCAPS */ -  zprivs->change = zprivs_change_null; -  zprivs->current_state = zprivs_state_null; -  zprivs_null_state = ZPRIVS_LOWERED; -  return; +	zprivs->change = zprivs_change_null; +	zprivs->current_state = zprivs_state_null; +	zprivs_null_state = ZPRIVS_LOWERED; +	return;  } -void -zprivs_get_ids(struct zprivs_ids_t *ids) +void zprivs_get_ids(struct zprivs_ids_t *ids)  { -   ids->uid_priv = getuid(); -   (zprivs_state.zuid) ? (ids->uid_normal = zprivs_state.zuid) -                     : (ids->uid_normal = -1); -   (zprivs_state.zgid) ? (ids->gid_normal = zprivs_state.zgid) -                     : (ids->gid_normal = -1); -   (zprivs_state.vtygrp) ? (ids->gid_vty = zprivs_state.vtygrp) -                       : (ids->gid_vty = -1); -    -   return; +	ids->uid_priv = getuid(); +	(zprivs_state.zuid) ? (ids->uid_normal = zprivs_state.zuid) +			    : (ids->uid_normal = -1); +	(zprivs_state.zgid) ? (ids->gid_normal = zprivs_state.zgid) +			    : (ids->gid_normal = -1); +	(zprivs_state.vtygrp) ? (ids->gid_vty = zprivs_state.vtygrp) +			      : (ids->gid_vty = -1); + +	return;  } diff --git a/lib/privs.h b/lib/privs.h index 46d614e008..74bbc36bee 100644 --- a/lib/privs.h +++ b/lib/privs.h @@ -1,4 +1,4 @@ -/*  +/*   * Zebra privileges header.   *   * Copyright (C) 2003 Paul Jakma. @@ -18,73 +18,67 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_PRIVS_H  #define _ZEBRA_PRIVS_H  /* list of zebra capabilities */ -typedef enum  -{ -  ZCAP_SETID, -  ZCAP_BIND, -  ZCAP_NET_ADMIN, -  ZCAP_SYS_ADMIN, -  ZCAP_NET_RAW, -  ZCAP_CHROOT, -  ZCAP_NICE, -  ZCAP_PTRACE, -  ZCAP_DAC_OVERRIDE, -  ZCAP_READ_SEARCH, -  ZCAP_FOWNER, -  ZCAP_MAX +typedef enum { +	ZCAP_SETID, +	ZCAP_BIND, +	ZCAP_NET_ADMIN, +	ZCAP_SYS_ADMIN, +	ZCAP_NET_RAW, +	ZCAP_CHROOT, +	ZCAP_NICE, +	ZCAP_PTRACE, +	ZCAP_DAC_OVERRIDE, +	ZCAP_READ_SEARCH, +	ZCAP_FOWNER, +	ZCAP_MAX  } zebra_capabilities_t; -typedef enum -{ -  ZPRIVS_LOWERED, -  ZPRIVS_RAISED, -  ZPRIVS_UNKNOWN, +typedef enum { +	ZPRIVS_LOWERED, +	ZPRIVS_RAISED, +	ZPRIVS_UNKNOWN,  } zebra_privs_current_t; -typedef enum -{ -  ZPRIVS_RAISE, -  ZPRIVS_LOWER, +typedef enum { +	ZPRIVS_RAISE, +	ZPRIVS_LOWER,  } zebra_privs_ops_t; -struct zebra_privs_t -{ -  zebra_capabilities_t *caps_p;       /* caps required for operation */ -  zebra_capabilities_t *caps_i;       /* caps to allow inheritance of */ -  int cap_num_p;                      /* number of caps in arrays */ -  int cap_num_i;                     -  const char *user;                   /* user and group to run as */ -  const char *group; -  const char *vty_group;              /* group to chown vty socket to */ -  /* methods */ -  int  -    (*change) (zebra_privs_ops_t);    /* change privileges, 0 on success */ -  zebra_privs_current_t  -    (*current_state) (void);          /* current privilege state */ +struct zebra_privs_t { +	zebra_capabilities_t *caps_p; /* caps required for operation */ +	zebra_capabilities_t *caps_i; /* caps to allow inheritance of */ +	int cap_num_p;		      /* number of caps in arrays */ +	int cap_num_i; +	const char *user; /* user and group to run as */ +	const char *group; +	const char *vty_group; /* group to chown vty socket to */ +	/* methods */ +	int (*change)(zebra_privs_ops_t); /* change privileges, 0 on success */ +	zebra_privs_current_t (*current_state)( +		void); /* current privilege state */  }; -struct zprivs_ids_t -{ -  /* -1 is undefined */ -  uid_t uid_priv;                     /* privileged uid */ -  uid_t uid_normal;                   /* normal uid */ -  gid_t gid_priv;                     /* privileged uid */ -  gid_t gid_normal;                   /* normal uid */ -  gid_t gid_vty;                      /* vty gid */ +struct zprivs_ids_t { +	/* -1 is undefined */ +	uid_t uid_priv;   /* privileged uid */ +	uid_t uid_normal; /* normal uid */ +	gid_t gid_priv;   /* privileged uid */ +	gid_t gid_normal; /* normal uid */ +	gid_t gid_vty;    /* vty gid */  }; -  /* initialise zebra privileges */ -extern void zprivs_init (struct zebra_privs_t *zprivs); -  /* drop all and terminate privileges */  -extern void zprivs_terminate (struct zebra_privs_t *); -  /* query for runtime uid's and gid's, eg vty needs this */ +/* initialise zebra privileges */ +extern void zprivs_init(struct zebra_privs_t *zprivs); +/* drop all and terminate privileges */ +extern void zprivs_terminate(struct zebra_privs_t *); +/* query for runtime uid's and gid's, eg vty needs this */  extern void zprivs_get_ids(struct zprivs_ids_t *);  #endif /* _ZEBRA_PRIVS_H */ diff --git a/lib/ptm_lib.c b/lib/ptm_lib.c index a93d7b8476..89484f73d5 100644 --- a/lib/ptm_lib.c +++ b/lib/ptm_lib.c @@ -33,445 +33,433 @@  #define DEBUG_E 0  #define DEBUG_V 0 -#define ERRLOG(fmt, ...) \ -  do { if (DEBUG_E) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \ -			    __LINE__, __func__, ##__VA_ARGS__); } while (0) - -#define DLOG(fmt, ...) \ -  do { if (DEBUG_V) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \ -			    __LINE__, __func__, ##__VA_ARGS__); } while (0) +#define ERRLOG(fmt, ...)                                                       \ +	do {                                                                   \ +		if (DEBUG_E)                                                   \ +			fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__,          \ +				__LINE__, __func__, ##__VA_ARGS__);            \ +	} while (0) + +#define DLOG(fmt, ...)                                                         \ +	do {                                                                   \ +		if (DEBUG_V)                                                   \ +			fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__,          \ +				__LINE__, __func__, ##__VA_ARGS__);            \ +	} while (0)  typedef struct ptm_lib_msg_ctxt_s { -    int cmd_id; -    csv_t *csv; -    ptmlib_msg_type type; +	int cmd_id; +	csv_t *csv; +	ptmlib_msg_type type;  } ptm_lib_msg_ctxt_t; -static csv_record_t * -_ptm_lib_encode_header(csv_t *csv, -		               csv_record_t *rec, -		               int msglen, -		               int version, -                       int type, -                       int cmd_id, -                       char *client_name) +static csv_record_t *_ptm_lib_encode_header(csv_t *csv, csv_record_t *rec, +					    int msglen, int version, int type, +					    int cmd_id, char *client_name)  { -    char msglen_buf[16], vers_buf[16], type_buf[16], cmdid_buf[16]; -    char client_buf[32]; -    csv_record_t *rec1; - -    sprintf(msglen_buf, "%4u", msglen); -    sprintf(vers_buf, "%4u", version); -    sprintf(type_buf, "%4u", type); -    sprintf(cmdid_buf, "%4u", cmd_id); -    snprintf(client_buf, 17, "%16.16s", client_name); -    if (rec) { -        rec1 = csv_encode_record(csv, rec, 5, msglen_buf, vers_buf, -                type_buf, cmdid_buf, client_buf); -    } else { -        rec1 = csv_encode(csv, 5, msglen_buf, vers_buf, -                type_buf, cmdid_buf, client_buf); -    } -    return (rec1); +	char msglen_buf[16], vers_buf[16], type_buf[16], cmdid_buf[16]; +	char client_buf[32]; +	csv_record_t *rec1; + +	sprintf(msglen_buf, "%4u", msglen); +	sprintf(vers_buf, "%4u", version); +	sprintf(type_buf, "%4u", type); +	sprintf(cmdid_buf, "%4u", cmd_id); +	snprintf(client_buf, 17, "%16.16s", client_name); +	if (rec) { +		rec1 = csv_encode_record(csv, rec, 5, msglen_buf, vers_buf, +					 type_buf, cmdid_buf, client_buf); +	} else { +		rec1 = csv_encode(csv, 5, msglen_buf, vers_buf, type_buf, +				  cmdid_buf, client_buf); +	} +	return (rec1);  } -static int -_ptm_lib_decode_header (csv_t *csv, -                       int *msglen, -                       int *version, -                       int *type, -                       int *cmd_id, -                       char *client_name) +static int _ptm_lib_decode_header(csv_t *csv, int *msglen, int *version, +				  int *type, int *cmd_id, char *client_name)  { -    char *hdr; -    csv_record_t *rec; -    csv_field_t *fld; -    int i, j; - -    csv_decode(csv, NULL); -    rec = csv_record_iter(csv); -    if (rec == NULL) { -        DLOG("malformed CSV\n"); -        return (-1); -    } -    hdr = csv_field_iter(rec, &fld); -    if (hdr == NULL) { -        DLOG("malformed CSV\n"); -        return (-1); -    } -    *msglen = atoi(hdr); -    hdr = csv_field_iter_next(&fld); -    if (hdr == NULL) { -        DLOG("malformed CSV\n"); -        return (-1); -    } -    *version = atoi(hdr); -    hdr = csv_field_iter_next(&fld); -    if (hdr == NULL) { -        DLOG("malformed CSV\n"); -        return (-1); -    } -    *type = atoi(hdr); -    hdr = csv_field_iter_next(&fld); -    if (hdr == NULL) { -        DLOG("malformed CSV\n"); -        return (-1); -    } -    *cmd_id = atoi(hdr); -    hdr = csv_field_iter_next(&fld); -    if (hdr == NULL) { -        DLOG("malformed CSV\n"); -        return (-1); -    } -    /* remove leading spaces */ -    for (i = j = 0; i < csv_field_len(fld); i++) { -        if (!isspace(hdr[i])) { -            client_name[j] = hdr[i]; -            j++; -        } -    } -    client_name[j] = '\0'; - -    return (0); +	char *hdr; +	csv_record_t *rec; +	csv_field_t *fld; +	int i, j; + +	csv_decode(csv, NULL); +	rec = csv_record_iter(csv); +	if (rec == NULL) { +		DLOG("malformed CSV\n"); +		return (-1); +	} +	hdr = csv_field_iter(rec, &fld); +	if (hdr == NULL) { +		DLOG("malformed CSV\n"); +		return (-1); +	} +	*msglen = atoi(hdr); +	hdr = csv_field_iter_next(&fld); +	if (hdr == NULL) { +		DLOG("malformed CSV\n"); +		return (-1); +	} +	*version = atoi(hdr); +	hdr = csv_field_iter_next(&fld); +	if (hdr == NULL) { +		DLOG("malformed CSV\n"); +		return (-1); +	} +	*type = atoi(hdr); +	hdr = csv_field_iter_next(&fld); +	if (hdr == NULL) { +		DLOG("malformed CSV\n"); +		return (-1); +	} +	*cmd_id = atoi(hdr); +	hdr = csv_field_iter_next(&fld); +	if (hdr == NULL) { +		DLOG("malformed CSV\n"); +		return (-1); +	} +	/* remove leading spaces */ +	for (i = j = 0; i < csv_field_len(fld); i++) { +		if (!isspace(hdr[i])) { +			client_name[j] = hdr[i]; +			j++; +		} +	} +	client_name[j] = '\0'; + +	return (0);  } -int -ptm_lib_append_msg(ptm_lib_handle_t *hdl, void *ctxt, -                   const char *key, const char *val) +int ptm_lib_append_msg(ptm_lib_handle_t *hdl, void *ctxt, const char *key, +		       const char *val)  { -    ptm_lib_msg_ctxt_t *p_ctxt = ctxt; -    csv_t *csv; -    csv_record_t *mh_rec, *rec; - -    if (!p_ctxt) { -        ERRLOG("%s: no context \n", __FUNCTION__); -        return -1; -    } - -    csv = p_ctxt->csv; -    mh_rec = csv_record_iter(csv); -    rec = csv_record_iter_next(mh_rec); - -    /* append to the hdr record */ -    rec = csv_append_record(csv, rec, 1, key); -    if (!rec) { -        ERRLOG("%s: Could not append key \n", __FUNCTION__); -        return -1; -    } - -    rec = csv_record_iter_next(rec); -    /* append to the data record */ -    rec = csv_append_record(csv, rec, 1, val); -    if (!rec) { -        ERRLOG("%s: Could not append val \n", __FUNCTION__); -        return -1; -    } - -    /* update the msg hdr */ -    _ptm_lib_encode_header(csv, mh_rec, -                    (csvlen(csv) - PTMLIB_MSG_HDR_LEN), -                    PTMLIB_MSG_VERSION, p_ctxt->type, -                    p_ctxt->cmd_id, hdl->client_name); - -    return 0; +	ptm_lib_msg_ctxt_t *p_ctxt = ctxt; +	csv_t *csv; +	csv_record_t *mh_rec, *rec; + +	if (!p_ctxt) { +		ERRLOG("%s: no context \n", __FUNCTION__); +		return -1; +	} + +	csv = p_ctxt->csv; +	mh_rec = csv_record_iter(csv); +	rec = csv_record_iter_next(mh_rec); + +	/* append to the hdr record */ +	rec = csv_append_record(csv, rec, 1, key); +	if (!rec) { +		ERRLOG("%s: Could not append key \n", __FUNCTION__); +		return -1; +	} + +	rec = csv_record_iter_next(rec); +	/* append to the data record */ +	rec = csv_append_record(csv, rec, 1, val); +	if (!rec) { +		ERRLOG("%s: Could not append val \n", __FUNCTION__); +		return -1; +	} + +	/* update the msg hdr */ +	_ptm_lib_encode_header(csv, mh_rec, (csvlen(csv) - PTMLIB_MSG_HDR_LEN), +			       PTMLIB_MSG_VERSION, p_ctxt->type, p_ctxt->cmd_id, +			       hdl->client_name); + +	return 0;  } -int -ptm_lib_init_msg(ptm_lib_handle_t *hdl, int cmd_id, int type, -                 void *in_ctxt, void **out_ctxt) +int ptm_lib_init_msg(ptm_lib_handle_t *hdl, int cmd_id, int type, void *in_ctxt, +		     void **out_ctxt)  { -    ptm_lib_msg_ctxt_t *p_ctxt; -    ptm_lib_msg_ctxt_t *p_in_ctxt = in_ctxt; -    csv_t *csv; -    csv_record_t *rec, *d_rec; - -    /* Initialize csv for using discrete record buffers */ -    csv = csv_init(NULL, NULL, PTMLIB_MSG_SZ); - -    if (!csv) { -        ERRLOG("%s: Could not allocate csv \n", __FUNCTION__); -        return -1; -    } - -    rec = _ptm_lib_encode_header(csv, NULL, 0, -                    PTMLIB_MSG_VERSION, type, -                    cmd_id, hdl->client_name); - -    if (!rec) { -        ERRLOG("%s: Could not allocate record \n", __FUNCTION__); -        csv_clean(csv); -        csv_free(csv); -        return -1; -    } - -    p_ctxt = calloc(1, sizeof(*p_ctxt)); -    if (!p_ctxt) { -        ERRLOG("%s: Could not allocate context \n", __FUNCTION__); -        csv_clean(csv); -        csv_free(csv); -        return -1; -    } - -    p_ctxt->csv = csv; -    p_ctxt->cmd_id = cmd_id; -    p_ctxt->type = type; - -    *(ptm_lib_msg_ctxt_t **)out_ctxt = p_ctxt; - -    /* caller supplied a context to initialize with? */ -    if (p_in_ctxt) { -        /* insert the hdr rec */ -        rec = csv_record_iter(p_in_ctxt->csv); -        csv_clone_record (p_in_ctxt->csv, rec, &d_rec); -        csv_insert_record (csv, d_rec); -        /* insert the data rec */ -        rec = csv_record_iter_next(rec); -        csv_clone_record (p_in_ctxt->csv, rec, &d_rec); -        csv_insert_record (csv, d_rec); -    } -    return 0; +	ptm_lib_msg_ctxt_t *p_ctxt; +	ptm_lib_msg_ctxt_t *p_in_ctxt = in_ctxt; +	csv_t *csv; +	csv_record_t *rec, *d_rec; + +	/* Initialize csv for using discrete record buffers */ +	csv = csv_init(NULL, NULL, PTMLIB_MSG_SZ); + +	if (!csv) { +		ERRLOG("%s: Could not allocate csv \n", __FUNCTION__); +		return -1; +	} + +	rec = _ptm_lib_encode_header(csv, NULL, 0, PTMLIB_MSG_VERSION, type, +				     cmd_id, hdl->client_name); + +	if (!rec) { +		ERRLOG("%s: Could not allocate record \n", __FUNCTION__); +		csv_clean(csv); +		csv_free(csv); +		return -1; +	} + +	p_ctxt = calloc(1, sizeof(*p_ctxt)); +	if (!p_ctxt) { +		ERRLOG("%s: Could not allocate context \n", __FUNCTION__); +		csv_clean(csv); +		csv_free(csv); +		return -1; +	} + +	p_ctxt->csv = csv; +	p_ctxt->cmd_id = cmd_id; +	p_ctxt->type = type; + +	*(ptm_lib_msg_ctxt_t **)out_ctxt = p_ctxt; + +	/* caller supplied a context to initialize with? */ +	if (p_in_ctxt) { +		/* insert the hdr rec */ +		rec = csv_record_iter(p_in_ctxt->csv); +		csv_clone_record(p_in_ctxt->csv, rec, &d_rec); +		csv_insert_record(csv, d_rec); +		/* insert the data rec */ +		rec = csv_record_iter_next(rec); +		csv_clone_record(p_in_ctxt->csv, rec, &d_rec); +		csv_insert_record(csv, d_rec); +	} +	return 0;  } -int -ptm_lib_complete_msg(ptm_lib_handle_t *hdl, void *ctxt, -                     char *buf, int *len) +int ptm_lib_complete_msg(ptm_lib_handle_t *hdl, void *ctxt, char *buf, int *len)  { -    ptm_lib_msg_ctxt_t *p_ctxt = ctxt; -    csv_t *csv; -    csv_record_t *rec; - -    if (!p_ctxt) { -        ERRLOG("%s: no context \n", __FUNCTION__); -        return -1; -    } - -    csv = p_ctxt->csv; -    rec = csv_record_iter(csv); - -    _ptm_lib_encode_header(csv, rec, -                    (csvlen(csv) - PTMLIB_MSG_HDR_LEN), -                    PTMLIB_MSG_VERSION, p_ctxt->type, -                    p_ctxt->cmd_id, hdl->client_name); - -    /* parse csv contents into string */ -    if (buf && len) { -        if (csv_serialize(csv, buf, *len)) { -            ERRLOG("%s: cannot serialize\n", __FUNCTION__); -            return -1; -        } -        *len = csvlen(csv); -    } - -    csv_clean(csv); -    csv_free(csv); -    free(p_ctxt); - -    return 0; +	ptm_lib_msg_ctxt_t *p_ctxt = ctxt; +	csv_t *csv; +	csv_record_t *rec; + +	if (!p_ctxt) { +		ERRLOG("%s: no context \n", __FUNCTION__); +		return -1; +	} + +	csv = p_ctxt->csv; +	rec = csv_record_iter(csv); + +	_ptm_lib_encode_header(csv, rec, (csvlen(csv) - PTMLIB_MSG_HDR_LEN), +			       PTMLIB_MSG_VERSION, p_ctxt->type, p_ctxt->cmd_id, +			       hdl->client_name); + +	/* parse csv contents into string */ +	if (buf && len) { +		if (csv_serialize(csv, buf, *len)) { +			ERRLOG("%s: cannot serialize\n", __FUNCTION__); +			return -1; +		} +		*len = csvlen(csv); +	} + +	csv_clean(csv); +	csv_free(csv); +	free(p_ctxt); + +	return 0;  } -int -ptm_lib_find_key_in_msg(void *ctxt, const char *key, char *val) +int ptm_lib_find_key_in_msg(void *ctxt, const char *key, char *val)  { -    ptm_lib_msg_ctxt_t *p_ctxt = ctxt; -    csv_t *csv = p_ctxt->csv; -    csv_record_t *hrec, *drec; -    csv_field_t *hfld, *dfld; -    char *hstr, *dstr; - -    /** -     * skip over ptm hdr if present -     * The next hdr is the keys (column name) -     * The next hdr is the data -     */ -    if (csv_num_records(csv) > 2) { -        hrec = csv_record_iter(csv); -        hrec = csv_record_iter_next(hrec); -    } else { -        hrec = csv_record_iter(csv); -    } -    drec = csv_record_iter_next(hrec); -    val[0] = '\0'; -    for(hstr = csv_field_iter(hrec, &hfld), -        dstr = csv_field_iter(drec, &dfld); -        (hstr && dstr); -        hstr = csv_field_iter_next(&hfld), -        dstr = csv_field_iter_next(&dfld)) { -        if (!strncmp(hstr, key, csv_field_len(hfld))) { -            snprintf(val, csv_field_len(dfld)+1, "%s", dstr); -            return 0; -        } -    } - -    return -1; +	ptm_lib_msg_ctxt_t *p_ctxt = ctxt; +	csv_t *csv = p_ctxt->csv; +	csv_record_t *hrec, *drec; +	csv_field_t *hfld, *dfld; +	char *hstr, *dstr; + +	/** +	 * skip over ptm hdr if present +	 * The next hdr is the keys (column name) +	 * The next hdr is the data +	 */ +	if (csv_num_records(csv) > 2) { +		hrec = csv_record_iter(csv); +		hrec = csv_record_iter_next(hrec); +	} else { +		hrec = csv_record_iter(csv); +	} +	drec = csv_record_iter_next(hrec); +	val[0] = '\0'; +	for (hstr = csv_field_iter(hrec, &hfld), +	    dstr = csv_field_iter(drec, &dfld); +	     (hstr && dstr); hstr = csv_field_iter_next(&hfld), +	    dstr = csv_field_iter_next(&dfld)) { +		if (!strncmp(hstr, key, csv_field_len(hfld))) { +			snprintf(val, csv_field_len(dfld) + 1, "%s", dstr); +			return 0; +		} +	} + +	return -1;  } -static int -_ptm_lib_read_ptm_socket(int fd, char *buf, int len) +static int _ptm_lib_read_ptm_socket(int fd, char *buf, int len)  { -    int retries = 0, rc; -    int bytes_read = 0; - -    while (bytes_read != len) { -        rc = recv(fd, (void *) (buf + bytes_read), (len - bytes_read), -                  MSG_DONTWAIT); -        if (rc <= 0) { -            if (errno && (errno != EAGAIN) && (errno != EWOULDBLOCK)) { -                ERRLOG("fatal recv error(%s), closing connection, rc %d\n", -                       strerror(errno), rc); -                return (rc); -            } else { -                if (retries++ < 2) { -                    usleep(10000); -                    continue; -                } -                DLOG("max retries - recv error(%d - %s) bytes read %d (%d)\n", -                     errno, strerror(errno), bytes_read, len); -                return (bytes_read); -            } -            break; -        } else { -            bytes_read += rc; -        } -    } - -    return bytes_read; +	int retries = 0, rc; +	int bytes_read = 0; + +	while (bytes_read != len) { +		rc = recv(fd, (void *)(buf + bytes_read), (len - bytes_read), +			  MSG_DONTWAIT); +		if (rc <= 0) { +			if (errno && (errno != EAGAIN) +			    && (errno != EWOULDBLOCK)) { +				ERRLOG("fatal recv error(%s), closing connection, rc %d\n", +				       strerror(errno), rc); +				return (rc); +			} else { +				if (retries++ < 2) { +					usleep(10000); +					continue; +				} +				DLOG("max retries - recv error(%d - %s) bytes read %d (%d)\n", +				     errno, strerror(errno), bytes_read, len); +				return (bytes_read); +			} +			break; +		} else { +			bytes_read += rc; +		} +	} + +	return bytes_read;  } -int -ptm_lib_process_msg(ptm_lib_handle_t *hdl, int fd, -                    char *inbuf, int inlen, void *arg) +int ptm_lib_process_msg(ptm_lib_handle_t *hdl, int fd, char *inbuf, int inlen, +			void *arg)  { -    int rc, len; -    char client_name[32]; -    int cmd_id, type, ver, msglen; -    csv_t *csv; -    ptm_lib_msg_ctxt_t *p_ctxt; - -    len = _ptm_lib_read_ptm_socket(fd, inbuf, PTMLIB_MSG_HDR_LEN); -    if (len <= 0) -        return (len); - -    csv = csv_init(NULL, inbuf, PTMLIB_MSG_HDR_LEN); - -    if (!csv) { -        DLOG("Cannot allocate csv for hdr\n"); -        return (-1); -    } - -    rc = _ptm_lib_decode_header(csv, &msglen, &ver, &type, &cmd_id, client_name); - -    csv_clean(csv); -    csv_free(csv); - -    if (rc < 0) { -        /* could not decode the CSV - maybe its legacy cmd? -         * get the entire cmd from the socket and see if we can process it -         */ -        if (len == PTMLIB_MSG_HDR_LEN) { -            len += _ptm_lib_read_ptm_socket(fd, (inbuf+PTMLIB_MSG_HDR_LEN), -                                        inlen - PTMLIB_MSG_HDR_LEN); -            if (len <= 0) -                return (len); -        } - -        inbuf[len] = '\0'; -        /* we only support the get-status cmd */ -        if (strcmp(inbuf, PTMLIB_CMD_GET_STATUS)) { -            DLOG("unsupported legacy cmd %s\n", inbuf); -            return (-1); -        } -        /* internally create a csv-style cmd */ -        ptm_lib_init_msg(hdl, 0, PTMLIB_MSG_TYPE_CMD, NULL, (void *)&p_ctxt); -        if (!p_ctxt) { -            DLOG("couldnt allocate context\n"); -            return (-1); -        } -        ptm_lib_append_msg(hdl, p_ctxt, "cmd", PTMLIB_CMD_GET_STATUS); - -    } else { - -        if (msglen > inlen) { -            DLOG("msglen [%d] > inlen [%d]\n", msglen, inlen); -            return -1; -        } - -        /* read the rest of the msg */ -        len = _ptm_lib_read_ptm_socket(fd, inbuf, msglen); -        if (len <= 0) { -            return (len); -        } - -        inbuf[len] = '\0'; - -        csv = csv_init(NULL, NULL, PTMLIB_MSG_SZ); -        if (!csv) { -            ERRLOG("Cannot allocate csv for msg\n"); -            return -1; -        } - -        csv_decode(csv, inbuf); -        p_ctxt = calloc(1, sizeof(*p_ctxt)); -        if (!p_ctxt) { -            ERRLOG("%s: Could not allocate context \n", __FUNCTION__); -            csv_clean(csv); -            csv_free(csv); -            return -1; -        } - -        p_ctxt->csv = csv; -        p_ctxt->cmd_id = cmd_id; -        p_ctxt->type = type; -    } - -    switch(p_ctxt->type) { -    case PTMLIB_MSG_TYPE_NOTIFICATION: -        if (hdl->notify_cb) -            hdl->notify_cb(arg, p_ctxt); -        break; -    case PTMLIB_MSG_TYPE_CMD: -        if (hdl->cmd_cb) -            hdl->cmd_cb(arg, p_ctxt); -        break; -    case PTMLIB_MSG_TYPE_RESPONSE: -        if (hdl->response_cb) -            hdl->response_cb(arg, p_ctxt); -        break; -    default: -        return -1; -    } - -    csv_clean(p_ctxt->csv); -    csv_free(p_ctxt->csv); -    free(p_ctxt); - -    return len; +	int rc, len; +	char client_name[32]; +	int cmd_id, type, ver, msglen; +	csv_t *csv; +	ptm_lib_msg_ctxt_t *p_ctxt; + +	len = _ptm_lib_read_ptm_socket(fd, inbuf, PTMLIB_MSG_HDR_LEN); +	if (len <= 0) +		return (len); + +	csv = csv_init(NULL, inbuf, PTMLIB_MSG_HDR_LEN); + +	if (!csv) { +		DLOG("Cannot allocate csv for hdr\n"); +		return (-1); +	} + +	rc = _ptm_lib_decode_header(csv, &msglen, &ver, &type, &cmd_id, +				    client_name); + +	csv_clean(csv); +	csv_free(csv); + +	if (rc < 0) { +		/* could not decode the CSV - maybe its legacy cmd? +		 * get the entire cmd from the socket and see if we can process +		 * it +		 */ +		if (len == PTMLIB_MSG_HDR_LEN) { +			len += _ptm_lib_read_ptm_socket( +				fd, (inbuf + PTMLIB_MSG_HDR_LEN), +				inlen - PTMLIB_MSG_HDR_LEN); +			if (len <= 0) +				return (len); +		} + +		inbuf[len] = '\0'; +		/* we only support the get-status cmd */ +		if (strcmp(inbuf, PTMLIB_CMD_GET_STATUS)) { +			DLOG("unsupported legacy cmd %s\n", inbuf); +			return (-1); +		} +		/* internally create a csv-style cmd */ +		ptm_lib_init_msg(hdl, 0, PTMLIB_MSG_TYPE_CMD, NULL, +				 (void *)&p_ctxt); +		if (!p_ctxt) { +			DLOG("couldnt allocate context\n"); +			return (-1); +		} +		ptm_lib_append_msg(hdl, p_ctxt, "cmd", PTMLIB_CMD_GET_STATUS); + +	} else { + +		if (msglen > inlen) { +			DLOG("msglen [%d] > inlen [%d]\n", msglen, inlen); +			return -1; +		} + +		/* read the rest of the msg */ +		len = _ptm_lib_read_ptm_socket(fd, inbuf, msglen); +		if (len <= 0) { +			return (len); +		} + +		inbuf[len] = '\0'; + +		csv = csv_init(NULL, NULL, PTMLIB_MSG_SZ); +		if (!csv) { +			ERRLOG("Cannot allocate csv for msg\n"); +			return -1; +		} + +		csv_decode(csv, inbuf); +		p_ctxt = calloc(1, sizeof(*p_ctxt)); +		if (!p_ctxt) { +			ERRLOG("%s: Could not allocate context \n", +			       __FUNCTION__); +			csv_clean(csv); +			csv_free(csv); +			return -1; +		} + +		p_ctxt->csv = csv; +		p_ctxt->cmd_id = cmd_id; +		p_ctxt->type = type; +	} + +	switch (p_ctxt->type) { +	case PTMLIB_MSG_TYPE_NOTIFICATION: +		if (hdl->notify_cb) +			hdl->notify_cb(arg, p_ctxt); +		break; +	case PTMLIB_MSG_TYPE_CMD: +		if (hdl->cmd_cb) +			hdl->cmd_cb(arg, p_ctxt); +		break; +	case PTMLIB_MSG_TYPE_RESPONSE: +		if (hdl->response_cb) +			hdl->response_cb(arg, p_ctxt); +		break; +	default: +		return -1; +	} + +	csv_clean(p_ctxt->csv); +	csv_free(p_ctxt->csv); +	free(p_ctxt); + +	return len;  } -ptm_lib_handle_t * -ptm_lib_register(char *client_name, -                 ptm_cmd_cb cmd_cb, -                 ptm_notify_cb notify_cb, -                 ptm_response_cb response_cb) +ptm_lib_handle_t *ptm_lib_register(char *client_name, ptm_cmd_cb cmd_cb, +				   ptm_notify_cb notify_cb, +				   ptm_response_cb response_cb)  { -    ptm_lib_handle_t *hdl; +	ptm_lib_handle_t *hdl; -    hdl = calloc(1, sizeof(*hdl)); +	hdl = calloc(1, sizeof(*hdl)); -    if (hdl) { -        strncpy(hdl->client_name, client_name, PTMLIB_MAXNAMELEN - 1); -        hdl->cmd_cb = cmd_cb; -        hdl->notify_cb = notify_cb; -        hdl->response_cb = response_cb; -    } +	if (hdl) { +		strncpy(hdl->client_name, client_name, PTMLIB_MAXNAMELEN - 1); +		hdl->cmd_cb = cmd_cb; +		hdl->notify_cb = notify_cb; +		hdl->response_cb = response_cb; +	} -    return hdl; +	return hdl;  } -void -ptm_lib_deregister(ptm_lib_handle_t *hdl) +void ptm_lib_deregister(ptm_lib_handle_t *hdl)  { -    if (hdl) { -        memset(hdl, 0x00, sizeof(*hdl)); -        free(hdl); -    } +	if (hdl) { +		memset(hdl, 0x00, sizeof(*hdl)); +		free(hdl); +	}  } diff --git a/lib/ptm_lib.h b/lib/ptm_lib.h index be4170bb37..59eae49491 100644 --- a/lib/ptm_lib.h +++ b/lib/ptm_lib.h @@ -32,32 +32,33 @@  #define    PTMLIB_CMD_STOP_BFD_SESS     "stop-bfd-sess"  typedef enum { -    PTMLIB_MSG_TYPE_NOTIFICATION = 1, -    PTMLIB_MSG_TYPE_CMD, -    PTMLIB_MSG_TYPE_RESPONSE, +	PTMLIB_MSG_TYPE_NOTIFICATION = 1, +	PTMLIB_MSG_TYPE_CMD, +	PTMLIB_MSG_TYPE_RESPONSE,  } ptmlib_msg_type;  typedef enum { -    MODULE_BFD = 0, -    MODULE_LLDP, -    MODULE_MAX, +	MODULE_BFD = 0, +	MODULE_LLDP, +	MODULE_MAX,  } ptmlib_mod_type; -typedef int (*ptm_cmd_cb) (void *data, void *arg); -typedef int (*ptm_notify_cb) (void *data, void *arg); -typedef int (*ptm_response_cb) (void *data, void *arg); -typedef int (*ptm_log_cb) (void *data, void *arg,...); +typedef int (*ptm_cmd_cb)(void *data, void *arg); +typedef int (*ptm_notify_cb)(void *data, void *arg); +typedef int (*ptm_response_cb)(void *data, void *arg); +typedef int (*ptm_log_cb)(void *data, void *arg, ...);  typedef struct ptm_lib_handle_s { -    char            client_name[PTMLIB_MAXNAMELEN]; -    ptm_cmd_cb      cmd_cb; -    ptm_notify_cb   notify_cb; -    ptm_response_cb response_cb; +	char client_name[PTMLIB_MAXNAMELEN]; +	ptm_cmd_cb cmd_cb; +	ptm_notify_cb notify_cb; +	ptm_response_cb response_cb;  } ptm_lib_handle_t;  /* Prototypes */  int ptm_lib_process_msg(ptm_lib_handle_t *, int, char *, int, void *); -ptm_lib_handle_t *ptm_lib_register(char *, ptm_cmd_cb, ptm_notify_cb, ptm_response_cb); +ptm_lib_handle_t *ptm_lib_register(char *, ptm_cmd_cb, ptm_notify_cb, +				   ptm_response_cb);  void ptm_lib_deregister(ptm_lib_handle_t *);  int ptm_lib_find_key_in_msg(void *, const char *, char *);  int ptm_lib_init_msg(ptm_lib_handle_t *, int, int, void *, void **); @@ -38,16 +38,15 @@  /*   * Protocol-specific information about the pseudowire.   */ -union pw_protocol_fields -{ -  struct { -      struct in_addr lsr_id; -      uint32_t pwid; -      char vpn_name[L2VPN_NAME_LEN]; -  } ldp; -  struct { -      /* TODO */ -  } bgp; +union pw_protocol_fields { +	struct { +		struct in_addr lsr_id; +		uint32_t pwid; +		char vpn_name[L2VPN_NAME_LEN]; +	} ldp; +	struct { +		/* TODO */ +	} bgp;  };  #endif /* _FRR_PW_H */ diff --git a/lib/qobj.c b/lib/qobj.c index 8a386d2486..4a681b4d9b 100644 --- a/lib/qobj.c +++ b/lib/qobj.c @@ -29,57 +29,56 @@  static struct hash *nodes = NULL; -static unsigned int qobj_key (void *data) +static unsigned int qobj_key(void *data)  { -  struct qobj_node *node = data; -  return (unsigned int)node->nid; +	struct qobj_node *node = data; +	return (unsigned int)node->nid;  } -static int qobj_cmp (const void *a, const void *b) +static int qobj_cmp(const void *a, const void *b)  { -  const struct qobj_node *na = a, *nb = b; -  return na->nid == nb->nid; +	const struct qobj_node *na = a, *nb = b; +	return na->nid == nb->nid;  }  void qobj_reg(struct qobj_node *node, struct qobj_nodetype *type)  { -  node->type = type; -  do -    { -      node->nid  = (uint64_t)random(); -      node->nid ^= (uint64_t)random() << 32; -    } -  while (!node->nid || hash_get (nodes, node, hash_alloc_intern) != node); +	node->type = type; +	do { +		node->nid = (uint64_t)random(); +		node->nid ^= (uint64_t)random() << 32; +	} while (!node->nid +		 || hash_get(nodes, node, hash_alloc_intern) != node);  }  void qobj_unreg(struct qobj_node *node)  { -  hash_release (nodes, node); +	hash_release(nodes, node);  }  struct qobj_node *qobj_get(uint64_t id)  { -  struct qobj_node dummy = { .nid = id }; -  return hash_lookup (nodes, &dummy); +	struct qobj_node dummy = {.nid = id}; +	return hash_lookup(nodes, &dummy);  }  void *qobj_get_typed(uint64_t id, struct qobj_nodetype *type)  { -  struct qobj_node *node = qobj_get(id); -  if (!node || node->type != type) -    return NULL; -  return (char *)node - node->type->node_member_offset; +	struct qobj_node *node = qobj_get(id); +	if (!node || node->type != type) +		return NULL; +	return (char *)node - node->type->node_member_offset;  } -void qobj_init (void) +void qobj_init(void)  { -  if (!nodes) -    nodes = hash_create (qobj_key, qobj_cmp); +	if (!nodes) +		nodes = hash_create(qobj_key, qobj_cmp);  } -void qobj_finish (void) +void qobj_finish(void)  { -  hash_clean (nodes, NULL); -  hash_free (nodes); -  nodes = NULL; +	hash_clean(nodes, NULL); +	hash_free(nodes); +	nodes = NULL;  } diff --git a/lib/qobj.h b/lib/qobj.h index 64a6774bff..79a5f87d61 100644 --- a/lib/qobj.h +++ b/lib/qobj.h @@ -28,10 +28,10 @@   * this is intentional to prevent the struct from growing beyond the allocated   * space.   */ -#define RESERVED_SPACE_STRUCT(name, fieldname, size) \ -	struct { \ -		struct name fieldname; \ -		char padding ## fieldname[size - sizeof(struct name)]; \ +#define RESERVED_SPACE_STRUCT(name, fieldname, size)                           \ +	struct {                                                               \ +		struct name fieldname;                                         \ +		char padding##fieldname[size - sizeof(struct name)];           \  	};  /* don't need struct definitions for these here.  code actually using @@ -47,12 +47,16 @@   */  #ifndef HAVE_QOBJ_NODETYPE_CLI  #define HAVE_QOBJ_NODETYPE_CLI -1 -struct qobj_nodetype_cli { int dummy; }; +struct qobj_nodetype_cli { +	int dummy; +};  #endif  #ifndef HAVE_QOBJ_NODETYPE_CAPNP  #define HAVE_QOBJ_NODETYPE_CAPNP -1 -struct qobj_nodetype_capnp { int dummy; }; +struct qobj_nodetype_capnp { +	int dummy; +};  #endif  /* each different kind of object will have a global variable of this type, @@ -71,15 +75,12 @@ struct qobj_node {  	struct qobj_nodetype *type;  }; -#define QOBJ_FIELDS \ -	struct qobj_node qobj_node; +#define QOBJ_FIELDS struct qobj_node qobj_node;  /* call these at the end of any _create function (QOBJ_REG)   * and beginning of any _destroy function (QOBJ_UNREG) */ -#define QOBJ_REG(n, structname) \ -	qobj_reg(&n->qobj_node, &qobj_t_ ## structname) -#define QOBJ_UNREG(n) \ -	qobj_unreg(&n->qobj_node) +#define QOBJ_REG(n, structname) qobj_reg(&n->qobj_node, &qobj_t_##structname) +#define QOBJ_UNREG(n) qobj_unreg(&n->qobj_node)  /* internals - should not be directly used without a good reason*/  void qobj_reg(struct qobj_node *node, struct qobj_nodetype *type); @@ -88,29 +89,29 @@ struct qobj_node *qobj_get(uint64_t id);  void *qobj_get_typed(uint64_t id, struct qobj_nodetype *type);  /* type declarations */ -#define DECLARE_QOBJ_TYPE(structname) \ -	extern struct qobj_nodetype qobj_t_ ## structname; -#define DEFINE_QOBJ_TYPE(structname) \ -	struct qobj_nodetype qobj_t_ ## structname = { \ -		.node_member_offset = \ -			(ptrdiff_t)offsetof(struct structname, qobj_node) \ -	}; -#define DEFINE_QOBJ_TYPE_INIT(structname, ...) \ -	struct qobj_nodetype qobj_t_ ## structname = { \ -		.node_member_offset = \ -			(ptrdiff_t)offsetof(struct structname, qobj_node), \ -		__VA_ARGS__ \ -	}; +#define DECLARE_QOBJ_TYPE(structname)                                          \ +	extern struct qobj_nodetype qobj_t_##structname; +#define DEFINE_QOBJ_TYPE(structname)                                           \ +	struct qobj_nodetype qobj_t_##structname = {                           \ +		.node_member_offset =                                          \ +			(ptrdiff_t)offsetof(struct structname, qobj_node)}; +#define DEFINE_QOBJ_TYPE_INIT(structname, ...)                                 \ +	struct qobj_nodetype qobj_t_##structname = {                           \ +		.node_member_offset =                                          \ +			(ptrdiff_t)offsetof(struct structname, qobj_node),     \ +		__VA_ARGS__};  /* ID dereference with typecheck.   * will return NULL if id not found or wrong type. */ -#define QOBJ_GET_TYPESAFE(id, structname) \ -	((struct structname *)qobj_get_typed((id), &qobj_t_ ## structname)) +#define QOBJ_GET_TYPESAFE(id, structname)                                      \ +	((struct structname *)qobj_get_typed((id), &qobj_t_##structname)) -#define QOBJ_ID(ptr) \ -	((ptr)->qobj_node.nid) -#define QOBJ_ID_0SAFE(ptr) \ -	({ typeof (ptr) _ptr = (ptr); _ptr ? _ptr->qobj_node.nid : 0ULL; }) +#define QOBJ_ID(ptr) ((ptr)->qobj_node.nid) +#define QOBJ_ID_0SAFE(ptr)                                                     \ +	({                                                                     \ +		typeof(ptr) _ptr = (ptr);                                      \ +		_ptr ? _ptr->qobj_node.nid : 0ULL;                             \ +	})  void qobj_init(void);  void qobj_finish(void); diff --git a/lib/queue.h b/lib/queue.h index 48b363e24d..658b602ba3 100644 --- a/lib/queue.h +++ b/lib/queue.h @@ -103,9 +103,9 @@  #ifdef QUEUE_MACRO_DEBUG  /* Store the last 2 places the queue element or head was altered */  struct qm_trace { -	char * lastfile; +	char *lastfile;  	int lastline; -	char * prevfile; +	char *prevfile;  	int prevline;  }; @@ -113,19 +113,21 @@ struct qm_trace {  #define	TRASHIT(x)	do {(x) = (void *)-1;} while (0)  #define	QMD_SAVELINK(name, link)	void **name = (void *)&(link) -#define	QMD_TRACE_HEAD(head) do {					\ -	(head)->trace.prevline = (head)->trace.lastline;		\ -	(head)->trace.prevfile = (head)->trace.lastfile;		\ -	(head)->trace.lastline = __LINE__;				\ -	(head)->trace.lastfile = __FILE__;				\ -} while (0) - -#define	QMD_TRACE_ELEM(elem) do {					\ -	(elem)->trace.prevline = (elem)->trace.lastline;		\ -	(elem)->trace.prevfile = (elem)->trace.lastfile;		\ -	(elem)->trace.lastline = __LINE__;				\ -	(elem)->trace.lastfile = __FILE__;				\ -} while (0) +#define QMD_TRACE_HEAD(head)                                                   \ +	do {                                                                   \ +		(head)->trace.prevline = (head)->trace.lastline;               \ +		(head)->trace.prevfile = (head)->trace.lastfile;               \ +		(head)->trace.lastline = __LINE__;                             \ +		(head)->trace.lastfile = __FILE__;                             \ +	} while (0) + +#define QMD_TRACE_ELEM(elem)                                                   \ +	do {                                                                   \ +		(elem)->trace.prevline = (elem)->trace.lastline;               \ +		(elem)->trace.prevfile = (elem)->trace.lastfile;               \ +		(elem)->trace.lastline = __LINE__;                             \ +		(elem)->trace.lastfile = __FILE__;                             \ +	} while (0)  #else  #define	QMD_TRACE_ELEM(elem) @@ -133,23 +135,25 @@ struct qm_trace {  #define	QMD_SAVELINK(name, link)  #define	TRACEBUF  #define	TRASHIT(x) -#endif	/* QUEUE_MACRO_DEBUG */ +#endif /* QUEUE_MACRO_DEBUG */  /*   * Singly-linked List declarations.   */ -#define	SLIST_HEAD(name, type)						\ -struct name {								\ -	struct type *slh_first;	/* first element */			\ -} +#define SLIST_HEAD(name, type)                                                 \ +	struct name {                                                          \ +		struct type *slh_first; /* first element */                    \ +	} -#define	SLIST_HEAD_INITIALIZER(head)					\ -	{ NULL } +#define SLIST_HEAD_INITIALIZER(head)                                           \ +	{                                                                      \ +		NULL                                                           \ +	} -#define	SLIST_ENTRY(type)						\ -struct {								\ -	struct type *sle_next;	/* next element */			\ -} +#define SLIST_ENTRY(type)                                                      \ +	struct {                                                               \ +		struct type *sle_next; /* next element */                      \ +	}  /*   * Singly-linked List functions. @@ -158,220 +162,241 @@ struct {								\  #define	SLIST_FIRST(head)	((head)->slh_first) -#define	SLIST_FOREACH(var, head, field)					\ -	for ((var) = SLIST_FIRST((head));				\ -	    (var);							\ -	    (var) = SLIST_NEXT((var), field)) +#define SLIST_FOREACH(var, head, field)                                        \ +	for ((var) = SLIST_FIRST((head)); (var);                               \ +	     (var) = SLIST_NEXT((var), field)) -#define	SLIST_FOREACH_SAFE(var, head, field, tvar)			\ -	for ((var) = SLIST_FIRST((head));				\ -	    (var) && ((tvar) = SLIST_NEXT((var), field), 1);		\ -	    (var) = (tvar)) +#define SLIST_FOREACH_SAFE(var, head, field, tvar)                             \ +	for ((var) = SLIST_FIRST((head));                                      \ +	     (var) && ((tvar) = SLIST_NEXT((var), field), 1); (var) = (tvar)) -#define	SLIST_FOREACH_PREVPTR(var, varp, head, field)			\ -	for ((varp) = &SLIST_FIRST((head));				\ -	    ((var) = *(varp)) != NULL;					\ -	    (varp) = &SLIST_NEXT((var), field)) +#define SLIST_FOREACH_PREVPTR(var, varp, head, field)                          \ +	for ((varp) = &SLIST_FIRST((head)); ((var) = *(varp)) != NULL;         \ +	     (varp) = &SLIST_NEXT((var), field)) -#define	SLIST_INIT(head) do {						\ -	SLIST_FIRST((head)) = NULL;					\ -} while (0) +#define SLIST_INIT(head)                                                       \ +	do {                                                                   \ +		SLIST_FIRST((head)) = NULL;                                    \ +	} while (0) -#define	SLIST_INSERT_AFTER(slistelm, elm, field) do {			\ -	SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field);	\ -	SLIST_NEXT((slistelm), field) = (elm);				\ -} while (0) +#define SLIST_INSERT_AFTER(slistelm, elm, field)                               \ +	do {                                                                   \ +		SLIST_NEXT((elm), field) = SLIST_NEXT((slistelm), field);      \ +		SLIST_NEXT((slistelm), field) = (elm);                         \ +	} while (0) -#define	SLIST_INSERT_HEAD(head, elm, field) do {			\ -	SLIST_NEXT((elm), field) = SLIST_FIRST((head));			\ -	SLIST_FIRST((head)) = (elm);					\ -} while (0) +#define SLIST_INSERT_HEAD(head, elm, field)                                    \ +	do {                                                                   \ +		SLIST_NEXT((elm), field) = SLIST_FIRST((head));                \ +		SLIST_FIRST((head)) = (elm);                                   \ +	} while (0)  #define	SLIST_NEXT(elm, field)	((elm)->field.sle_next) -#define	SLIST_REMOVE(head, elm, type, field) do {			\ -	QMD_SAVELINK(oldnext, (elm)->field.sle_next);			\ -	if (SLIST_FIRST((head)) == (elm)) {				\ -		SLIST_REMOVE_HEAD((head), field);			\ -	}								\ -	else {								\ -		struct type *curelm = SLIST_FIRST((head));		\ -		while (SLIST_NEXT(curelm, field) != (elm))		\ -			curelm = SLIST_NEXT(curelm, field);		\ -		SLIST_REMOVE_AFTER(curelm, field);			\ -	}								\ -	TRASHIT(*oldnext);						\ -} while (0) - -#define SLIST_REMOVE_AFTER(elm, field) do {				\ -	SLIST_NEXT(elm, field) =					\ -	    SLIST_NEXT(SLIST_NEXT(elm, field), field);			\ -} while (0) - -#define	SLIST_REMOVE_HEAD(head, field) do {				\ -	SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field);	\ -} while (0) - -#define SLIST_SWAP(head1, head2, type) do {				\ -	struct type *swap_first = SLIST_FIRST(head1);			\ -	SLIST_FIRST(head1) = SLIST_FIRST(head2);			\ -	SLIST_FIRST(head2) = swap_first;				\ -} while (0) +#define SLIST_REMOVE(head, elm, type, field)                                   \ +	do {                                                                   \ +		QMD_SAVELINK(oldnext, (elm)->field.sle_next);                  \ +		if (SLIST_FIRST((head)) == (elm)) {                            \ +			SLIST_REMOVE_HEAD((head), field);                      \ +		} else {                                                       \ +			struct type *curelm = SLIST_FIRST((head));             \ +			while (SLIST_NEXT(curelm, field) != (elm))             \ +				curelm = SLIST_NEXT(curelm, field);            \ +			SLIST_REMOVE_AFTER(curelm, field);                     \ +		}                                                              \ +		TRASHIT(*oldnext);                                             \ +	} while (0) + +#define SLIST_REMOVE_AFTER(elm, field)                                         \ +	do {                                                                   \ +		SLIST_NEXT(elm, field) =                                       \ +			SLIST_NEXT(SLIST_NEXT(elm, field), field);             \ +	} while (0) + +#define SLIST_REMOVE_HEAD(head, field)                                         \ +	do {                                                                   \ +		SLIST_FIRST((head)) = SLIST_NEXT(SLIST_FIRST((head)), field);  \ +	} while (0) + +#define SLIST_SWAP(head1, head2, type)                                         \ +	do {                                                                   \ +		struct type *swap_first = SLIST_FIRST(head1);                  \ +		SLIST_FIRST(head1) = SLIST_FIRST(head2);                       \ +		SLIST_FIRST(head2) = swap_first;                               \ +	} while (0)  /*   * Singly-linked Tail queue declarations.   */ -#define	STAILQ_HEAD(name, type)						\ -struct name {								\ -	struct type *stqh_first;/* first element */			\ -	struct type **stqh_last;/* addr of last next element */		\ -} - -#define	STAILQ_HEAD_INITIALIZER(head)					\ -	{ NULL, &(head).stqh_first } - -#define	STAILQ_ENTRY(type)						\ -struct {								\ -	struct type *stqe_next;	/* next element */			\ -} +#define STAILQ_HEAD(name, type)                                                \ +	struct name {                                                          \ +		struct type *stqh_first; /* first element */                   \ +		struct type **stqh_last; /* addr of last next element */       \ +	} + +#define STAILQ_HEAD_INITIALIZER(head)                                          \ +	{                                                                      \ +		NULL, &(head).stqh_first                                       \ +	} + +#define STAILQ_ENTRY(type)                                                     \ +	struct {                                                               \ +		struct type *stqe_next; /* next element */                     \ +	}  /*   * Singly-linked Tail queue functions.   */ -#define	STAILQ_CONCAT(head1, head2) do {				\ -	if (!STAILQ_EMPTY((head2))) {					\ -		*(head1)->stqh_last = (head2)->stqh_first;		\ -		(head1)->stqh_last = (head2)->stqh_last;		\ -		STAILQ_INIT((head2));					\ -	}								\ -} while (0) +#define STAILQ_CONCAT(head1, head2)                                            \ +	do {                                                                   \ +		if (!STAILQ_EMPTY((head2))) {                                  \ +			*(head1)->stqh_last = (head2)->stqh_first;             \ +			(head1)->stqh_last = (head2)->stqh_last;               \ +			STAILQ_INIT((head2));                                  \ +		}                                                              \ +	} while (0)  #define	STAILQ_EMPTY(head)	((head)->stqh_first == NULL)  #define	STAILQ_FIRST(head)	((head)->stqh_first) -#define	STAILQ_FOREACH(var, head, field)				\ -	for((var) = STAILQ_FIRST((head));				\ -	   (var);							\ -	   (var) = STAILQ_NEXT((var), field)) - - -#define	STAILQ_FOREACH_SAFE(var, head, field, tvar)			\ -	for ((var) = STAILQ_FIRST((head));				\ -	    (var) && ((tvar) = STAILQ_NEXT((var), field), 1);		\ -	    (var) = (tvar)) - -#define	STAILQ_INIT(head) do {						\ -	STAILQ_FIRST((head)) = NULL;					\ -	(head)->stqh_last = &STAILQ_FIRST((head));			\ -} while (0) - -#define	STAILQ_INSERT_AFTER(head, tqelm, elm, field) do {		\ -	if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field)) == NULL)\ -		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\ -	STAILQ_NEXT((tqelm), field) = (elm);				\ -} while (0) - -#define	STAILQ_INSERT_HEAD(head, elm, field) do {			\ -	if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head))) == NULL)	\ -		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\ -	STAILQ_FIRST((head)) = (elm);					\ -} while (0) - -#define	STAILQ_INSERT_TAIL(head, elm, field) do {			\ -	STAILQ_NEXT((elm), field) = NULL;				\ -	*(head)->stqh_last = (elm);					\ -	(head)->stqh_last = &STAILQ_NEXT((elm), field);			\ -} while (0) - -#define	STAILQ_LAST(head, type, field)					\ -	(STAILQ_EMPTY((head)) ?						\ -		NULL :							\ -	        ((struct type *)(void *)				\ -		((char *)((head)->stqh_last) - __offsetof(struct type, field)))) +#define STAILQ_FOREACH(var, head, field)                                       \ +	for ((var) = STAILQ_FIRST((head)); (var);                              \ +	     (var) = STAILQ_NEXT((var), field)) + + +#define STAILQ_FOREACH_SAFE(var, head, field, tvar)                            \ +	for ((var) = STAILQ_FIRST((head));                                     \ +	     (var) && ((tvar) = STAILQ_NEXT((var), field), 1); (var) = (tvar)) + +#define STAILQ_INIT(head)                                                      \ +	do {                                                                   \ +		STAILQ_FIRST((head)) = NULL;                                   \ +		(head)->stqh_last = &STAILQ_FIRST((head));                     \ +	} while (0) + +#define STAILQ_INSERT_AFTER(head, tqelm, elm, field)                           \ +	do {                                                                   \ +		if ((STAILQ_NEXT((elm), field) = STAILQ_NEXT((tqelm), field))  \ +		    == NULL)                                                   \ +			(head)->stqh_last = &STAILQ_NEXT((elm), field);        \ +		STAILQ_NEXT((tqelm), field) = (elm);                           \ +	} while (0) + +#define STAILQ_INSERT_HEAD(head, elm, field)                                   \ +	do {                                                                   \ +		if ((STAILQ_NEXT((elm), field) = STAILQ_FIRST((head)))         \ +		    == NULL)                                                   \ +			(head)->stqh_last = &STAILQ_NEXT((elm), field);        \ +		STAILQ_FIRST((head)) = (elm);                                  \ +	} while (0) + +#define STAILQ_INSERT_TAIL(head, elm, field)                                   \ +	do {                                                                   \ +		STAILQ_NEXT((elm), field) = NULL;                              \ +		*(head)->stqh_last = (elm);                                    \ +		(head)->stqh_last = &STAILQ_NEXT((elm), field);                \ +	} while (0) + +#define STAILQ_LAST(head, type, field)                                         \ +	(STAILQ_EMPTY((head))                                                  \ +		 ? NULL                                                        \ +		 : ((struct type *)(void *)((char *)((head)->stqh_last)        \ +					    - __offsetof(struct type,          \ +							 field))))  #define	STAILQ_NEXT(elm, field)	((elm)->field.stqe_next) -#define	STAILQ_REMOVE(head, elm, type, field) do {			\ -	QMD_SAVELINK(oldnext, (elm)->field.stqe_next);			\ -	if (STAILQ_FIRST((head)) == (elm)) {				\ -		STAILQ_REMOVE_HEAD((head), field);			\ -	}								\ -	else {								\ -		struct type *curelm = STAILQ_FIRST((head));		\ -		while (STAILQ_NEXT(curelm, field) != (elm))		\ -			curelm = STAILQ_NEXT(curelm, field);		\ -		STAILQ_REMOVE_AFTER(head, curelm, field);		\ -	}								\ -	TRASHIT(*oldnext);						\ -} while (0) - -#define STAILQ_REMOVE_AFTER(head, elm, field) do {			\ -	if ((STAILQ_NEXT(elm, field) =					\ -	     STAILQ_NEXT(STAILQ_NEXT(elm, field), field)) == NULL)	\ -		(head)->stqh_last = &STAILQ_NEXT((elm), field);		\ -} while (0) - -#define	STAILQ_REMOVE_HEAD(head, field) do {				\ -	if ((STAILQ_FIRST((head)) =					\ -	     STAILQ_NEXT(STAILQ_FIRST((head)), field)) == NULL)		\ -		(head)->stqh_last = &STAILQ_FIRST((head));		\ -} while (0) - -#define STAILQ_SWAP(head1, head2, type) do {				\ -	struct type *swap_first = STAILQ_FIRST(head1);			\ -	struct type **swap_last = (head1)->stqh_last;			\ -	STAILQ_FIRST(head1) = STAILQ_FIRST(head2);			\ -	(head1)->stqh_last = (head2)->stqh_last;			\ -	STAILQ_FIRST(head2) = swap_first;				\ -	(head2)->stqh_last = swap_last;					\ -	if (STAILQ_EMPTY(head1))					\ -		(head1)->stqh_last = &STAILQ_FIRST(head1);		\ -	if (STAILQ_EMPTY(head2))					\ -		(head2)->stqh_last = &STAILQ_FIRST(head2);		\ -} while (0) +#define STAILQ_REMOVE(head, elm, type, field)                                  \ +	do {                                                                   \ +		QMD_SAVELINK(oldnext, (elm)->field.stqe_next);                 \ +		if (STAILQ_FIRST((head)) == (elm)) {                           \ +			STAILQ_REMOVE_HEAD((head), field);                     \ +		} else {                                                       \ +			struct type *curelm = STAILQ_FIRST((head));            \ +			while (STAILQ_NEXT(curelm, field) != (elm))            \ +				curelm = STAILQ_NEXT(curelm, field);           \ +			STAILQ_REMOVE_AFTER(head, curelm, field);              \ +		}                                                              \ +		TRASHIT(*oldnext);                                             \ +	} while (0) + +#define STAILQ_REMOVE_AFTER(head, elm, field)                                  \ +	do {                                                                   \ +		if ((STAILQ_NEXT(elm, field) =                                 \ +			     STAILQ_NEXT(STAILQ_NEXT(elm, field), field))      \ +		    == NULL)                                                   \ +			(head)->stqh_last = &STAILQ_NEXT((elm), field);        \ +	} while (0) + +#define STAILQ_REMOVE_HEAD(head, field)                                        \ +	do {                                                                   \ +		if ((STAILQ_FIRST((head)) =                                    \ +			     STAILQ_NEXT(STAILQ_FIRST((head)), field))         \ +		    == NULL)                                                   \ +			(head)->stqh_last = &STAILQ_FIRST((head));             \ +	} while (0) + +#define STAILQ_SWAP(head1, head2, type)                                        \ +	do {                                                                   \ +		struct type *swap_first = STAILQ_FIRST(head1);                 \ +		struct type **swap_last = (head1)->stqh_last;                  \ +		STAILQ_FIRST(head1) = STAILQ_FIRST(head2);                     \ +		(head1)->stqh_last = (head2)->stqh_last;                       \ +		STAILQ_FIRST(head2) = swap_first;                              \ +		(head2)->stqh_last = swap_last;                                \ +		if (STAILQ_EMPTY(head1))                                       \ +			(head1)->stqh_last = &STAILQ_FIRST(head1);             \ +		if (STAILQ_EMPTY(head2))                                       \ +			(head2)->stqh_last = &STAILQ_FIRST(head2);             \ +	} while (0)  /*   * List declarations.   */ -#define	LIST_HEAD(name, type)						\ -struct name {								\ -	struct type *lh_first;	/* first element */			\ -} - -#define	LIST_HEAD_INITIALIZER(head)					\ -	{ NULL } - -#define	LIST_ENTRY(type)						\ -struct {								\ -	struct type *le_next;	/* next element */			\ -	struct type **le_prev;	/* address of previous next element */	\ -} +#define LIST_HEAD(name, type)                                                  \ +	struct name {                                                          \ +		struct type *lh_first; /* first element */                     \ +	} + +#define LIST_HEAD_INITIALIZER(head)                                            \ +	{                                                                      \ +		NULL                                                           \ +	} + +#define LIST_ENTRY(type)                                                       \ +	struct {                                                               \ +		struct type *le_next;  /* next element */                      \ +		struct type **le_prev; /* address of previous next element */  \ +	}  /*   * List functions.   */  #if (defined(_KERNEL) && defined(INVARIANTS)) -#define	QMD_LIST_CHECK_HEAD(head, field) do {				\ -	if (LIST_FIRST((head)) != NULL &&				\ -	    LIST_FIRST((head))->field.le_prev !=			\ -	     &LIST_FIRST((head)))					\ -		panic("Bad list head %p first->prev != head", (head));	\ -} while (0) - -#define	QMD_LIST_CHECK_NEXT(elm, field) do {				\ -	if (LIST_NEXT((elm), field) != NULL &&				\ -	    LIST_NEXT((elm), field)->field.le_prev !=			\ -	     &((elm)->field.le_next))					\ -		panic("Bad link elm %p next->prev != elm", (elm));	\ -} while (0) - -#define	QMD_LIST_CHECK_PREV(elm, field) do {				\ -	if (*(elm)->field.le_prev != (elm))				\ -		panic("Bad link elm %p prev->next != elm", (elm));	\ -} while (0) +#define QMD_LIST_CHECK_HEAD(head, field)                                       \ +	do {                                                                   \ +		if (LIST_FIRST((head)) != NULL                                 \ +		    && LIST_FIRST((head))->field.le_prev                       \ +			       != &LIST_FIRST((head)))                         \ +			panic("Bad list head %p first->prev != head", (head)); \ +	} while (0) + +#define QMD_LIST_CHECK_NEXT(elm, field)                                        \ +	do {                                                                   \ +		if (LIST_NEXT((elm), field) != NULL                            \ +		    && LIST_NEXT((elm), field)->field.le_prev                  \ +			       != &((elm)->field.le_next))                     \ +			panic("Bad link elm %p next->prev != elm", (elm));     \ +	} while (0) + +#define QMD_LIST_CHECK_PREV(elm, field)                                        \ +	do {                                                                   \ +		if (*(elm)->field.le_prev != (elm))                            \ +			panic("Bad link elm %p prev->next != elm", (elm));     \ +	} while (0)  #else  #define	QMD_LIST_CHECK_HEAD(head, field)  #define	QMD_LIST_CHECK_NEXT(elm, field) @@ -382,117 +407,129 @@ struct {								\  #define	LIST_FIRST(head)	((head)->lh_first) -#define	LIST_FOREACH(var, head, field)					\ -	for ((var) = LIST_FIRST((head));				\ -	    (var);							\ -	    (var) = LIST_NEXT((var), field)) - -#define	LIST_FOREACH_SAFE(var, head, field, tvar)			\ -	for ((var) = LIST_FIRST((head));				\ -	    (var) && ((tvar) = LIST_NEXT((var), field), 1);		\ -	    (var) = (tvar)) - -#define	LIST_INIT(head) do {						\ -	LIST_FIRST((head)) = NULL;					\ -} while (0) - -#define	LIST_INSERT_AFTER(listelm, elm, field) do {			\ -	QMD_LIST_CHECK_NEXT(listelm, field);				\ -	if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field)) != NULL)\ -		LIST_NEXT((listelm), field)->field.le_prev =		\ -		    &LIST_NEXT((elm), field);				\ -	LIST_NEXT((listelm), field) = (elm);				\ -	(elm)->field.le_prev = &LIST_NEXT((listelm), field);		\ -} while (0) - -#define	LIST_INSERT_BEFORE(listelm, elm, field) do {			\ -	QMD_LIST_CHECK_PREV(listelm, field);				\ -	(elm)->field.le_prev = (listelm)->field.le_prev;		\ -	LIST_NEXT((elm), field) = (listelm);				\ -	*(listelm)->field.le_prev = (elm);				\ -	(listelm)->field.le_prev = &LIST_NEXT((elm), field);		\ -} while (0) - -#define	LIST_INSERT_HEAD(head, elm, field) do {				\ -	QMD_LIST_CHECK_HEAD((head), field);				\ -	if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL)	\ -		LIST_FIRST((head))->field.le_prev = &LIST_NEXT((elm), field);\ -	LIST_FIRST((head)) = (elm);					\ -	(elm)->field.le_prev = &LIST_FIRST((head));			\ -} while (0) +#define LIST_FOREACH(var, head, field)                                         \ +	for ((var) = LIST_FIRST((head)); (var); (var) = LIST_NEXT((var), field)) + +#define LIST_FOREACH_SAFE(var, head, field, tvar)                              \ +	for ((var) = LIST_FIRST((head));                                       \ +	     (var) && ((tvar) = LIST_NEXT((var), field), 1); (var) = (tvar)) + +#define LIST_INIT(head)                                                        \ +	do {                                                                   \ +		LIST_FIRST((head)) = NULL;                                     \ +	} while (0) + +#define LIST_INSERT_AFTER(listelm, elm, field)                                 \ +	do {                                                                   \ +		QMD_LIST_CHECK_NEXT(listelm, field);                           \ +		if ((LIST_NEXT((elm), field) = LIST_NEXT((listelm), field))    \ +		    != NULL)                                                   \ +			LIST_NEXT((listelm), field)->field.le_prev =           \ +				&LIST_NEXT((elm), field);                      \ +		LIST_NEXT((listelm), field) = (elm);                           \ +		(elm)->field.le_prev = &LIST_NEXT((listelm), field);           \ +	} while (0) + +#define LIST_INSERT_BEFORE(listelm, elm, field)                                \ +	do {                                                                   \ +		QMD_LIST_CHECK_PREV(listelm, field);                           \ +		(elm)->field.le_prev = (listelm)->field.le_prev;               \ +		LIST_NEXT((elm), field) = (listelm);                           \ +		*(listelm)->field.le_prev = (elm);                             \ +		(listelm)->field.le_prev = &LIST_NEXT((elm), field);           \ +	} while (0) + +#define LIST_INSERT_HEAD(head, elm, field)                                     \ +	do {                                                                   \ +		QMD_LIST_CHECK_HEAD((head), field);                            \ +		if ((LIST_NEXT((elm), field) = LIST_FIRST((head))) != NULL)    \ +			LIST_FIRST((head))->field.le_prev =                    \ +				&LIST_NEXT((elm), field);                      \ +		LIST_FIRST((head)) = (elm);                                    \ +		(elm)->field.le_prev = &LIST_FIRST((head));                    \ +	} while (0)  #define	LIST_NEXT(elm, field)	((elm)->field.le_next) -#define	LIST_REMOVE(elm, field) do {					\ -	QMD_SAVELINK(oldnext, (elm)->field.le_next);			\ -	QMD_SAVELINK(oldprev, (elm)->field.le_prev);			\ -	QMD_LIST_CHECK_NEXT(elm, field);				\ -	QMD_LIST_CHECK_PREV(elm, field);				\ -	if (LIST_NEXT((elm), field) != NULL)				\ -		LIST_NEXT((elm), field)->field.le_prev = 		\ -		    (elm)->field.le_prev;				\ -	*(elm)->field.le_prev = LIST_NEXT((elm), field);		\ -	TRASHIT(*oldnext);						\ -	TRASHIT(*oldprev);						\ -} while (0) - -#define LIST_SWAP(head1, head2, type, field) do {			\ -	struct type *swap_tmp = LIST_FIRST((head1));			\ -	LIST_FIRST((head1)) = LIST_FIRST((head2));			\ -	LIST_FIRST((head2)) = swap_tmp;					\ -	if ((swap_tmp = LIST_FIRST((head1))) != NULL)			\ -		swap_tmp->field.le_prev = &LIST_FIRST((head1));		\ -	if ((swap_tmp = LIST_FIRST((head2))) != NULL)			\ -		swap_tmp->field.le_prev = &LIST_FIRST((head2));		\ -} while (0) +#define LIST_REMOVE(elm, field)                                                \ +	do {                                                                   \ +		QMD_SAVELINK(oldnext, (elm)->field.le_next);                   \ +		QMD_SAVELINK(oldprev, (elm)->field.le_prev);                   \ +		QMD_LIST_CHECK_NEXT(elm, field);                               \ +		QMD_LIST_CHECK_PREV(elm, field);                               \ +		if (LIST_NEXT((elm), field) != NULL)                           \ +			LIST_NEXT((elm), field)->field.le_prev =               \ +				(elm)->field.le_prev;                          \ +		*(elm)->field.le_prev = LIST_NEXT((elm), field);               \ +		TRASHIT(*oldnext);                                             \ +		TRASHIT(*oldprev);                                             \ +	} while (0) + +#define LIST_SWAP(head1, head2, type, field)                                   \ +	do {                                                                   \ +		struct type *swap_tmp = LIST_FIRST((head1));                   \ +		LIST_FIRST((head1)) = LIST_FIRST((head2));                     \ +		LIST_FIRST((head2)) = swap_tmp;                                \ +		if ((swap_tmp = LIST_FIRST((head1))) != NULL)                  \ +			swap_tmp->field.le_prev = &LIST_FIRST((head1));        \ +		if ((swap_tmp = LIST_FIRST((head2))) != NULL)                  \ +			swap_tmp->field.le_prev = &LIST_FIRST((head2));        \ +	} while (0)  /*   * Tail queue declarations.   */ -#define	TAILQ_HEAD(name, type)						\ -struct name {								\ -	struct type *tqh_first;	/* first element */			\ -	struct type **tqh_last;	/* addr of last next element */		\ -	TRACEBUF							\ -} - -#define	TAILQ_HEAD_INITIALIZER(head)					\ -	{ NULL, &(head).tqh_first } - -#define	TAILQ_ENTRY(type)						\ -struct {								\ -	struct type *tqe_next;	/* next element */			\ -	struct type **tqe_prev;	/* address of previous next element */	\ -	TRACEBUF							\ -} +#define TAILQ_HEAD(name, type)                                                 \ +	struct name {                                                          \ +		struct type *tqh_first; /* first element */                    \ +		struct type **tqh_last; /* addr of last next element */        \ +		TRACEBUF                                                       \ +	} + +#define TAILQ_HEAD_INITIALIZER(head)                                           \ +	{                                                                      \ +		NULL, &(head).tqh_first                                        \ +	} + +#define TAILQ_ENTRY(type)                                                      \ +	struct {                                                               \ +		struct type *tqe_next;  /* next element */                     \ +		struct type **tqe_prev; /* address of previous next element */ \ +		TRACEBUF                                                       \ +	}  /*   * Tail queue functions.   */  #if (defined(_KERNEL) && defined(INVARIANTS)) -#define	QMD_TAILQ_CHECK_HEAD(head, field) do {				\ -	if (!TAILQ_EMPTY(head) &&					\ -	    TAILQ_FIRST((head))->field.tqe_prev !=			\ -	     &TAILQ_FIRST((head)))					\ -		panic("Bad tailq head %p first->prev != head", (head));	\ -} while (0) - -#define	QMD_TAILQ_CHECK_TAIL(head, field) do {				\ -	if (*(head)->tqh_last != NULL)					\ -		panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); 	\ -} while (0) - -#define	QMD_TAILQ_CHECK_NEXT(elm, field) do {				\ -	if (TAILQ_NEXT((elm), field) != NULL &&				\ -	    TAILQ_NEXT((elm), field)->field.tqe_prev !=			\ -	     &((elm)->field.tqe_next))					\ -		panic("Bad link elm %p next->prev != elm", (elm));	\ -} while (0) - -#define	QMD_TAILQ_CHECK_PREV(elm, field) do {				\ -	if (*(elm)->field.tqe_prev != (elm))				\ -		panic("Bad link elm %p prev->next != elm", (elm));	\ -} while (0) +#define QMD_TAILQ_CHECK_HEAD(head, field)                                      \ +	do {                                                                   \ +		if (!TAILQ_EMPTY(head)                                         \ +		    && TAILQ_FIRST((head))->field.tqe_prev                     \ +			       != &TAILQ_FIRST((head)))                        \ +			panic("Bad tailq head %p first->prev != head",         \ +			      (head));                                         \ +	} while (0) + +#define QMD_TAILQ_CHECK_TAIL(head, field)                                      \ +	do {                                                                   \ +		if (*(head)->tqh_last != NULL)                                 \ +			panic("Bad tailq NEXT(%p->tqh_last) != NULL", (head)); \ +	} while (0) + +#define QMD_TAILQ_CHECK_NEXT(elm, field)                                       \ +	do {                                                                   \ +		if (TAILQ_NEXT((elm), field) != NULL                           \ +		    && TAILQ_NEXT((elm), field)->field.tqe_prev                \ +			       != &((elm)->field.tqe_next))                    \ +			panic("Bad link elm %p next->prev != elm", (elm));     \ +	} while (0) + +#define QMD_TAILQ_CHECK_PREV(elm, field)                                       \ +	do {                                                                   \ +		if (*(elm)->field.tqe_prev != (elm))                           \ +			panic("Bad link elm %p prev->next != elm", (elm));     \ +	} while (0)  #else  #define	QMD_TAILQ_CHECK_HEAD(head, field)  #define	QMD_TAILQ_CHECK_TAIL(head, headname) @@ -500,136 +537,143 @@ struct {								\  #define	QMD_TAILQ_CHECK_PREV(elm, field)  #endif /* (_KERNEL && INVARIANTS) */ -#define	TAILQ_CONCAT(head1, head2, field) do {				\ -	if (!TAILQ_EMPTY(head2)) {					\ -		*(head1)->tqh_last = (head2)->tqh_first;		\ -		(head2)->tqh_first->field.tqe_prev = (head1)->tqh_last;	\ -		(head1)->tqh_last = (head2)->tqh_last;			\ -		TAILQ_INIT((head2));					\ -		QMD_TRACE_HEAD(head1);					\ -		QMD_TRACE_HEAD(head2);					\ -	}								\ -} while (0) +#define TAILQ_CONCAT(head1, head2, field)                                      \ +	do {                                                                   \ +		if (!TAILQ_EMPTY(head2)) {                                     \ +			*(head1)->tqh_last = (head2)->tqh_first;               \ +			(head2)->tqh_first->field.tqe_prev =                   \ +				(head1)->tqh_last;                             \ +			(head1)->tqh_last = (head2)->tqh_last;                 \ +			TAILQ_INIT((head2));                                   \ +			QMD_TRACE_HEAD(head1);                                 \ +			QMD_TRACE_HEAD(head2);                                 \ +		}                                                              \ +	} while (0)  #define	TAILQ_EMPTY(head)	((head)->tqh_first == NULL)  #define	TAILQ_FIRST(head)	((head)->tqh_first) -#define	TAILQ_FOREACH(var, head, field)					\ -	for ((var) = TAILQ_FIRST((head));				\ -	    (var);							\ -	    (var) = TAILQ_NEXT((var), field)) - -#define	TAILQ_FOREACH_SAFE(var, head, field, tvar)			\ -	for ((var) = TAILQ_FIRST((head));				\ -	    (var) && ((tvar) = TAILQ_NEXT((var), field), 1);		\ -	    (var) = (tvar)) - -#define	TAILQ_FOREACH_REVERSE(var, head, headname, field)		\ -	for ((var) = TAILQ_LAST((head), headname);			\ -	    (var);							\ -	    (var) = TAILQ_PREV((var), headname, field)) - -#define	TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar)	\ -	for ((var) = TAILQ_LAST((head), headname);			\ -	    (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1);	\ -	    (var) = (tvar)) - -#define	TAILQ_INIT(head) do {						\ -	TAILQ_FIRST((head)) = NULL;					\ -	(head)->tqh_last = &TAILQ_FIRST((head));			\ -	QMD_TRACE_HEAD(head);						\ -} while (0) - -#define	TAILQ_INSERT_AFTER(head, listelm, elm, field) do {		\ -	QMD_TAILQ_CHECK_NEXT(listelm, field);				\ -	if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field)) != NULL)\ -		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\ -		    &TAILQ_NEXT((elm), field);				\ -	else {								\ -		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\ -		QMD_TRACE_HEAD(head);					\ -	}								\ -	TAILQ_NEXT((listelm), field) = (elm);				\ -	(elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field);		\ -	QMD_TRACE_ELEM(&(elm)->field);					\ -	QMD_TRACE_ELEM(&listelm->field);				\ -} while (0) - -#define	TAILQ_INSERT_BEFORE(listelm, elm, field) do {			\ -	QMD_TAILQ_CHECK_PREV(listelm, field);				\ -	(elm)->field.tqe_prev = (listelm)->field.tqe_prev;		\ -	TAILQ_NEXT((elm), field) = (listelm);				\ -	*(listelm)->field.tqe_prev = (elm);				\ -	(listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field);		\ -	QMD_TRACE_ELEM(&(elm)->field);					\ -	QMD_TRACE_ELEM(&listelm->field);				\ -} while (0) - -#define	TAILQ_INSERT_HEAD(head, elm, field) do {			\ -	QMD_TAILQ_CHECK_HEAD(head, field);				\ -	if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL)	\ -		TAILQ_FIRST((head))->field.tqe_prev =			\ -		    &TAILQ_NEXT((elm), field);				\ -	else								\ -		(head)->tqh_last = &TAILQ_NEXT((elm), field);		\ -	TAILQ_FIRST((head)) = (elm);					\ -	(elm)->field.tqe_prev = &TAILQ_FIRST((head));			\ -	QMD_TRACE_HEAD(head);						\ -	QMD_TRACE_ELEM(&(elm)->field);					\ -} while (0) - -#define	TAILQ_INSERT_TAIL(head, elm, field) do {			\ -	QMD_TAILQ_CHECK_TAIL(head, field);				\ -	TAILQ_NEXT((elm), field) = NULL;				\ -	(elm)->field.tqe_prev = (head)->tqh_last;			\ -	*(head)->tqh_last = (elm);					\ -	(head)->tqh_last = &TAILQ_NEXT((elm), field);			\ -	QMD_TRACE_HEAD(head);						\ -	QMD_TRACE_ELEM(&(elm)->field);					\ -} while (0) - -#define	TAILQ_LAST(head, headname)					\ +#define TAILQ_FOREACH(var, head, field)                                        \ +	for ((var) = TAILQ_FIRST((head)); (var);                               \ +	     (var) = TAILQ_NEXT((var), field)) + +#define TAILQ_FOREACH_SAFE(var, head, field, tvar)                             \ +	for ((var) = TAILQ_FIRST((head));                                      \ +	     (var) && ((tvar) = TAILQ_NEXT((var), field), 1); (var) = (tvar)) + +#define TAILQ_FOREACH_REVERSE(var, head, headname, field)                      \ +	for ((var) = TAILQ_LAST((head), headname); (var);                      \ +	     (var) = TAILQ_PREV((var), headname, field)) + +#define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar)           \ +	for ((var) = TAILQ_LAST((head), headname);                             \ +	     (var) && ((tvar) = TAILQ_PREV((var), headname, field), 1);        \ +	     (var) = (tvar)) + +#define TAILQ_INIT(head)                                                       \ +	do {                                                                   \ +		TAILQ_FIRST((head)) = NULL;                                    \ +		(head)->tqh_last = &TAILQ_FIRST((head));                       \ +		QMD_TRACE_HEAD(head);                                          \ +	} while (0) + +#define TAILQ_INSERT_AFTER(head, listelm, elm, field)                          \ +	do {                                                                   \ +		QMD_TAILQ_CHECK_NEXT(listelm, field);                          \ +		if ((TAILQ_NEXT((elm), field) = TAILQ_NEXT((listelm), field))  \ +		    != NULL)                                                   \ +			TAILQ_NEXT((elm), field)->field.tqe_prev =             \ +				&TAILQ_NEXT((elm), field);                     \ +		else {                                                         \ +			(head)->tqh_last = &TAILQ_NEXT((elm), field);          \ +			QMD_TRACE_HEAD(head);                                  \ +		}                                                              \ +		TAILQ_NEXT((listelm), field) = (elm);                          \ +		(elm)->field.tqe_prev = &TAILQ_NEXT((listelm), field);         \ +		QMD_TRACE_ELEM(&(elm)->field);                                 \ +		QMD_TRACE_ELEM(&listelm->field);                               \ +	} while (0) + +#define TAILQ_INSERT_BEFORE(listelm, elm, field)                               \ +	do {                                                                   \ +		QMD_TAILQ_CHECK_PREV(listelm, field);                          \ +		(elm)->field.tqe_prev = (listelm)->field.tqe_prev;             \ +		TAILQ_NEXT((elm), field) = (listelm);                          \ +		*(listelm)->field.tqe_prev = (elm);                            \ +		(listelm)->field.tqe_prev = &TAILQ_NEXT((elm), field);         \ +		QMD_TRACE_ELEM(&(elm)->field);                                 \ +		QMD_TRACE_ELEM(&listelm->field);                               \ +	} while (0) + +#define TAILQ_INSERT_HEAD(head, elm, field)                                    \ +	do {                                                                   \ +		QMD_TAILQ_CHECK_HEAD(head, field);                             \ +		if ((TAILQ_NEXT((elm), field) = TAILQ_FIRST((head))) != NULL)  \ +			TAILQ_FIRST((head))->field.tqe_prev =                  \ +				&TAILQ_NEXT((elm), field);                     \ +		else                                                           \ +			(head)->tqh_last = &TAILQ_NEXT((elm), field);          \ +		TAILQ_FIRST((head)) = (elm);                                   \ +		(elm)->field.tqe_prev = &TAILQ_FIRST((head));                  \ +		QMD_TRACE_HEAD(head);                                          \ +		QMD_TRACE_ELEM(&(elm)->field);                                 \ +	} while (0) + +#define TAILQ_INSERT_TAIL(head, elm, field)                                    \ +	do {                                                                   \ +		QMD_TAILQ_CHECK_TAIL(head, field);                             \ +		TAILQ_NEXT((elm), field) = NULL;                               \ +		(elm)->field.tqe_prev = (head)->tqh_last;                      \ +		*(head)->tqh_last = (elm);                                     \ +		(head)->tqh_last = &TAILQ_NEXT((elm), field);                  \ +		QMD_TRACE_HEAD(head);                                          \ +		QMD_TRACE_ELEM(&(elm)->field);                                 \ +	} while (0) + +#define TAILQ_LAST(head, headname)                                             \  	(*(((struct headname *)((head)->tqh_last))->tqh_last))  #define	TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) -#define	TAILQ_PREV(elm, headname, field)				\ +#define TAILQ_PREV(elm, headname, field)                                       \  	(*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) -#define	TAILQ_REMOVE(head, elm, field) do {				\ -	QMD_SAVELINK(oldnext, (elm)->field.tqe_next);			\ -	QMD_SAVELINK(oldprev, (elm)->field.tqe_prev);			\ -	QMD_TAILQ_CHECK_NEXT(elm, field);				\ -	QMD_TAILQ_CHECK_PREV(elm, field);				\ -	if ((TAILQ_NEXT((elm), field)) != NULL)				\ -		TAILQ_NEXT((elm), field)->field.tqe_prev = 		\ -		    (elm)->field.tqe_prev;				\ -	else {								\ -		(head)->tqh_last = (elm)->field.tqe_prev;		\ -		QMD_TRACE_HEAD(head);					\ -	}								\ -	*(elm)->field.tqe_prev = TAILQ_NEXT((elm), field);		\ -	TRASHIT(*oldnext);						\ -	TRASHIT(*oldprev);						\ -	QMD_TRACE_ELEM(&(elm)->field);					\ -} while (0) - -#define TAILQ_SWAP(head1, head2, type, field) do {			\ -	struct type *swap_first = (head1)->tqh_first;			\ -	struct type **swap_last = (head1)->tqh_last;			\ -	(head1)->tqh_first = (head2)->tqh_first;			\ -	(head1)->tqh_last = (head2)->tqh_last;				\ -	(head2)->tqh_first = swap_first;				\ -	(head2)->tqh_last = swap_last;					\ -	if ((swap_first = (head1)->tqh_first) != NULL)			\ -		swap_first->field.tqe_prev = &(head1)->tqh_first;	\ -	else								\ -		(head1)->tqh_last = &(head1)->tqh_first;		\ -	if ((swap_first = (head2)->tqh_first) != NULL)			\ -		swap_first->field.tqe_prev = &(head2)->tqh_first;	\ -	else								\ -		(head2)->tqh_last = &(head2)->tqh_first;		\ -} while (0) +#define TAILQ_REMOVE(head, elm, field)                                         \ +	do {                                                                   \ +		QMD_SAVELINK(oldnext, (elm)->field.tqe_next);                  \ +		QMD_SAVELINK(oldprev, (elm)->field.tqe_prev);                  \ +		QMD_TAILQ_CHECK_NEXT(elm, field);                              \ +		QMD_TAILQ_CHECK_PREV(elm, field);                              \ +		if ((TAILQ_NEXT((elm), field)) != NULL)                        \ +			TAILQ_NEXT((elm), field)->field.tqe_prev =             \ +				(elm)->field.tqe_prev;                         \ +		else {                                                         \ +			(head)->tqh_last = (elm)->field.tqe_prev;              \ +			QMD_TRACE_HEAD(head);                                  \ +		}                                                              \ +		*(elm)->field.tqe_prev = TAILQ_NEXT((elm), field);             \ +		TRASHIT(*oldnext);                                             \ +		TRASHIT(*oldprev);                                             \ +		QMD_TRACE_ELEM(&(elm)->field);                                 \ +	} while (0) + +#define TAILQ_SWAP(head1, head2, type, field)                                  \ +	do {                                                                   \ +		struct type *swap_first = (head1)->tqh_first;                  \ +		struct type **swap_last = (head1)->tqh_last;                   \ +		(head1)->tqh_first = (head2)->tqh_first;                       \ +		(head1)->tqh_last = (head2)->tqh_last;                         \ +		(head2)->tqh_first = swap_first;                               \ +		(head2)->tqh_last = swap_last;                                 \ +		if ((swap_first = (head1)->tqh_first) != NULL)                 \ +			swap_first->field.tqe_prev = &(head1)->tqh_first;      \ +		else                                                           \ +			(head1)->tqh_last = &(head1)->tqh_first;               \ +		if ((swap_first = (head2)->tqh_first) != NULL)                 \ +			swap_first->field.tqe_prev = &(head2)->tqh_first;      \ +		else                                                           \ +			(head2)->tqh_last = &(head2)->tqh_first;               \ +	} while (0)  #endif /* !_SYS_QUEUE_H_ */ diff --git a/lib/routemap.c b/lib/routemap.c index cd34ffaae5..40ac282d59 100644 --- a/lib/routemap.c +++ b/lib/routemap.c @@ -31,13 +31,13 @@ Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  #include "log_int.h"  #include "hash.h" -DEFINE_MTYPE_STATIC(LIB, ROUTE_MAP,          "Route map") -DEFINE_MTYPE(       LIB, ROUTE_MAP_NAME,     "Route map name") -DEFINE_MTYPE_STATIC(LIB, ROUTE_MAP_INDEX,    "Route map index") -DEFINE_MTYPE(       LIB, ROUTE_MAP_RULE,     "Route map rule") +DEFINE_MTYPE_STATIC(LIB, ROUTE_MAP, "Route map") +DEFINE_MTYPE(LIB, ROUTE_MAP_NAME, "Route map name") +DEFINE_MTYPE_STATIC(LIB, ROUTE_MAP_INDEX, "Route map index") +DEFINE_MTYPE(LIB, ROUTE_MAP_RULE, "Route map rule")  DEFINE_MTYPE_STATIC(LIB, ROUTE_MAP_RULE_STR, "Route map rule str") -DEFINE_MTYPE(       LIB, ROUTE_MAP_COMPILED, "Route map compiled") -DEFINE_MTYPE_STATIC(LIB, ROUTE_MAP_DEP,      "Route map dependency") +DEFINE_MTYPE(LIB, ROUTE_MAP_COMPILED, "Route map compiled") +DEFINE_MTYPE_STATIC(LIB, ROUTE_MAP_DEP, "Route map dependency")  DEFINE_QOBJ_TYPE(route_map_index)  DEFINE_QOBJ_TYPE(route_map) @@ -48,1482 +48,1298 @@ static vector route_match_vec;  /* Vector for route set rules. */  static vector route_set_vec; -struct route_map_match_set_hooks -{ -  /* match interface */ -  int (*match_interface) (struct vty *vty, -                          struct route_map_index *index, -                          const char *command, -                          const char *arg, -                          route_map_event_t type); - -  /* no match interface */ -  int (*no_match_interface) (struct vty *vty, -                             struct route_map_index *index, -                             const char *command, -                             const char *arg, -                             route_map_event_t type); - -  /* match ip address */ -  int (*match_ip_address) (struct vty *vty, -                           struct route_map_index *index, -                           const char *command, -                           const char *arg, -                           route_map_event_t type); - -  /* no match ip address */ -  int (*no_match_ip_address) (struct vty *vty, -                              struct route_map_index *index, -                              const char *command, -                              const char *arg, -                              route_map_event_t type); - -  /* match ip address prefix list */ -  int (*match_ip_address_prefix_list) (struct vty *vty, -                                       struct route_map_index *index, -                                       const char *command, -                                       const char *arg, -                                       route_map_event_t type); - -  /* no match ip address prefix list */ -  int (*no_match_ip_address_prefix_list) (struct vty *vty, -                                          struct route_map_index *index, -                                          const char *command, -                                          const char *arg, -                                          route_map_event_t type); - -  /* match ip next hop */ -  int (*match_ip_next_hop) (struct vty *vty, -                            struct route_map_index *index, -                            const char *command, -                            const char *arg, -                            route_map_event_t type); - -  /* no match ip next hop */ -  int (*no_match_ip_next_hop) (struct vty *vty, -                               struct route_map_index *index, -                               const char *command, -                               const char *arg, -                               route_map_event_t type); - -  /* match ip next hop prefix list */ -  int (*match_ip_next_hop_prefix_list) (struct vty *vty, -                                        struct route_map_index *index, -                                        const char *command, -                                        const char *arg, -                                        route_map_event_t type); - -  /* no match ip next hop prefix list */ -  int (*no_match_ip_next_hop_prefix_list) (struct vty *vty, -                                           struct route_map_index *index, -                                           const char *command, -                                           const char *arg, -                                           route_map_event_t type); - -  /* match ipv6 address */ -  int (*match_ipv6_address) (struct vty *vty, -                             struct route_map_index *index, -                             const char *command, -                             const char *arg, -                             route_map_event_t type); - -  /* no match ipv6 address */ -  int (*no_match_ipv6_address) (struct vty *vty, -                                struct route_map_index *index, -                                const char *command, -                                const char *arg, -                                route_map_event_t type); - - -  /* match ipv6 address prefix list */ -  int (*match_ipv6_address_prefix_list) (struct vty *vty, -                                         struct route_map_index *index, -                                         const char *command, -                                         const char *arg, -                                         route_map_event_t type); - -  /* no match ipv6 address prefix list */ -  int (*no_match_ipv6_address_prefix_list) (struct vty *vty, -                                            struct route_map_index *index, -                                            const char *command, -                                            const char *arg, -                                            route_map_event_t type); - -  /* match metric */ -  int (*match_metric) (struct vty *vty, -                       struct route_map_index *index, -                       const char *command, -                       const char *arg, -                       route_map_event_t type); - -  /* no match metric */ -  int (*no_match_metric) (struct vty *vty, -                          struct route_map_index *index, -                          const char *command, -                          const char *arg, -                          route_map_event_t type); - -  /* match tag */ -  int (*match_tag) (struct vty *vty, -                    struct route_map_index *index, -                    const char *command, -                    const char *arg, -                    route_map_event_t type); - -  /* no match tag */ -  int (*no_match_tag) (struct vty *vty, -                       struct route_map_index *index, -                       const char *command, -                       const char *arg, -                       route_map_event_t type); - -  /* set ip nexthop */ -  int (*set_ip_nexthop) (struct vty *vty, -                         struct route_map_index *index, -                         const char *command, -                         const char *arg); - -  /* no set ip nexthop */ -  int (*no_set_ip_nexthop) (struct vty *vty, -                            struct route_map_index *index, -                            const char *command, -                            const char *arg); - -  /* set ipv6 nexthop local */ -  int (*set_ipv6_nexthop_local) (struct vty *vty, -                                 struct route_map_index *index, -                                 const char *command, -                                 const char *arg); - -  /* no set ipv6 nexthop local */ -  int (*no_set_ipv6_nexthop_local) (struct vty *vty, -                                    struct route_map_index *index, -                                    const char *command, -                                    const char *arg); - -  /* set metric */ -  int (*set_metric) (struct vty *vty, -                     struct route_map_index *index, -                     const char *command, -                     const char *arg); - -  /* no set metric */ -  int (*no_set_metric) (struct vty *vty, -                        struct route_map_index *index, -                        const char *command, -                        const char *arg); - -  /* set tag */ -  int (*set_tag) (struct vty *vty, -                  struct route_map_index *index, -                  const char *command, -                  const char *arg); - -  /* no set tag */ -  int (*no_set_tag) (struct vty *vty, -                     struct route_map_index *index, -                     const char *command, -                     const char *arg); - +struct route_map_match_set_hooks { +	/* match interface */ +	int (*match_interface)(struct vty *vty, struct route_map_index *index, +			       const char *command, const char *arg, +			       route_map_event_t type); + +	/* no match interface */ +	int (*no_match_interface)(struct vty *vty, +				  struct route_map_index *index, +				  const char *command, const char *arg, +				  route_map_event_t type); + +	/* match ip address */ +	int (*match_ip_address)(struct vty *vty, struct route_map_index *index, +				const char *command, const char *arg, +				route_map_event_t type); + +	/* no match ip address */ +	int (*no_match_ip_address)(struct vty *vty, +				   struct route_map_index *index, +				   const char *command, const char *arg, +				   route_map_event_t type); + +	/* match ip address prefix list */ +	int (*match_ip_address_prefix_list)(struct vty *vty, +					    struct route_map_index *index, +					    const char *command, +					    const char *arg, +					    route_map_event_t type); + +	/* no match ip address prefix list */ +	int (*no_match_ip_address_prefix_list)(struct vty *vty, +					       struct route_map_index *index, +					       const char *command, +					       const char *arg, +					       route_map_event_t type); + +	/* match ip next hop */ +	int (*match_ip_next_hop)(struct vty *vty, struct route_map_index *index, +				 const char *command, const char *arg, +				 route_map_event_t type); + +	/* no match ip next hop */ +	int (*no_match_ip_next_hop)(struct vty *vty, +				    struct route_map_index *index, +				    const char *command, const char *arg, +				    route_map_event_t type); + +	/* match ip next hop prefix list */ +	int (*match_ip_next_hop_prefix_list)(struct vty *vty, +					     struct route_map_index *index, +					     const char *command, +					     const char *arg, +					     route_map_event_t type); + +	/* no match ip next hop prefix list */ +	int (*no_match_ip_next_hop_prefix_list)(struct vty *vty, +						struct route_map_index *index, +						const char *command, +						const char *arg, +						route_map_event_t type); + +	/* match ipv6 address */ +	int (*match_ipv6_address)(struct vty *vty, +				  struct route_map_index *index, +				  const char *command, const char *arg, +				  route_map_event_t type); + +	/* no match ipv6 address */ +	int (*no_match_ipv6_address)(struct vty *vty, +				     struct route_map_index *index, +				     const char *command, const char *arg, +				     route_map_event_t type); + + +	/* match ipv6 address prefix list */ +	int (*match_ipv6_address_prefix_list)(struct vty *vty, +					      struct route_map_index *index, +					      const char *command, +					      const char *arg, +					      route_map_event_t type); + +	/* no match ipv6 address prefix list */ +	int (*no_match_ipv6_address_prefix_list)(struct vty *vty, +						 struct route_map_index *index, +						 const char *command, +						 const char *arg, +						 route_map_event_t type); + +	/* match metric */ +	int (*match_metric)(struct vty *vty, struct route_map_index *index, +			    const char *command, const char *arg, +			    route_map_event_t type); + +	/* no match metric */ +	int (*no_match_metric)(struct vty *vty, struct route_map_index *index, +			       const char *command, const char *arg, +			       route_map_event_t type); + +	/* match tag */ +	int (*match_tag)(struct vty *vty, struct route_map_index *index, +			 const char *command, const char *arg, +			 route_map_event_t type); + +	/* no match tag */ +	int (*no_match_tag)(struct vty *vty, struct route_map_index *index, +			    const char *command, const char *arg, +			    route_map_event_t type); + +	/* set ip nexthop */ +	int (*set_ip_nexthop)(struct vty *vty, struct route_map_index *index, +			      const char *command, const char *arg); + +	/* no set ip nexthop */ +	int (*no_set_ip_nexthop)(struct vty *vty, struct route_map_index *index, +				 const char *command, const char *arg); + +	/* set ipv6 nexthop local */ +	int (*set_ipv6_nexthop_local)(struct vty *vty, +				      struct route_map_index *index, +				      const char *command, const char *arg); + +	/* no set ipv6 nexthop local */ +	int (*no_set_ipv6_nexthop_local)(struct vty *vty, +					 struct route_map_index *index, +					 const char *command, const char *arg); + +	/* set metric */ +	int (*set_metric)(struct vty *vty, struct route_map_index *index, +			  const char *command, const char *arg); + +	/* no set metric */ +	int (*no_set_metric)(struct vty *vty, struct route_map_index *index, +			     const char *command, const char *arg); + +	/* set tag */ +	int (*set_tag)(struct vty *vty, struct route_map_index *index, +		       const char *command, const char *arg); + +	/* no set tag */ +	int (*no_set_tag)(struct vty *vty, struct route_map_index *index, +			  const char *command, const char *arg);  };  struct route_map_match_set_hooks rmap_match_set_hook;  /* match interface */ -void -route_map_match_interface_hook (int (*func) (struct vty *vty, -                                             struct route_map_index *index, -                                             const char *command, -                                             const char *arg, -                                             route_map_event_t type)) +void route_map_match_interface_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.match_interface = func; +	rmap_match_set_hook.match_interface = func;  }  /* no match interface */ -void -route_map_no_match_interface_hook (int (*func) (struct vty *vty, -                                                struct route_map_index *index, -                                                const char *command, -                                                const char *arg, -                                                route_map_event_t type)) +void route_map_no_match_interface_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.no_match_interface = func; +	rmap_match_set_hook.no_match_interface = func;  }  /* match ip address */ -void -route_map_match_ip_address_hook (int (*func) (struct vty *vty, -                                              struct route_map_index *index, -                                              const char *command, -                                              const char *arg, -                                              route_map_event_t type)) +void route_map_match_ip_address_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.match_ip_address = func; +	rmap_match_set_hook.match_ip_address = func;  }  /* no match ip address */ -void -route_map_no_match_ip_address_hook (int (*func) (struct vty *vty, -                                                 struct route_map_index *index, -                                                 const char *command, -                                                 const char *arg, -                                                 route_map_event_t type)) +void route_map_no_match_ip_address_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.no_match_ip_address = func; +	rmap_match_set_hook.no_match_ip_address = func;  }  /* match ip address prefix list */ -void -route_map_match_ip_address_prefix_list_hook (int (*func) (struct vty *vty, -                                                          struct route_map_index *index, -                                                          const char *command, -                                                          const char *arg, -                                                          route_map_event_t type)) +void route_map_match_ip_address_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.match_ip_address_prefix_list = func; +	rmap_match_set_hook.match_ip_address_prefix_list = func;  }  /* no match ip address prefix list */ -void -route_map_no_match_ip_address_prefix_list_hook (int (*func) (struct vty *vty, -                                                             struct route_map_index *index, -                                                             const char *command, -                                                             const char *arg, -                                                             route_map_event_t type)) +void route_map_no_match_ip_address_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.no_match_ip_address_prefix_list = func; +	rmap_match_set_hook.no_match_ip_address_prefix_list = func;  }  /* match ip next hop */ -void -route_map_match_ip_next_hop_hook (int (*func) (struct vty *vty, -                                               struct route_map_index *index, -                                               const char *command, -                                               const char *arg, -                                               route_map_event_t type)) +void route_map_match_ip_next_hop_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.match_ip_next_hop = func; +	rmap_match_set_hook.match_ip_next_hop = func;  }  /* no match ip next hop */ -void -route_map_no_match_ip_next_hop_hook (int (*func) (struct vty *vty, -                                                  struct route_map_index *index, -                                                  const char *command, -                                                  const char *arg, -                                                  route_map_event_t type)) +void route_map_no_match_ip_next_hop_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.no_match_ip_next_hop = func; +	rmap_match_set_hook.no_match_ip_next_hop = func;  }  /* match ip next hop prefix list */ -void -route_map_match_ip_next_hop_prefix_list_hook (int (*func) (struct vty *vty, -                                                           struct route_map_index *index, -                                                           const char *command, -                                                           const char *arg, -                                                           route_map_event_t type)) +void route_map_match_ip_next_hop_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.match_ip_next_hop_prefix_list = func; +	rmap_match_set_hook.match_ip_next_hop_prefix_list = func;  }  /* no match ip next hop prefix list */ -void -route_map_no_match_ip_next_hop_prefix_list_hook (int (*func) (struct vty *vty, -                                                              struct route_map_index *index, -                                                              const char *command, -                                                              const char *arg, -                                                              route_map_event_t type)) +void route_map_no_match_ip_next_hop_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.no_match_ip_next_hop_prefix_list = func; +	rmap_match_set_hook.no_match_ip_next_hop_prefix_list = func;  }  /* match ipv6 address */ -void -route_map_match_ipv6_address_hook (int (*func) (struct vty *vty, -                                                struct route_map_index *index, -                                                const char *command, -                                                const char *arg, -                                                route_map_event_t type)) +void route_map_match_ipv6_address_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.match_ipv6_address = func; +	rmap_match_set_hook.match_ipv6_address = func;  }  /* no match ipv6 address */ -void -route_map_no_match_ipv6_address_hook (int (*func) (struct vty *vty, -                                                   struct route_map_index *index, -                                                   const char *command, -                                                   const char *arg, -                                                   route_map_event_t type)) +void route_map_no_match_ipv6_address_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.no_match_ipv6_address = func; +	rmap_match_set_hook.no_match_ipv6_address = func;  }  /* match ipv6 address prefix list */ -void -route_map_match_ipv6_address_prefix_list_hook (int (*func) (struct vty *vty, -                                                            struct route_map_index *index, -                                                            const char *command, -                                                            const char *arg, -                                                            route_map_event_t type)) +void route_map_match_ipv6_address_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.match_ipv6_address_prefix_list = func; +	rmap_match_set_hook.match_ipv6_address_prefix_list = func;  }  /* no match ipv6 address prefix list */ -void -route_map_no_match_ipv6_address_prefix_list_hook (int (*func) (struct vty *vty, -                                                               struct route_map_index *index, -                                                               const char *command, -                                                               const char *arg, -                                                               route_map_event_t type)) +void route_map_no_match_ipv6_address_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.no_match_ipv6_address_prefix_list = func; +	rmap_match_set_hook.no_match_ipv6_address_prefix_list = func;  }  /* match metric */ -void -route_map_match_metric_hook (int (*func) (struct vty *vty, -                                          struct route_map_index *index, -                                          const char *command, -                                          const char *arg, -                                          route_map_event_t type)) +void route_map_match_metric_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.match_metric = func; +	rmap_match_set_hook.match_metric = func;  }  /* no match metric */ -void -route_map_no_match_metric_hook (int (*func) (struct vty *vty, -                                             struct route_map_index *index, -                                             const char *command, -                                             const char *arg, -                                             route_map_event_t type)) +void route_map_no_match_metric_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.no_match_metric = func; +	rmap_match_set_hook.no_match_metric = func;  }  /* match tag */ -void -route_map_match_tag_hook (int (*func) (struct vty *vty, -                                       struct route_map_index *index, -                                       const char *command, -                                       const char *arg, -                                       route_map_event_t type)) +void route_map_match_tag_hook(int (*func)(struct vty *vty, +					  struct route_map_index *index, +					  const char *command, const char *arg, +					  route_map_event_t type))  { -  rmap_match_set_hook.match_tag = func; +	rmap_match_set_hook.match_tag = func;  }  /* no match tag */ -void -route_map_no_match_tag_hook (int (*func) (struct vty *vty, -                                          struct route_map_index *index, -                                          const char *command, -                                          const char *arg, -                                          route_map_event_t type)) +void route_map_no_match_tag_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type))  { -  rmap_match_set_hook.no_match_tag = func; +	rmap_match_set_hook.no_match_tag = func;  }  /* set ip nexthop */ -void -route_map_set_ip_nexthop_hook (int (*func) (struct vty *vty, -                                            struct route_map_index *index, -                                            const char *command, -                                            const char *arg)) +void route_map_set_ip_nexthop_hook(int (*func)(struct vty *vty, +					       struct route_map_index *index, +					       const char *command, +					       const char *arg))  { -  rmap_match_set_hook.set_ip_nexthop = func; +	rmap_match_set_hook.set_ip_nexthop = func;  }  /* no set ip nexthop */ -void -route_map_no_set_ip_nexthop_hook (int (*func) (struct vty *vty, -                                               struct route_map_index *index, -                                               const char *command, -                                               const char *arg)) +void route_map_no_set_ip_nexthop_hook(int (*func)(struct vty *vty, +						  struct route_map_index *index, +						  const char *command, +						  const char *arg))  { -  rmap_match_set_hook.no_set_ip_nexthop = func; +	rmap_match_set_hook.no_set_ip_nexthop = func;  }  /* set ipv6 nexthop local */ -void -route_map_set_ipv6_nexthop_local_hook (int (*func) (struct vty *vty, -                                                    struct route_map_index *index, -                                                    const char *command, -                                                    const char *arg)) +void route_map_set_ipv6_nexthop_local_hook( +	int (*func)(struct vty *vty, struct route_map_index *index, +		    const char *command, const char *arg))  { -  rmap_match_set_hook.set_ipv6_nexthop_local = func; +	rmap_match_set_hook.set_ipv6_nexthop_local = func;  }  /* no set ipv6 nexthop local */ -void -route_map_no_set_ipv6_nexthop_local_hook (int (*func) (struct vty *vty, -                                                       struct route_map_index *index, -                                                       const char *command, -                                                       const char *arg)) +void route_map_no_set_ipv6_nexthop_local_hook( +	int (*func)(struct vty *vty, struct route_map_index *index, +		    const char *command, const char *arg))  { -  rmap_match_set_hook.no_set_ipv6_nexthop_local = func; +	rmap_match_set_hook.no_set_ipv6_nexthop_local = func;  }  /* set metric */ -void -route_map_set_metric_hook (int (*func) (struct vty *vty, -                                        struct route_map_index *index, -                                        const char *command, -                                        const char *arg)) +void route_map_set_metric_hook(int (*func)(struct vty *vty, +					   struct route_map_index *index, +					   const char *command, +					   const char *arg))  { -  rmap_match_set_hook.set_metric = func; +	rmap_match_set_hook.set_metric = func;  }  /* no set metric */ -void -route_map_no_set_metric_hook (int (*func) (struct vty *vty, -                                           struct route_map_index *index, -                                           const char *command, -                                           const char *arg)) +void route_map_no_set_metric_hook(int (*func)(struct vty *vty, +					      struct route_map_index *index, +					      const char *command, +					      const char *arg))  { -  rmap_match_set_hook.no_set_metric = func; +	rmap_match_set_hook.no_set_metric = func;  }  /* set tag */ -void -route_map_set_tag_hook (int (*func) (struct vty *vty, -                                     struct route_map_index *index, -                                     const char *command, -                                     const char *arg)) +void route_map_set_tag_hook(int (*func)(struct vty *vty, +					struct route_map_index *index, +					const char *command, const char *arg))  { -  rmap_match_set_hook.set_tag = func; +	rmap_match_set_hook.set_tag = func;  }  /* no set tag */ -void -route_map_no_set_tag_hook (int (*func) (struct vty *vty, -                                        struct route_map_index *index, -                                        const char *command, -                                        const char *arg)) -{ -  rmap_match_set_hook.no_set_tag = func; -} - -int -generic_match_add (struct vty *vty, struct route_map_index *index, -                   const char *command, const char *arg, -                   route_map_event_t type) -{ -  int ret; - -  ret = route_map_add_match (index, command, arg); -  if (ret) -    { -      switch (ret) -        { -        case RMAP_RULE_MISSING: -          vty_out (vty, "%% Can't find rule.%s", VTY_NEWLINE); -          return CMD_WARNING; -        case RMAP_COMPILE_ERROR: -          vty_out (vty, "%% Argument is malformed.%s", VTY_NEWLINE); -          return CMD_WARNING; -        } -    } - -  if (type != RMAP_EVENT_MATCH_ADDED) -    { -      route_map_upd8_dependency (type, arg, index->map->name); -    } -  return CMD_SUCCESS; -} - -int -generic_match_delete (struct vty *vty, struct route_map_index *index, -                      const char *command, const char *arg, -                      route_map_event_t type) -{ -  int ret; -  char *dep_name = NULL; -  const char *tmpstr; -  char *rmap_name = NULL; - -  if (type != RMAP_EVENT_MATCH_DELETED) -    { -      /* ignore the mundane, the types without any dependency */ -      if (arg == NULL) -        { -          if ((tmpstr = route_map_get_match_arg(index, command)) != NULL) -            dep_name = XSTRDUP(MTYPE_ROUTE_MAP_RULE, tmpstr); -        } -      else -        { -          dep_name = XSTRDUP(MTYPE_ROUTE_MAP_RULE, arg); -        } -      rmap_name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, index->map->name); -    } - -  ret = route_map_delete_match (index, command, dep_name); -  if (ret) -    { -      switch (ret) -        { -        case RMAP_RULE_MISSING: -          vty_out (vty, "%% BGP Can't find rule.%s", VTY_NEWLINE); -          break; -        case RMAP_COMPILE_ERROR: -          vty_out (vty, "%% BGP Argument is malformed.%s", VTY_NEWLINE); -          break; -        } -      if (dep_name) -        XFREE(MTYPE_ROUTE_MAP_RULE, dep_name); -      if (rmap_name) -        XFREE(MTYPE_ROUTE_MAP_NAME, rmap_name); -      return CMD_WARNING; -    } - -  if (type != RMAP_EVENT_MATCH_DELETED && dep_name) -    route_map_upd8_dependency(type, dep_name, rmap_name); - -  if (dep_name) -    XFREE(MTYPE_ROUTE_MAP_RULE, dep_name); -  if (rmap_name) -    XFREE(MTYPE_ROUTE_MAP_NAME, rmap_name); - -  return CMD_SUCCESS; -} - -int -generic_set_add (struct vty *vty, struct route_map_index *index, -                 const char *command, const char *arg) -{ -  int ret; - -  ret = route_map_add_set (index, command, arg); -  if (ret) -    { -      switch (ret) -        { -        case RMAP_RULE_MISSING: -          vty_out (vty, "%% Can't find rule.%s", VTY_NEWLINE); -          return CMD_WARNING; -        case RMAP_COMPILE_ERROR: -          vty_out (vty, "%% Argument is malformed.%s", VTY_NEWLINE); -          return CMD_WARNING; -        } -    } -  return CMD_SUCCESS; -} - -int -generic_set_delete (struct vty *vty, struct route_map_index *index, -                    const char *command, const char *arg) -{ -  int ret; - -  ret = route_map_delete_set (index, command, arg); -  if (ret) -    { -      switch (ret) -        { -        case RMAP_RULE_MISSING: -          vty_out (vty, "%% Can't find rule.%s", VTY_NEWLINE); -          return CMD_WARNING; -        case RMAP_COMPILE_ERROR: -          vty_out (vty, "%% Argument is malformed.%s", VTY_NEWLINE); -          return CMD_WARNING; -        } -    } -  return CMD_SUCCESS; +void route_map_no_set_tag_hook(int (*func)(struct vty *vty, +					   struct route_map_index *index, +					   const char *command, +					   const char *arg)) +{ +	rmap_match_set_hook.no_set_tag = func;  } +int generic_match_add(struct vty *vty, struct route_map_index *index, +		      const char *command, const char *arg, +		      route_map_event_t type) +{ +	int ret; + +	ret = route_map_add_match(index, command, arg); +	if (ret) { +		switch (ret) { +		case RMAP_RULE_MISSING: +			vty_out(vty, "%% Can't find rule.%s", VTY_NEWLINE); +			return CMD_WARNING; +		case RMAP_COMPILE_ERROR: +			vty_out(vty, "%% Argument is malformed.%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} +	} -/* Route map rule. This rule has both `match' rule and `set' rule. */ -struct route_map_rule +	if (type != RMAP_EVENT_MATCH_ADDED) { +		route_map_upd8_dependency(type, arg, index->map->name); +	} +	return CMD_SUCCESS; +} + +int generic_match_delete(struct vty *vty, struct route_map_index *index, +			 const char *command, const char *arg, +			 route_map_event_t type) +{ +	int ret; +	char *dep_name = NULL; +	const char *tmpstr; +	char *rmap_name = NULL; + +	if (type != RMAP_EVENT_MATCH_DELETED) { +		/* ignore the mundane, the types without any dependency */ +		if (arg == NULL) { +			if ((tmpstr = route_map_get_match_arg(index, command)) +			    != NULL) +				dep_name = +					XSTRDUP(MTYPE_ROUTE_MAP_RULE, tmpstr); +		} else { +			dep_name = XSTRDUP(MTYPE_ROUTE_MAP_RULE, arg); +		} +		rmap_name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, index->map->name); +	} + +	ret = route_map_delete_match(index, command, dep_name); +	if (ret) { +		switch (ret) { +		case RMAP_RULE_MISSING: +			vty_out(vty, "%% BGP Can't find rule.%s", VTY_NEWLINE); +			break; +		case RMAP_COMPILE_ERROR: +			vty_out(vty, "%% BGP Argument is malformed.%s", +				VTY_NEWLINE); +			break; +		} +		if (dep_name) +			XFREE(MTYPE_ROUTE_MAP_RULE, dep_name); +		if (rmap_name) +			XFREE(MTYPE_ROUTE_MAP_NAME, rmap_name); +		return CMD_WARNING; +	} + +	if (type != RMAP_EVENT_MATCH_DELETED && dep_name) +		route_map_upd8_dependency(type, dep_name, rmap_name); + +	if (dep_name) +		XFREE(MTYPE_ROUTE_MAP_RULE, dep_name); +	if (rmap_name) +		XFREE(MTYPE_ROUTE_MAP_NAME, rmap_name); + +	return CMD_SUCCESS; +} + +int generic_set_add(struct vty *vty, struct route_map_index *index, +		    const char *command, const char *arg) +{ +	int ret; + +	ret = route_map_add_set(index, command, arg); +	if (ret) { +		switch (ret) { +		case RMAP_RULE_MISSING: +			vty_out(vty, "%% Can't find rule.%s", VTY_NEWLINE); +			return CMD_WARNING; +		case RMAP_COMPILE_ERROR: +			vty_out(vty, "%% Argument is malformed.%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} +	} +	return CMD_SUCCESS; +} + +int generic_set_delete(struct vty *vty, struct route_map_index *index, +		       const char *command, const char *arg)  { -  /* Rule type. */ -  struct route_map_rule_cmd *cmd; +	int ret; + +	ret = route_map_delete_set(index, command, arg); +	if (ret) { +		switch (ret) { +		case RMAP_RULE_MISSING: +			vty_out(vty, "%% Can't find rule.%s", VTY_NEWLINE); +			return CMD_WARNING; +		case RMAP_COMPILE_ERROR: +			vty_out(vty, "%% Argument is malformed.%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} +	} +	return CMD_SUCCESS; +} + -  /* For pretty printing. */ -  char *rule_str; +/* Route map rule. This rule has both `match' rule and `set' rule. */ +struct route_map_rule { +	/* Rule type. */ +	struct route_map_rule_cmd *cmd; + +	/* For pretty printing. */ +	char *rule_str; -  /* Pre-compiled match rule. */ -  void *value; +	/* Pre-compiled match rule. */ +	void *value; -  /* Linked list. */ -  struct route_map_rule *next; -  struct route_map_rule *prev; +	/* Linked list. */ +	struct route_map_rule *next; +	struct route_map_rule *prev;  };  /* Making route map list. */ -struct route_map_list -{ -  struct route_map *head; -  struct route_map *tail; +struct route_map_list { +	struct route_map *head; +	struct route_map *tail; -  void (*add_hook) (const char *); -  void (*delete_hook) (const char *); -  void (*event_hook) (route_map_event_t, const char *); +	void (*add_hook)(const char *); +	void (*delete_hook)(const char *); +	void (*event_hook)(route_map_event_t, const char *);  };  /* Master list of route map. */ -static struct route_map_list route_map_master = { NULL, NULL, NULL, NULL, NULL }; +static struct route_map_list route_map_master = {NULL, NULL, NULL, NULL, NULL};  struct hash *route_map_master_hash = NULL; -static unsigned int -route_map_hash_key_make (void *p) +static unsigned int route_map_hash_key_make(void *p)  { -  const struct route_map *map = p; -  return string_hash_make (map->name); +	const struct route_map *map = p; +	return string_hash_make(map->name);  } -static int -route_map_hash_cmp(const void *p1, const void *p2) +static int route_map_hash_cmp(const void *p1, const void *p2)  { -  const struct route_map *map1 = p1; -  const struct route_map *map2 = p2; +	const struct route_map *map1 = p1; +	const struct route_map *map2 = p2; -  if (map1->deleted == map2->deleted) -    { -      if (map1->name && map2->name) -        { -          if (!strcmp (map1->name, map2->name)) -            { -              return 1; -            } -        } -      else if (!map1->name && !map2->name) -        { -          return 1; -        } -    } +	if (map1->deleted == map2->deleted) { +		if (map1->name && map2->name) { +			if (!strcmp(map1->name, map2->name)) { +				return 1; +			} +		} else if (!map1->name && !map2->name) { +			return 1; +		} +	} -  return 0; +	return 0;  } -enum route_map_upd8_type -  { -    ROUTE_MAP_ADD = 1, -    ROUTE_MAP_DEL, -  }; +enum route_map_upd8_type { +	ROUTE_MAP_ADD = 1, +	ROUTE_MAP_DEL, +};  /* all possible route-map dependency types */ -enum route_map_dep_type -  { -    ROUTE_MAP_DEP_RMAP = 1, -    ROUTE_MAP_DEP_CLIST, -    ROUTE_MAP_DEP_ECLIST, -    ROUTE_MAP_DEP_LCLIST, -    ROUTE_MAP_DEP_PLIST, -    ROUTE_MAP_DEP_ASPATH, -    ROUTE_MAP_DEP_FILTER, -    ROUTE_MAP_DEP_MAX, -  }; - -struct route_map_dep -{ -  char *dep_name; -  struct hash *dep_rmap_hash; -  struct hash *this_hash;	/* ptr to the hash structure this is part of */ +enum route_map_dep_type { +	ROUTE_MAP_DEP_RMAP = 1, +	ROUTE_MAP_DEP_CLIST, +	ROUTE_MAP_DEP_ECLIST, +	ROUTE_MAP_DEP_LCLIST, +	ROUTE_MAP_DEP_PLIST, +	ROUTE_MAP_DEP_ASPATH, +	ROUTE_MAP_DEP_FILTER, +	ROUTE_MAP_DEP_MAX, +}; + +struct route_map_dep { +	char *dep_name; +	struct hash *dep_rmap_hash; +	struct hash *this_hash; /* ptr to the hash structure this is part of */  };  /* Hashes maintaining dependency between various sublists used by route maps */  struct hash *route_map_dep_hash[ROUTE_MAP_DEP_MAX]; -static unsigned int route_map_dep_hash_make_key (void *p); -static int route_map_dep_hash_cmp (const void *p1, const void *p2); -static void route_map_clear_all_references (char *rmap_name); -static void route_map_rule_delete (struct route_map_rule_list *, -				   struct route_map_rule *); +static unsigned int route_map_dep_hash_make_key(void *p); +static int route_map_dep_hash_cmp(const void *p1, const void *p2); +static void route_map_clear_all_references(char *rmap_name); +static void route_map_rule_delete(struct route_map_rule_list *, +				  struct route_map_rule *);  static int rmap_debug = 0; -static void -route_map_index_delete (struct route_map_index *, int); +static void route_map_index_delete(struct route_map_index *, int);  /* New route map allocation. Please note route map's name must be     specified. */ -static struct route_map * -route_map_new (const char *name) +static struct route_map *route_map_new(const char *name)  { -  struct route_map *new; +	struct route_map *new; -  new =  XCALLOC (MTYPE_ROUTE_MAP, sizeof (struct route_map)); -  new->name = XSTRDUP (MTYPE_ROUTE_MAP_NAME, name); -  QOBJ_REG (new, route_map); -  return new; +	new = XCALLOC(MTYPE_ROUTE_MAP, sizeof(struct route_map)); +	new->name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, name); +	QOBJ_REG(new, route_map); +	return new;  }  /* Add new name to route_map. */ -static struct route_map * -route_map_add (const char *name) -{ -  struct route_map *map; -  struct route_map_list *list; - -  map = route_map_new (name); -  list = &route_map_master; - -  /* Add map to the hash */ -  hash_get(route_map_master_hash, map, hash_alloc_intern); - -  /* Add new entry to the head of the list to match how it is added in the -   * hash table. This is to ensure that if the same route-map has been -   * created more than once and then marked for deletion (which can happen -   * if prior deletions haven't completed as BGP hasn't yet done the -   * route-map processing), the order of the entities is the same in both -   * the list and the hash table. Otherwise, since there is nothing to -   * distinguish between the two entries, the wrong entry could get freed. -   * TODO: This needs to be re-examined to handle it better - e.g., revive -   * a deleted entry if the route-map is created again. -   */ -  map->prev = NULL; -  map->next = list->head; -  if (list->head) -    list->head->prev = map; -  list->head = map; -  if (!list->tail) -    list->tail = map; - -  /* Execute hook. */ -  if (route_map_master.add_hook) -    { -      (*route_map_master.add_hook) (name); -      route_map_notify_dependencies(name, RMAP_EVENT_CALL_ADDED); -    } -  return map; +static struct route_map *route_map_add(const char *name) +{ +	struct route_map *map; +	struct route_map_list *list; + +	map = route_map_new(name); +	list = &route_map_master; + +	/* Add map to the hash */ +	hash_get(route_map_master_hash, map, hash_alloc_intern); + +	/* Add new entry to the head of the list to match how it is added in the +	 * hash table. This is to ensure that if the same route-map has been +	 * created more than once and then marked for deletion (which can happen +	 * if prior deletions haven't completed as BGP hasn't yet done the +	 * route-map processing), the order of the entities is the same in both +	 * the list and the hash table. Otherwise, since there is nothing to +	 * distinguish between the two entries, the wrong entry could get freed. +	 * TODO: This needs to be re-examined to handle it better - e.g., revive +	 * a deleted entry if the route-map is created again. +	 */ +	map->prev = NULL; +	map->next = list->head; +	if (list->head) +		list->head->prev = map; +	list->head = map; +	if (!list->tail) +		list->tail = map; + +	/* Execute hook. */ +	if (route_map_master.add_hook) { +		(*route_map_master.add_hook)(name); +		route_map_notify_dependencies(name, RMAP_EVENT_CALL_ADDED); +	} +	return map;  }  /* this is supposed to be called post processing by   * the delete hook function. Don't invoke delete_hook   * again in this routine.   */ -static void -route_map_free_map (struct route_map *map) +static void route_map_free_map(struct route_map *map)  { -  struct route_map_list *list; -  struct route_map_index *index; +	struct route_map_list *list; +	struct route_map_index *index; -  if (map == NULL) -    return; +	if (map == NULL) +		return; -  while ((index = map->head) != NULL) -    route_map_index_delete (index, 0); +	while ((index = map->head) != NULL) +		route_map_index_delete(index, 0); -  list = &route_map_master; +	list = &route_map_master; -  QOBJ_UNREG (map); +	QOBJ_UNREG(map); -  if (map->next) -    map->next->prev = map->prev; -  else -    list->tail = map->prev; +	if (map->next) +		map->next->prev = map->prev; +	else +		list->tail = map->prev; -  if (map->prev) -    map->prev->next = map->next; -  else -    list->head = map->next; +	if (map->prev) +		map->prev->next = map->next; +	else +		list->head = map->next; -  hash_release(route_map_master_hash, map); -  XFREE (MTYPE_ROUTE_MAP_NAME, map->name); -  XFREE (MTYPE_ROUTE_MAP, map); +	hash_release(route_map_master_hash, map); +	XFREE(MTYPE_ROUTE_MAP_NAME, map->name); +	XFREE(MTYPE_ROUTE_MAP, map);  }  /* Route map delete from list. */ -static void -route_map_delete (struct route_map *map) +static void route_map_delete(struct route_map *map)  { -  struct route_map_index *index; -  char *name; +	struct route_map_index *index; +	char *name; -  while ((index = map->head) != NULL) -    route_map_index_delete (index, 0); +	while ((index = map->head) != NULL) +		route_map_index_delete(index, 0); -  name = map->name; -  map->head = NULL; +	name = map->name; +	map->head = NULL; -  /* Clear all dependencies */ -  route_map_clear_all_references(name); -  map->deleted = 1; -  /* Execute deletion hook. */ -  if (route_map_master.delete_hook) -    { -      (*route_map_master.delete_hook) (name); -      route_map_notify_dependencies(name, RMAP_EVENT_CALL_DELETED); -    } +	/* Clear all dependencies */ +	route_map_clear_all_references(name); +	map->deleted = 1; +	/* Execute deletion hook. */ +	if (route_map_master.delete_hook) { +		(*route_map_master.delete_hook)(name); +		route_map_notify_dependencies(name, RMAP_EVENT_CALL_DELETED); +	} -  if (!map->to_be_processed) -    { -      route_map_free_map (map); -    } +	if (!map->to_be_processed) { +		route_map_free_map(map); +	}  }  /* Lookup route map by route map name string. */ -struct route_map * -route_map_lookup_by_name (const char *name) +struct route_map *route_map_lookup_by_name(const char *name)  { -  struct route_map *map; -  struct route_map tmp_map; +	struct route_map *map; +	struct route_map tmp_map; -  if (!name) -    return NULL; +	if (!name) +		return NULL; -  // map.deleted is 0 via memset -  memset(&tmp_map, 0, sizeof(struct route_map)); -  tmp_map.name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, name); -  map = hash_lookup(route_map_master_hash, &tmp_map); -  XFREE(MTYPE_ROUTE_MAP_NAME, tmp_map.name); -  return map; +	// map.deleted is 0 via memset +	memset(&tmp_map, 0, sizeof(struct route_map)); +	tmp_map.name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, name); +	map = hash_lookup(route_map_master_hash, &tmp_map); +	XFREE(MTYPE_ROUTE_MAP_NAME, tmp_map.name); +	return map;  } -int -route_map_mark_updated (const char *name, int del_later) +int route_map_mark_updated(const char *name, int del_later)  { -  struct route_map *map; -  int ret = -1; -  struct route_map tmp_map; +	struct route_map *map; +	int ret = -1; +	struct route_map tmp_map; -  if (!name) -    return (ret); +	if (!name) +		return (ret); -  map = route_map_lookup_by_name(name); +	map = route_map_lookup_by_name(name); -  /* If we did not find the routemap with deleted=0 try again -   * with deleted=1 -   */ -  if (!map) -    { -      memset(&tmp_map, 0, sizeof(struct route_map)); -      tmp_map.name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, name); -      tmp_map.deleted = 1; -      map = hash_lookup(route_map_master_hash, &tmp_map); -      XFREE(MTYPE_ROUTE_MAP_NAME, tmp_map.name); -    } +	/* If we did not find the routemap with deleted=0 try again +	 * with deleted=1 +	 */ +	if (!map) { +		memset(&tmp_map, 0, sizeof(struct route_map)); +		tmp_map.name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, name); +		tmp_map.deleted = 1; +		map = hash_lookup(route_map_master_hash, &tmp_map); +		XFREE(MTYPE_ROUTE_MAP_NAME, tmp_map.name); +	} -  if (map) -    { -      map->to_be_processed = 1; -      ret = 0; -    } +	if (map) { +		map->to_be_processed = 1; +		ret = 0; +	} -  return(ret); +	return (ret);  } -int -route_map_clear_updated (struct route_map *map) +int route_map_clear_updated(struct route_map *map)  { -  int ret = -1; +	int ret = -1; -  if (map) -    { -      map->to_be_processed = 0; -      if (map->deleted) -	route_map_free_map(map); -    } +	if (map) { +		map->to_be_processed = 0; +		if (map->deleted) +			route_map_free_map(map); +	} -  return (ret); +	return (ret);  }  /* Lookup route map.  If there isn't route map create one and return     it. */ -static struct route_map * -route_map_get (const char *name) +static struct route_map *route_map_get(const char *name)  { -  struct route_map *map; +	struct route_map *map; -  map = route_map_lookup_by_name (name); -  if (map == NULL) -    map = route_map_add (name); +	map = route_map_lookup_by_name(name); +	if (map == NULL) +		map = route_map_add(name); -  return map; +	return map;  } -void -route_map_walk_update_list (int (*route_map_update_fn) (char *name)) +void route_map_walk_update_list(int (*route_map_update_fn)(char *name))  { -  struct route_map *node; -  struct route_map *nnode = NULL; +	struct route_map *node; +	struct route_map *nnode = NULL; -  for (node = route_map_master.head; node; node = nnode) -    { -      if (node->to_be_processed) -	{ -	  /* DD: Should we add any thread yield code here */ -	  route_map_update_fn(node->name); -	  nnode = node->next; -	  route_map_clear_updated(node); +	for (node = route_map_master.head; node; node = nnode) { +		if (node->to_be_processed) { +			/* DD: Should we add any thread yield code here */ +			route_map_update_fn(node->name); +			nnode = node->next; +			route_map_clear_updated(node); +		} else +			nnode = node->next;  	} -      else -	nnode = node->next; -    }  }  /* Return route map's type string. */ -static const char * -route_map_type_str (enum route_map_type type) -{ -  switch (type) -    { -    case RMAP_PERMIT: -      return "permit"; -      break; -    case RMAP_DENY: -      return "deny"; -      break; -    default: -      return ""; -      break; -    } +static const char *route_map_type_str(enum route_map_type type) +{ +	switch (type) { +	case RMAP_PERMIT: +		return "permit"; +		break; +	case RMAP_DENY: +		return "deny"; +		break; +	default: +		return ""; +		break; +	}  } -static int -route_map_empty (struct route_map *map) +static int route_map_empty(struct route_map *map)  { -  if (map->head == NULL && map->tail == NULL) -    return 1; -  else -    return 0; +	if (map->head == NULL && map->tail == NULL) +		return 1; +	else +		return 0;  }  /* show route-map */ -static void -vty_show_route_map_entry (struct vty *vty, struct route_map *map) -{ -  struct route_map_index *index; -  struct route_map_rule *rule; - -  /* Print the name of the protocol */ -  if (zlog_default) -  { -    vty_out (vty, "%s", zlog_protoname()); -    if (zlog_default->instance) -      vty_out (vty, " %d", zlog_default->instance); -  } -  vty_out (vty, ":%s", VTY_NEWLINE); - -  for (index = map->head; index; index = index->next) -    { -      vty_out (vty, "route-map %s, %s, sequence %d%s", -               map->name, route_map_type_str (index->type), -               index->pref, VTY_NEWLINE); - -      /* Description */ -      if (index->description) -	vty_out (vty, "  Description:%s    %s%s", VTY_NEWLINE, -		 index->description, VTY_NEWLINE); -       -      /* Match clauses */ -      vty_out (vty, "  Match clauses:%s", VTY_NEWLINE); -      for (rule = index->match_list.head; rule; rule = rule->next) -        vty_out (vty, "    %s %s%s",  -                 rule->cmd->str, rule->rule_str, VTY_NEWLINE); -       -      vty_out (vty, "  Set clauses:%s", VTY_NEWLINE); -      for (rule = index->set_list.head; rule; rule = rule->next) -        vty_out (vty, "    %s %s%s", -                 rule->cmd->str, rule->rule_str, VTY_NEWLINE); -       -      /* Call clause */ -      vty_out (vty, "  Call clause:%s", VTY_NEWLINE); -      if (index->nextrm) -        vty_out (vty, "    Call %s%s", index->nextrm, VTY_NEWLINE); -       -      /* Exit Policy */ -      vty_out (vty, "  Action:%s", VTY_NEWLINE); -      if (index->exitpolicy == RMAP_GOTO) -        vty_out (vty, "    Goto %d%s", index->nextpref, VTY_NEWLINE); -      else if (index->exitpolicy == RMAP_NEXT) -        vty_out (vty, "    Continue to next entry%s", VTY_NEWLINE); -      else if (index->exitpolicy == RMAP_EXIT) -        vty_out (vty, "    Exit routemap%s", VTY_NEWLINE); -    } -} - -static int -vty_show_route_map (struct vty *vty, const char *name) -{ -  struct route_map *map; - -  if (name) -    { -      map = route_map_lookup_by_name (name); - -      if (map) -        { -          vty_show_route_map_entry (vty, map); -          return CMD_SUCCESS; -        } -      else -        { -          vty_out (vty, "%s", zlog_protoname()); -          if (zlog_default && zlog_default->instance) -            vty_out (vty, " %d", zlog_default->instance); -          vty_out (vty, ": 'route-map %s' not found%s", name, VTY_NEWLINE); -          return CMD_SUCCESS; -        } -    } -  else -    { -      for (map = route_map_master.head; map; map = map->next) -	if (!map->deleted) -	  vty_show_route_map_entry (vty, map); -    } -  return CMD_SUCCESS; +static void vty_show_route_map_entry(struct vty *vty, struct route_map *map) +{ +	struct route_map_index *index; +	struct route_map_rule *rule; + +	/* Print the name of the protocol */ +	if (zlog_default) { +		vty_out(vty, "%s", zlog_protoname()); +		if (zlog_default->instance) +			vty_out(vty, " %d", zlog_default->instance); +	} +	vty_out(vty, ":%s", VTY_NEWLINE); + +	for (index = map->head; index; index = index->next) { +		vty_out(vty, "route-map %s, %s, sequence %d%s", map->name, +			route_map_type_str(index->type), index->pref, +			VTY_NEWLINE); + +		/* Description */ +		if (index->description) +			vty_out(vty, "  Description:%s    %s%s", VTY_NEWLINE, +				index->description, VTY_NEWLINE); + +		/* Match clauses */ +		vty_out(vty, "  Match clauses:%s", VTY_NEWLINE); +		for (rule = index->match_list.head; rule; rule = rule->next) +			vty_out(vty, "    %s %s%s", rule->cmd->str, +				rule->rule_str, VTY_NEWLINE); + +		vty_out(vty, "  Set clauses:%s", VTY_NEWLINE); +		for (rule = index->set_list.head; rule; rule = rule->next) +			vty_out(vty, "    %s %s%s", rule->cmd->str, +				rule->rule_str, VTY_NEWLINE); + +		/* Call clause */ +		vty_out(vty, "  Call clause:%s", VTY_NEWLINE); +		if (index->nextrm) +			vty_out(vty, "    Call %s%s", index->nextrm, +				VTY_NEWLINE); + +		/* Exit Policy */ +		vty_out(vty, "  Action:%s", VTY_NEWLINE); +		if (index->exitpolicy == RMAP_GOTO) +			vty_out(vty, "    Goto %d%s", index->nextpref, +				VTY_NEWLINE); +		else if (index->exitpolicy == RMAP_NEXT) +			vty_out(vty, "    Continue to next entry%s", +				VTY_NEWLINE); +		else if (index->exitpolicy == RMAP_EXIT) +			vty_out(vty, "    Exit routemap%s", VTY_NEWLINE); +	} +} + +static int vty_show_route_map(struct vty *vty, const char *name) +{ +	struct route_map *map; + +	if (name) { +		map = route_map_lookup_by_name(name); + +		if (map) { +			vty_show_route_map_entry(vty, map); +			return CMD_SUCCESS; +		} else { +			vty_out(vty, "%s", zlog_protoname()); +			if (zlog_default && zlog_default->instance) +				vty_out(vty, " %d", zlog_default->instance); +			vty_out(vty, ": 'route-map %s' not found%s", name, +				VTY_NEWLINE); +			return CMD_SUCCESS; +		} +	} else { +		for (map = route_map_master.head; map; map = map->next) +			if (!map->deleted) +				vty_show_route_map_entry(vty, map); +	} +	return CMD_SUCCESS;  }  /* New route map allocation. Please note route map's name must be     specified. */ -static struct route_map_index * -route_map_index_new (void) +static struct route_map_index *route_map_index_new(void)  { -  struct route_map_index *new; +	struct route_map_index *new; -  new =  XCALLOC (MTYPE_ROUTE_MAP_INDEX, sizeof (struct route_map_index)); -  new->exitpolicy = RMAP_EXIT; /* Default to Cisco-style */ -  QOBJ_REG (new, route_map_index); -  return new; +	new = XCALLOC(MTYPE_ROUTE_MAP_INDEX, sizeof(struct route_map_index)); +	new->exitpolicy = RMAP_EXIT; /* Default to Cisco-style */ +	QOBJ_REG(new, route_map_index); +	return new;  }  /* Free route map index. */ -static void -route_map_index_delete (struct route_map_index *index, int notify) +static void route_map_index_delete(struct route_map_index *index, int notify)  { -  struct route_map_rule *rule; +	struct route_map_rule *rule; -  QOBJ_UNREG (index); +	QOBJ_UNREG(index); -  /* Free route match. */ -  while ((rule = index->match_list.head) != NULL) -    route_map_rule_delete (&index->match_list, rule); +	/* Free route match. */ +	while ((rule = index->match_list.head) != NULL) +		route_map_rule_delete(&index->match_list, rule); -  /* Free route set. */ -  while ((rule = index->set_list.head) != NULL) -    route_map_rule_delete (&index->set_list, rule); +	/* Free route set. */ +	while ((rule = index->set_list.head) != NULL) +		route_map_rule_delete(&index->set_list, rule); -  /* Remove index from route map list. */ -  if (index->next) -    index->next->prev = index->prev; -  else -    index->map->tail = index->prev; +	/* Remove index from route map list. */ +	if (index->next) +		index->next->prev = index->prev; +	else +		index->map->tail = index->prev; -  if (index->prev) -    index->prev->next = index->next; -  else -    index->map->head = index->next; +	if (index->prev) +		index->prev->next = index->next; +	else +		index->map->head = index->next; -  /* Free 'char *nextrm' if not NULL */ -  if (index->nextrm) -    XFREE (MTYPE_ROUTE_MAP_NAME, index->nextrm); +	/* Free 'char *nextrm' if not NULL */ +	if (index->nextrm) +		XFREE(MTYPE_ROUTE_MAP_NAME, index->nextrm); -    /* Execute event hook. */ -  if (route_map_master.event_hook && notify) -    { -      (*route_map_master.event_hook) (RMAP_EVENT_INDEX_DELETED, -				      index->map->name); -      route_map_notify_dependencies(index->map->name, RMAP_EVENT_CALL_ADDED); -    } -  XFREE (MTYPE_ROUTE_MAP_INDEX, index); +	/* Execute event hook. */ +	if (route_map_master.event_hook && notify) { +		(*route_map_master.event_hook)(RMAP_EVENT_INDEX_DELETED, +					       index->map->name); +		route_map_notify_dependencies(index->map->name, +					      RMAP_EVENT_CALL_ADDED); +	} +	XFREE(MTYPE_ROUTE_MAP_INDEX, index);  }  /* Lookup index from route map. */ -static struct route_map_index * -route_map_index_lookup (struct route_map *map, enum route_map_type type, -			int pref) +static struct route_map_index *route_map_index_lookup(struct route_map *map, +						      enum route_map_type type, +						      int pref)  { -  struct route_map_index *index; +	struct route_map_index *index; -  for (index = map->head; index; index = index->next) -    if ((index->type == type || type == RMAP_ANY) -	&& index->pref == pref) -      return index; -  return NULL; +	for (index = map->head; index; index = index->next) +		if ((index->type == type || type == RMAP_ANY) +		    && index->pref == pref) +			return index; +	return NULL;  }  /* Add new index to route map. */  static struct route_map_index * -route_map_index_add (struct route_map *map, enum route_map_type type, -		     int pref) -{ -  struct route_map_index *index; -  struct route_map_index *point; - -  /* Allocate new route map inex. */ -  index = route_map_index_new (); -  index->map = map; -  index->type = type; -  index->pref = pref; -   -  /* Compare preference. */ -  for (point = map->head; point; point = point->next) -    if (point->pref >= pref) -      break; - -  if (map->head == NULL) -    { -      map->head = map->tail = index; -    } -  else if (point == NULL) -    { -      index->prev = map->tail; -      map->tail->next = index; -      map->tail = index; -    } -  else if (point == map->head) -    { -      index->next = map->head; -      map->head->prev = index; -      map->head = index; -    } -  else -    { -      index->next = point; -      index->prev = point->prev; -      if (point->prev) -	point->prev->next = index; -      point->prev = index; -    } - -  /* Execute event hook. */ -  if (route_map_master.event_hook) -    { -      (*route_map_master.event_hook) (RMAP_EVENT_INDEX_ADDED, -				      map->name); -      route_map_notify_dependencies (map->name, RMAP_EVENT_CALL_ADDED); -    } -  return index; +route_map_index_add(struct route_map *map, enum route_map_type type, int pref) +{ +	struct route_map_index *index; +	struct route_map_index *point; + +	/* Allocate new route map inex. */ +	index = route_map_index_new(); +	index->map = map; +	index->type = type; +	index->pref = pref; + +	/* Compare preference. */ +	for (point = map->head; point; point = point->next) +		if (point->pref >= pref) +			break; + +	if (map->head == NULL) { +		map->head = map->tail = index; +	} else if (point == NULL) { +		index->prev = map->tail; +		map->tail->next = index; +		map->tail = index; +	} else if (point == map->head) { +		index->next = map->head; +		map->head->prev = index; +		map->head = index; +	} else { +		index->next = point; +		index->prev = point->prev; +		if (point->prev) +			point->prev->next = index; +		point->prev = index; +	} + +	/* Execute event hook. */ +	if (route_map_master.event_hook) { +		(*route_map_master.event_hook)(RMAP_EVENT_INDEX_ADDED, +					       map->name); +		route_map_notify_dependencies(map->name, RMAP_EVENT_CALL_ADDED); +	} +	return index;  }  /* Get route map index. */  static struct route_map_index * -route_map_index_get (struct route_map *map, enum route_map_type type,  -		     int pref) +route_map_index_get(struct route_map *map, enum route_map_type type, int pref)  { -  struct route_map_index *index; +	struct route_map_index *index; -  index = route_map_index_lookup (map, RMAP_ANY, pref); -  if (index && index->type != type) -    { -      /* Delete index from route map. */ -      route_map_index_delete (index, 1); -      index = NULL; -    } -  if (index == NULL) -    index = route_map_index_add (map, type, pref); -  return index; +	index = route_map_index_lookup(map, RMAP_ANY, pref); +	if (index && index->type != type) { +		/* Delete index from route map. */ +		route_map_index_delete(index, 1); +		index = NULL; +	} +	if (index == NULL) +		index = route_map_index_add(map, type, pref); +	return index;  }  /* New route map rule */ -static struct route_map_rule * -route_map_rule_new (void) +static struct route_map_rule *route_map_rule_new(void)  { -  struct route_map_rule *new; +	struct route_map_rule *new; -  new = XCALLOC (MTYPE_ROUTE_MAP_RULE, sizeof (struct route_map_rule)); -  return new; +	new = XCALLOC(MTYPE_ROUTE_MAP_RULE, sizeof(struct route_map_rule)); +	return new;  }  /* Install rule command to the match list. */ -void -route_map_install_match (struct route_map_rule_cmd *cmd) +void route_map_install_match(struct route_map_rule_cmd *cmd)  { -  vector_set (route_match_vec, cmd); +	vector_set(route_match_vec, cmd);  }  /* Install rule command to the set list. */ -void -route_map_install_set (struct route_map_rule_cmd *cmd) +void route_map_install_set(struct route_map_rule_cmd *cmd)  { -  vector_set (route_set_vec, cmd); +	vector_set(route_set_vec, cmd);  }  /* Lookup rule command from match list. */ -static struct route_map_rule_cmd * -route_map_lookup_match (const char *name) +static struct route_map_rule_cmd *route_map_lookup_match(const char *name)  { -  unsigned int i; -  struct route_map_rule_cmd *rule; +	unsigned int i; +	struct route_map_rule_cmd *rule; -  for (i = 0; i < vector_active (route_match_vec); i++) -    if ((rule = vector_slot (route_match_vec, i)) != NULL) -      if (strcmp (rule->str, name) == 0) -	return rule; -  return NULL; +	for (i = 0; i < vector_active(route_match_vec); i++) +		if ((rule = vector_slot(route_match_vec, i)) != NULL) +			if (strcmp(rule->str, name) == 0) +				return rule; +	return NULL;  }  /* Lookup rule command from set list. */ -static struct route_map_rule_cmd * -route_map_lookup_set (const char *name) +static struct route_map_rule_cmd *route_map_lookup_set(const char *name)  { -  unsigned int i; -  struct route_map_rule_cmd *rule; +	unsigned int i; +	struct route_map_rule_cmd *rule; -  for (i = 0; i < vector_active (route_set_vec); i++) -    if ((rule = vector_slot (route_set_vec, i)) != NULL) -      if (strcmp (rule->str, name) == 0) -	return rule; -  return NULL; +	for (i = 0; i < vector_active(route_set_vec); i++) +		if ((rule = vector_slot(route_set_vec, i)) != NULL) +			if (strcmp(rule->str, name) == 0) +				return rule; +	return NULL;  }  /* Add match and set rule to rule list. */ -static void -route_map_rule_add (struct route_map_rule_list *list, -		    struct route_map_rule *rule) +static void route_map_rule_add(struct route_map_rule_list *list, +			       struct route_map_rule *rule)  { -  rule->next = NULL; -  rule->prev = list->tail; -  if (list->tail) -    list->tail->next = rule; -  else -    list->head = rule; -  list->tail = rule; +	rule->next = NULL; +	rule->prev = list->tail; +	if (list->tail) +		list->tail->next = rule; +	else +		list->head = rule; +	list->tail = rule;  }  /* Delete rule from rule list. */ -static void -route_map_rule_delete (struct route_map_rule_list *list, -		       struct route_map_rule *rule) +static void route_map_rule_delete(struct route_map_rule_list *list, +				  struct route_map_rule *rule)  { -  if (rule->cmd->func_free) -    (*rule->cmd->func_free) (rule->value); +	if (rule->cmd->func_free) +		(*rule->cmd->func_free)(rule->value); -  if (rule->rule_str) -    XFREE (MTYPE_ROUTE_MAP_RULE_STR, rule->rule_str); +	if (rule->rule_str) +		XFREE(MTYPE_ROUTE_MAP_RULE_STR, rule->rule_str); -  if (rule->next) -    rule->next->prev = rule->prev; -  else -    list->tail = rule->prev; -  if (rule->prev) -    rule->prev->next = rule->next; -  else -    list->head = rule->next; +	if (rule->next) +		rule->next->prev = rule->prev; +	else +		list->tail = rule->prev; +	if (rule->prev) +		rule->prev->next = rule->next; +	else +		list->head = rule->next; -  XFREE (MTYPE_ROUTE_MAP_RULE, rule); +	XFREE(MTYPE_ROUTE_MAP_RULE, rule);  }  /* strcmp wrapper function which don't crush even argument is NULL. */ -static int -rulecmp (const char *dst, const char *src) -{ -  if (dst == NULL) -    { -      if (src ==  NULL) -	return 0; -      else -	return 1; -    } -  else -    { -      if (src == NULL) +static int rulecmp(const char *dst, const char *src) +{ +	if (dst == NULL) { +		if (src == NULL) +			return 0; +		else +			return 1; +	} else { +		if (src == NULL) +			return 1; +		else +			return strcmp(dst, src); +	}  	return 1; -      else -	return strcmp (dst, src); -    } -  return 1;  }  /* Use this to return the already specified argument for this match. This is   * useful to get the specified argument with a route map match rule when the   * rule is being deleted and the argument is not provided.   */ -const char * -route_map_get_match_arg(struct route_map_index *index, const char *match_name) +const char *route_map_get_match_arg(struct route_map_index *index, +				    const char *match_name)  { -  struct route_map_rule *rule; -  struct route_map_rule_cmd *cmd; +	struct route_map_rule *rule; +	struct route_map_rule_cmd *cmd; -  /* First lookup rule for add match statement. */ -  cmd = route_map_lookup_match (match_name); -  if (cmd == NULL) -    return NULL; +	/* First lookup rule for add match statement. */ +	cmd = route_map_lookup_match(match_name); +	if (cmd == NULL) +		return NULL; -  for (rule = index->match_list.head; rule; rule = rule->next) -    if (rule->cmd == cmd && rule->rule_str != NULL) -      return (rule->rule_str); +	for (rule = index->match_list.head; rule; rule = rule->next) +		if (rule->cmd == cmd && rule->rule_str != NULL) +			return (rule->rule_str); -  return (NULL); +	return (NULL);  }  /* Add match statement to route map. */ -int -route_map_add_match (struct route_map_index *index, const char *match_name, -                     const char *match_arg) -{ -  struct route_map_rule *rule; -  struct route_map_rule *next; -  struct route_map_rule_cmd *cmd; -  void *compile; -  int replaced = 0; - -  /* First lookup rule for add match statement. */ -  cmd = route_map_lookup_match (match_name); -  if (cmd == NULL) -    return RMAP_RULE_MISSING; - -  /* Next call compile function for this match statement. */ -  if (cmd->func_compile) -    { -      compile= (*cmd->func_compile)(match_arg); -      if (compile == NULL) -	return RMAP_COMPILE_ERROR; -    } -  else -    compile = NULL; - -  /* If argument is completely same ignore it. */ -  for (rule = index->match_list.head; rule; rule = next) -    { -      next = rule->next; -      if (rule->cmd == cmd) -	{	 -	  route_map_rule_delete (&index->match_list, rule); -	  replaced = 1; +int route_map_add_match(struct route_map_index *index, const char *match_name, +			const char *match_arg) +{ +	struct route_map_rule *rule; +	struct route_map_rule *next; +	struct route_map_rule_cmd *cmd; +	void *compile; +	int replaced = 0; + +	/* First lookup rule for add match statement. */ +	cmd = route_map_lookup_match(match_name); +	if (cmd == NULL) +		return RMAP_RULE_MISSING; + +	/* Next call compile function for this match statement. */ +	if (cmd->func_compile) { +		compile = (*cmd->func_compile)(match_arg); +		if (compile == NULL) +			return RMAP_COMPILE_ERROR; +	} else +		compile = NULL; + +	/* If argument is completely same ignore it. */ +	for (rule = index->match_list.head; rule; rule = next) { +		next = rule->next; +		if (rule->cmd == cmd) { +			route_map_rule_delete(&index->match_list, rule); +			replaced = 1; +		}  	} -    } -  /* Add new route map match rule. */ -  rule = route_map_rule_new (); -  rule->cmd = cmd; -  rule->value = compile; -  if (match_arg) -    rule->rule_str = XSTRDUP (MTYPE_ROUTE_MAP_RULE_STR, match_arg); -  else -    rule->rule_str = NULL; +	/* Add new route map match rule. */ +	rule = route_map_rule_new(); +	rule->cmd = cmd; +	rule->value = compile; +	if (match_arg) +		rule->rule_str = XSTRDUP(MTYPE_ROUTE_MAP_RULE_STR, match_arg); +	else +		rule->rule_str = NULL; -  /* Add new route match rule to linked list. */ -  route_map_rule_add (&index->match_list, rule); +	/* Add new route match rule to linked list. */ +	route_map_rule_add(&index->match_list, rule); -  /* Execute event hook. */ -  if (route_map_master.event_hook) -    { -      (*route_map_master.event_hook) (replaced ? -				      RMAP_EVENT_MATCH_REPLACED: -				      RMAP_EVENT_MATCH_ADDED, -				      index->map->name); -      route_map_notify_dependencies(index->map->name, RMAP_EVENT_CALL_ADDED); -    } +	/* Execute event hook. */ +	if (route_map_master.event_hook) { +		(*route_map_master.event_hook)( +			replaced ? RMAP_EVENT_MATCH_REPLACED +				 : RMAP_EVENT_MATCH_ADDED, +			index->map->name); +		route_map_notify_dependencies(index->map->name, +					      RMAP_EVENT_CALL_ADDED); +	} -  return 0; +	return 0;  }  /* Delete specified route match rule. */ -int -route_map_delete_match (struct route_map_index *index, const char *match_name, -                        const char *match_arg) -{ -  struct route_map_rule *rule; -  struct route_map_rule_cmd *cmd; - -  cmd = route_map_lookup_match (match_name); -  if (cmd == NULL) -    return 1; -   -  for (rule = index->match_list.head; rule; rule = rule->next) -    if (rule->cmd == cmd &&  -	(rulecmp (rule->rule_str, match_arg) == 0 || match_arg == NULL)) -      { -	route_map_rule_delete (&index->match_list, rule); -	/* Execute event hook. */ -	if (route_map_master.event_hook) -	  { -	    (*route_map_master.event_hook) (RMAP_EVENT_MATCH_DELETED, -					    index->map->name); -	    route_map_notify_dependencies(index->map->name, RMAP_EVENT_CALL_ADDED); -	  } -	return 0; -      } -  /* Can't find matched rule. */ -  return 1; +int route_map_delete_match(struct route_map_index *index, +			   const char *match_name, const char *match_arg) +{ +	struct route_map_rule *rule; +	struct route_map_rule_cmd *cmd; + +	cmd = route_map_lookup_match(match_name); +	if (cmd == NULL) +		return 1; + +	for (rule = index->match_list.head; rule; rule = rule->next) +		if (rule->cmd == cmd && (rulecmp(rule->rule_str, match_arg) == 0 +					 || match_arg == NULL)) { +			route_map_rule_delete(&index->match_list, rule); +			/* Execute event hook. */ +			if (route_map_master.event_hook) { +				(*route_map_master.event_hook)( +					RMAP_EVENT_MATCH_DELETED, +					index->map->name); +				route_map_notify_dependencies( +					index->map->name, +					RMAP_EVENT_CALL_ADDED); +			} +			return 0; +		} +	/* Can't find matched rule. */ +	return 1;  }  /* Add route-map set statement to the route map. */ -int -route_map_add_set (struct route_map_index *index, const char *set_name, -                   const char *set_arg) -{ -  struct route_map_rule *rule; -  struct route_map_rule *next; -  struct route_map_rule_cmd *cmd; -  void *compile; -  int replaced = 0; - -  cmd = route_map_lookup_set (set_name); -  if (cmd == NULL) -    return RMAP_RULE_MISSING; - -  /* Next call compile function for this match statement. */ -  if (cmd->func_compile) -    { -      compile= (*cmd->func_compile)(set_arg); -      if (compile == NULL) -	return RMAP_COMPILE_ERROR; -    } -  else -    compile = NULL; - - /* Add by WJL. if old set command of same kind exist, delete it first -    to ensure only one set command of same kind exist under a -    route_map_index. */ -  for (rule = index->set_list.head; rule; rule = next) -    { -      next = rule->next; -      if (rule->cmd == cmd) -	{ -	  route_map_rule_delete (&index->set_list, rule); -	  replaced = 1; +int route_map_add_set(struct route_map_index *index, const char *set_name, +		      const char *set_arg) +{ +	struct route_map_rule *rule; +	struct route_map_rule *next; +	struct route_map_rule_cmd *cmd; +	void *compile; +	int replaced = 0; + +	cmd = route_map_lookup_set(set_name); +	if (cmd == NULL) +		return RMAP_RULE_MISSING; + +	/* Next call compile function for this match statement. */ +	if (cmd->func_compile) { +		compile = (*cmd->func_compile)(set_arg); +		if (compile == NULL) +			return RMAP_COMPILE_ERROR; +	} else +		compile = NULL; + +	/* Add by WJL. if old set command of same kind exist, delete it first +	   to ensure only one set command of same kind exist under a +	   route_map_index. */ +	for (rule = index->set_list.head; rule; rule = next) { +		next = rule->next; +		if (rule->cmd == cmd) { +			route_map_rule_delete(&index->set_list, rule); +			replaced = 1; +		} +	} + +	/* Add new route map match rule. */ +	rule = route_map_rule_new(); +	rule->cmd = cmd; +	rule->value = compile; +	if (set_arg) +		rule->rule_str = XSTRDUP(MTYPE_ROUTE_MAP_RULE_STR, set_arg); +	else +		rule->rule_str = NULL; + +	/* Add new route match rule to linked list. */ +	route_map_rule_add(&index->set_list, rule); + +	/* Execute event hook. */ +	if (route_map_master.event_hook) { +		(*route_map_master.event_hook)(replaced +						       ? RMAP_EVENT_SET_REPLACED +						       : RMAP_EVENT_SET_ADDED, +					       index->map->name); +		route_map_notify_dependencies(index->map->name, +					      RMAP_EVENT_CALL_ADDED);  	} -    } - -  /* Add new route map match rule. */ -  rule = route_map_rule_new (); -  rule->cmd = cmd; -  rule->value = compile; -  if (set_arg) -    rule->rule_str = XSTRDUP (MTYPE_ROUTE_MAP_RULE_STR, set_arg); -  else -    rule->rule_str = NULL; - -  /* Add new route match rule to linked list. */ -  route_map_rule_add (&index->set_list, rule); - -  /* Execute event hook. */ -  if (route_map_master.event_hook) -    { -      (*route_map_master.event_hook) (replaced ? -				      RMAP_EVENT_SET_REPLACED: -				      RMAP_EVENT_SET_ADDED, -				      index->map->name); -      route_map_notify_dependencies(index->map->name, RMAP_EVENT_CALL_ADDED); -    } -  return 0; +	return 0;  }  /* Delete route map set rule. */ -int -route_map_delete_set (struct route_map_index *index, const char *set_name, -                      const char *set_arg) -{ -  struct route_map_rule *rule; -  struct route_map_rule_cmd *cmd; - -  cmd = route_map_lookup_set (set_name); -  if (cmd == NULL) -    return 1; -   -  for (rule = index->set_list.head; rule; rule = rule->next) -    if ((rule->cmd == cmd) && -         (rulecmp (rule->rule_str, set_arg) == 0 || set_arg == NULL)) -      { -        route_map_rule_delete (&index->set_list, rule); -	/* Execute event hook. */ -	if (route_map_master.event_hook) -	  { -	    (*route_map_master.event_hook) (RMAP_EVENT_SET_DELETED, -					    index->map->name); -	    route_map_notify_dependencies(index->map->name, RMAP_EVENT_CALL_ADDED); -	  } -        return 0; -      } -  /* Can't find matched rule. */ -  return 1; +int route_map_delete_set(struct route_map_index *index, const char *set_name, +			 const char *set_arg) +{ +	struct route_map_rule *rule; +	struct route_map_rule_cmd *cmd; + +	cmd = route_map_lookup_set(set_name); +	if (cmd == NULL) +		return 1; + +	for (rule = index->set_list.head; rule; rule = rule->next) +		if ((rule->cmd == cmd) && (rulecmp(rule->rule_str, set_arg) == 0 +					   || set_arg == NULL)) { +			route_map_rule_delete(&index->set_list, rule); +			/* Execute event hook. */ +			if (route_map_master.event_hook) { +				(*route_map_master.event_hook)( +					RMAP_EVENT_SET_DELETED, +					index->map->name); +				route_map_notify_dependencies( +					index->map->name, +					RMAP_EVENT_CALL_ADDED); +			} +			return 0; +		} +	/* Can't find matched rule. */ +	return 1;  }  /* Apply route map's each index to the object. @@ -1531,20 +1347,20 @@ route_map_delete_set (struct route_map_index *index, const char *set_name,     The matrix for a route-map looks like this:     (note, this includes the description for the "NEXT"     and "GOTO" frobs now -   -              Match   |   No Match -                      | + +	      Match   |   No Match +		      |      permit    action  |     cont -                      | +		      |      ------------------+--------------- -                      | +		      |      deny      deny    |     cont -                      | -   +		      | +     action)        -Apply Set statements, accept route        -If Call statement is present jump to the specified route-map, if it -         denies the route we finish. +	 denies the route we finish.        -If NEXT is specified, goto NEXT statement        -If GOTO is specified, goto the first clause where pref > nextpref        -If nothing is specified, do as Cisco and finish @@ -1552,434 +1368,415 @@ route_map_delete_set (struct route_map_index *index, const char *set_name,        -Route is denied by route-map.     cont)        -Goto Next index -   +     If we get no matches after we've processed all updates, then the route     is dropped too. -   +     Some notes on the new "CALL", "NEXT" and "GOTO"       call WORD        - If this clause is matched, then the set statements -                        are executed and then we jump to route-map 'WORD'. If -                        this route-map denies the route, we finish, in other case we -                        do whatever the exit policy (EXIT, NEXT or GOTO) tells. +			are executed and then we jump to route-map 'WORD'. If +			this route-map denies the route, we finish, in other +   case we +			do whatever the exit policy (EXIT, NEXT or GOTO) tells.       on-match next    - If this clause is matched, then the set statements -                        are executed and then we drop through to the next clause +			are executed and then we drop through to the next clause       on-match goto n  - If this clause is matched, then the set statments -                        are executed and then we goto the nth clause, or the -                        first clause greater than this. In order to ensure -                        route-maps *always* exit, you cannot jump backwards. -                        Sorry ;) -   +			are executed and then we goto the nth clause, or the +			first clause greater than this. In order to ensure +			route-maps *always* exit, you cannot jump backwards. +			Sorry ;) +     We need to make sure our route-map processing matches the above  */  static route_map_result_t -route_map_apply_match (struct route_map_rule_list *match_list, -                       struct prefix *prefix, route_map_object_t type, -                       void *object) -{ -  route_map_result_t ret = RMAP_NOMATCH; -  struct route_map_rule *match; - - -  /* Check all match rule and if there is no match rule, go to the -     set statement. */ -  if (!match_list->head) -    ret = RMAP_MATCH; -  else -    { -      for (match = match_list->head; match; match = match->next) -        { -          /* Try each match statement in turn, If any do not return -             RMAP_MATCH, return, otherwise continue on to next match  -             statement. All match statements must match for end-result -             to be a match. */ -          ret = (*match->cmd->func_apply) (match->value, prefix, -                                           type, object); -          if (ret != RMAP_MATCH) -            return ret; -        } -    } -  return ret; +route_map_apply_match(struct route_map_rule_list *match_list, +		      struct prefix *prefix, route_map_object_t type, +		      void *object) +{ +	route_map_result_t ret = RMAP_NOMATCH; +	struct route_map_rule *match; + + +	/* Check all match rule and if there is no match rule, go to the +	   set statement. */ +	if (!match_list->head) +		ret = RMAP_MATCH; +	else { +		for (match = match_list->head; match; match = match->next) { +			/* Try each match statement in turn, If any do not +			   return +			   RMAP_MATCH, return, otherwise continue on to next +			   match +			   statement. All match statements must match for +			   end-result +			   to be a match. */ +			ret = (*match->cmd->func_apply)(match->value, prefix, +							type, object); +			if (ret != RMAP_MATCH) +				return ret; +		} +	} +	return ret;  }  /* Apply route map to the object. */ -route_map_result_t -route_map_apply (struct route_map *map, struct prefix *prefix, -                 route_map_object_t type, void *object) -{ -  static int recursion = 0; -  int ret = 0; -  struct route_map_index *index; -  struct route_map_rule *set; - -  if (recursion > RMAP_RECURSION_LIMIT) -    { -      zlog_warn("route-map recursion limit (%d) reached, discarding route", -                RMAP_RECURSION_LIMIT); -      recursion = 0; -      return RMAP_DENYMATCH; -    } - -  if (map == NULL) -    return RMAP_DENYMATCH; - -  for (index = map->head; index; index = index->next) -    { -      /* Apply this index. */ -      ret = route_map_apply_match (&index->match_list, prefix, type, object); - -      /* Now we apply the matrix from above */ -      if (ret == RMAP_NOMATCH) -        /* 'cont' from matrix - continue to next route-map sequence */ -        continue; -      else if (ret == RMAP_MATCH) -        { -          if (index->type == RMAP_PERMIT) -            /* 'action' */ -            { -              /* permit+match must execute sets */ -              for (set = index->set_list.head; set; set = set->next) -                ret = (*set->cmd->func_apply) (set->value, prefix, -                                               type, object); - -              /* Call another route-map if available */ -              if (index->nextrm) -                { -                  struct route_map *nextrm = -                                    route_map_lookup_by_name (index->nextrm); - -                  if (nextrm) /* Target route-map found, jump to it */ -                    { -                      recursion++; -                      ret = route_map_apply (nextrm, prefix, type, object); -                      recursion--; -                    } - -                  /* If nextrm returned 'deny', finish. */ -                  if (ret == RMAP_DENYMATCH) -                    return ret; -                } -                 -              switch (index->exitpolicy) -                { -                  case RMAP_EXIT: -                    return ret; -                  case RMAP_NEXT: -                    continue; -                  case RMAP_GOTO: -                    { -                      /* Find the next clause to jump to */ -                      struct route_map_index *next = index->next; -                      int nextpref = index->nextpref; - -                      while (next && next->pref < nextpref) -                        { -                          index = next; -                          next = next->next; -                        } -                      if (next == NULL) -                        { -                          /* No clauses match! */ -                          return ret; -                        } -                    } -                } -            } -          else if (index->type == RMAP_DENY) -            /* 'deny' */ -            { -                return RMAP_DENYMATCH; -            } -        } -    } -  /* Finally route-map does not match at all. */ -  return RMAP_DENYMATCH; -} - -void -route_map_add_hook (void (*func) (const char *)) -{ -  route_map_master.add_hook = func; -} - -void -route_map_delete_hook (void (*func) (const char *)) -{ -  route_map_master.delete_hook = func; -} - -void -route_map_event_hook (void (*func) (route_map_event_t, const char *)) -{ -  route_map_master.event_hook = func; +route_map_result_t route_map_apply(struct route_map *map, struct prefix *prefix, +				   route_map_object_t type, void *object) +{ +	static int recursion = 0; +	int ret = 0; +	struct route_map_index *index; +	struct route_map_rule *set; + +	if (recursion > RMAP_RECURSION_LIMIT) { +		zlog_warn( +			"route-map recursion limit (%d) reached, discarding route", +			RMAP_RECURSION_LIMIT); +		recursion = 0; +		return RMAP_DENYMATCH; +	} + +	if (map == NULL) +		return RMAP_DENYMATCH; + +	for (index = map->head; index; index = index->next) { +		/* Apply this index. */ +		ret = route_map_apply_match(&index->match_list, prefix, type, +					    object); + +		/* Now we apply the matrix from above */ +		if (ret == RMAP_NOMATCH) +			/* 'cont' from matrix - continue to next route-map +			 * sequence */ +			continue; +		else if (ret == RMAP_MATCH) { +			if (index->type == RMAP_PERMIT) +			/* 'action' */ +			{ +				/* permit+match must execute sets */ +				for (set = index->set_list.head; set; +				     set = set->next) +					ret = (*set->cmd->func_apply)( +						set->value, prefix, type, +						object); + +				/* Call another route-map if available */ +				if (index->nextrm) { +					struct route_map *nextrm = +						route_map_lookup_by_name( +							index->nextrm); + +					if (nextrm) /* Target route-map found, +						       jump to it */ +					{ +						recursion++; +						ret = route_map_apply( +							nextrm, prefix, type, +							object); +						recursion--; +					} + +					/* If nextrm returned 'deny', finish. */ +					if (ret == RMAP_DENYMATCH) +						return ret; +				} + +				switch (index->exitpolicy) { +				case RMAP_EXIT: +					return ret; +				case RMAP_NEXT: +					continue; +				case RMAP_GOTO: { +					/* Find the next clause to jump to */ +					struct route_map_index *next = +						index->next; +					int nextpref = index->nextpref; + +					while (next && next->pref < nextpref) { +						index = next; +						next = next->next; +					} +					if (next == NULL) { +						/* No clauses match! */ +						return ret; +					} +				} +				} +			} else if (index->type == RMAP_DENY) +			/* 'deny' */ +			{ +				return RMAP_DENYMATCH; +			} +		} +	} +	/* Finally route-map does not match at all. */ +	return RMAP_DENYMATCH; +} + +void route_map_add_hook(void (*func)(const char *)) +{ +	route_map_master.add_hook = func; +} + +void route_map_delete_hook(void (*func)(const char *)) +{ +	route_map_master.delete_hook = func; +} + +void route_map_event_hook(void (*func)(route_map_event_t, const char *)) +{ +	route_map_master.event_hook = func;  }  /* Routines for route map dependency lists and dependency processing */ -static int -route_map_rmap_hash_cmp (const void *p1, const void *p2) +static int route_map_rmap_hash_cmp(const void *p1, const void *p2)  { -  return (strcmp((const char *)p1, (const char *)p2) == 0); +	return (strcmp((const char *)p1, (const char *)p2) == 0);  } -static int -route_map_dep_hash_cmp (const void *p1, const void *p2) +static int route_map_dep_hash_cmp(const void *p1, const void *p2)  { -  return (strcmp (((const struct route_map_dep *)p1)->dep_name, (const char *)p2) == 0); +	return (strcmp(((const struct route_map_dep *)p1)->dep_name, +		       (const char *)p2) +		== 0);  } -static void -route_map_clear_reference(struct hash_backet *backet, void *arg) +static void route_map_clear_reference(struct hash_backet *backet, void *arg)  { -  struct route_map_dep *dep = (struct route_map_dep *)backet->data; -  char *rmap_name; +	struct route_map_dep *dep = (struct route_map_dep *)backet->data; +	char *rmap_name; -  if (dep && arg) -    { -      rmap_name = (char *)hash_release(dep->dep_rmap_hash, (void *)arg); -      if (rmap_name) -	{ -	  XFREE(MTYPE_ROUTE_MAP_NAME, rmap_name); +	if (dep && arg) { +		rmap_name = +			(char *)hash_release(dep->dep_rmap_hash, (void *)arg); +		if (rmap_name) { +			XFREE(MTYPE_ROUTE_MAP_NAME, rmap_name); +		} +		if (!dep->dep_rmap_hash->count) { +			dep = hash_release(dep->this_hash, +					   (void *)dep->dep_name); +			hash_free(dep->dep_rmap_hash); +			XFREE(MTYPE_ROUTE_MAP_NAME, dep->dep_name); +			XFREE(MTYPE_ROUTE_MAP_DEP, dep); +		}  	} -      if (!dep->dep_rmap_hash->count) -	{ -	  dep = hash_release(dep->this_hash, (void *)dep->dep_name); -	  hash_free(dep->dep_rmap_hash); -	  XFREE(MTYPE_ROUTE_MAP_NAME, dep->dep_name); -	  XFREE(MTYPE_ROUTE_MAP_DEP, dep); +} + +static void route_map_clear_all_references(char *rmap_name) +{ +	int i; + +	for (i = 1; i < ROUTE_MAP_DEP_MAX; i++) { +		hash_iterate(route_map_dep_hash[i], route_map_clear_reference, +			     (void *)rmap_name);  	} -    }  } -static void -route_map_clear_all_references (char *rmap_name) +static void *route_map_dep_hash_alloc(void *p)  { -  int i; +	char *dep_name = (char *)p; +	struct route_map_dep *dep_entry; + +	dep_entry = XCALLOC(MTYPE_ROUTE_MAP_DEP, sizeof(struct route_map_dep)); +	dep_entry->dep_name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, dep_name); +	dep_entry->dep_rmap_hash = hash_create(route_map_dep_hash_make_key, +					       route_map_rmap_hash_cmp); +	dep_entry->this_hash = NULL; + +	return ((void *)dep_entry); +} -  for (i = 1; i < ROUTE_MAP_DEP_MAX; i++) -    { -      hash_iterate(route_map_dep_hash[i], route_map_clear_reference, -		   (void *)rmap_name); -    } +static void *route_map_name_hash_alloc(void *p) +{ +	return ((void *)XSTRDUP(MTYPE_ROUTE_MAP_NAME, (const char *)p));  } -static void * -route_map_dep_hash_alloc(void *p) +static unsigned int route_map_dep_hash_make_key(void *p)  { -  char *dep_name = (char *)p; -  struct route_map_dep *dep_entry; +	return (string_hash_make((char *)p)); +} -  dep_entry = XCALLOC(MTYPE_ROUTE_MAP_DEP, sizeof(struct route_map_dep)); -  dep_entry->dep_name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, dep_name); -  dep_entry->dep_rmap_hash = hash_create(route_map_dep_hash_make_key, -					 route_map_rmap_hash_cmp); -  dep_entry->this_hash = NULL; +static void route_map_print_dependency(struct hash_backet *backet, void *data) +{ +	char *rmap_name = (char *)backet->data; +	char *dep_name = (char *)data; -  return((void *)dep_entry); +	if (rmap_name) +		zlog_debug("%s: Dependency for %s: %s", __FUNCTION__, dep_name, +			   rmap_name);  } -static void * -route_map_name_hash_alloc(void *p) +static int route_map_dep_update(struct hash *dephash, const char *dep_name, +				const char *rmap_name, route_map_event_t type)  { -  return((void *)XSTRDUP(MTYPE_ROUTE_MAP_NAME, (const char *)p)); +	struct route_map_dep *dep = NULL; +	char *ret_map_name; +	char *dname, *rname; +	int ret = 0; + +	dname = XSTRDUP(MTYPE_ROUTE_MAP_NAME, dep_name); +	rname = XSTRDUP(MTYPE_ROUTE_MAP_NAME, rmap_name); + +	switch (type) { +	case RMAP_EVENT_PLIST_ADDED: +	case RMAP_EVENT_CLIST_ADDED: +	case RMAP_EVENT_ECLIST_ADDED: +	case RMAP_EVENT_ASLIST_ADDED: +	case RMAP_EVENT_LLIST_ADDED: +	case RMAP_EVENT_CALL_ADDED: +	case RMAP_EVENT_FILTER_ADDED: +		if (rmap_debug) +			zlog_debug("%s: Adding dependency for %s in %s", +				   __FUNCTION__, dep_name, rmap_name); +		dep = (struct route_map_dep *)hash_get( +			dephash, dname, route_map_dep_hash_alloc); +		if (!dep) { +			ret = -1; +			goto out; +		} + +		if (!dep->this_hash) +			dep->this_hash = dephash; + +		hash_get(dep->dep_rmap_hash, rname, route_map_name_hash_alloc); +		break; +	case RMAP_EVENT_PLIST_DELETED: +	case RMAP_EVENT_CLIST_DELETED: +	case RMAP_EVENT_ECLIST_DELETED: +	case RMAP_EVENT_ASLIST_DELETED: +	case RMAP_EVENT_LLIST_DELETED: +	case RMAP_EVENT_CALL_DELETED: +	case RMAP_EVENT_FILTER_DELETED: +		if (rmap_debug) +			zlog_debug("%s: Deleting dependency for %s in %s", +				   __FUNCTION__, dep_name, rmap_name); +		dep = (struct route_map_dep *)hash_get(dephash, dname, NULL); +		if (!dep) { +			goto out; +		} + +		ret_map_name = (char *)hash_release(dep->dep_rmap_hash, rname); +		if (ret_map_name) +			XFREE(MTYPE_ROUTE_MAP_NAME, ret_map_name); + +		if (!dep->dep_rmap_hash->count) { +			dep = hash_release(dephash, dname); +			hash_free(dep->dep_rmap_hash); +			XFREE(MTYPE_ROUTE_MAP_NAME, dep->dep_name); +			XFREE(MTYPE_ROUTE_MAP_DEP, dep); +			dep = NULL; +		} +		break; +	default: +		break; +	} + +	if (dep) { +		if (rmap_debug) +			hash_iterate(dep->dep_rmap_hash, +				     route_map_print_dependency, dname); +	} + +out: +	XFREE(MTYPE_ROUTE_MAP_NAME, rname); +	XFREE(MTYPE_ROUTE_MAP_NAME, dname); +	return ret; +} + +static struct hash *route_map_get_dep_hash(route_map_event_t event) +{ +	struct hash *upd8_hash = NULL; + +	switch (event) { +	case RMAP_EVENT_PLIST_ADDED: +	case RMAP_EVENT_PLIST_DELETED: +		upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_PLIST]; +		break; +	case RMAP_EVENT_CLIST_ADDED: +	case RMAP_EVENT_CLIST_DELETED: +		upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_CLIST]; +		break; +	case RMAP_EVENT_ECLIST_ADDED: +	case RMAP_EVENT_ECLIST_DELETED: +		upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_ECLIST]; +		break; +	case RMAP_EVENT_ASLIST_ADDED: +	case RMAP_EVENT_ASLIST_DELETED: +		upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_ASPATH]; +		break; +	case RMAP_EVENT_LLIST_ADDED: +	case RMAP_EVENT_LLIST_DELETED: +		upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_LCLIST]; +		break; +	case RMAP_EVENT_CALL_ADDED: +	case RMAP_EVENT_CALL_DELETED: +		upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_RMAP]; +		break; +	case RMAP_EVENT_FILTER_ADDED: +	case RMAP_EVENT_FILTER_DELETED: +		upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_FILTER]; +		break; +	default: +		upd8_hash = NULL; +		break; +	} +	return (upd8_hash);  } -static unsigned int -route_map_dep_hash_make_key (void *p) +static void route_map_process_dependency(struct hash_backet *backet, void *data)  { -  return (string_hash_make((char *)p)); +	char *rmap_name; +	route_map_event_t type = (route_map_event_t)(ptrdiff_t)data; + +	rmap_name = (char *)backet->data; + +	if (rmap_name) { +		if (rmap_debug) +			zlog_debug("%s: Notifying %s of dependency", +				   __FUNCTION__, rmap_name); +		if (route_map_master.event_hook) +			(*route_map_master.event_hook)(type, rmap_name); +	}  } -static void -route_map_print_dependency (struct hash_backet *backet, void *data) +void route_map_upd8_dependency(route_map_event_t type, const char *arg, +			       const char *rmap_name)  { -  char *rmap_name = (char *)backet->data; -  char *dep_name  = (char *)data; +	struct hash *upd8_hash = NULL; -  if (rmap_name) -    zlog_debug("%s: Dependency for %s: %s", __FUNCTION__, dep_name, rmap_name); +	if ((upd8_hash = route_map_get_dep_hash(type))) +		route_map_dep_update(upd8_hash, arg, rmap_name, type);  } -static int -route_map_dep_update (struct hash *dephash, const char *dep_name, -		      const char *rmap_name, -		      route_map_event_t type) +void route_map_notify_dependencies(const char *affected_name, +				   route_map_event_t event)  { -  struct route_map_dep *dep = NULL; -  char *ret_map_name; -  char *dname, *rname; -  int ret = 0; - -  dname = XSTRDUP(MTYPE_ROUTE_MAP_NAME, dep_name); -  rname = XSTRDUP(MTYPE_ROUTE_MAP_NAME, rmap_name); - -  switch (type) -    { -    case RMAP_EVENT_PLIST_ADDED: -    case RMAP_EVENT_CLIST_ADDED: -    case RMAP_EVENT_ECLIST_ADDED: -    case RMAP_EVENT_ASLIST_ADDED: -    case RMAP_EVENT_LLIST_ADDED: -    case RMAP_EVENT_CALL_ADDED: -    case RMAP_EVENT_FILTER_ADDED: -      if (rmap_debug) -	zlog_debug("%s: Adding dependency for %s in %s", __FUNCTION__, -		   dep_name, rmap_name); -      dep = (struct route_map_dep *) hash_get (dephash, dname, -					       route_map_dep_hash_alloc); -      if (!dep) { -	ret = -1; -	goto out; -      } - -      if (!dep->this_hash) -	dep->this_hash = dephash; - -      hash_get(dep->dep_rmap_hash, rname, route_map_name_hash_alloc); -      break; -    case RMAP_EVENT_PLIST_DELETED: -    case RMAP_EVENT_CLIST_DELETED: -    case RMAP_EVENT_ECLIST_DELETED: -    case RMAP_EVENT_ASLIST_DELETED: -    case RMAP_EVENT_LLIST_DELETED: -    case RMAP_EVENT_CALL_DELETED: -    case RMAP_EVENT_FILTER_DELETED: -      if (rmap_debug) -	zlog_debug("%s: Deleting dependency for %s in %s", __FUNCTION__, -		   dep_name, rmap_name); -      dep = (struct route_map_dep *) hash_get (dephash, dname, NULL); -      if (!dep) { -	goto out; -      } - -      ret_map_name = (char *)hash_release(dep->dep_rmap_hash, rname); -      if (ret_map_name) -	XFREE(MTYPE_ROUTE_MAP_NAME, ret_map_name); - -      if (!dep->dep_rmap_hash->count) -	{ -	  dep = hash_release(dephash, dname); -	  hash_free(dep->dep_rmap_hash); -	  XFREE(MTYPE_ROUTE_MAP_NAME, dep->dep_name); -	  XFREE(MTYPE_ROUTE_MAP_DEP, dep); -	  dep = NULL; +	struct route_map_dep *dep; +	struct hash *upd8_hash; +	char *name; + +	if (!affected_name) +		return; + +	name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, affected_name); + +	if ((upd8_hash = route_map_get_dep_hash(event)) == NULL) { +		XFREE(MTYPE_ROUTE_MAP_NAME, name); +		return; +	} + +	dep = (struct route_map_dep *)hash_get(upd8_hash, name, NULL); +	if (dep) { +		if (!dep->this_hash) +			dep->this_hash = upd8_hash; + +		hash_iterate(dep->dep_rmap_hash, route_map_process_dependency, +			     (void *)event);  	} -      break; -    default: -      break; -    } - -  if (dep) -    { -      if (rmap_debug) -	hash_iterate (dep->dep_rmap_hash, route_map_print_dependency, dname); -    } - - out: -  XFREE(MTYPE_ROUTE_MAP_NAME, rname); -  XFREE(MTYPE_ROUTE_MAP_NAME, dname); -  return ret; -} - -static struct hash * -route_map_get_dep_hash (route_map_event_t event) -{ -  struct hash *upd8_hash = NULL; - -  switch (event) -    { -    case RMAP_EVENT_PLIST_ADDED: -    case RMAP_EVENT_PLIST_DELETED: -      upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_PLIST]; -      break; -    case RMAP_EVENT_CLIST_ADDED: -    case RMAP_EVENT_CLIST_DELETED: -      upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_CLIST]; -      break; -    case RMAP_EVENT_ECLIST_ADDED: -    case RMAP_EVENT_ECLIST_DELETED: -      upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_ECLIST]; -      break; -    case RMAP_EVENT_ASLIST_ADDED: -    case RMAP_EVENT_ASLIST_DELETED: -      upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_ASPATH]; -      break; -    case RMAP_EVENT_LLIST_ADDED: -    case RMAP_EVENT_LLIST_DELETED: -      upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_LCLIST]; -      break; -    case RMAP_EVENT_CALL_ADDED: -    case RMAP_EVENT_CALL_DELETED: -      upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_RMAP]; -      break; -    case RMAP_EVENT_FILTER_ADDED: -    case RMAP_EVENT_FILTER_DELETED: -      upd8_hash = route_map_dep_hash[ROUTE_MAP_DEP_FILTER]; -      break; -    default: -      upd8_hash = NULL; -      break; -    } -  return (upd8_hash); -} - -static void -route_map_process_dependency (struct hash_backet *backet, void *data) -{ -  char *rmap_name; -  route_map_event_t type = (route_map_event_t)(ptrdiff_t)data; - -  rmap_name = (char *)backet->data; - -  if (rmap_name) -    { -      if (rmap_debug) -	zlog_debug("%s: Notifying %s of dependency", __FUNCTION__, -		   rmap_name); -      if (route_map_master.event_hook) -	(*route_map_master.event_hook) (type, rmap_name); -    } -} - -void -route_map_upd8_dependency (route_map_event_t type, const char *arg, -			   const char *rmap_name) -{ -  struct hash *upd8_hash = NULL; - -  if ((upd8_hash = route_map_get_dep_hash(type))) -    route_map_dep_update (upd8_hash, arg, rmap_name, type); -} - -void -route_map_notify_dependencies (const char *affected_name, route_map_event_t event) -{ -  struct route_map_dep *dep; -  struct hash *upd8_hash; -  char *name; - -  if (!affected_name) -    return; - -  name = XSTRDUP(MTYPE_ROUTE_MAP_NAME, affected_name); - -  if ((upd8_hash = route_map_get_dep_hash(event)) == NULL) -    { -      XFREE (MTYPE_ROUTE_MAP_NAME, name); -      return; -    } - -  dep = (struct route_map_dep *)hash_get (upd8_hash, name, -					  NULL); -  if (dep) -    { -      if (!dep->this_hash) -	dep->this_hash = upd8_hash; - -      hash_iterate (dep->dep_rmap_hash, route_map_process_dependency, (void *)event); -    } - -  XFREE (MTYPE_ROUTE_MAP_NAME, name); + +	XFREE(MTYPE_ROUTE_MAP_NAME, name);  } @@ -1991,12 +1788,14 @@ DEFUN (match_interface,         "match first hop interface of route\n"         "Interface name\n")  { -  int idx_word = 2; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_word = 2; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.match_interface) -    return rmap_match_set_hook.match_interface (vty, index, "interface", argv[idx_word]->arg, RMAP_EVENT_MATCH_ADDED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.match_interface) +		return rmap_match_set_hook.match_interface( +			vty, index, "interface", argv[idx_word]->arg, +			RMAP_EVENT_MATCH_ADDED); +	return CMD_SUCCESS;  }  DEFUN (no_match_interface, @@ -2007,12 +1806,14 @@ DEFUN (no_match_interface,         "Match first hop interface of route\n"         "Interface name\n")  { -  char *iface = (argc == 4) ? argv[3]->arg : NULL; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	char *iface = (argc == 4) ? argv[3]->arg : NULL; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.no_match_interface) -    return rmap_match_set_hook.no_match_interface (vty, index, "interface", iface, RMAP_EVENT_MATCH_DELETED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.no_match_interface) +		return rmap_match_set_hook.no_match_interface( +			vty, index, "interface", iface, +			RMAP_EVENT_MATCH_DELETED); +	return CMD_SUCCESS;  } @@ -2026,13 +1827,14 @@ DEFUN (match_ip_address,         "IP access-list number (expanded range)\n"         "IP Access-list name\n")  { -  int idx_acl = 3; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_acl = 3; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.match_ip_address) -        return rmap_match_set_hook.match_ip_address (vty, index, "ip address", argv[idx_acl]->arg, -                                                     RMAP_EVENT_FILTER_ADDED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.match_ip_address) +		return rmap_match_set_hook.match_ip_address( +			vty, index, "ip address", argv[idx_acl]->arg, +			RMAP_EVENT_FILTER_ADDED); +	return CMD_SUCCESS;  } @@ -2047,18 +1849,19 @@ DEFUN (no_match_ip_address,         "IP access-list number (expanded range)\n"         "IP Access-list name\n")  { -  int idx_word = 4; -  VTY_DECLVAR_CONTEXT (route_map_index, index); - -  if (rmap_match_set_hook.no_match_ip_address) -    { -      if (argc <= idx_word) -        return rmap_match_set_hook.no_match_ip_address (vty, index, "ip address", NULL, -                                                        RMAP_EVENT_FILTER_DELETED); -      return rmap_match_set_hook.no_match_ip_address (vty, index, "ip address", argv[idx_word]->arg, -                                                      RMAP_EVENT_FILTER_DELETED); -    } -  return CMD_SUCCESS; +	int idx_word = 4; +	VTY_DECLVAR_CONTEXT(route_map_index, index); + +	if (rmap_match_set_hook.no_match_ip_address) { +		if (argc <= idx_word) +			return rmap_match_set_hook.no_match_ip_address( +				vty, index, "ip address", NULL, +				RMAP_EVENT_FILTER_DELETED); +		return rmap_match_set_hook.no_match_ip_address( +			vty, index, "ip address", argv[idx_word]->arg, +			RMAP_EVENT_FILTER_DELETED); +	} +	return CMD_SUCCESS;  } @@ -2071,13 +1874,14 @@ DEFUN (match_ip_address_prefix_list,         "Match entries of prefix-lists\n"         "IP prefix-list name\n")  { -  int idx_word = 4; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_word = 4; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.match_ip_address_prefix_list) -    return rmap_match_set_hook.match_ip_address_prefix_list (vty, index, "ip address prefix-list", -                                                             argv[idx_word]->arg, RMAP_EVENT_PLIST_ADDED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.match_ip_address_prefix_list) +		return rmap_match_set_hook.match_ip_address_prefix_list( +			vty, index, "ip address prefix-list", +			argv[idx_word]->arg, RMAP_EVENT_PLIST_ADDED); +	return CMD_SUCCESS;  } @@ -2091,18 +1895,20 @@ DEFUN (no_match_ip_address_prefix_list,         "Match entries of prefix-lists\n"         "IP prefix-list name\n")  { -  int idx_word = 5; -  VTY_DECLVAR_CONTEXT (route_map_index, index); - -  if (rmap_match_set_hook.no_match_ip_address_prefix_list) -    { -      if (argc <= idx_word) -        return rmap_match_set_hook.no_match_ip_address_prefix_list (vty, index, "ip address prefix-list", -                                                                    NULL, RMAP_EVENT_PLIST_DELETED); -      return rmap_match_set_hook.no_match_ip_address_prefix_list(vty, index, "ip address prefix-list", -                                                                 argv[idx_word]->arg, RMAP_EVENT_PLIST_DELETED); -    } -  return CMD_SUCCESS; +	int idx_word = 5; +	VTY_DECLVAR_CONTEXT(route_map_index, index); + +	if (rmap_match_set_hook.no_match_ip_address_prefix_list) { +		if (argc <= idx_word) +			return rmap_match_set_hook +				.no_match_ip_address_prefix_list( +					vty, index, "ip address prefix-list", +					NULL, RMAP_EVENT_PLIST_DELETED); +		return rmap_match_set_hook.no_match_ip_address_prefix_list( +			vty, index, "ip address prefix-list", +			argv[idx_word]->arg, RMAP_EVENT_PLIST_DELETED); +	} +	return CMD_SUCCESS;  } @@ -2116,13 +1922,14 @@ DEFUN (match_ip_next_hop,         "IP access-list number (expanded range)\n"         "IP Access-list name\n")  { -  int idx_acl = 3; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_acl = 3; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.match_ip_next_hop) -    return rmap_match_set_hook.match_ip_next_hop (vty, index, "ip next-hop", argv[idx_acl]->arg, -                                                  RMAP_EVENT_FILTER_ADDED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.match_ip_next_hop) +		return rmap_match_set_hook.match_ip_next_hop( +			vty, index, "ip next-hop", argv[idx_acl]->arg, +			RMAP_EVENT_FILTER_ADDED); +	return CMD_SUCCESS;  } @@ -2137,18 +1944,19 @@ DEFUN (no_match_ip_next_hop,         "IP access-list number (expanded range)\n"         "IP Access-list name\n")  { -  int idx_word = 4;  -  VTY_DECLVAR_CONTEXT (route_map_index, index); - -  if (rmap_match_set_hook.no_match_ip_next_hop) -    { -      if (argc <= idx_word) -        return rmap_match_set_hook.no_match_ip_next_hop (vty, index, "ip next-hop", NULL, -                                                        RMAP_EVENT_FILTER_DELETED); -      return rmap_match_set_hook.no_match_ip_next_hop (vty, index, "ip next-hop", argv[idx_word]->arg, -                                                      RMAP_EVENT_FILTER_DELETED); -    } -  return CMD_SUCCESS; +	int idx_word = 4; +	VTY_DECLVAR_CONTEXT(route_map_index, index); + +	if (rmap_match_set_hook.no_match_ip_next_hop) { +		if (argc <= idx_word) +			return rmap_match_set_hook.no_match_ip_next_hop( +				vty, index, "ip next-hop", NULL, +				RMAP_EVENT_FILTER_DELETED); +		return rmap_match_set_hook.no_match_ip_next_hop( +			vty, index, "ip next-hop", argv[idx_word]->arg, +			RMAP_EVENT_FILTER_DELETED); +	} +	return CMD_SUCCESS;  } @@ -2161,13 +1969,14 @@ DEFUN (match_ip_next_hop_prefix_list,         "Match entries of prefix-lists\n"         "IP prefix-list name\n")  { -  int idx_word = 4; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_word = 4; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.match_ip_next_hop_prefix_list) -    return rmap_match_set_hook.match_ip_next_hop_prefix_list (vty, index, "ip next-hop prefix-list", -                                                             argv[idx_word]->arg, RMAP_EVENT_PLIST_ADDED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.match_ip_next_hop_prefix_list) +		return rmap_match_set_hook.match_ip_next_hop_prefix_list( +			vty, index, "ip next-hop prefix-list", +			argv[idx_word]->arg, RMAP_EVENT_PLIST_ADDED); +	return CMD_SUCCESS;  }  DEFUN (no_match_ip_next_hop_prefix_list, @@ -2180,18 +1989,19 @@ DEFUN (no_match_ip_next_hop_prefix_list,         "Match entries of prefix-lists\n"         "IP prefix-list name\n")  { -  int idx_word = 5; -  VTY_DECLVAR_CONTEXT (route_map_index, index); - -  if (rmap_match_set_hook.no_match_ip_next_hop) -    { -      if (argc <= idx_word) -        return rmap_match_set_hook.no_match_ip_next_hop (vty, index, "ip next-hop prefix-list", -                                                        NULL, RMAP_EVENT_PLIST_DELETED); -      return rmap_match_set_hook.no_match_ip_next_hop (vty, index, "ip next-hop prefix-list", -                                                      argv[idx_word]->arg, RMAP_EVENT_PLIST_DELETED); -    } -  return CMD_SUCCESS; +	int idx_word = 5; +	VTY_DECLVAR_CONTEXT(route_map_index, index); + +	if (rmap_match_set_hook.no_match_ip_next_hop) { +		if (argc <= idx_word) +			return rmap_match_set_hook.no_match_ip_next_hop( +				vty, index, "ip next-hop prefix-list", NULL, +				RMAP_EVENT_PLIST_DELETED); +		return rmap_match_set_hook.no_match_ip_next_hop( +			vty, index, "ip next-hop prefix-list", +			argv[idx_word]->arg, RMAP_EVENT_PLIST_DELETED); +	} +	return CMD_SUCCESS;  } @@ -2203,13 +2013,14 @@ DEFUN (match_ipv6_address,         "Match IPv6 address of route\n"         "IPv6 access-list name\n")  { -  int idx_word = 3; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_word = 3; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.match_ipv6_address) -    return rmap_match_set_hook.match_ipv6_address (vty, index, "ipv6 address", argv[idx_word]->arg, -                                                   RMAP_EVENT_FILTER_ADDED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.match_ipv6_address) +		return rmap_match_set_hook.match_ipv6_address( +			vty, index, "ipv6 address", argv[idx_word]->arg, +			RMAP_EVENT_FILTER_ADDED); +	return CMD_SUCCESS;  }  DEFUN (no_match_ipv6_address, @@ -2221,13 +2032,14 @@ DEFUN (no_match_ipv6_address,         "Match IPv6 address of route\n"         "IPv6 access-list name\n")  { -  int idx_word = 4; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_word = 4; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.no_match_ipv6_address) -    return rmap_match_set_hook.no_match_ipv6_address (vty, index, "ipv6 address", argv[idx_word]->arg, -                                                      RMAP_EVENT_FILTER_DELETED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.no_match_ipv6_address) +		return rmap_match_set_hook.no_match_ipv6_address( +			vty, index, "ipv6 address", argv[idx_word]->arg, +			RMAP_EVENT_FILTER_DELETED); +	return CMD_SUCCESS;  } @@ -2240,13 +2052,14 @@ DEFUN (match_ipv6_address_prefix_list,         "Match entries of prefix-lists\n"         "IP prefix-list name\n")  { -  int idx_word = 4; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_word = 4; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.match_ipv6_address_prefix_list) -    return rmap_match_set_hook.match_ipv6_address_prefix_list (vty, index, "ipv6 address prefix-list", -                                                               argv[idx_word]->arg, RMAP_EVENT_PLIST_ADDED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.match_ipv6_address_prefix_list) +		return rmap_match_set_hook.match_ipv6_address_prefix_list( +			vty, index, "ipv6 address prefix-list", +			argv[idx_word]->arg, RMAP_EVENT_PLIST_ADDED); +	return CMD_SUCCESS;  }  DEFUN (no_match_ipv6_address_prefix_list, @@ -2259,13 +2072,14 @@ DEFUN (no_match_ipv6_address_prefix_list,         "Match entries of prefix-lists\n"         "IP prefix-list name\n")  { -  int idx_word = 5; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_word = 5; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.no_match_ipv6_address_prefix_list) -    return rmap_match_set_hook.no_match_ipv6_address_prefix_list(vty, index, "ipv6 address prefix-list", -                                                                 argv[idx_word]->arg, RMAP_EVENT_PLIST_DELETED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.no_match_ipv6_address_prefix_list) +		return rmap_match_set_hook.no_match_ipv6_address_prefix_list( +			vty, index, "ipv6 address prefix-list", +			argv[idx_word]->arg, RMAP_EVENT_PLIST_DELETED); +	return CMD_SUCCESS;  } @@ -2276,13 +2090,14 @@ DEFUN (match_metric,         "Match metric of route\n"         "Metric value\n")  { -  int idx_number = 2; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_number = 2; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.match_metric) -    return rmap_match_set_hook.match_metric(vty, index, "metric", argv[idx_number]->arg, -                                            RMAP_EVENT_MATCH_ADDED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.match_metric) +		return rmap_match_set_hook.match_metric(vty, index, "metric", +							argv[idx_number]->arg, +							RMAP_EVENT_MATCH_ADDED); +	return CMD_SUCCESS;  } @@ -2294,19 +2109,19 @@ DEFUN (no_match_metric,         "Match metric of route\n"         "Metric value\n")  { -  int idx_number = 3; -  VTY_DECLVAR_CONTEXT (route_map_index, index); - -  if (rmap_match_set_hook.no_match_metric) -    { -      if (argc <= idx_number) -        return rmap_match_set_hook.no_match_metric (vty, index, "metric", -                                                    NULL, RMAP_EVENT_MATCH_DELETED); -      return rmap_match_set_hook.no_match_metric(vty, index, "metric", -                                                 argv[idx_number]->arg, -                                                 RMAP_EVENT_MATCH_DELETED); -    } -  return CMD_SUCCESS; +	int idx_number = 3; +	VTY_DECLVAR_CONTEXT(route_map_index, index); + +	if (rmap_match_set_hook.no_match_metric) { +		if (argc <= idx_number) +			return rmap_match_set_hook.no_match_metric( +				vty, index, "metric", NULL, +				RMAP_EVENT_MATCH_DELETED); +		return rmap_match_set_hook.no_match_metric( +			vty, index, "metric", argv[idx_number]->arg, +			RMAP_EVENT_MATCH_DELETED); +	} +	return CMD_SUCCESS;  } @@ -2317,13 +2132,14 @@ DEFUN (match_tag,         "Match tag of route\n"         "Tag value\n")  { -  int idx_number = 2; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_number = 2; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.match_tag) -    return rmap_match_set_hook.match_tag(vty, index, "tag", argv[idx_number]->arg, -                                         RMAP_EVENT_MATCH_ADDED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.match_tag) +		return rmap_match_set_hook.match_tag(vty, index, "tag", +						     argv[idx_number]->arg, +						     RMAP_EVENT_MATCH_ADDED); +	return CMD_SUCCESS;  } @@ -2335,16 +2151,17 @@ DEFUN (no_match_tag,         "Match tag of route\n"         "Tag value\n")  { -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  int idx = 0; -  char *arg = argv_find (argv, argc, "(1-4294967295)", &idx) ? -              argv[idx]->arg : NULL; +	int idx = 0; +	char *arg = argv_find(argv, argc, "(1-4294967295)", &idx) +			    ? argv[idx]->arg +			    : NULL; -  if (rmap_match_set_hook.no_match_tag) -    return rmap_match_set_hook.no_match_tag (vty, index, "tag", arg, -                                             RMAP_EVENT_MATCH_DELETED); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.no_match_tag) +		return rmap_match_set_hook.no_match_tag( +			vty, index, "tag", arg, RMAP_EVENT_MATCH_DELETED); +	return CMD_SUCCESS;  } @@ -2356,28 +2173,29 @@ DEFUN (set_ip_nexthop,         "Next hop address\n"         "IP address of next hop\n")  { -  int idx_ipv4 = 3; -  union sockunion su; -  int ret; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_ipv4 = 3; +	union sockunion su; +	int ret; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  ret = str2sockunion (argv[idx_ipv4]->arg, &su); -  if (ret < 0) -    { -      vty_out (vty, "%% Malformed nexthop address%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  if (su.sin.sin_addr.s_addr == 0 || -      IPV4_CLASS_DE(su.sin.sin_addr.s_addr)) -    { -      vty_out (vty, "%% nexthop address cannot be 0.0.0.0, multicast " -               "or reserved%s", VTY_NEWLINE); -      return CMD_WARNING; -    } +	ret = str2sockunion(argv[idx_ipv4]->arg, &su); +	if (ret < 0) { +		vty_out(vty, "%% Malformed nexthop address%s", VTY_NEWLINE); +		return CMD_WARNING; +	} +	if (su.sin.sin_addr.s_addr == 0 +	    || IPV4_CLASS_DE(su.sin.sin_addr.s_addr)) { +		vty_out(vty, +			"%% nexthop address cannot be 0.0.0.0, multicast " +			"or reserved%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  if (rmap_match_set_hook.set_ip_nexthop) -    return rmap_match_set_hook.set_ip_nexthop(vty, index, "ip next-hop", argv[idx_ipv4]->arg); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.set_ip_nexthop) +		return rmap_match_set_hook.set_ip_nexthop( +			vty, index, "ip next-hop", argv[idx_ipv4]->arg); +	return CMD_SUCCESS;  } @@ -2391,16 +2209,17 @@ DEFUN (no_set_ip_nexthop,         "Use peer address (for BGP only)\n"         "IP address of next hop\n")  { -  int idx_peer = 4; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_peer = 4; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.no_set_ip_nexthop) -    { -      if (argc <= idx_peer) -        return rmap_match_set_hook.no_set_ip_nexthop (vty, index, "ip next-hop", NULL); -      return rmap_match_set_hook.no_set_ip_nexthop (vty, index, "ip next-hop", argv[idx_peer]->arg); -    } -  return CMD_SUCCESS; +	if (rmap_match_set_hook.no_set_ip_nexthop) { +		if (argc <= idx_peer) +			return rmap_match_set_hook.no_set_ip_nexthop( +				vty, index, "ip next-hop", NULL); +		return rmap_match_set_hook.no_set_ip_nexthop( +			vty, index, "ip next-hop", argv[idx_peer]->arg); +	} +	return CMD_SUCCESS;  } @@ -2413,26 +2232,26 @@ DEFUN (set_ipv6_nexthop_local,         "IPv6 local address\n"         "IPv6 address of next hop\n")  { -  int idx_ipv6 = 4; -  struct in6_addr addr; -  int ret; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_ipv6 = 4; +	struct in6_addr addr; +	int ret; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  ret = inet_pton (AF_INET6, argv[idx_ipv6]->arg, &addr); -  if (!ret) -    { -      vty_out (vty, "%% Malformed nexthop address%s", VTY_NEWLINE); -      return CMD_WARNING; -    } -  if (!IN6_IS_ADDR_LINKLOCAL(&addr)) -    { -      vty_out (vty, "%% Invalid link-local nexthop address%s", VTY_NEWLINE); -      return CMD_WARNING; -    } +	ret = inet_pton(AF_INET6, argv[idx_ipv6]->arg, &addr); +	if (!ret) { +		vty_out(vty, "%% Malformed nexthop address%s", VTY_NEWLINE); +		return CMD_WARNING; +	} +	if (!IN6_IS_ADDR_LINKLOCAL(&addr)) { +		vty_out(vty, "%% Invalid link-local nexthop address%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  if (rmap_match_set_hook.set_ipv6_nexthop_local) -    return rmap_match_set_hook.set_ipv6_nexthop_local (vty, index, "ipv6 next-hop local", argv[idx_ipv6]->arg); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.set_ipv6_nexthop_local) +		return rmap_match_set_hook.set_ipv6_nexthop_local( +			vty, index, "ipv6 next-hop local", argv[idx_ipv6]->arg); +	return CMD_SUCCESS;  } @@ -2446,16 +2265,17 @@ DEFUN (no_set_ipv6_nexthop_local,         "IPv6 local address\n"         "IPv6 address of next hop\n")  { -  int idx_ipv6 = 5; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_ipv6 = 5; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.no_set_ipv6_nexthop_local) -    { -      if (argc <= idx_ipv6) -        return rmap_match_set_hook.no_set_ipv6_nexthop_local (vty, index, "ipv6 next-hop local", NULL); -      return rmap_match_set_hook.no_set_ipv6_nexthop_local (vty, index, "ipv6 next-hop local", argv[5]->arg); -    } -  return CMD_SUCCESS; +	if (rmap_match_set_hook.no_set_ipv6_nexthop_local) { +		if (argc <= idx_ipv6) +			return rmap_match_set_hook.no_set_ipv6_nexthop_local( +				vty, index, "ipv6 next-hop local", NULL); +		return rmap_match_set_hook.no_set_ipv6_nexthop_local( +			vty, index, "ipv6 next-hop local", argv[5]->arg); +	} +	return CMD_SUCCESS;  }  DEFUN (set_metric, @@ -2470,12 +2290,13 @@ DEFUN (set_metric,         "Add metric\n"         "Subtract metric\n")  { -  int idx_number = 2; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_number = 2; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.set_metric) -    return rmap_match_set_hook.set_metric (vty, index, "metric", argv[idx_number]->arg); -  return CMD_SUCCESS; +	if (rmap_match_set_hook.set_metric) +		return rmap_match_set_hook.set_metric(vty, index, "metric", +						      argv[idx_number]->arg); +	return CMD_SUCCESS;  } @@ -2487,16 +2308,17 @@ DEFUN (no_set_metric,         "Metric value for destination routing protocol\n"         "Metric value\n")  { -  int idx_number = 3; -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	int idx_number = 3; +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  if (rmap_match_set_hook.no_set_metric) -    { -      if (argc <= idx_number) -        return rmap_match_set_hook.no_set_metric (vty, index, "metric", NULL); -      return rmap_match_set_hook.no_set_metric (vty, index, "metric", argv[idx_number]->arg); -    } -  return CMD_SUCCESS; +	if (rmap_match_set_hook.no_set_metric) { +		if (argc <= idx_number) +			return rmap_match_set_hook.no_set_metric( +				vty, index, "metric", NULL); +		return rmap_match_set_hook.no_set_metric(vty, index, "metric", +							 argv[idx_number]->arg); +	} +	return CMD_SUCCESS;  } @@ -2507,12 +2329,13 @@ DEFUN (set_tag,         "Tag value for routing protocol\n"         "Tag value\n")  { -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  int idx_number = 2; -  if (rmap_match_set_hook.set_tag) -    return rmap_match_set_hook.set_tag (vty, index, "tag", argv[idx_number]->arg); -  return CMD_SUCCESS; +	int idx_number = 2; +	if (rmap_match_set_hook.set_tag) +		return rmap_match_set_hook.set_tag(vty, index, "tag", +						   argv[idx_number]->arg); +	return CMD_SUCCESS;  } @@ -2524,20 +2347,20 @@ DEFUN (no_set_tag,         "Tag value for routing protocol\n"         "Tag value\n")  { -  VTY_DECLVAR_CONTEXT (route_map_index, index); +	VTY_DECLVAR_CONTEXT(route_map_index, index); -  int idx_number = 3; -  if (rmap_match_set_hook.no_set_tag) -    { -      if (argc <= idx_number) -        return rmap_match_set_hook.no_set_tag (vty, index, "tag", NULL); -      return rmap_match_set_hook.no_set_tag (vty, index, "tag", argv[idx_number]->arg); -    } -  return CMD_SUCCESS; +	int idx_number = 3; +	if (rmap_match_set_hook.no_set_tag) { +		if (argc <= idx_number) +			return rmap_match_set_hook.no_set_tag(vty, index, "tag", +							      NULL); +		return rmap_match_set_hook.no_set_tag(vty, index, "tag", +						      argv[idx_number]->arg); +	} +	return CMD_SUCCESS;  } -  DEFUN_NOSH (route_map,         route_map_cmd,         "route-map WORD <deny|permit> (1-65535)", @@ -2547,22 +2370,23 @@ DEFUN_NOSH (route_map,         "Route map permits set operations\n"         "Sequence to insert to/delete from existing route-map entry\n")  { -  int idx_word = 1; -  int idx_permit_deny = 2; -  int idx_number = 3; -  struct route_map *map; -  struct route_map_index *index; -  char *endptr = NULL; -  int permit = argv[idx_permit_deny]->arg[0] == 'p' ? RMAP_PERMIT : RMAP_DENY; -  unsigned long pref = strtoul (argv[idx_number]->arg, &endptr, 10); -  const char *mapname = argv[idx_word]->arg; +	int idx_word = 1; +	int idx_permit_deny = 2; +	int idx_number = 3; +	struct route_map *map; +	struct route_map_index *index; +	char *endptr = NULL; +	int permit = +		argv[idx_permit_deny]->arg[0] == 'p' ? RMAP_PERMIT : RMAP_DENY; +	unsigned long pref = strtoul(argv[idx_number]->arg, &endptr, 10); +	const char *mapname = argv[idx_word]->arg; -  /* Get route map. */ -  map = route_map_get (mapname); -  index = route_map_index_get (map, permit, pref); +	/* Get route map. */ +	map = route_map_get(mapname); +	index = route_map_index_get(map, permit, pref); -  VTY_PUSH_CONTEXT (RMAP_NODE, index); -  return CMD_SUCCESS; +	VTY_PUSH_CONTEXT(RMAP_NODE, index); +	return CMD_SUCCESS;  }  DEFUN (no_route_map_all, @@ -2572,20 +2396,20 @@ DEFUN (no_route_map_all,         "Create route-map or enter route-map command mode\n"         "Route map tag\n")  { -  int idx_word = 2; -  const char *mapname = argv[idx_word]->arg; -  struct route_map *map; +	int idx_word = 2; +	const char *mapname = argv[idx_word]->arg; +	struct route_map *map; -  map = route_map_lookup_by_name (mapname); -  if (map == NULL) -    { -      vty_out (vty, "%% Could not find route-map %s%s", mapname, VTY_NEWLINE); -      return CMD_WARNING; -    } +	map = route_map_lookup_by_name(mapname); +	if (map == NULL) { +		vty_out(vty, "%% Could not find route-map %s%s", mapname, +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  route_map_delete (map); +	route_map_delete(map); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_route_map, @@ -2598,42 +2422,42 @@ DEFUN (no_route_map,         "Route map permits set operations\n"         "Sequence to insert to/delete from existing route-map entry\n")  { -  int idx_word = 2; -  int idx_permit_deny = 3; -  int idx_number = 4; -  struct route_map *map; -  struct route_map_index *index; -  char *endptr = NULL; -  int permit = argv[idx_permit_deny]->arg[0] == 'p' ? RMAP_PERMIT : RMAP_DENY; -  const char *prefstr = argv[idx_number]->arg; -  const char *mapname = argv[idx_word]->arg; -  unsigned long pref = strtoul (prefstr, &endptr, 10); - -  /* Existence check. */ -  map = route_map_lookup_by_name (mapname); -  if (map == NULL) -    { -      vty_out (vty, "%% Could not find route-map %s%s", mapname, VTY_NEWLINE); -      return CMD_WARNING; -    } - -  /* Lookup route map index. */ -  index = route_map_index_lookup (map, permit, pref); -  if (index == NULL) -    { -      vty_out (vty, "%% Could not find route-map entry %s %s%s",  -	       mapname, prefstr, VTY_NEWLINE); -      return CMD_WARNING; -    } - -  /* Delete index from route map. */ -  route_map_index_delete (index, 1); - -  /* If this route rule is the last one, delete route map itself. */ -  if (route_map_empty (map)) -    route_map_delete (map); - -  return CMD_SUCCESS; +	int idx_word = 2; +	int idx_permit_deny = 3; +	int idx_number = 4; +	struct route_map *map; +	struct route_map_index *index; +	char *endptr = NULL; +	int permit = +		argv[idx_permit_deny]->arg[0] == 'p' ? RMAP_PERMIT : RMAP_DENY; +	const char *prefstr = argv[idx_number]->arg; +	const char *mapname = argv[idx_word]->arg; +	unsigned long pref = strtoul(prefstr, &endptr, 10); + +	/* Existence check. */ +	map = route_map_lookup_by_name(mapname); +	if (map == NULL) { +		vty_out(vty, "%% Could not find route-map %s%s", mapname, +			VTY_NEWLINE); +		return CMD_WARNING; +	} + +	/* Lookup route map index. */ +	index = route_map_index_lookup(map, permit, pref); +	if (index == NULL) { +		vty_out(vty, "%% Could not find route-map entry %s %s%s", +			mapname, prefstr, VTY_NEWLINE); +		return CMD_WARNING; +	} + +	/* Delete index from route map. */ +	route_map_index_delete(index, 1); + +	/* If this route rule is the last one, delete route map itself. */ +	if (route_map_empty(map)) +		route_map_delete(map); + +	return CMD_SUCCESS;  }  DEFUN (rmap_onmatch_next, @@ -2642,20 +2466,20 @@ DEFUN (rmap_onmatch_next,         "Exit policy on matches\n"         "Next clause\n")  { -  struct route_map_index *index = VTY_GET_CONTEXT (route_map_index); - -  if (index) -    { -      if (index->type == RMAP_DENY) -        { -	  /* Under a deny clause, match means it's finished. No need to set next */ -	  vty_out (vty, "on-match next not supported under route-map deny%s", -		   VTY_NEWLINE); -	  return CMD_WARNING; -        } -      index->exitpolicy = RMAP_NEXT; -    } -  return CMD_SUCCESS; +	struct route_map_index *index = VTY_GET_CONTEXT(route_map_index); + +	if (index) { +		if (index->type == RMAP_DENY) { +			/* Under a deny clause, match means it's finished. No +			 * need to set next */ +			vty_out(vty, +				"on-match next not supported under route-map deny%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} +		index->exitpolicy = RMAP_NEXT; +	} +	return CMD_SUCCESS;  }  DEFUN (no_rmap_onmatch_next, @@ -2665,12 +2489,12 @@ DEFUN (no_rmap_onmatch_next,         "Exit policy on matches\n"         "Next clause\n")  { -  struct route_map_index *index = VTY_GET_CONTEXT (route_map_index); -   -  if (index) -    index->exitpolicy = RMAP_EXIT; +	struct route_map_index *index = VTY_GET_CONTEXT(route_map_index); -  return CMD_SUCCESS; +	if (index) +		index->exitpolicy = RMAP_EXIT; + +	return CMD_SUCCESS;  }  DEFUN (rmap_onmatch_goto, @@ -2680,40 +2504,40 @@ DEFUN (rmap_onmatch_goto,         "Goto Clause number\n"         "Number\n")  { -  int idx = 0; -  char *num = argv_find (argv, argc, "(1-65535)", &idx) ? argv[idx]->arg : NULL; -   -  struct route_map_index *index = VTY_GET_CONTEXT (route_map_index); -  int d = 0; - -  if (index) -    { -      if (index->type == RMAP_DENY) -        { -	  /* Under a deny clause, match means it's finished. No need to go anywhere */ -	  vty_out (vty, "on-match goto not supported under route-map deny%s", -		   VTY_NEWLINE); -	  return CMD_WARNING; -        } - -      if (num) -        VTY_GET_INTEGER_RANGE("route-map index", d, num, 1, 65535); -      else -        d = index->pref + 1; -       -      if (d <= index->pref) -	{ -	  /* Can't allow you to do that, Dave */ -	  vty_out (vty, "can't jump backwards in route-maps%s", VTY_NEWLINE); -	  return CMD_WARNING; -	} -      else -	{ -	  index->exitpolicy = RMAP_GOTO; -	  index->nextpref = d; +	int idx = 0; +	char *num = argv_find(argv, argc, "(1-65535)", &idx) ? argv[idx]->arg +							     : NULL; + +	struct route_map_index *index = VTY_GET_CONTEXT(route_map_index); +	int d = 0; + +	if (index) { +		if (index->type == RMAP_DENY) { +			/* Under a deny clause, match means it's finished. No +			 * need to go anywhere */ +			vty_out(vty, +				"on-match goto not supported under route-map deny%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} + +		if (num) +			VTY_GET_INTEGER_RANGE("route-map index", d, num, 1, +					      65535); +		else +			d = index->pref + 1; + +		if (d <= index->pref) { +			/* Can't allow you to do that, Dave */ +			vty_out(vty, "can't jump backwards in route-maps%s", +				VTY_NEWLINE); +			return CMD_WARNING; +		} else { +			index->exitpolicy = RMAP_GOTO; +			index->nextpref = d; +		}  	} -    } -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_rmap_onmatch_goto, @@ -2723,12 +2547,12 @@ DEFUN (no_rmap_onmatch_goto,         "Exit policy on matches\n"         "Goto Clause number\n")  { -  struct route_map_index *index = VTY_GET_CONTEXT (route_map_index); +	struct route_map_index *index = VTY_GET_CONTEXT(route_map_index); + +	if (index) +		index->exitpolicy = RMAP_EXIT; -  if (index) -    index->exitpolicy = RMAP_EXIT; -   -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* Cisco/GNU Zebra compatibility aliases */ @@ -2739,7 +2563,7 @@ DEFUN (rmap_continue,         "Continue on a different entry within the route-map\n"         "Route-map entry sequence number\n")  { -  return rmap_onmatch_goto (self, vty, argc, argv); +	return rmap_onmatch_goto(self, vty, argc, argv);  }  /* ALIAS_FIXME */ @@ -2750,7 +2574,7 @@ DEFUN (no_rmap_continue,         "Continue on a different entry within the route-map\n"         "Route-map entry sequence number\n")  { -  return no_rmap_onmatch_goto (self, vty, argc, argv); +	return no_rmap_onmatch_goto(self, vty, argc, argv);  } @@ -2761,9 +2585,9 @@ DEFUN_NOSH (rmap_show_name,         "route-map information\n"         "route-map name\n")  { -  int idx_word = 2; -  const char *name = (argc == 3) ? argv[idx_word]->arg : NULL; -  return vty_show_route_map (vty, name); +	int idx_word = 2; +	const char *name = (argc == 3) ? argv[idx_word]->arg : NULL; +	return vty_show_route_map(vty, name);  }  DEFUN (rmap_call, @@ -2772,26 +2596,23 @@ DEFUN (rmap_call,         "Jump to another Route-Map after match+set\n"         "Target route-map name\n")  { -  int idx_word = 1; -  struct route_map_index *index = VTY_GET_CONTEXT (route_map_index); -  const char *rmap = argv[idx_word]->arg; +	int idx_word = 1; +	struct route_map_index *index = VTY_GET_CONTEXT(route_map_index); +	const char *rmap = argv[idx_word]->arg; -  assert(index); +	assert(index); -  if (index->nextrm) -    { -      route_map_upd8_dependency (RMAP_EVENT_CALL_DELETED, -                                 index->nextrm, -                                 index->map->name); -      XFREE (MTYPE_ROUTE_MAP_NAME, index->nextrm); -    } -  index->nextrm = XSTRDUP (MTYPE_ROUTE_MAP_NAME, rmap); +	if (index->nextrm) { +		route_map_upd8_dependency(RMAP_EVENT_CALL_DELETED, +					  index->nextrm, index->map->name); +		XFREE(MTYPE_ROUTE_MAP_NAME, index->nextrm); +	} +	index->nextrm = XSTRDUP(MTYPE_ROUTE_MAP_NAME, rmap); -  /* Execute event hook. */ -  route_map_upd8_dependency (RMAP_EVENT_CALL_ADDED, -			     index->nextrm, -			     index->map->name); -  return CMD_SUCCESS; +	/* Execute event hook. */ +	route_map_upd8_dependency(RMAP_EVENT_CALL_ADDED, index->nextrm, +				  index->map->name); +	return CMD_SUCCESS;  }  DEFUN (no_rmap_call, @@ -2800,18 +2621,16 @@ DEFUN (no_rmap_call,         NO_STR         "Jump to another Route-Map after match+set\n")  { -  struct route_map_index *index = VTY_GET_CONTEXT (route_map_index); +	struct route_map_index *index = VTY_GET_CONTEXT(route_map_index); -  if (index->nextrm) -    { -      route_map_upd8_dependency (RMAP_EVENT_CALL_DELETED, -				 index->nextrm, -				 index->map->name); -      XFREE (MTYPE_ROUTE_MAP_NAME, index->nextrm); -      index->nextrm = NULL; -    } +	if (index->nextrm) { +		route_map_upd8_dependency(RMAP_EVENT_CALL_DELETED, +					  index->nextrm, index->map->name); +		XFREE(MTYPE_ROUTE_MAP_NAME, index->nextrm); +		index->nextrm = NULL; +	} -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (rmap_description, @@ -2820,16 +2639,15 @@ DEFUN (rmap_description,         "Route-map comment\n"         "Comment describing this route-map rule\n")  { -  int idx_line = 1; -  struct route_map_index *index = VTY_GET_CONTEXT (route_map_index); +	int idx_line = 1; +	struct route_map_index *index = VTY_GET_CONTEXT(route_map_index); -  if (index) -    { -      if (index->description) -	XFREE (MTYPE_TMP, index->description); -      index->description = argv_concat (argv, argc, idx_line); -    } -  return CMD_SUCCESS; +	if (index) { +		if (index->description) +			XFREE(MTYPE_TMP, index->description); +		index->description = argv_concat(argv, argc, idx_line); +	} +	return CMD_SUCCESS;  }  DEFUN (no_rmap_description, @@ -2838,209 +2656,199 @@ DEFUN (no_rmap_description,         NO_STR         "Route-map comment\n")  { -  struct route_map_index *index = VTY_GET_CONTEXT (route_map_index); +	struct route_map_index *index = VTY_GET_CONTEXT(route_map_index); -  if (index) -    { -      if (index->description) -	XFREE (MTYPE_TMP, index->description); -      index->description = NULL; -    } -  return CMD_SUCCESS; +	if (index) { +		if (index->description) +			XFREE(MTYPE_TMP, index->description); +		index->description = NULL; +	} +	return CMD_SUCCESS;  }  /* Configuration write function. */ -static int -route_map_config_write (struct vty *vty) -{ -  struct route_map *map; -  struct route_map_index *index; -  struct route_map_rule *rule; -  int first = 1; -  int write = 0; - -  for (map = route_map_master.head; map; map = map->next) -    for (index = map->head; index; index = index->next) -      { -	if (!first) -	  vty_out (vty, "!%s", VTY_NEWLINE); -	else -	  first = 0; - -	vty_out (vty, "route-map %s %s %d%s",  -		 map->name, -		 route_map_type_str (index->type), -		 index->pref, VTY_NEWLINE); - -	if (index->description) -	  vty_out (vty, " description %s%s", index->description, VTY_NEWLINE); - -	for (rule = index->match_list.head; rule; rule = rule->next) -	  vty_out (vty, " match %s %s%s", rule->cmd->str,  -		   rule->rule_str ? rule->rule_str : "", -		   VTY_NEWLINE); - -	for (rule = index->set_list.head; rule; rule = rule->next) -	  vty_out (vty, " set %s %s%s", rule->cmd->str, -		   rule->rule_str ? rule->rule_str : "", -		   VTY_NEWLINE); -   if (index->nextrm) -     vty_out (vty, " call %s%s", index->nextrm, VTY_NEWLINE); -	if (index->exitpolicy == RMAP_GOTO) -      vty_out (vty, " on-match goto %d%s", index->nextpref, VTY_NEWLINE); -	if (index->exitpolicy == RMAP_NEXT) -	  vty_out (vty," on-match next%s", VTY_NEWLINE); -	 -	write++; -      } -  return write; +static int route_map_config_write(struct vty *vty) +{ +	struct route_map *map; +	struct route_map_index *index; +	struct route_map_rule *rule; +	int first = 1; +	int write = 0; + +	for (map = route_map_master.head; map; map = map->next) +		for (index = map->head; index; index = index->next) { +			if (!first) +				vty_out(vty, "!%s", VTY_NEWLINE); +			else +				first = 0; + +			vty_out(vty, "route-map %s %s %d%s", map->name, +				route_map_type_str(index->type), index->pref, +				VTY_NEWLINE); + +			if (index->description) +				vty_out(vty, " description %s%s", +					index->description, VTY_NEWLINE); + +			for (rule = index->match_list.head; rule; +			     rule = rule->next) +				vty_out(vty, " match %s %s%s", rule->cmd->str, +					rule->rule_str ? rule->rule_str : "", +					VTY_NEWLINE); + +			for (rule = index->set_list.head; rule; +			     rule = rule->next) +				vty_out(vty, " set %s %s%s", rule->cmd->str, +					rule->rule_str ? rule->rule_str : "", +					VTY_NEWLINE); +			if (index->nextrm) +				vty_out(vty, " call %s%s", index->nextrm, +					VTY_NEWLINE); +			if (index->exitpolicy == RMAP_GOTO) +				vty_out(vty, " on-match goto %d%s", +					index->nextpref, VTY_NEWLINE); +			if (index->exitpolicy == RMAP_NEXT) +				vty_out(vty, " on-match next%s", VTY_NEWLINE); + +			write++; +		} +	return write;  }  /* Route map node structure. */ -static struct cmd_node rmap_node = -{ -  RMAP_NODE, -  "%s(config-route-map)# ", -  1 -}; +static struct cmd_node rmap_node = {RMAP_NODE, "%s(config-route-map)# ", 1};  /* Common route map rules */ -void * -route_map_rule_tag_compile (const char *arg) +void *route_map_rule_tag_compile(const char *arg)  { -  unsigned long int tmp; -  char *endptr; -  route_tag_t *tag; +	unsigned long int tmp; +	char *endptr; +	route_tag_t *tag; -  errno = 0; -  tmp = strtoul(arg, &endptr, 0); -  if (arg[0] == '\0' || *endptr != '\0' || errno || tmp > ROUTE_TAG_MAX) -    return NULL; +	errno = 0; +	tmp = strtoul(arg, &endptr, 0); +	if (arg[0] == '\0' || *endptr != '\0' || errno || tmp > ROUTE_TAG_MAX) +		return NULL; -  tag = XMALLOC(MTYPE_ROUTE_MAP_COMPILED, sizeof(*tag)); -  *tag = tmp; +	tag = XMALLOC(MTYPE_ROUTE_MAP_COMPILED, sizeof(*tag)); +	*tag = tmp; -  return tag; +	return tag;  } -void -route_map_rule_tag_free (void *rule) +void route_map_rule_tag_free(void *rule)  { -  XFREE (MTYPE_ROUTE_MAP_COMPILED, rule); +	XFREE(MTYPE_ROUTE_MAP_COMPILED, rule);  } -void -route_map_finish (void) +void route_map_finish(void)  { -  int i; +	int i; -  vector_free (route_match_vec); -  route_match_vec = NULL; -  vector_free (route_set_vec); -  route_set_vec = NULL; +	vector_free(route_match_vec); +	route_match_vec = NULL; +	vector_free(route_set_vec); +	route_set_vec = NULL; -  /* cleanup route_map */ -  while (route_map_master.head) -    { -      struct route_map *map = route_map_master.head; -      map->to_be_processed = 0; -      route_map_delete (map); -    } +	/* cleanup route_map */ +	while (route_map_master.head) { +		struct route_map *map = route_map_master.head; +		map->to_be_processed = 0; +		route_map_delete(map); +	} -  for (i = 1; i < ROUTE_MAP_DEP_MAX; i++) -    { -      hash_free(route_map_dep_hash[i]); -      route_map_dep_hash[i] = NULL; -    } +	for (i = 1; i < ROUTE_MAP_DEP_MAX; i++) { +		hash_free(route_map_dep_hash[i]); +		route_map_dep_hash[i] = NULL; +	} -  hash_free (route_map_master_hash); -  route_map_master_hash = NULL; +	hash_free(route_map_master_hash); +	route_map_master_hash = NULL;  }  /* Initialization of route map vector. */ -void -route_map_init (void) +void route_map_init(void)  { -  int i; +	int i; + +	/* Make vector for match and set. */ +	route_match_vec = vector_init(1); +	route_set_vec = vector_init(1); +	route_map_master_hash = +		hash_create(route_map_hash_key_make, route_map_hash_cmp); + +	for (i = 1; i < ROUTE_MAP_DEP_MAX; i++) +		route_map_dep_hash[i] = hash_create(route_map_dep_hash_make_key, +						    route_map_dep_hash_cmp); -  /* Make vector for match and set. */ -  route_match_vec = vector_init (1); -  route_set_vec = vector_init (1); -  route_map_master_hash = hash_create(route_map_hash_key_make, route_map_hash_cmp); +	/* Install route map top node. */ +	install_node(&rmap_node, route_map_config_write); -  for (i = 1; i < ROUTE_MAP_DEP_MAX; i++) -    route_map_dep_hash[i] = hash_create(route_map_dep_hash_make_key, -					route_map_dep_hash_cmp); +	/* Install route map commands. */ +	install_default(RMAP_NODE); +	install_element(CONFIG_NODE, &route_map_cmd); +	install_element(CONFIG_NODE, &no_route_map_cmd); +	install_element(CONFIG_NODE, &no_route_map_all_cmd); -  /* Install route map top node. */ -  install_node (&rmap_node, route_map_config_write); +	/* Install the on-match stuff */ +	install_element(RMAP_NODE, &route_map_cmd); +	install_element(RMAP_NODE, &rmap_onmatch_next_cmd); +	install_element(RMAP_NODE, &no_rmap_onmatch_next_cmd); +	install_element(RMAP_NODE, &rmap_onmatch_goto_cmd); +	install_element(RMAP_NODE, &no_rmap_onmatch_goto_cmd); +	install_element(RMAP_NODE, &rmap_continue_cmd); +	install_element(RMAP_NODE, &no_rmap_continue_cmd); -  /* Install route map commands. */ -  install_default (RMAP_NODE); -  install_element (CONFIG_NODE, &route_map_cmd); -  install_element (CONFIG_NODE, &no_route_map_cmd); -  install_element (CONFIG_NODE, &no_route_map_all_cmd); +	/* Install the continue stuff (ALIAS of on-match). */ -  /* Install the on-match stuff */ -  install_element (RMAP_NODE, &route_map_cmd); -  install_element (RMAP_NODE, &rmap_onmatch_next_cmd); -  install_element (RMAP_NODE, &no_rmap_onmatch_next_cmd); -  install_element (RMAP_NODE, &rmap_onmatch_goto_cmd); -  install_element (RMAP_NODE, &no_rmap_onmatch_goto_cmd); -  install_element (RMAP_NODE, &rmap_continue_cmd); -  install_element (RMAP_NODE, &no_rmap_continue_cmd); -   -  /* Install the continue stuff (ALIAS of on-match). */ -   -  /* Install the call stuff. */ -  install_element (RMAP_NODE, &rmap_call_cmd); -  install_element (RMAP_NODE, &no_rmap_call_cmd); +	/* Install the call stuff. */ +	install_element(RMAP_NODE, &rmap_call_cmd); +	install_element(RMAP_NODE, &no_rmap_call_cmd); -  /* Install description commands. */ -  install_element (RMAP_NODE, &rmap_description_cmd); -  install_element (RMAP_NODE, &no_rmap_description_cmd); -    -  /* Install show command */ -  install_element (ENABLE_NODE, &rmap_show_name_cmd); +	/* Install description commands. */ +	install_element(RMAP_NODE, &rmap_description_cmd); +	install_element(RMAP_NODE, &no_rmap_description_cmd); -  install_element (RMAP_NODE, &match_interface_cmd); -  install_element (RMAP_NODE, &no_match_interface_cmd); +	/* Install show command */ +	install_element(ENABLE_NODE, &rmap_show_name_cmd); -  install_element (RMAP_NODE, &match_ip_address_cmd); -  install_element (RMAP_NODE, &no_match_ip_address_cmd); +	install_element(RMAP_NODE, &match_interface_cmd); +	install_element(RMAP_NODE, &no_match_interface_cmd); -  install_element (RMAP_NODE, &match_ip_address_prefix_list_cmd); -  install_element (RMAP_NODE, &no_match_ip_address_prefix_list_cmd); +	install_element(RMAP_NODE, &match_ip_address_cmd); +	install_element(RMAP_NODE, &no_match_ip_address_cmd); -  install_element (RMAP_NODE, &match_ip_next_hop_cmd); -  install_element (RMAP_NODE, &no_match_ip_next_hop_cmd); +	install_element(RMAP_NODE, &match_ip_address_prefix_list_cmd); +	install_element(RMAP_NODE, &no_match_ip_address_prefix_list_cmd); -  install_element (RMAP_NODE, &match_ip_next_hop_prefix_list_cmd); -  install_element (RMAP_NODE, &no_match_ip_next_hop_prefix_list_cmd); +	install_element(RMAP_NODE, &match_ip_next_hop_cmd); +	install_element(RMAP_NODE, &no_match_ip_next_hop_cmd); -  install_element (RMAP_NODE, &match_ipv6_address_cmd); -  install_element (RMAP_NODE, &no_match_ipv6_address_cmd); +	install_element(RMAP_NODE, &match_ip_next_hop_prefix_list_cmd); +	install_element(RMAP_NODE, &no_match_ip_next_hop_prefix_list_cmd); -  install_element (RMAP_NODE, &match_ipv6_address_prefix_list_cmd); -  install_element (RMAP_NODE, &no_match_ipv6_address_prefix_list_cmd); +	install_element(RMAP_NODE, &match_ipv6_address_cmd); +	install_element(RMAP_NODE, &no_match_ipv6_address_cmd); -  install_element (RMAP_NODE, &match_metric_cmd); -  install_element (RMAP_NODE, &no_match_metric_cmd); +	install_element(RMAP_NODE, &match_ipv6_address_prefix_list_cmd); +	install_element(RMAP_NODE, &no_match_ipv6_address_prefix_list_cmd); -  install_element (RMAP_NODE, &match_tag_cmd); -  install_element (RMAP_NODE, &no_match_tag_cmd); +	install_element(RMAP_NODE, &match_metric_cmd); +	install_element(RMAP_NODE, &no_match_metric_cmd); -  install_element (RMAP_NODE, &set_ip_nexthop_cmd); -  install_element (RMAP_NODE, &no_set_ip_nexthop_cmd); +	install_element(RMAP_NODE, &match_tag_cmd); +	install_element(RMAP_NODE, &no_match_tag_cmd); -  install_element (RMAP_NODE, &set_ipv6_nexthop_local_cmd); -  install_element (RMAP_NODE, &no_set_ipv6_nexthop_local_cmd); +	install_element(RMAP_NODE, &set_ip_nexthop_cmd); +	install_element(RMAP_NODE, &no_set_ip_nexthop_cmd); -  install_element (RMAP_NODE, &set_metric_cmd); -  install_element (RMAP_NODE, &no_set_metric_cmd); +	install_element(RMAP_NODE, &set_ipv6_nexthop_local_cmd); +	install_element(RMAP_NODE, &no_set_ipv6_nexthop_local_cmd); -  install_element (RMAP_NODE, &set_tag_cmd); -  install_element (RMAP_NODE, &no_set_tag_cmd); +	install_element(RMAP_NODE, &set_metric_cmd); +	install_element(RMAP_NODE, &no_set_metric_cmd); +	install_element(RMAP_NODE, &set_tag_cmd); +	install_element(RMAP_NODE, &no_set_tag_cmd);  } diff --git a/lib/routemap.h b/lib/routemap.h index b378c64eae..b2db0927f2 100644 --- a/lib/routemap.h +++ b/lib/routemap.h @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_ROUTEMAP_H @@ -32,379 +32,312 @@ DECLARE_MTYPE(ROUTE_MAP_RULE)  DECLARE_MTYPE(ROUTE_MAP_COMPILED)  /* Route map's type. */ -enum route_map_type -{ -  RMAP_PERMIT, -  RMAP_DENY, -  RMAP_ANY -}; - -typedef enum  -{ -  RMAP_MATCH, -  RMAP_DENYMATCH, -  RMAP_NOMATCH, -  RMAP_ERROR, -  RMAP_OKAY +enum route_map_type { RMAP_PERMIT, RMAP_DENY, RMAP_ANY }; + +typedef enum { +	RMAP_MATCH, +	RMAP_DENYMATCH, +	RMAP_NOMATCH, +	RMAP_ERROR, +	RMAP_OKAY  } route_map_result_t; -typedef enum -{ -  RMAP_RIP, -  RMAP_RIPNG, -  RMAP_OSPF, -  RMAP_OSPF6, -  RMAP_BGP, -  RMAP_ZEBRA, -  RMAP_ISIS, +typedef enum { +	RMAP_RIP, +	RMAP_RIPNG, +	RMAP_OSPF, +	RMAP_OSPF6, +	RMAP_BGP, +	RMAP_ZEBRA, +	RMAP_ISIS,  } route_map_object_t; -typedef enum -{ -  RMAP_EXIT, -  RMAP_GOTO, -  RMAP_NEXT -} route_map_end_t; - -typedef enum -{ -  RMAP_EVENT_SET_ADDED, -  RMAP_EVENT_SET_DELETED, -  RMAP_EVENT_SET_REPLACED, -  RMAP_EVENT_MATCH_ADDED, -  RMAP_EVENT_MATCH_DELETED, -  RMAP_EVENT_MATCH_REPLACED, -  RMAP_EVENT_INDEX_ADDED, -  RMAP_EVENT_INDEX_DELETED, -  RMAP_EVENT_CALL_ADDED,	/* call to another routemap added */ -  RMAP_EVENT_CALL_DELETED, -  RMAP_EVENT_PLIST_ADDED, -  RMAP_EVENT_PLIST_DELETED, -  RMAP_EVENT_CLIST_ADDED, -  RMAP_EVENT_CLIST_DELETED, -  RMAP_EVENT_ECLIST_ADDED, -  RMAP_EVENT_ECLIST_DELETED, -  RMAP_EVENT_LLIST_ADDED, -  RMAP_EVENT_LLIST_DELETED, -  RMAP_EVENT_ASLIST_ADDED, -  RMAP_EVENT_ASLIST_DELETED, -  RMAP_EVENT_FILTER_ADDED, -  RMAP_EVENT_FILTER_DELETED, +typedef enum { RMAP_EXIT, RMAP_GOTO, RMAP_NEXT } route_map_end_t; + +typedef enum { +	RMAP_EVENT_SET_ADDED, +	RMAP_EVENT_SET_DELETED, +	RMAP_EVENT_SET_REPLACED, +	RMAP_EVENT_MATCH_ADDED, +	RMAP_EVENT_MATCH_DELETED, +	RMAP_EVENT_MATCH_REPLACED, +	RMAP_EVENT_INDEX_ADDED, +	RMAP_EVENT_INDEX_DELETED, +	RMAP_EVENT_CALL_ADDED, /* call to another routemap added */ +	RMAP_EVENT_CALL_DELETED, +	RMAP_EVENT_PLIST_ADDED, +	RMAP_EVENT_PLIST_DELETED, +	RMAP_EVENT_CLIST_ADDED, +	RMAP_EVENT_CLIST_DELETED, +	RMAP_EVENT_ECLIST_ADDED, +	RMAP_EVENT_ECLIST_DELETED, +	RMAP_EVENT_LLIST_ADDED, +	RMAP_EVENT_LLIST_DELETED, +	RMAP_EVENT_ASLIST_ADDED, +	RMAP_EVENT_ASLIST_DELETED, +	RMAP_EVENT_FILTER_ADDED, +	RMAP_EVENT_FILTER_DELETED,  } route_map_event_t;  /* Depth limit in RMAP recursion using RMAP_CALL. */  #define RMAP_RECURSION_LIMIT      10  /* Route map rule structure for matching and setting. */ -struct route_map_rule_cmd -{ -  /* Route map rule name (e.g. as-path, metric) */ -  const char *str; +struct route_map_rule_cmd { +	/* Route map rule name (e.g. as-path, metric) */ +	const char *str; -  /* Function for value set or match. */ -  route_map_result_t (*func_apply)(void *, struct prefix *,  -				   route_map_object_t, void *); +	/* Function for value set or match. */ +	route_map_result_t (*func_apply)(void *, struct prefix *, +					 route_map_object_t, void *); -  /* Compile argument and return result as void *. */ -  void *(*func_compile)(const char *); +	/* Compile argument and return result as void *. */ +	void *(*func_compile)(const char *); -  /* Free allocated value by func_compile (). */ -  void (*func_free)(void *); +	/* Free allocated value by func_compile (). */ +	void (*func_free)(void *);  };  /* Route map apply error. */ -enum -{ -  /* Route map rule is missing. */ -  RMAP_RULE_MISSING = 1, +enum { +	/* Route map rule is missing. */ +	RMAP_RULE_MISSING = 1, -  /* Route map rule can't compile */ -  RMAP_COMPILE_ERROR +	/* Route map rule can't compile */ +	RMAP_COMPILE_ERROR  };  /* Route map rule list. */ -struct route_map_rule_list -{ -  struct route_map_rule *head; -  struct route_map_rule *tail; +struct route_map_rule_list { +	struct route_map_rule *head; +	struct route_map_rule *tail;  };  /* Route map index structure. */ -struct route_map_index -{ -  struct route_map *map; -  char *description; +struct route_map_index { +	struct route_map *map; +	char *description; -  /* Preference of this route map rule. */ -  int pref; +	/* Preference of this route map rule. */ +	int pref; -  /* Route map type permit or deny. */ -  enum route_map_type type;			 +	/* Route map type permit or deny. */ +	enum route_map_type type; -  /* Do we follow old rules, or hop forward? */ -  route_map_end_t exitpolicy; +	/* Do we follow old rules, or hop forward? */ +	route_map_end_t exitpolicy; -  /* If we're using "GOTO", to where do we go? */ -  int nextpref; +	/* If we're using "GOTO", to where do we go? */ +	int nextpref; -  /* If we're using "CALL", to which route-map do ew go? */ -  char *nextrm; +	/* If we're using "CALL", to which route-map do ew go? */ +	char *nextrm; -  /* Matching rule list. */ -  struct route_map_rule_list match_list; -  struct route_map_rule_list set_list; +	/* Matching rule list. */ +	struct route_map_rule_list match_list; +	struct route_map_rule_list set_list; -  /* Make linked list. */ -  struct route_map_index *next; -  struct route_map_index *prev; +	/* Make linked list. */ +	struct route_map_index *next; +	struct route_map_index *prev; -  QOBJ_FIELDS +	QOBJ_FIELDS  };  DECLARE_QOBJ_TYPE(route_map_index)  /* Route map list structure. */ -struct route_map -{ -  /* Name of route map. */ -  char *name; +struct route_map { +	/* Name of route map. */ +	char *name; -  /* Route map's rule. */ -  struct route_map_index *head; -  struct route_map_index *tail; +	/* Route map's rule. */ +	struct route_map_index *head; +	struct route_map_index *tail; -  /* Make linked list. */ -  struct route_map *next; -  struct route_map *prev; +	/* Make linked list. */ +	struct route_map *next; +	struct route_map *prev; -  /* Maintain update info */ -  int to_be_processed;	 /* True if modification isn't acted on yet */ -  int deleted;		 /* If 1, then this node will be deleted */ +	/* Maintain update info */ +	int to_be_processed; /* True if modification isn't acted on yet */ +	int deleted;	 /* If 1, then this node will be deleted */ -  QOBJ_FIELDS +	QOBJ_FIELDS  };  DECLARE_QOBJ_TYPE(route_map)  /* Prototypes. */ -extern void route_map_init (void); -extern void route_map_finish (void); +extern void route_map_init(void); +extern void route_map_finish(void);  /* Add match statement to route map. */ -extern int route_map_add_match (struct route_map_index *index, -		                const char *match_name, -		                const char *match_arg); +extern int route_map_add_match(struct route_map_index *index, +			       const char *match_name, const char *match_arg);  /* Delete specified route match rule. */ -extern int route_map_delete_match (struct route_map_index *index, -			           const char *match_name, -			           const char *match_arg); +extern int route_map_delete_match(struct route_map_index *index, +				  const char *match_name, +				  const char *match_arg); -extern const char *route_map_get_match_arg (struct route_map_index *index, -					    const char *match_name); +extern const char *route_map_get_match_arg(struct route_map_index *index, +					   const char *match_name);  /* Add route-map set statement to the route map. */ -extern int route_map_add_set (struct route_map_index *index,  -		              const char *set_name, -		              const char *set_arg); +extern int route_map_add_set(struct route_map_index *index, +			     const char *set_name, const char *set_arg);  /* Delete route map set rule. */ -extern int route_map_delete_set (struct route_map_index *index, -                                 const char *set_name, -                                 const char *set_arg); +extern int route_map_delete_set(struct route_map_index *index, +				const char *set_name, const char *set_arg);  /* Install rule command to the match list. */ -extern void route_map_install_match (struct route_map_rule_cmd *cmd); +extern void route_map_install_match(struct route_map_rule_cmd *cmd);  /* Install rule command to the set list. */ -extern void route_map_install_set (struct route_map_rule_cmd *cmd); +extern void route_map_install_set(struct route_map_rule_cmd *cmd);  /* Lookup route map by name. */ -extern struct route_map * route_map_lookup_by_name (const char *name); +extern struct route_map *route_map_lookup_by_name(const char *name);  /* Apply route map to the object. */ -extern route_map_result_t route_map_apply (struct route_map *map, -                                           struct prefix *, -                                           route_map_object_t object_type, -                                           void *object); - -extern void route_map_add_hook (void (*func) (const char *)); -extern void route_map_delete_hook (void (*func) (const char *)); -extern void route_map_event_hook (void (*func) (route_map_event_t, -						const char *)); -extern int route_map_mark_updated (const char *name, int deleted); -extern int route_map_clear_updated (struct route_map *rmap); -extern void route_map_walk_update_list (int (*update_fn) (char *name)); -extern void route_map_upd8_dependency (route_map_event_t type, const char *arg, -				       const char *rmap_name); -extern void route_map_notify_dependencies (const char *affected_name, -					   route_map_event_t event); - -extern int generic_match_add (struct vty *vty, -                              struct route_map_index *index, -                              const char *command, -                              const char *arg, -                              route_map_event_t type); - -extern int generic_match_delete (struct vty *vty, -                                 struct route_map_index *index, -                                 const char *command, -                                 const char *arg, -                                 route_map_event_t type); -extern int generic_set_add (struct vty *vty, struct route_map_index *index, -                            const char *command, const char *arg); -extern int generic_set_delete (struct vty *vty, struct route_map_index *index, -                               const char *command, const char *arg); +extern route_map_result_t route_map_apply(struct route_map *map, +					  struct prefix *, +					  route_map_object_t object_type, +					  void *object); + +extern void route_map_add_hook(void (*func)(const char *)); +extern void route_map_delete_hook(void (*func)(const char *)); +extern void route_map_event_hook(void (*func)(route_map_event_t, const char *)); +extern int route_map_mark_updated(const char *name, int deleted); +extern int route_map_clear_updated(struct route_map *rmap); +extern void route_map_walk_update_list(int (*update_fn)(char *name)); +extern void route_map_upd8_dependency(route_map_event_t type, const char *arg, +				      const char *rmap_name); +extern void route_map_notify_dependencies(const char *affected_name, +					  route_map_event_t event); + +extern int generic_match_add(struct vty *vty, struct route_map_index *index, +			     const char *command, const char *arg, +			     route_map_event_t type); + +extern int generic_match_delete(struct vty *vty, struct route_map_index *index, +				const char *command, const char *arg, +				route_map_event_t type); +extern int generic_set_add(struct vty *vty, struct route_map_index *index, +			   const char *command, const char *arg); +extern int generic_set_delete(struct vty *vty, struct route_map_index *index, +			      const char *command, const char *arg);  /* match interface */ -extern void route_map_match_interface_hook (int (*func) (struct vty *vty, -                                                         struct route_map_index *index, -                                                         const char *command, -                                                         const char *arg, -                                                         route_map_event_t type)); +extern void route_map_match_interface_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* no match interface */ -extern void route_map_no_match_interface_hook (int (*func) (struct vty *vty, -                                                            struct route_map_index *index, -                                                            const char *command, -                                                            const char *arg, -                                                            route_map_event_t type)); +extern void route_map_no_match_interface_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* match ip address */ -extern void route_map_match_ip_address_hook (int (*func) (struct vty *vty, -                                                          struct route_map_index *index, -                                                          const char *command, -                                                          const char *arg, -                                                          route_map_event_t type)); +extern void route_map_match_ip_address_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* no match ip address */ -extern void route_map_no_match_ip_address_hook (int (*func) (struct vty *vty, -                                                             struct route_map_index *index, -                                                             const char *command, -                                                             const char *arg, -                                                             route_map_event_t type)); +extern void route_map_no_match_ip_address_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* match ip address prefix list */ -extern void route_map_match_ip_address_prefix_list_hook (int (*func) (struct vty *vty, -                                                                      struct route_map_index *index, -                                                                      const char *command, -                                                                      const char *arg, -                                                                      route_map_event_t type)); +extern void route_map_match_ip_address_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* no match ip address prefix list */ -extern void route_map_no_match_ip_address_prefix_list_hook (int (*func) (struct vty *vty, -                                                                         struct route_map_index *index, -                                                                         const char *command, -                                                                         const char *arg, -                                                                         route_map_event_t type)); +extern void route_map_no_match_ip_address_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* match ip next hop */ -extern void route_map_match_ip_next_hop_hook (int (*func) (struct vty *vty, -                                                           struct route_map_index *index, -                                                           const char *command, -                                                           const char *arg, -                                                           route_map_event_t type)); +extern void route_map_match_ip_next_hop_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* no match ip next hop */ -extern void route_map_no_match_ip_next_hop_hook (int (*func) (struct vty *vty, -                                                              struct route_map_index *index, -                                                              const char *command, -                                                              const char *arg, -                                                              route_map_event_t type)); +extern void route_map_no_match_ip_next_hop_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* match ip next hop prefix list */ -extern void route_map_match_ip_next_hop_prefix_list_hook (int (*func) (struct vty *vty, -                                                                       struct route_map_index *index, -                                                                       const char *command, -                                                                       const char *arg, -                                                                       route_map_event_t type)); +extern void route_map_match_ip_next_hop_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* no match ip next hop prefix list */ -extern void route_map_no_match_ip_next_hop_prefix_list_hook (int (*func) (struct vty *vty, -                                                                          struct route_map_index *index, -                                                                          const char *command, -                                                                          const char *arg, -                                                                          route_map_event_t type)); +extern void route_map_no_match_ip_next_hop_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* match ipv6 address */ -extern void route_map_match_ipv6_address_hook (int (*func) (struct vty *vty, -                                                            struct route_map_index *index, -                                                            const char *command, -                                                            const char *arg, -                                                            route_map_event_t type)); +extern void route_map_match_ipv6_address_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* no match ipv6 address */ -extern void route_map_no_match_ipv6_address_hook (int (*func) (struct vty *vty, -                                                               struct route_map_index *index, -                                                               const char *command, -                                                               const char *arg, -                                                               route_map_event_t type)); +extern void route_map_no_match_ipv6_address_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* match ipv6 address prefix list */ -extern void route_map_match_ipv6_address_prefix_list_hook (int (*func) (struct vty *vty, -                                                                        struct route_map_index *index, -                                                                        const char *command, -                                                                        const char *arg, -                                                                        route_map_event_t type)); +extern void route_map_match_ipv6_address_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* no match ipv6 address prefix list */ -extern void route_map_no_match_ipv6_address_prefix_list_hook (int (*func) (struct vty *vty, -                                                                           struct route_map_index *index, -                                                                           const char *command, -                                                                           const char *arg, -                                                                           route_map_event_t type)); +extern void route_map_no_match_ipv6_address_prefix_list_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* match metric */ -extern void route_map_match_metric_hook (int (*func) (struct vty *vty, -                                                      struct route_map_index *index, -                                                      const char *command, -                                                      const char *arg, -                                                      route_map_event_t type)); +extern void route_map_match_metric_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* no match metric */ -extern void route_map_no_match_metric_hook (int (*func) (struct vty *vty, -                                                         struct route_map_index *index, -                                                         const char *command, -                                                         const char *arg, -                                                         route_map_event_t type)); +extern void route_map_no_match_metric_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* match tag */ -extern void route_map_match_tag_hook (int (*func) (struct vty *vty, -                                                   struct route_map_index *index, -                                                   const char *command, -                                                   const char *arg, -                                                   route_map_event_t type)); +extern void route_map_match_tag_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* no match tag */ -extern void route_map_no_match_tag_hook (int (*func) (struct vty *vty, -                                                      struct route_map_index *index, -                                                      const char *command, -                                                      const char *arg, -                                                      route_map_event_t type)); +extern void route_map_no_match_tag_hook(int (*func)( +	struct vty *vty, struct route_map_index *index, const char *command, +	const char *arg, route_map_event_t type));  /* set ip nexthop */ -extern void route_map_set_ip_nexthop_hook (int (*func) (struct vty *vty, -                                                        struct route_map_index *index, -                                                        const char *command, -                                                        const char *arg)); +extern void route_map_set_ip_nexthop_hook( +	int (*func)(struct vty *vty, struct route_map_index *index, +		    const char *command, const char *arg));  /* no set ip nexthop */ -extern void route_map_no_set_ip_nexthop_hook (int (*func) (struct vty *vty, -                                                           struct route_map_index *index, -                                                           const char *command, -                                                           const char *arg)); +extern void route_map_no_set_ip_nexthop_hook( +	int (*func)(struct vty *vty, struct route_map_index *index, +		    const char *command, const char *arg));  /* set ipv6 nexthop local */ -extern void route_map_set_ipv6_nexthop_local_hook (int (*func) (struct vty *vty, -                                                                struct route_map_index *index, -                                                                const char *command, -                                                                const char *arg)); +extern void route_map_set_ipv6_nexthop_local_hook( +	int (*func)(struct vty *vty, struct route_map_index *index, +		    const char *command, const char *arg));  /* no set ipv6 nexthop local */ -extern void route_map_no_set_ipv6_nexthop_local_hook (int (*func) (struct vty *vty, -                                                                   struct route_map_index *index, -                                                                   const char *command, -                                                                   const char *arg)); +extern void route_map_no_set_ipv6_nexthop_local_hook( +	int (*func)(struct vty *vty, struct route_map_index *index, +		    const char *command, const char *arg));  /* set metric */ -extern void route_map_set_metric_hook (int (*func) (struct vty *vty, -                                                    struct route_map_index *index, -                                                    const char *command, -                                                    const char *arg)); +extern void route_map_set_metric_hook(int (*func)(struct vty *vty, +						  struct route_map_index *index, +						  const char *command, +						  const char *arg));  /* no set metric */ -extern void route_map_no_set_metric_hook (int (*func) (struct vty *vty, -                                                       struct route_map_index *index, -                                                       const char *command, -                                                       const char *arg)); +extern void route_map_no_set_metric_hook( +	int (*func)(struct vty *vty, struct route_map_index *index, +		    const char *command, const char *arg));  /* set tag */ -extern void route_map_set_tag_hook (int (*func) (struct vty *vty, -                                                 struct route_map_index *index, -                                                 const char *command, -                                                 const char *arg)); +extern void route_map_set_tag_hook(int (*func)(struct vty *vty, +					       struct route_map_index *index, +					       const char *command, +					       const char *arg));  /* no set tag */ -extern void route_map_no_set_tag_hook (int (*func) (struct vty *vty, -                                                    struct route_map_index *index, -                                                    const char *command, -                                                    const char *arg)); +extern void route_map_no_set_tag_hook(int (*func)(struct vty *vty, +						  struct route_map_index *index, +						  const char *command, +						  const char *arg)); -extern void *route_map_rule_tag_compile (const char *arg); -extern void route_map_rule_tag_free (void *rule); +extern void *route_map_rule_tag_compile(const char *arg); +extern void route_map_rule_tag_free(void *rule);  #endif /* _ZEBRA_ROUTEMAP_H */ diff --git a/lib/sigevent.c b/lib/sigevent.c index 09f07180ce..2569428e90 100644 --- a/lib/sigevent.c +++ b/lib/sigevent.c @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with Quagga; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -38,331 +38,311 @@  /* master signals descriptor struct */ -struct quagga_sigevent_master_t -{ -  struct thread *t; +struct quagga_sigevent_master_t { +	struct thread *t; + +	struct quagga_signal_t *signals; +	int sigc; -  struct quagga_signal_t *signals;  -  int sigc; -   -  volatile sig_atomic_t caught; +	volatile sig_atomic_t caught;  } sigmaster; -/* Generic signal handler  +/* Generic signal handler   * Schedules signal event thread   */ -static void -quagga_signal_handler (int signo) +static void quagga_signal_handler(int signo)  { -  int i; -  struct quagga_signal_t *sig; -   -  for (i = 0; i < sigmaster.sigc; i++) -    { -      sig = &(sigmaster.signals[i]); -       -      if (sig->signal == signo) -        sig->caught = 1; -    } -   -  sigmaster.caught = 1; -}  +	int i; +	struct quagga_signal_t *sig; + +	for (i = 0; i < sigmaster.sigc; i++) { +		sig = &(sigmaster.signals[i]); + +		if (sig->signal == signo) +			sig->caught = 1; +	} + +	sigmaster.caught = 1; +}  /* check if signals have been caught and run appropriate handlers */ -int -quagga_sigevent_process (void) +int quagga_sigevent_process(void)  { -  struct quagga_signal_t *sig; -  int i; +	struct quagga_signal_t *sig; +	int i;  #ifdef SIGEVENT_BLOCK_SIGNALS -  /* shouldnt need to block signals, but potentially may be needed */ -  sigset_t newmask, oldmask; - -  /* -   * Block most signals, but be careful not to defer SIGTRAP because -   * doing so breaks gdb, at least on NetBSD 2.0.  Avoid asking to -   * block SIGKILL, just because we shouldn't be able to do so. -   */ -  sigfillset (&newmask); -  sigdelset (&newmask, SIGTRAP); -  sigdelset (&newmask, SIGKILL); -    -  if ( (sigprocmask (SIG_BLOCK, &newmask, &oldmask)) < 0) -    { -      zlog_err ("quagga_signal_timer: couldnt block signals!"); -      return -1; -    } +	/* shouldnt need to block signals, but potentially may be needed */ +	sigset_t newmask, oldmask; + +	/* +	 * Block most signals, but be careful not to defer SIGTRAP because +	 * doing so breaks gdb, at least on NetBSD 2.0.  Avoid asking to +	 * block SIGKILL, just because we shouldn't be able to do so. +	 */ +	sigfillset(&newmask); +	sigdelset(&newmask, SIGTRAP); +	sigdelset(&newmask, SIGKILL); + +	if ((sigprocmask(SIG_BLOCK, &newmask, &oldmask)) < 0) { +		zlog_err("quagga_signal_timer: couldnt block signals!"); +		return -1; +	}  #endif /* SIGEVENT_BLOCK_SIGNALS */ -  if (sigmaster.caught > 0) -    { -      sigmaster.caught = 0; -      /* must not read or set sigmaster.caught after here, -       * race condition with per-sig caught flags if one does -       */ -       -      for (i = 0; i < sigmaster.sigc; i++) -        { -          sig = &(sigmaster.signals[i]); - -          if (sig->caught > 0) -            { -              sig->caught = 0; -              if (sig->handler) -                sig->handler (); -            } -        } -    } +	if (sigmaster.caught > 0) { +		sigmaster.caught = 0; +		/* must not read or set sigmaster.caught after here, +		 * race condition with per-sig caught flags if one does +		 */ + +		for (i = 0; i < sigmaster.sigc; i++) { +			sig = &(sigmaster.signals[i]); + +			if (sig->caught > 0) { +				sig->caught = 0; +				if (sig->handler) +					sig->handler(); +			} +		} +	}  #ifdef SIGEVENT_BLOCK_SIGNALS -  if ( sigprocmask (SIG_UNBLOCK, &oldmask, NULL) < 0 ); -    return -1; +	if (sigprocmask(SIG_UNBLOCK, &oldmask, NULL) < 0) +		; +	return -1;  #endif /* SIGEVENT_BLOCK_SIGNALS */ -  return 0; +	return 0;  }  #ifdef SIGEVENT_SCHEDULE_THREAD  /* timer thread to check signals. Shouldnt be needed */ -int -quagga_signal_timer (struct thread *t) +int quagga_signal_timer(struct thread *t)  { -  struct quagga_sigevent_master_t *sigm; -  struct quagga_signal_t *sig; -  int i; - -  sigm = THREAD_ARG (t); -  sigm->t = thread_add_timer (sigm->t->master, quagga_signal_timer, &sigmaster, -                              QUAGGA_SIGNAL_TIMER_INTERVAL); -  return quagga_sigevent_process (); +	struct quagga_sigevent_master_t *sigm; +	struct quagga_signal_t *sig; +	int i; + +	sigm = THREAD_ARG(t); +	sigm->t = thread_add_timer(sigm->t->master, quagga_signal_timer, +				   &sigmaster, QUAGGA_SIGNAL_TIMER_INTERVAL); +	return quagga_sigevent_process();  }  #endif /* SIGEVENT_SCHEDULE_THREAD */  /* Initialization of signal handles. */  /* Signal wrapper. */ -static int -signal_set (int signo) +static int signal_set(int signo)  { -  int ret; -  struct sigaction sig; -  struct sigaction osig; - -  sig.sa_handler = &quagga_signal_handler; -  sigfillset (&sig.sa_mask); -  sig.sa_flags = 0; -  if (signo == SIGALRM) { +	int ret; +	struct sigaction sig; +	struct sigaction osig; + +	sig.sa_handler = &quagga_signal_handler; +	sigfillset(&sig.sa_mask); +	sig.sa_flags = 0; +	if (signo == SIGALRM) {  #ifdef SA_INTERRUPT -      sig.sa_flags |= SA_INTERRUPT; /* SunOS */ +		sig.sa_flags |= SA_INTERRUPT; /* SunOS */  #endif -  } else { +	} else {  #ifdef SA_RESTART -      sig.sa_flags |= SA_RESTART; +		sig.sa_flags |= SA_RESTART;  #endif /* SA_RESTART */ -  } +	} -  ret = sigaction (signo, &sig, &osig); -  if (ret < 0)  -    return ret; -  else -    return 0; +	ret = sigaction(signo, &sig, &osig); +	if (ret < 0) +		return ret; +	else +		return 0;  }  #ifdef SA_SIGINFO  /* XXX This function should be enhanced to support more platforms         (it currently works only on Linux/x86). */ -static void * -program_counter(void *context) +static void *program_counter(void *context)  {  #ifdef HAVE_UCONTEXT_H  #ifdef GNU_LINUX -  /* these are from GNU libc, rather than Linux, strictly speaking */ -# if defined(REG_EIP) +/* these are from GNU libc, rather than Linux, strictly speaking */ +#if defined(REG_EIP)  #  define REG_INDEX REG_EIP -# elif defined(REG_RIP) +#elif defined(REG_RIP)  #  define REG_INDEX REG_RIP -# elif defined(__powerpc__) +#elif defined(__powerpc__)  #  define REG_INDEX 32 -# endif +#endif  #elif defined(SUNOS_5) /* !GNU_LINUX */  # define REG_INDEX REG_PC -#endif /* GNU_LINUX */ +#endif		       /* GNU_LINUX */  #ifdef REG_INDEX -# ifdef HAVE_UCONTEXT_T_UC_MCONTEXT_GREGS +#ifdef HAVE_UCONTEXT_T_UC_MCONTEXT_GREGS  #  define REGS gregs[REG_INDEX] -# elif defined(HAVE_UCONTEXT_T_UC_MCONTEXT_UC_REGS) +#elif defined(HAVE_UCONTEXT_T_UC_MCONTEXT_UC_REGS)  #  define REGS uc_regs->gregs[REG_INDEX] -# endif /* HAVE_UCONTEXT_T_UC_MCONTEXT_GREGS */ +#endif /* HAVE_UCONTEXT_T_UC_MCONTEXT_GREGS */  #endif /* REG_INDEX */  #ifdef REGS -  if (context) -    return (void *)(((ucontext_t *)context)->uc_mcontext.REGS); -#elif defined(HAVE_UCONTEXT_T_UC_MCONTEXT_REGS__NIP)  -  /* older Linux / struct pt_regs ? */ -  if (context) -    return (void *)(((ucontext_t *)context)->uc_mcontext.regs->nip); +	if (context) +		return (void *)(((ucontext_t *)context)->uc_mcontext.REGS); +#elif defined(HAVE_UCONTEXT_T_UC_MCONTEXT_REGS__NIP) +	/* older Linux / struct pt_regs ? */ +	if (context) +		return (void *)(((ucontext_t *)context)->uc_mcontext.regs->nip);  #endif /* REGS */  #endif /* HAVE_UCONTEXT_H */ -  return NULL; +	return NULL;  }  #endif /* SA_SIGINFO */ -static void __attribute__ ((noreturn)) +static void __attribute__((noreturn))  exit_handler(int signo  #ifdef SA_SIGINFO -	     , siginfo_t *siginfo, void *context +	     , +	     siginfo_t *siginfo, void *context  #endif -	    ) +	     )  { -  zlog_signal(signo, "exiting..." +	zlog_signal(signo, "exiting..."  #ifdef SA_SIGINFO -	      , siginfo, program_counter(context) +		    , +		    siginfo, program_counter(context)  #endif -	     ); -  _exit(128+signo); +			    ); +	_exit(128 + signo);  } -static void __attribute__ ((noreturn)) +static void __attribute__((noreturn))  core_handler(int signo  #ifdef SA_SIGINFO -	     , siginfo_t *siginfo, void *context +	     , +	     siginfo_t *siginfo, void *context  #endif -	    ) +	     )  { -  zlog_signal(signo, "aborting..." +	zlog_signal(signo, "aborting..."  #ifdef SA_SIGINFO -	      , siginfo, program_counter(context) +		    , +		    siginfo, program_counter(context)  #endif -	     ); -  /* dump memory stats on core */ -  log_memstats_stderr ("core_handler"); -  abort(); +			    ); +	/* dump memory stats on core */ +	log_memstats_stderr("core_handler"); +	abort();  } -static void -trap_default_signals(void) +static void trap_default_signals(void)  { -  static const int core_signals[] = { -    SIGQUIT, -    SIGILL, +	static const int core_signals[] = { +		SIGQUIT, SIGILL,  #ifdef SIGEMT -    SIGEMT, +		SIGEMT,  #endif -    SIGFPE, -    SIGBUS, -    SIGSEGV, +		SIGFPE,  SIGBUS, SIGSEGV,  #ifdef SIGSYS -    SIGSYS, +		SIGSYS,  #endif  #ifdef SIGXCPU -    SIGXCPU, +		SIGXCPU,  #endif  #ifdef SIGXFSZ -    SIGXFSZ, +		SIGXFSZ,  #endif -  }; -  static const int exit_signals[] = { -    SIGHUP, -    SIGINT, -    SIGALRM, -    SIGTERM, -    SIGUSR1, -    SIGUSR2, +	}; +	static const int exit_signals[] = { +		SIGHUP,    SIGINT, SIGALRM, SIGTERM, SIGUSR1, SIGUSR2,  #ifdef SIGPOLL -    SIGPOLL,  +		SIGPOLL,  #endif  #ifdef SIGVTALRM -    SIGVTALRM, +		SIGVTALRM,  #endif  #ifdef SIGSTKFLT -    SIGSTKFLT,  +		SIGSTKFLT,  #endif -  }; -  static const int ignore_signals[] = { -    SIGPIPE, -  }; -  static const struct { -    const int *sigs; -    u_int nsigs; -    void (*handler)(int signo +	}; +	static const int ignore_signals[] = { +		SIGPIPE, +	}; +	static const struct { +		const int *sigs; +		u_int nsigs; +		void (*handler)(int signo  #ifdef SA_SIGINFO -		    , siginfo_t *info, void *context +				, +				siginfo_t *info, void *context  #endif -		   ); -  } sigmap[] = { -    { core_signals, array_size(core_signals), core_handler}, -    { exit_signals, array_size(exit_signals), exit_handler}, -    { ignore_signals, array_size(ignore_signals), NULL}, -  }; -  u_int i; - -  for (i = 0; i < array_size(sigmap); i++) -    { -      u_int j; - -      for (j = 0; j < sigmap[i].nsigs; j++) -        { -	  struct sigaction oact; -	  if ((sigaction(sigmap[i].sigs[j],NULL,&oact) == 0) && -	      (oact.sa_handler == SIG_DFL)) -	    { -	      struct sigaction act; -	      sigfillset (&act.sa_mask); -	      if (sigmap[i].handler == NULL) -	        { -		  act.sa_handler = SIG_IGN; -		  act.sa_flags = 0; -	        } -	      else -	        { +				); +	} sigmap[] = { +		{core_signals, array_size(core_signals), core_handler}, +		{exit_signals, array_size(exit_signals), exit_handler}, +		{ignore_signals, array_size(ignore_signals), NULL}, +	}; +	u_int i; + +	for (i = 0; i < array_size(sigmap); i++) { +		u_int j; + +		for (j = 0; j < sigmap[i].nsigs; j++) { +			struct sigaction oact; +			if ((sigaction(sigmap[i].sigs[j], NULL, &oact) == 0) +			    && (oact.sa_handler == SIG_DFL)) { +				struct sigaction act; +				sigfillset(&act.sa_mask); +				if (sigmap[i].handler == NULL) { +					act.sa_handler = SIG_IGN; +					act.sa_flags = 0; +				} else {  #ifdef SA_SIGINFO -		  /* Request extra arguments to signal handler. */ -		  act.sa_sigaction = sigmap[i].handler; -		  act.sa_flags = SA_SIGINFO; +					/* Request extra arguments to signal +					 * handler. */ +					act.sa_sigaction = sigmap[i].handler; +					act.sa_flags = SA_SIGINFO;  #else -		  act.sa_handler = sigmap[i].handler; -		  act.sa_flags = 0; +					act.sa_handler = sigmap[i].handler; +					act.sa_flags = 0;  #endif -	        } -	      if (sigaction(sigmap[i].sigs[j],&act,NULL) < 0) -	        zlog_warn("Unable to set signal handler for signal %d: %s", -			  sigmap[i].sigs[j],safe_strerror(errno)); - -	    } -        } -    } +				} +				if (sigaction(sigmap[i].sigs[j], &act, NULL) +				    < 0) +					zlog_warn( +						"Unable to set signal handler for signal %d: %s", +						sigmap[i].sigs[j], +						safe_strerror(errno)); +			} +		} +	}  } -void  -signal_init (struct thread_master *m, int sigc,  -             struct quagga_signal_t signals[]) +void signal_init(struct thread_master *m, int sigc, +		 struct quagga_signal_t signals[])  { -  int i = 0; -  struct quagga_signal_t *sig; - -  /* First establish some default handlers that can be overridden by -     the application. */ -  trap_default_signals(); -   -  while (i < sigc) -    { -      sig = &signals[i]; -      if ( signal_set (sig->signal) < 0 ) -        exit (-1); -      i++; -    } - -  sigmaster.sigc = sigc; -  sigmaster.signals = signals; - -#ifdef SIGEVENT_SCHEDULE_THREAD   -  sigmaster.t =  -    thread_add_timer (m, quagga_signal_timer, &sigmaster,  -                      QUAGGA_SIGNAL_TIMER_INTERVAL); +	int i = 0; +	struct quagga_signal_t *sig; + +	/* First establish some default handlers that can be overridden by +	   the application. */ +	trap_default_signals(); + +	while (i < sigc) { +		sig = &signals[i]; +		if (signal_set(sig->signal) < 0) +			exit(-1); +		i++; +	} + +	sigmaster.sigc = sigc; +	sigmaster.signals = signals; + +#ifdef SIGEVENT_SCHEDULE_THREAD +	sigmaster.t = thread_add_timer(m, quagga_signal_timer, &sigmaster, +				       QUAGGA_SIGNAL_TIMER_INTERVAL);  #endif /* SIGEVENT_SCHEDULE_THREAD */  } diff --git a/lib/sigevent.h b/lib/sigevent.h index 248fa2c058..1c35cf188c 100644 --- a/lib/sigevent.h +++ b/lib/sigevent.h @@ -1,4 +1,4 @@ -/*  +/*   * Quagga Signal handling header.   *   * Copyright (C) 2004 Paul Jakma. @@ -18,7 +18,7 @@   * You should have received a copy of the GNU General Public License   * along with Quagga; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _QUAGGA_SIGNAL_H @@ -28,12 +28,11 @@  #define QUAGGA_SIGNAL_TIMER_INTERVAL 2L -struct quagga_signal_t -{ -  int signal;                     /* signal number    */ -  void (*handler) (void);         /* handler to call  */ +struct quagga_signal_t { +	int signal;	    /* signal number    */ +	void (*handler)(void); /* handler to call  */ -  volatile sig_atomic_t caught;   /* private member   */ +	volatile sig_atomic_t caught; /* private member   */  };  /* initialise sigevent system @@ -43,10 +42,10 @@ struct quagga_signal_t   * - array of quagga_signal_t's describing signals to handle   *   and handlers to use for each signal   */ -extern void signal_init (struct thread_master *m, int sigc,  -                         struct quagga_signal_t *signals); +extern void signal_init(struct thread_master *m, int sigc, +			struct quagga_signal_t *signals);  /* check whether there are signals to handle, process any found */ -extern int quagga_sigevent_process (void); +extern int quagga_sigevent_process(void);  #endif /* _QUAGGA_SIGNAL_H */ diff --git a/lib/skiplist.c b/lib/skiplist.c index 05f489c905..db8e035070 100644 --- a/lib/skiplist.c +++ b/lib/skiplist.c @@ -1,5 +1,5 @@  /* - * Copyright 1990 William Pugh  + * Copyright 1990 William Pugh   *   * Redistribution and use in source and binary forms, with or without   * modification, are permitted. @@ -23,34 +23,34 @@  /*   * Skip List impementation based on code from William Pugh.   * ftp://ftp.cs.umd.edu/pub/skipLists/ - *  + *   * Skip Lists are a probabilistic alternative to balanced trees, as - * described in the June 1990 issue of CACM and were invented by  - * William Pugh in 1987.  - *  - * This file contains source code to implement a dictionary using  + * described in the June 1990 issue of CACM and were invented by + * William Pugh in 1987. + * + * This file contains source code to implement a dictionary using   * skip lists and a test driver to test the routines. - *  + *   * A couple of comments about this implementation:   *   The routine randomLevel has been hard-coded to generate random   *   levels using p=0.25. It can be easily changed. - *    + *   *   The insertion routine has been implemented so as to use the   *   dirty hack described in the CACM paper: if a random level is   *   generated that is more than the current maximum level, the   *   current maximum level plus one is used instead. - *  + *   *   Levels start at zero and go up to MaxLevel (which is equal to   * 	(MaxNumberOfLevels-1). - *  + *   * The run-time flag SKIPLIST_FLAG_ALLOW_DUPLICATES determines whether or   * not duplicates are allowed for a given list. If set, duplicates are   * allowed and act in a FIFO manner. If not set, an insertion of a value   * already in the list updates the previously existing binding. - *  + *   * BitsInRandom is defined to be the number of bits returned by a call to   * random(). For most all machines with 32-bit integers, this is 31 bits - * as currently set.  + * as currently set.   */ @@ -61,7 +61,7 @@  #include "vty.h"  #include "skiplist.h" -DEFINE_MTYPE_STATIC(LIB, SKIP_LIST,      "Skip List") +DEFINE_MTYPE_STATIC(LIB, SKIP_LIST, "Skip List")  DEFINE_MTYPE_STATIC(LIB, SKIP_LIST_NODE, "Skip Node")  #define BitsInRandom 31 @@ -72,256 +72,251 @@ DEFINE_MTYPE_STATIC(LIB, SKIP_LIST_NODE, "Skip Node")  static int randomsLeft;  static int randomBits; -static struct skiplist *skiplist_last_created;	/* debugging hack */ +static struct skiplist *skiplist_last_created; /* debugging hack */  #if 1 -#define CHECKLAST(sl) do {\ -    if ((sl)->header->forward[0] && !(sl)->last) assert(0);	\ -    if (!(sl)->header->forward[0] && (sl)->last) assert(0);	\ -} while (0) +#define CHECKLAST(sl)                                                          \ +	do {                                                                   \ +		if ((sl)->header->forward[0] && !(sl)->last)                   \ +			assert(0);                                             \ +		if (!(sl)->header->forward[0] && (sl)->last)                   \ +			assert(0);                                             \ +	} while (0)  #else  #define CHECKLAST(sl)  #endif -static int -randomLevel() +static int randomLevel()  { -    register int level = 0; -    register int b; +	register int level = 0; +	register int b; -    do { -	if (randomsLeft <= 0) { -	    randomBits = random(); -	    randomsLeft = BitsInRandom/2; -	} -	b = randomBits&3; -	randomBits>>=2; -	--randomsLeft; - -	if (!b) { -	    level++; -	    if (level >= MaxLevel) -		return MaxLevel; -	} -    } while (!b); - -    return level; +	do { +		if (randomsLeft <= 0) { +			randomBits = random(); +			randomsLeft = BitsInRandom / 2; +		} +		b = randomBits & 3; +		randomBits >>= 2; +		--randomsLeft; + +		if (!b) { +			level++; +			if (level >= MaxLevel) +				return MaxLevel; +		} +	} while (!b); + +	return level;  } -static int -default_cmp(void *key1, void *key2) +static int default_cmp(void *key1, void *key2)  { -    if (key1 < key2) -	return -1; -    if (key1 > key2) -	return 1; -    return 0; +	if (key1 < key2) +		return -1; +	if (key1 > key2) +		return 1; +	return 0;  } -unsigned int -skiplist_count(struct skiplist *l) +unsigned int skiplist_count(struct skiplist *l)  { -    return l->count; +	return l->count;  } -struct skiplist * -skiplist_new( -    int	flags, -    int (*cmp) (void *key1, void *key2), -    void (*del) (void *val)) +struct skiplist *skiplist_new(int flags, int (*cmp)(void *key1, void *key2), +			      void (*del)(void *val))  { -    struct skiplist *new; +	struct skiplist *new; -    new = XCALLOC (MTYPE_SKIP_LIST, sizeof (struct skiplist)); -    assert(new); +	new = XCALLOC(MTYPE_SKIP_LIST, sizeof(struct skiplist)); +	assert(new); -    new->level = 0; -    new->count = 0; -    new->header = newNodeOfLevel(MaxNumberOfLevels); -    new->stats = newNodeOfLevel(MaxNumberOfLevels); +	new->level = 0; +	new->count = 0; +	new->header = newNodeOfLevel(MaxNumberOfLevels); +	new->stats = newNodeOfLevel(MaxNumberOfLevels); -    new->flags = flags; -    if (cmp) -	new->cmp = cmp; -    else -	new->cmp = default_cmp; +	new->flags = flags; +	if (cmp) +		new->cmp = cmp; +	else +		new->cmp = default_cmp; -    if (del) -	new->del = del; +	if (del) +		new->del = del; -    skiplist_last_created = new;	/* debug */ +	skiplist_last_created = new; /* debug */ -    return new; +	return new;  } -void -skiplist_free(struct skiplist *l) +void skiplist_free(struct skiplist *l)  { -    register struct skiplistnode *p, *q; +	register struct skiplistnode *p, *q; -    p = l->header; +	p = l->header; -    do { -	q = p->forward[0]; -	if (l->del && p != l->header) -	    (*l->del)(p->value); -	XFREE(MTYPE_SKIP_LIST_NODE, p); -	p = q; -    } while (p); +	do { +		q = p->forward[0]; +		if (l->del && p != l->header) +			(*l->del)(p->value); +		XFREE(MTYPE_SKIP_LIST_NODE, p); +		p = q; +	} while (p); -    XFREE(MTYPE_SKIP_LIST_NODE, l->stats); -    XFREE(MTYPE_SKIP_LIST, l); +	XFREE(MTYPE_SKIP_LIST_NODE, l->stats); +	XFREE(MTYPE_SKIP_LIST, l);  } -int -skiplist_insert( -    register struct skiplist	*l, -    register void		*key, -    register void		*value) +int skiplist_insert(register struct skiplist *l, register void *key, +		    register void *value)  { -    register int			k; -    struct skiplistnode			*update[MaxNumberOfLevels]; -    register struct skiplistnode	*p, *q; - -    CHECKLAST(l); - -/* DEBUG */ -    if (!key) { -	zlog_err("%s: key is 0, value is %p", __func__, value); -    } - -    p = l->header; -    k = l->level; -    do { -	while (q = p->forward[k], q && (*l->cmp)(q->key, key) < 0) p = q; -	update[k] = p; -    } while (--k >= 0); - -    if (!(l->flags & SKIPLIST_FLAG_ALLOW_DUPLICATES) && -	q && ((*l->cmp)(q->key, key) == 0)) { - -	    return -1; -    } - -    k = randomLevel(); -    if (k>l->level) { -	k = ++l->level; -	update[k] = l->header; -    } - -    q = newNodeOfLevel(k); -    q->key = key; -    q->value = value; +	register int k; +	struct skiplistnode *update[MaxNumberOfLevels]; +	register struct skiplistnode *p, *q; + +	CHECKLAST(l); + +	/* DEBUG */ +	if (!key) { +		zlog_err("%s: key is 0, value is %p", __func__, value); +	} + +	p = l->header; +	k = l->level; +	do { +		while (q = p->forward[k], q && (*l->cmp)(q->key, key) < 0) +			p = q; +		update[k] = p; +	} while (--k >= 0); + +	if (!(l->flags & SKIPLIST_FLAG_ALLOW_DUPLICATES) && q +	    && ((*l->cmp)(q->key, key) == 0)) { + +		return -1; +	} + +	k = randomLevel(); +	if (k > l->level) { +		k = ++l->level; +		update[k] = l->header; +	} + +	q = newNodeOfLevel(k); +	q->key = key; +	q->value = value;  #if SKIPLIST_0TIMER_DEBUG -    q->flags = SKIPLIST_NODE_FLAG_INSERTED;	/* debug */ +	q->flags = SKIPLIST_NODE_FLAG_INSERTED; /* debug */  #endif -    ++(l->stats->forward[k]); +	++(l->stats->forward[k]);  #if SKIPLIST_DEBUG -    zlog_debug("%s: incremented stats @%p:%d, now %ld", __func__, l, k, -	l->stats->forward[k] - (struct skiplistnode *)NULL); +	zlog_debug("%s: incremented stats @%p:%d, now %ld", __func__, l, k, +		   l->stats->forward[k] - (struct skiplistnode *)NULL);  #endif -    do { -	p = update[k]; -	q->forward[k] = p->forward[k]; -	p->forward[k] = q; -    } while(--k>=0); +	do { +		p = update[k]; +		q->forward[k] = p->forward[k]; +		p->forward[k] = q; +	} while (--k >= 0); -    /* -     * If this is the last item in the list, update the "last" pointer -     */ -    if (!q->forward[0]) { -	l->last = q; -    } +	/* +	 * If this is the last item in the list, update the "last" pointer +	 */ +	if (!q->forward[0]) { +		l->last = q; +	} -    ++(l->count); +	++(l->count); -    CHECKLAST(l); +	CHECKLAST(l); -    return 0; +	return 0;  } -int -skiplist_delete( -    register struct skiplist	*l, -    register void		*key, -    register void		*value)	/* used only if duplicates allowed */ +int skiplist_delete(register struct skiplist *l, register void *key, +		    register void *value) /* used only if duplicates allowed */  { -    register int		k,m; -    struct skiplistnode		*update[MaxNumberOfLevels]; -    register struct skiplistnode *p, *q; - -    CHECKLAST(l); - -    /* to make debugging easier */ -    for (k = 0; k < MaxNumberOfLevels; ++k) -	update[k] = NULL; - -    p = l->header; -    k = m = l->level; -    do { -	while (q = p->forward[k], q && (*l->cmp)(q->key, key) < 0) p = q; -	update[k] = p; -    } while(--k>=0); - -    if (l->flags & SKIPLIST_FLAG_ALLOW_DUPLICATES) { -	while (q && ((*l->cmp)(q->key, key) == 0) && (q->value != value)) { -	    int i; -	    for (i = 0; i <= l->level; ++i) { -		if (update[i]->forward[i] == q) -		    update[i] = q; -	    } -	    q = q->forward[0]; +	register int k, m; +	struct skiplistnode *update[MaxNumberOfLevels]; +	register struct skiplistnode *p, *q; + +	CHECKLAST(l); + +	/* to make debugging easier */ +	for (k = 0; k < MaxNumberOfLevels; ++k) +		update[k] = NULL; + +	p = l->header; +	k = m = l->level; +	do { +		while (q = p->forward[k], q && (*l->cmp)(q->key, key) < 0) +			p = q; +		update[k] = p; +	} while (--k >= 0); + +	if (l->flags & SKIPLIST_FLAG_ALLOW_DUPLICATES) { +		while (q && ((*l->cmp)(q->key, key) == 0) +		       && (q->value != value)) { +			int i; +			for (i = 0; i <= l->level; ++i) { +				if (update[i]->forward[i] == q) +					update[i] = q; +			} +			q = q->forward[0]; +		}  	} -    } -    if (q && (*l->cmp)(q->key, key) == 0) { -	if (!(l->flags & SKIPLIST_FLAG_ALLOW_DUPLICATES) || -	    (q->value == value)) { +	if (q && (*l->cmp)(q->key, key) == 0) { +		if (!(l->flags & SKIPLIST_FLAG_ALLOW_DUPLICATES) +		    || (q->value == value)) { -	    /* -	     * found node to delete -	     */ +/* + * found node to delete + */  #if SKIPLIST_0TIMER_DEBUG -	    q->flags &= ~SKIPLIST_NODE_FLAG_INSERTED; +			q->flags &= ~SKIPLIST_NODE_FLAG_INSERTED;  #endif -	    /* -	     * If we are deleting the last element of the list, -	     * update the list's "last" pointer. -	     */ -	    if (l->last == q) { -		if (update[0] == l->header) -		    l->last = NULL; -		else -		    l->last = update[0]; -	    } - -	    for(k=0; k<=m && (p=update[k])->forward[k] == q; k++) { -		p->forward[k] = q->forward[k]; -	    } -	    --(l->stats->forward[k-1]); +			/* +			 * If we are deleting the last element of the list, +			 * update the list's "last" pointer. +			 */ +			if (l->last == q) { +				if (update[0] == l->header) +					l->last = NULL; +				else +					l->last = update[0]; +			} + +			for (k = 0; k <= m && (p = update[k])->forward[k] == q; +			     k++) { +				p->forward[k] = q->forward[k]; +			} +			--(l->stats->forward[k - 1]);  #if SKIPLIST_DEBUG -	    zlog_debug("%s: decremented stats @%p:%d, now %ld", -		__func__, l, k-1, -		l->stats->forward[k-1] - (struct skiplistnode *)NULL); +			zlog_debug("%s: decremented stats @%p:%d, now %ld", +				   __func__, l, k - 1, +				   l->stats->forward[k - 1] +					   - (struct skiplistnode *)NULL);  #endif -	    if (l->del) -		(*l->del)(q->value); -	    XFREE(MTYPE_SKIP_LIST_NODE, q); -	    while( l->header->forward[m] == NULL && m > 0 ) -		 m--; -	    l->level = m; -	    CHECKLAST(l); -	    --(l->count); -	    return 0; +			if (l->del) +				(*l->del)(q->value); +			XFREE(MTYPE_SKIP_LIST_NODE, q); +			while (l->header->forward[m] == NULL && m > 0) +				m--; +			l->level = m; +			CHECKLAST(l); +			--(l->count); +			return 0; +		}  	} -    } -    CHECKLAST(l); -    return -1; +	CHECKLAST(l); +	return -1;  }  /* @@ -330,44 +325,39 @@ skiplist_delete(   *   * Also set a cursor for use with skiplist_next_value.   */ -int -skiplist_first_value( -    register struct skiplist	*l,			/* in */ -    register void		*key,			/* in */ -    void			**valuePointer,		/* out */ -    void			**cursor)		/* out */ +int skiplist_first_value(register struct skiplist *l, /* in */ +			 register void *key,	  /* in */ +			 void **valuePointer,	 /* out */ +			 void **cursor)		      /* out */  { -    register int k; -    register struct skiplistnode *p, *q; +	register int k; +	register struct skiplistnode *p, *q; -    p = l->header; -    k = l->level; +	p = l->header; +	k = l->level; -    do { -	while (q = p->forward[k], q && (*l->cmp)(q->key, key) < 0) -	    p = q; +	do { +		while (q = p->forward[k], q && (*l->cmp)(q->key, key) < 0) +			p = q; -    } while (--k >= 0); +	} while (--k >= 0); -    if (!q || (*l->cmp)(q->key, key)) -	return -1; +	if (!q || (*l->cmp)(q->key, key)) +		return -1; -    if (valuePointer) -	*valuePointer = q->value; +	if (valuePointer) +		*valuePointer = q->value; -    if (cursor) -	*cursor = q; +	if (cursor) +		*cursor = q; -    return 0; +	return 0;  } -int -skiplist_search( -    register struct skiplist	*l, -    register void		*key, -    void			**valuePointer) +int skiplist_search(register struct skiplist *l, register void *key, +		    void **valuePointer)  { -    return skiplist_first_value(l, key, valuePointer, NULL); +	return skiplist_first_value(l, key, valuePointer, NULL);  } @@ -380,307 +370,296 @@ skiplist_search(   * do not correspond to a list element, or if they specify the   * last element with the given key, -1 is returned.   */ -int -skiplist_next_value( -    register struct skiplist	*l,			/* in */ -    register void		*key,			/* in */ -    void			**valuePointer,		/* in/out */ -    void			**cursor)		/* in/out */ +int skiplist_next_value(register struct skiplist *l, /* in */ +			register void *key,	  /* in */ +			void **valuePointer,	 /* in/out */ +			void **cursor)		     /* in/out */  { -    register int		k,m; -    register struct skiplistnode *p, *q; +	register int k, m; +	register struct skiplistnode *p, *q; -    CHECKLAST(l); +	CHECKLAST(l); -    if (!(l->flags & SKIPLIST_FLAG_ALLOW_DUPLICATES)) { -	return -1; -    } +	if (!(l->flags & SKIPLIST_FLAG_ALLOW_DUPLICATES)) { +		return -1; +	} -    if (!cursor || !*cursor) { -	p = l->header; -	k = m = l->level; +	if (!cursor || !*cursor) { +		p = l->header; +		k = m = l->level; + +		/* +		 * Find matching key +		 */ +		do { +			while (q = p->forward[k], +			       q && (*l->cmp)(q->key, key) < 0) +				p = q; +		} while (--k >= 0); + +		/* +		 * Find matching value +		 */ +		while (q && ((*l->cmp)(q->key, key) == 0) +		       && (q->value != *valuePointer)) { +			q = q->forward[0]; +		} + +		if (!q || ((*l->cmp)(q->key, key) != 0) +		    || (q->value != *valuePointer)) { +			/* +			 * No matching value +			 */ +			CHECKLAST(l); +			return -1; +		} +	} else { +		q = (struct skiplistnode *)*cursor; +	}  	/* -	 * Find matching key +	 * Advance cursor  	 */ -	do { -	    while (q = p->forward[k], q && (*l->cmp)(q->key, key) < 0) -		p = q; -	} while(--k>=0); +	q = q->forward[0]; -	/*  -	 * Find matching value +	/* +	 * If we reached end-of-list or if the key is no longer the same, +	 * then return error  	 */ -	while (q && ((*l->cmp)(q->key, key) == 0) && (q->value != *valuePointer)) { -	    q = q->forward[0]; -	} - -	if (!q || ((*l->cmp)(q->key, key) != 0) || (q->value != *valuePointer)) { -	    /* -	     * No matching value -	     */ -	    CHECKLAST(l); -	    return -1; -	} -    } else { -	q = (struct skiplistnode *)*cursor; -    } - -    /* -     * Advance cursor -     */ -    q = q->forward[0]; - -    /* -     * If we reached end-of-list or if the key is no longer the same, -     * then return error -     */ -    if (!q || ((*l->cmp)(q->key, key) != 0)) -	return -1; +	if (!q || ((*l->cmp)(q->key, key) != 0)) +		return -1; -    *valuePointer = q->value; -    if (cursor) -	*cursor = q; -    CHECKLAST(l); -    return 0; +	*valuePointer = q->value; +	if (cursor) +		*cursor = q; +	CHECKLAST(l); +	return 0;  } -int -skiplist_first( -    register struct skiplist	 *l, -    void			**keyPointer, -    void			**valuePointer) +int skiplist_first(register struct skiplist *l, void **keyPointer, +		   void **valuePointer)  { -    register struct skiplistnode *p; +	register struct skiplistnode *p; -    CHECKLAST(l); -    p = l->header->forward[0]; -    if (!p) -	return -1; +	CHECKLAST(l); +	p = l->header->forward[0]; +	if (!p) +		return -1; -    if (keyPointer) -	*keyPointer = p->key; +	if (keyPointer) +		*keyPointer = p->key; -    if (valuePointer) -	*valuePointer = p->value; +	if (valuePointer) +		*valuePointer = p->value; -    CHECKLAST(l); +	CHECKLAST(l); -    return 0; +	return 0;  } -int -skiplist_last( -    register struct skiplist	 *l, -    void			**keyPointer, -    void			**valuePointer) +int skiplist_last(register struct skiplist *l, void **keyPointer, +		  void **valuePointer)  { -    CHECKLAST(l); -    if (l->last) { -	if (keyPointer) -	    *keyPointer = l->last->key; -	if (valuePointer) -	    *valuePointer = l->last->value; -	return 0; -    } -    return -1; +	CHECKLAST(l); +	if (l->last) { +		if (keyPointer) +			*keyPointer = l->last->key; +		if (valuePointer) +			*valuePointer = l->last->value; +		return 0; +	} +	return -1;  }  /*   * true = empty   */ -int -skiplist_empty( -    register struct skiplist	 *l) +int skiplist_empty(register struct skiplist *l)  { -    CHECKLAST(l); -    if (l->last) -	return 0; -    return 1; +	CHECKLAST(l); +	if (l->last) +		return 0; +	return 1;  } -/*  +/*   * Use this to walk the list. Caller sets *cursor to NULL to obtain   * first element. Return value of 0 indicates valid cursor/element   * returned, otherwise NULL cursor arg or EOL.   */ -int -skiplist_next( -    register struct skiplist	 *l,			/* in */ -    void			**keyPointer,		/* out */ -    void			**valuePointer,		/* out */ -    void			**cursor)		/* in/out */ +int skiplist_next(register struct skiplist *l, /* in */ +		  void **keyPointer,	   /* out */ +		  void **valuePointer,	 /* out */ +		  void **cursor)	       /* in/out */  { -    struct skiplistnode *p; +	struct skiplistnode *p; -    if (!cursor) -	return -1; +	if (!cursor) +		return -1; -    CHECKLAST(l); +	CHECKLAST(l); -    if (!*cursor) { -	p = l->header->forward[0]; -    } else { -	p = *cursor; -	p = p->forward[0]; -    } -    *cursor = p; +	if (!*cursor) { +		p = l->header->forward[0]; +	} else { +		p = *cursor; +		p = p->forward[0]; +	} +	*cursor = p; -    if (!p) -	return -1; +	if (!p) +		return -1; -    if (keyPointer) -	*keyPointer = p->key; +	if (keyPointer) +		*keyPointer = p->key; -    if (valuePointer) -	*valuePointer = p->value; +	if (valuePointer) +		*valuePointer = p->value; -    CHECKLAST(l); +	CHECKLAST(l); -    return 0; +	return 0;  } -int -skiplist_delete_first( -    register struct skiplist	 *l) +int skiplist_delete_first(register struct skiplist *l)  { -    register int		k; -    register struct skiplistnode *p, *q; -    int nodelevel = 0; - -    CHECKLAST(l); +	register int k; +	register struct skiplistnode *p, *q; +	int nodelevel = 0; -    p = l->header; -    q = l->header->forward[0]; +	CHECKLAST(l); -    if (!q) -	return -1; - -    for (k = l->level; k >= 0; --k) { -	if (p->forward[k] == q) { -	    p->forward[k] = q->forward[k]; -	    if ((k == l->level) && (p->forward[k] == NULL) && (l->level > 0)) -		--(l->level); -	    if (!nodelevel) -		nodelevel = k; +	p = l->header; +	q = l->header->forward[0]; + +	if (!q) +		return -1; + +	for (k = l->level; k >= 0; --k) { +		if (p->forward[k] == q) { +			p->forward[k] = q->forward[k]; +			if ((k == l->level) && (p->forward[k] == NULL) +			    && (l->level > 0)) +				--(l->level); +			if (!nodelevel) +				nodelevel = k; +		}  	} -    }  #if SKIPLIST_0TIMER_DEBUG -    q->flags &= ~SKIPLIST_NODE_FLAG_INSERTED; +	q->flags &= ~SKIPLIST_NODE_FLAG_INSERTED;  #endif -    /* -     * If we are deleting the last element of the list, -     * update the list's "last" pointer. -     */ -    if (l->last == q) { -	l->last = NULL; -    } - -    --(l->stats->forward[nodelevel]); +	/* +	 * If we are deleting the last element of the list, +	 * update the list's "last" pointer. +	 */ +	if (l->last == q) { +		l->last = NULL; +	} + +	--(l->stats->forward[nodelevel]);  #if SKIPLIST_DEBUG -    zlog_debug("%s: decremented stats @%p:%d, now %ld", __func__, l, nodelevel, -	l->stats->forward[nodelevel] - (struct skiplistnode *)NULL); +	zlog_debug("%s: decremented stats @%p:%d, now %ld", __func__, l, +		   nodelevel, +		   l->stats->forward[nodelevel] - (struct skiplistnode *)NULL);  #endif -    if (l->del) -	(*l->del)(q->value); +	if (l->del) +		(*l->del)(q->value); -    XFREE(MTYPE_SKIP_LIST_NODE, q); +	XFREE(MTYPE_SKIP_LIST_NODE, q); -    CHECKLAST(l); +	CHECKLAST(l); -    --(l->count); +	--(l->count); -    return 0; +	return 0;  } -void -skiplist_debug(struct vty *vty, struct skiplist *l) +void skiplist_debug(struct vty *vty, struct skiplist *l)  { -    int i; - -    if (!l) -	l = skiplist_last_created; -    vty_out(vty, "Skiplist %p has max level %d%s", l, l->level, VTY_NEWLINE); -    for (i = l->level; i >= 0; --i) -	vty_out(vty, "  @%d: %ld%s", -	    i, (long)((l->stats->forward[i]) - (struct skiplistnode *)NULL), -	    VTY_NEWLINE); +	int i; + +	if (!l) +		l = skiplist_last_created; +	vty_out(vty, "Skiplist %p has max level %d%s", l, l->level, +		VTY_NEWLINE); +	for (i = l->level; i >= 0; --i) +		vty_out(vty, "  @%d: %ld%s", i, +			(long)((l->stats->forward[i]) +			       - (struct skiplistnode *)NULL), +			VTY_NEWLINE);  } -static void * -scramble(int i) +static void *scramble(int i)  { -    uintptr_t	result; +	uintptr_t result; -    result = (i & 0xff) << 24; -    result |= (i >> 8); +	result = (i & 0xff) << 24; +	result |= (i >> 8); -    return (void *)result; +	return (void *)result;  }  #define sampleSize 65536 -void -skiplist_test(struct vty *vty) { -    struct skiplist *l; -    register int i,k; -    void *keys[sampleSize]; -    void *v; - -    zlog_debug("%s: entry", __func__); +void skiplist_test(struct vty *vty) +{ +	struct skiplist *l; +	register int i, k; +	void *keys[sampleSize]; +	void *v; -    l= skiplist_new(SKIPLIST_FLAG_ALLOW_DUPLICATES, NULL, NULL); +	zlog_debug("%s: entry", __func__); -    zlog_debug("%s: skiplist_new returned %p", __func__, l); +	l = skiplist_new(SKIPLIST_FLAG_ALLOW_DUPLICATES, NULL, NULL); -    for (i=0; i < 4; i++) { +	zlog_debug("%s: skiplist_new returned %p", __func__, l); -	for (k=0; k < sampleSize; k++) { -	    if (!(k%1000)) { -		zlog_debug("%s: (%d:%d)", __func__, i, k); -	    } -	    //keys[k] = (void *)random(); -	    keys[k] = (void *)scramble(k); -	    if (skiplist_insert(l, keys[k], keys[k])) -		zlog_debug("error in insert #%d,#%d",i,k); -	} +	for (i = 0; i < 4; i++) { -	zlog_debug("%s: inserts done", __func__); +		for (k = 0; k < sampleSize; k++) { +			if (!(k % 1000)) { +				zlog_debug("%s: (%d:%d)", __func__, i, k); +			} +			// keys[k] = (void *)random(); +			keys[k] = (void *)scramble(k); +			if (skiplist_insert(l, keys[k], keys[k])) +				zlog_debug("error in insert #%d,#%d", i, k); +		} -        for (k=0; k < sampleSize; k++) { +		zlog_debug("%s: inserts done", __func__); -	    if (!(k % 1000)) -		zlog_debug("[%d:%d]", i, k); -	    if (skiplist_search(l, keys[k], &v)) -		zlog_debug("error in search #%d,#%d",i,k); +		for (k = 0; k < sampleSize; k++) { -	    if (v != keys[k]) -		zlog_debug("search returned wrong value"); -	} +			if (!(k % 1000)) +				zlog_debug("[%d:%d]", i, k); +			if (skiplist_search(l, keys[k], &v)) +				zlog_debug("error in search #%d,#%d", i, k); +			if (v != keys[k]) +				zlog_debug("search returned wrong value"); +		} -        for (k=0; k < sampleSize; k++) { +		for (k = 0; k < sampleSize; k++) { -	    if (!(k % 1000)) -		zlog_debug("<%d:%d>", i, k); -	    if (skiplist_delete(l, keys[k], keys[k])) -		zlog_debug("error in delete"); -	    keys[k] = (void *)scramble(k ^ 0xf0f0f0f0); -	    if (skiplist_insert(l, keys[k], keys[k])) -		zlog_debug("error in insert #%d,#%d",i,k); -	} +			if (!(k % 1000)) +				zlog_debug("<%d:%d>", i, k); +			if (skiplist_delete(l, keys[k], keys[k])) +				zlog_debug("error in delete"); +			keys[k] = (void *)scramble(k ^ 0xf0f0f0f0); +			if (skiplist_insert(l, keys[k], keys[k])) +				zlog_debug("error in insert #%d,#%d", i, k); +		} -        for (k=0; k < sampleSize; k++) { +		for (k = 0; k < sampleSize; k++) { -	    if (!(k % 1000)) -		zlog_debug("{%d:%d}", i, k); -	    if (skiplist_delete_first(l)) -		zlog_debug("error in delete_first"); +			if (!(k % 1000)) +				zlog_debug("{%d:%d}", i, k); +			if (skiplist_delete_first(l)) +				zlog_debug("error in delete_first"); +		}  	} -    } -    skiplist_free(l); +	skiplist_free(l);  } - diff --git a/lib/skiplist.h b/lib/skiplist.h index 25775f7543..a2e8c374b1 100644 --- a/lib/skiplist.h +++ b/lib/skiplist.h @@ -1,5 +1,5 @@  /* - * Copyright 1990 William Pugh  + * Copyright 1990 William Pugh   *   * Redistribution and use in source and binary forms, with or without   * modification, are permitted. @@ -33,127 +33,93 @@  #define SKIPLIST_0TIMER_DEBUG 1 -/*  +/*   * skiplistnodes must always contain data to be valid. Adding an   * empty node to a list is invalid   */ -struct skiplistnode  -{ -  void			*key; -  void			*value; +struct skiplistnode { +	void *key; +	void *value;  #if SKIPLIST_0TIMER_DEBUG -  int			flags; +	int flags;  #define SKIPLIST_NODE_FLAG_INSERTED 0x00000001  #endif -  struct skiplistnode	*forward[1];	/* variable sized */ +	struct skiplistnode *forward[1]; /* variable sized */  }; -struct skiplist  -{ -  int			flags; +struct skiplist { +	int flags;  #define SKIPLIST_FLAG_ALLOW_DUPLICATES	0x00000001 -  int			level;	/* max lvl (1 + current # of levels in list) */ -  unsigned int		count; -  struct skiplistnode	*header; -  struct skiplistnode	*stats; -  struct skiplistnode	*last;	/* last real list item (NULL if empty list) */ - -  /* -   * Returns -1 if val1 < val2, 0 if equal?, 1 if val1 > val2. -   * Used as definition of sorted for listnode_add_sort -   */ -  int (*cmp) (void *val1, void *val2); - -  /* callback to free user-owned data when listnode is deleted. supplying -   * this callback is very much encouraged! -   */ -  void (*del) (void *val); +	int level; /* max lvl (1 + current # of levels in list) */ +	unsigned int count; +	struct skiplistnode *header; +	struct skiplistnode *stats; +	struct skiplistnode +		*last; /* last real list item (NULL if empty list) */ + +	/* +	 * Returns -1 if val1 < val2, 0 if equal?, 1 if val1 > val2. +	 * Used as definition of sorted for listnode_add_sort +	 */ +	int (*cmp)(void *val1, void *val2); + +	/* callback to free user-owned data when listnode is deleted. supplying +	 * this callback is very much encouraged! +	 */ +	void (*del)(void *val);  };  /* Prototypes. */  extern struct skiplist * -skiplist_new( /* encouraged: set list.del callback on new lists */ -    int	flags, -    int (*cmp) (void *key1, void *key2),	/* NULL => default cmp */ -    void (*del) (void *val));			/* NULL => no auto val free */ - -extern void -skiplist_free (struct skiplist *); - -extern int -skiplist_insert( -    register struct skiplist *l, -    register void *key, -    register void *value); - -extern int -skiplist_delete( -    register struct skiplist *l, -    register void *key, -    register void *value); - -extern int -skiplist_search( -    register struct skiplist     *l, -    register void               *key, -    void                        **valuePointer); - -extern int -skiplist_first_value( -    register struct skiplist	*l,			/* in */ -    register void		*key,			/* in */ -    void			**valuePointer,		/* in/out */ -    void			**cursor);		/* out */ - -extern int -skiplist_next_value( -    register struct skiplist	*l,			/* in */ -    register void		*key,			/* in */ -    void			**valuePointer,		/* in/out */ -    void			**cursor);		/* in/out */ - -extern int -skiplist_first( -    register struct skiplist     *l, -    void                        **keyPointer, -    void                        **valuePointer); - -extern int -skiplist_last( -    register struct skiplist     *l, -    void                        **keyPointer, -    void                        **valuePointer); - -extern int -skiplist_delete_first( -    register struct skiplist     *l); - -extern int -skiplist_next( -    register struct skiplist	 *l,			/* in */ -    void			**keyPointer,		/* out */ -    void			**valuePointer,		/* out */ -    void			**cursor);		/* in/out */ - -extern int -skiplist_empty( -    register struct skiplist	 *l);			/* in */ - -extern unsigned int -skiplist_count( -    register struct skiplist	 *l);			/* in */ - -extern void -skiplist_debug( -    struct vty *vty,  -    struct skiplist *l); - -extern void -skiplist_test( -    struct vty *vty); +skiplist_new(/* encouraged: set list.del callback on new lists */ +	     int flags, +	     int (*cmp)(void *key1, void *key2), /* NULL => default cmp */ +	     void (*del)(void *val));		 /* NULL => no auto val free */ + +extern void skiplist_free(struct skiplist *); + +extern int skiplist_insert(register struct skiplist *l, register void *key, +			   register void *value); + +extern int skiplist_delete(register struct skiplist *l, register void *key, +			   register void *value); + +extern int skiplist_search(register struct skiplist *l, register void *key, +			   void **valuePointer); + +extern int skiplist_first_value(register struct skiplist *l, /* in */ +				register void *key,	  /* in */ +				void **valuePointer,	 /* in/out */ +				void **cursor);		     /* out */ + +extern int skiplist_next_value(register struct skiplist *l, /* in */ +			       register void *key,	  /* in */ +			       void **valuePointer,	 /* in/out */ +			       void **cursor);		    /* in/out */ + +extern int skiplist_first(register struct skiplist *l, void **keyPointer, +			  void **valuePointer); + +extern int skiplist_last(register struct skiplist *l, void **keyPointer, +			 void **valuePointer); + +extern int skiplist_delete_first(register struct skiplist *l); + +extern int skiplist_next(register struct skiplist *l, /* in */ +			 void **keyPointer,	   /* out */ +			 void **valuePointer,	 /* out */ +			 void **cursor);	      /* in/out */ + +extern int skiplist_empty(register struct skiplist *l); /* in */ + +extern unsigned int skiplist_count(register struct skiplist *l); /* in */ + +extern void skiplist_debug(struct vty *vty, struct skiplist *l); + +extern void skiplist_test(struct vty *vty);  #endif /* _ZEBRA_SKIPLIST_H */ diff --git a/lib/smux.c b/lib/smux.c index 370b8f138e..b14784f9a6 100644 --- a/lib/smux.c +++ b/lib/smux.c @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -54,30 +54,29 @@  #define SMUX_MAX_FAILURE 3  /* SNMP tree. */ -struct subtree -{ -  /* Tree's oid. */ -  oid name[MAX_OID_LEN]; -  u_char name_len; +struct subtree { +	/* Tree's oid. */ +	oid name[MAX_OID_LEN]; +	u_char name_len; -  /* List of the variables. */ -  struct variable *variables; +	/* List of the variables. */ +	struct variable *variables; -  /* Length of the variables list. */ -  int variables_num; +	/* Length of the variables list. */ +	int variables_num; -  /* Width of the variables list. */ -  int variables_width; +	/* Width of the variables list. */ +	int variables_width; -  /* Registered flag. */ -  int registered; +	/* Registered flag. */ +	int registered;  };  #define min(A,B) ((A) < (B) ? (A) : (B)) -enum smux_event {SMUX_SCHEDULE, SMUX_CONNECT, SMUX_READ}; +enum smux_event { SMUX_SCHEDULE, SMUX_CONNECT, SMUX_READ }; -void smux_event (enum smux_event, int); +void smux_event(enum smux_event, int);  /* SMUX socket. */ @@ -106,824 +105,810 @@ int debug_smux = 0;  int fail = 0;  /* SMUX node. */ -static struct cmd_node smux_node = -{ -  SMUX_NODE, -  ""                            /* SMUX has no interface. */ +static struct cmd_node smux_node = { +	SMUX_NODE, "" /* SMUX has no interface. */  };  /* thread master */  static struct thread_master *smux_master; -static int -oid_compare_part (oid *o1, int o1_len, oid *o2, int o2_len) +static int oid_compare_part(oid *o1, int o1_len, oid *o2, int o2_len)  { -  int i; - -  for (i = 0; i < min (o1_len, o2_len); i++) -    { -      if (o1[i] < o2[i]) -	return -1; -      else if (o1[i] > o2[i]) -	return 1; -    } -  if (o1_len < o2_len) -    return -1; - -  return 0; +	int i; + +	for (i = 0; i < min(o1_len, o2_len); i++) { +		if (o1[i] < o2[i]) +			return -1; +		else if (o1[i] > o2[i]) +			return 1; +	} +	if (o1_len < o2_len) +		return -1; + +	return 0;  } -static void -smux_oid_dump (const char *prefix, const oid *oid, size_t oid_len) +static void smux_oid_dump(const char *prefix, const oid *oid, size_t oid_len)  { -  unsigned int i; -  int first = 1; -  char buf[MAX_OID_LEN * 3]; - -  buf[0] = '\0'; - -  for (i = 0; i < oid_len; i++) -    { -      sprintf (buf + strlen (buf), "%s%d", first ? "" : ".", (int) oid[i]); -      first = 0; -    } -  zlog_debug ("%s: %s", prefix, buf); +	unsigned int i; +	int first = 1; +	char buf[MAX_OID_LEN * 3]; + +	buf[0] = '\0'; + +	for (i = 0; i < oid_len; i++) { +		sprintf(buf + strlen(buf), "%s%d", first ? "" : ".", +			(int)oid[i]); +		first = 0; +	} +	zlog_debug("%s: %s", prefix, buf);  } -static int -smux_socket (void) +static int smux_socket(void)  { -  int ret; -  struct addrinfo hints, *res0, *res; -  int gai; -  int sock = 0; - -  memset(&hints, 0, sizeof(hints)); -  hints.ai_family = PF_UNSPEC; -  hints.ai_socktype = SOCK_STREAM; -  gai = getaddrinfo(NULL, "smux", &hints, &res0); -  if (gai == EAI_SERVICE) -    { -      char servbuf[NI_MAXSERV]; -      sprintf(servbuf,"%d",SMUX_PORT_DEFAULT); -      servbuf[sizeof (servbuf) - 1] = '\0'; -      gai = getaddrinfo(NULL, servbuf, &hints, &res0); -    } -  if (gai) -    { -      zlog_warn("Cannot locate loopback service smux"); -      return -1; -    } -  for(res=res0; res; res=res->ai_next) -    { -      if (res->ai_family != AF_INET  -	  && res->ai_family != AF_INET6 -	  ) -	continue; - -      sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol); -      if (sock < 0) -	continue; -      sockopt_reuseaddr (sock); -      sockopt_reuseport (sock); -      ret = connect (sock, res->ai_addr, res->ai_addrlen); -      if (ret < 0) -	{ -	  close(sock); -	  sock = -1; -	  continue; +	int ret; +	struct addrinfo hints, *res0, *res; +	int gai; +	int sock = 0; + +	memset(&hints, 0, sizeof(hints)); +	hints.ai_family = PF_UNSPEC; +	hints.ai_socktype = SOCK_STREAM; +	gai = getaddrinfo(NULL, "smux", &hints, &res0); +	if (gai == EAI_SERVICE) { +		char servbuf[NI_MAXSERV]; +		sprintf(servbuf, "%d", SMUX_PORT_DEFAULT); +		servbuf[sizeof(servbuf) - 1] = '\0'; +		gai = getaddrinfo(NULL, servbuf, &hints, &res0); +	} +	if (gai) { +		zlog_warn("Cannot locate loopback service smux"); +		return -1; +	} +	for (res = res0; res; res = res->ai_next) { +		if (res->ai_family != AF_INET && res->ai_family != AF_INET6) +			continue; + +		sock = socket(res->ai_family, res->ai_socktype, +			      res->ai_protocol); +		if (sock < 0) +			continue; +		sockopt_reuseaddr(sock); +		sockopt_reuseport(sock); +		ret = connect(sock, res->ai_addr, res->ai_addrlen); +		if (ret < 0) { +			close(sock); +			sock = -1; +			continue; +		} +		break;  	} -      break; -    } -  freeaddrinfo(res0); -  if (sock < 0) -    zlog_warn ("Can't connect to SNMP agent with SMUX"); -  return sock; +	freeaddrinfo(res0); +	if (sock < 0) +		zlog_warn("Can't connect to SNMP agent with SMUX"); +	return sock;  } -static void -smux_getresp_send (oid objid[], size_t objid_len, long reqid, long errstat, -		   long errindex, u_char val_type, void *arg, size_t arg_len) +static void smux_getresp_send(oid objid[], size_t objid_len, long reqid, +			      long errstat, long errindex, u_char val_type, +			      void *arg, size_t arg_len)  { -  u_char buf[BUFSIZ]; -  u_char *ptr, *h1, *h1e, *h2, *h2e; -  size_t len, length; - -  ptr = buf; -  len = BUFSIZ; -  length = len; - -  if (debug_smux) -    { -      zlog_debug ("SMUX GETRSP send"); -      zlog_debug ("SMUX GETRSP reqid: %ld", reqid); -    } - -  h1 = ptr; -  /* Place holder h1 for complete sequence */ -  ptr = asn_build_sequence (ptr, &len, (u_char) SMUX_GETRSP, 0); -  h1e = ptr; -  -  ptr = asn_build_int (ptr, &len, -		       (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), -		       &reqid, sizeof (reqid)); - -  if (debug_smux) -    zlog_debug ("SMUX GETRSP errstat: %ld", errstat); - -  ptr = asn_build_int (ptr, &len, -		       (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), -		       &errstat, sizeof (errstat)); -  if (debug_smux) -    zlog_debug ("SMUX GETRSP errindex: %ld", errindex); - -  ptr = asn_build_int (ptr, &len, -		       (u_char) (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), -		       &errindex, sizeof (errindex)); - -  h2 = ptr; -  /* Place holder h2 for one variable */ -  ptr = asn_build_sequence (ptr, &len,  -			   (u_char)(ASN_SEQUENCE | ASN_CONSTRUCTOR), -			   0); -  h2e = ptr; - -  ptr = snmp_build_var_op (ptr, objid, &objid_len,  -			   val_type, arg_len, arg, &len); - -  /* Now variable size is known, fill in size */ -  asn_build_sequence(h2,&length,(u_char)(ASN_SEQUENCE|ASN_CONSTRUCTOR),ptr-h2e); - -  /* Fill in size of whole sequence */ -  asn_build_sequence(h1,&length,(u_char)SMUX_GETRSP,ptr-h1e); - -  if (debug_smux) -    zlog_debug ("SMUX getresp send: %td", (ptr - buf)); -   -  send (smux_sock, buf, (ptr - buf), 0); +	u_char buf[BUFSIZ]; +	u_char *ptr, *h1, *h1e, *h2, *h2e; +	size_t len, length; + +	ptr = buf; +	len = BUFSIZ; +	length = len; + +	if (debug_smux) { +		zlog_debug("SMUX GETRSP send"); +		zlog_debug("SMUX GETRSP reqid: %ld", reqid); +	} + +	h1 = ptr; +	/* Place holder h1 for complete sequence */ +	ptr = asn_build_sequence(ptr, &len, (u_char)SMUX_GETRSP, 0); +	h1e = ptr; + +	ptr = asn_build_int(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						| ASN_INTEGER), +			    &reqid, sizeof(reqid)); + +	if (debug_smux) +		zlog_debug("SMUX GETRSP errstat: %ld", errstat); + +	ptr = asn_build_int(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						| ASN_INTEGER), +			    &errstat, sizeof(errstat)); +	if (debug_smux) +		zlog_debug("SMUX GETRSP errindex: %ld", errindex); + +	ptr = asn_build_int(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						| ASN_INTEGER), +			    &errindex, sizeof(errindex)); + +	h2 = ptr; +	/* Place holder h2 for one variable */ +	ptr = asn_build_sequence(ptr, &len, +				 (u_char)(ASN_SEQUENCE | ASN_CONSTRUCTOR), 0); +	h2e = ptr; + +	ptr = snmp_build_var_op(ptr, objid, &objid_len, val_type, arg_len, arg, +				&len); + +	/* Now variable size is known, fill in size */ +	asn_build_sequence(h2, &length, +			   (u_char)(ASN_SEQUENCE | ASN_CONSTRUCTOR), ptr - h2e); + +	/* Fill in size of whole sequence */ +	asn_build_sequence(h1, &length, (u_char)SMUX_GETRSP, ptr - h1e); + +	if (debug_smux) +		zlog_debug("SMUX getresp send: %td", (ptr - buf)); + +	send(smux_sock, buf, (ptr - buf), 0);  } -static u_char * -smux_var (u_char *ptr, size_t len, oid objid[], size_t *objid_len, -          size_t *var_val_len, -          u_char *var_val_type, -          void **var_value) +static u_char *smux_var(u_char *ptr, size_t len, oid objid[], size_t *objid_len, +			size_t *var_val_len, u_char *var_val_type, +			void **var_value)  { -  u_char type; -  u_char val_type; -  size_t val_len; -  u_char *val; - -  if (debug_smux) -    zlog_debug ("SMUX var parse: len %zd", len); - -  /* Parse header. */ -  ptr = asn_parse_header (ptr, &len, &type); -   -  if (debug_smux) -    { -      zlog_debug ("SMUX var parse: type %d len %zd", type, len); -      zlog_debug ("SMUX var parse: type must be %d",  -		 (ASN_SEQUENCE | ASN_CONSTRUCTOR)); -    } - -  /* Parse var option. */ -  *objid_len = MAX_OID_LEN; -  ptr = snmp_parse_var_op(ptr, objid, objid_len, &val_type,  -			  &val_len, &val, &len); - -  if (var_val_len) -    *var_val_len = val_len; - -  if (var_value) -    *var_value = (void*) val; - -  if (var_val_type) -    *var_val_type = val_type; - -  /* Requested object id length is objid_len. */ -  if (debug_smux) -    smux_oid_dump ("Request OID", objid, *objid_len); - -  if (debug_smux) -    zlog_debug ("SMUX val_type: %d", val_type); - -  /* Check request value type. */ -  if (debug_smux) -  switch (val_type) -    { -    case ASN_NULL: -      /* In case of SMUX_GET or SMUX_GET_NEXT val_type is set to -         ASN_NULL. */ -      zlog_debug ("ASN_NULL"); -      break; - -    case ASN_INTEGER: -      zlog_debug ("ASN_INTEGER"); -      break; -    case ASN_COUNTER: -    case ASN_GAUGE: -    case ASN_TIMETICKS: -    case ASN_UINTEGER: -      zlog_debug ("ASN_COUNTER"); -      break; -    case ASN_COUNTER64: -      zlog_debug ("ASN_COUNTER64"); -      break; -    case ASN_IPADDRESS: -      zlog_debug ("ASN_IPADDRESS"); -      break; -    case ASN_OCTET_STR: -      zlog_debug ("ASN_OCTET_STR"); -      break; -    case ASN_OPAQUE: -    case ASN_NSAP: -    case ASN_OBJECT_ID: -      zlog_debug ("ASN_OPAQUE"); -      break; -    case SNMP_NOSUCHOBJECT: -      zlog_debug ("SNMP_NOSUCHOBJECT"); -      break; -    case SNMP_NOSUCHINSTANCE: -      zlog_debug ("SNMP_NOSUCHINSTANCE"); -      break; -    case SNMP_ENDOFMIBVIEW: -      zlog_debug ("SNMP_ENDOFMIBVIEW"); -      break; -    case ASN_BIT_STR: -      zlog_debug ("ASN_BIT_STR"); -      break; -    default: -      zlog_debug ("Unknown type"); -      break; -    } -  return ptr; +	u_char type; +	u_char val_type; +	size_t val_len; +	u_char *val; + +	if (debug_smux) +		zlog_debug("SMUX var parse: len %zd", len); + +	/* Parse header. */ +	ptr = asn_parse_header(ptr, &len, &type); + +	if (debug_smux) { +		zlog_debug("SMUX var parse: type %d len %zd", type, len); +		zlog_debug("SMUX var parse: type must be %d", +			   (ASN_SEQUENCE | ASN_CONSTRUCTOR)); +	} + +	/* Parse var option. */ +	*objid_len = MAX_OID_LEN; +	ptr = snmp_parse_var_op(ptr, objid, objid_len, &val_type, &val_len, +				&val, &len); + +	if (var_val_len) +		*var_val_len = val_len; + +	if (var_value) +		*var_value = (void *)val; + +	if (var_val_type) +		*var_val_type = val_type; + +	/* Requested object id length is objid_len. */ +	if (debug_smux) +		smux_oid_dump("Request OID", objid, *objid_len); + +	if (debug_smux) +		zlog_debug("SMUX val_type: %d", val_type); + +	/* Check request value type. */ +	if (debug_smux) +		switch (val_type) { +		case ASN_NULL: +			/* In case of SMUX_GET or SMUX_GET_NEXT val_type is set +			   to +			   ASN_NULL. */ +			zlog_debug("ASN_NULL"); +			break; + +		case ASN_INTEGER: +			zlog_debug("ASN_INTEGER"); +			break; +		case ASN_COUNTER: +		case ASN_GAUGE: +		case ASN_TIMETICKS: +		case ASN_UINTEGER: +			zlog_debug("ASN_COUNTER"); +			break; +		case ASN_COUNTER64: +			zlog_debug("ASN_COUNTER64"); +			break; +		case ASN_IPADDRESS: +			zlog_debug("ASN_IPADDRESS"); +			break; +		case ASN_OCTET_STR: +			zlog_debug("ASN_OCTET_STR"); +			break; +		case ASN_OPAQUE: +		case ASN_NSAP: +		case ASN_OBJECT_ID: +			zlog_debug("ASN_OPAQUE"); +			break; +		case SNMP_NOSUCHOBJECT: +			zlog_debug("SNMP_NOSUCHOBJECT"); +			break; +		case SNMP_NOSUCHINSTANCE: +			zlog_debug("SNMP_NOSUCHINSTANCE"); +			break; +		case SNMP_ENDOFMIBVIEW: +			zlog_debug("SNMP_ENDOFMIBVIEW"); +			break; +		case ASN_BIT_STR: +			zlog_debug("ASN_BIT_STR"); +			break; +		default: +			zlog_debug("Unknown type"); +			break; +		} +	return ptr;  }  /* NOTE: all 3 functions (smux_set, smux_get & smux_getnext) are based on     ucd-snmp smux and as such suppose, that the peer receives in the message     only one variable. Fortunately, IBM seems to do the same in AIX. */ -static int -smux_set (oid *reqid, size_t *reqid_len, -          u_char val_type, void *val, size_t val_len, int action) +static int smux_set(oid *reqid, size_t *reqid_len, u_char val_type, void *val, +		    size_t val_len, int action)  { -  int j; -  struct subtree *subtree; -  struct variable *v; -  int subresult; -  oid *suffix; -  size_t suffix_len; -  int result; -  u_char *statP = NULL; -  WriteMethod *write_method = NULL; -  struct listnode *node, *nnode; - -  /* Check */ -  for (ALL_LIST_ELEMENTS (treelist, node, nnode, subtree)) -    { -      subresult = oid_compare_part (reqid, *reqid_len, -                                    subtree->name, subtree->name_len); - -      /* Subtree matched. */ -      if (subresult == 0) -        { -          /* Prepare suffix. */ -          suffix = reqid + subtree->name_len; -          suffix_len = *reqid_len - subtree->name_len; -          result = subresult; - -          /* Check variables. */ -          for (j = 0; j < subtree->variables_num; j++) -            { -              v = &subtree->variables[j]; - -              /* Always check suffix */ -              result = oid_compare_part (suffix, suffix_len, -                                         v->name, v->namelen); - -              /* This is exact match so result must be zero. */ -              if (result == 0) -                { -                  if (debug_smux) -                    zlog_debug ("SMUX function call index is %d", v->magic); -		   -                  statP = (*v->findVar) (v, suffix, &suffix_len, 1, -					 &val_len, &write_method); - -                  if (write_method) -                    { -                      return (*write_method)(action, val, val_type, val_len, -					     statP, suffix, suffix_len); -                    } -                  else -                    { -                      return SNMP_ERR_READONLY; -                    } -                } - -              /* If above execution is failed or oid is small (so -                 there is no further match). */ -              if (result < 0) -                return SNMP_ERR_NOSUCHNAME; -            } -        } -    } -  return SNMP_ERR_NOSUCHNAME; +	int j; +	struct subtree *subtree; +	struct variable *v; +	int subresult; +	oid *suffix; +	size_t suffix_len; +	int result; +	u_char *statP = NULL; +	WriteMethod *write_method = NULL; +	struct listnode *node, *nnode; + +	/* Check */ +	for (ALL_LIST_ELEMENTS(treelist, node, nnode, subtree)) { +		subresult = oid_compare_part(reqid, *reqid_len, subtree->name, +					     subtree->name_len); + +		/* Subtree matched. */ +		if (subresult == 0) { +			/* Prepare suffix. */ +			suffix = reqid + subtree->name_len; +			suffix_len = *reqid_len - subtree->name_len; +			result = subresult; + +			/* Check variables. */ +			for (j = 0; j < subtree->variables_num; j++) { +				v = &subtree->variables[j]; + +				/* Always check suffix */ +				result = oid_compare_part(suffix, suffix_len, +							  v->name, v->namelen); + +				/* This is exact match so result must be zero. +				 */ +				if (result == 0) { +					if (debug_smux) +						zlog_debug( +							"SMUX function call index is %d", +							v->magic); + +					statP = (*v->findVar)( +						v, suffix, &suffix_len, 1, +						&val_len, &write_method); + +					if (write_method) { +						return (*write_method)( +							action, val, val_type, +							val_len, statP, suffix, +							suffix_len); +					} else { +						return SNMP_ERR_READONLY; +					} +				} + +				/* If above execution is failed or oid is small +				   (so +				   there is no further match). */ +				if (result < 0) +					return SNMP_ERR_NOSUCHNAME; +			} +		} +	} +	return SNMP_ERR_NOSUCHNAME;  } -static int -smux_get (oid *reqid, size_t *reqid_len, int exact,  -	  u_char *val_type,void **val, size_t *val_len) +static int smux_get(oid *reqid, size_t *reqid_len, int exact, u_char *val_type, +		    void **val, size_t *val_len)  { -  int j; -  struct subtree *subtree; -  struct variable *v; -  int subresult; -  oid *suffix; -  size_t suffix_len; -  int result; -  WriteMethod *write_method=NULL; -  struct listnode *node, *nnode; - -  /* Check */ -  for (ALL_LIST_ELEMENTS (treelist, node, nnode,subtree)) -    { -      subresult = oid_compare_part (reqid, *reqid_len,  -				    subtree->name, subtree->name_len); - -      /* Subtree matched. */ -      if (subresult == 0) -	{ -	  /* Prepare suffix. */ -	  suffix = reqid + subtree->name_len; -	  suffix_len = *reqid_len - subtree->name_len; -	  result = subresult; - -	  /* Check variables. */ -	  for (j = 0; j < subtree->variables_num; j++) -	    { -	      v = &subtree->variables[j]; - -	      /* Always check suffix */ -	      result = oid_compare_part (suffix, suffix_len, -					 v->name, v->namelen); - -	      /* This is exact match so result must be zero. */ -	      if (result == 0) -		{ -		  if (debug_smux) -		    zlog_debug ("SMUX function call index is %d", v->magic); - -		  *val = (*v->findVar) (v, suffix, &suffix_len, exact, -					val_len, &write_method); - -		  /* There is no instance. */ -		  if (*val == NULL) -		    return SNMP_NOSUCHINSTANCE; - -		  /* Call is suceed. */ -		  *val_type = v->type; - -		  return 0; +	int j; +	struct subtree *subtree; +	struct variable *v; +	int subresult; +	oid *suffix; +	size_t suffix_len; +	int result; +	WriteMethod *write_method = NULL; +	struct listnode *node, *nnode; + +	/* Check */ +	for (ALL_LIST_ELEMENTS(treelist, node, nnode, subtree)) { +		subresult = oid_compare_part(reqid, *reqid_len, subtree->name, +					     subtree->name_len); + +		/* Subtree matched. */ +		if (subresult == 0) { +			/* Prepare suffix. */ +			suffix = reqid + subtree->name_len; +			suffix_len = *reqid_len - subtree->name_len; +			result = subresult; + +			/* Check variables. */ +			for (j = 0; j < subtree->variables_num; j++) { +				v = &subtree->variables[j]; + +				/* Always check suffix */ +				result = oid_compare_part(suffix, suffix_len, +							  v->name, v->namelen); + +				/* This is exact match so result must be zero. +				 */ +				if (result == 0) { +					if (debug_smux) +						zlog_debug( +							"SMUX function call index is %d", +							v->magic); + +					*val = (*v->findVar)( +						v, suffix, &suffix_len, exact, +						val_len, &write_method); + +					/* There is no instance. */ +					if (*val == NULL) +						return SNMP_NOSUCHINSTANCE; + +					/* Call is suceed. */ +					*val_type = v->type; + +					return 0; +				} + +				/* If above execution is failed or oid is small +				   (so +				   there is no further match). */ +				if (result < 0) +					return SNMP_ERR_NOSUCHNAME; +			}  		} - -	      /* If above execution is failed or oid is small (so -                 there is no further match). */ -	      if (result < 0) -		return SNMP_ERR_NOSUCHNAME; -	    }  	} -    } -  return SNMP_ERR_NOSUCHNAME; +	return SNMP_ERR_NOSUCHNAME;  } -static int -smux_getnext (oid *reqid, size_t *reqid_len, int exact,  -	      u_char *val_type,void **val, size_t *val_len) +static int smux_getnext(oid *reqid, size_t *reqid_len, int exact, +			u_char *val_type, void **val, size_t *val_len)  { -  int j; -  oid save[MAX_OID_LEN]; -  int savelen = 0; -  struct subtree *subtree; -  struct variable *v; -  int subresult; -  oid *suffix; -  size_t suffix_len; -  int result; -  WriteMethod *write_method=NULL; -  struct listnode *node, *nnode; - - -  /* Save incoming request. */ -  oid_copy (save, reqid, *reqid_len); -  savelen = *reqid_len; - -  /* Check */ -  for (ALL_LIST_ELEMENTS (treelist, node, nnode, subtree)) -    { -      subresult = oid_compare_part (reqid, *reqid_len,  -				    subtree->name, subtree->name_len); - -      /* If request is in the tree. The agent has to make sure we -         only receive requests we have registered for. */ -      /* Unfortunately, that's not true. In fact, a SMUX subagent has to -         behave as if it manages the whole SNMP MIB tree itself. It's the -         duty of the master agent to collect the best answer and return it -         to the manager. See RFC 1227 chapter 3.1.6 for the glory details -         :-). ucd-snmp really behaves bad here as it actually might ask -         multiple times for the same GETNEXT request as it throws away the -         answer when it expects it in a different subtree and might come -         back later with the very same request. --jochen */ - -      if (subresult <= 0) -	{ -	  /* Prepare suffix. */ -	  suffix = reqid + subtree->name_len; -	  suffix_len = *reqid_len - subtree->name_len; -	  if (subresult < 0) -	    { -	      oid_copy(reqid, subtree->name, subtree->name_len); -	      *reqid_len = subtree->name_len; -	    } -	  for (j = 0; j < subtree->variables_num; j++) -	    { -	      result = subresult; -	      v = &subtree->variables[j]; - -	      /* Next then check result >= 0. */ -	      if (result == 0) -		result = oid_compare_part (suffix, suffix_len, -					   v->name, v->namelen); - -	      if (result <= 0) -		{ -		  if (debug_smux) -		    zlog_debug ("SMUX function call index is %d", v->magic); -		  if(result<0) -		    { -		      oid_copy(suffix, v->name, v->namelen); -		      suffix_len = v->namelen; -		    } -		  *val = (*v->findVar) (v, suffix, &suffix_len, exact, -					val_len, &write_method); -		  *reqid_len = suffix_len + subtree->name_len; -		  if (*val) -		    { -		      *val_type = v->type; -		      return 0; -		    } +	int j; +	oid save[MAX_OID_LEN]; +	int savelen = 0; +	struct subtree *subtree; +	struct variable *v; +	int subresult; +	oid *suffix; +	size_t suffix_len; +	int result; +	WriteMethod *write_method = NULL; +	struct listnode *node, *nnode; + + +	/* Save incoming request. */ +	oid_copy(save, reqid, *reqid_len); +	savelen = *reqid_len; + +	/* Check */ +	for (ALL_LIST_ELEMENTS(treelist, node, nnode, subtree)) { +		subresult = oid_compare_part(reqid, *reqid_len, subtree->name, +					     subtree->name_len); + +		/* If request is in the tree. The agent has to make sure we +		   only receive requests we have registered for. */ +		/* Unfortunately, that's not true. In fact, a SMUX subagent has +		   to +		   behave as if it manages the whole SNMP MIB tree itself. It's +		   the +		   duty of the master agent to collect the best answer and +		   return it +		   to the manager. See RFC 1227 chapter 3.1.6 for the glory +		   details +		   :-). ucd-snmp really behaves bad here as it actually might +		   ask +		   multiple times for the same GETNEXT request as it throws away +		   the +		   answer when it expects it in a different subtree and might +		   come +		   back later with the very same request. --jochen */ + +		if (subresult <= 0) { +			/* Prepare suffix. */ +			suffix = reqid + subtree->name_len; +			suffix_len = *reqid_len - subtree->name_len; +			if (subresult < 0) { +				oid_copy(reqid, subtree->name, +					 subtree->name_len); +				*reqid_len = subtree->name_len; +			} +			for (j = 0; j < subtree->variables_num; j++) { +				result = subresult; +				v = &subtree->variables[j]; + +				/* Next then check result >= 0. */ +				if (result == 0) +					result = oid_compare_part( +						suffix, suffix_len, v->name, +						v->namelen); + +				if (result <= 0) { +					if (debug_smux) +						zlog_debug( +							"SMUX function call index is %d", +							v->magic); +					if (result < 0) { +						oid_copy(suffix, v->name, +							 v->namelen); +						suffix_len = v->namelen; +					} +					*val = (*v->findVar)( +						v, suffix, &suffix_len, exact, +						val_len, &write_method); +					*reqid_len = +						suffix_len + subtree->name_len; +					if (*val) { +						*val_type = v->type; +						return 0; +					} +				} +			}  		} -	    }  	} -    } -  memcpy (reqid, save, savelen * sizeof(oid)); -  *reqid_len = savelen; +	memcpy(reqid, save, savelen * sizeof(oid)); +	*reqid_len = savelen; -  return SNMP_ERR_NOSUCHNAME; +	return SNMP_ERR_NOSUCHNAME;  }  /* GET message header. */ -static u_char * -smux_parse_get_header (u_char *ptr, size_t *len, long *reqid) +static u_char *smux_parse_get_header(u_char *ptr, size_t *len, long *reqid)  { -  u_char type; -  long errstat; -  long errindex; +	u_char type; +	long errstat; +	long errindex; -  /* Request ID. */ -  ptr = asn_parse_int (ptr, len, &type, reqid, sizeof (*reqid)); +	/* Request ID. */ +	ptr = asn_parse_int(ptr, len, &type, reqid, sizeof(*reqid)); -  if (debug_smux) -    zlog_debug ("SMUX GET reqid: %d len: %d", (int) *reqid, (int) *len); +	if (debug_smux) +		zlog_debug("SMUX GET reqid: %d len: %d", (int)*reqid, +			   (int)*len); -  /* Error status. */ -  ptr = asn_parse_int (ptr, len, &type, &errstat, sizeof (errstat)); +	/* Error status. */ +	ptr = asn_parse_int(ptr, len, &type, &errstat, sizeof(errstat)); -  if (debug_smux) -    zlog_debug ("SMUX GET errstat %ld len: %zd", errstat, *len); +	if (debug_smux) +		zlog_debug("SMUX GET errstat %ld len: %zd", errstat, *len); -  /* Error index. */ -  ptr = asn_parse_int (ptr, len, &type, &errindex, sizeof (errindex)); +	/* Error index. */ +	ptr = asn_parse_int(ptr, len, &type, &errindex, sizeof(errindex)); -  if (debug_smux) -    zlog_debug ("SMUX GET errindex %ld len: %zd", errindex, *len); +	if (debug_smux) +		zlog_debug("SMUX GET errindex %ld len: %zd", errindex, *len); -  return ptr; +	return ptr;  } -static void -smux_parse_set (u_char *ptr, size_t len, int action) +static void smux_parse_set(u_char *ptr, size_t len, int action)  { -  long reqid; -  oid oid[MAX_OID_LEN]; -  size_t oid_len; -  u_char val_type; -  void *val; -  size_t val_len; -  int ret; - -  if (debug_smux) -    zlog_debug ("SMUX SET(%s) message parse: len %zd", -               (RESERVE1 == action) ? "RESERVE1" : ((FREE == action) ? "FREE" : "COMMIT"), -               len); - -  /* Parse SET message header. */ -  ptr = smux_parse_get_header (ptr, &len, &reqid); - -  /* Parse SET message object ID. */ -  ptr = smux_var (ptr, len, oid, &oid_len, &val_len, &val_type, &val); - -  ret = smux_set (oid, &oid_len, val_type, val, val_len, action); -  if (debug_smux) -    zlog_debug ("SMUX SET ret %d", ret); - -  /* Return result. */ -  if (RESERVE1 == action) -    smux_getresp_send (oid, oid_len, reqid, ret, 3, ASN_NULL, NULL, 0); +	long reqid; +	oid oid[MAX_OID_LEN]; +	size_t oid_len; +	u_char val_type; +	void *val; +	size_t val_len; +	int ret; + +	if (debug_smux) +		zlog_debug("SMUX SET(%s) message parse: len %zd", +			   (RESERVE1 == action) +				   ? "RESERVE1" +				   : ((FREE == action) ? "FREE" : "COMMIT"), +			   len); + +	/* Parse SET message header. */ +	ptr = smux_parse_get_header(ptr, &len, &reqid); + +	/* Parse SET message object ID. */ +	ptr = smux_var(ptr, len, oid, &oid_len, &val_len, &val_type, &val); + +	ret = smux_set(oid, &oid_len, val_type, val, val_len, action); +	if (debug_smux) +		zlog_debug("SMUX SET ret %d", ret); + +	/* Return result. */ +	if (RESERVE1 == action) +		smux_getresp_send(oid, oid_len, reqid, ret, 3, ASN_NULL, NULL, +				  0);  } -static void -smux_parse_get (u_char *ptr, size_t len, int exact) +static void smux_parse_get(u_char *ptr, size_t len, int exact)  { -  long reqid; -  oid oid[MAX_OID_LEN]; -  size_t oid_len; -  u_char val_type; -  void *val; -  size_t val_len; -  int ret; - -  if (debug_smux) -    zlog_debug ("SMUX GET message parse: len %zd", len); -   -  /* Parse GET message header. */ -  ptr = smux_parse_get_header (ptr, &len, &reqid); -   -  /* Parse GET message object ID. We needn't the value come */ -  ptr = smux_var (ptr, len, oid, &oid_len, NULL, NULL, NULL); - -  /* Traditional getstatptr. */ -  if (exact) -    ret = smux_get (oid, &oid_len, exact, &val_type, &val, &val_len); -  else -    ret = smux_getnext (oid, &oid_len, exact, &val_type, &val, &val_len); - -  /* Return result. */ -  if (ret == 0) -    smux_getresp_send (oid, oid_len, reqid, 0, 0, val_type, val, val_len); -  else -    smux_getresp_send (oid, oid_len, reqid, ret, 3, ASN_NULL, NULL, 0); +	long reqid; +	oid oid[MAX_OID_LEN]; +	size_t oid_len; +	u_char val_type; +	void *val; +	size_t val_len; +	int ret; + +	if (debug_smux) +		zlog_debug("SMUX GET message parse: len %zd", len); + +	/* Parse GET message header. */ +	ptr = smux_parse_get_header(ptr, &len, &reqid); + +	/* Parse GET message object ID. We needn't the value come */ +	ptr = smux_var(ptr, len, oid, &oid_len, NULL, NULL, NULL); + +	/* Traditional getstatptr. */ +	if (exact) +		ret = smux_get(oid, &oid_len, exact, &val_type, &val, &val_len); +	else +		ret = smux_getnext(oid, &oid_len, exact, &val_type, &val, +				   &val_len); + +	/* Return result. */ +	if (ret == 0) +		smux_getresp_send(oid, oid_len, reqid, 0, 0, val_type, val, +				  val_len); +	else +		smux_getresp_send(oid, oid_len, reqid, ret, 3, ASN_NULL, NULL, +				  0);  }  /* Parse SMUX_CLOSE message. */ -static void -smux_parse_close (u_char *ptr, int len) +static void smux_parse_close(u_char *ptr, int len)  { -  long reason = 0; - -  while (len--) -    { -      reason = (reason << 8) | (long) *ptr; -      ptr++; -    } -  zlog_info ("SMUX_CLOSE with reason: %ld", reason); +	long reason = 0; + +	while (len--) { +		reason = (reason << 8) | (long)*ptr; +		ptr++; +	} +	zlog_info("SMUX_CLOSE with reason: %ld", reason);  }  /* SMUX_RRSP message. */ -static void -smux_parse_rrsp (u_char *ptr, size_t len) +static void smux_parse_rrsp(u_char *ptr, size_t len)  { -  u_char val; -  long errstat; -   -  ptr = asn_parse_int (ptr, &len, &val, &errstat, sizeof (errstat)); +	u_char val; +	long errstat; -  if (debug_smux) -    zlog_debug ("SMUX_RRSP value: %d errstat: %ld", val, errstat); +	ptr = asn_parse_int(ptr, &len, &val, &errstat, sizeof(errstat)); + +	if (debug_smux) +		zlog_debug("SMUX_RRSP value: %d errstat: %ld", val, errstat);  }  /* Parse SMUX message. */ -static int -smux_parse (u_char *ptr, size_t len) +static int smux_parse(u_char *ptr, size_t len)  { -  /* This buffer we'll use for SOUT message. We could allocate it with -     malloc and save only static pointer/lenght, but IMHO static -     buffer is a faster solusion. */ -  static u_char sout_save_buff[SMUXMAXPKTSIZE]; -  static int sout_save_len = 0; +	/* This buffer we'll use for SOUT message. We could allocate it with +	   malloc and save only static pointer/lenght, but IMHO static +	   buffer is a faster solusion. */ +	static u_char sout_save_buff[SMUXMAXPKTSIZE]; +	static int sout_save_len = 0; -  int len_income = len; /* see note below: YYY */ -  u_char type; -  u_char rollback; +	int len_income = len; /* see note below: YYY */ +	u_char type; +	u_char rollback; -  rollback = ptr[2]; /* important only for SMUX_SOUT */ +	rollback = ptr[2]; /* important only for SMUX_SOUT */  process_rest: /* see note below: YYY */ -  /* Parse SMUX message type and subsequent length. */ -  ptr = asn_parse_header (ptr, &len, &type); - -  if (debug_smux) -    zlog_debug ("SMUX message received type: %d rest len: %zd", type, len); - -  switch (type) -    { -    case SMUX_OPEN: -      /* Open must be not send from SNMP agent. */ -      zlog_warn ("SMUX_OPEN received: resetting connection."); -      return -1; -      break; -    case SMUX_RREQ: -      /* SMUX_RREQ message is invalid for us. */ -      zlog_warn ("SMUX_RREQ received: resetting connection."); -      return -1; -      break; -    case SMUX_SOUT: -      /* SMUX_SOUT message is now valied for us. */ -      if (debug_smux) -        zlog_debug ("SMUX_SOUT(%s)", rollback ? "rollback" : "commit"); - -      if (sout_save_len > 0) -        { -          smux_parse_set (sout_save_buff, sout_save_len, rollback ? FREE : COMMIT); -          sout_save_len = 0; -        } -      else -        zlog_warn ("SMUX_SOUT sout_save_len=%d - invalid", (int) sout_save_len); - -      if (len_income > 3)  -        { -          /* YYY: this strange code has to solve the "slow peer" -             problem: When agent sends SMUX_SOUT message it doesn't -             wait any responce and may send some next message to -             subagent. Then the peer in 'smux_read()' will recieve -             from socket the 'concatenated' buffer, contaning both -             SMUX_SOUT message and the next one -             (SMUX_GET/SMUX_GETNEXT/SMUX_GET). So we should check: if -             the buffer is longer than 3 ( length of SMUX_SOUT ), we -             must process the rest of it.  This effect may be observed -             if 'debug_smux' is set to '1' */ -          ptr++; -          len = len_income - 3; -          goto process_rest; -        } -      break; -    case SMUX_GETRSP: -      /* SMUX_GETRSP message is invalid for us. */ -      zlog_warn ("SMUX_GETRSP received: resetting connection."); -      return -1; -      break; -    case SMUX_CLOSE: -      /* Close SMUX connection. */ -      if (debug_smux) -	zlog_debug ("SMUX_CLOSE"); -      smux_parse_close (ptr, len); -      return -1; -      break; -    case SMUX_RRSP: -      /* This is response for register message. */ -      if (debug_smux) -	zlog_debug ("SMUX_RRSP"); -      smux_parse_rrsp (ptr, len); -      break; -    case SMUX_GET: -      /* Exact request for object id. */ -      if (debug_smux) -	zlog_debug ("SMUX_GET"); -      smux_parse_get (ptr, len, 1); -      break; -    case SMUX_GETNEXT: -      /* Next request for object id. */ -      if (debug_smux) -	zlog_debug ("SMUX_GETNEXT"); -      smux_parse_get (ptr, len, 0); -      break; -    case SMUX_SET: -      /* SMUX_SET is supported with some limitations. */ -      if (debug_smux) -	zlog_debug ("SMUX_SET"); - -      /* save the data for future SMUX_SOUT */ -      memcpy (sout_save_buff, ptr, len); -      sout_save_len = len; -      smux_parse_set (ptr, len, RESERVE1); -      break; -    default: -      zlog_info ("Unknown type: %d", type); -      break; -    } -  return 0; +	/* Parse SMUX message type and subsequent length. */ +	ptr = asn_parse_header(ptr, &len, &type); + +	if (debug_smux) +		zlog_debug("SMUX message received type: %d rest len: %zd", type, +			   len); + +	switch (type) { +	case SMUX_OPEN: +		/* Open must be not send from SNMP agent. */ +		zlog_warn("SMUX_OPEN received: resetting connection."); +		return -1; +		break; +	case SMUX_RREQ: +		/* SMUX_RREQ message is invalid for us. */ +		zlog_warn("SMUX_RREQ received: resetting connection."); +		return -1; +		break; +	case SMUX_SOUT: +		/* SMUX_SOUT message is now valied for us. */ +		if (debug_smux) +			zlog_debug("SMUX_SOUT(%s)", +				   rollback ? "rollback" : "commit"); + +		if (sout_save_len > 0) { +			smux_parse_set(sout_save_buff, sout_save_len, +				       rollback ? FREE : COMMIT); +			sout_save_len = 0; +		} else +			zlog_warn("SMUX_SOUT sout_save_len=%d - invalid", +				  (int)sout_save_len); + +		if (len_income > 3) { +			/* YYY: this strange code has to solve the "slow peer" +			   problem: When agent sends SMUX_SOUT message it +			   doesn't +			   wait any responce and may send some next message to +			   subagent. Then the peer in 'smux_read()' will recieve +			   from socket the 'concatenated' buffer, contaning both +			   SMUX_SOUT message and the next one +			   (SMUX_GET/SMUX_GETNEXT/SMUX_GET). So we should check: +			   if +			   the buffer is longer than 3 ( length of SMUX_SOUT ), +			   we +			   must process the rest of it.  This effect may be +			   observed +			   if 'debug_smux' is set to '1' */ +			ptr++; +			len = len_income - 3; +			goto process_rest; +		} +		break; +	case SMUX_GETRSP: +		/* SMUX_GETRSP message is invalid for us. */ +		zlog_warn("SMUX_GETRSP received: resetting connection."); +		return -1; +		break; +	case SMUX_CLOSE: +		/* Close SMUX connection. */ +		if (debug_smux) +			zlog_debug("SMUX_CLOSE"); +		smux_parse_close(ptr, len); +		return -1; +		break; +	case SMUX_RRSP: +		/* This is response for register message. */ +		if (debug_smux) +			zlog_debug("SMUX_RRSP"); +		smux_parse_rrsp(ptr, len); +		break; +	case SMUX_GET: +		/* Exact request for object id. */ +		if (debug_smux) +			zlog_debug("SMUX_GET"); +		smux_parse_get(ptr, len, 1); +		break; +	case SMUX_GETNEXT: +		/* Next request for object id. */ +		if (debug_smux) +			zlog_debug("SMUX_GETNEXT"); +		smux_parse_get(ptr, len, 0); +		break; +	case SMUX_SET: +		/* SMUX_SET is supported with some limitations. */ +		if (debug_smux) +			zlog_debug("SMUX_SET"); + +		/* save the data for future SMUX_SOUT */ +		memcpy(sout_save_buff, ptr, len); +		sout_save_len = len; +		smux_parse_set(ptr, len, RESERVE1); +		break; +	default: +		zlog_info("Unknown type: %d", type); +		break; +	} +	return 0;  }  /* SMUX message read function. */ -static int -smux_read (struct thread *t) +static int smux_read(struct thread *t)  { -  int sock; -  int len; -  u_char buf[SMUXMAXPKTSIZE]; -  int ret; - -  /* Clear thread. */ -  sock = THREAD_FD (t); -  smux_read_thread = NULL; - -  if (debug_smux) -    zlog_debug ("SMUX read start"); - -  /* Read message from SMUX socket. */ -  len = recv (sock, buf, SMUXMAXPKTSIZE, 0); - -  if (len < 0) -    { -      zlog_warn ("Can't read all SMUX packet: %s", safe_strerror (errno)); -      close (sock); -      smux_sock = -1; -      smux_event (SMUX_CONNECT, 0); -      return -1; -    } - -  if (len == 0) -    { -      zlog_warn ("SMUX connection closed: %d", sock); -      close (sock); -      smux_sock = -1; -      smux_event (SMUX_CONNECT, 0); -      return -1; -    } - -  if (debug_smux) -    zlog_debug ("SMUX read len: %d", len); - -  /* Parse the message. */ -  ret = smux_parse (buf, len); - -  if (ret < 0) -    { -      close (sock); -      smux_sock = -1; -      smux_event (SMUX_CONNECT, 0); -      return -1; -    } - -  /* Regiser read thread. */ -  smux_event (SMUX_READ, sock); - -  return 0; +	int sock; +	int len; +	u_char buf[SMUXMAXPKTSIZE]; +	int ret; + +	/* Clear thread. */ +	sock = THREAD_FD(t); +	smux_read_thread = NULL; + +	if (debug_smux) +		zlog_debug("SMUX read start"); + +	/* Read message from SMUX socket. */ +	len = recv(sock, buf, SMUXMAXPKTSIZE, 0); + +	if (len < 0) { +		zlog_warn("Can't read all SMUX packet: %s", +			  safe_strerror(errno)); +		close(sock); +		smux_sock = -1; +		smux_event(SMUX_CONNECT, 0); +		return -1; +	} + +	if (len == 0) { +		zlog_warn("SMUX connection closed: %d", sock); +		close(sock); +		smux_sock = -1; +		smux_event(SMUX_CONNECT, 0); +		return -1; +	} + +	if (debug_smux) +		zlog_debug("SMUX read len: %d", len); + +	/* Parse the message. */ +	ret = smux_parse(buf, len); + +	if (ret < 0) { +		close(sock); +		smux_sock = -1; +		smux_event(SMUX_CONNECT, 0); +		return -1; +	} + +	/* Regiser read thread. */ +	smux_event(SMUX_READ, sock); + +	return 0;  } -static int -smux_open (int sock) +static int smux_open(int sock)  { -  u_char buf[BUFSIZ]; -  u_char *ptr; -  size_t len; -  long version; -  const char progname[] = FRR_SMUX_NAME "-" FRR_VERSION; - -  if (debug_smux) -    { -      smux_oid_dump ("SMUX open oid", smux_oid, smux_oid_len); -      zlog_debug ("SMUX open progname: %s", progname); -      zlog_debug ("SMUX open password: %s", smux_passwd); -    } - -  ptr = buf; -  len = BUFSIZ; - -  /* SMUX Header.  As placeholder. */ -  ptr = asn_build_header (ptr, &len, (u_char) SMUX_OPEN, 0); - -  /* SMUX Open. */ -  version = 0; -  ptr = asn_build_int (ptr, &len,  -		       (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), -		       &version, sizeof (version)); - -  /* SMUX connection oid. */ -  ptr = asn_build_objid (ptr, &len, -			 (u_char)  -			 (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OBJECT_ID), -			 smux_oid, smux_oid_len); - -  /* SMUX connection description. */ -  ptr = asn_build_string (ptr, &len,  -			  (u_char) -			  (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OCTET_STR), -			  (const u_char *) progname, strlen (progname)); - -  /* SMUX connection password. */ -  ptr = asn_build_string (ptr, &len,  -			  (u_char) -			  (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OCTET_STR), -			  (u_char *)smux_passwd, strlen (smux_passwd)); - -  /* Fill in real SMUX header.  We exclude ASN header size (2). */ -  len = BUFSIZ; -  asn_build_header (buf, &len, (u_char) SMUX_OPEN, (ptr - buf) - 2); - -  return send (sock, buf, (ptr - buf), 0); +	u_char buf[BUFSIZ]; +	u_char *ptr; +	size_t len; +	long version; +	const char progname[] = FRR_SMUX_NAME "-" FRR_VERSION; + +	if (debug_smux) { +		smux_oid_dump("SMUX open oid", smux_oid, smux_oid_len); +		zlog_debug("SMUX open progname: %s", progname); +		zlog_debug("SMUX open password: %s", smux_passwd); +	} + +	ptr = buf; +	len = BUFSIZ; + +	/* SMUX Header.  As placeholder. */ +	ptr = asn_build_header(ptr, &len, (u_char)SMUX_OPEN, 0); + +	/* SMUX Open. */ +	version = 0; +	ptr = asn_build_int(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						| ASN_INTEGER), +			    &version, sizeof(version)); + +	/* SMUX connection oid. */ +	ptr = asn_build_objid(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						  | ASN_OBJECT_ID), +			      smux_oid, smux_oid_len); + +	/* SMUX connection description. */ +	ptr = asn_build_string(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						   | ASN_OCTET_STR), +			       (const u_char *)progname, strlen(progname)); + +	/* SMUX connection password. */ +	ptr = asn_build_string(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						   | ASN_OCTET_STR), +			       (u_char *)smux_passwd, strlen(smux_passwd)); + +	/* Fill in real SMUX header.  We exclude ASN header size (2). */ +	len = BUFSIZ; +	asn_build_header(buf, &len, (u_char)SMUX_OPEN, (ptr - buf) - 2); + +	return send(sock, buf, (ptr - buf), 0);  }  /* `ename` is ignored. Instead of using the provided enterprise OID, @@ -931,394 +916,372 @@ smux_open (int sock)     versions of Quagga.     All other fields are used as they are intended. */ -int -smux_trap (struct variable *vp, size_t vp_len, -	   const oid *ename, size_t enamelen, -	   const oid *name, size_t namelen, -	   const oid *iname, size_t inamelen, -	   const struct trap_object *trapobj, size_t trapobjlen, -	   u_char sptrap) +int smux_trap(struct variable *vp, size_t vp_len, const oid *ename, +	      size_t enamelen, const oid *name, size_t namelen, +	      const oid *iname, size_t inamelen, +	      const struct trap_object *trapobj, size_t trapobjlen, +	      u_char sptrap)  { -  unsigned int i; -  u_char buf[BUFSIZ]; -  u_char *ptr; -  size_t len, length; -  struct in_addr addr; -  unsigned long val; -  u_char *h1, *h1e; - -  ptr = buf; -  len = BUFSIZ; -  length = len; - -  /* When SMUX connection is not established. */ -  if (smux_sock < 0) -    return 0; - -  /* SMUX header. */ -  ptr = asn_build_header (ptr, &len, (u_char) SMUX_TRAP, 0); - -  /* Sub agent enterprise oid. */ -  ptr = asn_build_objid (ptr, &len, -			 (u_char)  -			 (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OBJECT_ID), -			 smux_oid, smux_oid_len); - -  /* IP address. */ -  addr.s_addr = 0; -  ptr = asn_build_string (ptr, &len,  -			  (u_char) -			  (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_IPADDRESS), -			  (u_char *)&addr, sizeof (addr)); - -  /* Generic trap integer. */ -  val = SNMP_TRAP_ENTERPRISESPECIFIC; -  ptr = asn_build_int (ptr, &len,  -		       (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), -		       (long *)&val, sizeof (val)); - -  /* Specific trap integer. */ -  val = sptrap; -  ptr = asn_build_int (ptr, &len,  -		       (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), -		       (long *)&val, sizeof (val)); - -  /* Timeticks timestamp. */ -  val = 0; -  ptr = asn_build_unsigned_int (ptr, &len,  -				(u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_TIMETICKS), -				&val, sizeof (val)); -   -  /* Variables. */ -  h1 = ptr; -  ptr = asn_build_sequence (ptr, &len,  -			    (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), -			    0); - - -  /* Iteration for each objects. */ -  h1e = ptr; -  for (i = 0; i < trapobjlen; i++) -    { -      int ret; -      oid oid[MAX_OID_LEN]; -      size_t oid_len; -      void *val; -      size_t val_len; -      u_char val_type; - -      /* Make OID. */ -      if (trapobj[i].namelen > 0)  -        { -          oid_copy (oid, name, namelen); -          oid_copy (oid + namelen, trapobj[i].name, trapobj[i].namelen); -          oid_copy (oid + namelen + trapobj[i].namelen, iname, inamelen); -          oid_len = namelen + trapobj[i].namelen + inamelen; -        } -      else  -        { -          oid_copy (oid, name, namelen); -          oid_copy (oid + namelen, trapobj[i].name, trapobj[i].namelen * (-1)); -          oid_len = namelen + trapobj[i].namelen * (-1) ; -        } - -      if (debug_smux)  -        { -          smux_oid_dump ("Trap", name, namelen); -          if (trapobj[i].namelen < 0) -            smux_oid_dump ("Trap",  -                           trapobj[i].name, (- 1) * (trapobj[i].namelen)); -          else  -            { -              smux_oid_dump ("Trap", trapobj[i].name, (trapobj[i].namelen)); -              smux_oid_dump ("Trap", iname, inamelen); -            } -          smux_oid_dump ("Trap", oid, oid_len); -          zlog_info ("BUFSIZ: %d // oid_len: %lu", BUFSIZ, (u_long)oid_len); -      } - -      ret = smux_get (oid, &oid_len, 1, &val_type, &val, &val_len); - -      if (debug_smux) -	zlog_debug ("smux_get result %d", ret); - -      if (ret == 0) -	ptr = snmp_build_var_op (ptr, oid, &oid_len, -				 val_type, val_len, val, &len); -    } - -  /* Now variable size is known, fill in size */ -  asn_build_sequence(h1, &length, -		     (u_char) (ASN_SEQUENCE | ASN_CONSTRUCTOR), -		     ptr - h1e); - -  /* Fill in size of whole sequence */ -  len = BUFSIZ; -  asn_build_header (buf, &len, (u_char) SMUX_TRAP, (ptr - buf) - 2); - -  return send (smux_sock, buf, (ptr - buf), 0); +	unsigned int i; +	u_char buf[BUFSIZ]; +	u_char *ptr; +	size_t len, length; +	struct in_addr addr; +	unsigned long val; +	u_char *h1, *h1e; + +	ptr = buf; +	len = BUFSIZ; +	length = len; + +	/* When SMUX connection is not established. */ +	if (smux_sock < 0) +		return 0; + +	/* SMUX header. */ +	ptr = asn_build_header(ptr, &len, (u_char)SMUX_TRAP, 0); + +	/* Sub agent enterprise oid. */ +	ptr = asn_build_objid(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						  | ASN_OBJECT_ID), +			      smux_oid, smux_oid_len); + +	/* IP address. */ +	addr.s_addr = 0; +	ptr = asn_build_string(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						   | ASN_IPADDRESS), +			       (u_char *)&addr, sizeof(addr)); + +	/* Generic trap integer. */ +	val = SNMP_TRAP_ENTERPRISESPECIFIC; +	ptr = asn_build_int(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						| ASN_INTEGER), +			    (long *)&val, sizeof(val)); + +	/* Specific trap integer. */ +	val = sptrap; +	ptr = asn_build_int(ptr, &len, (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE +						| ASN_INTEGER), +			    (long *)&val, sizeof(val)); + +	/* Timeticks timestamp. */ +	val = 0; +	ptr = asn_build_unsigned_int( +		ptr, &len, +		(u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_TIMETICKS), &val, +		sizeof(val)); + +	/* Variables. */ +	h1 = ptr; +	ptr = asn_build_sequence(ptr, &len, +				 (u_char)(ASN_SEQUENCE | ASN_CONSTRUCTOR), 0); + + +	/* Iteration for each objects. */ +	h1e = ptr; +	for (i = 0; i < trapobjlen; i++) { +		int ret; +		oid oid[MAX_OID_LEN]; +		size_t oid_len; +		void *val; +		size_t val_len; +		u_char val_type; + +		/* Make OID. */ +		if (trapobj[i].namelen > 0) { +			oid_copy(oid, name, namelen); +			oid_copy(oid + namelen, trapobj[i].name, +				 trapobj[i].namelen); +			oid_copy(oid + namelen + trapobj[i].namelen, iname, +				 inamelen); +			oid_len = namelen + trapobj[i].namelen + inamelen; +		} else { +			oid_copy(oid, name, namelen); +			oid_copy(oid + namelen, trapobj[i].name, +				 trapobj[i].namelen * (-1)); +			oid_len = namelen + trapobj[i].namelen * (-1); +		} + +		if (debug_smux) { +			smux_oid_dump("Trap", name, namelen); +			if (trapobj[i].namelen < 0) +				smux_oid_dump("Trap", trapobj[i].name, +					      (-1) * (trapobj[i].namelen)); +			else { +				smux_oid_dump("Trap", trapobj[i].name, +					      (trapobj[i].namelen)); +				smux_oid_dump("Trap", iname, inamelen); +			} +			smux_oid_dump("Trap", oid, oid_len); +			zlog_info("BUFSIZ: %d // oid_len: %lu", BUFSIZ, +				  (u_long)oid_len); +		} + +		ret = smux_get(oid, &oid_len, 1, &val_type, &val, &val_len); + +		if (debug_smux) +			zlog_debug("smux_get result %d", ret); + +		if (ret == 0) +			ptr = snmp_build_var_op(ptr, oid, &oid_len, val_type, +						val_len, val, &len); +	} + +	/* Now variable size is known, fill in size */ +	asn_build_sequence(h1, &length, +			   (u_char)(ASN_SEQUENCE | ASN_CONSTRUCTOR), ptr - h1e); + +	/* Fill in size of whole sequence */ +	len = BUFSIZ; +	asn_build_header(buf, &len, (u_char)SMUX_TRAP, (ptr - buf) - 2); + +	return send(smux_sock, buf, (ptr - buf), 0);  } -static int -smux_register (int sock) +static int smux_register(int sock)  { -  u_char buf[BUFSIZ]; -  u_char *ptr; -  int ret; -  size_t len; -  long priority; -  long operation; -  struct subtree *subtree; -  struct listnode *node, *nnode; - -  ret = 0; - -  for (ALL_LIST_ELEMENTS (treelist, node, nnode, subtree)) -    { -      ptr = buf; -      len = BUFSIZ; - -      /* SMUX RReq Header. */ -      ptr = asn_build_header (ptr, &len, (u_char) SMUX_RREQ, 0); - -      /* Register MIB tree. */ -      ptr = asn_build_objid (ptr, &len, -			    (u_char) -			    (ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OBJECT_ID), -			    subtree->name, subtree->name_len); - -      /* Priority. */ -      priority = -1; -      ptr = asn_build_int (ptr, &len,  -		          (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), -		          &priority, sizeof (priority)); - -      /* Operation. */ -      operation = 2; /* Register R/W */ -      ptr = asn_build_int (ptr, &len,  -		          (u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), -		          &operation, sizeof (operation)); - -      if (debug_smux) -        { -          smux_oid_dump ("SMUX register oid", subtree->name, subtree->name_len); -          zlog_debug ("SMUX register priority: %ld", priority); -          zlog_debug ("SMUX register operation: %ld", operation); -        } - -      len = BUFSIZ; -      asn_build_header (buf, &len, (u_char) SMUX_RREQ, (ptr - buf) - 2); -      ret = send (sock, buf, (ptr - buf), 0); -      if (ret < 0) -        return ret; -    } -  return ret; +	u_char buf[BUFSIZ]; +	u_char *ptr; +	int ret; +	size_t len; +	long priority; +	long operation; +	struct subtree *subtree; +	struct listnode *node, *nnode; + +	ret = 0; + +	for (ALL_LIST_ELEMENTS(treelist, node, nnode, subtree)) { +		ptr = buf; +		len = BUFSIZ; + +		/* SMUX RReq Header. */ +		ptr = asn_build_header(ptr, &len, (u_char)SMUX_RREQ, 0); + +		/* Register MIB tree. */ +		ptr = asn_build_objid( +			ptr, &len, +			(u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_OBJECT_ID), +			subtree->name, subtree->name_len); + +		/* Priority. */ +		priority = -1; +		ptr = asn_build_int( +			ptr, &len, +			(u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), +			&priority, sizeof(priority)); + +		/* Operation. */ +		operation = 2; /* Register R/W */ +		ptr = asn_build_int( +			ptr, &len, +			(u_char)(ASN_UNIVERSAL | ASN_PRIMITIVE | ASN_INTEGER), +			&operation, sizeof(operation)); + +		if (debug_smux) { +			smux_oid_dump("SMUX register oid", subtree->name, +				      subtree->name_len); +			zlog_debug("SMUX register priority: %ld", priority); +			zlog_debug("SMUX register operation: %ld", operation); +		} + +		len = BUFSIZ; +		asn_build_header(buf, &len, (u_char)SMUX_RREQ, (ptr - buf) - 2); +		ret = send(sock, buf, (ptr - buf), 0); +		if (ret < 0) +			return ret; +	} +	return ret;  }  /* Try to connect to SNMP agent. */ -static int -smux_connect (struct thread *t) +static int smux_connect(struct thread *t)  { -  int ret; - -  if (debug_smux) -    zlog_debug ("SMUX connect try %d", fail + 1); - -  /* Clear thread poner of myself. */ -  smux_connect_thread = NULL; - -  /* Make socket.  Try to connect. */ -  smux_sock = smux_socket (); -  if (smux_sock < 0) -    { -      if (++fail < SMUX_MAX_FAILURE) -	smux_event (SMUX_CONNECT, 0); -      return 0; -    } - -  /* Send OPEN PDU. */ -  ret = smux_open (smux_sock); -  if (ret < 0) -    { -      zlog_warn ("SMUX open message send failed: %s", safe_strerror (errno)); -      close (smux_sock); -      smux_sock = -1; -      if (++fail < SMUX_MAX_FAILURE) -	smux_event (SMUX_CONNECT, 0); -      return -1; -    } - -  /* Send any outstanding register PDUs. */ -  ret = smux_register (smux_sock); -  if (ret < 0) -    { -      zlog_warn ("SMUX register message send failed: %s", safe_strerror (errno)); -      close (smux_sock); -      smux_sock = -1; -      if (++fail < SMUX_MAX_FAILURE) -	smux_event (SMUX_CONNECT, 0); -      return -1; -    } - -  /* Everything goes fine. */ -  smux_event (SMUX_READ, smux_sock); - -  return 0; +	int ret; + +	if (debug_smux) +		zlog_debug("SMUX connect try %d", fail + 1); + +	/* Clear thread poner of myself. */ +	smux_connect_thread = NULL; + +	/* Make socket.  Try to connect. */ +	smux_sock = smux_socket(); +	if (smux_sock < 0) { +		if (++fail < SMUX_MAX_FAILURE) +			smux_event(SMUX_CONNECT, 0); +		return 0; +	} + +	/* Send OPEN PDU. */ +	ret = smux_open(smux_sock); +	if (ret < 0) { +		zlog_warn("SMUX open message send failed: %s", +			  safe_strerror(errno)); +		close(smux_sock); +		smux_sock = -1; +		if (++fail < SMUX_MAX_FAILURE) +			smux_event(SMUX_CONNECT, 0); +		return -1; +	} + +	/* Send any outstanding register PDUs. */ +	ret = smux_register(smux_sock); +	if (ret < 0) { +		zlog_warn("SMUX register message send failed: %s", +			  safe_strerror(errno)); +		close(smux_sock); +		smux_sock = -1; +		if (++fail < SMUX_MAX_FAILURE) +			smux_event(SMUX_CONNECT, 0); +		return -1; +	} + +	/* Everything goes fine. */ +	smux_event(SMUX_READ, smux_sock); + +	return 0;  }  /* Clear all SMUX related resources. */ -static void -smux_stop (void) +static void smux_stop(void)  { -  if (smux_read_thread) -    { -      thread_cancel (smux_read_thread); -      smux_read_thread = NULL; -    } - -  if (smux_connect_thread) -    { -      thread_cancel (smux_connect_thread); -      smux_connect_thread = NULL; -    } - -  if (smux_sock >= 0) -    { -      close (smux_sock); -      smux_sock = -1; -    } -} +	if (smux_read_thread) { +		thread_cancel(smux_read_thread); +		smux_read_thread = NULL; +	} +	if (smux_connect_thread) { +		thread_cancel(smux_connect_thread); +		smux_connect_thread = NULL; +	} +	if (smux_sock >= 0) { +		close(smux_sock); +		smux_sock = -1; +	} +} -void -smux_event (enum smux_event event, int sock) + +void smux_event(enum smux_event event, int sock)  { -  switch (event) -    { -    case SMUX_SCHEDULE: -      smux_connect_thread = thread_add_event (smux_master, smux_connect, NULL, 0); -      break; -    case SMUX_CONNECT: -      smux_connect_thread = thread_add_timer (smux_master, smux_connect, NULL, 10); -      break; -    case SMUX_READ: -      smux_read_thread = thread_add_read (smux_master, smux_read, NULL, sock); -      break; -    default: -      break; -    } +	switch (event) { +	case SMUX_SCHEDULE: +		smux_connect_thread = +			thread_add_event(smux_master, smux_connect, NULL, 0); +		break; +	case SMUX_CONNECT: +		smux_connect_thread = +			thread_add_timer(smux_master, smux_connect, NULL, 10); +		break; +	case SMUX_READ: +		smux_read_thread = +			thread_add_read(smux_master, smux_read, NULL, sock); +		break; +	default: +		break; +	}  } -static int -smux_str2oid (const char *str, oid *oid, size_t *oid_len) +static int smux_str2oid(const char *str, oid *oid, size_t *oid_len)  { -  int len; -  int val; - -  len = 0; -  val = 0; -  *oid_len = 0; - -  if (*str == '.') -    str++; -  if (*str == '\0') -    return 0; - -  while (1) -    { -      if (! isdigit (*str)) -	return -1; - -      while (isdigit (*str)) -	{ -	  val *= 10; -	  val += (*str - '0'); -	  str++; -	} +	int len; +	int val; + +	len = 0; +	val = 0; +	*oid_len = 0; + +	if (*str == '.') +		str++; +	if (*str == '\0') +		return 0; + +	while (1) { +		if (!isdigit(*str)) +			return -1; + +		while (isdigit(*str)) { +			val *= 10; +			val += (*str - '0'); +			str++; +		} -      if (*str == '\0') -	break; -      if (*str != '.') -	return -1; +		if (*str == '\0') +			break; +		if (*str != '.') +			return -1; -      oid[len++] = val; -      val = 0; -      str++; -    } +		oid[len++] = val; +		val = 0; +		str++; +	} -  oid[len++] = val; -  *oid_len = len; +	oid[len++] = val; +	*oid_len = len; -  return 0; +	return 0;  } -static oid * -smux_oid_dup (oid *objid, size_t objid_len) +static oid *smux_oid_dup(oid *objid, size_t objid_len)  { -  oid *new; +	oid *new; -  new = XMALLOC (MTYPE_TMP, sizeof (oid) * objid_len); -  oid_copy (new, objid, objid_len); +	new = XMALLOC(MTYPE_TMP, sizeof(oid) * objid_len); +	oid_copy(new, objid, objid_len); -  return new; +	return new;  } -static int -smux_peer_oid (struct vty *vty, const char *oid_str, const char *passwd_str) +static int smux_peer_oid(struct vty *vty, const char *oid_str, +			 const char *passwd_str)  { -  int ret; -  oid oid[MAX_OID_LEN]; -  size_t oid_len; - -  ret = smux_str2oid (oid_str, oid, &oid_len); -  if (ret != 0) -    { -      vty_out (vty, "object ID malformed%s", VTY_NEWLINE); -      return CMD_WARNING; -    } - -  if (smux_oid) -    { -      free (smux_oid); -      smux_oid = NULL; -    } - -  /* careful, smux_passwd might point to string constant */ -  if (smux_passwd) -    { -      free (smux_passwd); -      smux_passwd = NULL; -    } - -  smux_oid = smux_oid_dup (oid, oid_len); -  smux_oid_len = oid_len; - -  if (passwd_str) -    smux_passwd = strdup (passwd_str); -  else -    smux_passwd = strdup (""); - -  return 0; +	int ret; +	oid oid[MAX_OID_LEN]; +	size_t oid_len; + +	ret = smux_str2oid(oid_str, oid, &oid_len); +	if (ret != 0) { +		vty_out(vty, "object ID malformed%s", VTY_NEWLINE); +		return CMD_WARNING; +	} + +	if (smux_oid) { +		free(smux_oid); +		smux_oid = NULL; +	} + +	/* careful, smux_passwd might point to string constant */ +	if (smux_passwd) { +		free(smux_passwd); +		smux_passwd = NULL; +	} + +	smux_oid = smux_oid_dup(oid, oid_len); +	smux_oid_len = oid_len; + +	if (passwd_str) +		smux_passwd = strdup(passwd_str); +	else +		smux_passwd = strdup(""); + +	return 0;  } -static int -smux_peer_default (void) +static int smux_peer_default(void)  { -  if (smux_oid) -    { -      free (smux_oid); -      smux_oid = NULL; -    } -   -  /* careful, smux_passwd might be pointing at string constant */ -  if (smux_passwd) -    { -      free (smux_passwd); -      smux_passwd = NULL; -    } - -  return CMD_SUCCESS; +	if (smux_oid) { +		free(smux_oid); +		smux_oid = NULL; +	} + +	/* careful, smux_passwd might be pointing at string constant */ +	if (smux_passwd) { +		free(smux_passwd); +		smux_passwd = NULL; +	} + +	return CMD_SUCCESS;  }  DEFUN (smux_peer, @@ -1328,14 +1291,12 @@ DEFUN (smux_peer,         "SNMP MUX peer settings\n"         "Object ID used in SMUX peering\n")  { -  int idx_oid = 2; -  if (smux_peer_oid (vty, argv[idx_oid]->arg, NULL) == 0) -    { -      smux_start(); -      return CMD_SUCCESS; -    } -  else -    return CMD_WARNING; +	int idx_oid = 2; +	if (smux_peer_oid(vty, argv[idx_oid]->arg, NULL) == 0) { +		smux_start(); +		return CMD_SUCCESS; +	} else +		return CMD_WARNING;  }  DEFUN (smux_peer_password, @@ -1346,14 +1307,12 @@ DEFUN (smux_peer_password,         "SMUX peering object ID\n"         "SMUX peering password\n")  { -  int idx_oid = 2; -  if (smux_peer_oid (vty, argv[idx_oid]->arg, argv[3]->rg) == 0) -    { -      smux_start(); -      return CMD_SUCCESS; -    } -  else -    return CMD_WARNING; +	int idx_oid = 2; +	if (smux_peer_oid(vty, argv[idx_oid]->arg, argv[3]->rg) == 0) { +		smux_start(); +		return CMD_SUCCESS; +	} else +		return CMD_WARNING;  }  DEFUN (no_smux_peer, @@ -1365,84 +1324,77 @@ DEFUN (no_smux_peer,         "SMUX peering object ID\n"         "SMUX peering password\n")  { -  smux_stop(); -  return smux_peer_default (); +	smux_stop(); +	return smux_peer_default();  } -static int -config_write_smux (struct vty *vty) +static int config_write_smux(struct vty *vty)  { -  int first = 1; -  unsigned int i; - -  if (smux_oid) -    { -      vty_out (vty, "smux peer "); -      for (i = 0; i < smux_oid_len; i++) -	{ -	  vty_out (vty, "%s%d", first ? "" : ".", (int) smux_oid[i]); -	  first = 0; +	int first = 1; +	unsigned int i; + +	if (smux_oid) { +		vty_out(vty, "smux peer "); +		for (i = 0; i < smux_oid_len; i++) { +			vty_out(vty, "%s%d", first ? "" : ".", +				(int)smux_oid[i]); +			first = 0; +		} +		vty_out(vty, " %s%s", smux_passwd, VTY_NEWLINE);  	} -      vty_out (vty, " %s%s", smux_passwd, VTY_NEWLINE); -    } -  return 0; +	return 0;  }  /* Register subtree to smux master tree. */ -void -smux_register_mib (const char *descr, struct variable *var,  -                   size_t width, int num,  -		   oid name[], size_t namelen) +void smux_register_mib(const char *descr, struct variable *var, size_t width, +		       int num, oid name[], size_t namelen)  { -  struct subtree *tree; - -  tree = (struct subtree *)malloc(sizeof(struct subtree)); -  oid_copy (tree->name, name, namelen); -  tree->name_len = namelen; -  tree->variables = var; -  tree->variables_num = num; -  tree->variables_width = width; -  tree->registered = 0; -  listnode_add_sort(treelist, tree); +	struct subtree *tree; + +	tree = (struct subtree *)malloc(sizeof(struct subtree)); +	oid_copy(tree->name, name, namelen); +	tree->name_len = namelen; +	tree->variables = var; +	tree->variables_num = num; +	tree->variables_width = width; +	tree->registered = 0; +	listnode_add_sort(treelist, tree);  }  /* Compare function to keep treelist sorted */ -static int -smux_tree_cmp(struct subtree *tree1, struct subtree *tree2) +static int smux_tree_cmp(struct subtree *tree1, struct subtree *tree2)  { -  return oid_compare(tree1->name, tree1->name_len,  -		     tree2->name, tree2->name_len); +	return oid_compare(tree1->name, tree1->name_len, tree2->name, +			   tree2->name_len);  }  /* Initialize some values then schedule first SMUX connection. */ -void -smux_init (struct thread_master *tm) +void smux_init(struct thread_master *tm)  { -  assert (tm); -  /* copy callers thread master */ -  smux_master = tm; -   -  /* Make MIB tree. */ -  treelist = list_new(); -  treelist->cmp = (int (*)(void *, void *))smux_tree_cmp; - -  /* Install commands. */ -  install_node (&smux_node, config_write_smux); - -  install_element (CONFIG_NODE, &smux_peer_cmd); -  install_element (CONFIG_NODE, &smux_peer_password_cmd); -  install_element (CONFIG_NODE, &no_smux_peer_cmd); -  install_element (CONFIG_NODE, &no_smux_peer_oid_cmd); -  install_element (CONFIG_NODE, &no_smux_peer_oid_password_cmd); +	assert(tm); +	/* copy callers thread master */ +	smux_master = tm; + +	/* Make MIB tree. */ +	treelist = list_new(); +	treelist->cmp = (int (*)(void *, void *))smux_tree_cmp; + +	/* Install commands. */ +	install_node(&smux_node, config_write_smux); + +	install_element(CONFIG_NODE, &smux_peer_cmd); +	install_element(CONFIG_NODE, &smux_peer_password_cmd); +	install_element(CONFIG_NODE, &no_smux_peer_cmd); +	install_element(CONFIG_NODE, &no_smux_peer_oid_cmd); +	install_element(CONFIG_NODE, &no_smux_peer_oid_password_cmd);  } -void -smux_start(void) +void smux_start(void)  { -  /* Close any existing connections. */ -  smux_stop(); +	/* Close any existing connections. */ +	smux_stop(); -  /* Schedule first connection. */ -  smux_event (SMUX_SCHEDULE, 0); +	/* Schedule first connection. */ +	smux_event(SMUX_SCHEDULE, 0);  }  #endif /* SNMP_SMUX */ diff --git a/lib/smux.h b/lib/smux.h index dc91cac71a..0d76fc32bb 100644 --- a/lib/smux.h +++ b/lib/smux.h @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_SNMP_H @@ -42,43 +42,37 @@  #define IN_ADDR_SIZE sizeof(struct in_addr)  #undef REGISTER_MIB -#define REGISTER_MIB(descr, var, vartype, theoid)		\ -    smux_register_mib(descr, (struct variable *)var, sizeof(struct vartype), \ -    sizeof(var)/sizeof(struct vartype),			\ -    theoid, sizeof(theoid)/sizeof(oid)) - -struct trap_object -{ -  int namelen; /* Negative if the object is not indexed */ -  oid name[MAX_OID_LEN]; +#define REGISTER_MIB(descr, var, vartype, theoid)                              \ +	smux_register_mib(descr, (struct variable *)var,                       \ +			  sizeof(struct vartype),                              \ +			  sizeof(var) / sizeof(struct vartype), theoid,        \ +			  sizeof(theoid) / sizeof(oid)) + +struct trap_object { +	int namelen; /* Negative if the object is not indexed */ +	oid name[MAX_OID_LEN];  };  /* Declare SMUX return value. */ -#define SNMP_LOCAL_VARIABLES \ -  static long snmp_int_val __attribute__ ((unused)); \ -  static struct in_addr snmp_in_addr_val __attribute__ ((unused)); - -#define SNMP_INTEGER(V) \ -  ( \ -    *var_len = sizeof (snmp_int_val), \ -    snmp_int_val = V, \ -    (u_char *) &snmp_int_val \ -  ) - -#define SNMP_IPADDRESS(V) \ -  ( \ -    *var_len = sizeof (struct in_addr), \ -    snmp_in_addr_val = V, \ -    (u_char *) &snmp_in_addr_val \ -  ) - -extern void smux_init (struct thread_master *tm); -extern void smux_register_mib(const char *, struct variable *,  -                              size_t, int, oid [], size_t); -extern int smux_header_generic (struct variable *, oid [], size_t *,  -                                int, size_t *, WriteMethod **); -extern int smux_header_table (struct variable *, oid *, size_t *,  -			      int, size_t *, WriteMethod **); +#define SNMP_LOCAL_VARIABLES                                                   \ +	static long snmp_int_val __attribute__((unused));                      \ +	static struct in_addr snmp_in_addr_val __attribute__((unused)); + +#define SNMP_INTEGER(V)                                                        \ +	(*var_len = sizeof(snmp_int_val), snmp_int_val = V,                    \ +	 (u_char *)&snmp_int_val) + +#define SNMP_IPADDRESS(V)                                                      \ +	(*var_len = sizeof(struct in_addr), snmp_in_addr_val = V,              \ +	 (u_char *)&snmp_in_addr_val) + +extern void smux_init(struct thread_master *tm); +extern void smux_register_mib(const char *, struct variable *, size_t, int, +			      oid[], size_t); +extern int smux_header_generic(struct variable *, oid[], size_t *, int, +			       size_t *, WriteMethod **); +extern int smux_header_table(struct variable *, oid *, size_t *, int, size_t *, +			     WriteMethod **);  /* For traps, three OID are provided: @@ -101,16 +95,13 @@ extern int smux_header_table (struct variable *, oid *, size_t *,   The use of the arguments may differ depending on the implementation   used.  */ -extern int smux_trap (struct variable *, size_t, -		      const oid *, size_t, -		      const oid *, size_t, -		      const oid *, size_t, -		      const struct trap_object *, size_t, -		      u_char); - -extern int oid_compare (const oid *, int, const oid *, int); -extern void oid2in_addr (oid [], int, struct in_addr *); -extern void *oid_copy (void *, const void *, size_t); -extern void oid_copy_addr (oid [], struct in_addr *, int); +extern int smux_trap(struct variable *, size_t, const oid *, size_t, +		     const oid *, size_t, const oid *, size_t, +		     const struct trap_object *, size_t, u_char); + +extern int oid_compare(const oid *, int, const oid *, int); +extern void oid2in_addr(oid[], int, struct in_addr *); +extern void *oid_copy(void *, const void *, size_t); +extern void oid_copy_addr(oid[], struct in_addr *, int);  #endif /* _ZEBRA_SNMP_H */ diff --git a/lib/snmp.c b/lib/snmp.c index 1cbd41c720..c23a22931e 100644 --- a/lib/snmp.c +++ b/lib/snmp.c @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -28,104 +28,96 @@  #define min(A,B) ((A) < (B) ? (A) : (B)) -int -oid_compare (const oid *o1, int o1_len, const oid *o2, int o2_len) +int oid_compare(const oid *o1, int o1_len, const oid *o2, int o2_len)  { -  int i; - -  for (i = 0; i < min (o1_len, o2_len); i++) -    { -      if (o1[i] < o2[i]) -	return -1; -      else if (o1[i] > o2[i]) -	return 1; -    } -  if (o1_len < o2_len) -    return -1; -  if (o1_len > o2_len) -    return 1; - -  return 0; +	int i; + +	for (i = 0; i < min(o1_len, o2_len); i++) { +		if (o1[i] < o2[i]) +			return -1; +		else if (o1[i] > o2[i]) +			return 1; +	} +	if (o1_len < o2_len) +		return -1; +	if (o1_len > o2_len) +		return 1; + +	return 0;  } -void * -oid_copy (void *dest, const void *src, size_t size) +void *oid_copy(void *dest, const void *src, size_t size)  { -  return memcpy (dest, src, size * sizeof (oid)); +	return memcpy(dest, src, size * sizeof(oid));  } -void -oid2in_addr (oid oid[], int len, struct in_addr *addr) +void oid2in_addr(oid oid[], int len, struct in_addr *addr)  { -  int i; -  u_char *pnt; -   -  if (len == 0) -    return; +	int i; +	u_char *pnt; -  pnt = (u_char *) addr; +	if (len == 0) +		return; -  for (i = 0; i < len; i++) -    *pnt++ = oid[i]; +	pnt = (u_char *)addr; + +	for (i = 0; i < len; i++) +		*pnt++ = oid[i];  } -void -oid_copy_addr (oid oid[], struct in_addr *addr, int len) +void oid_copy_addr(oid oid[], struct in_addr *addr, int len)  { -  int i; -  u_char *pnt; -   -  if (len == 0) -    return; +	int i; +	u_char *pnt; + +	if (len == 0) +		return; -  pnt = (u_char *) addr; +	pnt = (u_char *)addr; -  for (i = 0; i < len; i++) -    oid[i] = *pnt++; +	for (i = 0; i < len; i++) +		oid[i] = *pnt++;  } -int -smux_header_generic (struct variable *v, oid *name, size_t *length, int exact, -		     size_t *var_len, WriteMethod **write_method) +int smux_header_generic(struct variable *v, oid *name, size_t *length, +			int exact, size_t *var_len, WriteMethod **write_method)  { -  oid fulloid[MAX_OID_LEN]; -  int ret; +	oid fulloid[MAX_OID_LEN]; +	int ret; -  oid_copy (fulloid, v->name, v->namelen); -  fulloid[v->namelen] = 0; -  /* Check against full instance. */ -  ret = oid_compare (name, *length, fulloid, v->namelen + 1); +	oid_copy(fulloid, v->name, v->namelen); +	fulloid[v->namelen] = 0; +	/* Check against full instance. */ +	ret = oid_compare(name, *length, fulloid, v->namelen + 1); -  /* Check single instance. */ -  if ((exact && (ret != 0)) || (!exact && (ret >= 0))) -	return MATCH_FAILED; +	/* Check single instance. */ +	if ((exact && (ret != 0)) || (!exact && (ret >= 0))) +		return MATCH_FAILED; -  /* In case of getnext, fill in full instance. */ -  memcpy (name, fulloid, (v->namelen + 1) * sizeof (oid)); -  *length = v->namelen + 1; +	/* In case of getnext, fill in full instance. */ +	memcpy(name, fulloid, (v->namelen + 1) * sizeof(oid)); +	*length = v->namelen + 1; -  *write_method = 0; -  *var_len = sizeof(long);    /* default to 'long' results */ +	*write_method = 0; +	*var_len = sizeof(long); /* default to 'long' results */ -  return MATCH_SUCCEEDED; +	return MATCH_SUCCEEDED;  } -int -smux_header_table (struct variable *v, oid *name, size_t *length, int exact, -		   size_t *var_len, WriteMethod **write_method) +int smux_header_table(struct variable *v, oid *name, size_t *length, int exact, +		      size_t *var_len, WriteMethod **write_method)  { -  /* If the requested OID name is less than OID prefix we -     handle, adjust it to our prefix. */ -  if ((oid_compare (name, *length, v->name, v->namelen)) < 0) -    { -      if (exact) -	return MATCH_FAILED; -      oid_copy(name, v->name, v->namelen); -      *length = v->namelen; -    } - -  *write_method = 0; -  *var_len = sizeof(long); - -  return MATCH_SUCCEEDED; +	/* If the requested OID name is less than OID prefix we +	   handle, adjust it to our prefix. */ +	if ((oid_compare(name, *length, v->name, v->namelen)) < 0) { +		if (exact) +			return MATCH_FAILED; +		oid_copy(name, v->name, v->namelen); +		*length = v->namelen; +	} + +	*write_method = 0; +	*var_len = sizeof(long); + +	return MATCH_SUCCEEDED;  } diff --git a/lib/sockopt.c b/lib/sockopt.c index 2a9f907cb3..6ef93ce916 100644 --- a/lib/sockopt.c +++ b/lib/sockopt.c @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -29,173 +29,168 @@  #include "sockopt.h"  #include "sockunion.h" -void -setsockopt_so_recvbuf (int sock, int size) +void setsockopt_so_recvbuf(int sock, int size)  { -  int orig_req = size; +	int orig_req = size; -  while (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof (size)) == -1) -    size /= 2; +	while (setsockopt(sock, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)) +	       == -1) +		size /= 2; -  if (size != orig_req) -    zlog_warn ("%s: fd %d: SO_RCVBUF set to %d (requested %d)", __func__, sock, -	       size, orig_req); +	if (size != orig_req) +		zlog_warn("%s: fd %d: SO_RCVBUF set to %d (requested %d)", +			  __func__, sock, size, orig_req);  } -void -setsockopt_so_sendbuf (const int sock, int size) +void setsockopt_so_sendbuf(const int sock, int size)  { -  int orig_req = size; +	int orig_req = size; -  while (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof (size)) == -1) -    size /= 2; +	while (setsockopt(sock, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size)) +	       == -1) +		size /= 2; -  if (size != orig_req) -    zlog_warn ("%s: fd %d: SO_SNDBUF set to %d (requested %d)", __func__, sock, -	       size, orig_req); +	if (size != orig_req) +		zlog_warn("%s: fd %d: SO_SNDBUF set to %d (requested %d)", +			  __func__, sock, size, orig_req);  } -int -getsockopt_so_sendbuf (const int sock) +int getsockopt_so_sendbuf(const int sock)  { -  u_int32_t optval; -  socklen_t optlen = sizeof (optval); -  int ret = getsockopt (sock, SOL_SOCKET, SO_SNDBUF, -    (char *)&optval, &optlen); -  if (ret < 0) -  { -    zlog_err ("fd %d: can't getsockopt SO_SNDBUF: %d (%s)", -      sock, errno, safe_strerror (errno)); -    return ret; -  } -  return optval; +	u_int32_t optval; +	socklen_t optlen = sizeof(optval); +	int ret = getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char *)&optval, +			     &optlen); +	if (ret < 0) { +		zlog_err("fd %d: can't getsockopt SO_SNDBUF: %d (%s)", sock, +			 errno, safe_strerror(errno)); +		return ret; +	} +	return optval;  } -static void * -getsockopt_cmsg_data (struct msghdr *msgh, int level, int type) +static void *getsockopt_cmsg_data(struct msghdr *msgh, int level, int type)  { -  struct cmsghdr *cmsg; -  void *ptr = NULL; -   -  for (cmsg = ZCMSG_FIRSTHDR(msgh);  -       cmsg != NULL; -       cmsg = CMSG_NXTHDR(msgh, cmsg)) -    if (cmsg->cmsg_level == level && cmsg->cmsg_type) -      return (ptr = CMSG_DATA(cmsg)); - -  return NULL; +	struct cmsghdr *cmsg; +	void *ptr = NULL; + +	for (cmsg = ZCMSG_FIRSTHDR(msgh); cmsg != NULL; +	     cmsg = CMSG_NXTHDR(msgh, cmsg)) +		if (cmsg->cmsg_level == level && cmsg->cmsg_type) +			return (ptr = CMSG_DATA(cmsg)); + +	return NULL;  }  /* Set IPv6 packet info to the socket. */ -int -setsockopt_ipv6_pktinfo (int sock, int val) +int setsockopt_ipv6_pktinfo(int sock, int val)  { -  int ret; -     -#ifdef IPV6_RECVPKTINFO		/*2292bis-01*/ -  ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, sizeof(val)); -  if (ret < 0) -    zlog_warn ("can't setsockopt IPV6_RECVPKTINFO : %s", safe_strerror (errno)); -#else	/*RFC2292*/ -  ret = setsockopt(sock, IPPROTO_IPV6, IPV6_PKTINFO, &val, sizeof(val)); -  if (ret < 0) -    zlog_warn ("can't setsockopt IPV6_PKTINFO : %s", safe_strerror (errno)); +	int ret; + +#ifdef IPV6_RECVPKTINFO /*2292bis-01*/ +	ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVPKTINFO, &val, +			 sizeof(val)); +	if (ret < 0) +		zlog_warn("can't setsockopt IPV6_RECVPKTINFO : %s", +			  safe_strerror(errno)); +#else  /*RFC2292*/ +	ret = setsockopt(sock, IPPROTO_IPV6, IPV6_PKTINFO, &val, sizeof(val)); +	if (ret < 0) +		zlog_warn("can't setsockopt IPV6_PKTINFO : %s", +			  safe_strerror(errno));  #endif /* INIA_IPV6 */ -  return ret; +	return ret;  }  /* Set multicast hops val to the socket. */ -int -setsockopt_ipv6_checksum (int sock, int val) +int setsockopt_ipv6_checksum(int sock, int val)  { -  int ret; +	int ret;  #ifdef GNU_LINUX -  ret = setsockopt(sock, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val)); +	ret = setsockopt(sock, IPPROTO_RAW, IPV6_CHECKSUM, &val, sizeof(val));  #else -  ret = setsockopt(sock, IPPROTO_IPV6, IPV6_CHECKSUM, &val, sizeof(val)); +	ret = setsockopt(sock, IPPROTO_IPV6, IPV6_CHECKSUM, &val, sizeof(val));  #endif /* GNU_LINUX */ -  if (ret < 0) -    zlog_warn ("can't setsockopt IPV6_CHECKSUM"); -  return ret; +	if (ret < 0) +		zlog_warn("can't setsockopt IPV6_CHECKSUM"); +	return ret;  }  /* Set multicast hops val to the socket. */ -int -setsockopt_ipv6_multicast_hops (int sock, int val) +int setsockopt_ipv6_multicast_hops(int sock, int val)  { -  int ret; +	int ret; -  ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, sizeof(val)); -  if (ret < 0) -    zlog_warn ("can't setsockopt IPV6_MULTICAST_HOPS"); -  return ret; +	ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, &val, +			 sizeof(val)); +	if (ret < 0) +		zlog_warn("can't setsockopt IPV6_MULTICAST_HOPS"); +	return ret;  }  /* Set multicast hops val to the socket. */ -int -setsockopt_ipv6_unicast_hops (int sock, int val) +int setsockopt_ipv6_unicast_hops(int sock, int val)  { -  int ret; +	int ret; -  ret = setsockopt(sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, sizeof(val)); -  if (ret < 0) -    zlog_warn ("can't setsockopt IPV6_UNICAST_HOPS"); -  return ret; +	ret = setsockopt(sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &val, +			 sizeof(val)); +	if (ret < 0) +		zlog_warn("can't setsockopt IPV6_UNICAST_HOPS"); +	return ret;  } -int -setsockopt_ipv6_hoplimit (int sock, int val) +int setsockopt_ipv6_hoplimit(int sock, int val)  { -  int ret; - -#ifdef IPV6_RECVHOPLIMIT	/*2292bis-01*/ -  ret = setsockopt (sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &val, sizeof(val)); -  if (ret < 0) -    zlog_warn ("can't setsockopt IPV6_RECVHOPLIMIT"); -#else	/*RFC2292*/ -  ret = setsockopt (sock, IPPROTO_IPV6, IPV6_HOPLIMIT, &val, sizeof(val)); -  if (ret < 0) -    zlog_warn ("can't setsockopt IPV6_HOPLIMIT"); +	int ret; + +#ifdef IPV6_RECVHOPLIMIT /*2292bis-01*/ +	ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVHOPLIMIT, &val, +			 sizeof(val)); +	if (ret < 0) +		zlog_warn("can't setsockopt IPV6_RECVHOPLIMIT"); +#else /*RFC2292*/ +	ret = setsockopt(sock, IPPROTO_IPV6, IPV6_HOPLIMIT, &val, sizeof(val)); +	if (ret < 0) +		zlog_warn("can't setsockopt IPV6_HOPLIMIT");  #endif -  return ret; +	return ret;  }  /* Set multicast loop zero to the socket. */ -int -setsockopt_ipv6_multicast_loop (int sock, int val) +int setsockopt_ipv6_multicast_loop(int sock, int val)  { -  int ret; -     -  ret = setsockopt (sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, -		    sizeof (val)); -  if (ret < 0) -    zlog_warn ("can't setsockopt IPV6_MULTICAST_LOOP"); -  return ret; +	int ret; + +	ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, &val, +			 sizeof(val)); +	if (ret < 0) +		zlog_warn("can't setsockopt IPV6_MULTICAST_LOOP"); +	return ret;  } -static int -getsockopt_ipv6_ifindex (struct msghdr *msgh) +static int getsockopt_ipv6_ifindex(struct msghdr *msgh)  { -  struct in6_pktinfo *pktinfo; -   -  pktinfo = getsockopt_cmsg_data (msgh, IPPROTO_IPV6, IPV6_PKTINFO); -   -  return pktinfo->ipi6_ifindex; +	struct in6_pktinfo *pktinfo; + +	pktinfo = getsockopt_cmsg_data(msgh, IPPROTO_IPV6, IPV6_PKTINFO); + +	return pktinfo->ipi6_ifindex;  } -int -setsockopt_ipv6_tclass(int sock, int tclass) +int setsockopt_ipv6_tclass(int sock, int tclass)  { -  int ret = 0; +	int ret = 0;  #ifdef IPV6_TCLASS /* RFC3542 */ -  ret = setsockopt (sock, IPPROTO_IPV6, IPV6_TCLASS, &tclass, sizeof (tclass)); -  if (ret < 0) -    zlog_warn ("Can't set IPV6_TCLASS option for fd %d to %#x: %s", -	       sock, tclass, safe_strerror(errno)); +	ret = setsockopt(sock, IPPROTO_IPV6, IPV6_TCLASS, &tclass, +			 sizeof(tclass)); +	if (ret < 0) +		zlog_warn("Can't set IPV6_TCLASS option for fd %d to %#x: %s", +			  sock, tclass, safe_strerror(errno));  #endif -  return ret; +	return ret;  }  /* @@ -219,238 +214,241 @@ setsockopt_ipv6_tclass(int sock, int tclass)   * but this behavior should not be harmful if they behave the same way,   * allow leaves, or implicitly leave all groups joined to down interfaces.   */ -int -setsockopt_ipv4_multicast(int sock, -			int optname,  -			struct in_addr if_addr, -			unsigned int mcast_addr, -			ifindex_t ifindex) +int setsockopt_ipv4_multicast(int sock, int optname, struct in_addr if_addr, +			      unsigned int mcast_addr, ifindex_t ifindex)  {  #ifdef HAVE_RFC3678 -  struct group_req gr; -  struct sockaddr_in *si; -  int ret; -  memset (&gr, 0, sizeof(gr)); -  si = (struct sockaddr_in *)&gr.gr_group; -  gr.gr_interface = ifindex; -  si->sin_family = AF_INET; +	struct group_req gr; +	struct sockaddr_in *si; +	int ret; +	memset(&gr, 0, sizeof(gr)); +	si = (struct sockaddr_in *)&gr.gr_group; +	gr.gr_interface = ifindex; +	si->sin_family = AF_INET;  #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN -  si->sin_len = sizeof(struct sockaddr_in); +	si->sin_len = sizeof(struct sockaddr_in);  #endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */ -  si->sin_addr.s_addr = mcast_addr; -  ret = setsockopt(sock, IPPROTO_IP, (optname == IP_ADD_MEMBERSHIP) ?  -    MCAST_JOIN_GROUP : MCAST_LEAVE_GROUP, (void *)&gr, sizeof(gr)); -  if ((ret < 0) && (optname == IP_ADD_MEMBERSHIP) && (errno == EADDRINUSE)) -    { -      setsockopt(sock, IPPROTO_IP, MCAST_LEAVE_GROUP, (void *)&gr, sizeof(gr)); -      ret = setsockopt(sock, IPPROTO_IP, MCAST_JOIN_GROUP, (void *)&gr, sizeof(gr)); -    } -  return ret; +	si->sin_addr.s_addr = mcast_addr; +	ret = setsockopt(sock, IPPROTO_IP, +			 (optname == IP_ADD_MEMBERSHIP) ? MCAST_JOIN_GROUP +							: MCAST_LEAVE_GROUP, +			 (void *)&gr, sizeof(gr)); +	if ((ret < 0) && (optname == IP_ADD_MEMBERSHIP) +	    && (errno == EADDRINUSE)) { +		setsockopt(sock, IPPROTO_IP, MCAST_LEAVE_GROUP, (void *)&gr, +			   sizeof(gr)); +		ret = setsockopt(sock, IPPROTO_IP, MCAST_JOIN_GROUP, +				 (void *)&gr, sizeof(gr)); +	} +	return ret;  #elif defined(HAVE_STRUCT_IP_MREQN_IMR_IFINDEX) && !defined(__FreeBSD__) -  struct ip_mreqn mreqn; -  int ret; -   -  assert(optname == IP_ADD_MEMBERSHIP || optname == IP_DROP_MEMBERSHIP); -  memset (&mreqn, 0, sizeof(mreqn)); - -  mreqn.imr_multiaddr.s_addr = mcast_addr; -  mreqn.imr_ifindex = ifindex; -   -  ret = setsockopt(sock, IPPROTO_IP, optname, -                   (void *)&mreqn, sizeof(mreqn)); -  if ((ret < 0) && (optname == IP_ADD_MEMBERSHIP) && (errno == EADDRINUSE)) -    { -      /* see above: handle possible problem when interface comes back up */ -      char buf[1][INET_ADDRSTRLEN]; -      zlog_info("setsockopt_ipv4_multicast attempting to drop and " -                "re-add (fd %d, mcast %s, ifindex %u)", -                sock, -                inet_ntop(AF_INET, &mreqn.imr_multiaddr, -                          buf[0], sizeof(buf[0])), ifindex); -      setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, -                 (void *)&mreqn, sizeof(mreqn)); -      ret = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, -                       (void *)&mreqn, sizeof(mreqn)); -    } -  return ret; - -  /* Example defines for another OS, boilerplate off other code in this -     function, AND handle optname as per other sections for consistency !! */ -  /* #elif  defined(BOGON_NIX) && EXAMPLE_VERSION_CODE > -100000 */ -  /* Add your favourite OS here! */ - -#elif defined(HAVE_BSD_STRUCT_IP_MREQ_HACK) /* #if OS_TYPE */  -  /* standard BSD API */ - -  struct ip_mreq mreq; -  int ret; - -  assert(optname == IP_ADD_MEMBERSHIP || optname == IP_DROP_MEMBERSHIP); - - -  memset (&mreq, 0, sizeof(mreq)); -  mreq.imr_multiaddr.s_addr = mcast_addr; +	struct ip_mreqn mreqn; +	int ret; + +	assert(optname == IP_ADD_MEMBERSHIP || optname == IP_DROP_MEMBERSHIP); +	memset(&mreqn, 0, sizeof(mreqn)); + +	mreqn.imr_multiaddr.s_addr = mcast_addr; +	mreqn.imr_ifindex = ifindex; + +	ret = setsockopt(sock, IPPROTO_IP, optname, (void *)&mreqn, +			 sizeof(mreqn)); +	if ((ret < 0) && (optname == IP_ADD_MEMBERSHIP) +	    && (errno == EADDRINUSE)) { +		/* see above: handle possible problem when interface comes back +		 * up */ +		char buf[1][INET_ADDRSTRLEN]; +		zlog_info( +			"setsockopt_ipv4_multicast attempting to drop and " +			"re-add (fd %d, mcast %s, ifindex %u)", +			sock, inet_ntop(AF_INET, &mreqn.imr_multiaddr, buf[0], +					sizeof(buf[0])), +			ifindex); +		setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, (void *)&mreqn, +			   sizeof(mreqn)); +		ret = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, +				 (void *)&mreqn, sizeof(mreqn)); +	} +	return ret; + +/* Example defines for another OS, boilerplate off other code in this +   function, AND handle optname as per other sections for consistency !! */ +/* #elif  defined(BOGON_NIX) && EXAMPLE_VERSION_CODE > -100000 */ +/* Add your favourite OS here! */ + +#elif defined(HAVE_BSD_STRUCT_IP_MREQ_HACK) /* #if OS_TYPE */ +	/* standard BSD API */ + +	struct ip_mreq mreq; +	int ret; + +	assert(optname == IP_ADD_MEMBERSHIP || optname == IP_DROP_MEMBERSHIP); + + +	memset(&mreq, 0, sizeof(mreq)); +	mreq.imr_multiaddr.s_addr = mcast_addr;  #if !defined __OpenBSD__ -  mreq.imr_interface.s_addr = htonl (ifindex); +	mreq.imr_interface.s_addr = htonl(ifindex);  #else -  mreq.imr_interface.s_addr = if_addr.s_addr; +	mreq.imr_interface.s_addr = if_addr.s_addr;  #endif -  ret = setsockopt (sock, IPPROTO_IP, optname, (void *)&mreq, sizeof(mreq)); -  if ((ret < 0) && (optname == IP_ADD_MEMBERSHIP) && (errno == EADDRINUSE)) -    { -      /* see above: handle possible problem when interface comes back up */ -      char buf[1][INET_ADDRSTRLEN]; -      zlog_info("setsockopt_ipv4_multicast attempting to drop and " -                "re-add (fd %d, mcast %s, ifindex %u)", -                sock, -                inet_ntop(AF_INET, &mreq.imr_multiaddr, -                          buf[0], sizeof(buf[0])), ifindex); -      setsockopt (sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, -                  (void *)&mreq, sizeof(mreq)); -      ret = setsockopt (sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, -                        (void *)&mreq, sizeof(mreq)); -    } -  return ret; +	ret = setsockopt(sock, IPPROTO_IP, optname, (void *)&mreq, +			 sizeof(mreq)); +	if ((ret < 0) && (optname == IP_ADD_MEMBERSHIP) +	    && (errno == EADDRINUSE)) { +		/* see above: handle possible problem when interface comes back +		 * up */ +		char buf[1][INET_ADDRSTRLEN]; +		zlog_info( +			"setsockopt_ipv4_multicast attempting to drop and " +			"re-add (fd %d, mcast %s, ifindex %u)", +			sock, inet_ntop(AF_INET, &mreq.imr_multiaddr, buf[0], +					sizeof(buf[0])), +			ifindex); +		setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, (void *)&mreq, +			   sizeof(mreq)); +		ret = setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, +				 (void *)&mreq, sizeof(mreq)); +	} +	return ret;  #else -  #error "Unsupported multicast API" +#error "Unsupported multicast API"  #endif /* #if OS_TYPE */ -  }  /*   * Set IP_MULTICAST_IF socket option in an OS-dependent manner.   */ -int -setsockopt_ipv4_multicast_if(int sock, struct in_addr if_addr, -			     ifindex_t ifindex) +int setsockopt_ipv4_multicast_if(int sock, struct in_addr if_addr, +				 ifindex_t ifindex)  {  #ifdef HAVE_STRUCT_IP_MREQN_IMR_IFINDEX -  struct ip_mreqn mreqn; -  memset (&mreqn, 0, sizeof(mreqn)); +	struct ip_mreqn mreqn; +	memset(&mreqn, 0, sizeof(mreqn)); -  mreqn.imr_ifindex = ifindex; -  return setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (void *)&mreqn, sizeof(mreqn)); +	mreqn.imr_ifindex = ifindex; +	return setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (void *)&mreqn, +			  sizeof(mreqn)); -  /* Example defines for another OS, boilerplate off other code in this -     function */ -  /* #elif  defined(BOGON_NIX) && EXAMPLE_VERSION_CODE > -100000 */ -  /* Add your favourite OS here! */ +/* Example defines for another OS, boilerplate off other code in this +   function */ +/* #elif  defined(BOGON_NIX) && EXAMPLE_VERSION_CODE > -100000 */ +/* Add your favourite OS here! */  #elif defined(HAVE_BSD_STRUCT_IP_MREQ_HACK) -  struct in_addr m; +	struct in_addr m;  #if !defined __OpenBSD__ -  m.s_addr = htonl (ifindex); +	m.s_addr = htonl(ifindex);  #else -  m.s_addr = if_addr.s_addr; +	m.s_addr = if_addr.s_addr;  #endif -  return setsockopt (sock, IPPROTO_IP, IP_MULTICAST_IF, (void *)&m, sizeof(m)); +	return setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (void *)&m, +			  sizeof(m));  #elif defined(SUNOS_5) -  char ifname[IF_NAMESIZE]; -  struct ifaddrs *ifa, *ifap; -  struct in_addr ifaddr; - -  if (if_indextoname(ifindex, ifname) == NULL) -    return -1; - -  if (getifaddrs(&ifa) != 0) -    return -1; - -  for (ifap = ifa; ifap != NULL; ifap = ifap->ifa_next) -    { -      struct sockaddr_in *sa; - -      if (strcmp(ifap->ifa_name, ifname) != 0) -        continue; -      if (ifap->ifa_addr->sa_family != AF_INET) -        continue; -      sa = (struct sockaddr_in*)ifap->ifa_addr; -      memcpy(&ifaddr, &sa->sin_addr, sizeof(ifaddr)); -      break; -    } - -  freeifaddrs(ifa); -  if (!ifap) /* This means we did not find an IP */ -    return -1; - -  return setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (void *)&ifaddr, sizeof(ifaddr)); +	char ifname[IF_NAMESIZE]; +	struct ifaddrs *ifa, *ifap; +	struct in_addr ifaddr; + +	if (if_indextoname(ifindex, ifname) == NULL) +		return -1; + +	if (getifaddrs(&ifa) != 0) +		return -1; + +	for (ifap = ifa; ifap != NULL; ifap = ifap->ifa_next) { +		struct sockaddr_in *sa; + +		if (strcmp(ifap->ifa_name, ifname) != 0) +			continue; +		if (ifap->ifa_addr->sa_family != AF_INET) +			continue; +		sa = (struct sockaddr_in *)ifap->ifa_addr; +		memcpy(&ifaddr, &sa->sin_addr, sizeof(ifaddr)); +		break; +	} + +	freeifaddrs(ifa); +	if (!ifap) /* This means we did not find an IP */ +		return -1; + +	return setsockopt(sock, IPPROTO_IP, IP_MULTICAST_IF, (void *)&ifaddr, +			  sizeof(ifaddr));  #else -  #error "Unsupported multicast API" +#error "Unsupported multicast API"  #endif  } -int -setsockopt_ipv4_multicast_loop (int sock, u_char val) +int setsockopt_ipv4_multicast_loop(int sock, u_char val)  { -  int ret; +	int ret; -  ret = setsockopt (sock, IPPROTO_IP, IP_MULTICAST_LOOP, (void *) &val, -		    sizeof (val)); -  if (ret < 0) -    zlog_warn ("can't setsockopt IP_MULTICAST_LOOP"); +	ret = setsockopt(sock, IPPROTO_IP, IP_MULTICAST_LOOP, (void *)&val, +			 sizeof(val)); +	if (ret < 0) +		zlog_warn("can't setsockopt IP_MULTICAST_LOOP"); -  return ret; +	return ret;  } -static int -setsockopt_ipv4_ifindex (int sock, ifindex_t val) +static int setsockopt_ipv4_ifindex(int sock, ifindex_t val)  { -  int ret; - -#if defined (IP_PKTINFO) -  if ((ret = setsockopt (sock, IPPROTO_IP, IP_PKTINFO, &val, sizeof (val))) < 0) -    zlog_warn ("Can't set IP_PKTINFO option for fd %d to %d: %s", -	       sock,val,safe_strerror(errno)); -#elif defined (IP_RECVIF) -  if ((ret = setsockopt (sock, IPPROTO_IP, IP_RECVIF, &val, sizeof (val))) < 0) -    zlog_warn ("Can't set IP_RECVIF option for fd %d to %d: %s", -	       sock,val,safe_strerror(errno)); +	int ret; + +#if defined(IP_PKTINFO) +	if ((ret = setsockopt(sock, IPPROTO_IP, IP_PKTINFO, &val, sizeof(val))) +	    < 0) +		zlog_warn("Can't set IP_PKTINFO option for fd %d to %d: %s", +			  sock, val, safe_strerror(errno)); +#elif defined(IP_RECVIF) +	if ((ret = setsockopt(sock, IPPROTO_IP, IP_RECVIF, &val, sizeof(val))) +	    < 0) +		zlog_warn("Can't set IP_RECVIF option for fd %d to %d: %s", +			  sock, val, safe_strerror(errno));  #else  #warning "Neither IP_PKTINFO nor IP_RECVIF is available."  #warning "Will not be able to receive link info."  #warning "Things might be seriously broken.." -  /* XXX Does this ever happen?  Should there be a zlog_warn message here? */ -  ret = -1; +	/* XXX Does this ever happen?  Should there be a zlog_warn message here? +	 */ +	ret = -1;  #endif -  return ret; +	return ret;  } -int -setsockopt_ipv4_tos(int sock, int tos) +int setsockopt_ipv4_tos(int sock, int tos)  { -  int ret; +	int ret; -  ret = setsockopt (sock, IPPROTO_IP, IP_TOS, &tos, sizeof (tos)); -  if (ret < 0) -    zlog_warn ("Can't set IP_TOS option for fd %d to %#x: %s", -	       sock, tos, safe_strerror(errno)); -  return ret; +	ret = setsockopt(sock, IPPROTO_IP, IP_TOS, &tos, sizeof(tos)); +	if (ret < 0) +		zlog_warn("Can't set IP_TOS option for fd %d to %#x: %s", sock, +			  tos, safe_strerror(errno)); +	return ret;  } -int -setsockopt_ifindex (int af, int sock, ifindex_t val) +int setsockopt_ifindex(int af, int sock, ifindex_t val)  { -  int ret = -1; -   -  switch (af) -    { -      case AF_INET: -        ret = setsockopt_ipv4_ifindex (sock, val); -        break; -      case AF_INET6: -        ret = setsockopt_ipv6_pktinfo (sock, val); -        break; -      default: -        zlog_warn ("setsockopt_ifindex: unknown address family %d", af); -    } -  return ret; +	int ret = -1; + +	switch (af) { +	case AF_INET: +		ret = setsockopt_ipv4_ifindex(sock, val); +		break; +	case AF_INET6: +		ret = setsockopt_ipv6_pktinfo(sock, val); +		break; +	default: +		zlog_warn("setsockopt_ifindex: unknown address family %d", af); +	} +	return ret;  } -   +  /*   * Requires: msgh is not NULL and points to a valid struct msghdr, which   * may or may not have control data about the incoming interface. @@ -458,225 +456,223 @@ setsockopt_ifindex (int af, int sock, ifindex_t val)   * Returns the interface index (small integer >= 1) if it can be   * determined, or else 0.   */ -static ifindex_t -getsockopt_ipv4_ifindex (struct msghdr *msgh) +static ifindex_t getsockopt_ipv4_ifindex(struct msghdr *msgh)  { -  /* XXX: initialize to zero?  (Always overwritten, so just cosmetic.) */ -  ifindex_t ifindex = -1; +	/* XXX: initialize to zero?  (Always overwritten, so just cosmetic.) */ +	ifindex_t ifindex = -1;  #if defined(IP_PKTINFO) -/* Linux pktinfo based ifindex retrieval */ -  struct in_pktinfo *pktinfo; -   -  pktinfo =  -    (struct in_pktinfo *)getsockopt_cmsg_data (msgh, IPPROTO_IP, IP_PKTINFO); -  /* XXX Can pktinfo be NULL?  Clean up post 0.98. */ -  ifindex = pktinfo->ipi_ifindex; -   +	/* Linux pktinfo based ifindex retrieval */ +	struct in_pktinfo *pktinfo; + +	pktinfo = (struct in_pktinfo *)getsockopt_cmsg_data(msgh, IPPROTO_IP, +							    IP_PKTINFO); +	/* XXX Can pktinfo be NULL?  Clean up post 0.98. */ +	ifindex = pktinfo->ipi_ifindex; +  #elif defined(IP_RECVIF) -  /* retrieval based on IP_RECVIF */ +/* retrieval based on IP_RECVIF */  #ifndef SUNOS_5 -  /* BSD systems use a sockaddr_dl as the control message payload. */ -  struct sockaddr_dl *sdl; +	/* BSD systems use a sockaddr_dl as the control message payload. */ +	struct sockaddr_dl *sdl;  #else -  /* SUNOS_5 uses an integer with the index. */ -  ifindex_t *ifindex_p; +	/* SUNOS_5 uses an integer with the index. */ +	ifindex_t *ifindex_p;  #endif /* SUNOS_5 */  #ifndef SUNOS_5 -  /* BSD */ -  sdl =  -    (struct sockaddr_dl *)getsockopt_cmsg_data (msgh, IPPROTO_IP, IP_RECVIF); -  if (sdl != NULL) -    ifindex = sdl->sdl_index; -  else -    ifindex = 0; +	/* BSD */ +	sdl = (struct sockaddr_dl *)getsockopt_cmsg_data(msgh, IPPROTO_IP, +							 IP_RECVIF); +	if (sdl != NULL) +		ifindex = sdl->sdl_index; +	else +		ifindex = 0;  #else -  /* -   * Solaris.  On Solaris 8, IP_RECVIF is defined, but the call to -   * enable it fails with errno=99, and the struct msghdr has -   * controllen 0. -   */ -  ifindex_p = (uint_t *)getsockopt_cmsg_data (msgh, IPPROTO_IP, IP_RECVIF);  -  if (ifindex_p != NULL) -    ifindex = *ifindex_p; -  else -    ifindex = 0; +	/* +	 * Solaris.  On Solaris 8, IP_RECVIF is defined, but the call to +	 * enable it fails with errno=99, and the struct msghdr has +	 * controllen 0. +	 */ +	ifindex_p = (uint_t *)getsockopt_cmsg_data(msgh, IPPROTO_IP, IP_RECVIF); +	if (ifindex_p != NULL) +		ifindex = *ifindex_p; +	else +		ifindex = 0;  #endif /* SUNOS_5 */  #else -  /* -   * Neither IP_PKTINFO nor IP_RECVIF defined - warn at compile time. -   * XXX Decide if this is a core service, or if daemons have to cope. -   * Since Solaris 8 and OpenBSD seem not to provide it, it seems that -   * daemons have to cope. -   */ +/* + * Neither IP_PKTINFO nor IP_RECVIF defined - warn at compile time. + * XXX Decide if this is a core service, or if daemons have to cope. + * Since Solaris 8 and OpenBSD seem not to provide it, it seems that + * daemons have to cope. + */  #warning "getsockopt_ipv4_ifindex: Neither IP_PKTINFO nor IP_RECVIF defined."  #warning "Some daemons may fail to operate correctly!" -  ifindex = 0; +	ifindex = 0; -#endif /* IP_PKTINFO */  +#endif /* IP_PKTINFO */ -  return ifindex; +	return ifindex;  }  /* return ifindex, 0 if none found */ -ifindex_t -getsockopt_ifindex (int af, struct msghdr *msgh) +ifindex_t getsockopt_ifindex(int af, struct msghdr *msgh)  { -  switch (af) -    { -      case AF_INET: -        return (getsockopt_ipv4_ifindex (msgh)); -        break; -      case AF_INET6: -        return (getsockopt_ipv6_ifindex (msgh)); -        break; -      default: -        zlog_warn ("getsockopt_ifindex: unknown address family %d", af); -        return 0; -    } +	switch (af) { +	case AF_INET: +		return (getsockopt_ipv4_ifindex(msgh)); +		break; +	case AF_INET6: +		return (getsockopt_ipv6_ifindex(msgh)); +		break; +	default: +		zlog_warn("getsockopt_ifindex: unknown address family %d", af); +		return 0; +	}  }  /* swab iph between order system uses for IP_HDRINCL and host order */ -void -sockopt_iphdrincl_swab_htosys (struct ip *iph) +void sockopt_iphdrincl_swab_htosys(struct ip *iph)  { -  /* BSD and derived take iph in network order, except for  -   * ip_len and ip_off -   */ +/* BSD and derived take iph in network order, except for + * ip_len and ip_off + */  #ifndef HAVE_IP_HDRINCL_BSD_ORDER -  iph->ip_len = htons(iph->ip_len); -  iph->ip_off = htons(iph->ip_off); +	iph->ip_len = htons(iph->ip_len); +	iph->ip_off = htons(iph->ip_off);  #endif /* HAVE_IP_HDRINCL_BSD_ORDER */ -  iph->ip_id = htons(iph->ip_id); +	iph->ip_id = htons(iph->ip_id);  } -void -sockopt_iphdrincl_swab_systoh (struct ip *iph) +void sockopt_iphdrincl_swab_systoh(struct ip *iph)  {  #ifndef HAVE_IP_HDRINCL_BSD_ORDER -  iph->ip_len = ntohs(iph->ip_len); -  iph->ip_off = ntohs(iph->ip_off); +	iph->ip_len = ntohs(iph->ip_len); +	iph->ip_off = ntohs(iph->ip_off);  #endif /* HAVE_IP_HDRINCL_BSD_ORDER */ -  iph->ip_id = ntohs(iph->ip_id); +	iph->ip_id = ntohs(iph->ip_id);  } -int -sockopt_tcp_rtt (int sock) +int sockopt_tcp_rtt(int sock)  {  #ifdef TCP_INFO -  struct tcp_info ti; -  socklen_t len = sizeof(ti); +	struct tcp_info ti; +	socklen_t len = sizeof(ti); -  if (getsockopt (sock, IPPROTO_TCP, TCP_INFO, &ti, &len) != 0) -    return 0; +	if (getsockopt(sock, IPPROTO_TCP, TCP_INFO, &ti, &len) != 0) +		return 0; -  return ti.tcpi_rtt / 1000; +	return ti.tcpi_rtt / 1000;  #else -  return 0; +	return 0;  #endif  } -int -sockopt_tcp_signature (int sock, union sockunion *su, const char *password) +int sockopt_tcp_signature(int sock, union sockunion *su, const char *password)  {  #if defined(HAVE_TCP_MD5_LINUX24) && defined(GNU_LINUX) -  /* Support for the old Linux 2.4 TCP-MD5 patch, taken from Hasso Tepper's -   * version of the Quagga patch (based on work by Rick Payne, and Bruce -   * Simpson) -   */ +/* Support for the old Linux 2.4 TCP-MD5 patch, taken from Hasso Tepper's + * version of the Quagga patch (based on work by Rick Payne, and Bruce + * Simpson) + */  #define TCP_MD5_AUTH 13  #define TCP_MD5_AUTH_ADD 1  #define TCP_MD5_AUTH_DEL 2 -  struct tcp_rfc2385_cmd { -    u_int8_t     command;    /* Command - Add/Delete */ -    u_int32_t    address;    /* IPV4 address associated */ -    u_int8_t     keylen;     /* MD5 Key len (do NOT assume 0 terminated ascii) */ -    void         *key;       /* MD5 Key */ -  } cmd; -  struct in_addr *addr = &su->sin.sin_addr; -   -  cmd.command = (password != NULL ? TCP_MD5_AUTH_ADD : TCP_MD5_AUTH_DEL); -  cmd.address = addr->s_addr; -  cmd.keylen = (password != NULL ? strlen (password) : 0); -  cmd.key = password; -   -  return setsockopt (sock, IPPROTO_TCP, TCP_MD5_AUTH, &cmd, sizeof cmd); -   +	struct tcp_rfc2385_cmd { +		u_int8_t command;  /* Command - Add/Delete */ +		u_int32_t address; /* IPV4 address associated */ +		u_int8_t keylen;   /* MD5 Key len (do NOT assume 0 terminated +				      ascii) */ +		void *key;	 /* MD5 Key */ +	} cmd; +	struct in_addr *addr = &su->sin.sin_addr; + +	cmd.command = (password != NULL ? TCP_MD5_AUTH_ADD : TCP_MD5_AUTH_DEL); +	cmd.address = addr->s_addr; +	cmd.keylen = (password != NULL ? strlen(password) : 0); +	cmd.key = password; + +	return setsockopt(sock, IPPROTO_TCP, TCP_MD5_AUTH, &cmd, sizeof cmd); +  #elif HAVE_DECL_TCP_MD5SIG -  int ret; +	int ret;  #ifndef GNU_LINUX -  /* -   * XXX Need to do PF_KEY operation here to add/remove an SA entry, -   * and add/remove an SP entry for this peer's packet flows also. -   */ -  int md5sig = password && *password ? 1 : 0; +	/* +	 * XXX Need to do PF_KEY operation here to add/remove an SA entry, +	 * and add/remove an SP entry for this peer's packet flows also. +	 */ +	int md5sig = password && *password ? 1 : 0;  #else -  int keylen = password ? strlen (password) : 0; -  struct tcp_md5sig md5sig; -  union sockunion *su2, *susock; -   -  /* Figure out whether the socket and the sockunion are the same family.. -   * adding AF_INET to AF_INET6 needs to be v4 mapped, you'd think.. -   */ -  if (!(susock = sockunion_getsockname (sock))) -    return -1; -   -  if (susock->sa.sa_family == su->sa.sa_family) -    su2 = su; -  else -    { -      /* oops.. */ -      su2 = susock; -       -      if (su2->sa.sa_family == AF_INET) -        { -          sockunion_free (susock); -          return 0; -        } -       -      /* If this does not work, then all users of this sockopt will need to -       * differentiate between IPv4 and IPv6, and keep seperate sockets for -       * each.  -       * -       * Sadly, it doesn't seem to work at present. It's unknown whether -       * this is a bug or not. -       */ -      if (su2->sa.sa_family == AF_INET6 -          && su->sa.sa_family == AF_INET) -        { -           su2->sin6.sin6_family = AF_INET6; -           /* V4Map the address */ -           memset (&su2->sin6.sin6_addr, 0, sizeof (struct in6_addr)); -           su2->sin6.sin6_addr.s6_addr32[2] = htonl(0xffff); -           memcpy (&su2->sin6.sin6_addr.s6_addr32[3], &su->sin.sin_addr, 4); -        } -    } -   -  memset (&md5sig, 0, sizeof (md5sig)); -  memcpy (&md5sig.tcpm_addr, su2, sizeof (*su2)); -  md5sig.tcpm_keylen = keylen; -  if (keylen) -    memcpy (md5sig.tcpm_key, password, keylen); -  sockunion_free (susock); +	int keylen = password ? strlen(password) : 0; +	struct tcp_md5sig md5sig; +	union sockunion *su2, *susock; + +	/* Figure out whether the socket and the sockunion are the same family.. +	 * adding AF_INET to AF_INET6 needs to be v4 mapped, you'd think.. +	 */ +	if (!(susock = sockunion_getsockname(sock))) +		return -1; + +	if (susock->sa.sa_family == su->sa.sa_family) +		su2 = su; +	else { +		/* oops.. */ +		su2 = susock; + +		if (su2->sa.sa_family == AF_INET) { +			sockunion_free(susock); +			return 0; +		} + +		/* If this does not work, then all users of this sockopt will +		 * need to +		 * differentiate between IPv4 and IPv6, and keep seperate +		 * sockets for +		 * each. +		 * +		 * Sadly, it doesn't seem to work at present. It's unknown +		 * whether +		 * this is a bug or not. +		 */ +		if (su2->sa.sa_family == AF_INET6 +		    && su->sa.sa_family == AF_INET) { +			su2->sin6.sin6_family = AF_INET6; +			/* V4Map the address */ +			memset(&su2->sin6.sin6_addr, 0, +			       sizeof(struct in6_addr)); +			su2->sin6.sin6_addr.s6_addr32[2] = htonl(0xffff); +			memcpy(&su2->sin6.sin6_addr.s6_addr32[3], +			       &su->sin.sin_addr, 4); +		} +	} + +	memset(&md5sig, 0, sizeof(md5sig)); +	memcpy(&md5sig.tcpm_addr, su2, sizeof(*su2)); +	md5sig.tcpm_keylen = keylen; +	if (keylen) +		memcpy(md5sig.tcpm_key, password, keylen); +	sockunion_free(susock);  #endif /* GNU_LINUX */ -  if ((ret = setsockopt (sock, IPPROTO_TCP, TCP_MD5SIG, &md5sig, sizeof md5sig)) < 0) -    { -      /* ENOENT is harmless.  It is returned when we clear a password for which -	 one was not previously set. */ -      if (ENOENT == errno) -	ret = 0; -      else -	zlog_err ("sockopt_tcp_signature: setsockopt(%d): %s", -		  sock, safe_strerror(errno)); -    } -  return ret; -#else /* HAVE_TCP_MD5SIG */ -  return -2; +	if ((ret = setsockopt(sock, IPPROTO_TCP, TCP_MD5SIG, &md5sig, +			      sizeof md5sig)) +	    < 0) { +		/* ENOENT is harmless.  It is returned when we clear a password +		   for which +		   one was not previously set. */ +		if (ENOENT == errno) +			ret = 0; +		else +			zlog_err("sockopt_tcp_signature: setsockopt(%d): %s", +				 sock, safe_strerror(errno)); +	} +	return ret; +#else  /* HAVE_TCP_MD5SIG */ +	return -2;  #endif /* !HAVE_TCP_MD5SIG */  } diff --git a/lib/sockopt.h b/lib/sockopt.h index 1b7be1e49f..dcd9e9ed78 100644 --- a/lib/sockopt.h +++ b/lib/sockopt.h @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_SOCKOPT_H @@ -24,17 +24,17 @@  #include "sockunion.h" -extern void setsockopt_so_recvbuf (int sock, int size); -extern void setsockopt_so_sendbuf (const int sock, int size); -extern int getsockopt_so_sendbuf (const int sock); +extern void setsockopt_so_recvbuf(int sock, int size); +extern void setsockopt_so_sendbuf(const int sock, int size); +extern int getsockopt_so_sendbuf(const int sock); -extern int setsockopt_ipv6_pktinfo (int, int); -extern int setsockopt_ipv6_checksum (int, int); -extern int setsockopt_ipv6_multicast_hops (int, int); -extern int setsockopt_ipv6_unicast_hops (int, int); -extern int setsockopt_ipv6_hoplimit (int, int); -extern int setsockopt_ipv6_multicast_loop (int, int); -extern int setsockopt_ipv6_tclass (int, int); +extern int setsockopt_ipv6_pktinfo(int, int); +extern int setsockopt_ipv6_checksum(int, int); +extern int setsockopt_ipv6_multicast_hops(int, int); +extern int setsockopt_ipv6_unicast_hops(int, int); +extern int setsockopt_ipv6_hoplimit(int, int); +extern int setsockopt_ipv6_multicast_loop(int, int); +extern int setsockopt_ipv6_tclass(int, int);  #define SOPT_SIZE_CMSG_PKTINFO_IPV6() (sizeof (struct in6_pktinfo)); @@ -44,19 +44,19 @@ extern int setsockopt_ipv6_tclass (int, int);   * that is unaware of which method is in use.   * These values are without any alignment needed (see CMSG_SPACE in RFC3542).   */ -#if defined (IP_PKTINFO) +#if defined(IP_PKTINFO)  /* Linux in_pktinfo. */  #define SOPT_SIZE_CMSG_PKTINFO_IPV4()  (CMSG_SPACE(sizeof (struct in_pktinfo)))  /* XXX This should perhaps be defined even if IP_PKTINFO is not. */ -#define SOPT_SIZE_CMSG_PKTINFO(af) \ +#define SOPT_SIZE_CMSG_PKTINFO(af)                                             \    ((af == AF_INET) ? SOPT_SIZE_CMSG_PKTINFO_IPV4() \                     : SOPT_SIZE_CMSG_PKTINFO_IPV6()  #endif /* IP_PKTINFO */ -#if defined (IP_RECVIF) +#if defined(IP_RECVIF)  /* BSD/Solaris */ -#if defined (SUNOS_5) +#if defined(SUNOS_5)  #define SOPT_SIZE_CMSG_RECVIF_IPV4()  (sizeof (uint_t))  #else  #define SOPT_SIZE_CMSG_RECVIF_IPV4()	(sizeof (struct sockaddr_dl)) @@ -64,39 +64,39 @@ extern int setsockopt_ipv6_tclass (int, int);  #endif /* IP_RECVIF */  /* SOPT_SIZE_CMSG_IFINDEX_IPV4 - portable type */ -#if defined (SOPT_SIZE_CMSG_PKTINFO) +#if defined(SOPT_SIZE_CMSG_PKTINFO)  #define SOPT_SIZE_CMSG_IFINDEX_IPV4() SOPT_SIZE_CMSG_PKTINFO_IPV4() -#elif defined (SOPT_SIZE_CMSG_RECVIF_IPV4) +#elif defined(SOPT_SIZE_CMSG_RECVIF_IPV4)  #define SOPT_SIZE_CMSG_IFINDEX_IPV4() SOPT_SIZE_CMSG_RECVIF_IPV4() -#else /* Nothing available */ +#else  /* Nothing available */  #define SOPT_SIZE_CMSG_IFINDEX_IPV4() (sizeof (char *))  #endif /* SOPT_SIZE_CMSG_IFINDEX_IPV4 */ -#define SOPT_SIZE_CMSG_IFINDEX(af) \ +#define SOPT_SIZE_CMSG_IFINDEX(af)                                             \    (((af) == AF_INET) : SOPT_SIZE_CMSG_IFINDEX_IPV4() \                      ? SOPT_SIZE_CMSG_PKTINFO_IPV6())  extern int setsockopt_ipv4_multicast_if(int sock, struct in_addr if_addr,  					ifindex_t ifindex);  extern int setsockopt_ipv4_multicast(int sock, int optname, -                                     struct in_addr if_addr, -                                     unsigned int mcast_addr, -			             ifindex_t ifindex); -extern int setsockopt_ipv4_multicast_loop (int sock, u_char val); +				     struct in_addr if_addr, +				     unsigned int mcast_addr, +				     ifindex_t ifindex); +extern int setsockopt_ipv4_multicast_loop(int sock, u_char val);  extern int setsockopt_ipv4_tos(int sock, int tos);  /* Ask for, and get, ifindex, by whatever method is supported. */ -extern int setsockopt_ifindex (int, int, ifindex_t); -extern ifindex_t getsockopt_ifindex (int, struct msghdr *); +extern int setsockopt_ifindex(int, int, ifindex_t); +extern ifindex_t getsockopt_ifindex(int, struct msghdr *); -/* swab the fields in iph between the host order and system order expected  +/* swab the fields in iph between the host order and system order expected   * for IP_HDRINCL.   */ -extern void sockopt_iphdrincl_swab_htosys (struct ip *iph); -extern void sockopt_iphdrincl_swab_systoh (struct ip *iph); +extern void sockopt_iphdrincl_swab_htosys(struct ip *iph); +extern void sockopt_iphdrincl_swab_systoh(struct ip *iph); -extern int sockopt_tcp_rtt (int); +extern int sockopt_tcp_rtt(int);  extern int sockopt_tcp_signature(int sock, union sockunion *su, -                                 const char *password); +				 const char *password);  #endif /*_ZEBRA_SOCKOPT_H */ diff --git a/lib/sockunion.c b/lib/sockunion.c index 9ba2ce82f6..04920c0820 100644 --- a/lib/sockunion.c +++ b/lib/sockunion.c @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -30,715 +30,654 @@  DEFINE_MTYPE_STATIC(LIB, SOCKUNION, "Socket union") -const char * -inet_sutop (const union sockunion *su, char *str) +const char *inet_sutop(const union sockunion *su, char *str)  { -  switch (su->sa.sa_family) -    { -    case AF_INET: -      inet_ntop (AF_INET, &su->sin.sin_addr, str, INET_ADDRSTRLEN); -      break; -    case AF_INET6: -      inet_ntop (AF_INET6, &su->sin6.sin6_addr, str, INET6_ADDRSTRLEN); -      break; -    } -  return str; +	switch (su->sa.sa_family) { +	case AF_INET: +		inet_ntop(AF_INET, &su->sin.sin_addr, str, INET_ADDRSTRLEN); +		break; +	case AF_INET6: +		inet_ntop(AF_INET6, &su->sin6.sin6_addr, str, INET6_ADDRSTRLEN); +		break; +	} +	return str;  } -int -str2sockunion (const char *str, union sockunion *su) +int str2sockunion(const char *str, union sockunion *su)  { -  int ret; +	int ret; -  memset (su, 0, sizeof (union sockunion)); +	memset(su, 0, sizeof(union sockunion)); -  ret = inet_pton (AF_INET, str, &su->sin.sin_addr); -  if (ret > 0)			/* Valid IPv4 address format. */ -    { -      su->sin.sin_family = AF_INET; +	ret = inet_pton(AF_INET, str, &su->sin.sin_addr); +	if (ret > 0) /* Valid IPv4 address format. */ +	{ +		su->sin.sin_family = AF_INET;  #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN -      su->sin.sin_len = sizeof(struct sockaddr_in); +		su->sin.sin_len = sizeof(struct sockaddr_in);  #endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */ -      return 0; -    } -  ret = inet_pton (AF_INET6, str, &su->sin6.sin6_addr); -  if (ret > 0)			/* Valid IPv6 address format. */ -    { -      su->sin6.sin6_family = AF_INET6; +		return 0; +	} +	ret = inet_pton(AF_INET6, str, &su->sin6.sin6_addr); +	if (ret > 0) /* Valid IPv6 address format. */ +	{ +		su->sin6.sin6_family = AF_INET6;  #ifdef SIN6_LEN -      su->sin6.sin6_len = sizeof(struct sockaddr_in6); +		su->sin6.sin6_len = sizeof(struct sockaddr_in6);  #endif /* SIN6_LEN */ -      return 0; -    } -  return -1; +		return 0; +	} +	return -1;  } -const char * -sockunion2str (const union sockunion *su, char *buf, size_t len) +const char *sockunion2str(const union sockunion *su, char *buf, size_t len)  { -  switch (sockunion_family(su)) -    { -    case AF_UNSPEC: -      snprintf (buf, len, "(unspec)"); -      return buf; -    case AF_INET: -      return inet_ntop (AF_INET, &su->sin.sin_addr, buf, len); -    case AF_INET6: -      return inet_ntop (AF_INET6, &su->sin6.sin6_addr, buf, len); -    } -  snprintf (buf, len, "(af %d)", sockunion_family(su)); -  return buf; +	switch (sockunion_family(su)) { +	case AF_UNSPEC: +		snprintf(buf, len, "(unspec)"); +		return buf; +	case AF_INET: +		return inet_ntop(AF_INET, &su->sin.sin_addr, buf, len); +	case AF_INET6: +		return inet_ntop(AF_INET6, &su->sin6.sin6_addr, buf, len); +	} +	snprintf(buf, len, "(af %d)", sockunion_family(su)); +	return buf;  } -union sockunion * -sockunion_str2su (const char *str) +union sockunion *sockunion_str2su(const char *str)  { -  union sockunion *su = XCALLOC (MTYPE_SOCKUNION, sizeof (union sockunion)); -   -  if (!str2sockunion (str, su)) -    return su; -   -  XFREE (MTYPE_SOCKUNION, su); -  return NULL; +	union sockunion *su = XCALLOC(MTYPE_SOCKUNION, sizeof(union sockunion)); + +	if (!str2sockunion(str, su)) +		return su; + +	XFREE(MTYPE_SOCKUNION, su); +	return NULL;  }  /* Convert IPv4 compatible IPv6 address to IPv4 address. */ -static void -sockunion_normalise_mapped (union sockunion *su) -{ -  struct sockaddr_in sin; -   -  if (su->sa.sa_family == AF_INET6  -      && IN6_IS_ADDR_V4MAPPED (&su->sin6.sin6_addr)) -    { -      memset (&sin, 0, sizeof (struct sockaddr_in)); -      sin.sin_family = AF_INET; -      sin.sin_port = su->sin6.sin6_port; -      memcpy (&sin.sin_addr, ((char *)&su->sin6.sin6_addr) + 12, 4); -      memcpy (su, &sin, sizeof (struct sockaddr_in)); -    } +static void sockunion_normalise_mapped(union sockunion *su) +{ +	struct sockaddr_in sin; + +	if (su->sa.sa_family == AF_INET6 +	    && IN6_IS_ADDR_V4MAPPED(&su->sin6.sin6_addr)) { +		memset(&sin, 0, sizeof(struct sockaddr_in)); +		sin.sin_family = AF_INET; +		sin.sin_port = su->sin6.sin6_port; +		memcpy(&sin.sin_addr, ((char *)&su->sin6.sin6_addr) + 12, 4); +		memcpy(su, &sin, sizeof(struct sockaddr_in)); +	}  }  /* return sockunion structure : this function should be revised. */ -static const char * -sockunion_log (const union sockunion *su, char *buf, size_t len) +static const char *sockunion_log(const union sockunion *su, char *buf, +				 size_t len)  { -  switch (su->sa.sa_family) -    { -    case AF_INET: -      return inet_ntop(AF_INET, &su->sin.sin_addr, buf, len); +	switch (su->sa.sa_family) { +	case AF_INET: +		return inet_ntop(AF_INET, &su->sin.sin_addr, buf, len); -    case AF_INET6: -      return inet_ntop(AF_INET6, &(su->sin6.sin6_addr), buf, len); -      break; +	case AF_INET6: +		return inet_ntop(AF_INET6, &(su->sin6.sin6_addr), buf, len); +		break; -    default: -      snprintf (buf, len, "af_unknown %d ", su->sa.sa_family); -      return buf; -    } +	default: +		snprintf(buf, len, "af_unknown %d ", su->sa.sa_family); +		return buf; +	}  }  /* Return socket of sockunion. */ -int -sockunion_socket (const union sockunion *su) +int sockunion_socket(const union sockunion *su)  { -  int sock; +	int sock; -  sock = socket (su->sa.sa_family, SOCK_STREAM, 0); -  if (sock < 0) -    { -      char buf[SU_ADDRSTRLEN]; -      zlog_warn("Can't make socket for %s : %s", -                sockunion_log(su, buf, SU_ADDRSTRLEN), safe_strerror(errno)); -      return -1; -    } +	sock = socket(su->sa.sa_family, SOCK_STREAM, 0); +	if (sock < 0) { +		char buf[SU_ADDRSTRLEN]; +		zlog_warn("Can't make socket for %s : %s", +			  sockunion_log(su, buf, SU_ADDRSTRLEN), +			  safe_strerror(errno)); +		return -1; +	} -  return sock; +	return sock;  }  /* Return accepted new socket file descriptor. */ -int -sockunion_accept (int sock, union sockunion *su) +int sockunion_accept(int sock, union sockunion *su)  { -  socklen_t len; -  int client_sock; +	socklen_t len; +	int client_sock; -  len = sizeof (union sockunion); -  client_sock = accept (sock, (struct sockaddr *) su, &len); -   -  sockunion_normalise_mapped (su); -  return client_sock; +	len = sizeof(union sockunion); +	client_sock = accept(sock, (struct sockaddr *)su, &len); + +	sockunion_normalise_mapped(su); +	return client_sock;  }  /* Return sizeof union sockunion.  */ -static int -sockunion_sizeof (const union sockunion *su) -{ -  int ret; - -  ret = 0; -  switch (su->sa.sa_family) -    { -    case AF_INET: -      ret = sizeof (struct sockaddr_in); -      break; -    case AF_INET6: -      ret = sizeof (struct sockaddr_in6); -      break; -    } -  return ret; +static int sockunion_sizeof(const union sockunion *su) +{ +	int ret; + +	ret = 0; +	switch (su->sa.sa_family) { +	case AF_INET: +		ret = sizeof(struct sockaddr_in); +		break; +	case AF_INET6: +		ret = sizeof(struct sockaddr_in6); +		break; +	} +	return ret;  }  /* sockunion_connect returns     -1 : error occured     0 : connect success     1 : connect is in progress */ -enum connect_result -sockunion_connect (int fd, const union sockunion *peersu, unsigned short port, -		   ifindex_t ifindex) -{ -  int ret; -  int val; -  union sockunion su; - -  memcpy (&su, peersu, sizeof (union sockunion)); - -  switch (su.sa.sa_family) -    { -    case AF_INET: -      su.sin.sin_port = port; -      break; -    case AF_INET6: -      su.sin6.sin6_port  = port; +enum connect_result sockunion_connect(int fd, const union sockunion *peersu, +				      unsigned short port, ifindex_t ifindex) +{ +	int ret; +	int val; +	union sockunion su; + +	memcpy(&su, peersu, sizeof(union sockunion)); + +	switch (su.sa.sa_family) { +	case AF_INET: +		su.sin.sin_port = port; +		break; +	case AF_INET6: +		su.sin6.sin6_port = port;  #ifdef KAME -      if (IN6_IS_ADDR_LINKLOCAL(&su.sin6.sin6_addr) && ifindex) -	{ -	  su.sin6.sin6_scope_id = ifindex; -	  SET_IN6_LINKLOCAL_IFINDEX (su.sin6.sin6_addr, ifindex); -	} +		if (IN6_IS_ADDR_LINKLOCAL(&su.sin6.sin6_addr) && ifindex) { +			su.sin6.sin6_scope_id = ifindex; +			SET_IN6_LINKLOCAL_IFINDEX(su.sin6.sin6_addr, ifindex); +		}  #endif /* KAME */ -      break; -    }       - -  /* Make socket non-block. */ -  val = fcntl (fd, F_GETFL, 0); -  fcntl (fd, F_SETFL, val|O_NONBLOCK); - -  /* Call connect function. */ -  ret = connect (fd, (struct sockaddr *) &su, sockunion_sizeof (&su)); - -  /* Immediate success */ -  if (ret == 0) -    { -      fcntl (fd, F_SETFL, val); -      return connect_success; -    } - -  /* If connect is in progress then return 1 else it's real error. */ -  if (ret < 0) -    { -      if (errno != EINPROGRESS) -	{ -	  char str[SU_ADDRSTRLEN]; -	  zlog_info ("can't connect to %s fd %d : %s", -		     sockunion_log (&su, str, sizeof str), -		     fd, safe_strerror (errno)); -	  return connect_error; +		break; +	} + +	/* Make socket non-block. */ +	val = fcntl(fd, F_GETFL, 0); +	fcntl(fd, F_SETFL, val | O_NONBLOCK); + +	/* Call connect function. */ +	ret = connect(fd, (struct sockaddr *)&su, sockunion_sizeof(&su)); + +	/* Immediate success */ +	if (ret == 0) { +		fcntl(fd, F_SETFL, val); +		return connect_success; +	} + +	/* If connect is in progress then return 1 else it's real error. */ +	if (ret < 0) { +		if (errno != EINPROGRESS) { +			char str[SU_ADDRSTRLEN]; +			zlog_info("can't connect to %s fd %d : %s", +				  sockunion_log(&su, str, sizeof str), fd, +				  safe_strerror(errno)); +			return connect_error; +		}  	} -    } -  fcntl (fd, F_SETFL, val); +	fcntl(fd, F_SETFL, val); -  return connect_in_progress; +	return connect_in_progress;  }  /* Make socket from sockunion union. */ -int -sockunion_stream_socket (union sockunion *su) +int sockunion_stream_socket(union sockunion *su)  { -  int sock; +	int sock; -  if (su->sa.sa_family == 0) -    su->sa.sa_family = AF_INET_UNION; +	if (su->sa.sa_family == 0) +		su->sa.sa_family = AF_INET_UNION; -  sock = socket (su->sa.sa_family, SOCK_STREAM, 0); +	sock = socket(su->sa.sa_family, SOCK_STREAM, 0); -  if (sock < 0) -    zlog_warn("can't make socket sockunion_stream_socket"); +	if (sock < 0) +		zlog_warn("can't make socket sockunion_stream_socket"); -  return sock; +	return sock;  }  /* Bind socket to specified address. */ -int -sockunion_bind (int sock, union sockunion *su, unsigned short port,  -		union sockunion *su_addr) +int sockunion_bind(int sock, union sockunion *su, unsigned short port, +		   union sockunion *su_addr)  { -  int size = 0; -  int ret; +	int size = 0; +	int ret; -  if (su->sa.sa_family == AF_INET) -    { -      size = sizeof (struct sockaddr_in); -      su->sin.sin_port = htons (port); +	if (su->sa.sa_family == AF_INET) { +		size = sizeof(struct sockaddr_in); +		su->sin.sin_port = htons(port);  #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN -      su->sin.sin_len = size; +		su->sin.sin_len = size;  #endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */ -      if (su_addr == NULL) -	sockunion2ip (su) = htonl (INADDR_ANY); -    } -  else if (su->sa.sa_family == AF_INET6) -    { -      size = sizeof (struct sockaddr_in6); -      su->sin6.sin6_port = htons (port); +		if (su_addr == NULL) +			sockunion2ip(su) = htonl(INADDR_ANY); +	} else if (su->sa.sa_family == AF_INET6) { +		size = sizeof(struct sockaddr_in6); +		su->sin6.sin6_port = htons(port);  #ifdef SIN6_LEN -      su->sin6.sin6_len = size; +		su->sin6.sin6_len = size;  #endif /* SIN6_LEN */ -      if (su_addr == NULL) -	{ +		if (su_addr == NULL) {  #ifdef LINUX_IPV6 -	  memset (&su->sin6.sin6_addr, 0, sizeof (struct in6_addr)); +			memset(&su->sin6.sin6_addr, 0, sizeof(struct in6_addr));  #else -	  su->sin6.sin6_addr = in6addr_any; +			su->sin6.sin6_addr = in6addr_any;  #endif /* LINUX_IPV6 */ +		}  	} -    } -  ret = bind (sock, (struct sockaddr *)su, size); -  if (ret < 0) -    { -      char buf[SU_ADDRSTRLEN]; -      zlog_warn("can't bind socket for %s : %s", -                sockunion_log(su, buf, SU_ADDRSTRLEN), safe_strerror(errno)); -    } +	ret = bind(sock, (struct sockaddr *)su, size); +	if (ret < 0) { +		char buf[SU_ADDRSTRLEN]; +		zlog_warn("can't bind socket for %s : %s", +			  sockunion_log(su, buf, SU_ADDRSTRLEN), +			  safe_strerror(errno)); +	} -  return ret; +	return ret;  } -int -sockopt_reuseaddr (int sock) +int sockopt_reuseaddr(int sock)  { -  int ret; -  int on = 1; +	int ret; +	int on = 1; -  ret = setsockopt (sock, SOL_SOCKET, SO_REUSEADDR,  -		    (void *) &on, sizeof (on)); -  if (ret < 0) -    { -      zlog_warn("can't set sockopt SO_REUSEADDR to socket %d", sock); -      return -1; -    } -  return 0; +	ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&on, +			 sizeof(on)); +	if (ret < 0) { +		zlog_warn("can't set sockopt SO_REUSEADDR to socket %d", sock); +		return -1; +	} +	return 0;  }  #ifdef SO_REUSEPORT -int -sockopt_reuseport (int sock) +int sockopt_reuseport(int sock)  { -  int ret; -  int on = 1; +	int ret; +	int on = 1; -  ret = setsockopt (sock, SOL_SOCKET, SO_REUSEPORT,  -		    (void *) &on, sizeof (on)); -  if (ret < 0) -    { -      zlog_warn("can't set sockopt SO_REUSEPORT to socket %d", sock); -      return -1; -    } -  return 0; +	ret = setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, (void *)&on, +			 sizeof(on)); +	if (ret < 0) { +		zlog_warn("can't set sockopt SO_REUSEPORT to socket %d", sock); +		return -1; +	} +	return 0;  }  #else -int -sockopt_reuseport (int sock) +int sockopt_reuseport(int sock)  { -  return 0; +	return 0;  }  #endif /* 0 */ -int -sockopt_ttl (int family, int sock, int ttl) +int sockopt_ttl(int family, int sock, int ttl)  { -  int ret; +	int ret;  #ifdef IP_TTL -  if (family == AF_INET) -    { -      ret = setsockopt (sock, IPPROTO_IP, IP_TTL,  -			(void *) &ttl, sizeof (int)); -      if (ret < 0) -	{ -	  zlog_warn("can't set sockopt IP_TTL %d to socket %d", ttl, sock); -	  return -1; +	if (family == AF_INET) { +		ret = setsockopt(sock, IPPROTO_IP, IP_TTL, (void *)&ttl, +				 sizeof(int)); +		if (ret < 0) { +			zlog_warn("can't set sockopt IP_TTL %d to socket %d", +				  ttl, sock); +			return -1; +		} +		return 0;  	} -      return 0; -    }  #endif /* IP_TTL */ -  if (family == AF_INET6) -    { -      ret = setsockopt (sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS,  -			(void *) &ttl, sizeof (int)); -      if (ret < 0) -	{ -	  zlog_warn("can't set sockopt IPV6_UNICAST_HOPS %d to socket %d", -                    ttl, sock); -	  return -1; +	if (family == AF_INET6) { +		ret = setsockopt(sock, IPPROTO_IPV6, IPV6_UNICAST_HOPS, +				 (void *)&ttl, sizeof(int)); +		if (ret < 0) { +			zlog_warn( +				"can't set sockopt IPV6_UNICAST_HOPS %d to socket %d", +				ttl, sock); +			return -1; +		} +		return 0;  	} -      return 0; -    } -  return 0; +	return 0;  } -int -sockopt_cork (int sock, int onoff) +int sockopt_cork(int sock, int onoff)  {  #ifdef TCP_CORK -  return setsockopt (sock, IPPROTO_TCP, TCP_CORK, &onoff, sizeof(onoff)); +	return setsockopt(sock, IPPROTO_TCP, TCP_CORK, &onoff, sizeof(onoff));  #else -  return 0; +	return 0;  #endif  }  int sockopt_mark_default(int sock, int mark, struct zebra_privs_t *cap)  {  #ifdef SO_MARK -  int ret; +	int ret; -  if ( cap->change (ZPRIVS_RAISE) ) -    zlog_err ("routing_socket: Can't raise privileges"); +	if (cap->change(ZPRIVS_RAISE)) +		zlog_err("routing_socket: Can't raise privileges"); -  ret = setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)); +	ret = setsockopt(sock, SOL_SOCKET, SO_MARK, &mark, sizeof(mark)); -  if ( cap->change (ZPRIVS_LOWER) ) -    zlog_err ("routing_socket: Can't lower privileges"); +	if (cap->change(ZPRIVS_LOWER)) +		zlog_err("routing_socket: Can't lower privileges"); -  return ret; +	return ret;  #else -  return 0; +	return 0;  #endif  } -int -sockopt_minttl (int family, int sock, int minttl) +int sockopt_minttl(int family, int sock, int minttl)  {  #ifdef IP_MINTTL -  if (family == AF_INET) -    { -      int ret = setsockopt (sock, IPPROTO_IP, IP_MINTTL, &minttl, sizeof(minttl)); -      if (ret < 0) -	  zlog_warn("can't set sockopt IP_MINTTL to %d on socket %d: %s", -                    minttl, sock, safe_strerror(errno)); -      return ret; -    } +	if (family == AF_INET) { +		int ret = setsockopt(sock, IPPROTO_IP, IP_MINTTL, &minttl, +				     sizeof(minttl)); +		if (ret < 0) +			zlog_warn( +				"can't set sockopt IP_MINTTL to %d on socket %d: %s", +				minttl, sock, safe_strerror(errno)); +		return ret; +	}  #endif /* IP_MINTTL */  #ifdef IPV6_MINHOPCOUNT -  if (family == AF_INET6) -    { -      int ret = setsockopt (sock, IPPROTO_IPV6, IPV6_MINHOPCOUNT, &minttl, sizeof(minttl)); -      if (ret < 0) -	  zlog_warn("can't set sockopt IPV6_MINHOPCOUNT to %d on socket %d: %s", -                    minttl, sock, safe_strerror(errno)); -      return ret; -    } +	if (family == AF_INET6) { +		int ret = setsockopt(sock, IPPROTO_IPV6, IPV6_MINHOPCOUNT, +				     &minttl, sizeof(minttl)); +		if (ret < 0) +			zlog_warn( +				"can't set sockopt IPV6_MINHOPCOUNT to %d on socket %d: %s", +				minttl, sock, safe_strerror(errno)); +		return ret; +	}  #endif -  errno = EOPNOTSUPP; -  return -1; +	errno = EOPNOTSUPP; +	return -1;  } -int -sockopt_v6only (int family, int sock) +int sockopt_v6only(int family, int sock)  { -  int ret, on = 1; +	int ret, on = 1;  #ifdef IPV6_V6ONLY -  if (family == AF_INET6) -    { -      ret = setsockopt (sock, IPPROTO_IPV6, IPV6_V6ONLY, -			(void *) &on, sizeof (int)); -      if (ret < 0) -	{ -	  zlog_warn("can't set sockopt IPV6_V6ONLY " "to socket %d", -                    sock); -	  return -1; +	if (family == AF_INET6) { +		ret = setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&on, +				 sizeof(int)); +		if (ret < 0) { +			zlog_warn( +				"can't set sockopt IPV6_V6ONLY " +				"to socket %d", +				sock); +			return -1; +		} +		return 0;  	} -      return 0; -    }  #endif /* IPV6_V6ONLY */ -  return 0; +	return 0;  }  /* If same family and same prefix return 1. */ -int -sockunion_same (const union sockunion *su1, const union sockunion *su2) -{ -  int ret = 0; - -  if (su1->sa.sa_family != su2->sa.sa_family) -    return 0; - -  switch (su1->sa.sa_family) -    { -    case AF_INET: -      ret = memcmp (&su1->sin.sin_addr, &su2->sin.sin_addr, -		    sizeof (struct in_addr)); -      break; -    case AF_INET6: -      ret = memcmp (&su1->sin6.sin6_addr, &su2->sin6.sin6_addr, -		    sizeof (struct in6_addr)); -      if ((ret == 0) && IN6_IS_ADDR_LINKLOCAL(&su1->sin6.sin6_addr)) -	{ -	  /* compare interface indices */ -	  if (su1->sin6.sin6_scope_id && su2->sin6.sin6_scope_id) -	    ret = (su1->sin6.sin6_scope_id == su2->sin6.sin6_scope_id) ? 0 : 1; +int sockunion_same(const union sockunion *su1, const union sockunion *su2) +{ +	int ret = 0; + +	if (su1->sa.sa_family != su2->sa.sa_family) +		return 0; + +	switch (su1->sa.sa_family) { +	case AF_INET: +		ret = memcmp(&su1->sin.sin_addr, &su2->sin.sin_addr, +			     sizeof(struct in_addr)); +		break; +	case AF_INET6: +		ret = memcmp(&su1->sin6.sin6_addr, &su2->sin6.sin6_addr, +			     sizeof(struct in6_addr)); +		if ((ret == 0) && IN6_IS_ADDR_LINKLOCAL(&su1->sin6.sin6_addr)) { +			/* compare interface indices */ +			if (su1->sin6.sin6_scope_id && su2->sin6.sin6_scope_id) +				ret = (su1->sin6.sin6_scope_id +				       == su2->sin6.sin6_scope_id) +					      ? 0 +					      : 1; +		} +		break;  	} -      break; -    } -  if (ret == 0) -    return 1; -  else -    return 0; +	if (ret == 0) +		return 1; +	else +		return 0;  } -unsigned int -sockunion_hash (const union sockunion *su) +unsigned int sockunion_hash(const union sockunion *su)  { -  switch (sockunion_family(su)) -    { -    case AF_INET: -      return jhash_1word(su->sin.sin_addr.s_addr, 0); -    case AF_INET6: -      return jhash2(su->sin6.sin6_addr.s6_addr32, ZEBRA_NUM_OF(su->sin6.sin6_addr.s6_addr32), 0); -    } -  return 0; +	switch (sockunion_family(su)) { +	case AF_INET: +		return jhash_1word(su->sin.sin_addr.s_addr, 0); +	case AF_INET6: +		return jhash2(su->sin6.sin6_addr.s6_addr32, +			      ZEBRA_NUM_OF(su->sin6.sin6_addr.s6_addr32), 0); +	} +	return 0;  } -size_t -family2addrsize(int family) +size_t family2addrsize(int family)  { -  switch (family) -    { -    case AF_INET: -      return sizeof(struct in_addr); -    case AF_INET6: -      return sizeof(struct in6_addr); -    } -  return 0; +	switch (family) { +	case AF_INET: +		return sizeof(struct in_addr); +	case AF_INET6: +		return sizeof(struct in6_addr); +	} +	return 0;  } -size_t -sockunion_get_addrlen(const union sockunion *su) +size_t sockunion_get_addrlen(const union sockunion *su)  { -  return family2addrsize(sockunion_family(su)); +	return family2addrsize(sockunion_family(su));  } -const u_char * -sockunion_get_addr(const union sockunion *su) +const u_char *sockunion_get_addr(const union sockunion *su)  { -  switch (sockunion_family(su)) -    { -    case AF_INET: -      return (const u_char *) &su->sin.sin_addr.s_addr; -    case AF_INET6: -      return (const u_char *) &su->sin6.sin6_addr; -    } -  return NULL; +	switch (sockunion_family(su)) { +	case AF_INET: +		return (const u_char *)&su->sin.sin_addr.s_addr; +	case AF_INET6: +		return (const u_char *)&su->sin6.sin6_addr; +	} +	return NULL;  } -void -sockunion_set(union sockunion *su, int family, const u_char *addr, size_t bytes) +void sockunion_set(union sockunion *su, int family, const u_char *addr, +		   size_t bytes)  { -  if (family2addrsize(family) != bytes) -    return; +	if (family2addrsize(family) != bytes) +		return; -  sockunion_family(su) = family; -  switch (family) -    { -    case AF_INET: -      memcpy(&su->sin.sin_addr.s_addr, addr, bytes); -      break; -    case AF_INET6: -      memcpy(&su->sin6.sin6_addr, addr, bytes); -      break; -    } +	sockunion_family(su) = family; +	switch (family) { +	case AF_INET: +		memcpy(&su->sin.sin_addr.s_addr, addr, bytes); +		break; +	case AF_INET6: +		memcpy(&su->sin6.sin6_addr, addr, bytes); +		break; +	}  }  /* After TCP connection is established.  Get local address and port. */ -union sockunion * -sockunion_getsockname (int fd) -{ -  int ret; -  socklen_t len; -  union -  { -    struct sockaddr sa; -    struct sockaddr_in sin; -    struct sockaddr_in6 sin6; -    char tmp_buffer[128]; -  } name; -  union sockunion *su; - -  memset (&name, 0, sizeof name); -  len = sizeof name; - -  ret = getsockname (fd, (struct sockaddr *)&name, &len); -  if (ret < 0) -    { -      zlog_warn ("Can't get local address and port by getsockname: %s", -		 safe_strerror (errno)); -      return NULL; -    } - -  if (name.sa.sa_family == AF_INET) -    { -      su = XCALLOC (MTYPE_SOCKUNION, sizeof (union sockunion)); -      memcpy (su, &name, sizeof (struct sockaddr_in)); -      return su; -    } -  if (name.sa.sa_family == AF_INET6) -    { -      su = XCALLOC (MTYPE_SOCKUNION, sizeof (union sockunion)); -      memcpy (su, &name, sizeof (struct sockaddr_in6)); -      sockunion_normalise_mapped (su); -      return su; -    } -  return NULL; +union sockunion *sockunion_getsockname(int fd) +{ +	int ret; +	socklen_t len; +	union { +		struct sockaddr sa; +		struct sockaddr_in sin; +		struct sockaddr_in6 sin6; +		char tmp_buffer[128]; +	} name; +	union sockunion *su; + +	memset(&name, 0, sizeof name); +	len = sizeof name; + +	ret = getsockname(fd, (struct sockaddr *)&name, &len); +	if (ret < 0) { +		zlog_warn("Can't get local address and port by getsockname: %s", +			  safe_strerror(errno)); +		return NULL; +	} + +	if (name.sa.sa_family == AF_INET) { +		su = XCALLOC(MTYPE_SOCKUNION, sizeof(union sockunion)); +		memcpy(su, &name, sizeof(struct sockaddr_in)); +		return su; +	} +	if (name.sa.sa_family == AF_INET6) { +		su = XCALLOC(MTYPE_SOCKUNION, sizeof(union sockunion)); +		memcpy(su, &name, sizeof(struct sockaddr_in6)); +		sockunion_normalise_mapped(su); +		return su; +	} +	return NULL;  }  /* After TCP connection is established.  Get remote address and port. */ -union sockunion * -sockunion_getpeername (int fd) -{ -  int ret; -  socklen_t len; -  union -  { -    struct sockaddr sa; -    struct sockaddr_in sin; -    struct sockaddr_in6 sin6; -    char tmp_buffer[128]; -  } name; -  union sockunion *su; - -  memset (&name, 0, sizeof name); -  len = sizeof name; -  ret = getpeername (fd, (struct sockaddr *)&name, &len); -  if (ret < 0) -    { -      zlog_warn("Can't get remote address and port: %s", safe_strerror(errno)); -      return NULL; -    } - -  if (name.sa.sa_family == AF_INET) -    { -      su = XCALLOC (MTYPE_SOCKUNION, sizeof (union sockunion)); -      memcpy (su, &name, sizeof (struct sockaddr_in)); -      return su; -    } -  if (name.sa.sa_family == AF_INET6) -    { -      su = XCALLOC (MTYPE_SOCKUNION, sizeof (union sockunion)); -      memcpy (su, &name, sizeof (struct sockaddr_in6)); -      sockunion_normalise_mapped (su); -      return su; -    } -  return NULL; +union sockunion *sockunion_getpeername(int fd) +{ +	int ret; +	socklen_t len; +	union { +		struct sockaddr sa; +		struct sockaddr_in sin; +		struct sockaddr_in6 sin6; +		char tmp_buffer[128]; +	} name; +	union sockunion *su; + +	memset(&name, 0, sizeof name); +	len = sizeof name; +	ret = getpeername(fd, (struct sockaddr *)&name, &len); +	if (ret < 0) { +		zlog_warn("Can't get remote address and port: %s", +			  safe_strerror(errno)); +		return NULL; +	} + +	if (name.sa.sa_family == AF_INET) { +		su = XCALLOC(MTYPE_SOCKUNION, sizeof(union sockunion)); +		memcpy(su, &name, sizeof(struct sockaddr_in)); +		return su; +	} +	if (name.sa.sa_family == AF_INET6) { +		su = XCALLOC(MTYPE_SOCKUNION, sizeof(union sockunion)); +		memcpy(su, &name, sizeof(struct sockaddr_in6)); +		sockunion_normalise_mapped(su); +		return su; +	} +	return NULL;  }  /* Print sockunion structure */ -static void __attribute__ ((unused)) -sockunion_print (const union sockunion *su) -{ -  if (su == NULL) -    return; - -  switch (su->sa.sa_family)  -    { -    case AF_INET: -      printf ("%s\n", inet_ntoa (su->sin.sin_addr)); -      break; -    case AF_INET6: -      { -	char buf [SU_ADDRSTRLEN]; - -	printf ("%s\n", inet_ntop (AF_INET6, &(su->sin6.sin6_addr), -				 buf, sizeof (buf))); -      } -      break; +static void __attribute__((unused)) sockunion_print(const union sockunion *su) +{ +	if (su == NULL) +		return; + +	switch (su->sa.sa_family) { +	case AF_INET: +		printf("%s\n", inet_ntoa(su->sin.sin_addr)); +		break; +	case AF_INET6: { +		char buf[SU_ADDRSTRLEN]; + +		printf("%s\n", inet_ntop(AF_INET6, &(su->sin6.sin6_addr), buf, +					 sizeof(buf))); +	} break;  #ifdef AF_LINK -    case AF_LINK: -      { -	struct sockaddr_dl *sdl; - -	sdl = (struct sockaddr_dl *)&(su->sa); -	printf ("link#%d\n", sdl->sdl_index); -      } -      break; +	case AF_LINK: { +		struct sockaddr_dl *sdl; + +		sdl = (struct sockaddr_dl *)&(su->sa); +		printf("link#%d\n", sdl->sdl_index); +	} break;  #endif /* AF_LINK */ -    default: -      printf ("af_unknown %d\n", su->sa.sa_family); -      break; -    } +	default: +		printf("af_unknown %d\n", su->sa.sa_family); +		break; +	}  } -static int -in6addr_cmp (const struct in6_addr *addr1, const struct in6_addr *addr2) +static int in6addr_cmp(const struct in6_addr *addr1, +		       const struct in6_addr *addr2)  { -  unsigned int i; -  const u_char *p1, *p2; +	unsigned int i; +	const u_char *p1, *p2; -  p1 = (const u_char *)addr1; -  p2 = (const u_char *)addr2; +	p1 = (const u_char *)addr1; +	p2 = (const u_char *)addr2; -  for (i = 0; i < sizeof (struct in6_addr); i++) -    { -      if (p1[i] > p2[i]) -	return 1; -      else if (p1[i] < p2[i]) -	return -1; -    } -  return 0; +	for (i = 0; i < sizeof(struct in6_addr); i++) { +		if (p1[i] > p2[i]) +			return 1; +		else if (p1[i] < p2[i]) +			return -1; +	} +	return 0;  } -int -sockunion_cmp (const union sockunion *su1, const union sockunion *su2) +int sockunion_cmp(const union sockunion *su1, const union sockunion *su2)  { -  if (su1->sa.sa_family > su2->sa.sa_family) -    return 1; -  if (su1->sa.sa_family < su2->sa.sa_family) -    return -1; +	if (su1->sa.sa_family > su2->sa.sa_family) +		return 1; +	if (su1->sa.sa_family < su2->sa.sa_family) +		return -1; -  if (su1->sa.sa_family == AF_INET) -    { -      if (ntohl (sockunion2ip (su1)) == ntohl (sockunion2ip (su2))) +	if (su1->sa.sa_family == AF_INET) { +		if (ntohl(sockunion2ip(su1)) == ntohl(sockunion2ip(su2))) +			return 0; +		if (ntohl(sockunion2ip(su1)) > ntohl(sockunion2ip(su2))) +			return 1; +		else +			return -1; +	} +	if (su1->sa.sa_family == AF_INET6) +		return in6addr_cmp(&su1->sin6.sin6_addr, &su2->sin6.sin6_addr);  	return 0; -      if (ntohl (sockunion2ip (su1)) > ntohl (sockunion2ip (su2))) -	return 1; -      else -	return -1; -    } -  if (su1->sa.sa_family == AF_INET6) -    return in6addr_cmp (&su1->sin6.sin6_addr, &su2->sin6.sin6_addr); -  return 0;  }  /* Duplicate sockunion. */ -union sockunion * -sockunion_dup (const union sockunion *su) +union sockunion *sockunion_dup(const union sockunion *su)  { -  union sockunion *dup = XCALLOC (MTYPE_SOCKUNION, sizeof (union sockunion)); -  memcpy (dup, su, sizeof (union sockunion)); -  return dup; +	union sockunion *dup = +		XCALLOC(MTYPE_SOCKUNION, sizeof(union sockunion)); +	memcpy(dup, su, sizeof(union sockunion)); +	return dup;  } -void -sockunion_free (union sockunion *su) +void sockunion_free(union sockunion *su)  { -  XFREE (MTYPE_SOCKUNION, su); +	XFREE(MTYPE_SOCKUNION, su);  } -void -sockunion_init (union sockunion *su) +void sockunion_init(union sockunion *su)  { -  memset(su, 0, sizeof(union sockunion)); +	memset(su, 0, sizeof(union sockunion));  } diff --git a/lib/sockunion.h b/lib/sockunion.h index bed68e1ee1..2132a4f729 100644 --- a/lib/sockunion.h +++ b/lib/sockunion.h @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_SOCKUNION_H @@ -29,22 +29,16 @@  #include <netmpls/mpls.h>  #endif -union sockunion  -{ -  struct sockaddr sa; -  struct sockaddr_in sin; -  struct sockaddr_in6 sin6; +union sockunion { +	struct sockaddr sa; +	struct sockaddr_in sin; +	struct sockaddr_in6 sin6;  #ifdef __OpenBSD__ -  struct sockaddr_mpls smpls; +	struct sockaddr_mpls smpls;  #endif  }; -enum connect_result -{ -  connect_error, -  connect_success, -  connect_in_progress -}; +enum connect_result { connect_error, connect_success, connect_in_progress };  /* Default address family. */  #define AF_INET_UNION AF_INET6 @@ -56,11 +50,11 @@ enum connect_result     stack. */  #ifdef KAME  #define	IN6_LINKLOCAL_IFINDEX(a)  ((a).s6_addr[2] << 8 | (a).s6_addr[3]) -#define SET_IN6_LINKLOCAL_IFINDEX(a, i) \ -  do { \ -    (a).s6_addr[2] = ((i) >> 8) & 0xff; \ -    (a).s6_addr[3] = (i) & 0xff; \ -  } while (0) +#define SET_IN6_LINKLOCAL_IFINDEX(a, i)                                        \ +	do {                                                                   \ +		(a).s6_addr[2] = ((i) >> 8) & 0xff;                            \ +		(a).s6_addr[3] = (i)&0xff;                                     \ +	} while (0)  #else  #define	IN6_LINKLOCAL_IFINDEX(a)  #define SET_IN6_LINKLOCAL_IFINDEX(a, i) @@ -71,38 +65,38 @@ enum connect_result  #define sockunion2ip(X)      (X)->sin.sin_addr.s_addr  /* Prototypes. */ -extern int str2sockunion (const char *, union sockunion *); -extern const char *sockunion2str (const union sockunion *, char *, size_t); -extern int sockunion_cmp (const union sockunion *, const union sockunion *); -extern int sockunion_same (const union sockunion *, const union sockunion *); -extern unsigned int sockunion_hash (const union sockunion *); +extern int str2sockunion(const char *, union sockunion *); +extern const char *sockunion2str(const union sockunion *, char *, size_t); +extern int sockunion_cmp(const union sockunion *, const union sockunion *); +extern int sockunion_same(const union sockunion *, const union sockunion *); +extern unsigned int sockunion_hash(const union sockunion *);  extern size_t family2addrsize(int family);  extern size_t sockunion_get_addrlen(const union sockunion *);  extern const u_char *sockunion_get_addr(const union sockunion *); -extern void sockunion_set(union sockunion *, int family, const u_char *addr, size_t bytes); +extern void sockunion_set(union sockunion *, int family, const u_char *addr, +			  size_t bytes); -extern union sockunion *sockunion_str2su (const char *str); -extern int sockunion_accept (int sock, union sockunion *); -extern int sockunion_stream_socket (union sockunion *); -extern int sockopt_reuseaddr (int); -extern int sockopt_reuseport (int); -extern int sockopt_v6only (int family, int sock); -extern int sockunion_bind (int sock, union sockunion *,  -                           unsigned short, union sockunion *); -extern int sockopt_ttl (int family, int sock, int ttl); -extern int sockopt_minttl (int family, int sock, int minttl); -extern int sockopt_cork (int sock, int onoff); +extern union sockunion *sockunion_str2su(const char *str); +extern int sockunion_accept(int sock, union sockunion *); +extern int sockunion_stream_socket(union sockunion *); +extern int sockopt_reuseaddr(int); +extern int sockopt_reuseport(int); +extern int sockopt_v6only(int family, int sock); +extern int sockunion_bind(int sock, union sockunion *, unsigned short, +			  union sockunion *); +extern int sockopt_ttl(int family, int sock, int ttl); +extern int sockopt_minttl(int family, int sock, int minttl); +extern int sockopt_cork(int sock, int onoff);  extern int sockopt_mark_default(int sock, int mark, struct zebra_privs_t *); -extern int sockunion_socket (const union sockunion *su); -extern const char *inet_sutop (const union sockunion *su, char *str); -extern enum connect_result sockunion_connect (int fd, const union sockunion *su,  -                                              unsigned short port, -                                              ifindex_t); -extern union sockunion *sockunion_getsockname (int); -extern union sockunion *sockunion_getpeername (int); -extern union sockunion *sockunion_dup (const union sockunion *); -extern void sockunion_free (union sockunion *); -extern void sockunion_init (union sockunion *); +extern int sockunion_socket(const union sockunion *su); +extern const char *inet_sutop(const union sockunion *su, char *str); +extern enum connect_result sockunion_connect(int fd, const union sockunion *su, +					     unsigned short port, ifindex_t); +extern union sockunion *sockunion_getsockname(int); +extern union sockunion *sockunion_getpeername(int); +extern union sockunion *sockunion_dup(const union sockunion *); +extern void sockunion_free(union sockunion *); +extern void sockunion_init(union sockunion *);  #endif /* _ZEBRA_SOCKUNION_H */ diff --git a/lib/spf_backoff.c b/lib/spf_backoff.c index e923f232b8..a969d86f4e 100644 --- a/lib/spf_backoff.c +++ b/lib/spf_backoff.c @@ -38,232 +38,220 @@ DEFINE_MTYPE_STATIC(LIB, SPF_BACKOFF, "SPF backoff")  DEFINE_MTYPE_STATIC(LIB, SPF_BACKOFF_NAME, "SPF backoff name")  static bool debug_spf_backoff = false; -#define backoff_debug(...) \ -  do \ -    { \ -      if (debug_spf_backoff) \ -        zlog_debug(__VA_ARGS__); \ -    } \ -  while (0) +#define backoff_debug(...)                                                     \ +	do {                                                                   \ +		if (debug_spf_backoff)                                         \ +			zlog_debug(__VA_ARGS__);                               \ +	} while (0)  enum spf_backoff_state { -  SPF_BACKOFF_QUIET, -  SPF_BACKOFF_SHORT_WAIT, -  SPF_BACKOFF_LONG_WAIT +	SPF_BACKOFF_QUIET, +	SPF_BACKOFF_SHORT_WAIT, +	SPF_BACKOFF_LONG_WAIT  };  struct spf_backoff { -  struct thread_master *m; - -  /* Timers as per draft */ -  long init_delay; -  long short_delay; -  long long_delay; -  long holddown; -  long timetolearn; - -  /* State machine */ -  enum spf_backoff_state state; -  struct thread *t_holddown; -  struct thread *t_timetolearn; - -  /* For debugging */ -  char *name; -  struct timeval first_event_time; -  struct timeval last_event_time; +	struct thread_master *m; + +	/* Timers as per draft */ +	long init_delay; +	long short_delay; +	long long_delay; +	long holddown; +	long timetolearn; + +	/* State machine */ +	enum spf_backoff_state state; +	struct thread *t_holddown; +	struct thread *t_timetolearn; + +	/* For debugging */ +	char *name; +	struct timeval first_event_time; +	struct timeval last_event_time;  }; -static const char * -spf_backoff_state2str(enum spf_backoff_state state) +static const char *spf_backoff_state2str(enum spf_backoff_state state)  { -  switch (state) -    { -    case SPF_BACKOFF_QUIET: -      return "QUIET"; -    case SPF_BACKOFF_SHORT_WAIT: -      return "SHORT_WAIT"; -    case SPF_BACKOFF_LONG_WAIT: -      return "LONG_WAIT"; -    } -  return "???"; +	switch (state) { +	case SPF_BACKOFF_QUIET: +		return "QUIET"; +	case SPF_BACKOFF_SHORT_WAIT: +		return "SHORT_WAIT"; +	case SPF_BACKOFF_LONG_WAIT: +		return "LONG_WAIT"; +	} +	return "???";  } -struct spf_backoff * -spf_backoff_new(struct thread_master *m, -                const char *name, -                long init_delay, -                long short_delay, -                long long_delay, -                long holddown, -                long timetolearn) +struct spf_backoff *spf_backoff_new(struct thread_master *m, const char *name, +				    long init_delay, long short_delay, +				    long long_delay, long holddown, +				    long timetolearn)  { -  struct spf_backoff *rv; +	struct spf_backoff *rv; -  rv = XCALLOC(MTYPE_SPF_BACKOFF, sizeof(*rv)); -  rv->m = m; +	rv = XCALLOC(MTYPE_SPF_BACKOFF, sizeof(*rv)); +	rv->m = m; -  rv->init_delay = init_delay; -  rv->short_delay = short_delay; -  rv->long_delay = long_delay; -  rv->holddown = holddown; -  rv->timetolearn = timetolearn; +	rv->init_delay = init_delay; +	rv->short_delay = short_delay; +	rv->long_delay = long_delay; +	rv->holddown = holddown; +	rv->timetolearn = timetolearn; -  rv->state = SPF_BACKOFF_QUIET; +	rv->state = SPF_BACKOFF_QUIET; -  rv->name = XSTRDUP(MTYPE_SPF_BACKOFF_NAME, name); -  return rv; +	rv->name = XSTRDUP(MTYPE_SPF_BACKOFF_NAME, name); +	return rv;  } -void -spf_backoff_free(struct spf_backoff *backoff) +void spf_backoff_free(struct spf_backoff *backoff)  { -  if (!backoff) -    return; +	if (!backoff) +		return; -  THREAD_TIMER_OFF(backoff->t_holddown); -  THREAD_TIMER_OFF(backoff->t_timetolearn); -  XFREE(MTYPE_SPF_BACKOFF_NAME, backoff->name); +	THREAD_TIMER_OFF(backoff->t_holddown); +	THREAD_TIMER_OFF(backoff->t_timetolearn); +	XFREE(MTYPE_SPF_BACKOFF_NAME, backoff->name); -  XFREE(MTYPE_SPF_BACKOFF, backoff); +	XFREE(MTYPE_SPF_BACKOFF, backoff);  } -static int -spf_backoff_timetolearn_elapsed(struct thread *thread) +static int spf_backoff_timetolearn_elapsed(struct thread *thread)  { -  struct spf_backoff *backoff = THREAD_ARG(thread); +	struct spf_backoff *backoff = THREAD_ARG(thread); -  backoff->t_timetolearn = NULL; -  backoff->state = SPF_BACKOFF_LONG_WAIT; -  backoff_debug("SPF Back-off(%s) TIMETOLEARN elapsed, move to state %s", -                backoff->name, spf_backoff_state2str(backoff->state)); -  return 0; +	backoff->t_timetolearn = NULL; +	backoff->state = SPF_BACKOFF_LONG_WAIT; +	backoff_debug("SPF Back-off(%s) TIMETOLEARN elapsed, move to state %s", +		      backoff->name, spf_backoff_state2str(backoff->state)); +	return 0;  } -static int -spf_backoff_holddown_elapsed(struct thread *thread) +static int spf_backoff_holddown_elapsed(struct thread *thread)  { -  struct spf_backoff *backoff = THREAD_ARG(thread); - -  backoff->t_holddown = NULL; -  THREAD_TIMER_OFF(backoff->t_timetolearn); -  timerclear(&backoff->first_event_time); -  backoff->state = SPF_BACKOFF_QUIET; -  backoff_debug("SPF Back-off(%s) HOLDDOWN elapsed, move to state %s", -                backoff->name, spf_backoff_state2str(backoff->state)); -  return 0; +	struct spf_backoff *backoff = THREAD_ARG(thread); + +	backoff->t_holddown = NULL; +	THREAD_TIMER_OFF(backoff->t_timetolearn); +	timerclear(&backoff->first_event_time); +	backoff->state = SPF_BACKOFF_QUIET; +	backoff_debug("SPF Back-off(%s) HOLDDOWN elapsed, move to state %s", +		      backoff->name, spf_backoff_state2str(backoff->state)); +	return 0;  }  long spf_backoff_schedule(struct spf_backoff *backoff)  { -  long rv; -  struct timeval now; - -  gettimeofday(&now, NULL); - -  backoff_debug("SPF Back-off(%s) schedule called in state %s", -                backoff->name, spf_backoff_state2str(backoff->state)); - -  backoff->last_event_time = now; - -  switch (backoff->state) -    { -    case SPF_BACKOFF_QUIET: -      backoff->state = SPF_BACKOFF_SHORT_WAIT; -      THREAD_TIMER_MSEC_ON(backoff->m, backoff->t_timetolearn, -                           spf_backoff_timetolearn_elapsed, backoff, -                           backoff->timetolearn); -      THREAD_TIMER_MSEC_ON(backoff->m, backoff->t_holddown, -                           spf_backoff_holddown_elapsed, backoff, -                           backoff->holddown); -      backoff->first_event_time = now; -      rv = backoff->init_delay; -      break; -    case SPF_BACKOFF_SHORT_WAIT: -    case SPF_BACKOFF_LONG_WAIT: -      THREAD_TIMER_OFF(backoff->t_holddown); -      THREAD_TIMER_MSEC_ON(backoff->m, backoff->t_holddown, -                           spf_backoff_holddown_elapsed, backoff, -                           backoff->holddown); -      if (backoff->state == SPF_BACKOFF_SHORT_WAIT) -        rv = backoff->short_delay; -      else -        rv = backoff->long_delay; -      break; -    default: -      zlog_warn("SPF Back-off(%s) in unknown state", backoff->name); -      rv = backoff->init_delay; -    } - -  backoff_debug("SPF Back-off(%s) changed state to %s and returned %ld delay", -                backoff->name, spf_backoff_state2str(backoff->state), rv); -  return rv; +	long rv; +	struct timeval now; + +	gettimeofday(&now, NULL); + +	backoff_debug("SPF Back-off(%s) schedule called in state %s", +		      backoff->name, spf_backoff_state2str(backoff->state)); + +	backoff->last_event_time = now; + +	switch (backoff->state) { +	case SPF_BACKOFF_QUIET: +		backoff->state = SPF_BACKOFF_SHORT_WAIT; +		THREAD_TIMER_MSEC_ON(backoff->m, backoff->t_timetolearn, +				     spf_backoff_timetolearn_elapsed, backoff, +				     backoff->timetolearn); +		THREAD_TIMER_MSEC_ON(backoff->m, backoff->t_holddown, +				     spf_backoff_holddown_elapsed, backoff, +				     backoff->holddown); +		backoff->first_event_time = now; +		rv = backoff->init_delay; +		break; +	case SPF_BACKOFF_SHORT_WAIT: +	case SPF_BACKOFF_LONG_WAIT: +		THREAD_TIMER_OFF(backoff->t_holddown); +		THREAD_TIMER_MSEC_ON(backoff->m, backoff->t_holddown, +				     spf_backoff_holddown_elapsed, backoff, +				     backoff->holddown); +		if (backoff->state == SPF_BACKOFF_SHORT_WAIT) +			rv = backoff->short_delay; +		else +			rv = backoff->long_delay; +		break; +	default: +		zlog_warn("SPF Back-off(%s) in unknown state", backoff->name); +		rv = backoff->init_delay; +	} + +	backoff_debug( +		"SPF Back-off(%s) changed state to %s and returned %ld delay", +		backoff->name, spf_backoff_state2str(backoff->state), rv); +	return rv;  } -static const char * -timeval_format(struct timeval *tv) +static const char *timeval_format(struct timeval *tv)  { -  struct tm tm_store; -  struct tm *tm; -  static char timebuf[256]; +	struct tm tm_store; +	struct tm *tm; +	static char timebuf[256]; -  if (!tv->tv_sec && !tv->tv_usec) -    return "(never)"; +	if (!tv->tv_sec && !tv->tv_usec) +		return "(never)"; -  tm = localtime_r(&tv->tv_sec, &tm_store); -  if (!tm || strftime(timebuf, sizeof(timebuf), -                      "%Z %a %Y-%m-%d %H:%M:%S", tm) == 0) -    { -      return "???"; -    } +	tm = localtime_r(&tv->tv_sec, &tm_store); +	if (!tm +	    || strftime(timebuf, sizeof(timebuf), "%Z %a %Y-%m-%d %H:%M:%S", tm) +		       == 0) { +		return "???"; +	} -  size_t offset = strlen(timebuf); -  snprintf(timebuf + offset, sizeof(timebuf) - offset, ".%ld", tv->tv_usec); +	size_t offset = strlen(timebuf); +	snprintf(timebuf + offset, sizeof(timebuf) - offset, ".%ld", +		 tv->tv_usec); -  return timebuf; +	return timebuf;  } -void -spf_backoff_show(struct spf_backoff *backoff, struct vty *vty, -                 const char *prefix) +void spf_backoff_show(struct spf_backoff *backoff, struct vty *vty, +		      const char *prefix)  { -  vty_out(vty, "%sCurrent state:     %s%s", prefix, -          spf_backoff_state2str(backoff->state), VTY_NEWLINE); -  vty_out(vty, "%sInit timer:        %ld msec%s", prefix, -          backoff->init_delay, VTY_NEWLINE); -  vty_out(vty, "%sShort timer:       %ld msec%s", prefix, -          backoff->short_delay, VTY_NEWLINE); -  vty_out(vty, "%sLong timer:        %ld msec%s", prefix, -          backoff->long_delay, VTY_NEWLINE); -  vty_out(vty, "%sHolddown timer:    %ld msec%s", prefix, -          backoff->holddown, VTY_NEWLINE); -  if (backoff->t_holddown) -    { -      struct timeval remain = thread_timer_remain(backoff->t_holddown); -      vty_out(vty, "%s                   Still runs for %ld msec%s", -              prefix, remain.tv_sec * 1000 + remain.tv_usec/1000, VTY_NEWLINE); -    } -  else -    { -      vty_out(vty, "%s                   Inactive%s", prefix, VTY_NEWLINE); -    } - -  vty_out(vty, "%sTimeToLearn timer: %ld msec%s", prefix, -          backoff->timetolearn, VTY_NEWLINE); -  if (backoff->t_timetolearn) -    { -      struct timeval remain = thread_timer_remain(backoff->t_timetolearn); -      vty_out(vty, "%s                   Still runs for %ld msec%s", -              prefix, remain.tv_sec * 1000 + remain.tv_usec/1000, VTY_NEWLINE); -    } -  else -    { -      vty_out(vty, "%s                   Inactive%s", prefix, VTY_NEWLINE); -    } - -  vty_out(vty, "%sFirst event:       %s%s", prefix, -          timeval_format(&backoff->first_event_time), VTY_NEWLINE); -  vty_out(vty, "%sLast event:        %s%s", prefix, -          timeval_format(&backoff->last_event_time), VTY_NEWLINE); +	vty_out(vty, "%sCurrent state:     %s%s", prefix, +		spf_backoff_state2str(backoff->state), VTY_NEWLINE); +	vty_out(vty, "%sInit timer:        %ld msec%s", prefix, +		backoff->init_delay, VTY_NEWLINE); +	vty_out(vty, "%sShort timer:       %ld msec%s", prefix, +		backoff->short_delay, VTY_NEWLINE); +	vty_out(vty, "%sLong timer:        %ld msec%s", prefix, +		backoff->long_delay, VTY_NEWLINE); +	vty_out(vty, "%sHolddown timer:    %ld msec%s", prefix, +		backoff->holddown, VTY_NEWLINE); +	if (backoff->t_holddown) { +		struct timeval remain = +			thread_timer_remain(backoff->t_holddown); +		vty_out(vty, "%s                   Still runs for %ld msec%s", +			prefix, remain.tv_sec * 1000 + remain.tv_usec / 1000, +			VTY_NEWLINE); +	} else { +		vty_out(vty, "%s                   Inactive%s", prefix, +			VTY_NEWLINE); +	} + +	vty_out(vty, "%sTimeToLearn timer: %ld msec%s", prefix, +		backoff->timetolearn, VTY_NEWLINE); +	if (backoff->t_timetolearn) { +		struct timeval remain = +			thread_timer_remain(backoff->t_timetolearn); +		vty_out(vty, "%s                   Still runs for %ld msec%s", +			prefix, remain.tv_sec * 1000 + remain.tv_usec / 1000, +			VTY_NEWLINE); +	} else { +		vty_out(vty, "%s                   Inactive%s", prefix, +			VTY_NEWLINE); +	} + +	vty_out(vty, "%sFirst event:       %s%s", prefix, +		timeval_format(&backoff->first_event_time), VTY_NEWLINE); +	vty_out(vty, "%sLast event:        %s%s", prefix, +		timeval_format(&backoff->last_event_time), VTY_NEWLINE);  }  DEFUN(spf_backoff_debug, @@ -272,8 +260,8 @@ DEFUN(spf_backoff_debug,        DEBUG_STR        "SPF Back-off Debugging\n")  { -  debug_spf_backoff = true; -  return CMD_SUCCESS; +	debug_spf_backoff = true; +	return CMD_SUCCESS;  }  DEFUN(no_spf_backoff_debug, @@ -283,59 +271,51 @@ DEFUN(no_spf_backoff_debug,        DEBUG_STR        "SPF Back-off Debugging\n")  { -  debug_spf_backoff = false; -  return CMD_SUCCESS; +	debug_spf_backoff = false; +	return CMD_SUCCESS;  } -int -spf_backoff_write_config(struct vty *vty) +int spf_backoff_write_config(struct vty *vty)  { -  int written = 0; +	int written = 0; -  if (debug_spf_backoff) -    { -      vty_out(vty, "debug spf-delay-ietf%s", VTY_NEWLINE); -      written++; -    } +	if (debug_spf_backoff) { +		vty_out(vty, "debug spf-delay-ietf%s", VTY_NEWLINE); +		written++; +	} -  return written; +	return written;  } -void -spf_backoff_cmd_init(void) +void spf_backoff_cmd_init(void)  { -  install_element(ENABLE_NODE, &spf_backoff_debug_cmd); -  install_element(CONFIG_NODE, &spf_backoff_debug_cmd); -  install_element(ENABLE_NODE, &no_spf_backoff_debug_cmd); -  install_element(CONFIG_NODE, &no_spf_backoff_debug_cmd); +	install_element(ENABLE_NODE, &spf_backoff_debug_cmd); +	install_element(CONFIG_NODE, &spf_backoff_debug_cmd); +	install_element(ENABLE_NODE, &no_spf_backoff_debug_cmd); +	install_element(CONFIG_NODE, &no_spf_backoff_debug_cmd);  } -long -spf_backoff_init_delay(struct spf_backoff *backoff) +long spf_backoff_init_delay(struct spf_backoff *backoff)  { -  return backoff->init_delay; +	return backoff->init_delay;  } -long -spf_backoff_short_delay(struct spf_backoff *backoff) +long spf_backoff_short_delay(struct spf_backoff *backoff)  { -  return backoff->short_delay; +	return backoff->short_delay;  } -long -spf_backoff_long_delay(struct spf_backoff *backoff) +long spf_backoff_long_delay(struct spf_backoff *backoff)  { -  return backoff->long_delay; +	return backoff->long_delay;  } -long -spf_backoff_holddown(struct spf_backoff *backoff) +long spf_backoff_holddown(struct spf_backoff *backoff)  { -  return backoff->holddown; +	return backoff->holddown;  } -long -spf_backoff_timetolearn(struct spf_backoff *backoff) +long spf_backoff_timetolearn(struct spf_backoff *backoff)  { -  return backoff->timetolearn; +	return backoff->timetolearn;  } diff --git a/lib/spf_backoff.h b/lib/spf_backoff.h index 552ca4ae41..127e71102d 100644 --- a/lib/spf_backoff.h +++ b/lib/spf_backoff.h @@ -31,13 +31,10 @@ struct spf_backoff;  struct thread_master;  struct vty; -struct spf_backoff *spf_backoff_new(struct thread_master *m, -                                    const char *name, -                                    long init_delay, -                                    long short_delay, -                                    long long_delay, -                                    long holddown, -                                    long timetolearn); +struct spf_backoff *spf_backoff_new(struct thread_master *m, const char *name, +				    long init_delay, long short_delay, +				    long long_delay, long holddown, +				    long timetolearn);  void spf_backoff_free(struct spf_backoff *backoff); @@ -46,9 +43,8 @@ void spf_backoff_free(struct spf_backoff *backoff);  long spf_backoff_schedule(struct spf_backoff *backoff);  /* Shows status of SPF backoff instance */ -void spf_backoff_show(struct spf_backoff *backoff, -                      struct vty *vty, -                      const char *prefix); +void spf_backoff_show(struct spf_backoff *backoff, struct vty *vty, +		      const char *prefix);  /* Writes out global SPF backoff debug config */  int spf_backoff_write_config(struct vty *vty); diff --git a/lib/srcdest_table.c b/lib/srcdest_table.c index 04c9eff79a..62f6659633 100644 --- a/lib/srcdest_table.c +++ b/lib/srcdest_table.c @@ -33,59 +33,54 @@  DEFINE_MTYPE_STATIC(LIB, ROUTE_SRC_NODE, "Route source node")  /* ----- functions to manage rnodes _with_ srcdest table ----- */ -struct srcdest_rnode -{ -  /* must be first in structure for casting to/from route_node */ -  ROUTE_NODE_FIELDS; +struct srcdest_rnode { +	/* must be first in structure for casting to/from route_node */ +	ROUTE_NODE_FIELDS; -  struct route_table *src_table; +	struct route_table *src_table;  }; -static struct srcdest_rnode * -srcdest_rnode_from_rnode (struct route_node *rn) +static struct srcdest_rnode *srcdest_rnode_from_rnode(struct route_node *rn)  { -  assert (rnode_is_dstnode (rn)); -  return (struct srcdest_rnode *) rn; +	assert(rnode_is_dstnode(rn)); +	return (struct srcdest_rnode *)rn;  } -static struct route_node * -srcdest_rnode_to_rnode (struct srcdest_rnode *srn) +static struct route_node *srcdest_rnode_to_rnode(struct srcdest_rnode *srn)  { -  return (struct route_node *) srn; +	return (struct route_node *)srn;  } -static struct route_node * -srcdest_rnode_create (route_table_delegate_t *delegate, -		      struct route_table *table) +static struct route_node *srcdest_rnode_create(route_table_delegate_t *delegate, +					       struct route_table *table)  { -  struct srcdest_rnode *srn; -  srn = XCALLOC (MTYPE_ROUTE_NODE, sizeof (struct srcdest_rnode)); -  return srcdest_rnode_to_rnode(srn); +	struct srcdest_rnode *srn; +	srn = XCALLOC(MTYPE_ROUTE_NODE, sizeof(struct srcdest_rnode)); +	return srcdest_rnode_to_rnode(srn);  } -static void -srcdest_rnode_destroy (route_table_delegate_t *delegate, -		       struct route_table *table, struct route_node *rn) +static void srcdest_rnode_destroy(route_table_delegate_t *delegate, +				  struct route_table *table, +				  struct route_node *rn)  { -  struct srcdest_rnode *srn = srcdest_rnode_from_rnode(rn); -  struct route_table *src_table; - -  /* Clear route node's src_table here already, otherwise the -   * deletion of the last node in the src_table will trigger -   * another call to route_table_finish for the src_table. -   * -   * (Compare with srcdest_srcnode_destroy) -   */ -  src_table = srn->src_table; -  srn->src_table = NULL; -  route_table_finish(src_table); -  XFREE (MTYPE_ROUTE_NODE, rn); +	struct srcdest_rnode *srn = srcdest_rnode_from_rnode(rn); +	struct route_table *src_table; + +	/* Clear route node's src_table here already, otherwise the +	 * deletion of the last node in the src_table will trigger +	 * another call to route_table_finish for the src_table. +	 * +	 * (Compare with srcdest_srcnode_destroy) +	 */ +	src_table = srn->src_table; +	srn->src_table = NULL; +	route_table_finish(src_table); +	XFREE(MTYPE_ROUTE_NODE, rn);  }  route_table_delegate_t _srcdest_dstnode_delegate = { -  .create_node = srcdest_rnode_create, -  .destroy_node = srcdest_rnode_destroy -}; +	.create_node = srcdest_rnode_create, +	.destroy_node = srcdest_rnode_destroy};  /* ----- functions to manage rnodes _in_ srcdest table ----- */ @@ -95,218 +90,209 @@ route_table_delegate_t _srcdest_dstnode_delegate = {   * destination prefix's route_node) */  static struct route_node * -srcdest_srcnode_create (route_table_delegate_t *delegate, -		   struct route_table *table) +srcdest_srcnode_create(route_table_delegate_t *delegate, +		       struct route_table *table)  { -  return XCALLOC (MTYPE_ROUTE_SRC_NODE, sizeof (struct route_node)); +	return XCALLOC(MTYPE_ROUTE_SRC_NODE, sizeof(struct route_node));  } -static void -srcdest_srcnode_destroy (route_table_delegate_t *delegate, -		    struct route_table *table, struct route_node *rn) +static void srcdest_srcnode_destroy(route_table_delegate_t *delegate, +				    struct route_table *table, +				    struct route_node *rn)  { -  struct srcdest_rnode *srn; - -  XFREE (MTYPE_ROUTE_SRC_NODE, rn); - -  srn = table->info; -  if (srn->src_table && route_table_count (srn->src_table) == 0) -    { -      /* deleting the route_table from inside destroy_node is ONLY -       * permitted IF table->count is 0!  see lib/table.c route_node_delete() -       * for details */ -      route_table_finish (srn->src_table); -      srn->src_table = NULL; - -      /* drop the ref we're holding in srcdest_node_get().  there might be -       * non-srcdest routes, so the route_node may still exist.  hence, it's -       * important to clear src_table above. */ -      route_unlock_node (srcdest_rnode_to_rnode (srn)); -    } +	struct srcdest_rnode *srn; + +	XFREE(MTYPE_ROUTE_SRC_NODE, rn); + +	srn = table->info; +	if (srn->src_table && route_table_count(srn->src_table) == 0) { +		/* deleting the route_table from inside destroy_node is ONLY +		 * permitted IF table->count is 0!  see lib/table.c +		 * route_node_delete() +		 * for details */ +		route_table_finish(srn->src_table); +		srn->src_table = NULL; + +		/* drop the ref we're holding in srcdest_node_get().  there +		 * might be +		 * non-srcdest routes, so the route_node may still exist. +		 * hence, it's +		 * important to clear src_table above. */ +		route_unlock_node(srcdest_rnode_to_rnode(srn)); +	}  }  route_table_delegate_t _srcdest_srcnode_delegate = { -  .create_node = srcdest_srcnode_create, -  .destroy_node = srcdest_srcnode_destroy -}; +	.create_node = srcdest_srcnode_create, +	.destroy_node = srcdest_srcnode_destroy};  /* NB: read comments in code for refcounting before using! */ -static struct route_node * -srcdest_srcnode_get (struct route_node *rn, struct prefix_ipv6 *src_p) +static struct route_node *srcdest_srcnode_get(struct route_node *rn, +					      struct prefix_ipv6 *src_p)  { -  struct srcdest_rnode *srn; - -  if (!src_p || src_p->prefixlen == 0) -    return rn; - -  srn = srcdest_rnode_from_rnode (rn); -  if (!srn->src_table) -    { -      /* this won't use srcdest_rnode, we're already on the source here */ -      srn->src_table = route_table_init_with_delegate (&_srcdest_srcnode_delegate); -      srn->src_table->info = srn; - -      /* there is no route_unlock_node on the original rn here. -       * The reference is kept for the src_table. */ -    } -  else -    { -      /* only keep 1 reference for the src_table, makes the refcounting -       * more similar to the non-srcdest case.  Either way after return from -       * function, the only reference held is the one on the return value. -       * -       * We can safely drop our reference here because src_table is holding -       * another reference, so this won't free rn */ -      route_unlock_node (rn); -    } - -  return route_node_get (srn->src_table, (struct prefix *)src_p); +	struct srcdest_rnode *srn; + +	if (!src_p || src_p->prefixlen == 0) +		return rn; + +	srn = srcdest_rnode_from_rnode(rn); +	if (!srn->src_table) { +		/* this won't use srcdest_rnode, we're already on the source +		 * here */ +		srn->src_table = route_table_init_with_delegate( +			&_srcdest_srcnode_delegate); +		srn->src_table->info = srn; + +		/* there is no route_unlock_node on the original rn here. +		 * The reference is kept for the src_table. */ +	} else { +		/* only keep 1 reference for the src_table, makes the +		 * refcounting +		 * more similar to the non-srcdest case.  Either way after +		 * return from +		 * function, the only reference held is the one on the return +		 * value. +		 * +		 * We can safely drop our reference here because src_table is +		 * holding +		 * another reference, so this won't free rn */ +		route_unlock_node(rn); +	} + +	return route_node_get(srn->src_table, (struct prefix *)src_p);  } -static struct route_node * -srcdest_srcnode_lookup (struct route_node *rn, struct prefix_ipv6 *src_p) +static struct route_node *srcdest_srcnode_lookup(struct route_node *rn, +						 struct prefix_ipv6 *src_p)  { -  struct srcdest_rnode *srn; +	struct srcdest_rnode *srn; -  if (!rn || !src_p || src_p->prefixlen == 0) -    return rn; +	if (!rn || !src_p || src_p->prefixlen == 0) +		return rn; -  /* We got this rn from a lookup, so its refcnt was incremented. As we won't -   * return return rn from any point beyond here, we should decrement its refcnt. -   */ -  route_unlock_node (rn); +	/* We got this rn from a lookup, so its refcnt was incremented. As we +	 * won't +	 * return return rn from any point beyond here, we should decrement its +	 * refcnt. +	 */ +	route_unlock_node(rn); -  srn = srcdest_rnode_from_rnode (rn); -  if (!srn->src_table) -    return NULL; +	srn = srcdest_rnode_from_rnode(rn); +	if (!srn->src_table) +		return NULL; -  return route_node_lookup (srn->src_table, (struct prefix *)src_p); +	return route_node_lookup(srn->src_table, (struct prefix *)src_p);  }  /* ----- exported functions ----- */ -struct route_table * -srcdest_table_init(void) +struct route_table *srcdest_table_init(void)  { -  return route_table_init_with_delegate(&_srcdest_dstnode_delegate); +	return route_table_init_with_delegate(&_srcdest_dstnode_delegate);  } -struct route_node * -srcdest_route_next(struct route_node *rn) +struct route_node *srcdest_route_next(struct route_node *rn)  { -  struct route_node *next, *parent; - -  /* For a non src-dest node, just return route_next */ -  if (!(rnode_is_dstnode(rn) || rnode_is_srcnode(rn))) -    return route_next(rn); - -  if (rnode_is_dstnode(rn)) -    { -      /* This means the route_node is part of the top hierarchy -       * and refers to a destination prefix. */ -      struct srcdest_rnode *srn = srcdest_rnode_from_rnode(rn); - -      if (srn->src_table) -        next = route_top(srn->src_table); -      else -        next = NULL; - -      if (next) -        { -          /* There is a source prefix. Return the node for it */ -          route_unlock_node(rn); -          return next; -        } -      else -        { -          /* There is no source prefix, just continue as usual */ -          return route_next(rn); -        } -    } - -  /* This part handles the case of iterating source nodes. */ -  parent = route_lock_node(rn->table->info); -  next = route_next(rn); - -  if (next) -    { -      /* There is another source node, continue in the source table */ -      route_unlock_node(parent); -      return next; -    } -  else -    { -      /* The source table is complete, continue in the parent table */ -      return route_next(parent); -    } +	struct route_node *next, *parent; + +	/* For a non src-dest node, just return route_next */ +	if (!(rnode_is_dstnode(rn) || rnode_is_srcnode(rn))) +		return route_next(rn); + +	if (rnode_is_dstnode(rn)) { +		/* This means the route_node is part of the top hierarchy +		 * and refers to a destination prefix. */ +		struct srcdest_rnode *srn = srcdest_rnode_from_rnode(rn); + +		if (srn->src_table) +			next = route_top(srn->src_table); +		else +			next = NULL; + +		if (next) { +			/* There is a source prefix. Return the node for it */ +			route_unlock_node(rn); +			return next; +		} else { +			/* There is no source prefix, just continue as usual */ +			return route_next(rn); +		} +	} + +	/* This part handles the case of iterating source nodes. */ +	parent = route_lock_node(rn->table->info); +	next = route_next(rn); + +	if (next) { +		/* There is another source node, continue in the source table */ +		route_unlock_node(parent); +		return next; +	} else { +		/* The source table is complete, continue in the parent table */ +		return route_next(parent); +	}  } -struct route_node * -srcdest_rnode_get (struct route_table *table, union prefixptr dst_pu, -                  struct prefix_ipv6 *src_p) +struct route_node *srcdest_rnode_get(struct route_table *table, +				     union prefixptr dst_pu, +				     struct prefix_ipv6 *src_p)  { -  struct prefix_ipv6 *dst_p = dst_pu.p6; -  struct route_node *rn; +	struct prefix_ipv6 *dst_p = dst_pu.p6; +	struct route_node *rn; -  rn = route_node_get (table, (struct prefix *) dst_p); -  return srcdest_srcnode_get (rn, src_p); +	rn = route_node_get(table, (struct prefix *)dst_p); +	return srcdest_srcnode_get(rn, src_p);  } -struct route_node * -srcdest_rnode_lookup (struct route_table *table, union prefixptr dst_pu, -                      struct prefix_ipv6 *src_p) +struct route_node *srcdest_rnode_lookup(struct route_table *table, +					union prefixptr dst_pu, +					struct prefix_ipv6 *src_p)  { -  struct prefix_ipv6 *dst_p = dst_pu.p6; -  struct route_node *rn; -  struct route_node *srn; - -  rn = route_node_lookup_maynull (table, (struct prefix *) dst_p); -  srn = srcdest_srcnode_lookup (rn, src_p); - -  if (rn != NULL && rn == srn && !rn->info) -    { -      /* Match the behavior of route_node_lookup and don't return an -       * empty route-node for a dest-route */ -      route_unlock_node(rn); -      return NULL; -    } -  return srn; +	struct prefix_ipv6 *dst_p = dst_pu.p6; +	struct route_node *rn; +	struct route_node *srn; + +	rn = route_node_lookup_maynull(table, (struct prefix *)dst_p); +	srn = srcdest_srcnode_lookup(rn, src_p); + +	if (rn != NULL && rn == srn && !rn->info) { +		/* Match the behavior of route_node_lookup and don't return an +		 * empty route-node for a dest-route */ +		route_unlock_node(rn); +		return NULL; +	} +	return srn;  } -void -srcdest_rnode_prefixes (struct route_node *rn, struct prefix **p, -		    struct prefix **src_p) +void srcdest_rnode_prefixes(struct route_node *rn, struct prefix **p, +			    struct prefix **src_p)  { -  if (rnode_is_srcnode (rn)) -    { -      struct route_node *dst_rn = rn->table->info; -      if (p) -	*p = &dst_rn->p; -      if (src_p) -	*src_p = &rn->p; -    } -  else -    { -      if (p) -	*p = &rn->p; -      if (src_p) -	*src_p = NULL; -    } +	if (rnode_is_srcnode(rn)) { +		struct route_node *dst_rn = rn->table->info; +		if (p) +			*p = &dst_rn->p; +		if (src_p) +			*src_p = &rn->p; +	} else { +		if (p) +			*p = &rn->p; +		if (src_p) +			*src_p = NULL; +	}  } -const char * -srcdest_rnode2str (struct route_node *rn, char *str, int size) +const char *srcdest_rnode2str(struct route_node *rn, char *str, int size)  { -  struct prefix *dst_p, *src_p; -  char dst_buf[PREFIX_STRLEN], src_buf[PREFIX_STRLEN]; - -  srcdest_rnode_prefixes(rn, &dst_p, &src_p); - -  snprintf(str, size, "%s%s%s", -           prefix2str(dst_p, dst_buf, sizeof(dst_buf)), -           (src_p && src_p->prefixlen) ? " from " : "", -           (src_p && src_p->prefixlen) ? prefix2str(src_p, src_buf, -                                                    sizeof(src_buf)) -                                       : ""); -  return str; +	struct prefix *dst_p, *src_p; +	char dst_buf[PREFIX_STRLEN], src_buf[PREFIX_STRLEN]; + +	srcdest_rnode_prefixes(rn, &dst_p, &src_p); + +	snprintf(str, size, "%s%s%s", +		 prefix2str(dst_p, dst_buf, sizeof(dst_buf)), +		 (src_p && src_p->prefixlen) ? " from " : "", +		 (src_p && src_p->prefixlen) +			 ? prefix2str(src_p, src_buf, sizeof(src_buf)) +			 : ""); +	return str;  } diff --git a/lib/srcdest_table.h b/lib/srcdest_table.h index 207f5d121d..0a69cb6e82 100644 --- a/lib/srcdest_table.h +++ b/lib/srcdest_table.h @@ -57,45 +57,39 @@ extern route_table_delegate_t _srcdest_srcnode_delegate;  extern struct route_table *srcdest_table_init(void);  extern struct route_node *srcdest_rnode_get(struct route_table *table, -                                            union prefixptr dst_pu, -                                            struct prefix_ipv6 *src_p); +					    union prefixptr dst_pu, +					    struct prefix_ipv6 *src_p);  extern struct route_node *srcdest_rnode_lookup(struct route_table *table, -                                            union prefixptr dst_pu, -                                            struct prefix_ipv6 *src_p); -extern void srcdest_rnode_prefixes (struct route_node *rn, struct prefix **p, -                                    struct prefix **src_p); -extern const char *srcdest_rnode2str(struct route_node *rn, char *str, int size); +					       union prefixptr dst_pu, +					       struct prefix_ipv6 *src_p); +extern void srcdest_rnode_prefixes(struct route_node *rn, struct prefix **p, +				   struct prefix **src_p); +extern const char *srcdest_rnode2str(struct route_node *rn, char *str, +				     int size);  extern struct route_node *srcdest_route_next(struct route_node *rn); -static inline int -rnode_is_dstnode (struct route_node *rn) +static inline int rnode_is_dstnode(struct route_node *rn)  { -  return rn->table->delegate == &_srcdest_dstnode_delegate; +	return rn->table->delegate == &_srcdest_dstnode_delegate;  } -static inline int -rnode_is_srcnode (struct route_node *rn) +static inline int rnode_is_srcnode(struct route_node *rn)  { -  return rn->table->delegate == &_srcdest_srcnode_delegate; +	return rn->table->delegate == &_srcdest_srcnode_delegate;  } -static inline struct route_table * -srcdest_rnode_table (struct route_node *rn) +static inline struct route_table *srcdest_rnode_table(struct route_node *rn)  { -  if (rnode_is_srcnode (rn)) -    { -      struct route_node *dst_rn = rn->table->info; -      return dst_rn->table; -    } -  else -    { -      return rn->table; -    } +	if (rnode_is_srcnode(rn)) { +		struct route_node *dst_rn = rn->table->info; +		return dst_rn->table; +	} else { +		return rn->table; +	}  } -static inline void * -srcdest_rnode_table_info (struct route_node *rn) +static inline void *srcdest_rnode_table_info(struct route_node *rn)  { -  return srcdest_rnode_table(rn)->info; +	return srcdest_rnode_table(rn)->info;  }  #endif /* _ZEBRA_SRC_DEST_TABLE_H */ diff --git a/lib/stream.c b/lib/stream.c index 301ebc6275..7e9bfcca7c 100644 --- a/lib/stream.c +++ b/lib/stream.c @@ -1,24 +1,24 @@ -  /* - * Packet interface - * Copyright (C) 1999 Kunihiro Ishiguro - * - * This file is part of GNU Zebra. - * - * GNU Zebra is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the - * Free Software Foundation; either version 2, or (at your option) any - * later version. - * - * GNU Zebra is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU - * General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with GNU Zebra; see the file COPYING.  If not, write to the Free - * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   - */ +/* +*Packet interface +*Copyright (C) 1999 Kunihiro Ishiguro +* +*This file is part of GNU Zebra. +* +*GNU Zebra is free software; you can redistribute it and/or modify it +*under the terms of the GNU General Public License as published by the +*Free Software Foundation; either version 2, or (at your option) any +*later version. +* +*GNU Zebra is distributed in the hope that it will be useful, but +*WITHOUT ANY WARRANTY; without even the implied warranty of +*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU +*General Public License for more details. +* +*You should have received a copy of the GNU General Public License +*along with GNU Zebra; see the file COPYING.  If not, write to the Free +*Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +*02111-1307, USA. +*/  #include <zebra.h>  #include <stddef.h> @@ -29,16 +29,14 @@  #include "prefix.h"  #include "log.h" -DEFINE_MTYPE_STATIC(LIB, STREAM,      "Stream") +DEFINE_MTYPE_STATIC(LIB, STREAM, "Stream")  DEFINE_MTYPE_STATIC(LIB, STREAM_DATA, "Stream data")  DEFINE_MTYPE_STATIC(LIB, STREAM_FIFO, "Stream FIFO") -/* Tests whether a position is valid */  -#define GETP_VALID(S,G) \ -  ((G) <= (S)->endp) +/* Tests whether a position is valid */ +#define GETP_VALID(S, G) ((G) <= (S)->endp)  #define PUT_AT_VALID(S,G) GETP_VALID(S,G) -#define ENDP_VALID(S,E) \ -  ((E) <= (S)->size) +#define ENDP_VALID(S, E) ((E) <= (S)->size)  /* asserting sanity checks. Following must be true before   * stream functions are called: @@ -55,518 +53,471 @@ DEFINE_MTYPE_STATIC(LIB, STREAM_FIFO, "Stream FIFO")   * It is valid to put to anywhere within the size of the stream, but only   * using stream_put..._at() functions.   */ -#define STREAM_WARN_OFFSETS(S) \ -  zlog_warn ("&(struct stream): %p, size: %lu, getp: %lu, endp: %lu\n", \ -             (void *)(S), \ -             (unsigned long) (S)->size, \ -             (unsigned long) (S)->getp, \ -             (unsigned long) (S)->endp)\ - -#define STREAM_VERIFY_SANE(S) \ -  do { \ -    if ( !(GETP_VALID(S, (S)->getp) && ENDP_VALID(S, (S)->endp)) ) \ -      STREAM_WARN_OFFSETS(S); \ -    assert ( GETP_VALID(S, (S)->getp) ); \ -    assert ( ENDP_VALID(S, (S)->endp) ); \ -  } while (0) - -#define STREAM_BOUND_WARN(S, WHAT) \ -  do { \ -    zlog_warn ("%s: Attempt to %s out of bounds", __func__, (WHAT)); \ -    STREAM_WARN_OFFSETS(S); \ -    assert (0); \ -  } while (0) +#define STREAM_WARN_OFFSETS(S)                                                 \ +	zlog_warn("&(struct stream): %p, size: %lu, getp: %lu, endp: %lu\n",   \ +		  (void *)(S), (unsigned long)(S)->size,                       \ +		  (unsigned long)(S)->getp, (unsigned long)(S)->endp) + +#define STREAM_VERIFY_SANE(S)                                                  \ +	do {                                                                   \ +		if (!(GETP_VALID(S, (S)->getp) && ENDP_VALID(S, (S)->endp)))   \ +			STREAM_WARN_OFFSETS(S);                                \ +		assert(GETP_VALID(S, (S)->getp));                              \ +		assert(ENDP_VALID(S, (S)->endp));                              \ +	} while (0) + +#define STREAM_BOUND_WARN(S, WHAT)                                             \ +	do {                                                                   \ +		zlog_warn("%s: Attempt to %s out of bounds", __func__,         \ +			  (WHAT));                                             \ +		STREAM_WARN_OFFSETS(S);                                        \ +		assert(0);                                                     \ +	} while (0)  /* XXX: Deprecated macro: do not use */ -#define CHECK_SIZE(S, Z) \ -  do { \ -    if (((S)->endp + (Z)) > (S)->size) \ -      { \ -        zlog_warn ("CHECK_SIZE: truncating requested size %lu\n", \ -                   (unsigned long) (Z)); \ -        STREAM_WARN_OFFSETS(S); \ -        (Z) = (S)->size - (S)->endp; \ -      } \ -  } while (0); +#define CHECK_SIZE(S, Z)                                                       \ +	do {                                                                   \ +		if (((S)->endp + (Z)) > (S)->size) {                           \ +			zlog_warn(                                             \ +				"CHECK_SIZE: truncating requested size %lu\n", \ +				(unsigned long)(Z));                           \ +			STREAM_WARN_OFFSETS(S);                                \ +			(Z) = (S)->size - (S)->endp;                           \ +		}                                                              \ +	} while (0);  /* Make stream buffer. */ -struct stream * -stream_new (size_t size) +struct stream *stream_new(size_t size)  { -  struct stream *s; - -  assert (size > 0); -   -  s = XCALLOC (MTYPE_STREAM, sizeof (struct stream)); - -  if (s == NULL) -    return s; -   -  if ( (s->data = XMALLOC (MTYPE_STREAM_DATA, size)) == NULL) -    { -      XFREE (MTYPE_STREAM, s); -      return NULL; -    } -   -  s->size = size; -  return s; +	struct stream *s; + +	assert(size > 0); + +	s = XCALLOC(MTYPE_STREAM, sizeof(struct stream)); + +	if (s == NULL) +		return s; + +	if ((s->data = XMALLOC(MTYPE_STREAM_DATA, size)) == NULL) { +		XFREE(MTYPE_STREAM, s); +		return NULL; +	} + +	s->size = size; +	return s;  }  /* Free it now. */ -void -stream_free (struct stream *s) +void stream_free(struct stream *s)  { -  if (!s) -    return; -   -  XFREE (MTYPE_STREAM_DATA, s->data); -  XFREE (MTYPE_STREAM, s); +	if (!s) +		return; + +	XFREE(MTYPE_STREAM_DATA, s->data); +	XFREE(MTYPE_STREAM, s);  } -struct stream * -stream_copy (struct stream *new, struct stream *src) +struct stream *stream_copy(struct stream *new, struct stream *src)  { -  STREAM_VERIFY_SANE (src); -   -  assert (new != NULL); -  assert (STREAM_SIZE(new) >= src->endp); - -  new->endp = src->endp; -  new->getp = src->getp; -   -  memcpy (new->data, src->data, src->endp); -   -  return new; +	STREAM_VERIFY_SANE(src); + +	assert(new != NULL); +	assert(STREAM_SIZE(new) >= src->endp); + +	new->endp = src->endp; +	new->getp = src->getp; + +	memcpy(new->data, src->data, src->endp); + +	return new;  } -struct stream * -stream_dup (struct stream *s) +struct stream *stream_dup(struct stream *s)  { -  struct stream *new; +	struct stream *new; -  STREAM_VERIFY_SANE (s); +	STREAM_VERIFY_SANE(s); -  if ( (new = stream_new (s->endp)) == NULL) -    return NULL; +	if ((new = stream_new(s->endp)) == NULL) +		return NULL; -  return (stream_copy (new, s)); +	return (stream_copy(new, s));  } -struct stream * -stream_dupcat (struct stream *s1, struct stream *s2, size_t offset) +struct stream *stream_dupcat(struct stream *s1, struct stream *s2, +			     size_t offset)  { -  struct stream *new; +	struct stream *new; -  STREAM_VERIFY_SANE (s1); -  STREAM_VERIFY_SANE (s2); +	STREAM_VERIFY_SANE(s1); +	STREAM_VERIFY_SANE(s2); -  if ( (new = stream_new (s1->endp + s2->endp)) == NULL) -    return NULL; +	if ((new = stream_new(s1->endp + s2->endp)) == NULL) +		return NULL; -  memcpy (new->data, s1->data, offset); -  memcpy (new->data + offset, s2->data, s2->endp); -  memcpy (new->data + offset + s2->endp, s1->data + offset, -	  (s1->endp - offset)); -  new->endp = s1->endp + s2->endp; -  return new; +	memcpy(new->data, s1->data, offset); +	memcpy(new->data + offset, s2->data, s2->endp); +	memcpy(new->data + offset + s2->endp, s1->data + offset, +	       (s1->endp - offset)); +	new->endp = s1->endp + s2->endp; +	return new;  } -size_t -stream_resize (struct stream *s, size_t newsize) +size_t stream_resize(struct stream *s, size_t newsize)  { -  u_char *newdata; -  STREAM_VERIFY_SANE (s); -   -  newdata = XREALLOC (MTYPE_STREAM_DATA, s->data, newsize); -   -  if (newdata == NULL) -    return s->size; -   -  s->data = newdata; -  s->size = newsize; -   -  if (s->endp > s->size) -    s->endp = s->size; -  if (s->getp > s->endp) -    s->getp = s->endp; -   -  STREAM_VERIFY_SANE (s); -   -  return s->size; +	u_char *newdata; +	STREAM_VERIFY_SANE(s); + +	newdata = XREALLOC(MTYPE_STREAM_DATA, s->data, newsize); + +	if (newdata == NULL) +		return s->size; + +	s->data = newdata; +	s->size = newsize; + +	if (s->endp > s->size) +		s->endp = s->size; +	if (s->getp > s->endp) +		s->getp = s->endp; + +	STREAM_VERIFY_SANE(s); + +	return s->size;  } -size_t -stream_get_getp (struct stream *s) +size_t stream_get_getp(struct stream *s)  { -  STREAM_VERIFY_SANE(s); -  return s->getp; +	STREAM_VERIFY_SANE(s); +	return s->getp;  } -size_t -stream_get_endp (struct stream *s) +size_t stream_get_endp(struct stream *s)  { -  STREAM_VERIFY_SANE(s); -  return s->endp; +	STREAM_VERIFY_SANE(s); +	return s->endp;  } -size_t -stream_get_size (struct stream *s) +size_t stream_get_size(struct stream *s)  { -  STREAM_VERIFY_SANE(s); -  return s->size; +	STREAM_VERIFY_SANE(s); +	return s->size;  }  /* Stream structre' stream pointer related functions.  */ -void -stream_set_getp (struct stream *s, size_t pos) +void stream_set_getp(struct stream *s, size_t pos)  { -  STREAM_VERIFY_SANE(s); -   -  if (!GETP_VALID (s, pos)) -    { -      STREAM_BOUND_WARN (s, "set getp"); -      pos = s->endp; -    } - -  s->getp = pos; +	STREAM_VERIFY_SANE(s); + +	if (!GETP_VALID(s, pos)) { +		STREAM_BOUND_WARN(s, "set getp"); +		pos = s->endp; +	} + +	s->getp = pos;  } -void -stream_set_endp (struct stream *s, size_t pos) +void stream_set_endp(struct stream *s, size_t pos)  { -  STREAM_VERIFY_SANE(s); - -  if (!ENDP_VALID(s, pos)) -    { -      STREAM_BOUND_WARN (s, "set endp"); -      return; -    } - -  /* -   * Make sure the current read pointer is not beyond the new endp. -   */ -  if (s->getp > pos) -    { -      STREAM_BOUND_WARN(s, "set endp"); -      return; -    } - -  s->endp = pos; -  STREAM_VERIFY_SANE(s); +	STREAM_VERIFY_SANE(s); + +	if (!ENDP_VALID(s, pos)) { +		STREAM_BOUND_WARN(s, "set endp"); +		return; +	} + +	/* +	 * Make sure the current read pointer is not beyond the new endp. +	 */ +	if (s->getp > pos) { +		STREAM_BOUND_WARN(s, "set endp"); +		return; +	} + +	s->endp = pos; +	STREAM_VERIFY_SANE(s);  }  /* Forward pointer. */ -void -stream_forward_getp (struct stream *s, size_t size) +void stream_forward_getp(struct stream *s, size_t size)  { -  STREAM_VERIFY_SANE(s); -   -  if (!GETP_VALID (s, s->getp + size)) -    { -      STREAM_BOUND_WARN (s, "seek getp"); -      return; -    } -   -  s->getp += size; +	STREAM_VERIFY_SANE(s); + +	if (!GETP_VALID(s, s->getp + size)) { +		STREAM_BOUND_WARN(s, "seek getp"); +		return; +	} + +	s->getp += size;  } -void -stream_forward_endp (struct stream *s, size_t size) +void stream_forward_endp(struct stream *s, size_t size)  { -  STREAM_VERIFY_SANE(s); -   -  if (!ENDP_VALID (s, s->endp + size)) -    { -      STREAM_BOUND_WARN (s, "seek endp"); -      return; -    } -   -  s->endp += size; +	STREAM_VERIFY_SANE(s); + +	if (!ENDP_VALID(s, s->endp + size)) { +		STREAM_BOUND_WARN(s, "seek endp"); +		return; +	} + +	s->endp += size;  }  /* Copy from stream to destination. */ -void -stream_get (void *dst, struct stream *s, size_t size) +void stream_get(void *dst, struct stream *s, size_t size)  { -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_READABLE(s) < size) -    { -      STREAM_BOUND_WARN (s, "get"); -      return; -    } -   -  memcpy (dst, s->data + s->getp, size); -  s->getp += size; +	STREAM_VERIFY_SANE(s); + +	if (STREAM_READABLE(s) < size) { +		STREAM_BOUND_WARN(s, "get"); +		return; +	} + +	memcpy(dst, s->data + s->getp, size); +	s->getp += size;  }  /* Get next character from the stream. */ -u_char -stream_getc (struct stream *s) +u_char stream_getc(struct stream *s)  { -  u_char c; -   -  STREAM_VERIFY_SANE (s); - -  if (STREAM_READABLE(s) < sizeof (u_char)) -    { -      STREAM_BOUND_WARN (s, "get char"); -      return 0; -    } -  c = s->data[s->getp++]; -   -  return c; +	u_char c; + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_READABLE(s) < sizeof(u_char)) { +		STREAM_BOUND_WARN(s, "get char"); +		return 0; +	} +	c = s->data[s->getp++]; + +	return c;  }  /* Get next character from the stream. */ -u_char -stream_getc_from (struct stream *s, size_t from) +u_char stream_getc_from(struct stream *s, size_t from)  { -  u_char c; - -  STREAM_VERIFY_SANE(s); -   -  if (!GETP_VALID (s, from + sizeof (u_char))) -    { -      STREAM_BOUND_WARN (s, "get char"); -      return 0; -    } -   -  c = s->data[from]; -   -  return c; +	u_char c; + +	STREAM_VERIFY_SANE(s); + +	if (!GETP_VALID(s, from + sizeof(u_char))) { +		STREAM_BOUND_WARN(s, "get char"); +		return 0; +	} + +	c = s->data[from]; + +	return c;  }  /* Get next word from the stream. */ -u_int16_t -stream_getw (struct stream *s) +u_int16_t stream_getw(struct stream *s)  { -  u_int16_t w; - -  STREAM_VERIFY_SANE (s); - -  if (STREAM_READABLE (s) < sizeof (u_int16_t)) -    { -      STREAM_BOUND_WARN (s, "get "); -      return 0; -    } -   -  w = s->data[s->getp++] << 8; -  w |= s->data[s->getp++]; -   -  return w; +	u_int16_t w; + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_READABLE(s) < sizeof(u_int16_t)) { +		STREAM_BOUND_WARN(s, "get "); +		return 0; +	} + +	w = s->data[s->getp++] << 8; +	w |= s->data[s->getp++]; + +	return w;  }  /* Get next word from the stream. */ -u_int16_t -stream_getw_from (struct stream *s, size_t from) +u_int16_t stream_getw_from(struct stream *s, size_t from)  { -  u_int16_t w; - -  STREAM_VERIFY_SANE(s); -   -  if (!GETP_VALID (s, from + sizeof (u_int16_t))) -    { -      STREAM_BOUND_WARN (s, "get "); -      return 0; -    } -   -  w = s->data[from++] << 8; -  w |= s->data[from]; -   -  return w; +	u_int16_t w; + +	STREAM_VERIFY_SANE(s); + +	if (!GETP_VALID(s, from + sizeof(u_int16_t))) { +		STREAM_BOUND_WARN(s, "get "); +		return 0; +	} + +	w = s->data[from++] << 8; +	w |= s->data[from]; + +	return w;  }  /* Get next 3-byte from the stream. */ -u_int32_t -stream_get3_from (struct stream *s, size_t from) +u_int32_t stream_get3_from(struct stream *s, size_t from)  { -  u_int32_t l; - -  STREAM_VERIFY_SANE(s); -   -  if (!GETP_VALID (s, from + 3)) -    { -      STREAM_BOUND_WARN (s, "get 3byte"); -      return 0; -    } -   -  l  = s->data[from++] << 16; -  l |= s->data[from++] << 8; -  l |= s->data[from]; -   -  return l; +	u_int32_t l; + +	STREAM_VERIFY_SANE(s); + +	if (!GETP_VALID(s, from + 3)) { +		STREAM_BOUND_WARN(s, "get 3byte"); +		return 0; +	} + +	l = s->data[from++] << 16; +	l |= s->data[from++] << 8; +	l |= s->data[from]; + +	return l;  } -u_int32_t -stream_get3 (struct stream *s) +u_int32_t stream_get3(struct stream *s)  { -  u_int32_t l; - -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_READABLE (s) < 3) -    { -      STREAM_BOUND_WARN (s, "get 3byte"); -      return 0; -    } -   -  l  = s->data[s->getp++] << 16; -  l |= s->data[s->getp++] << 8; -  l |= s->data[s->getp++]; -   -  return l; +	u_int32_t l; + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_READABLE(s) < 3) { +		STREAM_BOUND_WARN(s, "get 3byte"); +		return 0; +	} + +	l = s->data[s->getp++] << 16; +	l |= s->data[s->getp++] << 8; +	l |= s->data[s->getp++]; + +	return l;  }  /* Get next long word from the stream. */ -u_int32_t -stream_getl_from (struct stream *s, size_t from) +u_int32_t stream_getl_from(struct stream *s, size_t from)  { -  u_int32_t l; - -  STREAM_VERIFY_SANE(s); -   -  if (!GETP_VALID (s, from + sizeof (u_int32_t))) -    { -      STREAM_BOUND_WARN (s, "get long"); -      return 0; -    } -   -  l  = s->data[from++] << 24; -  l |= s->data[from++] << 16; -  l |= s->data[from++] << 8; -  l |= s->data[from]; -   -  return l; +	u_int32_t l; + +	STREAM_VERIFY_SANE(s); + +	if (!GETP_VALID(s, from + sizeof(u_int32_t))) { +		STREAM_BOUND_WARN(s, "get long"); +		return 0; +	} + +	l = s->data[from++] << 24; +	l |= s->data[from++] << 16; +	l |= s->data[from++] << 8; +	l |= s->data[from]; + +	return l;  }  /* Copy from stream at specific location to destination. */ -void -stream_get_from (void *dst, struct stream *s, size_t from, size_t size) +void stream_get_from(void *dst, struct stream *s, size_t from, size_t size)  { -  STREAM_VERIFY_SANE(s); +	STREAM_VERIFY_SANE(s); -  if (!GETP_VALID (s, from + size)) -    { -      STREAM_BOUND_WARN (s, "get from"); -      return; -    } +	if (!GETP_VALID(s, from + size)) { +		STREAM_BOUND_WARN(s, "get from"); +		return; +	} -  memcpy (dst, s->data + from, size); +	memcpy(dst, s->data + from, size);  } -u_int32_t -stream_getl (struct stream *s) +u_int32_t stream_getl(struct stream *s)  { -  u_int32_t l; - -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_READABLE (s) < sizeof (u_int32_t)) -    { -      STREAM_BOUND_WARN (s, "get long"); -      return 0; -    } -   -  l  = s->data[s->getp++] << 24; -  l |= s->data[s->getp++] << 16; -  l |= s->data[s->getp++] << 8; -  l |= s->data[s->getp++]; -   -  return l; +	u_int32_t l; + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_READABLE(s) < sizeof(u_int32_t)) { +		STREAM_BOUND_WARN(s, "get long"); +		return 0; +	} + +	l = s->data[s->getp++] << 24; +	l |= s->data[s->getp++] << 16; +	l |= s->data[s->getp++] << 8; +	l |= s->data[s->getp++]; + +	return l;  }  /* Get next quad word from the stream. */ -uint64_t -stream_getq_from (struct stream *s, size_t from) +uint64_t stream_getq_from(struct stream *s, size_t from)  { -  uint64_t q; - -  STREAM_VERIFY_SANE(s); -   -  if (!GETP_VALID (s, from + sizeof (uint64_t))) -    { -      STREAM_BOUND_WARN (s, "get quad"); -      return 0; -    } -   -  q  = ((uint64_t) s->data[from++]) << 56; -  q |= ((uint64_t) s->data[from++]) << 48; -  q |= ((uint64_t) s->data[from++]) << 40; -  q |= ((uint64_t) s->data[from++]) << 32;   -  q |= ((uint64_t) s->data[from++]) << 24; -  q |= ((uint64_t) s->data[from++]) << 16; -  q |= ((uint64_t) s->data[from++]) << 8; -  q |= ((uint64_t) s->data[from++]); -   -  return q; +	uint64_t q; + +	STREAM_VERIFY_SANE(s); + +	if (!GETP_VALID(s, from + sizeof(uint64_t))) { +		STREAM_BOUND_WARN(s, "get quad"); +		return 0; +	} + +	q = ((uint64_t)s->data[from++]) << 56; +	q |= ((uint64_t)s->data[from++]) << 48; +	q |= ((uint64_t)s->data[from++]) << 40; +	q |= ((uint64_t)s->data[from++]) << 32; +	q |= ((uint64_t)s->data[from++]) << 24; +	q |= ((uint64_t)s->data[from++]) << 16; +	q |= ((uint64_t)s->data[from++]) << 8; +	q |= ((uint64_t)s->data[from++]); + +	return q;  } -uint64_t -stream_getq (struct stream *s) +uint64_t stream_getq(struct stream *s)  { -  uint64_t q; - -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_READABLE (s) < sizeof (uint64_t)) -    { -      STREAM_BOUND_WARN (s, "get quad"); -      return 0; -    } -   -  q  = ((uint64_t) s->data[s->getp++]) << 56; -  q |= ((uint64_t) s->data[s->getp++]) << 48; -  q |= ((uint64_t) s->data[s->getp++]) << 40; -  q |= ((uint64_t) s->data[s->getp++]) << 32;   -  q |= ((uint64_t) s->data[s->getp++]) << 24; -  q |= ((uint64_t) s->data[s->getp++]) << 16; -  q |= ((uint64_t) s->data[s->getp++]) << 8; -  q |= ((uint64_t) s->data[s->getp++]); -   -  return q; +	uint64_t q; + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_READABLE(s) < sizeof(uint64_t)) { +		STREAM_BOUND_WARN(s, "get quad"); +		return 0; +	} + +	q = ((uint64_t)s->data[s->getp++]) << 56; +	q |= ((uint64_t)s->data[s->getp++]) << 48; +	q |= ((uint64_t)s->data[s->getp++]) << 40; +	q |= ((uint64_t)s->data[s->getp++]) << 32; +	q |= ((uint64_t)s->data[s->getp++]) << 24; +	q |= ((uint64_t)s->data[s->getp++]) << 16; +	q |= ((uint64_t)s->data[s->getp++]) << 8; +	q |= ((uint64_t)s->data[s->getp++]); + +	return q;  }  /* Get next long word from the stream. */ -u_int32_t -stream_get_ipv4 (struct stream *s) +u_int32_t stream_get_ipv4(struct stream *s)  { -  u_int32_t l; - -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_READABLE (s) < sizeof(u_int32_t)) -    { -      STREAM_BOUND_WARN (s, "get ipv4"); -      return 0; -    } -   -  memcpy (&l, s->data + s->getp, sizeof(u_int32_t)); -  s->getp += sizeof(u_int32_t); - -  return l; +	u_int32_t l; + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_READABLE(s) < sizeof(u_int32_t)) { +		STREAM_BOUND_WARN(s, "get ipv4"); +		return 0; +	} + +	memcpy(&l, s->data + s->getp, sizeof(u_int32_t)); +	s->getp += sizeof(u_int32_t); + +	return l;  } -float -stream_getf (struct stream *s) +float stream_getf(struct stream *s)  { -  union { -    float r; -    uint32_t d; -  } u; -  u.d = stream_getl (s); -  return u.r; +	union { +		float r; +		uint32_t d; +	} u; +	u.d = stream_getl(s); +	return u.r;  } -double -stream_getd (struct stream *s) +double stream_getd(struct stream *s)  { -  union { -    double r; -    uint64_t d; -  } u; -  u.d = stream_getq (s); -  return u.r; +	union { +		double r; +		uint64_t d; +	} u; +	u.d = stream_getq(s); +	return u.r;  }  /* Copy to source to stream. @@ -576,429 +527,388 @@ stream_getd (struct stream *s)   *   * stream_write() is saner   */ -void -stream_put (struct stream *s, const void *src, size_t size) +void stream_put(struct stream *s, const void *src, size_t size)  { -  /* XXX: CHECK_SIZE has strange semantics. It should be deprecated */ -  CHECK_SIZE(s, size); -   -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_WRITEABLE (s) < size) -    { -      STREAM_BOUND_WARN (s, "put"); -      return; -    } -   -  if (src) -    memcpy (s->data + s->endp, src, size); -  else -    memset (s->data + s->endp, 0, size); - -  s->endp += size; +	/* XXX: CHECK_SIZE has strange semantics. It should be deprecated */ +	CHECK_SIZE(s, size); + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < size) { +		STREAM_BOUND_WARN(s, "put"); +		return; +	} + +	if (src) +		memcpy(s->data + s->endp, src, size); +	else +		memset(s->data + s->endp, 0, size); + +	s->endp += size;  }  /* Put character to the stream. */ -int -stream_putc (struct stream *s, u_char c) +int stream_putc(struct stream *s, u_char c)  { -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_WRITEABLE (s) < sizeof(u_char)) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -   -  s->data[s->endp++] = c; -  return sizeof (u_char); +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < sizeof(u_char)) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} + +	s->data[s->endp++] = c; +	return sizeof(u_char);  }  /* Put word to the stream. */ -int -stream_putw (struct stream *s, u_int16_t w) +int stream_putw(struct stream *s, u_int16_t w)  { -  STREAM_VERIFY_SANE (s); - -  if (STREAM_WRITEABLE (s) < sizeof (u_int16_t)) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -   -  s->data[s->endp++] = (u_char)(w >>  8); -  s->data[s->endp++] = (u_char) w; - -  return 2; +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < sizeof(u_int16_t)) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} + +	s->data[s->endp++] = (u_char)(w >> 8); +	s->data[s->endp++] = (u_char)w; + +	return 2;  }  /* Put long word to the stream. */ -int -stream_put3 (struct stream *s, u_int32_t l) +int stream_put3(struct stream *s, u_int32_t l)  { -  STREAM_VERIFY_SANE (s); - -  if (STREAM_WRITEABLE (s) < 3) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -   -  s->data[s->endp++] = (u_char)(l >> 16); -  s->data[s->endp++] = (u_char)(l >>  8); -  s->data[s->endp++] = (u_char)l; - -  return 3; +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < 3) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} + +	s->data[s->endp++] = (u_char)(l >> 16); +	s->data[s->endp++] = (u_char)(l >> 8); +	s->data[s->endp++] = (u_char)l; + +	return 3;  }  /* Put long word to the stream. */ -int -stream_putl (struct stream *s, u_int32_t l) +int stream_putl(struct stream *s, u_int32_t l)  { -  STREAM_VERIFY_SANE (s); - -  if (STREAM_WRITEABLE (s) < sizeof (u_int32_t)) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -   -  s->data[s->endp++] = (u_char)(l >> 24); -  s->data[s->endp++] = (u_char)(l >> 16); -  s->data[s->endp++] = (u_char)(l >>  8); -  s->data[s->endp++] = (u_char)l; - -  return 4; +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < sizeof(u_int32_t)) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} + +	s->data[s->endp++] = (u_char)(l >> 24); +	s->data[s->endp++] = (u_char)(l >> 16); +	s->data[s->endp++] = (u_char)(l >> 8); +	s->data[s->endp++] = (u_char)l; + +	return 4;  }  /* Put quad word to the stream. */ -int -stream_putq (struct stream *s, uint64_t q) +int stream_putq(struct stream *s, uint64_t q)  { -  STREAM_VERIFY_SANE (s); - -  if (STREAM_WRITEABLE (s) < sizeof (uint64_t)) -    { -      STREAM_BOUND_WARN (s, "put quad"); -      return 0; -    } -   -  s->data[s->endp++] = (u_char)(q >> 56); -  s->data[s->endp++] = (u_char)(q >> 48); -  s->data[s->endp++] = (u_char)(q >> 40); -  s->data[s->endp++] = (u_char)(q >> 32); -  s->data[s->endp++] = (u_char)(q >> 24); -  s->data[s->endp++] = (u_char)(q >> 16); -  s->data[s->endp++] = (u_char)(q >>  8); -  s->data[s->endp++] = (u_char)q; - -  return 8; +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < sizeof(uint64_t)) { +		STREAM_BOUND_WARN(s, "put quad"); +		return 0; +	} + +	s->data[s->endp++] = (u_char)(q >> 56); +	s->data[s->endp++] = (u_char)(q >> 48); +	s->data[s->endp++] = (u_char)(q >> 40); +	s->data[s->endp++] = (u_char)(q >> 32); +	s->data[s->endp++] = (u_char)(q >> 24); +	s->data[s->endp++] = (u_char)(q >> 16); +	s->data[s->endp++] = (u_char)(q >> 8); +	s->data[s->endp++] = (u_char)q; + +	return 8;  } -int -stream_putf (struct stream *s, float f) +int stream_putf(struct stream *s, float f)  { -  union { -    float i; -    uint32_t o; -  } u; -  u.i = f; -  return stream_putl (s, u.o); +	union { +		float i; +		uint32_t o; +	} u; +	u.i = f; +	return stream_putl(s, u.o);  } -int -stream_putd (struct stream *s, double d) +int stream_putd(struct stream *s, double d)  { -  union { -    double i; -    uint64_t o; -  } u; -  u.i = d; -  return stream_putq (s, u.o); +	union { +		double i; +		uint64_t o; +	} u; +	u.i = d; +	return stream_putq(s, u.o);  } -int -stream_putc_at (struct stream *s, size_t putp, u_char c) +int stream_putc_at(struct stream *s, size_t putp, u_char c)  { -  STREAM_VERIFY_SANE(s); -   -  if (!PUT_AT_VALID (s, putp + sizeof (u_char))) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -   -  s->data[putp] = c; -   -  return 1; +	STREAM_VERIFY_SANE(s); + +	if (!PUT_AT_VALID(s, putp + sizeof(u_char))) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} + +	s->data[putp] = c; + +	return 1;  } -int -stream_putw_at (struct stream *s, size_t putp, u_int16_t w) +int stream_putw_at(struct stream *s, size_t putp, u_int16_t w)  { -  STREAM_VERIFY_SANE(s); -   -  if (!PUT_AT_VALID (s, putp + sizeof (u_int16_t))) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -   -  s->data[putp] = (u_char)(w >>  8); -  s->data[putp + 1] = (u_char) w; -   -  return 2; +	STREAM_VERIFY_SANE(s); + +	if (!PUT_AT_VALID(s, putp + sizeof(u_int16_t))) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} + +	s->data[putp] = (u_char)(w >> 8); +	s->data[putp + 1] = (u_char)w; + +	return 2;  } -int -stream_put3_at (struct stream *s, size_t putp, u_int32_t l) +int stream_put3_at(struct stream *s, size_t putp, u_int32_t l)  { -  STREAM_VERIFY_SANE(s); -   -  if (!PUT_AT_VALID (s, putp + 3)) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -  s->data[putp] = (u_char)(l >> 16); -  s->data[putp + 1] = (u_char)(l >>  8); -  s->data[putp + 2] = (u_char)l; -   -  return 3; +	STREAM_VERIFY_SANE(s); + +	if (!PUT_AT_VALID(s, putp + 3)) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} +	s->data[putp] = (u_char)(l >> 16); +	s->data[putp + 1] = (u_char)(l >> 8); +	s->data[putp + 2] = (u_char)l; + +	return 3;  } -int -stream_putl_at (struct stream *s, size_t putp, u_int32_t l) +int stream_putl_at(struct stream *s, size_t putp, u_int32_t l)  { -  STREAM_VERIFY_SANE(s); -   -  if (!PUT_AT_VALID (s, putp + sizeof (u_int32_t))) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -  s->data[putp] = (u_char)(l >> 24); -  s->data[putp + 1] = (u_char)(l >> 16); -  s->data[putp + 2] = (u_char)(l >>  8); -  s->data[putp + 3] = (u_char)l; -   -  return 4; +	STREAM_VERIFY_SANE(s); + +	if (!PUT_AT_VALID(s, putp + sizeof(u_int32_t))) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} +	s->data[putp] = (u_char)(l >> 24); +	s->data[putp + 1] = (u_char)(l >> 16); +	s->data[putp + 2] = (u_char)(l >> 8); +	s->data[putp + 3] = (u_char)l; + +	return 4;  } -int -stream_putq_at (struct stream *s, size_t putp, uint64_t q) +int stream_putq_at(struct stream *s, size_t putp, uint64_t q)  { -  STREAM_VERIFY_SANE(s); -   -  if (!PUT_AT_VALID (s, putp + sizeof (uint64_t))) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -  s->data[putp] =     (u_char)(q >> 56); -  s->data[putp + 1] = (u_char)(q >> 48); -  s->data[putp + 2] = (u_char)(q >> 40); -  s->data[putp + 3] = (u_char)(q >> 32); -  s->data[putp + 4] = (u_char)(q >> 24); -  s->data[putp + 5] = (u_char)(q >> 16); -  s->data[putp + 6] = (u_char)(q >>  8); -  s->data[putp + 7] = (u_char)q; -   -  return 8; +	STREAM_VERIFY_SANE(s); + +	if (!PUT_AT_VALID(s, putp + sizeof(uint64_t))) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} +	s->data[putp] = (u_char)(q >> 56); +	s->data[putp + 1] = (u_char)(q >> 48); +	s->data[putp + 2] = (u_char)(q >> 40); +	s->data[putp + 3] = (u_char)(q >> 32); +	s->data[putp + 4] = (u_char)(q >> 24); +	s->data[putp + 5] = (u_char)(q >> 16); +	s->data[putp + 6] = (u_char)(q >> 8); +	s->data[putp + 7] = (u_char)q; + +	return 8;  }  /* Put long word to the stream. */ -int -stream_put_ipv4 (struct stream *s, u_int32_t l) +int stream_put_ipv4(struct stream *s, u_int32_t l)  { -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_WRITEABLE (s) < sizeof (u_int32_t)) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -  memcpy (s->data + s->endp, &l, sizeof (u_int32_t)); -  s->endp += sizeof (u_int32_t); - -  return sizeof (u_int32_t); +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < sizeof(u_int32_t)) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} +	memcpy(s->data + s->endp, &l, sizeof(u_int32_t)); +	s->endp += sizeof(u_int32_t); + +	return sizeof(u_int32_t);  }  /* Put long word to the stream. */ -int -stream_put_in_addr (struct stream *s, struct in_addr *addr) +int stream_put_in_addr(struct stream *s, struct in_addr *addr)  { -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_WRITEABLE (s) < sizeof (u_int32_t)) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } - -  memcpy (s->data + s->endp, addr, sizeof (u_int32_t)); -  s->endp += sizeof (u_int32_t); - -  return sizeof (u_int32_t); +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < sizeof(u_int32_t)) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} + +	memcpy(s->data + s->endp, addr, sizeof(u_int32_t)); +	s->endp += sizeof(u_int32_t); + +	return sizeof(u_int32_t);  }  /* Put in_addr at location in the stream. */ -int -stream_put_in_addr_at (struct stream *s, size_t putp, struct in_addr *addr) +int stream_put_in_addr_at(struct stream *s, size_t putp, struct in_addr *addr)  { -  STREAM_VERIFY_SANE(s); +	STREAM_VERIFY_SANE(s); -  if (!PUT_AT_VALID (s, putp + 4)) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } +	if (!PUT_AT_VALID(s, putp + 4)) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} -  memcpy (&s->data[putp], addr, 4); -  return 4; +	memcpy(&s->data[putp], addr, 4); +	return 4;  }  /* Put in6_addr at location in the stream. */ -int -stream_put_in6_addr_at (struct stream *s, size_t putp, struct in6_addr *addr) +int stream_put_in6_addr_at(struct stream *s, size_t putp, struct in6_addr *addr)  { -  STREAM_VERIFY_SANE(s); +	STREAM_VERIFY_SANE(s); -  if (!PUT_AT_VALID (s, putp + 16)) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } +	if (!PUT_AT_VALID(s, putp + 16)) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} -  memcpy (&s->data[putp], addr, 16); -  return 16; +	memcpy(&s->data[putp], addr, 16); +	return 16;  }  /* Put prefix by nlri type format. */ -int -stream_put_prefix_addpath (struct stream *s, struct prefix *p, -                           int addpath_encode, u_int32_t addpath_tx_id) +int stream_put_prefix_addpath(struct stream *s, struct prefix *p, +			      int addpath_encode, u_int32_t addpath_tx_id)  { -  size_t psize; -  size_t psize_with_addpath; -   -  STREAM_VERIFY_SANE(s); -   -  psize = PSIZE (p->prefixlen); - -  if (addpath_encode) -    psize_with_addpath = psize + 4; -  else -    psize_with_addpath = psize; -   -  if (STREAM_WRITEABLE (s) < (psize_with_addpath + sizeof (u_char))) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -   -  if (addpath_encode) -    { -        s->data[s->endp++] = (u_char)(addpath_tx_id >> 24); -        s->data[s->endp++] = (u_char)(addpath_tx_id >> 16); -        s->data[s->endp++] = (u_char)(addpath_tx_id >>  8); -        s->data[s->endp++] = (u_char)addpath_tx_id; -    } - -  s->data[s->endp++] = p->prefixlen; -  memcpy (s->data + s->endp, &p->u.prefix, psize); -  s->endp += psize; -   -  return psize; +	size_t psize; +	size_t psize_with_addpath; + +	STREAM_VERIFY_SANE(s); + +	psize = PSIZE(p->prefixlen); + +	if (addpath_encode) +		psize_with_addpath = psize + 4; +	else +		psize_with_addpath = psize; + +	if (STREAM_WRITEABLE(s) < (psize_with_addpath + sizeof(u_char))) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} + +	if (addpath_encode) { +		s->data[s->endp++] = (u_char)(addpath_tx_id >> 24); +		s->data[s->endp++] = (u_char)(addpath_tx_id >> 16); +		s->data[s->endp++] = (u_char)(addpath_tx_id >> 8); +		s->data[s->endp++] = (u_char)addpath_tx_id; +	} + +	s->data[s->endp++] = p->prefixlen; +	memcpy(s->data + s->endp, &p->u.prefix, psize); +	s->endp += psize; + +	return psize;  } -int -stream_put_prefix (struct stream *s, struct prefix *p) +int stream_put_prefix(struct stream *s, struct prefix *p)  { -  return stream_put_prefix_addpath (s, p, 0, 0); +	return stream_put_prefix_addpath(s, p, 0, 0);  }  /* Read size from fd. */ -int -stream_read (struct stream *s, int fd, size_t size) +int stream_read(struct stream *s, int fd, size_t size)  { -  int nbytes; - -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_WRITEABLE (s) < size) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -   -  nbytes = readn (fd, s->data + s->endp, size); - -  if (nbytes > 0) -    s->endp += nbytes; -   -  return nbytes; +	int nbytes; + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < size) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} + +	nbytes = readn(fd, s->data + s->endp, size); + +	if (nbytes > 0) +		s->endp += nbytes; + +	return nbytes;  } -ssize_t -stream_read_try(struct stream *s, int fd, size_t size) +ssize_t stream_read_try(struct stream *s, int fd, size_t size)  { -  ssize_t nbytes; - -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_WRITEABLE(s) < size) -    { -      STREAM_BOUND_WARN (s, "put"); -      /* Fatal (not transient) error, since retrying will not help -         (stream is too small to contain the desired data). */ -      return -1; -    } - -  if ((nbytes = read(fd, s->data + s->endp, size)) >= 0) -    { -      s->endp += nbytes; -      return nbytes; -    } -  /* Error: was it transient (return -2) or fatal (return -1)? */ -  if (ERRNO_IO_RETRY(errno)) -    return -2; -  zlog_warn("%s: read failed on fd %d: %s", __func__, fd, safe_strerror(errno)); -  return -1; +	ssize_t nbytes; + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < size) { +		STREAM_BOUND_WARN(s, "put"); +		/* Fatal (not transient) error, since retrying will not help +		   (stream is too small to contain the desired data). */ +		return -1; +	} + +	if ((nbytes = read(fd, s->data + s->endp, size)) >= 0) { +		s->endp += nbytes; +		return nbytes; +	} +	/* Error: was it transient (return -2) or fatal (return -1)? */ +	if (ERRNO_IO_RETRY(errno)) +		return -2; +	zlog_warn("%s: read failed on fd %d: %s", __func__, fd, +		  safe_strerror(errno)); +	return -1;  }  /* Read up to size bytes into the stream from the fd, using recvmsgfrom   * whose arguments match the remaining arguments to this function   */ -ssize_t  -stream_recvfrom (struct stream *s, int fd, size_t size, int flags, -                 struct sockaddr *from, socklen_t *fromlen)                      +ssize_t stream_recvfrom(struct stream *s, int fd, size_t size, int flags, +			struct sockaddr *from, socklen_t *fromlen)  { -  ssize_t nbytes; - -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_WRITEABLE(s) < size) -    { -      STREAM_BOUND_WARN (s, "put"); -      /* Fatal (not transient) error, since retrying will not help -         (stream is too small to contain the desired data). */ -      return -1; -    } - -  if ((nbytes = recvfrom (fd, s->data + s->endp, size,  -                          flags, from, fromlen)) >= 0) -    { -      s->endp += nbytes; -      return nbytes; -    } -  /* Error: was it transient (return -2) or fatal (return -1)? */ -  if (ERRNO_IO_RETRY(errno)) -    return -2; -  zlog_warn("%s: read failed on fd %d: %s", __func__, fd, safe_strerror(errno)); -  return -1; +	ssize_t nbytes; + +	STREAM_VERIFY_SANE(s); + +	if (STREAM_WRITEABLE(s) < size) { +		STREAM_BOUND_WARN(s, "put"); +		/* Fatal (not transient) error, since retrying will not help +		   (stream is too small to contain the desired data). */ +		return -1; +	} + +	if ((nbytes = recvfrom(fd, s->data + s->endp, size, flags, from, +			       fromlen)) +	    >= 0) { +		s->endp += nbytes; +		return nbytes; +	} +	/* Error: was it transient (return -2) or fatal (return -1)? */ +	if (ERRNO_IO_RETRY(errno)) +		return -2; +	zlog_warn("%s: read failed on fd %d: %s", __func__, fd, +		  safe_strerror(errno)); +	return -1;  }  /* Read up to smaller of size or SIZE_REMAIN() bytes to the stream, starting @@ -1006,171 +916,156 @@ stream_recvfrom (struct stream *s, int fd, size_t size, int flags,   * First iovec will be used to receive the data.   * Stream need not be empty.   */ -ssize_t -stream_recvmsg (struct stream *s, int fd, struct msghdr *msgh, int flags,  -                size_t size) +ssize_t stream_recvmsg(struct stream *s, int fd, struct msghdr *msgh, int flags, +		       size_t size)  { -  int nbytes; -  struct iovec *iov; -   -  STREAM_VERIFY_SANE(s); -  assert (msgh->msg_iovlen > 0);   -   -  if (STREAM_WRITEABLE (s) < size) -    { -      STREAM_BOUND_WARN (s, "put"); -      /* This is a logic error in the calling code: the stream is too small -         to hold the desired data! */ -      return -1; -    } -   -  iov = &(msgh->msg_iov[0]); -  iov->iov_base = (s->data + s->endp); -  iov->iov_len = size; -   -  nbytes = recvmsg (fd, msgh, flags); -   -  if (nbytes > 0) -    s->endp += nbytes; -   -  return nbytes; +	int nbytes; +	struct iovec *iov; + +	STREAM_VERIFY_SANE(s); +	assert(msgh->msg_iovlen > 0); + +	if (STREAM_WRITEABLE(s) < size) { +		STREAM_BOUND_WARN(s, "put"); +		/* This is a logic error in the calling code: the stream is too +		   small +		   to hold the desired data! */ +		return -1; +	} + +	iov = &(msgh->msg_iov[0]); +	iov->iov_base = (s->data + s->endp); +	iov->iov_len = size; + +	nbytes = recvmsg(fd, msgh, flags); + +	if (nbytes > 0) +		s->endp += nbytes; + +	return nbytes;  } -   +  /* Write data to buffer. */ -size_t -stream_write (struct stream *s, const void *ptr, size_t size) +size_t stream_write(struct stream *s, const void *ptr, size_t size)  { -  CHECK_SIZE(s, size); +	CHECK_SIZE(s, size); + +	STREAM_VERIFY_SANE(s); -  STREAM_VERIFY_SANE(s); -   -  if (STREAM_WRITEABLE (s) < size) -    { -      STREAM_BOUND_WARN (s, "put"); -      return 0; -    } -   -  memcpy (s->data + s->endp, ptr, size); -  s->endp += size; +	if (STREAM_WRITEABLE(s) < size) { +		STREAM_BOUND_WARN(s, "put"); +		return 0; +	} -  return size; +	memcpy(s->data + s->endp, ptr, size); +	s->endp += size; + +	return size;  } -/* Return current read pointer.  +/* Return current read pointer.   * DEPRECATED!   * Use stream_get_pnt_to if you must, but decoding streams properly   * is preferred   */ -u_char * -stream_pnt (struct stream *s) +u_char *stream_pnt(struct stream *s)  { -  STREAM_VERIFY_SANE(s); -  return s->data + s->getp; +	STREAM_VERIFY_SANE(s); +	return s->data + s->getp;  }  /* Check does this stream empty? */ -int -stream_empty (struct stream *s) +int stream_empty(struct stream *s)  { -  STREAM_VERIFY_SANE(s); +	STREAM_VERIFY_SANE(s); -  return (s->endp == 0); +	return (s->endp == 0);  }  /* Reset stream. */ -void -stream_reset (struct stream *s) +void stream_reset(struct stream *s)  { -  STREAM_VERIFY_SANE (s); +	STREAM_VERIFY_SANE(s); -  s->getp = s->endp = 0; +	s->getp = s->endp = 0;  }  /* Write stream contens to the file discriptor. */ -int -stream_flush (struct stream *s, int fd) +int stream_flush(struct stream *s, int fd)  { -  int nbytes; -   -  STREAM_VERIFY_SANE(s); -   -  nbytes = write (fd, s->data + s->getp, s->endp - s->getp); -   -  return nbytes; +	int nbytes; + +	STREAM_VERIFY_SANE(s); + +	nbytes = write(fd, s->data + s->getp, s->endp - s->getp); + +	return nbytes;  }  /* Stream first in first out queue. */ -struct stream_fifo * -stream_fifo_new (void) +struct stream_fifo *stream_fifo_new(void)  { -  struct stream_fifo *new; -  -  new = XCALLOC (MTYPE_STREAM_FIFO, sizeof (struct stream_fifo)); -  return new; +	struct stream_fifo *new; + +	new = XCALLOC(MTYPE_STREAM_FIFO, sizeof(struct stream_fifo)); +	return new;  }  /* Add new stream to fifo. */ -void -stream_fifo_push (struct stream_fifo *fifo, struct stream *s) +void stream_fifo_push(struct stream_fifo *fifo, struct stream *s)  { -  if (fifo->tail) -    fifo->tail->next = s; -  else -    fifo->head = s; -      -  fifo->tail = s; - -  fifo->count++; +	if (fifo->tail) +		fifo->tail->next = s; +	else +		fifo->head = s; + +	fifo->tail = s; + +	fifo->count++;  }  /* Delete first stream from fifo. */ -struct stream * -stream_fifo_pop (struct stream_fifo *fifo) +struct stream *stream_fifo_pop(struct stream_fifo *fifo)  { -  struct stream *s; -   -  s = fifo->head;  +	struct stream *s; + +	s = fifo->head; -  if (s) -    {  -      fifo->head = s->next; +	if (s) { +		fifo->head = s->next; -      if (fifo->head == NULL) -	fifo->tail = NULL; +		if (fifo->head == NULL) +			fifo->tail = NULL; -      fifo->count--; -    } +		fifo->count--; +	} -  return s;  +	return s;  }  /* Return first fifo entry. */ -struct stream * -stream_fifo_head (struct stream_fifo *fifo) +struct stream *stream_fifo_head(struct stream_fifo *fifo)  { -  return fifo->head; +	return fifo->head;  } -void -stream_fifo_clean (struct stream_fifo *fifo) +void stream_fifo_clean(struct stream_fifo *fifo)  { -  struct stream *s; -  struct stream *next; - -  for (s = fifo->head; s; s = next) -    { -      next = s->next; -      stream_free (s); -    } -  fifo->head = fifo->tail = NULL; -  fifo->count = 0; +	struct stream *s; +	struct stream *next; + +	for (s = fifo->head; s; s = next) { +		next = s->next; +		stream_free(s); +	} +	fifo->head = fifo->tail = NULL; +	fifo->count = 0;  } -void -stream_fifo_free (struct stream_fifo *fifo) +void stream_fifo_free(struct stream_fifo *fifo)  { -  stream_fifo_clean (fifo); -  XFREE (MTYPE_STREAM_FIFO, fifo); +	stream_fifo_clean(fifo); +	XFREE(MTYPE_STREAM_FIFO, fifo);  } diff --git a/lib/stream.h b/lib/stream.h index 1e2bc89b32..9e147258d4 100644 --- a/lib/stream.h +++ b/lib/stream.h @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_STREAM_H @@ -78,7 +78,7 @@   * The stream is empty from endp to size. Without adjusting getp, there are   * still endp-getp bytes of valid data to be read from the stream.   * - * Methods are provided to get and put to/from the stream, as well as  + * Methods are provided to get and put to/from the stream, as well as   * retrieve the values of the 3 markers and manipulate the getp marker.   *   * Note: @@ -92,45 +92,42 @@   */  /* Stream buffer. */ -struct stream -{ -  struct stream *next; - -  /* Remainder is ***private*** to stream -   * direct access is frowned upon! -   * Use the appropriate functions/macros  -   */ -  size_t getp; 		/* next get position */ -  size_t endp;		/* last valid data position */ -  size_t size;		/* size of data segment */ -  unsigned char *data; /* data pointer */ +struct stream { +	struct stream *next; + +	/* Remainder is ***private*** to stream +	 * direct access is frowned upon! +	 * Use the appropriate functions/macros +	 */ +	size_t getp;	 /* next get position */ +	size_t endp;	 /* last valid data position */ +	size_t size;	 /* size of data segment */ +	unsigned char *data; /* data pointer */  };  /* First in first out queue structure. */ -struct stream_fifo -{ -  size_t count; +struct stream_fifo { +	size_t count; -  struct stream *head; -  struct stream *tail; +	struct stream *head; +	struct stream *tail;  };  /* Utility macros. */  #define STREAM_SIZE(S)  ((S)->size) -  /* number of bytes which can still be written */ +/* number of bytes which can still be written */  #define STREAM_WRITEABLE(S) ((S)->size - (S)->endp) -  /* number of bytes still to be read */ +/* number of bytes still to be read */  #define STREAM_READABLE(S) ((S)->endp - (S)->getp) -#define STREAM_CONCAT_REMAIN(S1, S2, size) \ -  ((size) - (S1)->endp - (S2)->endp) +#define STREAM_CONCAT_REMAIN(S1, S2, size) ((size) - (S1)->endp - (S2)->endp)  /* deprecated macros - do not use in new code */  #define STREAM_PNT(S)   stream_pnt((S))  #define STREAM_DATA(S)  ((S)->data)  #define STREAM_REMAIN(S) STREAM_WRITEABLE((S)) -/* Stream prototypes.  +/* Stream prototypes.   * For stream_{put,get}S, the S suffix mean:   *   * c: character (unsigned byte) @@ -138,15 +135,15 @@ struct stream_fifo   * l: long (two words)   * q: quad (four words)   */ -extern struct stream *stream_new (size_t); -extern void stream_free (struct stream *); -extern struct stream * stream_copy (struct stream *, struct stream *src); -extern struct stream *stream_dup (struct stream *); -extern size_t stream_resize (struct stream *, size_t); -extern size_t stream_get_getp (struct stream *); -extern size_t stream_get_endp (struct stream *); -extern size_t stream_get_size (struct stream *); -extern u_char *stream_get_data (struct stream *); +extern struct stream *stream_new(size_t); +extern void stream_free(struct stream *); +extern struct stream *stream_copy(struct stream *, struct stream *src); +extern struct stream *stream_dup(struct stream *); +extern size_t stream_resize(struct stream *, size_t); +extern size_t stream_get_getp(struct stream *); +extern size_t stream_get_endp(struct stream *); +extern size_t stream_get_size(struct stream *); +extern u_char *stream_get_data(struct stream *);  /**   * Create a new stream structure; copy offset bytes from s1 to the new @@ -156,58 +153,58 @@ extern u_char *stream_get_data (struct stream *);  extern struct stream *stream_dupcat(struct stream *s1, struct stream *s2,  				    size_t offset); -extern void stream_set_getp (struct stream *, size_t); -extern void stream_set_endp (struct stream *, size_t); -extern void stream_forward_getp (struct stream *, size_t); -extern void stream_forward_endp (struct stream *, size_t); +extern void stream_set_getp(struct stream *, size_t); +extern void stream_set_endp(struct stream *, size_t); +extern void stream_forward_getp(struct stream *, size_t); +extern void stream_forward_endp(struct stream *, size_t);  /* steam_put: NULL source zeroes out size_t bytes of stream */ -extern void stream_put (struct stream *, const void *, size_t); -extern int stream_putc (struct stream *, u_char); -extern int stream_putc_at (struct stream *, size_t, u_char); -extern int stream_putw (struct stream *, u_int16_t); -extern int stream_putw_at (struct stream *, size_t, u_int16_t); -extern int stream_put3 (struct stream *, u_int32_t); -extern int stream_put3_at (struct stream *, size_t, u_int32_t); -extern int stream_putl (struct stream *, u_int32_t); -extern int stream_putl_at (struct stream *, size_t, u_int32_t); -extern int stream_putq (struct stream *, uint64_t); -extern int stream_putq_at (struct stream *, size_t, uint64_t); -extern int stream_put_ipv4 (struct stream *, u_int32_t); -extern int stream_put_in_addr (struct stream *, struct in_addr *); -extern int stream_put_in_addr_at (struct stream *, size_t, struct in_addr *); -extern int stream_put_in6_addr_at (struct stream *, size_t, struct in6_addr *); -extern int stream_put_prefix_addpath (struct stream *, struct prefix *, -                                      int addpath_encode, -                                      u_int32_t addpath_tx_id); -extern int stream_put_prefix (struct stream *, struct prefix *); - -extern void stream_get (void *, struct stream *, size_t); -extern void stream_get_from (void *, struct stream *, size_t, size_t); -extern u_char stream_getc (struct stream *); -extern u_char stream_getc_from (struct stream *, size_t); -extern u_int16_t stream_getw (struct stream *); -extern u_int16_t stream_getw_from (struct stream *, size_t); -extern u_int32_t stream_get3 (struct stream *); -extern u_int32_t stream_get3_from (struct stream *, size_t); -extern u_int32_t stream_getl (struct stream *); -extern u_int32_t stream_getl_from (struct stream *, size_t); -extern uint64_t stream_getq (struct stream *); -extern uint64_t stream_getq_from (struct stream *, size_t); -extern u_int32_t stream_get_ipv4 (struct stream *); +extern void stream_put(struct stream *, const void *, size_t); +extern int stream_putc(struct stream *, u_char); +extern int stream_putc_at(struct stream *, size_t, u_char); +extern int stream_putw(struct stream *, u_int16_t); +extern int stream_putw_at(struct stream *, size_t, u_int16_t); +extern int stream_put3(struct stream *, u_int32_t); +extern int stream_put3_at(struct stream *, size_t, u_int32_t); +extern int stream_putl(struct stream *, u_int32_t); +extern int stream_putl_at(struct stream *, size_t, u_int32_t); +extern int stream_putq(struct stream *, uint64_t); +extern int stream_putq_at(struct stream *, size_t, uint64_t); +extern int stream_put_ipv4(struct stream *, u_int32_t); +extern int stream_put_in_addr(struct stream *, struct in_addr *); +extern int stream_put_in_addr_at(struct stream *, size_t, struct in_addr *); +extern int stream_put_in6_addr_at(struct stream *, size_t, struct in6_addr *); +extern int stream_put_prefix_addpath(struct stream *, struct prefix *, +				     int addpath_encode, +				     u_int32_t addpath_tx_id); +extern int stream_put_prefix(struct stream *, struct prefix *); + +extern void stream_get(void *, struct stream *, size_t); +extern void stream_get_from(void *, struct stream *, size_t, size_t); +extern u_char stream_getc(struct stream *); +extern u_char stream_getc_from(struct stream *, size_t); +extern u_int16_t stream_getw(struct stream *); +extern u_int16_t stream_getw_from(struct stream *, size_t); +extern u_int32_t stream_get3(struct stream *); +extern u_int32_t stream_get3_from(struct stream *, size_t); +extern u_int32_t stream_getl(struct stream *); +extern u_int32_t stream_getl_from(struct stream *, size_t); +extern uint64_t stream_getq(struct stream *); +extern uint64_t stream_getq_from(struct stream *, size_t); +extern u_int32_t stream_get_ipv4(struct stream *);  /* IEEE-754 floats */ -extern float stream_getf (struct stream *); -extern double stream_getd (struct stream *); -extern int stream_putf (struct stream *, float); -extern int stream_putd (struct stream *, double); +extern float stream_getf(struct stream *); +extern double stream_getd(struct stream *); +extern int stream_putf(struct stream *, float); +extern int stream_putd(struct stream *, double);  #undef stream_read  #undef stream_write -/* Deprecated: assumes blocking I/O.  Will be removed.  +/* Deprecated: assumes blocking I/O.  Will be removed.     Use stream_read_try instead.  */ -extern int stream_read (struct stream *, int, size_t); +extern int stream_read(struct stream *, int, size_t);  /* Read up to size bytes into the stream.     Return code: @@ -219,27 +216,26 @@ extern int stream_read (struct stream *, int, size_t);   */  extern ssize_t stream_read_try(struct stream *s, int fd, size_t size); -extern ssize_t stream_recvmsg (struct stream *s, int fd, struct msghdr *, -                               int flags, size_t size); -extern ssize_t stream_recvfrom (struct stream *s, int fd, size_t len,  -                                int flags, struct sockaddr *from,  -                                socklen_t *fromlen); -extern size_t stream_write (struct stream *, const void *, size_t); +extern ssize_t stream_recvmsg(struct stream *s, int fd, struct msghdr *, +			      int flags, size_t size); +extern ssize_t stream_recvfrom(struct stream *s, int fd, size_t len, int flags, +			       struct sockaddr *from, socklen_t *fromlen); +extern size_t stream_write(struct stream *, const void *, size_t);  /* reset the stream. See Note above */ -extern void stream_reset (struct stream *); -extern int stream_flush (struct stream *, int); -extern int stream_empty (struct stream *); /* is the stream empty? */ +extern void stream_reset(struct stream *); +extern int stream_flush(struct stream *, int); +extern int stream_empty(struct stream *); /* is the stream empty? */  /* deprecated */ -extern u_char *stream_pnt (struct stream *); +extern u_char *stream_pnt(struct stream *);  /* Stream fifo. */ -extern struct stream_fifo *stream_fifo_new (void); -extern void stream_fifo_push (struct stream_fifo *fifo, struct stream *s); -extern struct stream *stream_fifo_pop (struct stream_fifo *fifo); -extern struct stream *stream_fifo_head (struct stream_fifo *fifo); -extern void stream_fifo_clean (struct stream_fifo *fifo); -extern void stream_fifo_free (struct stream_fifo *fifo); +extern struct stream_fifo *stream_fifo_new(void); +extern void stream_fifo_push(struct stream_fifo *fifo, struct stream *s); +extern struct stream *stream_fifo_pop(struct stream_fifo *fifo); +extern struct stream *stream_fifo_head(struct stream_fifo *fifo); +extern void stream_fifo_clean(struct stream_fifo *fifo); +extern void stream_fifo_free(struct stream_fifo *fifo);  #endif /* _ZEBRA_STREAM_H */ diff --git a/lib/strlcat.c b/lib/strlcat.c index 1d04b43d95..f144b76b5b 100644 --- a/lib/strlcat.c +++ b/lib/strlcat.c @@ -27,45 +27,42 @@  #ifndef HAVE_STRLCAT  #undef strlcat -size_t -strlcat (char *__restrict dest, const char *__restrict src, size_t size); +size_t strlcat(char *__restrict dest, const char *__restrict src, size_t size); -size_t -strlcat (char *__restrict dest, const char *__restrict src, size_t size) +size_t strlcat(char *__restrict dest, const char *__restrict src, size_t size)  { -  size_t src_length = strlen (src); +	size_t src_length = strlen(src); -  /* Our implementation strlcat supports dest == NULL if size == 0 -     (for consistency with snprintf and strlcpy), but strnlen does -     not, so we have to cover this case explicitly.  */ -  if (size == 0) -    return src_length; +	/* Our implementation strlcat supports dest == NULL if size == 0 +	   (for consistency with snprintf and strlcpy), but strnlen does +	   not, so we have to cover this case explicitly.  */ +	if (size == 0) +		return src_length; -  size_t dest_length = strnlen (dest, size); -  if (dest_length != size) -    { -      /* Copy at most the remaining number of characters in the -	 destination buffer.  Leave for the NUL terminator.  */ -      size_t to_copy = size - dest_length - 1; -      /* But not more than what is available in the source string.  */ -      if (to_copy > src_length) -	to_copy = src_length; +	size_t dest_length = strnlen(dest, size); +	if (dest_length != size) { +		/* Copy at most the remaining number of characters in the +		   destination buffer.  Leave for the NUL terminator.  */ +		size_t to_copy = size - dest_length - 1; +		/* But not more than what is available in the source string.  */ +		if (to_copy > src_length) +			to_copy = src_length; -      char *target = dest + dest_length; -      memcpy (target, src, to_copy); -      target[to_copy] = '\0'; -    } +		char *target = dest + dest_length; +		memcpy(target, src, to_copy); +		target[to_copy] = '\0'; +	} -  /* If the sum wraps around, we have more than SIZE_MAX + 2 bytes in -     the two input strings (including both null terminators).  If each -     byte in the address space can be assigned a unique size_t value -     (which the static_assert checks), then by the pigeonhole -     principle, the two input strings must overlap, which is -     undefined.  */ +/* If the sum wraps around, we have more than SIZE_MAX + 2 bytes in +   the two input strings (including both null terminators).  If each +   byte in the address space can be assigned a unique size_t value +   (which the static_assert checks), then by the pigeonhole +   principle, the two input strings must overlap, which is +   undefined.  */  #if __STDC_VERSION__ >= 201112L -  _Static_assert (sizeof (uintptr_t) == sizeof (size_t), -		  "theoretical maximum object size covers address space"); +	_Static_assert(sizeof(uintptr_t) == sizeof(size_t), +		       "theoretical maximum object size covers address space");  #endif -  return dest_length + src_length; +	return dest_length + src_length;  }  #endif /* HAVE_STRLCAT */ diff --git a/lib/strlcpy.c b/lib/strlcpy.c index 41bab97ea7..e023ca13e7 100644 --- a/lib/strlcpy.c +++ b/lib/strlcpy.c @@ -26,31 +26,27 @@  #ifndef HAVE_STRLCPY  #undef strlcpy -size_t -strlcpy (char *__restrict dest, const char *__restrict src, size_t size); +size_t strlcpy(char *__restrict dest, const char *__restrict src, size_t size); -size_t -strlcpy (char *__restrict dest, const char *__restrict src, size_t size) +size_t strlcpy(char *__restrict dest, const char *__restrict src, size_t size)  { -  size_t src_length = strlen (src); - -  if (__builtin_expect (src_length >= size, 0)) -    { -      if (size > 0) -	{ -	  /* Copy the leading portion of the string.  The last -	     character is subsequently overwritten with the NUL -	     terminator, but the destination size is usually a -	     multiple of a small power of two, so writing it twice -	     should be more efficient than copying an odd number of -	     bytes.  */ -	  memcpy (dest, src, size); -	  dest[size - 1] = '\0'; -	} -    } -  else -      /* Copy the string and its terminating NUL character.  */ -      memcpy (dest, src, src_length + 1); -  return src_length; +	size_t src_length = strlen(src); + +	if (__builtin_expect(src_length >= size, 0)) { +		if (size > 0) { +			/* Copy the leading portion of the string.  The last +			   character is subsequently overwritten with the NUL +			   terminator, but the destination size is usually a +			   multiple of a small power of two, so writing it twice +			   should be more efficient than copying an odd number +			   of +			   bytes.  */ +			memcpy(dest, src, size); +			dest[size - 1] = '\0'; +		} +	} else +		/* Copy the string and its terminating NUL character.  */ +		memcpy(dest, src, src_length + 1); +	return src_length;  }  #endif /* HAVE_STRLCPY */ diff --git a/lib/systemd.c b/lib/systemd.c index 4c78cf328c..54f755865b 100644 --- a/lib/systemd.c +++ b/lib/systemd.c @@ -32,65 +32,61 @@ Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA   * Wrapper this silliness if we   * don't have systemd   */ -void -systemd_send_information (const char *info) +void systemd_send_information(const char *info)  {  #if defined HAVE_SYSTEMD -  sd_notify (0, info); +	sd_notify(0, info);  #else -  return; +	return;  #endif  }  /*   * A return of 0 means that we are not watchdoged   */ -static int -systemd_get_watchdog_time (int the_process) +static int systemd_get_watchdog_time(int the_process)  {  #if defined HAVE_SYSTEMD -  uint64_t usec; -  char *watchdog = NULL; -  int ret; - -  ret = sd_watchdog_enabled (0, &usec); - -  /* -   * If return is 0 -> we don't want watchdog -   * if return is < 0, some sort of failure occurred -   */ -  if (ret < 0) -    return 0; - -  /* -   * systemd can return that this process -   * is not the expected sender of the watchdog timer -   * If we set the_process = 0 then we expect to -   * be able to send the watchdog to systemd -   * irrelevant of the pid of this process. -   */ -  if (ret == 0 && the_process) -    return 0; - -  if (ret == 0 && !the_process) -    { -      watchdog = getenv ("WATCHDOG_USEC"); -      if (!watchdog) -	return 0; - -      usec = atol (watchdog); -    } - -  return (usec / 1000000)/ 3; +	uint64_t usec; +	char *watchdog = NULL; +	int ret; + +	ret = sd_watchdog_enabled(0, &usec); + +	/* +	 * If return is 0 -> we don't want watchdog +	 * if return is < 0, some sort of failure occurred +	 */ +	if (ret < 0) +		return 0; + +	/* +	 * systemd can return that this process +	 * is not the expected sender of the watchdog timer +	 * If we set the_process = 0 then we expect to +	 * be able to send the watchdog to systemd +	 * irrelevant of the pid of this process. +	 */ +	if (ret == 0 && the_process) +		return 0; + +	if (ret == 0 && !the_process) { +		watchdog = getenv("WATCHDOG_USEC"); +		if (!watchdog) +			return 0; + +		usec = atol(watchdog); +	} + +	return (usec / 1000000) / 3;  #else -  return 0; +	return 0;  #endif  } -void -systemd_send_stopping (void) +void systemd_send_stopping(void)  { -  systemd_send_information ("STOPPING=1"); +	systemd_send_information("STOPPING=1");  }  /* @@ -99,25 +95,23 @@ systemd_send_stopping (void)  int wsecs = 0;  struct thread_master *systemd_master = NULL; -static int -systemd_send_watchdog (struct thread *t) +static int systemd_send_watchdog(struct thread *t)  { -  systemd_send_information ("WATCHDOG=1"); +	systemd_send_information("WATCHDOG=1"); -  thread_add_timer (systemd_master, systemd_send_watchdog, NULL, wsecs); +	thread_add_timer(systemd_master, systemd_send_watchdog, NULL, wsecs); -  return 1; +	return 1;  } -void -systemd_send_started (struct thread_master *m, int the_process) +void systemd_send_started(struct thread_master *m, int the_process)  { -  assert (m != NULL); +	assert(m != NULL); -  wsecs = systemd_get_watchdog_time(the_process); -  systemd_master = m; +	wsecs = systemd_get_watchdog_time(the_process); +	systemd_master = m; -  systemd_send_information ("READY=1"); -  if (wsecs != 0) -    thread_add_timer (m, systemd_send_watchdog, m, wsecs); +	systemd_send_information("READY=1"); +	if (wsecs != 0) +		thread_add_timer(m, systemd_send_watchdog, m, wsecs);  } diff --git a/lib/systemd.h b/lib/systemd.h index 685f3d9a77..a9a8fb1f34 100644 --- a/lib/systemd.h +++ b/lib/systemd.h @@ -28,13 +28,12 @@ Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA   * To turn on systemd compilation, use --enable-systemd on   * configure run.   */ -void systemd_send_information (const char *info); -void systemd_send_stopping (void); +void systemd_send_information(const char *info); +void systemd_send_stopping(void);  /*   *  master - The struct thread_master * to use to schedule ourself   *  the_process - Should we send watchdog if we are not the requested   *                process?   */ -void systemd_send_started (struct thread_master *master, int the_process); - +void systemd_send_started(struct thread_master *master, int the_process); diff --git a/lib/table.c b/lib/table.c index 7f789dd3cd..ae5f49f160 100644 --- a/lib/table.c +++ b/lib/table.c @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -27,496 +27,456 @@  #include "memory.h"  #include "sockunion.h" -DEFINE_MTYPE(       LIB, ROUTE_TABLE, "Route table") -DEFINE_MTYPE(       LIB, ROUTE_NODE,  "Route node") +DEFINE_MTYPE(LIB, ROUTE_TABLE, "Route table") +DEFINE_MTYPE(LIB, ROUTE_NODE, "Route node") -static void route_node_delete (struct route_node *); -static void route_table_free (struct route_table *); +static void route_node_delete(struct route_node *); +static void route_table_free(struct route_table *);  /*   * route_table_init_with_delegate   */  struct route_table * -route_table_init_with_delegate (route_table_delegate_t *delegate) +route_table_init_with_delegate(route_table_delegate_t *delegate)  { -  struct route_table *rt; +	struct route_table *rt; -  rt = XCALLOC (MTYPE_ROUTE_TABLE, sizeof (struct route_table)); -  rt->delegate = delegate; -  return rt; +	rt = XCALLOC(MTYPE_ROUTE_TABLE, sizeof(struct route_table)); +	rt->delegate = delegate; +	return rt;  } -void -route_table_finish (struct route_table *rt) +void route_table_finish(struct route_table *rt)  { -  route_table_free (rt); +	route_table_free(rt);  }  /* Allocate new route node. */ -static struct route_node * -route_node_new (struct route_table *table) +static struct route_node *route_node_new(struct route_table *table)  { -  return table->delegate->create_node (table->delegate, table); +	return table->delegate->create_node(table->delegate, table);  }  /* Allocate new route node with prefix set. */ -static struct route_node * -route_node_set (struct route_table *table, const struct prefix *prefix) +static struct route_node *route_node_set(struct route_table *table, +					 const struct prefix *prefix)  { -  struct route_node *node; -   -  node = route_node_new (table); +	struct route_node *node; -  prefix_copy (&node->p, prefix); -  node->table = table; +	node = route_node_new(table); -  return node; +	prefix_copy(&node->p, prefix); +	node->table = table; + +	return node;  }  /* Free route node. */ -static void -route_node_free (struct route_table *table, struct route_node *node) +static void route_node_free(struct route_table *table, struct route_node *node)  { -  if (table->cleanup) -    table->cleanup(table, node); -  table->delegate->destroy_node (table->delegate, table, node); +	if (table->cleanup) +		table->cleanup(table, node); +	table->delegate->destroy_node(table->delegate, table, node);  }  /* Free route table. */ -static void -route_table_free (struct route_table *rt) -{ -  struct route_node *tmp_node; -  struct route_node *node; -  -  if (rt == NULL) -    return; - -  node = rt->top; - -  /* Bulk deletion of nodes remaining in this table.  This function is not -     called until workers have completed their dependency on this table. -     A final route_unlock_node() will not be called for these nodes. */ -  while (node) -    { -      if (node->l_left) -	{ -	  node = node->l_left; -	  continue; +static void route_table_free(struct route_table *rt) +{ +	struct route_node *tmp_node; +	struct route_node *node; + +	if (rt == NULL) +		return; + +	node = rt->top; + +	/* Bulk deletion of nodes remaining in this table.  This function is not +	   called until workers have completed their dependency on this table. +	   A final route_unlock_node() will not be called for these nodes. */ +	while (node) { +		if (node->l_left) { +			node = node->l_left; +			continue; +		} + +		if (node->l_right) { +			node = node->l_right; +			continue; +		} + +		tmp_node = node; +		node = node->parent; + +		tmp_node->table->count--; +		tmp_node->lock = 0; /* to cause assert if unlocked after this */ +		route_node_free(rt, tmp_node); + +		if (node != NULL) { +			if (node->l_left == tmp_node) +				node->l_left = NULL; +			else +				node->l_right = NULL; +		} else { +			break; +		}  	} -      if (node->l_right) -	{ -	  node = node->l_right; -	  continue; -	} - -      tmp_node = node; -      node = node->parent; - -      tmp_node->table->count--; -      tmp_node->lock = 0;  /* to cause assert if unlocked after this */ -      route_node_free (rt, tmp_node); - -      if (node != NULL) -	{ -	  if (node->l_left == tmp_node) -	    node->l_left = NULL; -	  else -	    node->l_right = NULL; -	} -      else -	{ -	  break; -	} -    } -  -  assert (rt->count == 0); +	assert(rt->count == 0); -  XFREE (MTYPE_ROUTE_TABLE, rt); -  return; +	XFREE(MTYPE_ROUTE_TABLE, rt); +	return;  }  /* Utility mask array. */ -static const u_char maskbit[] = -{ -  0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff -}; +static const u_char maskbit[] = {0x00, 0x80, 0xc0, 0xe0, 0xf0, +				 0xf8, 0xfc, 0xfe, 0xff};  /* Common prefix route genaration. */ -static void -route_common (const struct prefix *n, const struct prefix *p, struct prefix *new) -{ -  int i; -  u_char diff; -  u_char mask; - -  const u_char *np = (const u_char *)&n->u.prefix; -  const u_char *pp = (const u_char *)&p->u.prefix; -  u_char *newp = (u_char *)&new->u.prefix; - -  for (i = 0; i < p->prefixlen / 8; i++) -    { -      if (np[i] == pp[i]) -	newp[i] = np[i]; -      else -	break; -    } - -  new->prefixlen = i * 8; - -  if (new->prefixlen != p->prefixlen) -    { -      diff = np[i] ^ pp[i]; -      mask = 0x80; -      while (new->prefixlen < p->prefixlen && !(mask & diff)) -	{ -	  mask >>= 1; -	  new->prefixlen++; +static void route_common(const struct prefix *n, const struct prefix *p, +			 struct prefix *new) +{ +	int i; +	u_char diff; +	u_char mask; + +	const u_char *np = (const u_char *)&n->u.prefix; +	const u_char *pp = (const u_char *)&p->u.prefix; +	u_char *newp = (u_char *)&new->u.prefix; + +	for (i = 0; i < p->prefixlen / 8; i++) { +		if (np[i] == pp[i]) +			newp[i] = np[i]; +		else +			break; +	} + +	new->prefixlen = i * 8; + +	if (new->prefixlen != p->prefixlen) { +		diff = np[i] ^ pp[i]; +		mask = 0x80; +		while (new->prefixlen < p->prefixlen && !(mask & diff)) { +			mask >>= 1; +			new->prefixlen++; +		} +		newp[i] = np[i] & maskbit[new->prefixlen % 8];  	} -      newp[i] = np[i] & maskbit[new->prefixlen % 8]; -    }  } -static void -set_link (struct route_node *node, struct route_node *new) +static void set_link(struct route_node *node, struct route_node *new)  { -  unsigned int bit = prefix_bit (&new->p.u.prefix, node->p.prefixlen); +	unsigned int bit = prefix_bit(&new->p.u.prefix, node->p.prefixlen); -  node->link[bit] = new; -  new->parent = node; +	node->link[bit] = new; +	new->parent = node;  }  /* Lock node. */ -struct route_node * -route_lock_node (struct route_node *node) +struct route_node *route_lock_node(struct route_node *node)  { -  node->lock++; -  return node; +	node->lock++; +	return node;  }  /* Unlock node. */ -void -route_unlock_node (struct route_node *node) +void route_unlock_node(struct route_node *node)  { -  assert (node->lock > 0); -  node->lock--; +	assert(node->lock > 0); +	node->lock--; -  if (node->lock == 0) -    route_node_delete (node); +	if (node->lock == 0) +		route_node_delete(node);  }  /* Find matched prefix. */ -struct route_node * -route_node_match (const struct route_table *table, const struct prefix *p) +struct route_node *route_node_match(const struct route_table *table, +				    const struct prefix *p)  { -  struct route_node *node; -  struct route_node *matched; +	struct route_node *node; +	struct route_node *matched; + +	matched = NULL; +	node = table->top; -  matched = NULL; -  node = table->top; +	/* Walk down tree.  If there is matched route then store it to +	   matched. */ +	while (node && node->p.prefixlen <= p->prefixlen +	       && prefix_match(&node->p, p)) { +		if (node->info) +			matched = node; -  /* Walk down tree.  If there is matched route then store it to -     matched. */ -  while (node && node->p.prefixlen <= p->prefixlen &&  -	 prefix_match (&node->p, p)) -    { -      if (node->info) -	matched = node; -       -      if (node->p.prefixlen == p->prefixlen) -        break; -       -      node = node->link[prefix_bit(&p->u.prefix, node->p.prefixlen)]; -    } +		if (node->p.prefixlen == p->prefixlen) +			break; -  /* If matched route found, return it. */ -  if (matched) -    return route_lock_node (matched); +		node = node->link[prefix_bit(&p->u.prefix, node->p.prefixlen)]; +	} + +	/* If matched route found, return it. */ +	if (matched) +		return route_lock_node(matched); -  return NULL; +	return NULL;  } -struct route_node * -route_node_match_ipv4 (const struct route_table *table, -		       const struct in_addr *addr) +struct route_node *route_node_match_ipv4(const struct route_table *table, +					 const struct in_addr *addr)  { -  struct prefix_ipv4 p; +	struct prefix_ipv4 p; -  memset (&p, 0, sizeof (struct prefix_ipv4)); -  p.family = AF_INET; -  p.prefixlen = IPV4_MAX_PREFIXLEN; -  p.prefix = *addr; +	memset(&p, 0, sizeof(struct prefix_ipv4)); +	p.family = AF_INET; +	p.prefixlen = IPV4_MAX_PREFIXLEN; +	p.prefix = *addr; -  return route_node_match (table, (struct prefix *) &p); +	return route_node_match(table, (struct prefix *)&p);  } -struct route_node * -route_node_match_ipv6 (const struct route_table *table, -		       const struct in6_addr *addr) +struct route_node *route_node_match_ipv6(const struct route_table *table, +					 const struct in6_addr *addr)  { -  struct prefix_ipv6 p; +	struct prefix_ipv6 p; -  memset (&p, 0, sizeof (struct prefix_ipv6)); -  p.family = AF_INET6; -  p.prefixlen = IPV6_MAX_PREFIXLEN; -  p.prefix = *addr; +	memset(&p, 0, sizeof(struct prefix_ipv6)); +	p.family = AF_INET6; +	p.prefixlen = IPV6_MAX_PREFIXLEN; +	p.prefix = *addr; -  return route_node_match (table, (struct prefix *) &p); +	return route_node_match(table, (struct prefix *)&p);  }  /* Lookup same prefix node.  Return NULL when we can't find route. */ -struct route_node * -route_node_lookup (const struct route_table *table, const struct prefix *p) +struct route_node *route_node_lookup(const struct route_table *table, +				     const struct prefix *p)  { -  struct route_node *node; -  u_char prefixlen = p->prefixlen; -  const u_char *prefix = &p->u.prefix; +	struct route_node *node; +	u_char prefixlen = p->prefixlen; +	const u_char *prefix = &p->u.prefix; -  node = table->top; +	node = table->top; -  while (node && node->p.prefixlen <= prefixlen && -	 prefix_match (&node->p, p)) -    { -      if (node->p.prefixlen == prefixlen) -        return node->info ? route_lock_node (node) : NULL; +	while (node && node->p.prefixlen <= prefixlen +	       && prefix_match(&node->p, p)) { +		if (node->p.prefixlen == prefixlen) +			return node->info ? route_lock_node(node) : NULL; -      node = node->link[prefix_bit(prefix, node->p.prefixlen)]; -    } +		node = node->link[prefix_bit(prefix, node->p.prefixlen)]; +	} -  return NULL; +	return NULL;  }  /* Lookup same prefix node.  Return NULL when we can't find route. */ -struct route_node * -route_node_lookup_maynull (const struct route_table *table, const struct prefix *p) +struct route_node *route_node_lookup_maynull(const struct route_table *table, +					     const struct prefix *p)  { -  struct route_node *node; -  u_char prefixlen = p->prefixlen; -  const u_char *prefix = &p->u.prefix; +	struct route_node *node; +	u_char prefixlen = p->prefixlen; +	const u_char *prefix = &p->u.prefix; -  node = table->top; +	node = table->top; -  while (node && node->p.prefixlen <= prefixlen && -	 prefix_match (&node->p, p)) -    { -      if (node->p.prefixlen == prefixlen) -        return route_lock_node (node); +	while (node && node->p.prefixlen <= prefixlen +	       && prefix_match(&node->p, p)) { +		if (node->p.prefixlen == prefixlen) +			return route_lock_node(node); -      node = node->link[prefix_bit(prefix, node->p.prefixlen)]; -    } +		node = node->link[prefix_bit(prefix, node->p.prefixlen)]; +	} -  return NULL; +	return NULL;  }  /* Add node to routing table. */ -struct route_node * -route_node_get (struct route_table *const table, const struct prefix *p) -{ -  struct route_node *new; -  struct route_node *node; -  struct route_node *match; -  u_char prefixlen = p->prefixlen; -  const u_char *prefix = &p->u.prefix; - -  match = NULL; -  node = table->top; -  while (node && node->p.prefixlen <= prefixlen && -	 prefix_match (&node->p, p)) -    { -      if (node->p.prefixlen == prefixlen) -        return route_lock_node (node); - -      match = node; -      node = node->link[prefix_bit(prefix, node->p.prefixlen)]; -    } - -  if (node == NULL) -    { -      new = route_node_set (table, p); -      if (match) -	set_link (match, new); -      else -	table->top = new; -    } -  else -    { -      new = route_node_new (table); -      route_common (&node->p, p, &new->p); -      new->p.family = p->family; -      new->table = table; -      set_link (new, node); - -      if (match) -	set_link (match, new); -      else -	table->top = new; - -      if (new->p.prefixlen != p->prefixlen) -	{ -	  match = new; -	  new = route_node_set (table, p); -	  set_link (match, new); -	  table->count++; +struct route_node *route_node_get(struct route_table *const table, +				  const struct prefix *p) +{ +	struct route_node *new; +	struct route_node *node; +	struct route_node *match; +	u_char prefixlen = p->prefixlen; +	const u_char *prefix = &p->u.prefix; + +	match = NULL; +	node = table->top; +	while (node && node->p.prefixlen <= prefixlen +	       && prefix_match(&node->p, p)) { +		if (node->p.prefixlen == prefixlen) +			return route_lock_node(node); + +		match = node; +		node = node->link[prefix_bit(prefix, node->p.prefixlen)];  	} -    } -  table->count++; -  route_lock_node (new); -   -  return new; + +	if (node == NULL) { +		new = route_node_set(table, p); +		if (match) +			set_link(match, new); +		else +			table->top = new; +	} else { +		new = route_node_new(table); +		route_common(&node->p, p, &new->p); +		new->p.family = p->family; +		new->table = table; +		set_link(new, node); + +		if (match) +			set_link(match, new); +		else +			table->top = new; + +		if (new->p.prefixlen != p->prefixlen) { +			match = new; +			new = route_node_set(table, p); +			set_link(match, new); +			table->count++; +		} +	} +	table->count++; +	route_lock_node(new); + +	return new;  }  /* Delete node from the routing table. */ -static void -route_node_delete (struct route_node *node) +static void route_node_delete(struct route_node *node)  { -  struct route_node *child; -  struct route_node *parent; +	struct route_node *child; +	struct route_node *parent; -  assert (node->lock == 0); -  assert (node->info == NULL); +	assert(node->lock == 0); +	assert(node->info == NULL); -  if (node->l_left && node->l_right) -    return; +	if (node->l_left && node->l_right) +		return; -  if (node->l_left) -    child = node->l_left; -  else -    child = node->l_right; +	if (node->l_left) +		child = node->l_left; +	else +		child = node->l_right; -  parent = node->parent; +	parent = node->parent; -  if (child) -    child->parent = parent; +	if (child) +		child->parent = parent; -  if (parent) -    { -      if (parent->l_left == node) -	parent->l_left = child; -      else -	parent->l_right = child; -    } -  else -    node->table->top = child; +	if (parent) { +		if (parent->l_left == node) +			parent->l_left = child; +		else +			parent->l_right = child; +	} else +		node->table->top = child; -  node->table->count--; +	node->table->count--; -  /* WARNING: FRAGILE CODE! -   * route_node_free may have the side effect of free'ing the entire table. -   * this is permitted only if table->count got decremented to zero above, -   * because in that case parent will also be NULL, so that we won't try to -   * delete a now-stale parent below. -   * -   * cf. srcdest_srcnode_destroy() in zebra/zebra_rib.c */ +	/* WARNING: FRAGILE CODE! +	 * route_node_free may have the side effect of free'ing the entire +	 * table. +	 * this is permitted only if table->count got decremented to zero above, +	 * because in that case parent will also be NULL, so that we won't try +	 * to +	 * delete a now-stale parent below. +	 * +	 * cf. srcdest_srcnode_destroy() in zebra/zebra_rib.c */ -  route_node_free (node->table, node); +	route_node_free(node->table, node); -  /* If parent node is stub then delete it also. */ -  if (parent && parent->lock == 0) -    route_node_delete (parent); +	/* If parent node is stub then delete it also. */ +	if (parent && parent->lock == 0) +		route_node_delete(parent);  }  /* Get fist node and lock it.  This function is useful when one want     to lookup all the node exist in the routing table. */ -struct route_node * -route_top (struct route_table *table) +struct route_node *route_top(struct route_table *table)  { -  /* If there is no node in the routing table return NULL. */ -  if (table->top == NULL) -    return NULL; +	/* If there is no node in the routing table return NULL. */ +	if (table->top == NULL) +		return NULL; -  /* Lock the top node and return it. */ -  route_lock_node (table->top); -  return table->top; +	/* Lock the top node and return it. */ +	route_lock_node(table->top); +	return table->top;  }  /* Unlock current node and lock next node then return it. */ -struct route_node * -route_next (struct route_node *node) -{ -  struct route_node *next; -  struct route_node *start; - -  /* Node may be deleted from route_unlock_node so we have to preserve -     next node's pointer. */ - -  if (node->l_left) -    { -      next = node->l_left; -      route_lock_node (next); -      route_unlock_node (node); -      return next; -    } -  if (node->l_right) -    { -      next = node->l_right; -      route_lock_node (next); -      route_unlock_node (node); -      return next; -    } - -  start = node; -  while (node->parent) -    { -      if (node->parent->l_left == node && node->parent->l_right) -	{ -	  next = node->parent->l_right; -	  route_lock_node (next); -	  route_unlock_node (start); -	  return next; +struct route_node *route_next(struct route_node *node) +{ +	struct route_node *next; +	struct route_node *start; + +	/* Node may be deleted from route_unlock_node so we have to preserve +	   next node's pointer. */ + +	if (node->l_left) { +		next = node->l_left; +		route_lock_node(next); +		route_unlock_node(node); +		return next; +	} +	if (node->l_right) { +		next = node->l_right; +		route_lock_node(next); +		route_unlock_node(node); +		return next;  	} -      node = node->parent; -    } -  route_unlock_node (start); -  return NULL; + +	start = node; +	while (node->parent) { +		if (node->parent->l_left == node && node->parent->l_right) { +			next = node->parent->l_right; +			route_lock_node(next); +			route_unlock_node(start); +			return next; +		} +		node = node->parent; +	} +	route_unlock_node(start); +	return NULL;  }  /* Unlock current node and lock next node until limit. */ -struct route_node * -route_next_until (struct route_node *node, struct route_node *limit) -{ -  struct route_node *next; -  struct route_node *start; - -  /* Node may be deleted from route_unlock_node so we have to preserve -     next node's pointer. */ - -  if (node->l_left) -    { -      next = node->l_left; -      route_lock_node (next); -      route_unlock_node (node); -      return next; -    } -  if (node->l_right) -    { -      next = node->l_right; -      route_lock_node (next); -      route_unlock_node (node); -      return next; -    } - -  start = node; -  while (node->parent && node != limit) -    { -      if (node->parent->l_left == node && node->parent->l_right) -	{ -	  next = node->parent->l_right; -	  route_lock_node (next); -	  route_unlock_node (start); -	  return next; +struct route_node *route_next_until(struct route_node *node, +				    struct route_node *limit) +{ +	struct route_node *next; +	struct route_node *start; + +	/* Node may be deleted from route_unlock_node so we have to preserve +	   next node's pointer. */ + +	if (node->l_left) { +		next = node->l_left; +		route_lock_node(next); +		route_unlock_node(node); +		return next;  	} -      node = node->parent; -    } -  route_unlock_node (start); -  return NULL; +	if (node->l_right) { +		next = node->l_right; +		route_lock_node(next); +		route_unlock_node(node); +		return next; +	} + +	start = node; +	while (node->parent && node != limit) { +		if (node->parent->l_left == node && node->parent->l_right) { +			next = node->parent->l_right; +			route_lock_node(next); +			route_unlock_node(start); +			return next; +		} +		node = node->parent; +	} +	route_unlock_node(start); +	return NULL;  } -unsigned long -route_table_count (const struct route_table *table) +unsigned long route_table_count(const struct route_table *table)  { -  return table->count; +	return table->count;  }  /** @@ -524,13 +484,12 @@ route_table_count (const struct route_table *table)   *   * Default function for creating a route node.   */ -struct route_node * -route_node_create (route_table_delegate_t *delegate, -		   struct route_table *table) +struct route_node *route_node_create(route_table_delegate_t *delegate, +				     struct route_table *table)  { -  struct route_node *node; -  node = XCALLOC (MTYPE_ROUTE_NODE, sizeof (struct route_node)); -  return node; +	struct route_node *node; +	node = XCALLOC(MTYPE_ROUTE_NODE, sizeof(struct route_node)); +	return node;  }  /** @@ -538,34 +497,30 @@ route_node_create (route_table_delegate_t *delegate,   *   * Default function for destroying a route node.   */ -void -route_node_destroy (route_table_delegate_t *delegate, -		    struct route_table *table, struct route_node *node) +void route_node_destroy(route_table_delegate_t *delegate, +			struct route_table *table, struct route_node *node)  { -  XFREE (MTYPE_ROUTE_NODE, node); +	XFREE(MTYPE_ROUTE_NODE, node);  }  /*   * Default delegate.   */  static route_table_delegate_t default_delegate = { -  .create_node = route_node_create, -  .destroy_node = route_node_destroy -}; +	.create_node = route_node_create, +	.destroy_node = route_node_destroy}; -route_table_delegate_t * -route_table_get_default_delegate(void) +route_table_delegate_t *route_table_get_default_delegate(void)  { -  return &default_delegate; +	return &default_delegate;  }  /*   * route_table_init   */ -struct route_table * -route_table_init (void) +struct route_table *route_table_init(void)  { -  return route_table_init_with_delegate (&default_delegate); +	return route_table_init_with_delegate(&default_delegate);  }  /** @@ -573,63 +528,57 @@ route_table_init (void)   *   * Compare two prefixes according to the order in which they appear in   * an iteration over a tree. - *  + *   * @return -1 if p1 occurs before p2 (p1 < p2)   *          0 if the prefixes are identical (p1 == p2)   *         +1 if p1 occurs after p2 (p1 > p2)   */ -int -route_table_prefix_iter_cmp (struct prefix *p1, struct prefix *p2) -{ -  struct prefix common_space; -  struct prefix *common = &common_space; - -  if (p1->prefixlen <= p2->prefixlen) -    { -      if (prefix_match (p1, p2)) -	{ +int route_table_prefix_iter_cmp(struct prefix *p1, struct prefix *p2) +{ +	struct prefix common_space; +	struct prefix *common = &common_space; + +	if (p1->prefixlen <= p2->prefixlen) { +		if (prefix_match(p1, p2)) { + +			/* +			 * p1 contains p2, or is equal to it. +			 */ +			return (p1->prefixlen == p2->prefixlen) ? 0 : -1; +		} +	} else { + +		/* +		 * Check if p2 contains p1. +		 */ +		if (prefix_match(p2, p1)) +			return 1; +	} -	  /* -	   * p1 contains p2, or is equal to it. -	   */ -	  return (p1->prefixlen == p2->prefixlen) ? 0 : -1; +	route_common(p1, p2, common); +	assert(common->prefixlen < p1->prefixlen); +	assert(common->prefixlen < p2->prefixlen); + +	/* +	 * Both prefixes are longer than the common prefix. +	 * +	 * We need to check the bit after the common prefixlen to determine +	 * which one comes later. +	 */ +	if (prefix_bit(&p1->u.prefix, common->prefixlen)) { + +		/* +		 * We branch to the right to get to p1 from the common prefix. +		 */ +		assert(!prefix_bit(&p2->u.prefix, common->prefixlen)); +		return 1;  	} -    } -  else -    { - -      /* -       * Check if p2 contains p1. -       */ -      if (prefix_match (p2, p1)) -	  return 1; -    } - -  route_common (p1, p2, common); -  assert (common->prefixlen < p1->prefixlen); -  assert (common->prefixlen < p2->prefixlen); - -  /* -   * Both prefixes are longer than the common prefix. -   * -   * We need to check the bit after the common prefixlen to determine -   * which one comes later. -   */ -  if (prefix_bit (&p1->u.prefix, common->prefixlen)) -    { - -      /* -       * We branch to the right to get to p1 from the common prefix. -       */ -      assert (!prefix_bit (&p2->u.prefix, common->prefixlen)); -      return 1; -    } - -  /* -   * We branch to the right to get to p2 from the common prefix. -   */ -  assert (prefix_bit (&p2->u.prefix, common->prefixlen)); -  return -1; + +	/* +	 * We branch to the right to get to p2 from the common prefix. +	 */ +	assert(prefix_bit(&p2->u.prefix, common->prefixlen)); +	return -1;  }  /* @@ -638,18 +587,16 @@ route_table_prefix_iter_cmp (struct prefix *p1, struct prefix *p2)   * Helper function that returns the first node that follows the nodes   * in the sub-tree under 'node' in iteration order.   */ -static struct route_node * -route_get_subtree_next (struct route_node *node) +static struct route_node *route_get_subtree_next(struct route_node *node)  { -  while (node->parent) -    { -      if (node->parent->l_left == node && node->parent->l_right) -	return node->parent->l_right; +	while (node->parent) { +		if (node->parent->l_left == node && node->parent->l_right) +			return node->parent->l_right; -      node = node->parent; -    } +		node = node->parent; +	} -  return NULL; +	return NULL;  }  /** @@ -661,99 +608,98 @@ route_get_subtree_next (struct route_node *node)   * @see route_table_get_next   */  static struct route_node * -route_table_get_next_internal (const struct route_table *table, -			       struct prefix *p) -{ -  struct route_node *node, *tmp_node; -  int cmp; - -  node = table->top; - -  while (node) -    { -      int match; - -      if (node->p.prefixlen < p->prefixlen) -	match = prefix_match (&node->p, p); -      else -	match = prefix_match (p, &node->p); - -      if (match) -	{ -	  if (node->p.prefixlen == p->prefixlen) -	    { - -	      /* -	       * The prefix p exists in the tree, just return the next -	       * node. -	       */ -	      route_lock_node (node); -	      node = route_next (node); -	      if (node) -		route_unlock_node (node); - -	      return (node); -	    } - -	  if (node->p.prefixlen > p->prefixlen) -	    { - -	      /* -	       * Node is in the subtree of p, and hence greater than p. -	       */ -	      return node; -	    } - -	  /* -	   * p is in the sub-tree under node. -	   */ -	  tmp_node = node->link[prefix_bit (&p->u.prefix, node->p.prefixlen)]; - -	  if (tmp_node) -	    { -	      node = tmp_node; -	      continue; -	    } - -	  /* -	   * There are no nodes in the direction where p should be. If -	   * node has a right child, then it must be greater than p. -	   */ -	  if (node->l_right) -	    return node->l_right; - -	  /* -	   * No more children to follow, go upwards looking for the next -	   * node. -	   */ -	  return route_get_subtree_next (node); -	} - -      /* -       * Neither node prefix nor 'p' contains the other. -       */ -      cmp = route_table_prefix_iter_cmp (&node->p, p); -      if (cmp > 0) -	{ - -	  /* -	   * Node follows p in iteration order. Return it. -	   */ -	  return node; +route_table_get_next_internal(const struct route_table *table, struct prefix *p) +{ +	struct route_node *node, *tmp_node; +	int cmp; + +	node = table->top; + +	while (node) { +		int match; + +		if (node->p.prefixlen < p->prefixlen) +			match = prefix_match(&node->p, p); +		else +			match = prefix_match(p, &node->p); + +		if (match) { +			if (node->p.prefixlen == p->prefixlen) { + +				/* +				 * The prefix p exists in the tree, just return +				 * the next +				 * node. +				 */ +				route_lock_node(node); +				node = route_next(node); +				if (node) +					route_unlock_node(node); + +				return (node); +			} + +			if (node->p.prefixlen > p->prefixlen) { + +				/* +				 * Node is in the subtree of p, and hence +				 * greater than p. +				 */ +				return node; +			} + +			/* +			 * p is in the sub-tree under node. +			 */ +			tmp_node = node->link[prefix_bit(&p->u.prefix, +							 node->p.prefixlen)]; + +			if (tmp_node) { +				node = tmp_node; +				continue; +			} + +			/* +			 * There are no nodes in the direction where p should +			 * be. If +			 * node has a right child, then it must be greater than +			 * p. +			 */ +			if (node->l_right) +				return node->l_right; + +			/* +			 * No more children to follow, go upwards looking for +			 * the next +			 * node. +			 */ +			return route_get_subtree_next(node); +		} + +		/* +		 * Neither node prefix nor 'p' contains the other. +		 */ +		cmp = route_table_prefix_iter_cmp(&node->p, p); +		if (cmp > 0) { + +			/* +			 * Node follows p in iteration order. Return it. +			 */ +			return node; +		} + +		assert(cmp < 0); + +		/* +		 * Node and the subtree under it come before prefix p in +		 * iteration order. Prefix p and its sub-tree are not present in +		 * the tree. Go upwards and find the first node that follows the +		 * subtree. That node will also succeed p. +		 */ +		return route_get_subtree_next(node);  	} -      assert (cmp < 0); - -      /* -       * Node and the subtree under it come before prefix p in -       * iteration order. Prefix p and its sub-tree are not present in -       * the tree. Go upwards and find the first node that follows the -       * subtree. That node will also succeed p. -       */ -      return route_get_subtree_next (node); -    } - -  return NULL; +	return NULL;  }  /** @@ -762,29 +708,27 @@ route_table_get_next_internal (const struct route_table *table,   * Find the node that occurs after the given prefix in order of   * iteration.   */ -struct route_node * -route_table_get_next (const struct route_table *table, struct prefix *p) +struct route_node *route_table_get_next(const struct route_table *table, +					struct prefix *p)  { -  struct route_node *node; +	struct route_node *node; -  node = route_table_get_next_internal (table, p); -  if (node) -    { -      assert (route_table_prefix_iter_cmp (&node->p, p) > 0); -      route_lock_node (node); -    } -  return node; +	node = route_table_get_next_internal(table, p); +	if (node) { +		assert(route_table_prefix_iter_cmp(&node->p, p) > 0); +		route_lock_node(node); +	} +	return node;  }  /*   * route_table_iter_init   */ -void -route_table_iter_init (route_table_iter_t * iter, struct route_table *table) +void route_table_iter_init(route_table_iter_t *iter, struct route_table *table)  { -  memset (iter, 0, sizeof (*iter)); -  iter->state = RT_ITER_STATE_INIT; -  iter->table = table; +	memset(iter, 0, sizeof(*iter)); +	iter->state = RT_ITER_STATE_INIT; +	iter->table = table;  }  /* @@ -795,34 +739,32 @@ route_table_iter_init (route_table_iter_t * iter, struct route_table *table)   * An iteration can be resumed by just calling route_table_iter_next()   * on the iterator.   */ -void -route_table_iter_pause (route_table_iter_t * iter) -{ -  switch (iter->state) -    { - -    case RT_ITER_STATE_INIT: -    case RT_ITER_STATE_PAUSED: -    case RT_ITER_STATE_DONE: -      return; - -    case RT_ITER_STATE_ITERATING: - -      /* -       * Save the prefix that we are currently at. The next call to -       * route_table_iter_next() will return the node after this prefix -       * in the tree. -       */ -      prefix_copy (&iter->pause_prefix, &iter->current->p); -      route_unlock_node (iter->current); -      iter->current = NULL; -      iter->state = RT_ITER_STATE_PAUSED; -      return; - -    default: -      assert (0); -    } - +void route_table_iter_pause(route_table_iter_t *iter) +{ +	switch (iter->state) { + +	case RT_ITER_STATE_INIT: +	case RT_ITER_STATE_PAUSED: +	case RT_ITER_STATE_DONE: +		return; + +	case RT_ITER_STATE_ITERATING: + +		/* +		 * Save the prefix that we are currently at. The next call to +		 * route_table_iter_next() will return the node after this +		 * prefix +		 * in the tree. +		 */ +		prefix_copy(&iter->pause_prefix, &iter->current->p); +		route_unlock_node(iter->current); +		iter->current = NULL; +		iter->state = RT_ITER_STATE_PAUSED; +		return; + +	default: +		assert(0); +	}  }  /* @@ -830,19 +772,17 @@ route_table_iter_pause (route_table_iter_t * iter)   *   * Release any resources held by the iterator.   */ -void -route_table_iter_cleanup (route_table_iter_t * iter) -{ -  if (iter->state == RT_ITER_STATE_ITERATING) -    { -      route_unlock_node (iter->current); -      iter->current = NULL; -    } -  assert (!iter->current); - -  /* -   * Set the state to RT_ITER_STATE_DONE to make any -   * route_table_iter_next() calls on this iterator return NULL. -   */ -  iter->state = RT_ITER_STATE_DONE; +void route_table_iter_cleanup(route_table_iter_t *iter) +{ +	if (iter->state == RT_ITER_STATE_ITERATING) { +		route_unlock_node(iter->current); +		iter->current = NULL; +	} +	assert(!iter->current); + +	/* +	 * Set the state to RT_ITER_STATE_DONE to make any +	 * route_table_iter_next() calls on this iterator return NULL. +	 */ +	iter->state = RT_ITER_STATE_DONE;  } diff --git a/lib/table.h b/lib/table.h index 1691a8e20a..1eeed5c437 100644 --- a/lib/table.h +++ b/lib/table.h @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_TABLE_H @@ -41,63 +41,61 @@ struct route_table;   */  typedef struct route_table_delegate_t_ route_table_delegate_t; -typedef struct route_node * (*route_table_create_node_func_t)  -  (route_table_delegate_t *, struct route_table *); +typedef struct route_node *(*route_table_create_node_func_t)( +	route_table_delegate_t *, struct route_table *); -typedef void (*route_table_destroy_node_func_t)  -  (route_table_delegate_t *, struct route_table *, struct route_node *); +typedef void (*route_table_destroy_node_func_t)(route_table_delegate_t *, +						struct route_table *, +						struct route_node *); -struct route_table_delegate_t_  -{ -  route_table_create_node_func_t create_node; -  route_table_destroy_node_func_t destroy_node; +struct route_table_delegate_t_ { +	route_table_create_node_func_t create_node; +	route_table_destroy_node_func_t destroy_node;  };  /* Routing table top structure. */ -struct route_table -{ -  struct route_node *top; - -  /* -   * Delegate that performs certain functions for this table. -   */ -  route_table_delegate_t *delegate; -  void (*cleanup)(struct route_table *, struct route_node *); -   -  unsigned long count; -   -  /* -   * User data. -   */ -  void *info; +struct route_table { +	struct route_node *top; + +	/* +	 * Delegate that performs certain functions for this table. +	 */ +	route_table_delegate_t *delegate; +	void (*cleanup)(struct route_table *, struct route_node *); + +	unsigned long count; + +	/* +	 * User data. +	 */ +	void *info;  };  /*   * Macro that defines all fields in a route node.   */ -#define ROUTE_NODE_FIELDS			\ -  /* Actual prefix of this radix. */		\ -  struct prefix p;				\ -						\ -  /* Tree link. */				\ -  struct route_table *table;			\ -  struct route_node *parent;			\ -  struct route_node *link[2];			\ -						\ -  /* Lock of this radix */			\ -  unsigned int lock;				\ -						\ -  /* Each node of route. */			\ -  void *info;					\ -						\ -  /* Aggregation. */				\ -  void *aggregate; +#define ROUTE_NODE_FIELDS                                                      \ +	/* Actual prefix of this radix. */                                     \ +	struct prefix p;                                                       \ +                                                                               \ +	/* Tree link. */                                                       \ +	struct route_table *table;                                             \ +	struct route_node *parent;                                             \ +	struct route_node *link[2];                                            \ +                                                                               \ +	/* Lock of this radix */                                               \ +	unsigned int lock;                                                     \ +                                                                               \ +	/* Each node of route. */                                              \ +	void *info;                                                            \ +                                                                               \ +	/* Aggregation. */                                                     \ +	void *aggregate;  /* Each routing entry. */ -struct route_node -{ -  ROUTE_NODE_FIELDS +struct route_node { +	ROUTE_NODE_FIELDS  #define l_left   link[0]  #define l_right  link[1] @@ -105,89 +103,85 @@ struct route_node  typedef struct route_table_iter_t_ route_table_iter_t; -typedef enum  -{ -  RT_ITER_STATE_INIT, -  RT_ITER_STATE_ITERATING, -  RT_ITER_STATE_PAUSED, -  RT_ITER_STATE_DONE +typedef enum { +	RT_ITER_STATE_INIT, +	RT_ITER_STATE_ITERATING, +	RT_ITER_STATE_PAUSED, +	RT_ITER_STATE_DONE  } route_table_iter_state_t;  /*   * route_table_iter_t - *  + *   * Structure that holds state for iterating over a route table.   */ -struct route_table_iter_t_  -{ +struct route_table_iter_t_ { -  route_table_iter_state_t state; +	route_table_iter_state_t state; -  /* -   * Routing table that we are iterating over. The caller must ensure -   * that that table outlives the iterator. -   */ -  struct route_table *table; +	/* +	 * Routing table that we are iterating over. The caller must ensure +	 * that that table outlives the iterator. +	 */ +	struct route_table *table; -  /* -   * The node that the iterator is currently on. -   */ -  struct route_node *current; +	/* +	 * The node that the iterator is currently on. +	 */ +	struct route_node *current; -  /* -   * The last prefix that the iterator processed before it was paused. -   */   -  struct prefix pause_prefix; +	/* +	 * The last prefix that the iterator processed before it was paused. +	 */ +	struct prefix pause_prefix;  };  /* Prototypes. */ -extern struct route_table *route_table_init (void); +extern struct route_table *route_table_init(void);  extern struct route_table * -route_table_init_with_delegate (route_table_delegate_t *); - -extern route_table_delegate_t * -route_table_get_default_delegate(void); - -extern void route_table_finish (struct route_table *); -extern void route_unlock_node (struct route_node *node); -extern struct route_node *route_top (struct route_table *); -extern struct route_node *route_next (struct route_node *); -extern struct route_node *route_next_until (struct route_node *, -                                            struct route_node *); -extern struct route_node *route_node_get (struct route_table *const, -                                          const struct prefix *); -extern struct route_node *route_node_lookup (const struct route_table *, -                                             const struct prefix *); -extern struct route_node *route_node_lookup_maynull (const struct route_table *, -                                             const struct prefix *); -extern struct route_node *route_lock_node (struct route_node *node); -extern struct route_node *route_node_match (const struct route_table *, -                                            const struct prefix *); -extern struct route_node *route_node_match_ipv4 (const struct route_table *, -						 const struct in_addr *); -extern struct route_node *route_node_match_ipv6 (const struct route_table *, -						 const struct in6_addr *); - -extern unsigned long route_table_count (const struct route_table *); - -extern struct route_node *route_node_create (route_table_delegate_t *, -					     struct route_table *); -extern void route_node_destroy (route_table_delegate_t *, -				struct route_table *, struct route_node *); - -extern struct route_node * -route_table_get_next (const struct route_table *table, struct prefix *p); -extern int -route_table_prefix_iter_cmp (struct prefix *p1, struct prefix *p2); +route_table_init_with_delegate(route_table_delegate_t *); + +extern route_table_delegate_t *route_table_get_default_delegate(void); + +extern void route_table_finish(struct route_table *); +extern void route_unlock_node(struct route_node *node); +extern struct route_node *route_top(struct route_table *); +extern struct route_node *route_next(struct route_node *); +extern struct route_node *route_next_until(struct route_node *, +					   struct route_node *); +extern struct route_node *route_node_get(struct route_table *const, +					 const struct prefix *); +extern struct route_node *route_node_lookup(const struct route_table *, +					    const struct prefix *); +extern struct route_node *route_node_lookup_maynull(const struct route_table *, +						    const struct prefix *); +extern struct route_node *route_lock_node(struct route_node *node); +extern struct route_node *route_node_match(const struct route_table *, +					   const struct prefix *); +extern struct route_node *route_node_match_ipv4(const struct route_table *, +						const struct in_addr *); +extern struct route_node *route_node_match_ipv6(const struct route_table *, +						const struct in6_addr *); + +extern unsigned long route_table_count(const struct route_table *); + +extern struct route_node *route_node_create(route_table_delegate_t *, +					    struct route_table *); +extern void route_node_destroy(route_table_delegate_t *, struct route_table *, +			       struct route_node *); + +extern struct route_node *route_table_get_next(const struct route_table *table, +					       struct prefix *p); +extern int route_table_prefix_iter_cmp(struct prefix *p1, struct prefix *p2);  /*   * Iterator functions.   */ -extern void route_table_iter_init (route_table_iter_t *iter, -				   struct route_table *table); -extern void route_table_iter_pause (route_table_iter_t *iter); -extern void route_table_iter_cleanup (route_table_iter_t *iter); +extern void route_table_iter_init(route_table_iter_t *iter, +				  struct route_table *table); +extern void route_table_iter_pause(route_table_iter_t *iter); +extern void route_table_iter_cleanup(route_table_iter_t *iter);  /*   * Inline functions. @@ -198,48 +192,46 @@ extern void route_table_iter_cleanup (route_table_iter_t *iter);   *   * Get the next node in the tree.   */ -static inline struct route_node * -route_table_iter_next (route_table_iter_t * iter) +static inline struct route_node *route_table_iter_next(route_table_iter_t *iter)  { -  struct route_node *node; +	struct route_node *node; -  switch (iter->state) -    { +	switch (iter->state) { -    case RT_ITER_STATE_INIT: +	case RT_ITER_STATE_INIT: -      /* -       * We're just starting the iteration. -       */ -      node = route_top (iter->table); -      break; +		/* +		 * We're just starting the iteration. +		 */ +		node = route_top(iter->table); +		break; -    case RT_ITER_STATE_ITERATING: -      node = route_next (iter->current); -      break; +	case RT_ITER_STATE_ITERATING: +		node = route_next(iter->current); +		break; -    case RT_ITER_STATE_PAUSED: +	case RT_ITER_STATE_PAUSED: -      /* -       * Start with the node following pause_prefix. -       */ -      node = route_table_get_next (iter->table, &iter->pause_prefix); -      break; +		/* +		 * Start with the node following pause_prefix. +		 */ +		node = route_table_get_next(iter->table, &iter->pause_prefix); +		break; -    case RT_ITER_STATE_DONE: -      return NULL; +	case RT_ITER_STATE_DONE: +		return NULL; -    default: -      assert (0); -    } +	default: +		assert(0); +	} -  iter->current = node; -  if (node) -    iter->state = RT_ITER_STATE_ITERATING; -  else -    iter->state = RT_ITER_STATE_DONE; +	iter->current = node; +	if (node) +		iter->state = RT_ITER_STATE_ITERATING; +	else +		iter->state = RT_ITER_STATE_DONE; -  return node; +	return node;  }  /* @@ -247,10 +239,9 @@ route_table_iter_next (route_table_iter_t * iter)   *   * Returns TRUE if the iteration is complete.   */ -static inline int -route_table_iter_is_done (route_table_iter_t *iter) +static inline int route_table_iter_is_done(route_table_iter_t *iter)  { -  return iter->state == RT_ITER_STATE_DONE; +	return iter->state == RT_ITER_STATE_DONE;  }  /* @@ -258,10 +249,9 @@ route_table_iter_is_done (route_table_iter_t *iter)   *   * Returns TRUE if this iterator has started iterating over the tree.   */ -static inline int -route_table_iter_started (route_table_iter_t *iter) +static inline int route_table_iter_started(route_table_iter_t *iter)  { -  return iter->state != RT_ITER_STATE_INIT; +	return iter->state != RT_ITER_STATE_INIT;  }  #endif /* _ZEBRA_TABLE_H */ diff --git a/lib/thread.c b/lib/thread.c index dbdd91dd24..71ea8ac89d 100644 --- a/lib/thread.c +++ b/lib/thread.c @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  /* #define DEBUG */ @@ -32,9 +32,9 @@  #include "command.h"  #include "sigevent.h" -DEFINE_MTYPE_STATIC(LIB, THREAD,        "Thread") +DEFINE_MTYPE_STATIC(LIB, THREAD, "Thread")  DEFINE_MTYPE_STATIC(LIB, THREAD_MASTER, "Thread master") -DEFINE_MTYPE_STATIC(LIB, THREAD_STATS,  "Thread stats") +DEFINE_MTYPE_STATIC(LIB, THREAD_STATS, "Thread stats")  #if defined(__APPLE__)  #include <mach/mach.h> @@ -44,105 +44,96 @@ DEFINE_MTYPE_STATIC(LIB, THREAD_STATS,  "Thread stats")  /* Relative time, since startup */  static struct hash *cpu_record = NULL; -static unsigned long -timeval_elapsed (struct timeval a, struct timeval b) +static unsigned long timeval_elapsed(struct timeval a, struct timeval b)  { -  return (((a.tv_sec - b.tv_sec) * TIMER_SECOND_MICRO) -	  + (a.tv_usec - b.tv_usec)); +	return (((a.tv_sec - b.tv_sec) * TIMER_SECOND_MICRO) +		+ (a.tv_usec - b.tv_usec));  } -static unsigned int -cpu_record_hash_key (struct cpu_thread_history *a) +static unsigned int cpu_record_hash_key(struct cpu_thread_history *a)  { -  return (uintptr_t) a->func; +	return (uintptr_t)a->func;  } -static int  -cpu_record_hash_cmp (const struct cpu_thread_history *a, -		     const struct cpu_thread_history *b) +static int cpu_record_hash_cmp(const struct cpu_thread_history *a, +			       const struct cpu_thread_history *b)  { -  return a->func == b->func; +	return a->func == b->func;  } -static void * -cpu_record_hash_alloc (struct cpu_thread_history *a) +static void *cpu_record_hash_alloc(struct cpu_thread_history *a)  { -  struct cpu_thread_history *new; -  new = XCALLOC (MTYPE_THREAD_STATS, sizeof (struct cpu_thread_history)); -  new->func = a->func; -  new->funcname = a->funcname; -  return new; +	struct cpu_thread_history *new; +	new = XCALLOC(MTYPE_THREAD_STATS, sizeof(struct cpu_thread_history)); +	new->func = a->func; +	new->funcname = a->funcname; +	return new;  } -static void -cpu_record_hash_free (void *a) +static void cpu_record_hash_free(void *a)  { -  struct cpu_thread_history *hist = a; -  -  XFREE (MTYPE_THREAD_STATS, hist); +	struct cpu_thread_history *hist = a; + +	XFREE(MTYPE_THREAD_STATS, hist);  } -static void  -vty_out_cpu_thread_history(struct vty* vty, -			   struct cpu_thread_history *a) +static void vty_out_cpu_thread_history(struct vty *vty, +				       struct cpu_thread_history *a)  { -  vty_out(vty, "%5d %10ld.%03ld %9d %8ld %9ld %8ld %9ld", -	  a->total_active, a->cpu.total/1000, a->cpu.total%1000, a->total_calls, -	  a->cpu.total/a->total_calls, a->cpu.max, -	  a->real.total/a->total_calls, a->real.max); -  vty_out(vty, " %c%c%c%c%c%c %s%s", -	  a->types & (1 << THREAD_READ) ? 'R':' ', -	  a->types & (1 << THREAD_WRITE) ? 'W':' ', -	  a->types & (1 << THREAD_TIMER) ? 'T':' ', -	  a->types & (1 << THREAD_EVENT) ? 'E':' ', -	  a->types & (1 << THREAD_EXECUTE) ? 'X':' ', -	  a->types & (1 << THREAD_BACKGROUND) ? 'B' : ' ', -	  a->funcname, VTY_NEWLINE); +	vty_out(vty, "%5d %10ld.%03ld %9d %8ld %9ld %8ld %9ld", a->total_active, +		a->cpu.total / 1000, a->cpu.total % 1000, a->total_calls, +		a->cpu.total / a->total_calls, a->cpu.max, +		a->real.total / a->total_calls, a->real.max); +	vty_out(vty, " %c%c%c%c%c%c %s%s", +		a->types & (1 << THREAD_READ) ? 'R' : ' ', +		a->types & (1 << THREAD_WRITE) ? 'W' : ' ', +		a->types & (1 << THREAD_TIMER) ? 'T' : ' ', +		a->types & (1 << THREAD_EVENT) ? 'E' : ' ', +		a->types & (1 << THREAD_EXECUTE) ? 'X' : ' ', +		a->types & (1 << THREAD_BACKGROUND) ? 'B' : ' ', a->funcname, +		VTY_NEWLINE);  } -static void -cpu_record_hash_print(struct hash_backet *bucket,  -		      void *args[]) +static void cpu_record_hash_print(struct hash_backet *bucket, void *args[])  { -  struct cpu_thread_history *totals = args[0]; -  struct vty *vty = args[1]; -  thread_type *filter = args[2]; -  struct cpu_thread_history *a = bucket->data; - -  if ( !(a->types & *filter) ) -       return; -  vty_out_cpu_thread_history(vty,a); -  totals->total_active += a->total_active; -  totals->total_calls += a->total_calls; -  totals->real.total += a->real.total; -  if (totals->real.max < a->real.max) -    totals->real.max = a->real.max; -  totals->cpu.total += a->cpu.total; -  if (totals->cpu.max < a->cpu.max) -    totals->cpu.max = a->cpu.max; +	struct cpu_thread_history *totals = args[0]; +	struct vty *vty = args[1]; +	thread_type *filter = args[2]; +	struct cpu_thread_history *a = bucket->data; + +	if (!(a->types & *filter)) +		return; +	vty_out_cpu_thread_history(vty, a); +	totals->total_active += a->total_active; +	totals->total_calls += a->total_calls; +	totals->real.total += a->real.total; +	if (totals->real.max < a->real.max) +		totals->real.max = a->real.max; +	totals->cpu.total += a->cpu.total; +	if (totals->cpu.max < a->cpu.max) +		totals->cpu.max = a->cpu.max;  } -static void -cpu_record_print(struct vty *vty, thread_type filter) +static void cpu_record_print(struct vty *vty, thread_type filter)  { -  struct cpu_thread_history tmp; -  void *args[3] = {&tmp, vty, &filter}; - -  memset(&tmp, 0, sizeof tmp); -  tmp.funcname = "TOTAL"; -  tmp.types = filter; - -  vty_out(vty, "%21s %18s %18s%s", -	  "", "CPU (user+system):", "Real (wall-clock):", VTY_NEWLINE); -  vty_out(vty, "Active   Runtime(ms)   Invoked Avg uSec Max uSecs"); -  vty_out(vty, " Avg uSec Max uSecs"); -  vty_out(vty, "  Type  Thread%s", VTY_NEWLINE); -  hash_iterate(cpu_record, -	       (void(*)(struct hash_backet*,void*))cpu_record_hash_print, -	       args); - -  if (tmp.total_calls > 0) -    vty_out_cpu_thread_history(vty, &tmp); +	struct cpu_thread_history tmp; +	void *args[3] = {&tmp, vty, &filter}; + +	memset(&tmp, 0, sizeof tmp); +	tmp.funcname = "TOTAL"; +	tmp.types = filter; + +	vty_out(vty, "%21s %18s %18s%s", "", +		"CPU (user+system):", "Real (wall-clock):", VTY_NEWLINE); +	vty_out(vty, "Active   Runtime(ms)   Invoked Avg uSec Max uSecs"); +	vty_out(vty, " Avg uSec Max uSecs"); +	vty_out(vty, "  Type  Thread%s", VTY_NEWLINE); +	hash_iterate(cpu_record, (void (*)(struct hash_backet *, +					   void *))cpu_record_hash_print, +		     args); + +	if (tmp.total_calls > 0) +		vty_out_cpu_thread_history(vty, &tmp);  }  DEFUN (show_thread_cpu, @@ -153,79 +144,73 @@ DEFUN (show_thread_cpu,         "Thread CPU usage\n"         "Display filter (rwtexb)\n")  { -  int idx_filter = 3; -  int i = 0; -  thread_type filter = (thread_type) -1U; - -  if (argc > 3) -    { -      filter = 0; -      while (argv[idx_filter]->arg[i] != '\0') -	{ -	  switch ( argv[idx_filter]->arg[i] ) -	    { -	    case 'r': -	    case 'R': -	      filter |= (1 << THREAD_READ); -	      break; -	    case 'w': -	    case 'W': -	      filter |= (1 << THREAD_WRITE); -	      break; -	    case 't': -	    case 'T': -	      filter |= (1 << THREAD_TIMER); -	      break; -	    case 'e': -	    case 'E': -	      filter |= (1 << THREAD_EVENT); -	      break; -	    case 'x': -	    case 'X': -	      filter |= (1 << THREAD_EXECUTE); -	      break; -	    case 'b': -	    case 'B': -	      filter |= (1 << THREAD_BACKGROUND); -	      break; -	    default: -	      break; -	    } -	  ++i; -	} -      if (filter == 0) -	{ -	  vty_out(vty, "Invalid filter \"%s\" specified," -                  " must contain at least one of 'RWTEXB'%s", -		  argv[idx_filter]->arg, VTY_NEWLINE); -	  return CMD_WARNING; +	int idx_filter = 3; +	int i = 0; +	thread_type filter = (thread_type)-1U; + +	if (argc > 3) { +		filter = 0; +		while (argv[idx_filter]->arg[i] != '\0') { +			switch (argv[idx_filter]->arg[i]) { +			case 'r': +			case 'R': +				filter |= (1 << THREAD_READ); +				break; +			case 'w': +			case 'W': +				filter |= (1 << THREAD_WRITE); +				break; +			case 't': +			case 'T': +				filter |= (1 << THREAD_TIMER); +				break; +			case 'e': +			case 'E': +				filter |= (1 << THREAD_EVENT); +				break; +			case 'x': +			case 'X': +				filter |= (1 << THREAD_EXECUTE); +				break; +			case 'b': +			case 'B': +				filter |= (1 << THREAD_BACKGROUND); +				break; +			default: +				break; +			} +			++i; +		} +		if (filter == 0) { +			vty_out(vty, +				"Invalid filter \"%s\" specified," +				" must contain at least one of 'RWTEXB'%s", +				argv[idx_filter]->arg, VTY_NEWLINE); +			return CMD_WARNING; +		}  	} -    } -  cpu_record_print(vty, filter); -  return CMD_SUCCESS; +	cpu_record_print(vty, filter); +	return CMD_SUCCESS;  } -static void -cpu_record_hash_clear (struct hash_backet *bucket,  -		      void *args) +static void cpu_record_hash_clear(struct hash_backet *bucket, void *args)  { -  thread_type *filter = args; -  struct cpu_thread_history *a = bucket->data; +	thread_type *filter = args; +	struct cpu_thread_history *a = bucket->data; + +	if (!(a->types & *filter)) +		return; -  if ( !(a->types & *filter) ) -       return; -   -  hash_release (cpu_record, bucket->data); +	hash_release(cpu_record, bucket->data);  } -static void -cpu_record_clear (thread_type filter) +static void cpu_record_clear(thread_type filter)  { -  thread_type *tmp = &filter; -  hash_iterate (cpu_record, -	        (void (*) (struct hash_backet*,void*)) cpu_record_hash_clear, -	        tmp); +	thread_type *tmp = &filter; +	hash_iterate(cpu_record, (void (*)(struct hash_backet *, +					   void *))cpu_record_hash_clear, +		     tmp);  }  DEFUN (clear_thread_cpu, @@ -236,255 +221,238 @@ DEFUN (clear_thread_cpu,         "Thread CPU usage\n"         "Display filter (rwtexb)\n")  { -  int idx_filter = 3; -  int i = 0; -  thread_type filter = (thread_type) -1U; - -  if (argc > 3) -    { -      filter = 0; -      while (argv[idx_filter]->arg[i] != '\0') -	{ -	  switch ( argv[idx_filter]->arg[i] ) -	    { -	    case 'r': -	    case 'R': -	      filter |= (1 << THREAD_READ); -	      break; -	    case 'w': -	    case 'W': -	      filter |= (1 << THREAD_WRITE); -	      break; -	    case 't': -	    case 'T': -	      filter |= (1 << THREAD_TIMER); -	      break; -	    case 'e': -	    case 'E': -	      filter |= (1 << THREAD_EVENT); -	      break; -	    case 'x': -	    case 'X': -	      filter |= (1 << THREAD_EXECUTE); -	      break; -	    case 'b': -	    case 'B': -	      filter |= (1 << THREAD_BACKGROUND); -	      break; -	    default: -	      break; -	    } -	  ++i; +	int idx_filter = 3; +	int i = 0; +	thread_type filter = (thread_type)-1U; + +	if (argc > 3) { +		filter = 0; +		while (argv[idx_filter]->arg[i] != '\0') { +			switch (argv[idx_filter]->arg[i]) { +			case 'r': +			case 'R': +				filter |= (1 << THREAD_READ); +				break; +			case 'w': +			case 'W': +				filter |= (1 << THREAD_WRITE); +				break; +			case 't': +			case 'T': +				filter |= (1 << THREAD_TIMER); +				break; +			case 'e': +			case 'E': +				filter |= (1 << THREAD_EVENT); +				break; +			case 'x': +			case 'X': +				filter |= (1 << THREAD_EXECUTE); +				break; +			case 'b': +			case 'B': +				filter |= (1 << THREAD_BACKGROUND); +				break; +			default: +				break; +			} +			++i; +		} +		if (filter == 0) { +			vty_out(vty, +				"Invalid filter \"%s\" specified," +				" must contain at least one of 'RWTEXB'%s", +				argv[idx_filter]->arg, VTY_NEWLINE); +			return CMD_WARNING; +		}  	} -      if (filter == 0) -	{ -	  vty_out(vty, "Invalid filter \"%s\" specified," -                  " must contain at least one of 'RWTEXB'%s", -		  argv[idx_filter]->arg, VTY_NEWLINE); -	  return CMD_WARNING; -	} -    } -  cpu_record_clear (filter); -  return CMD_SUCCESS; +	cpu_record_clear(filter); +	return CMD_SUCCESS;  } -void -thread_cmd_init (void) +void thread_cmd_init(void)  { -  install_element (VIEW_NODE, &show_thread_cpu_cmd); -  install_element (ENABLE_NODE, &clear_thread_cpu_cmd); +	install_element(VIEW_NODE, &show_thread_cpu_cmd); +	install_element(ENABLE_NODE, &clear_thread_cpu_cmd);  } -static int -thread_timer_cmp(void *a, void *b) +static int thread_timer_cmp(void *a, void *b)  { -  struct thread *thread_a = a; -  struct thread *thread_b = b; - -  if (timercmp (&thread_a->u.sands, &thread_b->u.sands, <)) -    return -1; -  if (timercmp (&thread_a->u.sands, &thread_b->u.sands, >)) -    return 1; -  return 0; +	struct thread *thread_a = a; +	struct thread *thread_b = b; + +	if (timercmp(&thread_a->u.sands, &thread_b->u.sands, <)) +		return -1; +	if (timercmp(&thread_a->u.sands, &thread_b->u.sands, >)) +		return 1; +	return 0;  } -static void -thread_timer_update(void *node, int actual_position) +static void thread_timer_update(void *node, int actual_position)  { -  struct thread *thread = node; +	struct thread *thread = node; -  thread->index = actual_position; +	thread->index = actual_position;  }  /* Allocate new thread master.  */ -struct thread_master * -thread_master_create (void) +struct thread_master *thread_master_create(void)  { -  struct thread_master *rv; -  struct rlimit limit; - -  getrlimit(RLIMIT_NOFILE, &limit); - -  if (cpu_record == NULL)  -    cpu_record  -      = hash_create ((unsigned int (*) (void *))cpu_record_hash_key, -		     (int (*) (const void *, const void *))cpu_record_hash_cmp); - -  rv = XCALLOC (MTYPE_THREAD_MASTER, sizeof (struct thread_master)); -  if (rv == NULL) -    { -      return NULL; -    } - -  rv->fd_limit = (int)limit.rlim_cur; -  rv->read = XCALLOC (MTYPE_THREAD, sizeof (struct thread *) * rv->fd_limit); -  if (rv->read == NULL) -    { -      XFREE (MTYPE_THREAD_MASTER, rv); -      return NULL; -    } - -  rv->write = XCALLOC (MTYPE_THREAD, sizeof (struct thread *) * rv->fd_limit); -  if (rv->write == NULL) -    { -      XFREE (MTYPE_THREAD, rv->read); -      XFREE (MTYPE_THREAD_MASTER, rv); -      return NULL; -    } - -  /* Initialize the timer queues */ -  rv->timer = pqueue_create(); -  rv->background = pqueue_create(); -  rv->timer->cmp = rv->background->cmp = thread_timer_cmp; -  rv->timer->update = rv->background->update = thread_timer_update; +	struct thread_master *rv; +	struct rlimit limit; + +	getrlimit(RLIMIT_NOFILE, &limit); + +	if (cpu_record == NULL) +		cpu_record = hash_create( +			(unsigned int (*)(void *))cpu_record_hash_key, +			(int (*)(const void *, +				 const void *))cpu_record_hash_cmp); + +	rv = XCALLOC(MTYPE_THREAD_MASTER, sizeof(struct thread_master)); +	if (rv == NULL) { +		return NULL; +	} + +	rv->fd_limit = (int)limit.rlim_cur; +	rv->read = +		XCALLOC(MTYPE_THREAD, sizeof(struct thread *) * rv->fd_limit); +	if (rv->read == NULL) { +		XFREE(MTYPE_THREAD_MASTER, rv); +		return NULL; +	} + +	rv->write = +		XCALLOC(MTYPE_THREAD, sizeof(struct thread *) * rv->fd_limit); +	if (rv->write == NULL) { +		XFREE(MTYPE_THREAD, rv->read); +		XFREE(MTYPE_THREAD_MASTER, rv); +		return NULL; +	} + +	/* Initialize the timer queues */ +	rv->timer = pqueue_create(); +	rv->background = pqueue_create(); +	rv->timer->cmp = rv->background->cmp = thread_timer_cmp; +	rv->timer->update = rv->background->update = thread_timer_update;  #if defined(HAVE_POLL_CALL) -  rv->handler.pfdsize = rv->fd_limit; -  rv->handler.pfdcount = 0; -  rv->handler.pfds = XCALLOC (MTYPE_THREAD_MASTER, -                              sizeof (struct pollfd) * rv->handler.pfdsize); +	rv->handler.pfdsize = rv->fd_limit; +	rv->handler.pfdcount = 0; +	rv->handler.pfds = XCALLOC(MTYPE_THREAD_MASTER, +				   sizeof(struct pollfd) * rv->handler.pfdsize);  #endif -  return rv; +	return rv;  }  /* Add a new thread to the list.  */ -static void -thread_list_add (struct thread_list *list, struct thread *thread) +static void thread_list_add(struct thread_list *list, struct thread *thread)  { -  thread->next = NULL; -  thread->prev = list->tail; -  if (list->tail) -    list->tail->next = thread; -  else -    list->head = thread; -  list->tail = thread; -  list->count++; +	thread->next = NULL; +	thread->prev = list->tail; +	if (list->tail) +		list->tail->next = thread; +	else +		list->head = thread; +	list->tail = thread; +	list->count++;  }  /* Delete a thread from the list. */ -static struct thread * -thread_list_delete (struct thread_list *list, struct thread *thread) +static struct thread *thread_list_delete(struct thread_list *list, +					 struct thread *thread)  { -  if (thread->next) -    thread->next->prev = thread->prev; -  else -    list->tail = thread->prev; -  if (thread->prev) -    thread->prev->next = thread->next; -  else -    list->head = thread->next; -  thread->next = thread->prev = NULL; -  list->count--; -  return thread; +	if (thread->next) +		thread->next->prev = thread->prev; +	else +		list->tail = thread->prev; +	if (thread->prev) +		thread->prev->next = thread->next; +	else +		list->head = thread->next; +	thread->next = thread->prev = NULL; +	list->count--; +	return thread;  } -static void -thread_delete_fd (struct thread **thread_array, struct thread *thread) +static void thread_delete_fd(struct thread **thread_array, +			     struct thread *thread)  { -  thread_array[thread->u.fd] = NULL; +	thread_array[thread->u.fd] = NULL;  } -static void -thread_add_fd (struct thread **thread_array, struct thread *thread) +static void thread_add_fd(struct thread **thread_array, struct thread *thread)  { -  thread_array[thread->u.fd] = thread; +	thread_array[thread->u.fd] = thread;  }  /* Thread list is empty or not.  */ -static int -thread_empty (struct thread_list *list) +static int thread_empty(struct thread_list *list)  { -  return  list->head ? 0 : 1; +	return list->head ? 0 : 1;  }  /* Delete top of the list and return it. */ -static struct thread * -thread_trim_head (struct thread_list *list) +static struct thread *thread_trim_head(struct thread_list *list)  { -  if (!thread_empty (list)) -    return thread_list_delete (list, list->head); -  return NULL; +	if (!thread_empty(list)) +		return thread_list_delete(list, list->head); +	return NULL;  }  /* Move thread to unuse list. */ -static void -thread_add_unuse (struct thread_master *m, struct thread *thread) +static void thread_add_unuse(struct thread_master *m, struct thread *thread)  { -  assert (m != NULL && thread != NULL); -  assert (thread->next == NULL); -  assert (thread->prev == NULL); +	assert(m != NULL && thread != NULL); +	assert(thread->next == NULL); +	assert(thread->prev == NULL); -  thread->type = THREAD_UNUSED; -  thread->hist->total_active--; -  thread_list_add (&m->unuse, thread); +	thread->type = THREAD_UNUSED; +	thread->hist->total_active--; +	thread_list_add(&m->unuse, thread);  }  /* Free all unused thread. */ -static void -thread_list_free (struct thread_master *m, struct thread_list *list) +static void thread_list_free(struct thread_master *m, struct thread_list *list)  { -  struct thread *t; -  struct thread *next; - -  for (t = list->head; t; t = next) -    { -      next = t->next; -      XFREE (MTYPE_THREAD, t); -      list->count--; -      m->alloc--; -    } +	struct thread *t; +	struct thread *next; + +	for (t = list->head; t; t = next) { +		next = t->next; +		XFREE(MTYPE_THREAD, t); +		list->count--; +		m->alloc--; +	}  } -static void -thread_array_free (struct thread_master *m, struct thread **thread_array) +static void thread_array_free(struct thread_master *m, +			      struct thread **thread_array)  { -  struct thread *t; -  int index; - -  for (index = 0; index < m->fd_limit; ++index) -    { -      t = thread_array[index]; -      if (t) -        { -          thread_array[index] = NULL; -          XFREE (MTYPE_THREAD, t); -          m->alloc--; -        } -    } -  XFREE (MTYPE_THREAD, thread_array); +	struct thread *t; +	int index; + +	for (index = 0; index < m->fd_limit; ++index) { +		t = thread_array[index]; +		if (t) { +			thread_array[index] = NULL; +			XFREE(MTYPE_THREAD, t); +			m->alloc--; +		} +	} +	XFREE(MTYPE_THREAD, thread_array);  } -static void -thread_queue_free (struct thread_master *m, struct pqueue *queue) +static void thread_queue_free(struct thread_master *m, struct pqueue *queue)  { -  int i; +	int i; -  for (i = 0; i < queue->size; i++) -    XFREE(MTYPE_THREAD, queue->array[i]); +	for (i = 0; i < queue->size; i++) +		XFREE(MTYPE_THREAD, queue->array[i]); -  m->alloc -= queue->size; -  pqueue_delete(queue); +	m->alloc -= queue->size; +	pqueue_delete(queue);  }  /* @@ -495,718 +463,674 @@ thread_queue_free (struct thread_master *m, struct pqueue *queue)   * If we are shutting down, Free up unused threads   * So we can see if we forget to shut anything off   */ -void -thread_master_free_unused (struct thread_master *m) +void thread_master_free_unused(struct thread_master *m)  { -  struct thread *t; -  while ((t = thread_trim_head(&m->unuse)) != NULL) -    { -      XFREE(MTYPE_THREAD, t); -    } +	struct thread *t; +	while ((t = thread_trim_head(&m->unuse)) != NULL) { +		XFREE(MTYPE_THREAD, t); +	}  }  /* Stop thread scheduler. */ -void -thread_master_free (struct thread_master *m) +void thread_master_free(struct thread_master *m)  { -  thread_array_free (m, m->read); -  thread_array_free (m, m->write); -  thread_queue_free (m, m->timer); -  thread_list_free (m, &m->event); -  thread_list_free (m, &m->ready); -  thread_list_free (m, &m->unuse); -  thread_queue_free (m, m->background); +	thread_array_free(m, m->read); +	thread_array_free(m, m->write); +	thread_queue_free(m, m->timer); +	thread_list_free(m, &m->event); +	thread_list_free(m, &m->ready); +	thread_list_free(m, &m->unuse); +	thread_queue_free(m, m->background);  #if defined(HAVE_POLL_CALL) -  XFREE (MTYPE_THREAD_MASTER, m->handler.pfds); +	XFREE(MTYPE_THREAD_MASTER, m->handler.pfds);  #endif -  XFREE (MTYPE_THREAD_MASTER, m); - -  if (cpu_record) -    { -      hash_clean (cpu_record, cpu_record_hash_free); -      hash_free (cpu_record); -      cpu_record = NULL; -    } +	XFREE(MTYPE_THREAD_MASTER, m); + +	if (cpu_record) { +		hash_clean(cpu_record, cpu_record_hash_free); +		hash_free(cpu_record); +		cpu_record = NULL; +	}  }  /* Return remain time in second. */ -unsigned long -thread_timer_remain_second (struct thread *thread) +unsigned long thread_timer_remain_second(struct thread *thread)  { -  int64_t remain = monotime_until(&thread->u.sands, NULL) / 1000000LL; -  return remain < 0 ? 0 : remain; +	int64_t remain = monotime_until(&thread->u.sands, NULL) / 1000000LL; +	return remain < 0 ? 0 : remain;  }  #define debugargdef  const char *funcname, const char *schedfrom, int fromln  #define debugargpass funcname, schedfrom, fromln -struct timeval -thread_timer_remain(struct thread *thread) +struct timeval thread_timer_remain(struct thread *thread)  { -  struct timeval remain; -  monotime_until(&thread->u.sands, &remain); -  return remain; +	struct timeval remain; +	monotime_until(&thread->u.sands, &remain); +	return remain;  }  /* Get new thread.  */ -static struct thread * -thread_get (struct thread_master *m, u_char type, -	    int (*func) (struct thread *), void *arg, debugargdef) +static struct thread *thread_get(struct thread_master *m, u_char type, +				 int (*func)(struct thread *), void *arg, +				 debugargdef)  { -  struct thread *thread = thread_trim_head (&m->unuse); -  struct cpu_thread_history tmp; - -  if (! thread) -    { -      thread = XCALLOC (MTYPE_THREAD, sizeof (struct thread)); -      m->alloc++; -    } -  thread->type = type; -  thread->add_type = type; -  thread->master = m; -  thread->arg = arg; -  thread->index = -1; -  thread->yield = THREAD_YIELD_TIME_SLOT; /* default */ - -  /* -   * So if the passed in funcname is not what we have -   * stored that means the thread->hist needs to be -   * updated.  We keep the last one around in unused -   * under the assumption that we are probably -   * going to immediately allocate the same -   * type of thread. -   * This hopefully saves us some serious -   * hash_get lookups. -   */ -  if (thread->funcname != funcname || -      thread->func != func) -    { -      tmp.func = func; -      tmp.funcname = funcname; -      thread->hist = hash_get (cpu_record, &tmp, -			       (void * (*) (void *))cpu_record_hash_alloc); -    } -  thread->hist->total_active++; -  thread->func = func; -  thread->funcname = funcname; -  thread->schedfrom = schedfrom; -  thread->schedfrom_line = fromln; - -  return thread; +	struct thread *thread = thread_trim_head(&m->unuse); +	struct cpu_thread_history tmp; + +	if (!thread) { +		thread = XCALLOC(MTYPE_THREAD, sizeof(struct thread)); +		m->alloc++; +	} +	thread->type = type; +	thread->add_type = type; +	thread->master = m; +	thread->arg = arg; +	thread->index = -1; +	thread->yield = THREAD_YIELD_TIME_SLOT; /* default */ + +	/* +	 * So if the passed in funcname is not what we have +	 * stored that means the thread->hist needs to be +	 * updated.  We keep the last one around in unused +	 * under the assumption that we are probably +	 * going to immediately allocate the same +	 * type of thread. +	 * This hopefully saves us some serious +	 * hash_get lookups. +	 */ +	if (thread->funcname != funcname || thread->func != func) { +		tmp.func = func; +		tmp.funcname = funcname; +		thread->hist = +			hash_get(cpu_record, &tmp, +				 (void *(*)(void *))cpu_record_hash_alloc); +	} +	thread->hist->total_active++; +	thread->func = func; +	thread->funcname = funcname; +	thread->schedfrom = schedfrom; +	thread->schedfrom_line = fromln; + +	return thread;  } -#if defined (HAVE_POLL_CALL) +#if defined(HAVE_POLL_CALL)  #define fd_copy_fd_set(X) (X)  /* generic add thread function */ -static struct thread * -generic_thread_add(struct thread_master *m, int (*func) (struct thread *), -		   void *arg, int fd, int dir, debugargdef) +static struct thread *generic_thread_add(struct thread_master *m, +					 int (*func)(struct thread *), +					 void *arg, int fd, int dir, +					 debugargdef)  { -  struct thread *thread; - -  u_char type; -  short int event; - -  if (dir == THREAD_READ) -    { -      event = (POLLIN | POLLHUP); -      type = THREAD_READ; -    } -  else -    { -      event = (POLLOUT | POLLHUP); -      type = THREAD_WRITE; -    } - -  nfds_t queuepos = m->handler.pfdcount; -  nfds_t i=0; -  for (i=0; i<m->handler.pfdcount; i++) -    if (m->handler.pfds[i].fd == fd) -      { -        queuepos = i; -        break; -      } - -  /* is there enough space for a new fd? */ -  assert (queuepos < m->handler.pfdsize); - -  thread = thread_get (m, type, func, arg, debugargpass); -  m->handler.pfds[queuepos].fd = fd; -  m->handler.pfds[queuepos].events |= event; -  if (queuepos == m->handler.pfdcount) -    m->handler.pfdcount++; - -  return thread; +	struct thread *thread; + +	u_char type; +	short int event; + +	if (dir == THREAD_READ) { +		event = (POLLIN | POLLHUP); +		type = THREAD_READ; +	} else { +		event = (POLLOUT | POLLHUP); +		type = THREAD_WRITE; +	} + +	nfds_t queuepos = m->handler.pfdcount; +	nfds_t i = 0; +	for (i = 0; i < m->handler.pfdcount; i++) +		if (m->handler.pfds[i].fd == fd) { +			queuepos = i; +			break; +		} + +	/* is there enough space for a new fd? */ +	assert(queuepos < m->handler.pfdsize); + +	thread = thread_get(m, type, func, arg, debugargpass); +	m->handler.pfds[queuepos].fd = fd; +	m->handler.pfds[queuepos].events |= event; +	if (queuepos == m->handler.pfdcount) +		m->handler.pfdcount++; + +	return thread;  }  #else  #define fd_copy_fd_set(X) (X)  #endif -static int -fd_select (struct thread_master *m, int size, thread_fd_set *read, thread_fd_set *write, thread_fd_set *except, struct timeval *timer_wait) +static int fd_select(struct thread_master *m, int size, thread_fd_set *read, +		     thread_fd_set *write, thread_fd_set *except, +		     struct timeval *timer_wait)  { -  int num; +	int num;  #if defined(HAVE_POLL_CALL) -  /* recalc timeout for poll. Attention NULL pointer is no timeout with -  select, where with poll no timeount is -1 */ -  int timeout = -1; -  if (timer_wait != NULL) -    timeout = (timer_wait->tv_sec*1000) + (timer_wait->tv_usec/1000); - -  num = poll (m->handler.pfds, m->handler.pfdcount + m->handler.pfdcountsnmp, timeout); +	/* recalc timeout for poll. Attention NULL pointer is no timeout with +	select, where with poll no timeount is -1 */ +	int timeout = -1; +	if (timer_wait != NULL) +		timeout = (timer_wait->tv_sec * 1000) +			  + (timer_wait->tv_usec / 1000); + +	num = poll(m->handler.pfds, +		   m->handler.pfdcount + m->handler.pfdcountsnmp, timeout);  #else -  num = select (size, read, write, except, timer_wait); +	num = select(size, read, write, except, timer_wait);  #endif -  return num; +	return num;  } -static int -fd_is_set (struct thread *thread, thread_fd_set *fdset, int pos) +static int fd_is_set(struct thread *thread, thread_fd_set *fdset, int pos)  {  #if defined(HAVE_POLL_CALL) -  return 1; +	return 1;  #else -  return FD_ISSET (THREAD_FD (thread), fdset); +	return FD_ISSET(THREAD_FD(thread), fdset);  #endif  } -static int -fd_clear_read_write (struct thread *thread) +static int fd_clear_read_write(struct thread *thread)  {  #if !defined(HAVE_POLL_CALL) -  thread_fd_set *fdset = NULL; -  int fd = THREAD_FD (thread); +	thread_fd_set *fdset = NULL; +	int fd = THREAD_FD(thread); -  if (thread->type == THREAD_READ) -    fdset = &thread->master->handler.readfd; -  else -    fdset = &thread->master->handler.writefd; +	if (thread->type == THREAD_READ) +		fdset = &thread->master->handler.readfd; +	else +		fdset = &thread->master->handler.writefd; -  if (!FD_ISSET (fd, fdset)) -    return 0; +	if (!FD_ISSET(fd, fdset)) +		return 0; -  FD_CLR (fd, fdset); +	FD_CLR(fd, fdset);  #endif -  return 1; +	return 1;  }  /* Add new read thread. */ -struct thread * -funcname_thread_add_read_write (int dir, struct thread_master *m, -				int (*func) (struct thread *), void *arg, int fd, -				debugargdef) +struct thread *funcname_thread_add_read_write(int dir, struct thread_master *m, +					      int (*func)(struct thread *), +					      void *arg, int fd, debugargdef)  { -  struct thread *thread = NULL; +	struct thread *thread = NULL;  #if !defined(HAVE_POLL_CALL) -  thread_fd_set *fdset = NULL; -  if (dir == THREAD_READ) -    fdset = &m->handler.readfd; -  else -    fdset = &m->handler.writefd; +	thread_fd_set *fdset = NULL; +	if (dir == THREAD_READ) +		fdset = &m->handler.readfd; +	else +		fdset = &m->handler.writefd;  #endif -#if defined (HAVE_POLL_CALL) -  thread = generic_thread_add(m, func, arg, fd, dir, debugargpass); +#if defined(HAVE_POLL_CALL) +	thread = generic_thread_add(m, func, arg, fd, dir, debugargpass); -  if (thread == NULL) -    return NULL; +	if (thread == NULL) +		return NULL;  #else -  if (FD_ISSET (fd, fdset)) -    { -      zlog_warn ("There is already %s fd [%d]", -                 (dir == THREAD_READ) ? "read" : "write", fd); -      return NULL; -    } - -  FD_SET (fd, fdset); -  thread = thread_get (m, dir, func, arg, debugargpass); +	if (FD_ISSET(fd, fdset)) { +		zlog_warn("There is already %s fd [%d]", +			  (dir == THREAD_READ) ? "read" : "write", fd); +		return NULL; +	} + +	FD_SET(fd, fdset); +	thread = thread_get(m, dir, func, arg, debugargpass);  #endif -  thread->u.fd = fd; -  if (dir == THREAD_READ) -    thread_add_fd (m->read, thread); -  else -    thread_add_fd (m->write, thread); +	thread->u.fd = fd; +	if (dir == THREAD_READ) +		thread_add_fd(m->read, thread); +	else +		thread_add_fd(m->write, thread); -  return thread; +	return thread;  } -static struct thread * -funcname_thread_add_timer_timeval (struct thread_master *m, -                                   int (*func) (struct thread *),  -                                  int type, -                                  void *arg,  -                                  struct timeval *time_relative, -				  debugargdef) +static struct thread *funcname_thread_add_timer_timeval( +	struct thread_master *m, int (*func)(struct thread *), int type, +	void *arg, struct timeval *time_relative, debugargdef)  { -  struct thread *thread; -  struct pqueue *queue; +	struct thread *thread; +	struct pqueue *queue; -  assert (m != NULL); +	assert(m != NULL); -  assert (type == THREAD_TIMER || type == THREAD_BACKGROUND); -  assert (time_relative); -   -  queue = ((type == THREAD_TIMER) ? m->timer : m->background); -  thread = thread_get (m, type, func, arg, debugargpass); +	assert(type == THREAD_TIMER || type == THREAD_BACKGROUND); +	assert(time_relative); -  monotime(&thread->u.sands); -  timeradd(&thread->u.sands, time_relative, &thread->u.sands); +	queue = ((type == THREAD_TIMER) ? m->timer : m->background); +	thread = thread_get(m, type, func, arg, debugargpass); -  pqueue_enqueue(thread, queue); -  return thread; +	monotime(&thread->u.sands); +	timeradd(&thread->u.sands, time_relative, &thread->u.sands); + +	pqueue_enqueue(thread, queue); +	return thread;  }  /* Add timer event thread. */ -struct thread * -funcname_thread_add_timer (struct thread_master *m, -		           int (*func) (struct thread *),  -		           void *arg, long timer, -			   debugargdef) +struct thread *funcname_thread_add_timer(struct thread_master *m, +					 int (*func)(struct thread *), +					 void *arg, long timer, debugargdef)  { -  struct timeval trel; +	struct timeval trel; -  assert (m != NULL); +	assert(m != NULL); -  trel.tv_sec = timer; -  trel.tv_usec = 0; +	trel.tv_sec = timer; +	trel.tv_usec = 0; -  return funcname_thread_add_timer_timeval (m, func, THREAD_TIMER, arg,  -                                            &trel, debugargpass); +	return funcname_thread_add_timer_timeval(m, func, THREAD_TIMER, arg, +						 &trel, debugargpass);  }  /* Add timer event thread with "millisecond" resolution */ -struct thread * -funcname_thread_add_timer_msec (struct thread_master *m, -                                int (*func) (struct thread *),  -                                void *arg, long timer, -				debugargdef) +struct thread *funcname_thread_add_timer_msec(struct thread_master *m, +					      int (*func)(struct thread *), +					      void *arg, long timer, +					      debugargdef)  { -  struct timeval trel; +	struct timeval trel; -  assert (m != NULL); +	assert(m != NULL); -  trel.tv_sec = timer / 1000; -  trel.tv_usec = 1000*(timer % 1000); +	trel.tv_sec = timer / 1000; +	trel.tv_usec = 1000 * (timer % 1000); -  return funcname_thread_add_timer_timeval (m, func, THREAD_TIMER,  -                                            arg, &trel, debugargpass); +	return funcname_thread_add_timer_timeval(m, func, THREAD_TIMER, arg, +						 &trel, debugargpass);  }  /* Add timer event thread with "millisecond" resolution */ -struct thread * -funcname_thread_add_timer_tv (struct thread_master *m, -                              int (*func) (struct thread *), -                              void *arg, struct timeval *tv, -                              debugargdef) +struct thread *funcname_thread_add_timer_tv(struct thread_master *m, +					    int (*func)(struct thread *), +					    void *arg, struct timeval *tv, +					    debugargdef)  { -  return funcname_thread_add_timer_timeval (m, func, THREAD_TIMER, -                                            arg, tv, debugargpass); +	return funcname_thread_add_timer_timeval(m, func, THREAD_TIMER, arg, tv, +						 debugargpass);  }  /* Add a background thread, with an optional millisec delay */ -struct thread * -funcname_thread_add_background (struct thread_master *m, -                                int (*func) (struct thread *), -                                void *arg, long delay, -				debugargdef) +struct thread *funcname_thread_add_background(struct thread_master *m, +					      int (*func)(struct thread *), +					      void *arg, long delay, +					      debugargdef)  { -  struct timeval trel; -   -  assert (m != NULL); -   -  if (delay) -    { -      trel.tv_sec = delay / 1000; -      trel.tv_usec = 1000*(delay % 1000); -    } -  else -    { -      trel.tv_sec = 0; -      trel.tv_usec = 0; -    } - -  return funcname_thread_add_timer_timeval (m, func, THREAD_BACKGROUND, -                                            arg, &trel, debugargpass); +	struct timeval trel; + +	assert(m != NULL); + +	if (delay) { +		trel.tv_sec = delay / 1000; +		trel.tv_usec = 1000 * (delay % 1000); +	} else { +		trel.tv_sec = 0; +		trel.tv_usec = 0; +	} + +	return funcname_thread_add_timer_timeval(m, func, THREAD_BACKGROUND, +						 arg, &trel, debugargpass);  }  /* Add simple event thread. */ -struct thread * -funcname_thread_add_event (struct thread_master *m, -		  int (*func) (struct thread *), void *arg, int val, -		  debugargdef) +struct thread *funcname_thread_add_event(struct thread_master *m, +					 int (*func)(struct thread *), +					 void *arg, int val, debugargdef)  { -  struct thread *thread; +	struct thread *thread; -  assert (m != NULL); +	assert(m != NULL); -  thread = thread_get (m, THREAD_EVENT, func, arg, debugargpass); -  thread->u.val = val; -  thread_list_add (&m->event, thread); +	thread = thread_get(m, THREAD_EVENT, func, arg, debugargpass); +	thread->u.val = val; +	thread_list_add(&m->event, thread); -  return thread; +	return thread;  } -static void -thread_cancel_read_or_write (struct thread *thread, short int state) +static void thread_cancel_read_or_write(struct thread *thread, short int state)  {  #if defined(HAVE_POLL_CALL) -  nfds_t i; - -  for (i=0;i<thread->master->handler.pfdcount;++i) -    if (thread->master->handler.pfds[i].fd == thread->u.fd) -      { -        thread->master->handler.pfds[i].events &= ~(state); - -        /* remove thread fds from pfd list */ -        if (thread->master->handler.pfds[i].events == 0) -          { -            memmove(thread->master->handler.pfds+i, -                    thread->master->handler.pfds+i+1, -                    (thread->master->handler.pfdsize-i-1) * sizeof(struct pollfd)); -            thread->master->handler.pfdcount--; -            return; -          } -      } +	nfds_t i; + +	for (i = 0; i < thread->master->handler.pfdcount; ++i) +		if (thread->master->handler.pfds[i].fd == thread->u.fd) { +			thread->master->handler.pfds[i].events &= ~(state); + +			/* remove thread fds from pfd list */ +			if (thread->master->handler.pfds[i].events == 0) { +				memmove(thread->master->handler.pfds + i, +					thread->master->handler.pfds + i + 1, +					(thread->master->handler.pfdsize - i +					 - 1) * sizeof(struct pollfd)); +				thread->master->handler.pfdcount--; +				return; +			} +		}  #endif -  fd_clear_read_write (thread); +	fd_clear_read_write(thread);  }  /* Cancel thread from scheduler. */ -void -thread_cancel (struct thread *thread) +void thread_cancel(struct thread *thread)  { -  struct thread_list *list = NULL; -  struct pqueue *queue = NULL; -  struct thread **thread_array = NULL; -   -  switch (thread->type) -    { -    case THREAD_READ: -#if defined (HAVE_POLL_CALL) -      thread_cancel_read_or_write (thread, POLLIN | POLLHUP); +	struct thread_list *list = NULL; +	struct pqueue *queue = NULL; +	struct thread **thread_array = NULL; + +	switch (thread->type) { +	case THREAD_READ: +#if defined(HAVE_POLL_CALL) +		thread_cancel_read_or_write(thread, POLLIN | POLLHUP);  #else -      thread_cancel_read_or_write (thread, 0); +		thread_cancel_read_or_write(thread, 0);  #endif -      thread_array = thread->master->read; -      break; -    case THREAD_WRITE: -#if defined (HAVE_POLL_CALL) -      thread_cancel_read_or_write (thread, POLLOUT | POLLHUP); +		thread_array = thread->master->read; +		break; +	case THREAD_WRITE: +#if defined(HAVE_POLL_CALL) +		thread_cancel_read_or_write(thread, POLLOUT | POLLHUP);  #else -      thread_cancel_read_or_write (thread, 0); +		thread_cancel_read_or_write(thread, 0);  #endif -      thread_array = thread->master->write; -      break; -    case THREAD_TIMER: -      queue = thread->master->timer; -      break; -    case THREAD_EVENT: -      list = &thread->master->event; -      break; -    case THREAD_READY: -      list = &thread->master->ready; -      break; -    case THREAD_BACKGROUND: -      queue = thread->master->background; -      break; -    default: -      return; -      break; -    } - -  if (queue) -    { -      assert(thread->index >= 0); -      assert(thread == queue->array[thread->index]); -      pqueue_remove_at(thread->index, queue); -    } -  else if (list) -    { -      thread_list_delete (list, thread); -    } -  else if (thread_array) -    { -      thread_delete_fd (thread_array, thread); -    } -  else -    { -      assert(!"Thread should be either in queue or list or array!"); -    } - -  thread_add_unuse (thread->master, thread); +		thread_array = thread->master->write; +		break; +	case THREAD_TIMER: +		queue = thread->master->timer; +		break; +	case THREAD_EVENT: +		list = &thread->master->event; +		break; +	case THREAD_READY: +		list = &thread->master->ready; +		break; +	case THREAD_BACKGROUND: +		queue = thread->master->background; +		break; +	default: +		return; +		break; +	} + +	if (queue) { +		assert(thread->index >= 0); +		assert(thread == queue->array[thread->index]); +		pqueue_remove_at(thread->index, queue); +	} else if (list) { +		thread_list_delete(list, thread); +	} else if (thread_array) { +		thread_delete_fd(thread_array, thread); +	} else { +		assert(!"Thread should be either in queue or list or array!"); +	} + +	thread_add_unuse(thread->master, thread);  }  /* Delete all events which has argument value arg. */ -unsigned int -thread_cancel_event (struct thread_master *m, void *arg) +unsigned int thread_cancel_event(struct thread_master *m, void *arg)  { -  unsigned int ret = 0; -  struct thread *thread; - -  thread = m->event.head; -  while (thread) -    { -      struct thread *t; - -      t = thread; -      thread = t->next; - -      if (t->arg == arg) -        { -          ret++; -          thread_list_delete (&m->event, t); -          thread_add_unuse (m, t); -        } -    } - -  /* thread can be on the ready list too */ -  thread = m->ready.head; -  while (thread) -    { -      struct thread *t; - -      t = thread; -      thread = t->next; - -      if (t->arg == arg) -        { -          ret++; -          thread_list_delete (&m->ready, t); -          thread_add_unuse (m, t); -        } -    } -  return ret; +	unsigned int ret = 0; +	struct thread *thread; + +	thread = m->event.head; +	while (thread) { +		struct thread *t; + +		t = thread; +		thread = t->next; + +		if (t->arg == arg) { +			ret++; +			thread_list_delete(&m->event, t); +			thread_add_unuse(m, t); +		} +	} + +	/* thread can be on the ready list too */ +	thread = m->ready.head; +	while (thread) { +		struct thread *t; + +		t = thread; +		thread = t->next; + +		if (t->arg == arg) { +			ret++; +			thread_list_delete(&m->ready, t); +			thread_add_unuse(m, t); +		} +	} +	return ret;  } -static struct timeval * -thread_timer_wait (struct pqueue *queue, struct timeval *timer_val) +static struct timeval *thread_timer_wait(struct pqueue *queue, +					 struct timeval *timer_val)  { -  if (queue->size) -    { -      struct thread *next_timer = queue->array[0]; -      monotime_until(&next_timer->u.sands, timer_val); -      return timer_val; -    } -  return NULL; +	if (queue->size) { +		struct thread *next_timer = queue->array[0]; +		monotime_until(&next_timer->u.sands, timer_val); +		return timer_val; +	} +	return NULL;  } -static struct thread * -thread_run (struct thread_master *m, struct thread *thread, -	    struct thread *fetch) +static struct thread *thread_run(struct thread_master *m, struct thread *thread, +				 struct thread *fetch)  { -  *fetch = *thread; -  thread_add_unuse (m, thread); -  return fetch; +	*fetch = *thread; +	thread_add_unuse(m, thread); +	return fetch;  } -static int -thread_process_fds_helper (struct thread_master *m, struct thread *thread, thread_fd_set *fdset, short int state, int pos) +static int thread_process_fds_helper(struct thread_master *m, +				     struct thread *thread, +				     thread_fd_set *fdset, short int state, +				     int pos)  { -  struct thread **thread_array; - -  if (!thread) -    return 0; - -  if (thread->type == THREAD_READ) -    thread_array = m->read; -  else -    thread_array = m->write; - -  if (fd_is_set (thread, fdset, pos)) -    { -      fd_clear_read_write (thread); -      thread_delete_fd (thread_array, thread); -      thread_list_add (&m->ready, thread); -      thread->type = THREAD_READY; +	struct thread **thread_array; + +	if (!thread) +		return 0; + +	if (thread->type == THREAD_READ) +		thread_array = m->read; +	else +		thread_array = m->write; + +	if (fd_is_set(thread, fdset, pos)) { +		fd_clear_read_write(thread); +		thread_delete_fd(thread_array, thread); +		thread_list_add(&m->ready, thread); +		thread->type = THREAD_READY;  #if defined(HAVE_POLL_CALL) -      thread->master->handler.pfds[pos].events &= ~(state); +		thread->master->handler.pfds[pos].events &= ~(state);  #endif -      return 1; -    } -  return 0; +		return 1; +	} +	return 0;  }  #if defined(HAVE_POLL_CALL)  /* check poll events */ -static void -check_pollfds(struct thread_master *m, fd_set *readfd, int num) +static void check_pollfds(struct thread_master *m, fd_set *readfd, int num)  { -  nfds_t i = 0; -  int ready = 0; -  for (i = 0; i < m->handler.pfdcount && ready < num ; ++i) -    { -      /* no event for current fd? immideatly continue */ -      if(m->handler.pfds[i].revents == 0) -        continue; - -      ready++; - -      /* POLLIN / POLLOUT process event */ -      if (m->handler.pfds[i].revents & (POLLIN | POLLHUP)) -        thread_process_fds_helper(m, m->read[m->handler.pfds[i].fd], NULL, POLLIN, i); -      if (m->handler.pfds[i].revents & POLLOUT) -        thread_process_fds_helper(m, m->write[m->handler.pfds[i].fd], NULL, POLLOUT, i); - -      /* remove fd from list on POLLNVAL */ -      if (m->handler.pfds[i].revents & POLLNVAL) -        { -           memmove(m->handler.pfds+i, -                   m->handler.pfds+i+1, -                   (m->handler.pfdsize-i-1) * sizeof(struct pollfd)); -           m->handler.pfdcount--; -           i--; -        } -      else -          m->handler.pfds[i].revents = 0; -    } +	nfds_t i = 0; +	int ready = 0; +	for (i = 0; i < m->handler.pfdcount && ready < num; ++i) { +		/* no event for current fd? immideatly continue */ +		if (m->handler.pfds[i].revents == 0) +			continue; + +		ready++; + +		/* POLLIN / POLLOUT process event */ +		if (m->handler.pfds[i].revents & (POLLIN | POLLHUP)) +			thread_process_fds_helper( +				m, m->read[m->handler.pfds[i].fd], NULL, POLLIN, +				i); +		if (m->handler.pfds[i].revents & POLLOUT) +			thread_process_fds_helper( +				m, m->write[m->handler.pfds[i].fd], NULL, +				POLLOUT, i); + +		/* remove fd from list on POLLNVAL */ +		if (m->handler.pfds[i].revents & POLLNVAL) { +			memmove(m->handler.pfds + i, m->handler.pfds + i + 1, +				(m->handler.pfdsize - i - 1) +					* sizeof(struct pollfd)); +			m->handler.pfdcount--; +			i--; +		} else +			m->handler.pfds[i].revents = 0; +	}  }  #endif -static void -thread_process_fds (struct thread_master *m, thread_fd_set *rset, thread_fd_set *wset, int num) +static void thread_process_fds(struct thread_master *m, thread_fd_set *rset, +			       thread_fd_set *wset, int num)  { -#if defined (HAVE_POLL_CALL) -  check_pollfds (m, rset, num); +#if defined(HAVE_POLL_CALL) +	check_pollfds(m, rset, num);  #else -  int ready = 0, index; +	int ready = 0, index; -  for (index = 0; index < m->fd_limit && ready < num; ++index) -    { -      ready += thread_process_fds_helper (m, m->read[index], rset, 0, 0); -      ready += thread_process_fds_helper (m, m->write[index], wset, 0, 0); -    } +	for (index = 0; index < m->fd_limit && ready < num; ++index) { +		ready += thread_process_fds_helper(m, m->read[index], rset, 0, +						   0); +		ready += thread_process_fds_helper(m, m->write[index], wset, 0, +						   0); +	}  #endif  }  /* Add all timers that have popped to the ready list. */ -static unsigned int -thread_timer_process (struct pqueue *queue, struct timeval *timenow) +static unsigned int thread_timer_process(struct pqueue *queue, +					 struct timeval *timenow)  { -  struct thread *thread; -  unsigned int ready = 0; -   -  while (queue->size) -    { -      thread = queue->array[0]; -      if (timercmp (timenow, &thread->u.sands, <)) -        return ready; -      pqueue_dequeue(queue); -      thread->type = THREAD_READY; -      thread_list_add (&thread->master->ready, thread); -      ready++; -    } -  return ready; +	struct thread *thread; +	unsigned int ready = 0; + +	while (queue->size) { +		thread = queue->array[0]; +		if (timercmp(timenow, &thread->u.sands, <)) +			return ready; +		pqueue_dequeue(queue); +		thread->type = THREAD_READY; +		thread_list_add(&thread->master->ready, thread); +		ready++; +	} +	return ready;  }  /* process a list en masse, e.g. for event thread lists */ -static unsigned int -thread_process (struct thread_list *list) +static unsigned int thread_process(struct thread_list *list)  { -  struct thread *thread; -  struct thread *next; -  unsigned int ready = 0; -   -  for (thread = list->head; thread; thread = next) -    { -      next = thread->next; -      thread_list_delete (list, thread); -      thread->type = THREAD_READY; -      thread_list_add (&thread->master->ready, thread); -      ready++; -    } -  return ready; +	struct thread *thread; +	struct thread *next; +	unsigned int ready = 0; + +	for (thread = list->head; thread; thread = next) { +		next = thread->next; +		thread_list_delete(list, thread); +		thread->type = THREAD_READY; +		thread_list_add(&thread->master->ready, thread); +		ready++; +	} +	return ready;  }  /* Fetch next ready thread. */ -struct thread * -thread_fetch (struct thread_master *m, struct thread *fetch) +struct thread *thread_fetch(struct thread_master *m, struct thread *fetch)  { -  struct thread *thread; -  thread_fd_set readfd; -  thread_fd_set writefd; -  thread_fd_set exceptfd; -  struct timeval now; -  struct timeval timer_val = { .tv_sec = 0, .tv_usec = 0 }; -  struct timeval timer_val_bg; -  struct timeval *timer_wait = &timer_val; -  struct timeval *timer_wait_bg; - -  while (1) -    { -      int num = 0; - -      /* Signals pre-empt everything */ -      quagga_sigevent_process (); -        -      /* Drain the ready queue of already scheduled jobs, before scheduling -       * more. -       */ -      if ((thread = thread_trim_head (&m->ready)) != NULL) -        return thread_run (m, thread, fetch); -       -      /* To be fair to all kinds of threads, and avoid starvation, we -       * need to be careful to consider all thread types for scheduling -       * in each quanta. I.e. we should not return early from here on. -       */ -        -      /* Normal event are the next highest priority.  */ -      thread_process (&m->event); -       -      /* Structure copy.  */ +	struct thread *thread; +	thread_fd_set readfd; +	thread_fd_set writefd; +	thread_fd_set exceptfd; +	struct timeval now; +	struct timeval timer_val = {.tv_sec = 0, .tv_usec = 0}; +	struct timeval timer_val_bg; +	struct timeval *timer_wait = &timer_val; +	struct timeval *timer_wait_bg; + +	while (1) { +		int num = 0; + +		/* Signals pre-empt everything */ +		quagga_sigevent_process(); + +		/* Drain the ready queue of already scheduled jobs, before +		 * scheduling +		 * more. +		 */ +		if ((thread = thread_trim_head(&m->ready)) != NULL) +			return thread_run(m, thread, fetch); + +		/* To be fair to all kinds of threads, and avoid starvation, we +		 * need to be careful to consider all thread types for +		 * scheduling +		 * in each quanta. I.e. we should not return early from here on. +		 */ + +		/* Normal event are the next highest priority.  */ +		thread_process(&m->event); + +/* Structure copy.  */  #if !defined(HAVE_POLL_CALL) -      readfd = fd_copy_fd_set(m->handler.readfd); -      writefd = fd_copy_fd_set(m->handler.writefd); -      exceptfd = fd_copy_fd_set(m->handler.exceptfd); +		readfd = fd_copy_fd_set(m->handler.readfd); +		writefd = fd_copy_fd_set(m->handler.writefd); +		exceptfd = fd_copy_fd_set(m->handler.exceptfd);  #endif -       -      /* Calculate select wait timer if nothing else to do */ -      if (m->ready.count == 0) -        { -          timer_wait = thread_timer_wait (m->timer, &timer_val); -          timer_wait_bg = thread_timer_wait (m->background, &timer_val_bg); -           -          if (timer_wait_bg && -              (!timer_wait || (timercmp (timer_wait, timer_wait_bg, >)))) -            timer_wait = timer_wait_bg; -        } - -      if (timer_wait && timer_wait->tv_sec < 0) -        { -          timerclear(&timer_val); -          timer_wait = &timer_val; -        } - -      num = fd_select (m, FD_SETSIZE, &readfd, &writefd, &exceptfd, timer_wait); -       -      /* Signals should get quick treatment */ -      if (num < 0) -        { -          if (errno == EINTR) -            continue; /* signal received - process it */ -          zlog_warn ("select() error: %s", safe_strerror (errno)); -          return NULL; -        } - -      /* Check foreground timers.  Historically, they have had higher -         priority than I/O threads, so let's push them onto the ready -	 list in front of the I/O threads. */ -      monotime(&now); -      thread_timer_process (m->timer, &now); -       -      /* Got IO, process it */ -      if (num > 0) -        thread_process_fds (m, &readfd, &writefd, num); + +		/* Calculate select wait timer if nothing else to do */ +		if (m->ready.count == 0) { +			timer_wait = thread_timer_wait(m->timer, &timer_val); +			timer_wait_bg = +				thread_timer_wait(m->background, &timer_val_bg); + +			if (timer_wait_bg +			    && (!timer_wait +				|| (timercmp(timer_wait, timer_wait_bg, >)))) +				timer_wait = timer_wait_bg; +		} + +		if (timer_wait && timer_wait->tv_sec < 0) { +			timerclear(&timer_val); +			timer_wait = &timer_val; +		} + +		num = fd_select(m, FD_SETSIZE, &readfd, &writefd, &exceptfd, +				timer_wait); + +		/* Signals should get quick treatment */ +		if (num < 0) { +			if (errno == EINTR) +				continue; /* signal received - process it */ +			zlog_warn("select() error: %s", safe_strerror(errno)); +			return NULL; +		} + +		/* Check foreground timers.  Historically, they have had higher +		   priority than I/O threads, so let's push them onto the ready +		   list in front of the I/O threads. */ +		monotime(&now); +		thread_timer_process(m->timer, &now); + +		/* Got IO, process it */ +		if (num > 0) +			thread_process_fds(m, &readfd, &writefd, num);  #if 0        /* If any threads were made ready above (I/O or foreground timer), @@ -1217,21 +1141,21 @@ thread_fetch (struct thread_master *m, struct thread *fetch)          return thread_run (m, thread, fetch);  #endif -      /* Background timer/events, lowest priority */ -      thread_timer_process (m->background, &now); -       -      if ((thread = thread_trim_head (&m->ready)) != NULL) -        return thread_run (m, thread, fetch); -    } +		/* Background timer/events, lowest priority */ +		thread_timer_process(m->background, &now); + +		if ((thread = thread_trim_head(&m->ready)) != NULL) +			return thread_run(m, thread, fetch); +	}  } -unsigned long -thread_consumed_time (RUSAGE_T *now, RUSAGE_T *start, unsigned long *cputime) +unsigned long thread_consumed_time(RUSAGE_T *now, RUSAGE_T *start, +				   unsigned long *cputime)  { -  /* This is 'user + sys' time.  */ -  *cputime = timeval_elapsed (now->cpu.ru_utime, start->cpu.ru_utime) + -	     timeval_elapsed (now->cpu.ru_stime, start->cpu.ru_stime); -  return timeval_elapsed (now->real, start->real); +	/* This is 'user + sys' time.  */ +	*cputime = timeval_elapsed(now->cpu.ru_utime, start->cpu.ru_utime) +		   + timeval_elapsed(now->cpu.ru_stime, start->cpu.ru_stime); +	return timeval_elapsed(now->real, start->real);  }  /* We should aim to yield after yield milliseconds, which defaults @@ -1241,26 +1165,23 @@ thread_consumed_time (RUSAGE_T *now, RUSAGE_T *start, unsigned long *cputime)     contexts.  The things to consider are whether the thread may have     blocked (in which case wall time increases, but CPU time does not),     or whether the system is heavily loaded with other processes competing -   for CPU time.  On balance, wall clock time seems to make sense.  +   for CPU time.  On balance, wall clock time seems to make sense.     Plus it has the added benefit that gettimeofday should be faster     than calling getrusage. */ -int -thread_should_yield (struct thread *thread) +int thread_should_yield(struct thread *thread)  { -  return monotime_since(&thread->real, NULL) > (int64_t)thread->yield; +	return monotime_since(&thread->real, NULL) > (int64_t)thread->yield;  } -void -thread_set_yield_time (struct thread *thread, unsigned long yield_time) +void thread_set_yield_time(struct thread *thread, unsigned long yield_time)  { -  thread->yield = yield_time; +	thread->yield = yield_time;  } -void -thread_getrusage (RUSAGE_T *r) +void thread_getrusage(RUSAGE_T *r)  { -  monotime(&r->real); -  getrusage(RUSAGE_SELF, &(r->cpu)); +	monotime(&r->real); +	getrusage(RUSAGE_SELF, &(r->cpu));  }  struct thread *thread_current = NULL; @@ -1268,76 +1189,71 @@ struct thread *thread_current = NULL;  /* We check thread consumed time. If the system has getrusage, we'll     use that to get in-depth stats on the performance of the thread in addition     to wall clock time stats from gettimeofday. */ -void -thread_call (struct thread *thread) +void thread_call(struct thread *thread)  { -  unsigned long realtime, cputime; -  RUSAGE_T before, after; +	unsigned long realtime, cputime; +	RUSAGE_T before, after; -  GETRUSAGE (&before); -  thread->real = before.real; +	GETRUSAGE(&before); +	thread->real = before.real; -  thread_current = thread; -  (*thread->func) (thread); -  thread_current = NULL; +	thread_current = thread; +	(*thread->func)(thread); +	thread_current = NULL; -  GETRUSAGE (&after); +	GETRUSAGE(&after); -  realtime = thread_consumed_time (&after, &before, &cputime); -  thread->hist->real.total += realtime; -  if (thread->hist->real.max < realtime) -    thread->hist->real.max = realtime; -  thread->hist->cpu.total += cputime; -  if (thread->hist->cpu.max < cputime) -    thread->hist->cpu.max = cputime; +	realtime = thread_consumed_time(&after, &before, &cputime); +	thread->hist->real.total += realtime; +	if (thread->hist->real.max < realtime) +		thread->hist->real.max = realtime; +	thread->hist->cpu.total += cputime; +	if (thread->hist->cpu.max < cputime) +		thread->hist->cpu.max = cputime; -  ++(thread->hist->total_calls); -  thread->hist->types |= (1 << thread->add_type); +	++(thread->hist->total_calls); +	thread->hist->types |= (1 << thread->add_type);  #ifdef CONSUMED_TIME_CHECK -  if (realtime > CONSUMED_TIME_CHECK) -    { -      /* -       * We have a CPU Hog on our hands. -       * Whinge about it now, so we're aware this is yet another task -       * to fix. -       */ -      zlog_warn ("SLOW THREAD: task %s (%lx) ran for %lums (cpu time %lums)", -		 thread->funcname, -		 (unsigned long) thread->func, -		 realtime/1000, cputime/1000); -    } +	if (realtime > CONSUMED_TIME_CHECK) { +		/* +		 * We have a CPU Hog on our hands. +		 * Whinge about it now, so we're aware this is yet another task +		 * to fix. +		 */ +		zlog_warn( +			"SLOW THREAD: task %s (%lx) ran for %lums (cpu time %lums)", +			thread->funcname, (unsigned long)thread->func, +			realtime / 1000, cputime / 1000); +	}  #endif /* CONSUMED_TIME_CHECK */  }  /* Execute thread */ -struct thread * -funcname_thread_execute (struct thread_master *m, -                int (*func)(struct thread *),  -                void *arg, -                int val, -		debugargdef) +struct thread *funcname_thread_execute(struct thread_master *m, +				       int (*func)(struct thread *), void *arg, +				       int val, debugargdef)  { -  struct cpu_thread_history tmp; -  struct thread dummy; +	struct cpu_thread_history tmp; +	struct thread dummy; -  memset (&dummy, 0, sizeof (struct thread)); +	memset(&dummy, 0, sizeof(struct thread)); -  dummy.type = THREAD_EVENT; -  dummy.add_type = THREAD_EXECUTE; -  dummy.master = NULL; -  dummy.arg = arg; -  dummy.u.val = val; +	dummy.type = THREAD_EVENT; +	dummy.add_type = THREAD_EXECUTE; +	dummy.master = NULL; +	dummy.arg = arg; +	dummy.u.val = val; -  tmp.func = dummy.func = func; -  tmp.funcname = dummy.funcname = funcname; -  dummy.hist = hash_get (cpu_record, &tmp, -			 (void * (*) (void *))cpu_record_hash_alloc); +	tmp.func = dummy.func = func; +	tmp.funcname = dummy.funcname = funcname; +	dummy.hist = hash_get(cpu_record, &tmp, +			      (void *(*)(void *))cpu_record_hash_alloc); -  dummy.schedfrom = schedfrom; -  dummy.schedfrom_line = fromln; +	dummy.schedfrom = schedfrom; +	dummy.schedfrom_line = fromln; -  thread_call (&dummy); +	thread_call(&dummy); -  return NULL; +	return NULL;  } diff --git a/lib/thread.h b/lib/thread.h index 6cb7896e7d..bf89dcf0f6 100644 --- a/lib/thread.h +++ b/lib/thread.h @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_THREAD_H @@ -25,21 +25,19 @@  #include <zebra.h>  #include "monotime.h" -struct rusage_t -{ -  struct rusage cpu; -  struct timeval real; +struct rusage_t { +	struct rusage cpu; +	struct timeval real;  };  #define RUSAGE_T        struct rusage_t  #define GETRUSAGE(X) thread_getrusage(X)  /* Linked list of thread. */ -struct thread_list -{ -  struct thread *head; -  struct thread *tail; -  int count; +struct thread_list { +	struct thread *head; +	struct thread *tail; +	int count;  };  struct pqueue; @@ -52,78 +50,72 @@ typedef fd_set thread_fd_set;  #if defined(HAVE_POLL_CALL)  #include <poll.h> -struct fd_handler -{ -  /* number of pfd stored in pfds */ -  nfds_t pfdcount; -  /* number of pfd stored in pfds + number of snmp pfd */ -  nfds_t pfdcountsnmp; -  /* number of pfd that fit in the allocated space of pfds */ -  nfds_t pfdsize; -  struct pollfd *pfds; +struct fd_handler { +	/* number of pfd stored in pfds */ +	nfds_t pfdcount; +	/* number of pfd stored in pfds + number of snmp pfd */ +	nfds_t pfdcountsnmp; +	/* number of pfd that fit in the allocated space of pfds */ +	nfds_t pfdsize; +	struct pollfd *pfds;  };  #else -struct fd_handler -{ -  fd_set readfd; -  fd_set writefd; -  fd_set exceptfd; +struct fd_handler { +	fd_set readfd; +	fd_set writefd; +	fd_set exceptfd;  };  #endif  /* Master of the theads. */ -struct thread_master -{ -  struct thread **read; -  struct thread **write; -  struct pqueue *timer; -  struct thread_list event; -  struct thread_list ready; -  struct thread_list unuse; -  struct pqueue *background; -  int fd_limit; -  struct fd_handler handler; -  unsigned long alloc; +struct thread_master { +	struct thread **read; +	struct thread **write; +	struct pqueue *timer; +	struct thread_list event; +	struct thread_list ready; +	struct thread_list unuse; +	struct pqueue *background; +	int fd_limit; +	struct fd_handler handler; +	unsigned long alloc;  };  typedef unsigned char thread_type;  /* Thread itself. */ -struct thread -{ -  thread_type type;		/* thread type */ -  thread_type add_type;		/* thread type */ -  struct thread *next;		/* next pointer of the thread */    -  struct thread *prev;		/* previous pointer of the thread */ -  struct thread_master *master;	/* pointer to the struct thread_master. */ -  int (*func) (struct thread *); /* event function */ -  void *arg;			/* event argument */ -  union { -    int val;			/* second argument of the event. */ -    int fd;			/* file descriptor in case of read/write. */ -    struct timeval sands;	/* rest of time sands value. */ -  } u; -  int index;			/* used for timers to store position in queue */ -  struct timeval real; -  struct cpu_thread_history *hist; /* cache pointer to cpu_history */ -  unsigned long yield; /* yield time in us */ -  const char *funcname; -  const char *schedfrom; -  int schedfrom_line; +struct thread { +	thread_type type;	     /* thread type */ +	thread_type add_type;	 /* thread type */ +	struct thread *next;	  /* next pointer of the thread */ +	struct thread *prev;	  /* previous pointer of the thread */ +	struct thread_master *master; /* pointer to the struct thread_master. */ +	int (*func)(struct thread *); /* event function */ +	void *arg;		      /* event argument */ +	union { +		int val; /* second argument of the event. */ +		int fd;  /* file descriptor in case of read/write. */ +		struct timeval sands; /* rest of time sands value. */ +	} u; +	int index; /* used for timers to store position in queue */ +	struct timeval real; +	struct cpu_thread_history *hist; /* cache pointer to cpu_history */ +	unsigned long yield;		 /* yield time in us */ +	const char *funcname; +	const char *schedfrom; +	int schedfrom_line;  }; -struct cpu_thread_history  -{ -  int (*func)(struct thread *); -  unsigned int total_calls; -  unsigned int total_active; -  struct time_stats -  { -    unsigned long total, max; -  } real; -  struct time_stats cpu; -  thread_type types; -  const char *funcname; +struct cpu_thread_history { +	int (*func)(struct thread *); +	unsigned int total_calls; +	unsigned int total_active; +	struct time_stats { +		unsigned long total, max; +	} real; +	struct time_stats cpu; +	thread_type types; +	const char *funcname;  };  /* Struct timeval's tv_usec one second value.  */ @@ -147,38 +139,38 @@ struct cpu_thread_history  #define THREAD_FD(X)  ((X)->u.fd)  #define THREAD_VAL(X) ((X)->u.val) -#define THREAD_READ_ON(master,thread,func,arg,sock) \ -  do { \ -    if (! thread) \ -      thread = thread_add_read (master, func, arg, sock); \ -  } while (0) - -#define THREAD_WRITE_ON(master,thread,func,arg,sock) \ -  do { \ -    if (! thread) \ -      thread = thread_add_write (master, func, arg, sock); \ -  } while (0) - -#define THREAD_TIMER_ON(master,thread,func,arg,time) \ -  do { \ -    if (! thread) \ -      thread = thread_add_timer (master, func, arg, time); \ -  } while (0) - -#define THREAD_TIMER_MSEC_ON(master,thread,func,arg,time) \ -  do { \ -    if (! thread) \ -      thread = thread_add_timer_msec (master, func, arg, time); \ -  } while (0) - -#define THREAD_OFF(thread) \ -  do { \ -    if (thread) \ -      { \ -        thread_cancel (thread); \ -        thread = NULL; \ -      } \ -  } while (0) +#define THREAD_READ_ON(master, thread, func, arg, sock)                        \ +	do {                                                                   \ +		if (!thread)                                                   \ +			thread = thread_add_read(master, func, arg, sock);     \ +	} while (0) + +#define THREAD_WRITE_ON(master, thread, func, arg, sock)                       \ +	do {                                                                   \ +		if (!thread)                                                   \ +			thread = thread_add_write(master, func, arg, sock);    \ +	} while (0) + +#define THREAD_TIMER_ON(master, thread, func, arg, time)                       \ +	do {                                                                   \ +		if (!thread)                                                   \ +			thread = thread_add_timer(master, func, arg, time);    \ +	} while (0) + +#define THREAD_TIMER_MSEC_ON(master, thread, func, arg, time)                  \ +	do {                                                                   \ +		if (!thread)                                                   \ +			thread = thread_add_timer_msec(master, func, arg,      \ +						       time);                  \ +	} while (0) + +#define THREAD_OFF(thread)                                                     \ +	do {                                                                   \ +		if (thread) {                                                  \ +			thread_cancel(thread);                                 \ +			thread = NULL;                                         \ +		}                                                              \ +	} while (0)  #define THREAD_READ_OFF(thread)  THREAD_OFF(thread)  #define THREAD_WRITE_OFF(thread)  THREAD_OFF(thread) @@ -198,49 +190,49 @@ struct cpu_thread_history  #define thread_add_background(m,f,a,v) funcname_thread_add_background(m,f,a,v,#f,__FILE__,__LINE__)  /* Prototypes. */ -extern struct thread_master *thread_master_create (void); -extern void thread_master_free (struct thread_master *); +extern struct thread_master *thread_master_create(void); +extern void thread_master_free(struct thread_master *);  extern void thread_master_free_unused(struct thread_master *); -extern struct thread *funcname_thread_add_read_write (int dir, struct thread_master *, -				                int (*)(struct thread *), -				                void *, int, debugargdef); -extern struct thread *funcname_thread_add_timer (struct thread_master *, -				                 int (*)(struct thread *), -				                 void *, long, debugargdef); -extern struct thread *funcname_thread_add_timer_msec (struct thread_master *, -				                      int (*)(struct thread *), -				                      void *, long, debugargdef); -extern struct thread *funcname_thread_add_timer_tv (struct thread_master *, -				                    int (*)(struct thread *), -				                    void *, struct timeval *, -						    debugargdef); -extern struct thread *funcname_thread_add_event (struct thread_master *, -				                 int (*)(struct thread *), -				                 void *, int, debugargdef); -extern struct thread *funcname_thread_add_background (struct thread_master *, -                                               int (*func)(struct thread *), -				               void *arg, -				               long milliseconds_to_delay, -					       debugargdef); -extern struct thread *funcname_thread_execute (struct thread_master *, -                                               int (*)(struct thread *), -                                               void *, int, debugargdef); +extern struct thread *funcname_thread_add_read_write(int dir, +						     struct thread_master *, +						     int (*)(struct thread *), +						     void *, int, debugargdef); +extern struct thread *funcname_thread_add_timer(struct thread_master *, +						int (*)(struct thread *), +						void *, long, debugargdef); +extern struct thread *funcname_thread_add_timer_msec(struct thread_master *, +						     int (*)(struct thread *), +						     void *, long, debugargdef); +extern struct thread *funcname_thread_add_timer_tv(struct thread_master *, +						   int (*)(struct thread *), +						   void *, struct timeval *, +						   debugargdef); +extern struct thread *funcname_thread_add_event(struct thread_master *, +						int (*)(struct thread *), +						void *, int, debugargdef); +extern struct thread * +funcname_thread_add_background(struct thread_master *, +			       int (*func)(struct thread *), void *arg, +			       long milliseconds_to_delay, debugargdef); +extern struct thread *funcname_thread_execute(struct thread_master *, +					      int (*)(struct thread *), void *, +					      int, debugargdef);  #undef debugargdef -extern void thread_cancel (struct thread *); -extern unsigned int thread_cancel_event (struct thread_master *, void *); -extern struct thread *thread_fetch (struct thread_master *, struct thread *); -extern void thread_call (struct thread *); -extern unsigned long thread_timer_remain_second (struct thread *); -extern struct timeval thread_timer_remain(struct thread*); -extern int thread_should_yield (struct thread *); +extern void thread_cancel(struct thread *); +extern unsigned int thread_cancel_event(struct thread_master *, void *); +extern struct thread *thread_fetch(struct thread_master *, struct thread *); +extern void thread_call(struct thread *); +extern unsigned long thread_timer_remain_second(struct thread *); +extern struct timeval thread_timer_remain(struct thread *); +extern int thread_should_yield(struct thread *);  /* set yield time for thread */ -extern void thread_set_yield_time (struct thread *, unsigned long); +extern void thread_set_yield_time(struct thread *, unsigned long);  /* Internal libfrr exports */ -extern void thread_getrusage (RUSAGE_T *); -extern void thread_cmd_init (void); +extern void thread_getrusage(RUSAGE_T *); +extern void thread_cmd_init(void);  /* Returns elapsed real (wall clock) time. */  extern unsigned long thread_consumed_time(RUSAGE_T *after, RUSAGE_T *before, diff --git a/lib/vector.c b/lib/vector.c index e16fcf5315..e671c06d58 100644 --- a/lib/vector.c +++ b/lib/vector.c @@ -16,7 +16,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -24,175 +24,161 @@  #include "vector.h"  #include "memory.h" -DEFINE_MTYPE_STATIC(LIB, VECTOR,       "Vector") +DEFINE_MTYPE_STATIC(LIB, VECTOR, "Vector")  DEFINE_MTYPE_STATIC(LIB, VECTOR_INDEX, "Vector index")  /* Initialize vector : allocate memory and return vector. */ -vector -vector_init (unsigned int size) +vector vector_init(unsigned int size)  { -  vector v = XCALLOC (MTYPE_VECTOR, sizeof (struct _vector)); +	vector v = XCALLOC(MTYPE_VECTOR, sizeof(struct _vector)); -  /* allocate at least one slot */ -  if (size == 0) -    size = 1; +	/* allocate at least one slot */ +	if (size == 0) +		size = 1; -  v->alloced = size; -  v->active = 0; -  v->index = XCALLOC (MTYPE_VECTOR_INDEX, sizeof (void *) * size); -  return v; +	v->alloced = size; +	v->active = 0; +	v->index = XCALLOC(MTYPE_VECTOR_INDEX, sizeof(void *) * size); +	return v;  } -void -vector_free (vector v) +void vector_free(vector v)  { -  XFREE (MTYPE_VECTOR_INDEX, v->index); -  XFREE (MTYPE_VECTOR, v); +	XFREE(MTYPE_VECTOR_INDEX, v->index); +	XFREE(MTYPE_VECTOR, v);  } -vector -vector_copy (vector v) +vector vector_copy(vector v)  { -  unsigned int size; -  vector new = XCALLOC (MTYPE_VECTOR, sizeof (struct _vector)); +	unsigned int size; +	vector new = XCALLOC(MTYPE_VECTOR, sizeof(struct _vector)); -  new->active = v->active; -  new->alloced = v->alloced; +	new->active = v->active; +	new->alloced = v->alloced; -  size = sizeof (void *) * (v->alloced); -  new->index = XCALLOC (MTYPE_VECTOR_INDEX, size); -  memcpy (new->index, v->index, size); +	size = sizeof(void *) * (v->alloced); +	new->index = XCALLOC(MTYPE_VECTOR_INDEX, size); +	memcpy(new->index, v->index, size); -  return new; +	return new;  }  /* Check assigned index, and if it runs short double index pointer */ -void -vector_ensure (vector v, unsigned int num) +void vector_ensure(vector v, unsigned int num)  { -  if (v->alloced > num) -    return; - -  v->index = XREALLOC (MTYPE_VECTOR_INDEX,  -		       v->index, sizeof (void *) * (v->alloced * 2)); -  memset (&v->index[v->alloced], 0, sizeof (void *) * v->alloced); -  v->alloced *= 2; -   -  if (v->alloced <= num) -    vector_ensure (v, num); +	if (v->alloced > num) +		return; + +	v->index = XREALLOC(MTYPE_VECTOR_INDEX, v->index, +			    sizeof(void *) * (v->alloced * 2)); +	memset(&v->index[v->alloced], 0, sizeof(void *) * v->alloced); +	v->alloced *= 2; + +	if (v->alloced <= num) +		vector_ensure(v, num);  }  /* This function only returns next empty slot index.  It dose not mean     the slot's index memory is assigned, please call vector_ensure()     after calling this function. */ -int -vector_empty_slot (vector v) +int vector_empty_slot(vector v)  { -  unsigned int i; +	unsigned int i; -  if (v->active == 0) -    return 0; +	if (v->active == 0) +		return 0; -  for (i = 0; i < v->active; i++) -    if (v->index[i] == 0) -      return i; +	for (i = 0; i < v->active; i++) +		if (v->index[i] == 0) +			return i; -  return i; +	return i;  }  /* Set value to the smallest empty slot. */ -int -vector_set (vector v, void *val) +int vector_set(vector v, void *val)  { -  unsigned int i; +	unsigned int i; -  i = vector_empty_slot (v); -  vector_ensure (v, i); +	i = vector_empty_slot(v); +	vector_ensure(v, i); -  v->index[i] = val; +	v->index[i] = val; -  if (v->active <= i) -    v->active = i + 1; +	if (v->active <= i) +		v->active = i + 1; -  return i; +	return i;  }  /* Set value to specified index slot. */ -int -vector_set_index (vector v, unsigned int i, void *val) +int vector_set_index(vector v, unsigned int i, void *val)  { -  vector_ensure (v, i); +	vector_ensure(v, i); -  v->index[i] = val; +	v->index[i] = val; -  if (v->active <= i) -    v->active = i + 1; +	if (v->active <= i) +		v->active = i + 1; -  return i; +	return i;  }  /* Look up vector.  */ -void * -vector_lookup (vector v, unsigned int i) +void *vector_lookup(vector v, unsigned int i)  { -  if (i >= v->active) -    return NULL; -  return v->index[i]; +	if (i >= v->active) +		return NULL; +	return v->index[i];  }  /* Lookup vector, ensure it. */ -void * -vector_lookup_ensure (vector v, unsigned int i) +void *vector_lookup_ensure(vector v, unsigned int i)  { -  vector_ensure (v, i); -  return v->index[i]; +	vector_ensure(v, i); +	return v->index[i];  }  /* Unset value at specified index slot. */ -void -vector_unset (vector v, unsigned int i) +void vector_unset(vector v, unsigned int i)  { -  if (i >= v->alloced) -    return; +	if (i >= v->alloced) +		return; -  v->index[i] = NULL; +	v->index[i] = NULL; -  if (i + 1 == v->active)  -    { -      v->active--; -      while (i && v->index[--i] == NULL && v->active--)  -	;				/* Is this ugly ? */ -    } +	if (i + 1 == v->active) { +		v->active--; +		while (i && v->index[--i] == NULL && v->active--) +			; /* Is this ugly ? */ +	}  } -void -vector_unset_value (vector v, void *val) +void vector_unset_value(vector v, void *val)  { -  size_t i; - -  for (i = 0; i < v->active; i++) -    if (v->index[i] == val) -      { -        v->index[i] = NULL; -        break; -      } - -  if (i + 1 == v->active) -    do -      v->active--; -    while (i && v->index[--i] == NULL); +	size_t i; + +	for (i = 0; i < v->active; i++) +		if (v->index[i] == val) { +			v->index[i] = NULL; +			break; +		} + +	if (i + 1 == v->active) +		do +			v->active--; +		while (i && v->index[--i] == NULL);  }  /* Count the number of not emplty slot. */ -unsigned int -vector_count (vector v) +unsigned int vector_count(vector v)  { -  unsigned int i; -  unsigned count = 0; +	unsigned int i; +	unsigned count = 0; -  for (i = 0; i < v->active; i++)  -    if (v->index[i] != NULL) -      count++; +	for (i = 0; i < v->active; i++) +		if (v->index[i] != NULL) +			count++; -  return count; +	return count;  } diff --git a/lib/vector.h b/lib/vector.h index f57f28bbd0..bfda478223 100644 --- a/lib/vector.h +++ b/lib/vector.h @@ -17,7 +17,7 @@   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _ZEBRA_VECTOR_H @@ -26,11 +26,10 @@  #include "memory.h"  /* struct for vector */ -struct _vector  -{ -  unsigned int active;		/* number of active slots */ -  unsigned int alloced;		/* number of allocated slot */ -  void **index;			/* index to data */ +struct _vector { +	unsigned int active;  /* number of active slots */ +	unsigned int alloced; /* number of allocated slot */ +	void **index;	 /* index to data */  };  typedef struct _vector *vector; @@ -40,26 +39,26 @@ typedef struct _vector *vector;   array expression. */  /* Reference slot at given index, caller must ensure slot is active */  #define vector_slot(V,I)  ((V)->index[(I)]) -/* Number of active slots.  +/* Number of active slots.   * Note that this differs from vector_count() as it the count returned   * will include any empty slots   */  #define vector_active(V) ((V)->active)  /* Prototypes. */ -extern vector vector_init (unsigned int size); -extern void vector_ensure (vector v, unsigned int num); -extern int vector_empty_slot (vector v); -extern int vector_set (vector v, void *val); -extern int vector_set_index (vector v, unsigned int i, void *val); -extern void vector_unset (vector v, unsigned int i); -extern void vector_unset_value (vector v, void *val); +extern vector vector_init(unsigned int size); +extern void vector_ensure(vector v, unsigned int num); +extern int vector_empty_slot(vector v); +extern int vector_set(vector v, void *val); +extern int vector_set_index(vector v, unsigned int i, void *val); +extern void vector_unset(vector v, unsigned int i); +extern void vector_unset_value(vector v, void *val); -extern unsigned int vector_count (vector v); -extern void vector_free (vector v); -extern vector vector_copy (vector v); +extern unsigned int vector_count(vector v); +extern void vector_free(vector v); +extern vector vector_copy(vector v); -extern void *vector_lookup (vector, unsigned int); -extern void *vector_lookup_ensure (vector, unsigned int); +extern void *vector_lookup(vector, unsigned int); +extern void *vector_lookup_ensure(vector, unsigned int);  #endif /* _ZEBRA_VECTOR_H */ @@ -30,19 +30,19 @@  #include "memory.h"  #include "command.h" -DEFINE_MTYPE_STATIC(LIB, VRF,        "VRF") +DEFINE_MTYPE_STATIC(LIB, VRF, "VRF")  DEFINE_MTYPE_STATIC(LIB, VRF_BITMAP, "VRF bit-map")  DEFINE_QOBJ_TYPE(vrf) -static __inline int vrf_id_compare (struct vrf *, struct vrf *); -static __inline int vrf_name_compare (struct vrf *, struct vrf *); +static __inline int vrf_id_compare(struct vrf *, struct vrf *); +static __inline int vrf_name_compare(struct vrf *, struct vrf *); -RB_GENERATE (vrf_id_head, vrf, id_entry, vrf_id_compare) -RB_GENERATE (vrf_name_head, vrf, name_entry, vrf_name_compare) +RB_GENERATE(vrf_id_head, vrf, id_entry, vrf_id_compare) +RB_GENERATE(vrf_name_head, vrf, name_entry, vrf_name_compare) -struct vrf_id_head vrfs_by_id = RB_INITIALIZER (&vrfs_by_id); -struct vrf_name_head vrfs_by_name = RB_INITIALIZER (&vrfs_by_name); +struct vrf_id_head vrfs_by_id = RB_INITIALIZER(&vrfs_by_id); +struct vrf_name_head vrfs_by_name = RB_INITIALIZER(&vrfs_by_name);  /*   * Turn on/off debug code @@ -51,36 +51,34 @@ struct vrf_name_head vrfs_by_name = RB_INITIALIZER (&vrfs_by_name);  int debug_vrf = 0;  /* Holding VRF hooks  */ -struct vrf_master -{ -  int (*vrf_new_hook) (struct vrf *); -  int (*vrf_delete_hook) (struct vrf *); -  int (*vrf_enable_hook) (struct vrf *); -  int (*vrf_disable_hook) (struct vrf *); -} vrf_master = {0,}; +struct vrf_master { +	int (*vrf_new_hook)(struct vrf *); +	int (*vrf_delete_hook)(struct vrf *); +	int (*vrf_enable_hook)(struct vrf *); +	int (*vrf_disable_hook)(struct vrf *); +} vrf_master = { +	0, +}; -static int vrf_is_enabled (struct vrf *vrf); -static void vrf_disable (struct vrf *vrf); +static int vrf_is_enabled(struct vrf *vrf); +static void vrf_disable(struct vrf *vrf);  /* VRF list existance check by name. */ -struct vrf * -vrf_lookup_by_name (const char *name) +struct vrf *vrf_lookup_by_name(const char *name)  { -  struct vrf vrf; -  strlcpy (vrf.name, name, sizeof (vrf.name)); -  return (RB_FIND (vrf_name_head, &vrfs_by_name, &vrf)); +	struct vrf vrf; +	strlcpy(vrf.name, name, sizeof(vrf.name)); +	return (RB_FIND(vrf_name_head, &vrfs_by_name, &vrf));  } -static __inline int -vrf_id_compare (struct vrf *a, struct vrf *b) +static __inline int vrf_id_compare(struct vrf *a, struct vrf *b)  { -  return (a->vrf_id - b->vrf_id); +	return (a->vrf_id - b->vrf_id);  } -static int -vrf_name_compare (struct vrf *a, struct vrf *b) +static int vrf_name_compare(struct vrf *a, struct vrf *b)  { -  return strcmp (a->name, b->name); +	return strcmp(a->name, b->name);  }  /* Get a VRF. If not found, create one. @@ -90,104 +88,95 @@ vrf_name_compare (struct vrf *a, struct vrf *b)   * Description: Please note that this routine can be called with just the name   * and 0 vrf-id   */ -struct vrf * -vrf_get (vrf_id_t vrf_id, const char *name) -{ -  struct vrf *vrf = NULL; -  int new = 0; - -  if (debug_vrf) -    zlog_debug ("VRF_GET: %s(%d)", name, vrf_id); - -  /* Nothing to see, move along here */ -  if (!name && vrf_id == VRF_UNKNOWN) -    return NULL; - -  /* Try to find VRF both by ID and name */ -  if (vrf_id != VRF_UNKNOWN) -    vrf = vrf_lookup_by_id (vrf_id); -  if (! vrf && name) -    vrf = vrf_lookup_by_name (name); - -  if (vrf == NULL) -    { -      vrf = XCALLOC (MTYPE_VRF, sizeof (struct vrf)); -      vrf->vrf_id = VRF_UNKNOWN; -      if_init (&vrf->iflist); -      QOBJ_REG (vrf, vrf); -      new = 1; - -      if (debug_vrf) -	zlog_debug ("VRF(%u) %s is created.", -		    vrf_id, (name) ? name : "(NULL)"); -    } - -  /* Set identifier */ -  if (vrf_id != VRF_UNKNOWN && vrf->vrf_id == VRF_UNKNOWN) -    { -      vrf->vrf_id = vrf_id; -      RB_INSERT (vrf_id_head, &vrfs_by_id, vrf); -    } - -  /* Set name */ -  if (name && vrf->name[0] != '\0' && strcmp (name, vrf->name)) -    { -      RB_REMOVE (vrf_name_head, &vrfs_by_name, vrf); -      strlcpy (vrf->name, name, sizeof (vrf->name)); -      RB_INSERT (vrf_name_head, &vrfs_by_name, vrf); -    } -  else if (name && vrf->name[0] == '\0') -    { -      strlcpy (vrf->name, name, sizeof (vrf->name)); -      RB_INSERT (vrf_name_head, &vrfs_by_name, vrf); -    } - -  if (new && vrf_master.vrf_new_hook) -    (*vrf_master.vrf_new_hook) (vrf); - -  return vrf; +struct vrf *vrf_get(vrf_id_t vrf_id, const char *name) +{ +	struct vrf *vrf = NULL; +	int new = 0; + +	if (debug_vrf) +		zlog_debug("VRF_GET: %s(%d)", name, vrf_id); + +	/* Nothing to see, move along here */ +	if (!name && vrf_id == VRF_UNKNOWN) +		return NULL; + +	/* Try to find VRF both by ID and name */ +	if (vrf_id != VRF_UNKNOWN) +		vrf = vrf_lookup_by_id(vrf_id); +	if (!vrf && name) +		vrf = vrf_lookup_by_name(name); + +	if (vrf == NULL) { +		vrf = XCALLOC(MTYPE_VRF, sizeof(struct vrf)); +		vrf->vrf_id = VRF_UNKNOWN; +		if_init(&vrf->iflist); +		QOBJ_REG(vrf, vrf); +		new = 1; + +		if (debug_vrf) +			zlog_debug("VRF(%u) %s is created.", vrf_id, +				   (name) ? name : "(NULL)"); +	} + +	/* Set identifier */ +	if (vrf_id != VRF_UNKNOWN && vrf->vrf_id == VRF_UNKNOWN) { +		vrf->vrf_id = vrf_id; +		RB_INSERT(vrf_id_head, &vrfs_by_id, vrf); +	} + +	/* Set name */ +	if (name && vrf->name[0] != '\0' && strcmp(name, vrf->name)) { +		RB_REMOVE(vrf_name_head, &vrfs_by_name, vrf); +		strlcpy(vrf->name, name, sizeof(vrf->name)); +		RB_INSERT(vrf_name_head, &vrfs_by_name, vrf); +	} else if (name && vrf->name[0] == '\0') { +		strlcpy(vrf->name, name, sizeof(vrf->name)); +		RB_INSERT(vrf_name_head, &vrfs_by_name, vrf); +	} + +	if (new &&vrf_master.vrf_new_hook) +		(*vrf_master.vrf_new_hook)(vrf); + +	return vrf;  }  /* Delete a VRF. This is called in vrf_terminate(). */ -void -vrf_delete (struct vrf *vrf) +void vrf_delete(struct vrf *vrf)  { -  if (debug_vrf) -    zlog_debug ("VRF %u is to be deleted.", vrf->vrf_id); +	if (debug_vrf) +		zlog_debug("VRF %u is to be deleted.", vrf->vrf_id); -  if (vrf_is_enabled (vrf)) -    vrf_disable (vrf); +	if (vrf_is_enabled(vrf)) +		vrf_disable(vrf); -  if (vrf_master.vrf_delete_hook) -    (*vrf_master.vrf_delete_hook) (vrf); +	if (vrf_master.vrf_delete_hook) +		(*vrf_master.vrf_delete_hook)(vrf); -  QOBJ_UNREG (vrf); -  if_terminate (&vrf->iflist); +	QOBJ_UNREG(vrf); +	if_terminate(&vrf->iflist); -  if (vrf->vrf_id != VRF_UNKNOWN) -    RB_REMOVE (vrf_id_head, &vrfs_by_id, vrf); -  if (vrf->name[0] != '\0') -    RB_REMOVE (vrf_name_head, &vrfs_by_name, vrf); +	if (vrf->vrf_id != VRF_UNKNOWN) +		RB_REMOVE(vrf_id_head, &vrfs_by_id, vrf); +	if (vrf->name[0] != '\0') +		RB_REMOVE(vrf_name_head, &vrfs_by_name, vrf); -  XFREE (MTYPE_VRF, vrf); +	XFREE(MTYPE_VRF, vrf);  }  /* Look up a VRF by identifier. */ -struct vrf * -vrf_lookup_by_id (vrf_id_t vrf_id) +struct vrf *vrf_lookup_by_id(vrf_id_t vrf_id)  { -  struct vrf vrf; -  vrf.vrf_id = vrf_id; -  return (RB_FIND (vrf_id_head, &vrfs_by_id, &vrf)); +	struct vrf vrf; +	vrf.vrf_id = vrf_id; +	return (RB_FIND(vrf_id_head, &vrfs_by_id, &vrf));  }  /*   * Check whether the VRF is enabled.   */ -static int -vrf_is_enabled (struct vrf *vrf) +static int vrf_is_enabled(struct vrf *vrf)  { -  return vrf && CHECK_FLAG (vrf->status, VRF_ACTIVE); +	return vrf && CHECK_FLAG(vrf->status, VRF_ACTIVE);  }  /* @@ -197,21 +186,20 @@ vrf_is_enabled (struct vrf *vrf)   *   * RETURN: 1 - enabled successfully; otherwise, 0.   */ -int -vrf_enable (struct vrf *vrf) +int vrf_enable(struct vrf *vrf)  { -  if (vrf_is_enabled (vrf)) -    return 1; +	if (vrf_is_enabled(vrf)) +		return 1; -  if (debug_vrf) -    zlog_debug ("VRF %u is enabled.", vrf->vrf_id); +	if (debug_vrf) +		zlog_debug("VRF %u is enabled.", vrf->vrf_id); -  SET_FLAG (vrf->status, VRF_ACTIVE); +	SET_FLAG(vrf->status, VRF_ACTIVE); -  if (vrf_master.vrf_enable_hook) -    (*vrf_master.vrf_enable_hook) (vrf); +	if (vrf_master.vrf_enable_hook) +		(*vrf_master.vrf_enable_hook)(vrf); -  return 1; +	return 1;  }  /* @@ -219,112 +207,104 @@ vrf_enable (struct vrf *vrf)   * The VRF_DELETE_HOOK callback will be called to inform   * that they must release the resources in the VRF.   */ -static void -vrf_disable (struct vrf *vrf) +static void vrf_disable(struct vrf *vrf)  { -  if (! vrf_is_enabled (vrf)) -    return; +	if (!vrf_is_enabled(vrf)) +		return; -  UNSET_FLAG (vrf->status, VRF_ACTIVE); +	UNSET_FLAG(vrf->status, VRF_ACTIVE); -  if (debug_vrf) -    zlog_debug ("VRF %u is to be disabled.", vrf->vrf_id); +	if (debug_vrf) +		zlog_debug("VRF %u is to be disabled.", vrf->vrf_id); -  /* Till now, nothing to be done for the default VRF. */ -  //Pending: see why this statement. +	/* Till now, nothing to be done for the default VRF. */ +	// Pending: see why this statement. -  if (vrf_master.vrf_disable_hook) -    (*vrf_master.vrf_disable_hook) (vrf); +	if (vrf_master.vrf_disable_hook) +		(*vrf_master.vrf_disable_hook)(vrf);  }  /* Add a VRF hook. Please add hooks before calling vrf_init(). */ -void -vrf_add_hook (int type, int (*func)(struct vrf *)) +void vrf_add_hook(int type, int (*func)(struct vrf *))  { -  if (debug_vrf) -    zlog_debug ("%s: Add Hook %d to function %p",  __PRETTY_FUNCTION__, -		type, func); +	if (debug_vrf) +		zlog_debug("%s: Add Hook %d to function %p", +			   __PRETTY_FUNCTION__, type, func); -  switch (type) { -  case VRF_NEW_HOOK: -    vrf_master.vrf_new_hook = func; -    break; -  case VRF_DELETE_HOOK: -    vrf_master.vrf_delete_hook = func; -    break; -  case VRF_ENABLE_HOOK: -    vrf_master.vrf_enable_hook = func; -    break; -  case VRF_DISABLE_HOOK: -    vrf_master.vrf_disable_hook = func; -    break; -  default: -    break; -  } +	switch (type) { +	case VRF_NEW_HOOK: +		vrf_master.vrf_new_hook = func; +		break; +	case VRF_DELETE_HOOK: +		vrf_master.vrf_delete_hook = func; +		break; +	case VRF_ENABLE_HOOK: +		vrf_master.vrf_enable_hook = func; +		break; +	case VRF_DISABLE_HOOK: +		vrf_master.vrf_disable_hook = func; +		break; +	default: +		break; +	}  } -vrf_id_t -vrf_name_to_id (const char *name) +vrf_id_t vrf_name_to_id(const char *name)  { -  struct vrf *vrf; -  vrf_id_t vrf_id = VRF_DEFAULT; //Pending: need a way to return invalid id/ routine not used. +	struct vrf *vrf; +	vrf_id_t vrf_id = VRF_DEFAULT; // Pending: need a way to return invalid +				       // id/ routine not used. -  vrf = vrf_lookup_by_name (name); -  if (vrf) -    vrf_id = vrf->vrf_id; +	vrf = vrf_lookup_by_name(name); +	if (vrf) +		vrf_id = vrf->vrf_id; -  return vrf_id; +	return vrf_id;  }  /* Get the data pointer of the specified VRF. If not found, create one. */ -void * -vrf_info_get (vrf_id_t vrf_id) +void *vrf_info_get(vrf_id_t vrf_id)  { -  struct vrf *vrf = vrf_get (vrf_id, NULL); -  return vrf->info; +	struct vrf *vrf = vrf_get(vrf_id, NULL); +	return vrf->info;  }  /* Look up the data pointer of the specified VRF. */ -void * -vrf_info_lookup (vrf_id_t vrf_id) +void *vrf_info_lookup(vrf_id_t vrf_id)  { -  struct vrf *vrf = vrf_lookup_by_id (vrf_id); -  return vrf ? vrf->info : NULL; +	struct vrf *vrf = vrf_lookup_by_id(vrf_id); +	return vrf ? vrf->info : NULL;  }  /* Look up the interface list in a VRF. */ -struct list * -vrf_iflist (vrf_id_t vrf_id) +struct list *vrf_iflist(vrf_id_t vrf_id)  { -   struct vrf * vrf = vrf_lookup_by_id (vrf_id); -   return vrf ? vrf->iflist : NULL; +	struct vrf *vrf = vrf_lookup_by_id(vrf_id); +	return vrf ? vrf->iflist : NULL;  }  /* Get the interface list of the specified VRF. Create one if not find. */ -struct list * -vrf_iflist_get (vrf_id_t vrf_id) +struct list *vrf_iflist_get(vrf_id_t vrf_id)  { -   struct vrf * vrf = vrf_get (vrf_id, NULL); -   return vrf->iflist; +	struct vrf *vrf = vrf_get(vrf_id, NULL); +	return vrf->iflist;  }  /* Create the interface list for the specified VRF, if needed. */ -void -vrf_iflist_create (vrf_id_t vrf_id) +void vrf_iflist_create(vrf_id_t vrf_id)  { -   struct vrf * vrf = vrf_lookup_by_id (vrf_id); -   if (vrf && !vrf->iflist) -     if_init (&vrf->iflist); +	struct vrf *vrf = vrf_lookup_by_id(vrf_id); +	if (vrf && !vrf->iflist) +		if_init(&vrf->iflist);  }  /* Free the interface list of the specified VRF. */ -void -vrf_iflist_terminate (vrf_id_t vrf_id) +void vrf_iflist_terminate(vrf_id_t vrf_id)  { -   struct vrf * vrf = vrf_lookup_by_id (vrf_id); -   if (vrf && vrf->iflist) -     if_terminate (&vrf->iflist); +	struct vrf *vrf = vrf_lookup_by_id(vrf_id); +	if (vrf && vrf->iflist) +		if_terminate(&vrf->iflist);  }  /* @@ -332,145 +312,134 @@ vrf_iflist_terminate (vrf_id_t vrf_id)   */  #define VRF_BITMAP_NUM_OF_GROUPS            8 -#define VRF_BITMAP_NUM_OF_BITS_IN_GROUP \ -    (UINT16_MAX / VRF_BITMAP_NUM_OF_GROUPS) -#define VRF_BITMAP_NUM_OF_BYTES_IN_GROUP \ -    (VRF_BITMAP_NUM_OF_BITS_IN_GROUP / CHAR_BIT + 1) /* +1 for ensure */ +#define VRF_BITMAP_NUM_OF_BITS_IN_GROUP (UINT16_MAX / VRF_BITMAP_NUM_OF_GROUPS) +#define VRF_BITMAP_NUM_OF_BYTES_IN_GROUP                                       \ +	(VRF_BITMAP_NUM_OF_BITS_IN_GROUP / CHAR_BIT + 1) /* +1 for ensure */ -#define VRF_BITMAP_GROUP(_id) \ -    ((_id) / VRF_BITMAP_NUM_OF_BITS_IN_GROUP) -#define VRF_BITMAP_BIT_OFFSET(_id) \ -    ((_id) % VRF_BITMAP_NUM_OF_BITS_IN_GROUP) +#define VRF_BITMAP_GROUP(_id) ((_id) / VRF_BITMAP_NUM_OF_BITS_IN_GROUP) +#define VRF_BITMAP_BIT_OFFSET(_id) ((_id) % VRF_BITMAP_NUM_OF_BITS_IN_GROUP) -#define VRF_BITMAP_INDEX_IN_GROUP(_bit_offset) \ -    ((_bit_offset) / CHAR_BIT) -#define VRF_BITMAP_FLAG(_bit_offset) \ -    (((u_char)1) << ((_bit_offset) % CHAR_BIT)) +#define VRF_BITMAP_INDEX_IN_GROUP(_bit_offset) ((_bit_offset) / CHAR_BIT) +#define VRF_BITMAP_FLAG(_bit_offset) (((u_char)1) << ((_bit_offset) % CHAR_BIT)) -struct vrf_bitmap -{ -  u_char *groups[VRF_BITMAP_NUM_OF_GROUPS]; +struct vrf_bitmap { +	u_char *groups[VRF_BITMAP_NUM_OF_GROUPS];  }; -vrf_bitmap_t -vrf_bitmap_init (void) +vrf_bitmap_t vrf_bitmap_init(void)  { -  return (vrf_bitmap_t) XCALLOC (MTYPE_VRF_BITMAP, sizeof (struct vrf_bitmap)); +	return (vrf_bitmap_t)XCALLOC(MTYPE_VRF_BITMAP, +				     sizeof(struct vrf_bitmap));  } -void -vrf_bitmap_free (vrf_bitmap_t bmap) +void vrf_bitmap_free(vrf_bitmap_t bmap)  { -  struct vrf_bitmap *bm = (struct vrf_bitmap *) bmap; -  int i; +	struct vrf_bitmap *bm = (struct vrf_bitmap *)bmap; +	int i; -  if (bmap == VRF_BITMAP_NULL) -    return; +	if (bmap == VRF_BITMAP_NULL) +		return; -  for (i = 0; i < VRF_BITMAP_NUM_OF_GROUPS; i++) -    if (bm->groups[i]) -      XFREE (MTYPE_VRF_BITMAP, bm->groups[i]); +	for (i = 0; i < VRF_BITMAP_NUM_OF_GROUPS; i++) +		if (bm->groups[i]) +			XFREE(MTYPE_VRF_BITMAP, bm->groups[i]); -  XFREE (MTYPE_VRF_BITMAP, bm); +	XFREE(MTYPE_VRF_BITMAP, bm);  } -void -vrf_bitmap_set (vrf_bitmap_t bmap, vrf_id_t vrf_id) +void vrf_bitmap_set(vrf_bitmap_t bmap, vrf_id_t vrf_id)  { -  struct vrf_bitmap *bm = (struct vrf_bitmap *) bmap; -  u_char group = VRF_BITMAP_GROUP (vrf_id); -  u_char offset = VRF_BITMAP_BIT_OFFSET (vrf_id); +	struct vrf_bitmap *bm = (struct vrf_bitmap *)bmap; +	u_char group = VRF_BITMAP_GROUP(vrf_id); +	u_char offset = VRF_BITMAP_BIT_OFFSET(vrf_id); -  if (bmap == VRF_BITMAP_NULL || vrf_id == VRF_UNKNOWN) -    return; +	if (bmap == VRF_BITMAP_NULL || vrf_id == VRF_UNKNOWN) +		return; -  if (bm->groups[group] == NULL) -    bm->groups[group] = XCALLOC (MTYPE_VRF_BITMAP, -                                 VRF_BITMAP_NUM_OF_BYTES_IN_GROUP); +	if (bm->groups[group] == NULL) +		bm->groups[group] = XCALLOC(MTYPE_VRF_BITMAP, +					    VRF_BITMAP_NUM_OF_BYTES_IN_GROUP); -  SET_FLAG (bm->groups[group][VRF_BITMAP_INDEX_IN_GROUP (offset)], -            VRF_BITMAP_FLAG (offset)); +	SET_FLAG(bm->groups[group][VRF_BITMAP_INDEX_IN_GROUP(offset)], +		 VRF_BITMAP_FLAG(offset));  } -void -vrf_bitmap_unset (vrf_bitmap_t bmap, vrf_id_t vrf_id) +void vrf_bitmap_unset(vrf_bitmap_t bmap, vrf_id_t vrf_id)  { -  struct vrf_bitmap *bm = (struct vrf_bitmap *) bmap; -  u_char group = VRF_BITMAP_GROUP (vrf_id); -  u_char offset = VRF_BITMAP_BIT_OFFSET (vrf_id); +	struct vrf_bitmap *bm = (struct vrf_bitmap *)bmap; +	u_char group = VRF_BITMAP_GROUP(vrf_id); +	u_char offset = VRF_BITMAP_BIT_OFFSET(vrf_id); -  if (bmap == VRF_BITMAP_NULL || vrf_id == VRF_UNKNOWN || -      bm->groups[group] == NULL) -    return; +	if (bmap == VRF_BITMAP_NULL || vrf_id == VRF_UNKNOWN +	    || bm->groups[group] == NULL) +		return; -  UNSET_FLAG (bm->groups[group][VRF_BITMAP_INDEX_IN_GROUP (offset)], -              VRF_BITMAP_FLAG (offset)); +	UNSET_FLAG(bm->groups[group][VRF_BITMAP_INDEX_IN_GROUP(offset)], +		   VRF_BITMAP_FLAG(offset));  } -int -vrf_bitmap_check (vrf_bitmap_t bmap, vrf_id_t vrf_id) +int vrf_bitmap_check(vrf_bitmap_t bmap, vrf_id_t vrf_id)  { -  struct vrf_bitmap *bm = (struct vrf_bitmap *) bmap; -  u_char group = VRF_BITMAP_GROUP (vrf_id); -  u_char offset = VRF_BITMAP_BIT_OFFSET (vrf_id); +	struct vrf_bitmap *bm = (struct vrf_bitmap *)bmap; +	u_char group = VRF_BITMAP_GROUP(vrf_id); +	u_char offset = VRF_BITMAP_BIT_OFFSET(vrf_id); -  if (bmap == VRF_BITMAP_NULL || vrf_id == VRF_UNKNOWN || -      bm->groups[group] == NULL) -    return 0; +	if (bmap == VRF_BITMAP_NULL || vrf_id == VRF_UNKNOWN +	    || bm->groups[group] == NULL) +		return 0; -  return CHECK_FLAG (bm->groups[group][VRF_BITMAP_INDEX_IN_GROUP (offset)], -                     VRF_BITMAP_FLAG (offset)) ? 1 : 0; +	return CHECK_FLAG(bm->groups[group][VRF_BITMAP_INDEX_IN_GROUP(offset)], +			  VRF_BITMAP_FLAG(offset)) +		       ? 1 +		       : 0;  }  /* Initialize VRF module. */ -void -vrf_init (void) +void vrf_init(void)  { -  struct vrf *default_vrf; +	struct vrf *default_vrf; -  if (debug_vrf) -    zlog_debug ("%s: Initializing VRF subsystem", __PRETTY_FUNCTION__); +	if (debug_vrf) +		zlog_debug("%s: Initializing VRF subsystem", +			   __PRETTY_FUNCTION__); -  /* The default VRF always exists. */ -  default_vrf = vrf_get (VRF_DEFAULT, VRF_DEFAULT_NAME); -  if (!default_vrf) -    { -      zlog_err ("vrf_init: failed to create the default VRF!"); -      exit (1); -    } +	/* The default VRF always exists. */ +	default_vrf = vrf_get(VRF_DEFAULT, VRF_DEFAULT_NAME); +	if (!default_vrf) { +		zlog_err("vrf_init: failed to create the default VRF!"); +		exit(1); +	} -  /* Enable the default VRF. */ -  if (!vrf_enable (default_vrf)) -    { -      zlog_err ("vrf_init: failed to enable the default VRF!"); -      exit (1); -    } +	/* Enable the default VRF. */ +	if (!vrf_enable(default_vrf)) { +		zlog_err("vrf_init: failed to enable the default VRF!"); +		exit(1); +	}  }  /* Terminate VRF module. */ -void -vrf_terminate (void) +void vrf_terminate(void)  { -  struct vrf *vrf; +	struct vrf *vrf; -  if (debug_vrf) -    zlog_debug ("%s: Shutting down vrf subsystem", __PRETTY_FUNCTION__); +	if (debug_vrf) +		zlog_debug("%s: Shutting down vrf subsystem", +			   __PRETTY_FUNCTION__); -  while ((vrf = RB_ROOT (&vrfs_by_id)) != NULL) -    vrf_delete (vrf); -  while ((vrf = RB_ROOT (&vrfs_by_name)) != NULL) -    vrf_delete (vrf); +	while ((vrf = RB_ROOT(&vrfs_by_id)) != NULL) +		vrf_delete(vrf); +	while ((vrf = RB_ROOT(&vrfs_by_name)) != NULL) +		vrf_delete(vrf);  }  /* Create a socket for the VRF. */ -int -vrf_socket (int domain, int type, int protocol, vrf_id_t vrf_id) +int vrf_socket(int domain, int type, int protocol, vrf_id_t vrf_id)  { -  int ret = -1; +	int ret = -1; -  ret = socket (domain, type, protocol); +	ret = socket(domain, type, protocol); -  return ret; +	return ret;  }  /* vrf CLI commands */ @@ -480,23 +449,23 @@ DEFUN_NOSH (vrf,         "Select a VRF to configure\n"         "VRF's name\n")  { -  int idx_name = 1; -  const char *vrfname = argv[idx_name]->arg; -  struct vrf *vrfp; +	int idx_name = 1; +	const char *vrfname = argv[idx_name]->arg; +	struct vrf *vrfp; -  if (strlen(vrfname) > VRF_NAMSIZ) -    { -      vty_out (vty, "%% VRF name %s is invalid: length exceeds " -                    "%d characters%s", -               vrfname, VRF_NAMSIZ, VTY_NEWLINE); -      return CMD_WARNING; -    } +	if (strlen(vrfname) > VRF_NAMSIZ) { +		vty_out(vty, +			"%% VRF name %s is invalid: length exceeds " +			"%d characters%s", +			vrfname, VRF_NAMSIZ, VTY_NEWLINE); +		return CMD_WARNING; +	} -  vrfp = vrf_get (VRF_UNKNOWN, vrfname); +	vrfp = vrf_get(VRF_UNKNOWN, vrfname); -  VTY_PUSH_CONTEXT (VRF_NODE, vrfp); +	VTY_PUSH_CONTEXT(VRF_NODE, vrfp); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN_NOSH (no_vrf, @@ -506,37 +475,31 @@ DEFUN_NOSH (no_vrf,             "Delete a pseudo VRF's configuration\n"             "VRF's name\n")  { -  const char *vrfname = argv[2]->arg; +	const char *vrfname = argv[2]->arg; -  struct vrf *vrfp; +	struct vrf *vrfp; -  vrfp = vrf_lookup_by_name (vrfname); +	vrfp = vrf_lookup_by_name(vrfname); -  if (vrfp == NULL) -    { -      vty_out (vty, "%% VRF %s does not exist%s", vrfname, VTY_NEWLINE); -      return CMD_WARNING; -    } +	if (vrfp == NULL) { +		vty_out(vty, "%% VRF %s does not exist%s", vrfname, +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  if (CHECK_FLAG (vrfp->status, VRF_ACTIVE)) -    { -      vty_out (vty, "%% Only inactive VRFs can be deleted%s", -              VTY_NEWLINE); -      return CMD_WARNING; -    } +	if (CHECK_FLAG(vrfp->status, VRF_ACTIVE)) { +		vty_out(vty, "%% Only inactive VRFs can be deleted%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  vrf_delete(vrfp); +	vrf_delete(vrfp); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  } -struct cmd_node vrf_node = -{ -  VRF_NODE, -  "%s(config-vrf)# ", -  1 -}; +struct cmd_node vrf_node = {VRF_NODE, "%s(config-vrf)# ", 1};  /*   * Debug CLI for vrf's @@ -547,9 +510,9 @@ DEFUN (vrf_debug,        DEBUG_STR        "VRF Debugging\n")  { -  debug_vrf = 1; +	debug_vrf = 1; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (no_vrf_debug, @@ -559,43 +522,35 @@ DEFUN (no_vrf_debug,        DEBUG_STR        "VRF Debugging\n")  { -  debug_vrf = 0; +	debug_vrf = 0; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  } -static int -vrf_write_host (struct vty *vty) +static int vrf_write_host(struct vty *vty)  { -  if (debug_vrf) -    vty_out (vty, "debug vrf%s", VTY_NEWLINE); +	if (debug_vrf) +		vty_out(vty, "debug vrf%s", VTY_NEWLINE); -  return 1; +	return 1;  } -static struct cmd_node vrf_debug_node = -{ -  VRF_DEBUG_NODE, -  "", -  1 -}; +static struct cmd_node vrf_debug_node = {VRF_DEBUG_NODE, "", 1}; -void -vrf_install_commands (void) +void vrf_install_commands(void)  { -  install_node (&vrf_debug_node, vrf_write_host); +	install_node(&vrf_debug_node, vrf_write_host); -  install_element (CONFIG_NODE, &vrf_debug_cmd); -  install_element (ENABLE_NODE, &vrf_debug_cmd); -  install_element (CONFIG_NODE, &no_vrf_debug_cmd); -  install_element (ENABLE_NODE, &no_vrf_debug_cmd); +	install_element(CONFIG_NODE, &vrf_debug_cmd); +	install_element(ENABLE_NODE, &vrf_debug_cmd); +	install_element(CONFIG_NODE, &no_vrf_debug_cmd); +	install_element(ENABLE_NODE, &no_vrf_debug_cmd);  } -void -vrf_cmd_init (int (*writefunc)(struct vty *vty)) +void vrf_cmd_init(int (*writefunc)(struct vty *vty))  { -  install_element (CONFIG_NODE, &vrf_cmd); -  install_element (CONFIG_NODE, &no_vrf_cmd); -  install_node (&vrf_node, writefunc); -  install_default (VRF_NODE); +	install_element(CONFIG_NODE, &vrf_cmd); +	install_element(CONFIG_NODE, &no_vrf_cmd); +	install_node(&vrf_node, writefunc); +	install_default(VRF_NODE);  } @@ -38,11 +38,7 @@  /* Pending: May need to refine this. */  #ifndef IFLA_VRF_MAX -enum { -        IFLA_VRF_UNSPEC, -        IFLA_VRF_TABLE, -        __IFLA_VRF_MAX -}; +enum { IFLA_VRF_UNSPEC, IFLA_VRF_TABLE, __IFLA_VRF_MAX };  #define IFLA_VRF_MAX (__IFLA_VRF_MAX - 1)  #endif @@ -66,32 +62,31 @@ enum {  #define VRF_ENABLE_HOOK     2   /* a VRF is ready to use */  #define VRF_DISABLE_HOOK    3   /* a VRF is to be unusable */ -struct vrf -{ -  RB_ENTRY(vrf) id_entry, name_entry; +struct vrf { +	RB_ENTRY(vrf) id_entry, name_entry; -  /* Identifier, same as the vector index */ -  vrf_id_t vrf_id; +	/* Identifier, same as the vector index */ +	vrf_id_t vrf_id; -  /* Name */ -  char name[VRF_NAMSIZ + 1]; +	/* Name */ +	char name[VRF_NAMSIZ + 1]; -  /* Zebra internal VRF status */ -  u_char status; +	/* Zebra internal VRF status */ +	u_char status;  #define VRF_ACTIVE     (1 << 0) -  /* Master list of interfaces belonging to this VRF */ -  struct list *iflist; +	/* Master list of interfaces belonging to this VRF */ +	struct list *iflist; -  /* User data */ -  void *info; +	/* User data */ +	void *info; -  QOBJ_FIELDS +	QOBJ_FIELDS  }; -RB_HEAD (vrf_id_head, vrf); -RB_PROTOTYPE (vrf_id_head, vrf, id_entry, vrf_id_compare) -RB_HEAD (vrf_name_head, vrf); -RB_PROTOTYPE (vrf_name_head, vrf, name_entry, vrf_name_compare) +RB_HEAD(vrf_id_head, vrf); +RB_PROTOTYPE(vrf_id_head, vrf, id_entry, vrf_id_compare) +RB_HEAD(vrf_name_head, vrf); +RB_PROTOTYPE(vrf_name_head, vrf, name_entry, vrf_name_compare)  DECLARE_QOBJ_TYPE(vrf) @@ -106,85 +101,84 @@ extern struct vrf_name_head vrfs_by_name;   *          - param 2: the address of the user data pointer (the user data   *                     can be stored in or freed from there)   */ -extern void vrf_add_hook (int, int (*)(struct vrf *)); - -extern struct vrf *vrf_lookup_by_id (vrf_id_t); -extern struct vrf *vrf_lookup_by_name (const char *); -extern struct vrf *vrf_get (vrf_id_t, const char *); -extern void vrf_delete (struct vrf *); -extern int vrf_enable (struct vrf *); -extern vrf_id_t vrf_name_to_id (const char *); - -#define VRF_GET_ID(V,NAME)      \ -  do {                          \ -      struct vrf *vrf; \ -      if (!(vrf = vrf_lookup_by_name(NAME))) \ -        {                                                           \ -          vty_out (vty, "%% VRF %s not found%s", NAME, VTY_NEWLINE);\ -          return CMD_WARNING;                                       \ -        }                                               \ -      if (vrf->vrf_id == VRF_UNKNOWN) \ -        { \ -          vty_out (vty, "%% VRF %s not active%s", NAME, VTY_NEWLINE);\ -          return CMD_WARNING;                                       \ -        } \ -      (V) = vrf->vrf_id; \ -  } while (0) +extern void vrf_add_hook(int, int (*)(struct vrf *)); + +extern struct vrf *vrf_lookup_by_id(vrf_id_t); +extern struct vrf *vrf_lookup_by_name(const char *); +extern struct vrf *vrf_get(vrf_id_t, const char *); +extern void vrf_delete(struct vrf *); +extern int vrf_enable(struct vrf *); +extern vrf_id_t vrf_name_to_id(const char *); + +#define VRF_GET_ID(V, NAME)                                                    \ +	do {                                                                   \ +		struct vrf *vrf;                                               \ +		if (!(vrf = vrf_lookup_by_name(NAME))) {                       \ +			vty_out(vty, "%% VRF %s not found%s", NAME,            \ +				VTY_NEWLINE);                                  \ +			return CMD_WARNING;                                    \ +		}                                                              \ +		if (vrf->vrf_id == VRF_UNKNOWN) {                              \ +			vty_out(vty, "%% VRF %s not active%s", NAME,           \ +				VTY_NEWLINE);                                  \ +			return CMD_WARNING;                                    \ +		}                                                              \ +		(V) = vrf->vrf_id;                                             \ +	} while (0)  /*   * Utilities to obtain the user data   */  /* Get the data pointer of the specified VRF. If not found, create one. */ -extern void *vrf_info_get (vrf_id_t); +extern void *vrf_info_get(vrf_id_t);  /* Look up the data pointer of the specified VRF. */ -extern void *vrf_info_lookup (vrf_id_t); +extern void *vrf_info_lookup(vrf_id_t);  /*   * Utilities to obtain the interface list   */  /* Look up the interface list of the specified VRF. */ -extern struct list *vrf_iflist (vrf_id_t); +extern struct list *vrf_iflist(vrf_id_t);  /* Get the interface list of the specified VRF. Create one if not find. */ -extern struct list *vrf_iflist_get (vrf_id_t); +extern struct list *vrf_iflist_get(vrf_id_t);  /* Create the interface list for the specified VRF, if needed. */ -extern void vrf_iflist_create (vrf_id_t vrf_id); +extern void vrf_iflist_create(vrf_id_t vrf_id);  /* Free the interface list of the specified VRF. */ -extern void vrf_iflist_terminate (vrf_id_t vrf_id); +extern void vrf_iflist_terminate(vrf_id_t vrf_id);  /*   * VRF bit-map: maintaining flags, one bit per VRF ID   */ -typedef void *              vrf_bitmap_t; +typedef void *vrf_bitmap_t;  #define VRF_BITMAP_NULL     NULL -extern vrf_bitmap_t vrf_bitmap_init (void); -extern void vrf_bitmap_free (vrf_bitmap_t); -extern void vrf_bitmap_set (vrf_bitmap_t, vrf_id_t); -extern void vrf_bitmap_unset (vrf_bitmap_t, vrf_id_t); -extern int vrf_bitmap_check (vrf_bitmap_t, vrf_id_t); +extern vrf_bitmap_t vrf_bitmap_init(void); +extern void vrf_bitmap_free(vrf_bitmap_t); +extern void vrf_bitmap_set(vrf_bitmap_t, vrf_id_t); +extern void vrf_bitmap_unset(vrf_bitmap_t, vrf_id_t); +extern int vrf_bitmap_check(vrf_bitmap_t, vrf_id_t);  /*   * VRF initializer/destructor   */  /* Please add hooks before calling vrf_init(). */ -extern void vrf_init (void); -extern void vrf_terminate (void); +extern void vrf_init(void); +extern void vrf_terminate(void); -extern void vrf_cmd_init (int (*writefunc)(struct vty *vty)); +extern void vrf_cmd_init(int (*writefunc)(struct vty *vty));  /*   * VRF utilities   */  /* Create a socket serving for the given VRF */ -extern int vrf_socket (int, int, int, vrf_id_t); +extern int vrf_socket(int, int, int, vrf_id_t);  /*   * VRF Debugging   */ -extern void vrf_install_commands (void); +extern void vrf_install_commands(void);  #endif /*_ZEBRA_VRF_H*/ - @@ -39,25 +39,24 @@  #include <arpa/telnet.h>  #include <termios.h> -DEFINE_MTYPE_STATIC(LIB, VTY,         "VTY") +DEFINE_MTYPE_STATIC(LIB, VTY, "VTY")  DEFINE_MTYPE_STATIC(LIB, VTY_OUT_BUF, "VTY output buffer") -DEFINE_MTYPE_STATIC(LIB, VTY_HIST,    "VTY history") +DEFINE_MTYPE_STATIC(LIB, VTY_HIST, "VTY history")  /* Vty events */ -enum event -{ -  VTY_SERV, -  VTY_READ, -  VTY_WRITE, -  VTY_TIMEOUT_RESET, +enum event { +	VTY_SERV, +	VTY_READ, +	VTY_WRITE, +	VTY_TIMEOUT_RESET,  #ifdef VTYSH -  VTYSH_SERV, -  VTYSH_READ, -  VTYSH_WRITE +	VTYSH_SERV, +	VTYSH_READ, +	VTYSH_WRITE  #endif /* VTYSH */  }; -static void vty_event (enum event, int, struct vty *); +static void vty_event(enum event, int, struct vty *);  /* Extern host structure from command.c */  extern struct host host; @@ -93,220 +92,203 @@ char integrate_default[] = SYSCONFDIR INTEGRATE_DEFAULT_CONFIG;  static int do_log_commands = 0;  /* VTY standard output function. */ -int -vty_out (struct vty *vty, const char *format, ...) -{ -  va_list args; -  int len = 0; -  int size = 1024; -  char buf[1024]; -  char *p = NULL; - -  if (vty_shell (vty)) -    { -      va_start (args, format); -      vprintf (format, args); -      va_end (args); -    } -  else -    { -      /* Try to write to initial buffer.  */ -      va_start (args, format); -      len = vsnprintf (buf, sizeof(buf), format, args); -      va_end (args); - -      /* Initial buffer is not enough.  */ -      if (len < 0 || len >= size) -        { -          while (1) -            { -              if (len > -1) -                size = len + 1; -              else -                size = size * 2; - -              p = XREALLOC (MTYPE_VTY_OUT_BUF, p, size); -              if (! p) -                return -1; - -              va_start (args, format); -              len = vsnprintf (p, size, format, args); -              va_end (args); - -              if (len > -1 && len < size) -                break; -            } -        } - -      /* When initial buffer is enough to store all output.  */ -      if (! p) -        p = buf; - -      /* Pointer p must point out buffer. */ -      buffer_put (vty->obuf, (u_char *) p, len); - -      /* If p is not different with buf, it is allocated buffer.  */ -      if (p != buf) -        XFREE (MTYPE_VTY_OUT_BUF, p); -    } - -  return len; -} - -static int -vty_log_out (struct vty *vty, const char *level, const char *proto_str, -             const char *format, struct timestamp_control *ctl, va_list va) -{ -  int ret; -  int len; -  char buf[1024]; - -  if (!ctl->already_rendered) -    { -      ctl->len = quagga_timestamp(ctl->precision, ctl->buf, sizeof(ctl->buf)); -      ctl->already_rendered = 1; -    } -  if (ctl->len+1 >= sizeof(buf)) -    return -1; -  memcpy(buf, ctl->buf, len = ctl->len); -  buf[len++] = ' '; -  buf[len] = '\0'; - -  if (level) -    ret = snprintf(buf+len, sizeof(buf)-len, "%s: %s: ", level, proto_str); -  else -    ret = snprintf(buf+len, sizeof(buf)-len, "%s: ", proto_str); -  if ((ret < 0) || ((size_t)(len += ret) >= sizeof(buf))) -    return -1; - -  if (((ret = vsnprintf(buf+len, sizeof(buf)-len, format, va)) < 0) || -      ((size_t)((len += ret)+2) > sizeof(buf))) -    return -1; - -  buf[len++] = '\r'; -  buf[len++] = '\n'; - -  if (write(vty->wfd, buf, len) < 0) -    { -      if (ERRNO_IO_RETRY(errno)) -        /* Kernel buffer is full, probably too much debugging output, so just -           drop the data and ignore. */ -        return -1; -      /* Fatal I/O error. */ -      vty->monitor = 0; /* disable monitoring to avoid infinite recursion */ -      zlog_warn("%s: write failed to vty client fd %d, closing: %s", -                __func__, vty->fd, safe_strerror(errno)); -      buffer_reset(vty->obuf); -      /* cannot call vty_close, because a parent routine may still try -         to access the vty struct */ -      vty->status = VTY_CLOSE; -      shutdown(vty->fd, SHUT_RDWR); -      return -1; -    } -  return 0; +int vty_out(struct vty *vty, const char *format, ...) +{ +	va_list args; +	int len = 0; +	int size = 1024; +	char buf[1024]; +	char *p = NULL; + +	if (vty_shell(vty)) { +		va_start(args, format); +		vprintf(format, args); +		va_end(args); +	} else { +		/* Try to write to initial buffer.  */ +		va_start(args, format); +		len = vsnprintf(buf, sizeof(buf), format, args); +		va_end(args); + +		/* Initial buffer is not enough.  */ +		if (len < 0 || len >= size) { +			while (1) { +				if (len > -1) +					size = len + 1; +				else +					size = size * 2; + +				p = XREALLOC(MTYPE_VTY_OUT_BUF, p, size); +				if (!p) +					return -1; + +				va_start(args, format); +				len = vsnprintf(p, size, format, args); +				va_end(args); + +				if (len > -1 && len < size) +					break; +			} +		} + +		/* When initial buffer is enough to store all output.  */ +		if (!p) +			p = buf; + +		/* Pointer p must point out buffer. */ +		buffer_put(vty->obuf, (u_char *)p, len); + +		/* If p is not different with buf, it is allocated buffer.  */ +		if (p != buf) +			XFREE(MTYPE_VTY_OUT_BUF, p); +	} + +	return len; +} + +static int vty_log_out(struct vty *vty, const char *level, +		       const char *proto_str, const char *format, +		       struct timestamp_control *ctl, va_list va) +{ +	int ret; +	int len; +	char buf[1024]; + +	if (!ctl->already_rendered) { +		ctl->len = quagga_timestamp(ctl->precision, ctl->buf, +					    sizeof(ctl->buf)); +		ctl->already_rendered = 1; +	} +	if (ctl->len + 1 >= sizeof(buf)) +		return -1; +	memcpy(buf, ctl->buf, len = ctl->len); +	buf[len++] = ' '; +	buf[len] = '\0'; + +	if (level) +		ret = snprintf(buf + len, sizeof(buf) - len, "%s: %s: ", level, +			       proto_str); +	else +		ret = snprintf(buf + len, sizeof(buf) - len, "%s: ", proto_str); +	if ((ret < 0) || ((size_t)(len += ret) >= sizeof(buf))) +		return -1; + +	if (((ret = vsnprintf(buf + len, sizeof(buf) - len, format, va)) < 0) +	    || ((size_t)((len += ret) + 2) > sizeof(buf))) +		return -1; + +	buf[len++] = '\r'; +	buf[len++] = '\n'; + +	if (write(vty->wfd, buf, len) < 0) { +		if (ERRNO_IO_RETRY(errno)) +			/* Kernel buffer is full, probably too much debugging +			   output, so just +			   drop the data and ignore. */ +			return -1; +		/* Fatal I/O error. */ +		vty->monitor = +			0; /* disable monitoring to avoid infinite recursion */ +		zlog_warn("%s: write failed to vty client fd %d, closing: %s", +			  __func__, vty->fd, safe_strerror(errno)); +		buffer_reset(vty->obuf); +		/* cannot call vty_close, because a parent routine may still try +		   to access the vty struct */ +		vty->status = VTY_CLOSE; +		shutdown(vty->fd, SHUT_RDWR); +		return -1; +	} +	return 0;  }  /* Output current time to the vty. */ -void -vty_time_print (struct vty *vty, int cr) +void vty_time_print(struct vty *vty, int cr)  { -  char buf[QUAGGA_TIMESTAMP_LEN]; +	char buf[QUAGGA_TIMESTAMP_LEN]; -  if (quagga_timestamp(0, buf, sizeof(buf)) == 0) -    { -      zlog_info("quagga_timestamp error"); -      return; -    } -  if (cr) -    vty_out (vty, "%s\n", buf); -  else -    vty_out (vty, "%s ", buf); +	if (quagga_timestamp(0, buf, sizeof(buf)) == 0) { +		zlog_info("quagga_timestamp error"); +		return; +	} +	if (cr) +		vty_out(vty, "%s\n", buf); +	else +		vty_out(vty, "%s ", buf); -  return; +	return;  }  /* Say hello to vty interface. */ -void -vty_hello (struct vty *vty) -{ -  if (host.motdfile) -    { -      FILE *f; -      char buf[4096]; - -      f = fopen (host.motdfile, "r"); -      if (f) -        { -          while (fgets (buf, sizeof (buf), f)) -            { -              char *s; -              /* work backwards to ignore trailling isspace() */ -              for (s = buf + strlen (buf); (s > buf) && isspace ((int)*(s - 1)); -                   s--); -              *s = '\0'; -              vty_out (vty, "%s%s", buf, VTY_NEWLINE); -            } -          fclose (f); -        } -      else -        vty_out (vty, "MOTD file not found%s", VTY_NEWLINE); -    } -  else if (host.motd) -    vty_out (vty, "%s", host.motd); +void vty_hello(struct vty *vty) +{ +	if (host.motdfile) { +		FILE *f; +		char buf[4096]; + +		f = fopen(host.motdfile, "r"); +		if (f) { +			while (fgets(buf, sizeof(buf), f)) { +				char *s; +				/* work backwards to ignore trailling isspace() +				 */ +				for (s = buf + strlen(buf); +				     (s > buf) && isspace((int)*(s - 1)); s--) +					; +				*s = '\0'; +				vty_out(vty, "%s%s", buf, VTY_NEWLINE); +			} +			fclose(f); +		} else +			vty_out(vty, "MOTD file not found%s", VTY_NEWLINE); +	} else if (host.motd) +		vty_out(vty, "%s", host.motd);  }  /* Put out prompt and wait input from user. */ -static void -vty_prompt (struct vty *vty) +static void vty_prompt(struct vty *vty)  { -  struct utsname names; -  const char*hostname; +	struct utsname names; +	const char *hostname; -  if (vty->type == VTY_TERM) -    { -      hostname = host.name; -      if (!hostname) -        { -          uname (&names); -          hostname = names.nodename; -        } -      vty_out (vty, cmd_prompt (vty->node), hostname); -    } +	if (vty->type == VTY_TERM) { +		hostname = host.name; +		if (!hostname) { +			uname(&names); +			hostname = names.nodename; +		} +		vty_out(vty, cmd_prompt(vty->node), hostname); +	}  }  /* Send WILL TELOPT_ECHO to remote server. */ -static void -vty_will_echo (struct vty *vty) +static void vty_will_echo(struct vty *vty)  { -  unsigned char cmd[] = { IAC, WILL, TELOPT_ECHO, '\0' }; -  vty_out (vty, "%s", cmd); +	unsigned char cmd[] = {IAC, WILL, TELOPT_ECHO, '\0'}; +	vty_out(vty, "%s", cmd);  }  /* Make suppress Go-Ahead telnet option. */ -static void -vty_will_suppress_go_ahead (struct vty *vty) +static void vty_will_suppress_go_ahead(struct vty *vty)  { -  unsigned char cmd[] = { IAC, WILL, TELOPT_SGA, '\0' }; -  vty_out (vty, "%s", cmd); +	unsigned char cmd[] = {IAC, WILL, TELOPT_SGA, '\0'}; +	vty_out(vty, "%s", cmd);  }  /* Make don't use linemode over telnet. */ -static void -vty_dont_linemode (struct vty *vty) +static void vty_dont_linemode(struct vty *vty)  { -  unsigned char cmd[] = { IAC, DONT, TELOPT_LINEMODE, '\0' }; -  vty_out (vty, "%s", cmd); +	unsigned char cmd[] = {IAC, DONT, TELOPT_LINEMODE, '\0'}; +	vty_out(vty, "%s", cmd);  }  /* Use window size. */ -static void -vty_do_window_size (struct vty *vty) +static void vty_do_window_size(struct vty *vty)  { -  unsigned char cmd[] = { IAC, DO, TELOPT_NAWS, '\0' }; -  vty_out (vty, "%s", cmd); +	unsigned char cmd[] = {IAC, DO, TELOPT_NAWS, '\0'}; +	vty_out(vty, "%s", cmd);  } -#if 0 /* Currently not used. */ +#if 0  /* Currently not used. */  /* Make don't use lflow vty interface. */  static void  vty_dont_lflow_ahead (struct vty *vty) @@ -317,231 +299,217 @@ vty_dont_lflow_ahead (struct vty *vty)  #endif /* 0 */  /* Allocate new vty struct. */ -struct vty * -vty_new () +struct vty *vty_new()  { -  struct vty *new = XCALLOC (MTYPE_VTY, sizeof (struct vty)); +	struct vty *new = XCALLOC(MTYPE_VTY, sizeof(struct vty)); -  new->fd = new->wfd = -1; -  new->obuf = buffer_new(0);    /* Use default buffer size. */ -  new->buf = XCALLOC (MTYPE_VTY, VTY_BUFSIZ); -  new->error_buf = XCALLOC (MTYPE_VTY, VTY_BUFSIZ); -  new->max = VTY_BUFSIZ; +	new->fd = new->wfd = -1; +	new->obuf = buffer_new(0); /* Use default buffer size. */ +	new->buf = XCALLOC(MTYPE_VTY, VTY_BUFSIZ); +	new->error_buf = XCALLOC(MTYPE_VTY, VTY_BUFSIZ); +	new->max = VTY_BUFSIZ; -  return new; +	return new;  }  /* Authentication of vty */ -static void -vty_auth (struct vty *vty, char *buf) -{ -  char *passwd = NULL; -  enum node_type next_node = 0; -  int fail; -  char *crypt (const char *, const char *); - -  switch (vty->node) -    { -    case AUTH_NODE: -      if (host.encrypt) -        passwd = host.password_encrypt; -      else -        passwd = host.password; -      if (host.advanced) -        next_node = host.enable ? VIEW_NODE : ENABLE_NODE; -      else -        next_node = VIEW_NODE; -      break; -    case AUTH_ENABLE_NODE: -      if (host.encrypt) -        passwd = host.enable_encrypt; -      else -        passwd = host.enable; -      next_node = ENABLE_NODE; -      break; -    } - -  if (passwd) -    { -      if (host.encrypt) -        fail = strcmp (crypt(buf, passwd), passwd); -      else -        fail = strcmp (buf, passwd); -    } -  else -    fail = 1; - -  if (! fail) -    { -      vty->fail = 0; -      vty->node = next_node;    /* Success ! */ -    } -  else -    { -      vty->fail++; -      if (vty->fail >= 3) -        { -          if (vty->node == AUTH_NODE) -            { -              vty_out (vty, "%% Bad passwords, too many failures!%s", VTY_NEWLINE); -              vty->status = VTY_CLOSE; -            } -          else -            { -              /* AUTH_ENABLE_NODE */ -              vty->fail = 0; -              vty_out (vty, "%% Bad enable passwords, too many failures!%s", VTY_NEWLINE); -	      vty->status = VTY_CLOSE; -            } -        } -    } +static void vty_auth(struct vty *vty, char *buf) +{ +	char *passwd = NULL; +	enum node_type next_node = 0; +	int fail; +	char *crypt(const char *, const char *); + +	switch (vty->node) { +	case AUTH_NODE: +		if (host.encrypt) +			passwd = host.password_encrypt; +		else +			passwd = host.password; +		if (host.advanced) +			next_node = host.enable ? VIEW_NODE : ENABLE_NODE; +		else +			next_node = VIEW_NODE; +		break; +	case AUTH_ENABLE_NODE: +		if (host.encrypt) +			passwd = host.enable_encrypt; +		else +			passwd = host.enable; +		next_node = ENABLE_NODE; +		break; +	} + +	if (passwd) { +		if (host.encrypt) +			fail = strcmp(crypt(buf, passwd), passwd); +		else +			fail = strcmp(buf, passwd); +	} else +		fail = 1; + +	if (!fail) { +		vty->fail = 0; +		vty->node = next_node; /* Success ! */ +	} else { +		vty->fail++; +		if (vty->fail >= 3) { +			if (vty->node == AUTH_NODE) { +				vty_out(vty, +					"%% Bad passwords, too many failures!%s", +					VTY_NEWLINE); +				vty->status = VTY_CLOSE; +			} else { +				/* AUTH_ENABLE_NODE */ +				vty->fail = 0; +				vty_out(vty, +					"%% Bad enable passwords, too many failures!%s", +					VTY_NEWLINE); +				vty->status = VTY_CLOSE; +			} +		} +	}  }  /* Command execution over the vty interface. */ -static int -vty_command (struct vty *vty, char *buf) -{ -  int ret; -  vector vline; -  const char *protocolname; -  char *cp = NULL; - -  /* -   * Log non empty command lines -   */ -  if (do_log_commands) -    cp = buf; -  if (cp != NULL) -    { -      /* Skip white spaces. */ -      while (isspace ((int) *cp) && *cp != '\0') -        cp++; -    } -  if (cp != NULL && *cp != '\0') -    { -      unsigned i; -      char      vty_str[VTY_BUFSIZ]; -      char        prompt_str[VTY_BUFSIZ]; - -      /* format the base vty info */ -      snprintf(vty_str, sizeof(vty_str), "vty[??]@%s", vty->address); -      if (vty) -        for (i = 0; i < vector_active (vtyvec); i++) -          if (vty == vector_slot (vtyvec, i)) -            { -              snprintf(vty_str, sizeof(vty_str), "vty[%d]@%s", -                                                 i, vty->address); -              break; -            } - -      /* format the prompt */ -      snprintf(prompt_str, sizeof(prompt_str), cmd_prompt (vty->node), vty_str); - -      /* now log the command */ -      zlog_err("%s%s", prompt_str, buf); -    } -  /* Split readline string up into the vector */ -  vline = cmd_make_strvec (buf); - -  if (vline == NULL) -    return CMD_SUCCESS; +static int vty_command(struct vty *vty, char *buf) +{ +	int ret; +	vector vline; +	const char *protocolname; +	char *cp = NULL; + +	/* +	 * Log non empty command lines +	 */ +	if (do_log_commands) +		cp = buf; +	if (cp != NULL) { +		/* Skip white spaces. */ +		while (isspace((int)*cp) && *cp != '\0') +			cp++; +	} +	if (cp != NULL && *cp != '\0') { +		unsigned i; +		char vty_str[VTY_BUFSIZ]; +		char prompt_str[VTY_BUFSIZ]; + +		/* format the base vty info */ +		snprintf(vty_str, sizeof(vty_str), "vty[??]@%s", vty->address); +		if (vty) +			for (i = 0; i < vector_active(vtyvec); i++) +				if (vty == vector_slot(vtyvec, i)) { +					snprintf(vty_str, sizeof(vty_str), +						 "vty[%d]@%s", i, vty->address); +					break; +				} + +		/* format the prompt */ +		snprintf(prompt_str, sizeof(prompt_str), cmd_prompt(vty->node), +			 vty_str); + +		/* now log the command */ +		zlog_err("%s%s", prompt_str, buf); +	} +	/* Split readline string up into the vector */ +	vline = cmd_make_strvec(buf); + +	if (vline == NULL) +		return CMD_SUCCESS;  #ifdef CONSUMED_TIME_CHECK -  { -    RUSAGE_T before; -    RUSAGE_T after; -    unsigned long realtime, cputime; +	{ +		RUSAGE_T before; +		RUSAGE_T after; +		unsigned long realtime, cputime; -    GETRUSAGE(&before); +		GETRUSAGE(&before);  #endif /* CONSUMED_TIME_CHECK */ -  ret = cmd_execute_command (vline, vty, NULL, 0); +		ret = cmd_execute_command(vline, vty, NULL, 0); -  /* Get the name of the protocol if any */ -  protocolname = zlog_protoname(); +		/* Get the name of the protocol if any */ +		protocolname = zlog_protoname();  #ifdef CONSUMED_TIME_CHECK -    GETRUSAGE(&after); -    if ((realtime = thread_consumed_time(&after, &before, &cputime)) > -        CONSUMED_TIME_CHECK) -      /* Warn about CPU hog that must be fixed. */ -      zlog_warn("SLOW COMMAND: command took %lums (cpu time %lums): %s", -                realtime/1000, cputime/1000, buf); -  } +		GETRUSAGE(&after); +		if ((realtime = thread_consumed_time(&after, &before, &cputime)) +		    > CONSUMED_TIME_CHECK) +			/* Warn about CPU hog that must be fixed. */ +			zlog_warn( +				"SLOW COMMAND: command took %lums (cpu time %lums): %s", +				realtime / 1000, cputime / 1000, buf); +	}  #endif /* CONSUMED_TIME_CHECK */ -  if (ret != CMD_SUCCESS) -    switch (ret) -      { -      case CMD_WARNING: -        if (vty->type == VTY_FILE) -          vty_out (vty, "Warning...%s", VTY_NEWLINE); -        break; -      case CMD_ERR_AMBIGUOUS: -        vty_out (vty, "%% Ambiguous command.%s", VTY_NEWLINE); -        break; -      case CMD_ERR_NO_MATCH: -        vty_out (vty, "%% [%s] Unknown command: %s%s", protocolname, buf, VTY_NEWLINE); -        break; -      case CMD_ERR_INCOMPLETE: -        vty_out (vty, "%% Command incomplete.%s", VTY_NEWLINE); -        break; -      } -  cmd_free_strvec (vline); - -  return ret; +	if (ret != CMD_SUCCESS) +		switch (ret) { +		case CMD_WARNING: +			if (vty->type == VTY_FILE) +				vty_out(vty, "Warning...%s", VTY_NEWLINE); +			break; +		case CMD_ERR_AMBIGUOUS: +			vty_out(vty, "%% Ambiguous command.%s", VTY_NEWLINE); +			break; +		case CMD_ERR_NO_MATCH: +			vty_out(vty, "%% [%s] Unknown command: %s%s", +				protocolname, buf, VTY_NEWLINE); +			break; +		case CMD_ERR_INCOMPLETE: +			vty_out(vty, "%% Command incomplete.%s", VTY_NEWLINE); +			break; +		} +	cmd_free_strvec(vline); + +	return ret;  }  static const char telnet_backward_char = 0x08;  static const char telnet_space_char = ' ';  /* Basic function to write buffer to vty. */ -static void -vty_write (struct vty *vty, const char *buf, size_t nbytes) +static void vty_write(struct vty *vty, const char *buf, size_t nbytes)  { -  if ((vty->node == AUTH_NODE) || (vty->node == AUTH_ENABLE_NODE)) -    return; +	if ((vty->node == AUTH_NODE) || (vty->node == AUTH_ENABLE_NODE)) +		return; -  /* Should we do buffering here ?  And make vty_flush (vty) ? */ -  buffer_put (vty->obuf, buf, nbytes); +	/* Should we do buffering here ?  And make vty_flush (vty) ? */ +	buffer_put(vty->obuf, buf, nbytes);  }  /* Basic function to insert character into vty. */ -static void -vty_self_insert (struct vty *vty, char c) +static void vty_self_insert(struct vty *vty, char c)  { -  int i; -  int length; +	int i; +	int length; -  if (vty->length + 1 >= VTY_BUFSIZ) -    return; +	if (vty->length + 1 >= VTY_BUFSIZ) +		return; -  length = vty->length - vty->cp; -  memmove (&vty->buf[vty->cp + 1], &vty->buf[vty->cp], length); -  vty->buf[vty->cp] = c; +	length = vty->length - vty->cp; +	memmove(&vty->buf[vty->cp + 1], &vty->buf[vty->cp], length); +	vty->buf[vty->cp] = c; -  vty_write (vty, &vty->buf[vty->cp], length + 1); -  for (i = 0; i < length; i++) -    vty_write (vty, &telnet_backward_char, 1); +	vty_write(vty, &vty->buf[vty->cp], length + 1); +	for (i = 0; i < length; i++) +		vty_write(vty, &telnet_backward_char, 1); -  vty->cp++; -  vty->length++; +	vty->cp++; +	vty->length++; -  vty->buf[vty->length] = '\0'; +	vty->buf[vty->length] = '\0';  }  /* Self insert character 'c' in overwrite mode. */ -static void -vty_self_insert_overwrite (struct vty *vty, char c) +static void vty_self_insert_overwrite(struct vty *vty, char c)  { -  if (vty->cp == vty->length) -    { -      vty_self_insert (vty, c); -      return; -    } +	if (vty->cp == vty->length) { +		vty_self_insert(vty, c); +		return; +	} -  vty->buf[vty->cp++] = c; -  vty_write (vty, &c, 1); +	vty->buf[vty->cp++] = c; +	vty_write(vty, &c, 1);  }  /** @@ -550,811 +518,758 @@ vty_self_insert_overwrite (struct vty *vty, char c)   * If the resultant string would be larger than VTY_BUFSIZ it is   * truncated to fit.   */ -static void -vty_insert_word_overwrite (struct vty *vty, char *str) +static void vty_insert_word_overwrite(struct vty *vty, char *str)  { -  if (vty->cp == VTY_BUFSIZ) -    return; +	if (vty->cp == VTY_BUFSIZ) +		return; -  size_t nwrite = MIN ((int) strlen (str), VTY_BUFSIZ - vty->cp - 1); -  memcpy (&vty->buf[vty->cp], str, nwrite); -  vty->cp += nwrite; -  vty->length = MAX (vty->cp, vty->length); -  vty->buf[vty->length] = '\0'; -  vty_write (vty, str, nwrite); +	size_t nwrite = MIN((int)strlen(str), VTY_BUFSIZ - vty->cp - 1); +	memcpy(&vty->buf[vty->cp], str, nwrite); +	vty->cp += nwrite; +	vty->length = MAX(vty->cp, vty->length); +	vty->buf[vty->length] = '\0'; +	vty_write(vty, str, nwrite);  }  /* Forward character. */ -static void -vty_forward_char (struct vty *vty) +static void vty_forward_char(struct vty *vty)  { -  if (vty->cp < vty->length) -    { -      vty_write (vty, &vty->buf[vty->cp], 1); -      vty->cp++; -    } +	if (vty->cp < vty->length) { +		vty_write(vty, &vty->buf[vty->cp], 1); +		vty->cp++; +	}  }  /* Backward character. */ -static void -vty_backward_char (struct vty *vty) +static void vty_backward_char(struct vty *vty)  { -  if (vty->cp > 0) -    { -      vty->cp--; -      vty_write (vty, &telnet_backward_char, 1); -    } +	if (vty->cp > 0) { +		vty->cp--; +		vty_write(vty, &telnet_backward_char, 1); +	}  }  /* Move to the beginning of the line. */ -static void -vty_beginning_of_line (struct vty *vty) +static void vty_beginning_of_line(struct vty *vty)  { -  while (vty->cp) -    vty_backward_char (vty); +	while (vty->cp) +		vty_backward_char(vty);  }  /* Move to the end of the line. */ -static void -vty_end_of_line (struct vty *vty) +static void vty_end_of_line(struct vty *vty)  { -  while (vty->cp < vty->length) -    vty_forward_char (vty); +	while (vty->cp < vty->length) +		vty_forward_char(vty);  } -static void vty_kill_line_from_beginning (struct vty *); -static void vty_redraw_line (struct vty *); +static void vty_kill_line_from_beginning(struct vty *); +static void vty_redraw_line(struct vty *);  /* Print command line history.  This function is called from     vty_next_line and vty_previous_line. */ -static void -vty_history_print (struct vty *vty) +static void vty_history_print(struct vty *vty)  { -  int length; +	int length; -  vty_kill_line_from_beginning (vty); +	vty_kill_line_from_beginning(vty); -  /* Get previous line from history buffer */ -  length = strlen (vty->hist[vty->hp]); -  memcpy (vty->buf, vty->hist[vty->hp], length); -  vty->cp = vty->length = length; -  vty->buf[vty->length] = '\0'; +	/* Get previous line from history buffer */ +	length = strlen(vty->hist[vty->hp]); +	memcpy(vty->buf, vty->hist[vty->hp], length); +	vty->cp = vty->length = length; +	vty->buf[vty->length] = '\0'; -  /* Redraw current line */ -  vty_redraw_line (vty); +	/* Redraw current line */ +	vty_redraw_line(vty);  }  /* Show next command line history. */ -static void -vty_next_line (struct vty *vty) +static void vty_next_line(struct vty *vty)  { -  int try_index; +	int try_index; -  if (vty->hp == vty->hindex) -    return; +	if (vty->hp == vty->hindex) +		return; -  /* Try is there history exist or not. */ -  try_index = vty->hp; -  if (try_index == (VTY_MAXHIST - 1)) -    try_index = 0; -  else -    try_index++; +	/* Try is there history exist or not. */ +	try_index = vty->hp; +	if (try_index == (VTY_MAXHIST - 1)) +		try_index = 0; +	else +		try_index++; -  /* If there is not history return. */ -  if (vty->hist[try_index] == NULL) -    return; -  else -    vty->hp = try_index; +	/* If there is not history return. */ +	if (vty->hist[try_index] == NULL) +		return; +	else +		vty->hp = try_index; -  vty_history_print (vty); +	vty_history_print(vty);  }  /* Show previous command line history. */ -static void -vty_previous_line (struct vty *vty) +static void vty_previous_line(struct vty *vty)  { -  int try_index; +	int try_index; -  try_index = vty->hp; -  if (try_index == 0) -    try_index = VTY_MAXHIST - 1; -  else -    try_index--; +	try_index = vty->hp; +	if (try_index == 0) +		try_index = VTY_MAXHIST - 1; +	else +		try_index--; -  if (vty->hist[try_index] == NULL) -    return; -  else -    vty->hp = try_index; +	if (vty->hist[try_index] == NULL) +		return; +	else +		vty->hp = try_index; -  vty_history_print (vty); +	vty_history_print(vty);  }  /* This function redraw all of the command line character. */ -static void -vty_redraw_line (struct vty *vty) +static void vty_redraw_line(struct vty *vty)  { -  vty_write (vty, vty->buf, vty->length); -  vty->cp = vty->length; +	vty_write(vty, vty->buf, vty->length); +	vty->cp = vty->length;  }  /* Forward word. */ -static void -vty_forward_word (struct vty *vty) +static void vty_forward_word(struct vty *vty)  { -  while (vty->cp != vty->length && vty->buf[vty->cp] != ' ') -    vty_forward_char (vty); +	while (vty->cp != vty->length && vty->buf[vty->cp] != ' ') +		vty_forward_char(vty); -  while (vty->cp != vty->length && vty->buf[vty->cp] == ' ') -    vty_forward_char (vty); +	while (vty->cp != vty->length && vty->buf[vty->cp] == ' ') +		vty_forward_char(vty);  }  /* Backward word without skipping training space. */ -static void -vty_backward_pure_word (struct vty *vty) +static void vty_backward_pure_word(struct vty *vty)  { -  while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ') -    vty_backward_char (vty); +	while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ') +		vty_backward_char(vty);  }  /* Backward word. */ -static void -vty_backward_word (struct vty *vty) +static void vty_backward_word(struct vty *vty)  { -  while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ') -    vty_backward_char (vty); +	while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ') +		vty_backward_char(vty); -  while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ') -    vty_backward_char (vty); +	while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ') +		vty_backward_char(vty);  }  /* When '^D' is typed at the beginning of the line we move to the down     level. */ -static void -vty_down_level (struct vty *vty) +static void vty_down_level(struct vty *vty)  { -  vty_out (vty, "%s", VTY_NEWLINE); -  cmd_exit (vty); -  vty_prompt (vty); -  vty->cp = 0; +	vty_out(vty, "%s", VTY_NEWLINE); +	cmd_exit(vty); +	vty_prompt(vty); +	vty->cp = 0;  }  /* When '^Z' is received from vty, move down to the enable mode. */ -static void -vty_end_config (struct vty *vty) -{ -  vty_out (vty, "%s", VTY_NEWLINE); - -  switch (vty->node) -    { -    case VIEW_NODE: -    case ENABLE_NODE: -      /* Nothing to do. */ -      break; -    case CONFIG_NODE: -    case INTERFACE_NODE: -    case PW_NODE: -    case ZEBRA_NODE: -    case RIP_NODE: -    case RIPNG_NODE: -    case BGP_NODE: -    case BGP_VPNV4_NODE: -    case BGP_VPNV6_NODE: -    case BGP_VRF_POLICY_NODE: -    case BGP_VNC_DEFAULTS_NODE: -    case BGP_VNC_NVE_GROUP_NODE: -    case BGP_VNC_L2_GROUP_NODE: -    case BGP_IPV4_NODE: -    case BGP_IPV4M_NODE: -    case BGP_IPV6_NODE: -    case BGP_IPV6M_NODE: -    case BGP_EVPN_NODE: -    case RMAP_NODE: -    case OSPF_NODE: -    case OSPF6_NODE: -    case LDP_NODE: -    case LDP_IPV4_NODE: -    case LDP_IPV6_NODE: -    case LDP_IPV4_IFACE_NODE: -    case LDP_IPV6_IFACE_NODE: -    case LDP_L2VPN_NODE: -    case LDP_PSEUDOWIRE_NODE: -    case ISIS_NODE: -    case KEYCHAIN_NODE: -    case KEYCHAIN_KEY_NODE: -    case MASC_NODE: -    case PIM_NODE: -    case VTY_NODE: -      vty_config_unlock (vty); -      vty->node = ENABLE_NODE; -      break; -    default: -      /* Unknown node, we have to ignore it. */ -      break; -    } - -  vty_prompt (vty); -  vty->cp = 0; +static void vty_end_config(struct vty *vty) +{ +	vty_out(vty, "%s", VTY_NEWLINE); + +	switch (vty->node) { +	case VIEW_NODE: +	case ENABLE_NODE: +		/* Nothing to do. */ +		break; +	case CONFIG_NODE: +	case INTERFACE_NODE: +	case PW_NODE: +	case ZEBRA_NODE: +	case RIP_NODE: +	case RIPNG_NODE: +	case BGP_NODE: +	case BGP_VPNV4_NODE: +	case BGP_VPNV6_NODE: +	case BGP_VRF_POLICY_NODE: +	case BGP_VNC_DEFAULTS_NODE: +	case BGP_VNC_NVE_GROUP_NODE: +	case BGP_VNC_L2_GROUP_NODE: +	case BGP_IPV4_NODE: +	case BGP_IPV4M_NODE: +	case BGP_IPV6_NODE: +	case BGP_IPV6M_NODE: +	case BGP_EVPN_NODE: +	case RMAP_NODE: +	case OSPF_NODE: +	case OSPF6_NODE: +	case LDP_NODE: +	case LDP_IPV4_NODE: +	case LDP_IPV6_NODE: +	case LDP_IPV4_IFACE_NODE: +	case LDP_IPV6_IFACE_NODE: +	case LDP_L2VPN_NODE: +	case LDP_PSEUDOWIRE_NODE: +	case ISIS_NODE: +	case KEYCHAIN_NODE: +	case KEYCHAIN_KEY_NODE: +	case MASC_NODE: +	case PIM_NODE: +	case VTY_NODE: +		vty_config_unlock(vty); +		vty->node = ENABLE_NODE; +		break; +	default: +		/* Unknown node, we have to ignore it. */ +		break; +	} + +	vty_prompt(vty); +	vty->cp = 0;  }  /* Delete a charcter at the current point. */ -static void -vty_delete_char (struct vty *vty) +static void vty_delete_char(struct vty *vty)  { -  int i; -  int size; +	int i; +	int size; -  if (vty->length == 0) -    { -      vty_down_level (vty); -      return; -    } +	if (vty->length == 0) { +		vty_down_level(vty); +		return; +	} -  if (vty->cp == vty->length) -    return;                     /* completion need here? */ +	if (vty->cp == vty->length) +		return; /* completion need here? */ -  size = vty->length - vty->cp; +	size = vty->length - vty->cp; -  vty->length--; -  memmove (&vty->buf[vty->cp], &vty->buf[vty->cp + 1], size - 1); -  vty->buf[vty->length] = '\0'; +	vty->length--; +	memmove(&vty->buf[vty->cp], &vty->buf[vty->cp + 1], size - 1); +	vty->buf[vty->length] = '\0'; -  if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE) -    return; +	if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE) +		return; -  vty_write (vty, &vty->buf[vty->cp], size - 1); -  vty_write (vty, &telnet_space_char, 1); +	vty_write(vty, &vty->buf[vty->cp], size - 1); +	vty_write(vty, &telnet_space_char, 1); -  for (i = 0; i < size; i++) -    vty_write (vty, &telnet_backward_char, 1); +	for (i = 0; i < size; i++) +		vty_write(vty, &telnet_backward_char, 1);  }  /* Delete a character before the point. */ -static void -vty_delete_backward_char (struct vty *vty) +static void vty_delete_backward_char(struct vty *vty)  { -  if (vty->cp == 0) -    return; +	if (vty->cp == 0) +		return; -  vty_backward_char (vty); -  vty_delete_char (vty); +	vty_backward_char(vty); +	vty_delete_char(vty);  }  /* Kill rest of line from current point. */ -static void -vty_kill_line (struct vty *vty) +static void vty_kill_line(struct vty *vty)  { -  int i; -  int size; +	int i; +	int size; -  size = vty->length - vty->cp; +	size = vty->length - vty->cp; -  if (size == 0) -    return; +	if (size == 0) +		return; -  for (i = 0; i < size; i++) -    vty_write (vty, &telnet_space_char, 1); -  for (i = 0; i < size; i++) -    vty_write (vty, &telnet_backward_char, 1); +	for (i = 0; i < size; i++) +		vty_write(vty, &telnet_space_char, 1); +	for (i = 0; i < size; i++) +		vty_write(vty, &telnet_backward_char, 1); -  memset (&vty->buf[vty->cp], 0, size); -  vty->length = vty->cp; +	memset(&vty->buf[vty->cp], 0, size); +	vty->length = vty->cp;  }  /* Kill line from the beginning. */ -static void -vty_kill_line_from_beginning (struct vty *vty) +static void vty_kill_line_from_beginning(struct vty *vty)  { -  vty_beginning_of_line (vty); -  vty_kill_line (vty); +	vty_beginning_of_line(vty); +	vty_kill_line(vty);  }  /* Delete a word before the point. */ -static void -vty_forward_kill_word (struct vty *vty) +static void vty_forward_kill_word(struct vty *vty)  { -  while (vty->cp != vty->length && vty->buf[vty->cp] == ' ') -    vty_delete_char (vty); -  while (vty->cp != vty->length && vty->buf[vty->cp] != ' ') -    vty_delete_char (vty); +	while (vty->cp != vty->length && vty->buf[vty->cp] == ' ') +		vty_delete_char(vty); +	while (vty->cp != vty->length && vty->buf[vty->cp] != ' ') +		vty_delete_char(vty);  }  /* Delete a word before the point. */ -static void -vty_backward_kill_word (struct vty *vty) +static void vty_backward_kill_word(struct vty *vty)  { -  while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ') -    vty_delete_backward_char (vty); -  while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ') -    vty_delete_backward_char (vty); +	while (vty->cp > 0 && vty->buf[vty->cp - 1] == ' ') +		vty_delete_backward_char(vty); +	while (vty->cp > 0 && vty->buf[vty->cp - 1] != ' ') +		vty_delete_backward_char(vty);  }  /* Transpose chars before or at the point. */ -static void -vty_transpose_chars (struct vty *vty) +static void vty_transpose_chars(struct vty *vty)  { -  char c1, c2; +	char c1, c2; -  /* If length is short or point is near by the beginning of line then -     return. */ -  if (vty->length < 2 || vty->cp < 1) -    return; +	/* If length is short or point is near by the beginning of line then +	   return. */ +	if (vty->length < 2 || vty->cp < 1) +		return; -  /* In case of point is located at the end of the line. */ -  if (vty->cp == vty->length) -    { -      c1 = vty->buf[vty->cp - 1]; -      c2 = vty->buf[vty->cp - 2]; +	/* In case of point is located at the end of the line. */ +	if (vty->cp == vty->length) { +		c1 = vty->buf[vty->cp - 1]; +		c2 = vty->buf[vty->cp - 2]; -      vty_backward_char (vty); -      vty_backward_char (vty); -      vty_self_insert_overwrite (vty, c1); -      vty_self_insert_overwrite (vty, c2); -    } -  else -    { -      c1 = vty->buf[vty->cp]; -      c2 = vty->buf[vty->cp - 1]; +		vty_backward_char(vty); +		vty_backward_char(vty); +		vty_self_insert_overwrite(vty, c1); +		vty_self_insert_overwrite(vty, c2); +	} else { +		c1 = vty->buf[vty->cp]; +		c2 = vty->buf[vty->cp - 1]; -      vty_backward_char (vty); -      vty_self_insert_overwrite (vty, c1); -      vty_self_insert_overwrite (vty, c2); -    } +		vty_backward_char(vty); +		vty_self_insert_overwrite(vty, c1); +		vty_self_insert_overwrite(vty, c2); +	}  }  /* Do completion at vty interface. */ -static void -vty_complete_command (struct vty *vty) -{ -  int i; -  int ret; -  char **matched = NULL; -  vector vline; - -  if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE) -    return; - -  vline = cmd_make_strvec (vty->buf); -  if (vline == NULL) -    return; - -  /* In case of 'help \t'. */ -  if (isspace ((int) vty->buf[vty->length - 1])) -    vector_set (vline, NULL); - -  matched = cmd_complete_command (vline, vty, &ret); - -  cmd_free_strvec (vline); - -  vty_out (vty, "%s", VTY_NEWLINE); -  switch (ret) -    { -    case CMD_ERR_AMBIGUOUS: -      vty_out (vty, "%% Ambiguous command.%s", VTY_NEWLINE); -      vty_prompt (vty); -      vty_redraw_line (vty); -      break; -    case CMD_ERR_NO_MATCH: -      /* vty_out (vty, "%% There is no matched command.%s", VTY_NEWLINE); */ -      vty_prompt (vty); -      vty_redraw_line (vty); -      break; -    case CMD_COMPLETE_FULL_MATCH: -      if (!matched[0]) -        { -          /* 2016-11-28 equinox -- need to debug, SEGV here */ -          vty_out (vty, "%% CLI BUG: FULL_MATCH with NULL str%s", VTY_NEWLINE); -          vty_prompt (vty); -          vty_redraw_line (vty); -          break; -        } -      vty_prompt (vty); -      vty_redraw_line (vty); -      vty_backward_pure_word (vty); -      vty_insert_word_overwrite (vty, matched[0]); -      vty_self_insert (vty, ' '); -      XFREE (MTYPE_TMP, matched[0]); -      break; -    case CMD_COMPLETE_MATCH: -      vty_prompt (vty); -      vty_redraw_line (vty); -      vty_backward_pure_word (vty); -      vty_insert_word_overwrite (vty, matched[0]); -      XFREE (MTYPE_TMP, matched[0]); -      break; -    case CMD_COMPLETE_LIST_MATCH: -      for (i = 0; matched[i] != NULL; i++) -        { -          if (i != 0 && ((i % 6) == 0)) -            vty_out (vty, "%s", VTY_NEWLINE); -          vty_out (vty, "%-10s ", matched[i]); -          XFREE (MTYPE_TMP, matched[i]); -        } -      vty_out (vty, "%s", VTY_NEWLINE); - -      vty_prompt (vty); -      vty_redraw_line (vty); -      break; -    case CMD_ERR_NOTHING_TODO: -      vty_prompt (vty); -      vty_redraw_line (vty); -      break; -    default: -      break; -    } -  if (matched) -    XFREE (MTYPE_TMP, matched); -} - -static void -vty_describe_fold (struct vty *vty, int cmd_width, -                   unsigned int desc_width, struct cmd_token *token) -{ -  char *buf; -  const char *cmd, *p; -  int pos; - -  cmd = token->text; - -  if (desc_width <= 0) -    { -      vty_out (vty, "  %-*s  %s%s", cmd_width, cmd, token->desc, VTY_NEWLINE); -      return; -    } - -  buf = XCALLOC (MTYPE_TMP, strlen (token->desc) + 1); - -  for (p = token->desc; strlen (p) > desc_width; p += pos + 1) -    { -      for (pos = desc_width; pos > 0; pos--) -      if (*(p + pos) == ' ') -        break; - -      if (pos == 0) -      break; - -      strncpy (buf, p, pos); -      buf[pos] = '\0'; -      vty_out (vty, "  %-*s  %s%s", cmd_width, cmd, buf, VTY_NEWLINE); - -      cmd = ""; -    } - -  vty_out (vty, "  %-*s  %s%s", cmd_width, cmd, p, VTY_NEWLINE); - -  XFREE (MTYPE_TMP, buf); +static void vty_complete_command(struct vty *vty) +{ +	int i; +	int ret; +	char **matched = NULL; +	vector vline; + +	if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE) +		return; + +	vline = cmd_make_strvec(vty->buf); +	if (vline == NULL) +		return; + +	/* In case of 'help \t'. */ +	if (isspace((int)vty->buf[vty->length - 1])) +		vector_set(vline, NULL); + +	matched = cmd_complete_command(vline, vty, &ret); + +	cmd_free_strvec(vline); + +	vty_out(vty, "%s", VTY_NEWLINE); +	switch (ret) { +	case CMD_ERR_AMBIGUOUS: +		vty_out(vty, "%% Ambiguous command.%s", VTY_NEWLINE); +		vty_prompt(vty); +		vty_redraw_line(vty); +		break; +	case CMD_ERR_NO_MATCH: +		/* vty_out (vty, "%% There is no matched command.%s", +		 * VTY_NEWLINE); */ +		vty_prompt(vty); +		vty_redraw_line(vty); +		break; +	case CMD_COMPLETE_FULL_MATCH: +		if (!matched[0]) { +			/* 2016-11-28 equinox -- need to debug, SEGV here */ +			vty_out(vty, "%% CLI BUG: FULL_MATCH with NULL str%s", +				VTY_NEWLINE); +			vty_prompt(vty); +			vty_redraw_line(vty); +			break; +		} +		vty_prompt(vty); +		vty_redraw_line(vty); +		vty_backward_pure_word(vty); +		vty_insert_word_overwrite(vty, matched[0]); +		vty_self_insert(vty, ' '); +		XFREE(MTYPE_TMP, matched[0]); +		break; +	case CMD_COMPLETE_MATCH: +		vty_prompt(vty); +		vty_redraw_line(vty); +		vty_backward_pure_word(vty); +		vty_insert_word_overwrite(vty, matched[0]); +		XFREE(MTYPE_TMP, matched[0]); +		break; +	case CMD_COMPLETE_LIST_MATCH: +		for (i = 0; matched[i] != NULL; i++) { +			if (i != 0 && ((i % 6) == 0)) +				vty_out(vty, "%s", VTY_NEWLINE); +			vty_out(vty, "%-10s ", matched[i]); +			XFREE(MTYPE_TMP, matched[i]); +		} +		vty_out(vty, "%s", VTY_NEWLINE); + +		vty_prompt(vty); +		vty_redraw_line(vty); +		break; +	case CMD_ERR_NOTHING_TODO: +		vty_prompt(vty); +		vty_redraw_line(vty); +		break; +	default: +		break; +	} +	if (matched) +		XFREE(MTYPE_TMP, matched); +} + +static void vty_describe_fold(struct vty *vty, int cmd_width, +			      unsigned int desc_width, struct cmd_token *token) +{ +	char *buf; +	const char *cmd, *p; +	int pos; + +	cmd = token->text; + +	if (desc_width <= 0) { +		vty_out(vty, "  %-*s  %s%s", cmd_width, cmd, token->desc, +			VTY_NEWLINE); +		return; +	} + +	buf = XCALLOC(MTYPE_TMP, strlen(token->desc) + 1); + +	for (p = token->desc; strlen(p) > desc_width; p += pos + 1) { +		for (pos = desc_width; pos > 0; pos--) +			if (*(p + pos) == ' ') +				break; + +		if (pos == 0) +			break; + +		strncpy(buf, p, pos); +		buf[pos] = '\0'; +		vty_out(vty, "  %-*s  %s%s", cmd_width, cmd, buf, VTY_NEWLINE); + +		cmd = ""; +	} + +	vty_out(vty, "  %-*s  %s%s", cmd_width, cmd, p, VTY_NEWLINE); + +	XFREE(MTYPE_TMP, buf);  }  /* Describe matched command function. */ -static void -vty_describe_command (struct vty *vty) -{ -  int ret; -  vector vline; -  vector describe; -  unsigned int i, width, desc_width; -  struct cmd_token *token, *token_cr = NULL; - -  vline = cmd_make_strvec (vty->buf); - -  /* In case of '> ?'. */ -  if (vline == NULL) -    { -      vline = vector_init (1); -      vector_set (vline, NULL); -    } -  else -    if (isspace ((int) vty->buf[vty->length - 1])) -      vector_set (vline, NULL); - -  describe = cmd_describe_command (vline, vty, &ret); - -  vty_out (vty, "%s", VTY_NEWLINE); - -  /* Ambiguous error. */ -  switch (ret) -    { -    case CMD_ERR_AMBIGUOUS: -      vty_out (vty, "%% Ambiguous command.%s", VTY_NEWLINE); -      goto out; -      break; -    case CMD_ERR_NO_MATCH: -      vty_out (vty, "%% There is no matched command.%s", VTY_NEWLINE); -      goto out; -      break; -    } - -  /* Get width of command string. */ -  width = 0; -  for (i = 0; i < vector_active (describe); i++) -    if ((token = vector_slot (describe, i)) != NULL) -      { -        unsigned int len; - -        if (token->text[0] == '\0') -          continue; - -        len = strlen (token->text); - -        if (width < len) -          width = len; -      } - -  /* Get width of description string. */ -  desc_width = vty->width - (width + 6); - -  /* Print out description. */ -  for (i = 0; i < vector_active (describe); i++) -    if ((token = vector_slot (describe, i)) != NULL) -      { -        if (token->text[0] == '\0') -          continue; - -        if (strcmp (token->text, CMD_CR_TEXT) == 0) -          { -            token_cr = token; -            continue; -          } - -        if (!token->desc) -          vty_out (vty, "  %-s%s", -                   token->text, -                   VTY_NEWLINE); -        else if (desc_width >= strlen (token->desc)) -          vty_out (vty, "  %-*s  %s%s", width, -                   token->text, -                   token->desc, VTY_NEWLINE); -        else -          vty_describe_fold (vty, width, desc_width, token); +static void vty_describe_command(struct vty *vty) +{ +	int ret; +	vector vline; +	vector describe; +	unsigned int i, width, desc_width; +	struct cmd_token *token, *token_cr = NULL; + +	vline = cmd_make_strvec(vty->buf); + +	/* In case of '> ?'. */ +	if (vline == NULL) { +		vline = vector_init(1); +		vector_set(vline, NULL); +	} else if (isspace((int)vty->buf[vty->length - 1])) +		vector_set(vline, NULL); + +	describe = cmd_describe_command(vline, vty, &ret); + +	vty_out(vty, "%s", VTY_NEWLINE); + +	/* Ambiguous error. */ +	switch (ret) { +	case CMD_ERR_AMBIGUOUS: +		vty_out(vty, "%% Ambiguous command.%s", VTY_NEWLINE); +		goto out; +		break; +	case CMD_ERR_NO_MATCH: +		vty_out(vty, "%% There is no matched command.%s", VTY_NEWLINE); +		goto out; +		break; +	} + +	/* Get width of command string. */ +	width = 0; +	for (i = 0; i < vector_active(describe); i++) +		if ((token = vector_slot(describe, i)) != NULL) { +			unsigned int len; + +			if (token->text[0] == '\0') +				continue; + +			len = strlen(token->text); + +			if (width < len) +				width = len; +		} + +	/* Get width of description string. */ +	desc_width = vty->width - (width + 6); + +	/* Print out description. */ +	for (i = 0; i < vector_active(describe); i++) +		if ((token = vector_slot(describe, i)) != NULL) { +			if (token->text[0] == '\0') +				continue; + +			if (strcmp(token->text, CMD_CR_TEXT) == 0) { +				token_cr = token; +				continue; +			} + +			if (!token->desc) +				vty_out(vty, "  %-s%s", token->text, +					VTY_NEWLINE); +			else if (desc_width >= strlen(token->desc)) +				vty_out(vty, "  %-*s  %s%s", width, token->text, +					token->desc, VTY_NEWLINE); +			else +				vty_describe_fold(vty, width, desc_width, +						  token);  #if 0          vty_out (vty, "  %-*s %s%s", width                   desc->cmd[0] == '.' ? desc->cmd + 1 : desc->cmd,                   desc->str ? desc->str : "", VTY_NEWLINE);  #endif /* 0 */ -      } - -  if ((token = token_cr)) -    { -      if (!token->desc) -        vty_out (vty, "  %-s%s", -                 token->text, -                 VTY_NEWLINE); -      else if (desc_width >= strlen (token->desc)) -        vty_out (vty, "  %-*s  %s%s", width, -                 token->text, -                 token->desc, VTY_NEWLINE); -      else -        vty_describe_fold (vty, width, desc_width, token); -    } +		} + +	if ((token = token_cr)) { +		if (!token->desc) +			vty_out(vty, "  %-s%s", token->text, VTY_NEWLINE); +		else if (desc_width >= strlen(token->desc)) +			vty_out(vty, "  %-*s  %s%s", width, token->text, +				token->desc, VTY_NEWLINE); +		else +			vty_describe_fold(vty, width, desc_width, token); +	}  out: -  cmd_free_strvec (vline); -  if (describe) -    vector_free (describe); +	cmd_free_strvec(vline); +	if (describe) +		vector_free(describe); -  vty_prompt (vty); -  vty_redraw_line (vty); +	vty_prompt(vty); +	vty_redraw_line(vty);  } -static void -vty_clear_buf (struct vty *vty) +static void vty_clear_buf(struct vty *vty)  { -  memset (vty->buf, 0, vty->max); +	memset(vty->buf, 0, vty->max);  }  /* ^C stop current input and do not add command line to the history. */ -static void -vty_stop_input (struct vty *vty) -{ -  vty->cp = vty->length = 0; -  vty_clear_buf (vty); -  vty_out (vty, "%s", VTY_NEWLINE); - -  switch (vty->node) -    { -    case VIEW_NODE: -    case ENABLE_NODE: -      /* Nothing to do. */ -      break; -    case CONFIG_NODE: -    case INTERFACE_NODE: -    case PW_NODE: -    case ZEBRA_NODE: -    case RIP_NODE: -    case RIPNG_NODE: -    case BGP_NODE: -    case RMAP_NODE: -    case OSPF_NODE: -    case OSPF6_NODE: -    case LDP_NODE: -    case LDP_IPV4_NODE: -    case LDP_IPV6_NODE: -    case LDP_IPV4_IFACE_NODE: -    case LDP_IPV6_IFACE_NODE: -    case LDP_L2VPN_NODE: -    case LDP_PSEUDOWIRE_NODE: -    case ISIS_NODE: -    case KEYCHAIN_NODE: -    case KEYCHAIN_KEY_NODE: -    case MASC_NODE: -    case PIM_NODE: -    case VTY_NODE: -      vty_config_unlock (vty); -      vty->node = ENABLE_NODE; -      break; -    default: -      /* Unknown node, we have to ignore it. */ -      break; -    } -  vty_prompt (vty); - -  /* Set history pointer to the latest one. */ -  vty->hp = vty->hindex; +static void vty_stop_input(struct vty *vty) +{ +	vty->cp = vty->length = 0; +	vty_clear_buf(vty); +	vty_out(vty, "%s", VTY_NEWLINE); + +	switch (vty->node) { +	case VIEW_NODE: +	case ENABLE_NODE: +		/* Nothing to do. */ +		break; +	case CONFIG_NODE: +	case INTERFACE_NODE: +	case PW_NODE: +	case ZEBRA_NODE: +	case RIP_NODE: +	case RIPNG_NODE: +	case BGP_NODE: +	case RMAP_NODE: +	case OSPF_NODE: +	case OSPF6_NODE: +	case LDP_NODE: +	case LDP_IPV4_NODE: +	case LDP_IPV6_NODE: +	case LDP_IPV4_IFACE_NODE: +	case LDP_IPV6_IFACE_NODE: +	case LDP_L2VPN_NODE: +	case LDP_PSEUDOWIRE_NODE: +	case ISIS_NODE: +	case KEYCHAIN_NODE: +	case KEYCHAIN_KEY_NODE: +	case MASC_NODE: +	case PIM_NODE: +	case VTY_NODE: +		vty_config_unlock(vty); +		vty->node = ENABLE_NODE; +		break; +	default: +		/* Unknown node, we have to ignore it. */ +		break; +	} +	vty_prompt(vty); + +	/* Set history pointer to the latest one. */ +	vty->hp = vty->hindex;  }  /* Add current command line to the history buffer. */ -static void -vty_hist_add (struct vty *vty) +static void vty_hist_add(struct vty *vty)  { -  int index; +	int index; -  if (vty->length == 0) -    return; +	if (vty->length == 0) +		return; -  index = vty->hindex ? vty->hindex - 1 : VTY_MAXHIST - 1; +	index = vty->hindex ? vty->hindex - 1 : VTY_MAXHIST - 1; -  /* Ignore the same string as previous one. */ -  if (vty->hist[index]) -    if (strcmp (vty->buf, vty->hist[index]) == 0) -      { -      vty->hp = vty->hindex; -      return; -      } +	/* Ignore the same string as previous one. */ +	if (vty->hist[index]) +		if (strcmp(vty->buf, vty->hist[index]) == 0) { +			vty->hp = vty->hindex; +			return; +		} -  /* Insert history entry. */ -  if (vty->hist[vty->hindex]) -    XFREE (MTYPE_VTY_HIST, vty->hist[vty->hindex]); -  vty->hist[vty->hindex] = XSTRDUP (MTYPE_VTY_HIST, vty->buf); +	/* Insert history entry. */ +	if (vty->hist[vty->hindex]) +		XFREE(MTYPE_VTY_HIST, vty->hist[vty->hindex]); +	vty->hist[vty->hindex] = XSTRDUP(MTYPE_VTY_HIST, vty->buf); -  /* History index rotation. */ -  vty->hindex++; -  if (vty->hindex == VTY_MAXHIST) -    vty->hindex = 0; +	/* History index rotation. */ +	vty->hindex++; +	if (vty->hindex == VTY_MAXHIST) +		vty->hindex = 0; -  vty->hp = vty->hindex; +	vty->hp = vty->hindex;  }  /* #define TELNET_OPTION_DEBUG */  /* Get telnet window size. */ -static int -vty_telnet_option (struct vty *vty, unsigned char *buf, int nbytes) +static int vty_telnet_option(struct vty *vty, unsigned char *buf, int nbytes)  {  #ifdef TELNET_OPTION_DEBUG -  int i; - -  for (i = 0; i < nbytes; i++) -    { -      switch (buf[i]) -        { -        case IAC: -          vty_out (vty, "IAC "); -          break; -        case WILL: -          vty_out (vty, "WILL "); -          break; -        case WONT: -          vty_out (vty, "WONT "); -          break; -        case DO: -          vty_out (vty, "DO "); -          break; -        case DONT: -          vty_out (vty, "DONT "); -          break; -        case SB: -          vty_out (vty, "SB "); -          break; -        case SE: -          vty_out (vty, "SE "); -          break; -        case TELOPT_ECHO: -          vty_out (vty, "TELOPT_ECHO %s", VTY_NEWLINE); -          break; -        case TELOPT_SGA: -          vty_out (vty, "TELOPT_SGA %s", VTY_NEWLINE); -          break; -        case TELOPT_NAWS: -          vty_out (vty, "TELOPT_NAWS %s", VTY_NEWLINE); -          break; -        default: -          vty_out (vty, "%x ", buf[i]); -          break; -        } -    } -  vty_out (vty, "%s", VTY_NEWLINE); +	int i; + +	for (i = 0; i < nbytes; i++) { +		switch (buf[i]) { +		case IAC: +			vty_out(vty, "IAC "); +			break; +		case WILL: +			vty_out(vty, "WILL "); +			break; +		case WONT: +			vty_out(vty, "WONT "); +			break; +		case DO: +			vty_out(vty, "DO "); +			break; +		case DONT: +			vty_out(vty, "DONT "); +			break; +		case SB: +			vty_out(vty, "SB "); +			break; +		case SE: +			vty_out(vty, "SE "); +			break; +		case TELOPT_ECHO: +			vty_out(vty, "TELOPT_ECHO %s", VTY_NEWLINE); +			break; +		case TELOPT_SGA: +			vty_out(vty, "TELOPT_SGA %s", VTY_NEWLINE); +			break; +		case TELOPT_NAWS: +			vty_out(vty, "TELOPT_NAWS %s", VTY_NEWLINE); +			break; +		default: +			vty_out(vty, "%x ", buf[i]); +			break; +		} +	} +	vty_out(vty, "%s", VTY_NEWLINE);  #endif /* TELNET_OPTION_DEBUG */ -  switch (buf[0]) -    { -    case SB: -      vty->sb_len = 0; -      vty->iac_sb_in_progress = 1; -      return 0; -      break; -    case SE: -      { -        if (!vty->iac_sb_in_progress) -          return 0; - -        if ((vty->sb_len == 0) || (vty->sb_buf[0] == '\0')) -          { -            vty->iac_sb_in_progress = 0; -            return 0; -          } -        switch (vty->sb_buf[0]) -          { -          case TELOPT_NAWS: -            if (vty->sb_len != TELNET_NAWS_SB_LEN) -              zlog_warn("RFC 1073 violation detected: telnet NAWS option " -                        "should send %d characters, but we received %lu", -                        TELNET_NAWS_SB_LEN, (u_long)vty->sb_len); -            else if (sizeof(vty->sb_buf) < TELNET_NAWS_SB_LEN) -              zlog_err("Bug detected: sizeof(vty->sb_buf) %lu < %d, " -                       "too small to handle the telnet NAWS option", -                       (u_long)sizeof(vty->sb_buf), TELNET_NAWS_SB_LEN); -            else -              { -                vty->width = ((vty->sb_buf[1] << 8)|vty->sb_buf[2]); -                vty->height = ((vty->sb_buf[3] << 8)|vty->sb_buf[4]); +	switch (buf[0]) { +	case SB: +		vty->sb_len = 0; +		vty->iac_sb_in_progress = 1; +		return 0; +		break; +	case SE: { +		if (!vty->iac_sb_in_progress) +			return 0; + +		if ((vty->sb_len == 0) || (vty->sb_buf[0] == '\0')) { +			vty->iac_sb_in_progress = 0; +			return 0; +		} +		switch (vty->sb_buf[0]) { +		case TELOPT_NAWS: +			if (vty->sb_len != TELNET_NAWS_SB_LEN) +				zlog_warn( +					"RFC 1073 violation detected: telnet NAWS option " +					"should send %d characters, but we received %lu", +					TELNET_NAWS_SB_LEN, +					(u_long)vty->sb_len); +			else if (sizeof(vty->sb_buf) < TELNET_NAWS_SB_LEN) +				zlog_err( +					"Bug detected: sizeof(vty->sb_buf) %lu < %d, " +					"too small to handle the telnet NAWS option", +					(u_long)sizeof(vty->sb_buf), +					TELNET_NAWS_SB_LEN); +			else { +				vty->width = ((vty->sb_buf[1] << 8) +					      | vty->sb_buf[2]); +				vty->height = ((vty->sb_buf[3] << 8) +					       | vty->sb_buf[4]);  #ifdef TELNET_OPTION_DEBUG -                vty_out(vty, "TELNET NAWS window size negotiation completed: " -                              "width %d, height %d%s", -                        vty->width, vty->height, VTY_NEWLINE); +				vty_out(vty, +					"TELNET NAWS window size negotiation completed: " +					"width %d, height %d%s", +					vty->width, vty->height, VTY_NEWLINE);  #endif -              } -            break; -          } -        vty->iac_sb_in_progress = 0; -        return 0; -        break; -      } -    default: -      break; -    } -  return 1; +			} +			break; +		} +		vty->iac_sb_in_progress = 0; +		return 0; +		break; +	} +	default: +		break; +	} +	return 1;  }  /* Execute current command line. */ -static int -vty_execute (struct vty *vty) +static int vty_execute(struct vty *vty)  { -  int ret; +	int ret; -  ret = CMD_SUCCESS; +	ret = CMD_SUCCESS; -  switch (vty->node) -    { -    case AUTH_NODE: -    case AUTH_ENABLE_NODE: -      vty_auth (vty, vty->buf); -      break; -    default: -      ret = vty_command (vty, vty->buf); -      if (vty->type == VTY_TERM) -        vty_hist_add (vty); -      break; -    } +	switch (vty->node) { +	case AUTH_NODE: +	case AUTH_ENABLE_NODE: +		vty_auth(vty, vty->buf); +		break; +	default: +		ret = vty_command(vty, vty->buf); +		if (vty->type == VTY_TERM) +			vty_hist_add(vty); +		break; +	} -  /* Clear command line buffer. */ -  vty->cp = vty->length = 0; -  vty_clear_buf (vty); +	/* Clear command line buffer. */ +	vty->cp = vty->length = 0; +	vty_clear_buf(vty); -  if (vty->status != VTY_CLOSE ) -    vty_prompt (vty); +	if (vty->status != VTY_CLOSE) +		vty_prompt(vty); -  return ret; +	return ret;  }  #define CONTROL(X)  ((X) - '@') @@ -1363,397 +1278,369 @@ vty_execute (struct vty *vty)  #define VTY_ESCAPE     2  /* Escape character command map. */ -static void -vty_escape_map (unsigned char c, struct vty *vty) -{ -  switch (c) -    { -    case ('A'): -      vty_previous_line (vty); -      break; -    case ('B'): -      vty_next_line (vty); -      break; -    case ('C'): -      vty_forward_char (vty); -      break; -    case ('D'): -      vty_backward_char (vty); -      break; -    default: -      break; -    } - -  /* Go back to normal mode. */ -  vty->escape = VTY_NORMAL; +static void vty_escape_map(unsigned char c, struct vty *vty) +{ +	switch (c) { +	case ('A'): +		vty_previous_line(vty); +		break; +	case ('B'): +		vty_next_line(vty); +		break; +	case ('C'): +		vty_forward_char(vty); +		break; +	case ('D'): +		vty_backward_char(vty); +		break; +	default: +		break; +	} + +	/* Go back to normal mode. */ +	vty->escape = VTY_NORMAL;  }  /* Quit print out to the buffer. */ -static void -vty_buffer_reset (struct vty *vty) +static void vty_buffer_reset(struct vty *vty)  { -  buffer_reset (vty->obuf); -  vty_prompt (vty); -  vty_redraw_line (vty); +	buffer_reset(vty->obuf); +	vty_prompt(vty); +	vty_redraw_line(vty);  }  /* Read data via vty socket. */ -static int -vty_read (struct thread *thread) -{ -  int i; -  int nbytes; -  unsigned char buf[VTY_READ_BUFSIZ]; - -  int vty_sock = THREAD_FD (thread); -  struct vty *vty = THREAD_ARG (thread); -  vty->t_read = NULL; - -  /* Read raw data from socket */ -  if ((nbytes = read (vty->fd, buf, VTY_READ_BUFSIZ)) <= 0) -    { -      if (nbytes < 0) -        { -          if (ERRNO_IO_RETRY(errno)) -            { -              vty_event (VTY_READ, vty_sock, vty); -              return 0; -            } -          vty->monitor = 0; /* disable monitoring to avoid infinite recursion */ -          zlog_warn("%s: read error on vty client fd %d, closing: %s", -                    __func__, vty->fd, safe_strerror(errno)); -          buffer_reset(vty->obuf); -        } -      vty->status = VTY_CLOSE; -    } - -  for (i = 0; i < nbytes; i++) -    { -      if (buf[i] == IAC) -        { -          if (!vty->iac) -            { -              vty->iac = 1; -              continue; -            } -          else -            { -              vty->iac = 0; -            } -        } - -      if (vty->iac_sb_in_progress && !vty->iac) -        { -            if (vty->sb_len < sizeof(vty->sb_buf)) -              vty->sb_buf[vty->sb_len] = buf[i]; -            vty->sb_len++; -            continue; -        } - -      if (vty->iac) -        { -          /* In case of telnet command */ -          int ret = 0; -          ret = vty_telnet_option (vty, buf + i, nbytes - i); -          vty->iac = 0; -          i += ret; -          continue; -        } - - -      if (vty->status == VTY_MORE) -        { -          switch (buf[i]) -            { -            case CONTROL('C'): -            case 'q': -            case 'Q': -              vty_buffer_reset (vty); -              break; +static int vty_read(struct thread *thread) +{ +	int i; +	int nbytes; +	unsigned char buf[VTY_READ_BUFSIZ]; + +	int vty_sock = THREAD_FD(thread); +	struct vty *vty = THREAD_ARG(thread); +	vty->t_read = NULL; + +	/* Read raw data from socket */ +	if ((nbytes = read(vty->fd, buf, VTY_READ_BUFSIZ)) <= 0) { +		if (nbytes < 0) { +			if (ERRNO_IO_RETRY(errno)) { +				vty_event(VTY_READ, vty_sock, vty); +				return 0; +			} +			vty->monitor = 0; /* disable monitoring to avoid +					     infinite recursion */ +			zlog_warn( +				"%s: read error on vty client fd %d, closing: %s", +				__func__, vty->fd, safe_strerror(errno)); +			buffer_reset(vty->obuf); +		} +		vty->status = VTY_CLOSE; +	} + +	for (i = 0; i < nbytes; i++) { +		if (buf[i] == IAC) { +			if (!vty->iac) { +				vty->iac = 1; +				continue; +			} else { +				vty->iac = 0; +			} +		} + +		if (vty->iac_sb_in_progress && !vty->iac) { +			if (vty->sb_len < sizeof(vty->sb_buf)) +				vty->sb_buf[vty->sb_len] = buf[i]; +			vty->sb_len++; +			continue; +		} + +		if (vty->iac) { +			/* In case of telnet command */ +			int ret = 0; +			ret = vty_telnet_option(vty, buf + i, nbytes - i); +			vty->iac = 0; +			i += ret; +			continue; +		} + + +		if (vty->status == VTY_MORE) { +			switch (buf[i]) { +			case CONTROL('C'): +			case 'q': +			case 'Q': +				vty_buffer_reset(vty); +				break;  #if 0 /* More line does not work for "show ip bgp".  */              case '\n':              case '\r':                vty->status = VTY_MORELINE;                break;  #endif -            default: -              break; -            } -          continue; -        } - -      /* Escape character. */ -      if (vty->escape == VTY_ESCAPE) -        { -          vty_escape_map (buf[i], vty); -          continue; -        } - -      /* Pre-escape status. */ -      if (vty->escape == VTY_PRE_ESCAPE) -        { -          switch (buf[i]) -            { -            case '[': -              vty->escape = VTY_ESCAPE; -              break; -            case 'b': -              vty_backward_word (vty); -              vty->escape = VTY_NORMAL; -              break; -            case 'f': -              vty_forward_word (vty); -              vty->escape = VTY_NORMAL; -              break; -            case 'd': -              vty_forward_kill_word (vty); -              vty->escape = VTY_NORMAL; -              break; -            case CONTROL('H'): -            case 0x7f: -              vty_backward_kill_word (vty); -              vty->escape = VTY_NORMAL; -              break; -            default: -              vty->escape = VTY_NORMAL; -              break; -            } -          continue; -        } - -      switch (buf[i]) -        { -        case CONTROL('A'): -          vty_beginning_of_line (vty); -          break; -        case CONTROL('B'): -          vty_backward_char (vty); -          break; -        case CONTROL('C'): -          vty_stop_input (vty); -          break; -        case CONTROL('D'): -          vty_delete_char (vty); -          break; -        case CONTROL('E'): -          vty_end_of_line (vty); -          break; -        case CONTROL('F'): -          vty_forward_char (vty); -          break; -        case CONTROL('H'): -        case 0x7f: -          vty_delete_backward_char (vty); -          break; -        case CONTROL('K'): -          vty_kill_line (vty); -          break; -        case CONTROL('N'): -          vty_next_line (vty); -          break; -        case CONTROL('P'): -          vty_previous_line (vty); -          break; -        case CONTROL('T'): -          vty_transpose_chars (vty); -          break; -        case CONTROL('U'): -          vty_kill_line_from_beginning (vty); -          break; -        case CONTROL('W'): -          vty_backward_kill_word (vty); -          break; -        case CONTROL('Z'): -          vty_end_config (vty); -          break; -        case '\n': -        case '\r': -          vty_out (vty, "%s", VTY_NEWLINE); -          vty_execute (vty); -          break; -        case '\t': -          vty_complete_command (vty); -          break; -        case '?': -          if (vty->node == AUTH_NODE || vty->node == AUTH_ENABLE_NODE) -            vty_self_insert (vty, buf[i]); -          else -            vty_describe_command (vty); -          break; -        case '\033': -          if (i + 1 < nbytes && buf[i + 1] == '[') -            { -              vty->escape = VTY_ESCAPE; -              i++; -            } -          else -            vty->escape = VTY_PRE_ESCAPE; -          break; -        default: -          if (buf[i] > 31 && buf[i] < 127) -            vty_self_insert (vty, buf[i]); -          break; -        } -    } - -  /* Check status. */ -  if (vty->status == VTY_CLOSE) -    vty_close (vty); -  else -    { -      vty_event (VTY_WRITE, vty->wfd, vty); -      vty_event (VTY_READ, vty_sock, vty); -    } -  return 0; +			default: +				break; +			} +			continue; +		} + +		/* Escape character. */ +		if (vty->escape == VTY_ESCAPE) { +			vty_escape_map(buf[i], vty); +			continue; +		} + +		/* Pre-escape status. */ +		if (vty->escape == VTY_PRE_ESCAPE) { +			switch (buf[i]) { +			case '[': +				vty->escape = VTY_ESCAPE; +				break; +			case 'b': +				vty_backward_word(vty); +				vty->escape = VTY_NORMAL; +				break; +			case 'f': +				vty_forward_word(vty); +				vty->escape = VTY_NORMAL; +				break; +			case 'd': +				vty_forward_kill_word(vty); +				vty->escape = VTY_NORMAL; +				break; +			case CONTROL('H'): +			case 0x7f: +				vty_backward_kill_word(vty); +				vty->escape = VTY_NORMAL; +				break; +			default: +				vty->escape = VTY_NORMAL; +				break; +			} +			continue; +		} + +		switch (buf[i]) { +		case CONTROL('A'): +			vty_beginning_of_line(vty); +			break; +		case CONTROL('B'): +			vty_backward_char(vty); +			break; +		case CONTROL('C'): +			vty_stop_input(vty); +			break; +		case CONTROL('D'): +			vty_delete_char(vty); +			break; +		case CONTROL('E'): +			vty_end_of_line(vty); +			break; +		case CONTROL('F'): +			vty_forward_char(vty); +			break; +		case CONTROL('H'): +		case 0x7f: +			vty_delete_backward_char(vty); +			break; +		case CONTROL('K'): +			vty_kill_line(vty); +			break; +		case CONTROL('N'): +			vty_next_line(vty); +			break; +		case CONTROL('P'): +			vty_previous_line(vty); +			break; +		case CONTROL('T'): +			vty_transpose_chars(vty); +			break; +		case CONTROL('U'): +			vty_kill_line_from_beginning(vty); +			break; +		case CONTROL('W'): +			vty_backward_kill_word(vty); +			break; +		case CONTROL('Z'): +			vty_end_config(vty); +			break; +		case '\n': +		case '\r': +			vty_out(vty, "%s", VTY_NEWLINE); +			vty_execute(vty); +			break; +		case '\t': +			vty_complete_command(vty); +			break; +		case '?': +			if (vty->node == AUTH_NODE +			    || vty->node == AUTH_ENABLE_NODE) +				vty_self_insert(vty, buf[i]); +			else +				vty_describe_command(vty); +			break; +		case '\033': +			if (i + 1 < nbytes && buf[i + 1] == '[') { +				vty->escape = VTY_ESCAPE; +				i++; +			} else +				vty->escape = VTY_PRE_ESCAPE; +			break; +		default: +			if (buf[i] > 31 && buf[i] < 127) +				vty_self_insert(vty, buf[i]); +			break; +		} +	} + +	/* Check status. */ +	if (vty->status == VTY_CLOSE) +		vty_close(vty); +	else { +		vty_event(VTY_WRITE, vty->wfd, vty); +		vty_event(VTY_READ, vty_sock, vty); +	} +	return 0;  }  /* Flush buffer to the vty. */ -static int -vty_flush (struct thread *thread) -{ -  int erase; -  buffer_status_t flushrc; -  int vty_sock = THREAD_FD (thread); -  struct vty *vty = THREAD_ARG (thread); - -  vty->t_write = NULL; - -  /* Tempolary disable read thread. */ -  if ((vty->lines == 0) && vty->t_read) -    { -      thread_cancel (vty->t_read); -      vty->t_read = NULL; -    } - -  /* Function execution continue. */ -  erase = ((vty->status == VTY_MORE || vty->status == VTY_MORELINE)); - -  /* N.B. if width is 0, that means we don't know the window size. */ -  if ((vty->lines == 0) || (vty->width == 0) || (vty->height == 0)) -    flushrc = buffer_flush_available(vty->obuf, vty_sock); -  else if (vty->status == VTY_MORELINE) -    flushrc = buffer_flush_window(vty->obuf, vty_sock, vty->width, -                                  1, erase, 0); -  else -    flushrc = buffer_flush_window(vty->obuf, vty_sock, vty->width, -                                  vty->lines >= 0 ? vty->lines : -                                                    vty->height, -                                  erase, 0); -  switch (flushrc) -    { -    case BUFFER_ERROR: -      vty->monitor = 0; /* disable monitoring to avoid infinite recursion */ -      zlog_warn("buffer_flush failed on vty client fd %d, closing", -                vty->fd); -      buffer_reset(vty->obuf); -      vty_close(vty); -      return 0; -    case BUFFER_EMPTY: -      if (vty->status == VTY_CLOSE) -        vty_close (vty); -      else -        { -          vty->status = VTY_NORMAL; -          if (vty->lines == 0) -            vty_event (VTY_READ, vty_sock, vty); -        } -      break; -    case BUFFER_PENDING: -      /* There is more data waiting to be written. */ -      vty->status = VTY_MORE; -      if (vty->lines == 0) -        vty_event (VTY_WRITE, vty_sock, vty); -      break; -    } - -  return 0; +static int vty_flush(struct thread *thread) +{ +	int erase; +	buffer_status_t flushrc; +	int vty_sock = THREAD_FD(thread); +	struct vty *vty = THREAD_ARG(thread); + +	vty->t_write = NULL; + +	/* Tempolary disable read thread. */ +	if ((vty->lines == 0) && vty->t_read) { +		thread_cancel(vty->t_read); +		vty->t_read = NULL; +	} + +	/* Function execution continue. */ +	erase = ((vty->status == VTY_MORE || vty->status == VTY_MORELINE)); + +	/* N.B. if width is 0, that means we don't know the window size. */ +	if ((vty->lines == 0) || (vty->width == 0) || (vty->height == 0)) +		flushrc = buffer_flush_available(vty->obuf, vty_sock); +	else if (vty->status == VTY_MORELINE) +		flushrc = buffer_flush_window(vty->obuf, vty_sock, vty->width, +					      1, erase, 0); +	else +		flushrc = buffer_flush_window( +			vty->obuf, vty_sock, vty->width, +			vty->lines >= 0 ? vty->lines : vty->height, erase, 0); +	switch (flushrc) { +	case BUFFER_ERROR: +		vty->monitor = +			0; /* disable monitoring to avoid infinite recursion */ +		zlog_warn("buffer_flush failed on vty client fd %d, closing", +			  vty->fd); +		buffer_reset(vty->obuf); +		vty_close(vty); +		return 0; +	case BUFFER_EMPTY: +		if (vty->status == VTY_CLOSE) +			vty_close(vty); +		else { +			vty->status = VTY_NORMAL; +			if (vty->lines == 0) +				vty_event(VTY_READ, vty_sock, vty); +		} +		break; +	case BUFFER_PENDING: +		/* There is more data waiting to be written. */ +		vty->status = VTY_MORE; +		if (vty->lines == 0) +			vty_event(VTY_WRITE, vty_sock, vty); +		break; +	} + +	return 0;  }  /* allocate and initialise vty */ -static struct vty * -vty_new_init (int vty_sock) -{ -  struct vty *vty; - -  vty = vty_new (); -  vty->fd = vty_sock; -  vty->wfd = vty_sock; -  vty->type = VTY_TERM; -  vty->node = AUTH_NODE; -  vty->fail = 0; -  vty->cp = 0; -  vty_clear_buf (vty); -  vty->length = 0; -  memset (vty->hist, 0, sizeof (vty->hist)); -  vty->hp = 0; -  vty->hindex = 0; -  vector_set_index (vtyvec, vty_sock, vty); -  vty->status = VTY_NORMAL; -  vty->lines = -1; -  vty->iac = 0; -  vty->iac_sb_in_progress = 0; -  vty->sb_len = 0; - -  return vty; +static struct vty *vty_new_init(int vty_sock) +{ +	struct vty *vty; + +	vty = vty_new(); +	vty->fd = vty_sock; +	vty->wfd = vty_sock; +	vty->type = VTY_TERM; +	vty->node = AUTH_NODE; +	vty->fail = 0; +	vty->cp = 0; +	vty_clear_buf(vty); +	vty->length = 0; +	memset(vty->hist, 0, sizeof(vty->hist)); +	vty->hp = 0; +	vty->hindex = 0; +	vector_set_index(vtyvec, vty_sock, vty); +	vty->status = VTY_NORMAL; +	vty->lines = -1; +	vty->iac = 0; +	vty->iac_sb_in_progress = 0; +	vty->sb_len = 0; + +	return vty;  }  /* Create new vty structure. */ -static struct vty * -vty_create (int vty_sock, union sockunion *su) -{ -  char buf[SU_ADDRSTRLEN]; -  struct vty *vty; - -  sockunion2str(su, buf, SU_ADDRSTRLEN); - -  /* Allocate new vty structure and set up default values. */ -  vty = vty_new_init (vty_sock); - -  /* configurable parameters not part of basic init */ -  vty->v_timeout = vty_timeout_val; -  strcpy (vty->address, buf); -  if (no_password_check) -    { -      if (host.advanced) -        vty->node = ENABLE_NODE; -      else -        vty->node = VIEW_NODE; -    } -  if (host.lines >= 0) -    vty->lines = host.lines; - -  if (! no_password_check) -    { -      /* Vty is not available if password isn't set. */ -      if (host.password == NULL && host.password_encrypt == NULL) -        { -          vty_out (vty, "Vty password is not set.%s", VTY_NEWLINE); -          vty->status = VTY_CLOSE; -          vty_close (vty); -          return NULL; -        } -    } - -  /* Say hello to the world. */ -  vty_hello (vty); -  if (! no_password_check) -    vty_out (vty, "%sUser Access Verification%s%s", VTY_NEWLINE, VTY_NEWLINE, VTY_NEWLINE); - -  /* Setting up terminal. */ -  vty_will_echo (vty); -  vty_will_suppress_go_ahead (vty); - -  vty_dont_linemode (vty); -  vty_do_window_size (vty); -  /* vty_dont_lflow_ahead (vty); */ - -  vty_prompt (vty); - -  /* Add read/write thread. */ -  vty_event (VTY_WRITE, vty_sock, vty); -  vty_event (VTY_READ, vty_sock, vty); - -  return vty; +static struct vty *vty_create(int vty_sock, union sockunion *su) +{ +	char buf[SU_ADDRSTRLEN]; +	struct vty *vty; + +	sockunion2str(su, buf, SU_ADDRSTRLEN); + +	/* Allocate new vty structure and set up default values. */ +	vty = vty_new_init(vty_sock); + +	/* configurable parameters not part of basic init */ +	vty->v_timeout = vty_timeout_val; +	strcpy(vty->address, buf); +	if (no_password_check) { +		if (host.advanced) +			vty->node = ENABLE_NODE; +		else +			vty->node = VIEW_NODE; +	} +	if (host.lines >= 0) +		vty->lines = host.lines; + +	if (!no_password_check) { +		/* Vty is not available if password isn't set. */ +		if (host.password == NULL && host.password_encrypt == NULL) { +			vty_out(vty, "Vty password is not set.%s", VTY_NEWLINE); +			vty->status = VTY_CLOSE; +			vty_close(vty); +			return NULL; +		} +	} + +	/* Say hello to the world. */ +	vty_hello(vty); +	if (!no_password_check) +		vty_out(vty, "%sUser Access Verification%s%s", VTY_NEWLINE, +			VTY_NEWLINE, VTY_NEWLINE); + +	/* Setting up terminal. */ +	vty_will_echo(vty); +	vty_will_suppress_go_ahead(vty); + +	vty_dont_linemode(vty); +	vty_do_window_size(vty); +	/* vty_dont_lflow_ahead (vty); */ + +	vty_prompt(vty); + +	/* Add read/write thread. */ +	vty_event(VTY_WRITE, vty_sock, vty); +	vty_event(VTY_READ, vty_sock, vty); + +	return vty;  }  /* create vty for stdio */ @@ -1761,204 +1648,190 @@ static struct termios stdio_orig_termios;  static struct vty *stdio_vty = NULL;  static void (*stdio_vty_atclose)(void); -static void -vty_stdio_reset (void) +static void vty_stdio_reset(void)  { -  if (stdio_vty) -    { -      tcsetattr (0, TCSANOW, &stdio_orig_termios); -      stdio_vty = NULL; +	if (stdio_vty) { +		tcsetattr(0, TCSANOW, &stdio_orig_termios); +		stdio_vty = NULL; -      if (stdio_vty_atclose) -        stdio_vty_atclose (); -      stdio_vty_atclose = NULL; -    } +		if (stdio_vty_atclose) +			stdio_vty_atclose(); +		stdio_vty_atclose = NULL; +	}  } -struct vty * -vty_stdio (void (*atclose)()) +struct vty *vty_stdio(void (*atclose)())  { -  struct vty *vty; -  struct termios termios; +	struct vty *vty; +	struct termios termios; -  /* refuse creating two vtys on stdio */ -  if (stdio_vty) -    return NULL; +	/* refuse creating two vtys on stdio */ +	if (stdio_vty) +		return NULL; -  vty = stdio_vty = vty_new_init (0); -  stdio_vty_atclose = atclose; -  vty->wfd = 1; +	vty = stdio_vty = vty_new_init(0); +	stdio_vty_atclose = atclose; +	vty->wfd = 1; -  /* always have stdio vty in a known _unchangeable_ state, don't want config -   * to have any effect here to make sure scripting this works as intended */ -  vty->node = ENABLE_NODE; -  vty->v_timeout = 0; -  strcpy (vty->address, "console"); +	/* always have stdio vty in a known _unchangeable_ state, don't want +	 * config +	 * to have any effect here to make sure scripting this works as intended +	 */ +	vty->node = ENABLE_NODE; +	vty->v_timeout = 0; +	strcpy(vty->address, "console"); -  if (!tcgetattr (0, &stdio_orig_termios)) -    { -      termios = stdio_orig_termios; -      termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP -                           | INLCR | IGNCR | ICRNL | IXON); -      termios.c_oflag &= ~OPOST; -      termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); -      termios.c_cflag &= ~(CSIZE | PARENB); -      termios.c_cflag |= CS8; -      tcsetattr (0, TCSANOW, &termios); -    } +	if (!tcgetattr(0, &stdio_orig_termios)) { +		termios = stdio_orig_termios; +		termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR +				     | IGNCR | ICRNL | IXON); +		termios.c_oflag &= ~OPOST; +		termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); +		termios.c_cflag &= ~(CSIZE | PARENB); +		termios.c_cflag |= CS8; +		tcsetattr(0, TCSANOW, &termios); +	} -  vty_prompt (vty); +	vty_prompt(vty); -  /* Add read/write thread. */ -  vty_event (VTY_WRITE, 1, vty); -  vty_event (VTY_READ, 0, vty); +	/* Add read/write thread. */ +	vty_event(VTY_WRITE, 1, vty); +	vty_event(VTY_READ, 0, vty); -  return vty; +	return vty;  }  /* Accept connection from the network. */ -static int -vty_accept (struct thread *thread) -{ -  int vty_sock; -  union sockunion su; -  int ret; -  unsigned int on; -  int accept_sock; -  struct prefix p; -  struct access_list *acl = NULL; -  char buf[SU_ADDRSTRLEN]; - -  accept_sock = THREAD_FD (thread); - -  /* We continue hearing vty socket. */ -  vty_event (VTY_SERV, accept_sock, NULL); - -  memset (&su, 0, sizeof (union sockunion)); - -  /* We can handle IPv4 or IPv6 socket. */ -  vty_sock = sockunion_accept (accept_sock, &su); -  if (vty_sock < 0) -    { -      zlog_warn ("can't accept vty socket : %s", safe_strerror (errno)); -      return -1; -    } -  set_nonblocking(vty_sock); -  set_cloexec(vty_sock); - -  sockunion2hostprefix (&su, &p); - -  /* VTY's accesslist apply. */ -  if (p.family == AF_INET && vty_accesslist_name) -    { -      if ((acl = access_list_lookup (AFI_IP, vty_accesslist_name)) && -          (access_list_apply (acl, &p) == FILTER_DENY)) -        { -          zlog_info ("Vty connection refused from %s", -                     sockunion2str (&su, buf, SU_ADDRSTRLEN)); -          close (vty_sock); - -          /* continue accepting connections */ -          vty_event (VTY_SERV, accept_sock, NULL); - -          return 0; -        } -    } - -  /* VTY's ipv6 accesslist apply. */ -  if (p.family == AF_INET6 && vty_ipv6_accesslist_name) -    { -      if ((acl = access_list_lookup (AFI_IP6, vty_ipv6_accesslist_name)) && -          (access_list_apply (acl, &p) == FILTER_DENY)) -        { -          zlog_info ("Vty connection refused from %s", -                     sockunion2str (&su, buf, SU_ADDRSTRLEN)); -          close (vty_sock); - -          /* continue accepting connections */ -          vty_event (VTY_SERV, accept_sock, NULL); - -          return 0; -        } -    } - -  on = 1; -  ret = setsockopt (vty_sock, IPPROTO_TCP, TCP_NODELAY, -                    (char *) &on, sizeof (on)); -  if (ret < 0) -    zlog_info ("can't set sockopt to vty_sock : %s", -               safe_strerror (errno)); - -  zlog_info ("Vty connection from %s", -             sockunion2str (&su, buf, SU_ADDRSTRLEN)); - -  vty_create (vty_sock, &su); - -  return 0; -} +static int vty_accept(struct thread *thread) +{ +	int vty_sock; +	union sockunion su; +	int ret; +	unsigned int on; +	int accept_sock; +	struct prefix p; +	struct access_list *acl = NULL; +	char buf[SU_ADDRSTRLEN]; + +	accept_sock = THREAD_FD(thread); + +	/* We continue hearing vty socket. */ +	vty_event(VTY_SERV, accept_sock, NULL); + +	memset(&su, 0, sizeof(union sockunion)); + +	/* We can handle IPv4 or IPv6 socket. */ +	vty_sock = sockunion_accept(accept_sock, &su); +	if (vty_sock < 0) { +		zlog_warn("can't accept vty socket : %s", safe_strerror(errno)); +		return -1; +	} +	set_nonblocking(vty_sock); +	set_cloexec(vty_sock); + +	sockunion2hostprefix(&su, &p); + +	/* VTY's accesslist apply. */ +	if (p.family == AF_INET && vty_accesslist_name) { +		if ((acl = access_list_lookup(AFI_IP, vty_accesslist_name)) +		    && (access_list_apply(acl, &p) == FILTER_DENY)) { +			zlog_info("Vty connection refused from %s", +				  sockunion2str(&su, buf, SU_ADDRSTRLEN)); +			close(vty_sock); + +			/* continue accepting connections */ +			vty_event(VTY_SERV, accept_sock, NULL); + +			return 0; +		} +	} + +	/* VTY's ipv6 accesslist apply. */ +	if (p.family == AF_INET6 && vty_ipv6_accesslist_name) { +		if ((acl = access_list_lookup(AFI_IP6, +					      vty_ipv6_accesslist_name)) +		    && (access_list_apply(acl, &p) == FILTER_DENY)) { +			zlog_info("Vty connection refused from %s", +				  sockunion2str(&su, buf, SU_ADDRSTRLEN)); +			close(vty_sock); + +			/* continue accepting connections */ +			vty_event(VTY_SERV, accept_sock, NULL); + +			return 0; +		} +	} + +	on = 1; +	ret = setsockopt(vty_sock, IPPROTO_TCP, TCP_NODELAY, (char *)&on, +			 sizeof(on)); +	if (ret < 0) +		zlog_info("can't set sockopt to vty_sock : %s", +			  safe_strerror(errno)); + +	zlog_info("Vty connection from %s", +		  sockunion2str(&su, buf, SU_ADDRSTRLEN)); + +	vty_create(vty_sock, &su); + +	return 0; +} + +static void vty_serv_sock_addrinfo(const char *hostname, unsigned short port) +{ +	int ret; +	struct addrinfo req; +	struct addrinfo *ainfo; +	struct addrinfo *ainfo_save; +	int sock; +	char port_str[BUFSIZ]; + +	memset(&req, 0, sizeof(struct addrinfo)); +	req.ai_flags = AI_PASSIVE; +	req.ai_family = AF_UNSPEC; +	req.ai_socktype = SOCK_STREAM; +	sprintf(port_str, "%d", port); +	port_str[sizeof(port_str) - 1] = '\0'; + +	ret = getaddrinfo(hostname, port_str, &req, &ainfo); + +	if (ret != 0) { +		fprintf(stderr, "getaddrinfo failed: %s\n", gai_strerror(ret)); +		exit(1); +	} + +	ainfo_save = ainfo; + +	do { +		if (ainfo->ai_family != AF_INET && ainfo->ai_family != AF_INET6) +			continue; + +		sock = socket(ainfo->ai_family, ainfo->ai_socktype, +			      ainfo->ai_protocol); +		if (sock < 0) +			continue; -static void -vty_serv_sock_addrinfo (const char *hostname, unsigned short port) -{ -  int ret; -  struct addrinfo req; -  struct addrinfo *ainfo; -  struct addrinfo *ainfo_save; -  int sock; -  char port_str[BUFSIZ]; - -  memset (&req, 0, sizeof (struct addrinfo)); -  req.ai_flags = AI_PASSIVE; -  req.ai_family = AF_UNSPEC; -  req.ai_socktype = SOCK_STREAM; -  sprintf (port_str, "%d", port); -  port_str[sizeof (port_str) - 1] = '\0'; - -  ret = getaddrinfo (hostname, port_str, &req, &ainfo); - -  if (ret != 0) -    { -      fprintf (stderr, "getaddrinfo failed: %s\n", gai_strerror (ret)); -      exit (1); -    } - -  ainfo_save = ainfo; - -  do -    { -      if (ainfo->ai_family != AF_INET -          && ainfo->ai_family != AF_INET6 -          ) -        continue; - -      sock = socket (ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol); -      if (sock < 0) -        continue; - -      sockopt_v6only (ainfo->ai_family, sock); -      sockopt_reuseaddr (sock); -      sockopt_reuseport (sock); -      set_cloexec (sock); - -      ret = bind (sock, ainfo->ai_addr, ainfo->ai_addrlen); -      if (ret < 0) -        { -          close (sock); /* Avoid sd leak. */ -        continue; -        } - -      ret = listen (sock, 3); -      if (ret < 0) -        { -          close (sock); /* Avoid sd leak. */ -        continue; -        } - -      vty_event (VTY_SERV, sock, NULL); -    } -  while ((ainfo = ainfo->ai_next) != NULL); - -  freeaddrinfo (ainfo_save); +		sockopt_v6only(ainfo->ai_family, sock); +		sockopt_reuseaddr(sock); +		sockopt_reuseport(sock); +		set_cloexec(sock); + +		ret = bind(sock, ainfo->ai_addr, ainfo->ai_addrlen); +		if (ret < 0) { +			close(sock); /* Avoid sd leak. */ +			continue; +		} + +		ret = listen(sock, 3); +		if (ret < 0) { +			close(sock); /* Avoid sd leak. */ +			continue; +		} + +		vty_event(VTY_SERV, sock, NULL); +	} while ((ainfo = ainfo->ai_next) != NULL); + +	freeaddrinfo(ainfo_save);  }  #ifdef VTYSH @@ -1966,258 +1839,247 @@ vty_serv_sock_addrinfo (const char *hostname, unsigned short port)  #include <sys/un.h>  /* VTY shell UNIX domain socket. */ -static void -vty_serv_un (const char *path) -{ -  int ret; -  int sock, len; -  struct sockaddr_un serv; -  mode_t old_mask; -  struct zprivs_ids_t ids; - -  /* First of all, unlink existing socket */ -  unlink (path); - -  /* Set umask */ -  old_mask = umask (0007); - -  /* Make UNIX domain socket. */ -  sock = socket (AF_UNIX, SOCK_STREAM, 0); -  if (sock < 0) -    { -      zlog_err("Cannot create unix stream socket: %s", safe_strerror(errno)); -      return; -    } - -  /* Make server socket. */ -  memset (&serv, 0, sizeof (struct sockaddr_un)); -  serv.sun_family = AF_UNIX; -  strlcpy (serv.sun_path, path, sizeof (serv.sun_path)); +static void vty_serv_un(const char *path) +{ +	int ret; +	int sock, len; +	struct sockaddr_un serv; +	mode_t old_mask; +	struct zprivs_ids_t ids; + +	/* First of all, unlink existing socket */ +	unlink(path); + +	/* Set umask */ +	old_mask = umask(0007); + +	/* Make UNIX domain socket. */ +	sock = socket(AF_UNIX, SOCK_STREAM, 0); +	if (sock < 0) { +		zlog_err("Cannot create unix stream socket: %s", +			 safe_strerror(errno)); +		return; +	} + +	/* Make server socket. */ +	memset(&serv, 0, sizeof(struct sockaddr_un)); +	serv.sun_family = AF_UNIX; +	strlcpy(serv.sun_path, path, sizeof(serv.sun_path));  #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN -  len = serv.sun_len = SUN_LEN(&serv); +	len = serv.sun_len = SUN_LEN(&serv);  #else -  len = sizeof (serv.sun_family) + strlen (serv.sun_path); +	len = sizeof(serv.sun_family) + strlen(serv.sun_path);  #endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */ -  set_cloexec (sock); +	set_cloexec(sock); -  ret = bind (sock, (struct sockaddr *) &serv, len); -  if (ret < 0) -    { -      zlog_err("Cannot bind path %s: %s", path, safe_strerror(errno)); -      close (sock);     /* Avoid sd leak. */ -      return; -    } +	ret = bind(sock, (struct sockaddr *)&serv, len); +	if (ret < 0) { +		zlog_err("Cannot bind path %s: %s", path, safe_strerror(errno)); +		close(sock); /* Avoid sd leak. */ +		return; +	} -  ret = listen (sock, 5); -  if (ret < 0) -    { -      zlog_err("listen(fd %d) failed: %s", sock, safe_strerror(errno)); -      close (sock);     /* Avoid sd leak. */ -      return; -    } +	ret = listen(sock, 5); +	if (ret < 0) { +		zlog_err("listen(fd %d) failed: %s", sock, +			 safe_strerror(errno)); +		close(sock); /* Avoid sd leak. */ +		return; +	} -  umask (old_mask); +	umask(old_mask); -  zprivs_get_ids(&ids); +	zprivs_get_ids(&ids); -  /* Hack: ids.gid_vty is actually a uint, but we stored -1 in it -     earlier for the case when we don't need to chown the file -     type casting it here to make a compare */ -  if ((int)ids.gid_vty > 0) -    { -      /* set group of socket */ -      if ( chown (path, -1, ids.gid_vty) ) -        { -          zlog_err ("vty_serv_un: could chown socket, %s", -                     safe_strerror (errno) ); -        } -    } +	/* Hack: ids.gid_vty is actually a uint, but we stored -1 in it +	   earlier for the case when we don't need to chown the file +	   type casting it here to make a compare */ +	if ((int)ids.gid_vty > 0) { +		/* set group of socket */ +		if (chown(path, -1, ids.gid_vty)) { +			zlog_err("vty_serv_un: could chown socket, %s", +				 safe_strerror(errno)); +		} +	} -  vty_event (VTYSH_SERV, sock, NULL); +	vty_event(VTYSH_SERV, sock, NULL);  }  /* #define VTYSH_DEBUG 1 */ -static int -vtysh_accept (struct thread *thread) +static int vtysh_accept(struct thread *thread)  { -  int accept_sock; -  int sock; -  int client_len; -  struct sockaddr_un client; -  struct vty *vty; +	int accept_sock; +	int sock; +	int client_len; +	struct sockaddr_un client; +	struct vty *vty; -  accept_sock = THREAD_FD (thread); +	accept_sock = THREAD_FD(thread); -  vty_event (VTYSH_SERV, accept_sock, NULL); +	vty_event(VTYSH_SERV, accept_sock, NULL); -  memset (&client, 0, sizeof (struct sockaddr_un)); -  client_len = sizeof (struct sockaddr_un); +	memset(&client, 0, sizeof(struct sockaddr_un)); +	client_len = sizeof(struct sockaddr_un); -  sock = accept (accept_sock, (struct sockaddr *) &client, -                 (socklen_t *) &client_len); +	sock = accept(accept_sock, (struct sockaddr *)&client, +		      (socklen_t *)&client_len); -  if (sock < 0) -    { -      zlog_warn ("can't accept vty socket : %s", safe_strerror (errno)); -      return -1; -    } +	if (sock < 0) { +		zlog_warn("can't accept vty socket : %s", safe_strerror(errno)); +		return -1; +	} -  if (set_nonblocking(sock) < 0) -    { -      zlog_warn ("vtysh_accept: could not set vty socket %d to non-blocking," -                 " %s, closing", sock, safe_strerror (errno)); -      close (sock); -      return -1; -    } -  set_cloexec(sock); +	if (set_nonblocking(sock) < 0) { +		zlog_warn( +			"vtysh_accept: could not set vty socket %d to non-blocking," +			" %s, closing", +			sock, safe_strerror(errno)); +		close(sock); +		return -1; +	} +	set_cloexec(sock);  #ifdef VTYSH_DEBUG -  printf ("VTY shell accept\n"); +	printf("VTY shell accept\n");  #endif /* VTYSH_DEBUG */ -  vty = vty_new (); -  vty->fd = sock; -  vty->wfd = sock; -  vty->type = VTY_SHELL_SERV; -  vty->node = VIEW_NODE; - -  vty_event (VTYSH_READ, sock, vty); - -  return 0; -} - -static int -vtysh_flush(struct vty *vty) -{ -  switch (buffer_flush_available(vty->obuf, vty->wfd)) -    { -    case BUFFER_PENDING: -      vty_event(VTYSH_WRITE, vty->wfd, vty); -      break; -    case BUFFER_ERROR: -      vty->monitor = 0; /* disable monitoring to avoid infinite recursion */ -      zlog_warn("%s: write error to fd %d, closing", __func__, vty->fd); -      buffer_reset(vty->obuf); -      vty_close(vty); -      return -1; -      break; -    case BUFFER_EMPTY: -      break; -    } -  return 0; -} - -static int -vtysh_read (struct thread *thread) -{ -  int ret; -  int sock; -  int nbytes; -  struct vty *vty; -  unsigned char buf[VTY_READ_BUFSIZ]; -  unsigned char *p; -  u_char header[4] = {0, 0, 0, 0}; - -  sock = THREAD_FD (thread); -  vty = THREAD_ARG (thread); -  vty->t_read = NULL; - -  if ((nbytes = read (sock, buf, VTY_READ_BUFSIZ)) <= 0) -    { -      if (nbytes < 0) -        { -          if (ERRNO_IO_RETRY(errno)) -            { -              vty_event (VTYSH_READ, sock, vty); -              return 0; -            } -          vty->monitor = 0; /* disable monitoring to avoid infinite recursion */ -          zlog_warn("%s: read failed on vtysh client fd %d, closing: %s", -                    __func__, sock, safe_strerror(errno)); -        } -      buffer_reset(vty->obuf); -      vty_close (vty); +	vty = vty_new(); +	vty->fd = sock; +	vty->wfd = sock; +	vty->type = VTY_SHELL_SERV; +	vty->node = VIEW_NODE; + +	vty_event(VTYSH_READ, sock, vty); + +	return 0; +} + +static int vtysh_flush(struct vty *vty) +{ +	switch (buffer_flush_available(vty->obuf, vty->wfd)) { +	case BUFFER_PENDING: +		vty_event(VTYSH_WRITE, vty->wfd, vty); +		break; +	case BUFFER_ERROR: +		vty->monitor = +			0; /* disable monitoring to avoid infinite recursion */ +		zlog_warn("%s: write error to fd %d, closing", __func__, +			  vty->fd); +		buffer_reset(vty->obuf); +		vty_close(vty); +		return -1; +		break; +	case BUFFER_EMPTY: +		break; +	} +	return 0; +} + +static int vtysh_read(struct thread *thread) +{ +	int ret; +	int sock; +	int nbytes; +	struct vty *vty; +	unsigned char buf[VTY_READ_BUFSIZ]; +	unsigned char *p; +	u_char header[4] = {0, 0, 0, 0}; + +	sock = THREAD_FD(thread); +	vty = THREAD_ARG(thread); +	vty->t_read = NULL; + +	if ((nbytes = read(sock, buf, VTY_READ_BUFSIZ)) <= 0) { +		if (nbytes < 0) { +			if (ERRNO_IO_RETRY(errno)) { +				vty_event(VTYSH_READ, sock, vty); +				return 0; +			} +			vty->monitor = 0; /* disable monitoring to avoid +					     infinite recursion */ +			zlog_warn( +				"%s: read failed on vtysh client fd %d, closing: %s", +				__func__, sock, safe_strerror(errno)); +		} +		buffer_reset(vty->obuf); +		vty_close(vty);  #ifdef VTYSH_DEBUG -      printf ("close vtysh\n"); +		printf("close vtysh\n");  #endif /* VTYSH_DEBUG */ -      return 0; -    } +		return 0; +	}  #ifdef VTYSH_DEBUG -  printf ("line: %.*s\n", nbytes, buf); +	printf("line: %.*s\n", nbytes, buf);  #endif /* VTYSH_DEBUG */ -  if (vty->length + nbytes >= VTY_BUFSIZ) -    { -      /* Clear command line buffer. */ -      vty->cp = vty->length = 0; -      vty_clear_buf (vty); -      vty_out (vty, "%% Command is too long.%s", VTY_NEWLINE); -    } -  else -    { -      for (p = buf; p < buf+nbytes; p++) -        { -          vty->buf[vty->length++] = *p; -          if (*p == '\0') -            { -              /* Pass this line to parser. */ -              ret = vty_execute (vty); -              /* Note that vty_execute clears the command buffer and resets -                 vty->length to 0. */ - -              /* Return result. */ +	if (vty->length + nbytes >= VTY_BUFSIZ) { +		/* Clear command line buffer. */ +		vty->cp = vty->length = 0; +		vty_clear_buf(vty); +		vty_out(vty, "%% Command is too long.%s", VTY_NEWLINE); +	} else { +		for (p = buf; p < buf + nbytes; p++) { +			vty->buf[vty->length++] = *p; +			if (*p == '\0') { +				/* Pass this line to parser. */ +				ret = vty_execute(vty); +/* Note that vty_execute clears the command buffer and resets +   vty->length to 0. */ + +/* Return result. */  #ifdef VTYSH_DEBUG -              printf ("result: %d\n", ret); -              printf ("vtysh node: %d\n", vty->node); +				printf("result: %d\n", ret); +				printf("vtysh node: %d\n", vty->node);  #endif /* VTYSH_DEBUG */ -              /* hack for asynchronous "write integrated" -               * - other commands in "buf" will be ditched -               * - input during pending config-write is "unsupported" */ -              if (ret == CMD_SUSPEND) -                break; +				/* hack for asynchronous "write integrated" +				 * - other commands in "buf" will be ditched +				 * - input during pending config-write is +				 * "unsupported" */ +				if (ret == CMD_SUSPEND) +					break; -              /* warning: watchquagga hardcodes this result write */ -              header[3] = ret; -              buffer_put(vty->obuf, header, 4); +				/* warning: watchquagga hardcodes this result +				 * write */ +				header[3] = ret; +				buffer_put(vty->obuf, header, 4); -              if (!vty->t_write && (vtysh_flush(vty) < 0)) -                /* Try to flush results; exit if a write error occurs. */ -                return 0; -            } -        } -    } +				if (!vty->t_write && (vtysh_flush(vty) < 0)) +					/* Try to flush results; exit if a write +					 * error occurs. */ +					return 0; +			} +		} +	} -  vty_event (VTYSH_READ, sock, vty); +	vty_event(VTYSH_READ, sock, vty); -  return 0; +	return 0;  } -static int -vtysh_write (struct thread *thread) +static int vtysh_write(struct thread *thread)  { -  struct vty *vty = THREAD_ARG (thread); +	struct vty *vty = THREAD_ARG(thread); -  vty->t_write = NULL; -  vtysh_flush(vty); -  return 0; +	vty->t_write = NULL; +	vtysh_flush(vty); +	return 0;  }  #endif /* VTYSH */  /* Determine address family to bind. */ -void -vty_serv_sock (const char *addr, unsigned short port, const char *path) +void vty_serv_sock(const char *addr, unsigned short port, const char *path)  { -  /* If port is set to 0, do not listen on TCP/IP at all! */ -  if (port) -    vty_serv_sock_addrinfo (addr, port); +	/* If port is set to 0, do not listen on TCP/IP at all! */ +	if (port) +		vty_serv_sock_addrinfo(addr, port);  #ifdef VTYSH -  vty_serv_un (path); +	vty_serv_un(path);  #endif /* VTYSH */  } @@ -2225,445 +2087,426 @@ vty_serv_sock (const char *addr, unsigned short port, const char *path)     will be careful not to access the vty afterwards (since it has     now been freed).  This is safest from top-level functions (called     directly by the thread dispatcher). */ -void -vty_close (struct vty *vty) +void vty_close(struct vty *vty)  { -  int i; -  bool was_stdio = false; +	int i; +	bool was_stdio = false; -  /* Cancel threads.*/ -  if (vty->t_read) -    thread_cancel (vty->t_read); -  if (vty->t_write) -    thread_cancel (vty->t_write); -  if (vty->t_timeout) -    thread_cancel (vty->t_timeout); +	/* Cancel threads.*/ +	if (vty->t_read) +		thread_cancel(vty->t_read); +	if (vty->t_write) +		thread_cancel(vty->t_write); +	if (vty->t_timeout) +		thread_cancel(vty->t_timeout); -  /* Flush buffer. */ -  buffer_flush_all (vty->obuf, vty->wfd); +	/* Flush buffer. */ +	buffer_flush_all(vty->obuf, vty->wfd); -  /* Free input buffer. */ -  buffer_free (vty->obuf); +	/* Free input buffer. */ +	buffer_free(vty->obuf); -  /* Free command history. */ -  for (i = 0; i < VTY_MAXHIST; i++) -    if (vty->hist[i]) -      XFREE (MTYPE_VTY_HIST, vty->hist[i]); +	/* Free command history. */ +	for (i = 0; i < VTY_MAXHIST; i++) +		if (vty->hist[i]) +			XFREE(MTYPE_VTY_HIST, vty->hist[i]); -  /* Unset vector. */ -  if (vty->fd != -1) -    vector_unset(vtyvec, vty->fd); +	/* Unset vector. */ +	if (vty->fd != -1) +		vector_unset(vtyvec, vty->fd); -  if (vty->wfd > 0 && vty->type == VTY_FILE) -    fsync (vty->wfd); +	if (vty->wfd > 0 && vty->type == VTY_FILE) +		fsync(vty->wfd); -  /* Close socket. -   * note check is for fd > STDERR_FILENO, not fd != -1. -   * We never close stdin/stdout/stderr here, because we may be -   * running in foreground mode with logging to stdout.  Also, -   * additionally, we'd need to replace these fds with /dev/null. */ -  if (vty->wfd > STDERR_FILENO && vty->wfd != vty->fd) -    close(vty->wfd); +	/* Close socket. +	 * note check is for fd > STDERR_FILENO, not fd != -1. +	 * We never close stdin/stdout/stderr here, because we may be +	 * running in foreground mode with logging to stdout.  Also, +	 * additionally, we'd need to replace these fds with /dev/null. */ +	if (vty->wfd > STDERR_FILENO && vty->wfd != vty->fd) +		close(vty->wfd); -  if (vty->fd > STDERR_FILENO) -    close(vty->fd); -  else -    was_stdio = true; +	if (vty->fd > STDERR_FILENO) +		close(vty->fd); +	else +		was_stdio = true; -  if (vty->buf) -    XFREE (MTYPE_VTY, vty->buf); +	if (vty->buf) +		XFREE(MTYPE_VTY, vty->buf); -  if (vty->error_buf) -    XFREE (MTYPE_VTY, vty->error_buf); +	if (vty->error_buf) +		XFREE(MTYPE_VTY, vty->error_buf); -  /* Check configure. */ -  vty_config_unlock (vty); +	/* Check configure. */ +	vty_config_unlock(vty); -  /* OK free vty. */ -  XFREE (MTYPE_VTY, vty); +	/* OK free vty. */ +	XFREE(MTYPE_VTY, vty); -  if (was_stdio) -    vty_stdio_reset (); +	if (was_stdio) +		vty_stdio_reset();  }  /* When time out occur output message then close connection. */ -static int -vty_timeout (struct thread *thread) +static int vty_timeout(struct thread *thread)  { -  struct vty *vty; +	struct vty *vty; -  vty = THREAD_ARG (thread); -  vty->t_timeout = NULL; -  vty->v_timeout = 0; +	vty = THREAD_ARG(thread); +	vty->t_timeout = NULL; +	vty->v_timeout = 0; -  /* Clear buffer*/ -  buffer_reset (vty->obuf); -  vty_out (vty, "%sVty connection is timed out.%s", VTY_NEWLINE, VTY_NEWLINE); +	/* Clear buffer*/ +	buffer_reset(vty->obuf); +	vty_out(vty, "%sVty connection is timed out.%s", VTY_NEWLINE, +		VTY_NEWLINE); -  /* Close connection. */ -  vty->status = VTY_CLOSE; -  vty_close (vty); +	/* Close connection. */ +	vty->status = VTY_CLOSE; +	vty_close(vty); -  return 0; +	return 0;  }  /* Read up configuration file from file_name. */ -static void -vty_read_file (FILE *confp) -{ -  int ret; -  struct vty *vty; -  unsigned int line_num = 0; - -  vty = vty_new (); -  /* vty_close won't close stderr;  if some config command prints -   * something it'll end up there.  (not ideal; it'd be beter if output -   * from a file-load went to logging instead.  Also note that if this -   * function is called after daemonizing, stderr will be /dev/null.) -   * -   * vty->fd will be -1 from vty_new() -   */ -  vty->wfd = STDERR_FILENO; -  vty->type = VTY_FILE; -  vty->node = CONFIG_NODE; - -  /* Execute configuration file */ -  ret = config_from_file (vty, confp, &line_num); - -  /* Flush any previous errors before printing messages below */ -  buffer_flush_all (vty->obuf, vty->wfd); - -  if ( !((ret == CMD_SUCCESS) || (ret == CMD_ERR_NOTHING_TODO)) ) -    { -      const char *message = NULL; -      switch (ret) -       { -         case CMD_ERR_AMBIGUOUS: -           message = "*** Error reading config: Ambiguous command."; -           break; -         case CMD_ERR_NO_MATCH: -           message = "*** Error reading config: There is no such command."; -           break; -       } -      fprintf (stderr, "%s\n", message); -      zlog_err ("%s", message); -      fprintf (stderr, "*** Error occurred processing line %u, below:\n%s\n", -                       line_num, vty->error_buf); -      zlog_err ("*** Error occurred processing line %u, below:\n%s", -                      line_num, vty->error_buf); -    } - -  vty_close (vty); -} - -static FILE * -vty_use_backup_config (const char *fullpath) -{ -  char *fullpath_sav, *fullpath_tmp; -  FILE *ret = NULL; -  int tmp, sav; -  int c; -  char buffer[512]; - -  fullpath_sav = malloc (strlen (fullpath) + strlen (CONF_BACKUP_EXT) + 1); -  strcpy (fullpath_sav, fullpath); -  strcat (fullpath_sav, CONF_BACKUP_EXT); - -  sav = open (fullpath_sav, O_RDONLY); -  if (sav < 0) -    { -      free (fullpath_sav); -      return NULL; -    } - -  fullpath_tmp = malloc (strlen (fullpath) + 8); -  sprintf (fullpath_tmp, "%s.XXXXXX", fullpath); - -  /* Open file to configuration write. */ -  tmp = mkstemp (fullpath_tmp); -  if (tmp < 0) -    goto out_close_sav; - -  if (fchmod (tmp, CONFIGFILE_MASK) != 0) -    goto out_close; - -  while((c = read (sav, buffer, 512)) > 0) -    { -      if (write (tmp, buffer, c) <= 0) -        goto out_close; -    } -  close (sav); -  close (tmp); - -  if (rename (fullpath_tmp, fullpath) == 0) -    ret = fopen (fullpath, "r"); -  else -    unlink (fullpath_tmp); - -  if (0) -    { -out_close: -      close (tmp); -      unlink (fullpath_tmp); -out_close_sav: -      close (sav); -    } - -  free (fullpath_sav); -  free (fullpath_tmp); -  return ret; +static void vty_read_file(FILE *confp) +{ +	int ret; +	struct vty *vty; +	unsigned int line_num = 0; + +	vty = vty_new(); +	/* vty_close won't close stderr;  if some config command prints +	 * something it'll end up there.  (not ideal; it'd be beter if output +	 * from a file-load went to logging instead.  Also note that if this +	 * function is called after daemonizing, stderr will be /dev/null.) +	 * +	 * vty->fd will be -1 from vty_new() +	 */ +	vty->wfd = STDERR_FILENO; +	vty->type = VTY_FILE; +	vty->node = CONFIG_NODE; + +	/* Execute configuration file */ +	ret = config_from_file(vty, confp, &line_num); + +	/* Flush any previous errors before printing messages below */ +	buffer_flush_all(vty->obuf, vty->wfd); + +	if (!((ret == CMD_SUCCESS) || (ret == CMD_ERR_NOTHING_TODO))) { +		const char *message = NULL; +		switch (ret) { +		case CMD_ERR_AMBIGUOUS: +			message = +				"*** Error reading config: Ambiguous command."; +			break; +		case CMD_ERR_NO_MATCH: +			message = +				"*** Error reading config: There is no such command."; +			break; +		} +		fprintf(stderr, "%s\n", message); +		zlog_err("%s", message); +		fprintf(stderr, +			"*** Error occurred processing line %u, below:\n%s\n", +			line_num, vty->error_buf); +		zlog_err("*** Error occurred processing line %u, below:\n%s", +			 line_num, vty->error_buf); +	} + +	vty_close(vty); +} + +static FILE *vty_use_backup_config(const char *fullpath) +{ +	char *fullpath_sav, *fullpath_tmp; +	FILE *ret = NULL; +	int tmp, sav; +	int c; +	char buffer[512]; + +	fullpath_sav = malloc(strlen(fullpath) + strlen(CONF_BACKUP_EXT) + 1); +	strcpy(fullpath_sav, fullpath); +	strcat(fullpath_sav, CONF_BACKUP_EXT); + +	sav = open(fullpath_sav, O_RDONLY); +	if (sav < 0) { +		free(fullpath_sav); +		return NULL; +	} + +	fullpath_tmp = malloc(strlen(fullpath) + 8); +	sprintf(fullpath_tmp, "%s.XXXXXX", fullpath); + +	/* Open file to configuration write. */ +	tmp = mkstemp(fullpath_tmp); +	if (tmp < 0) +		goto out_close_sav; + +	if (fchmod(tmp, CONFIGFILE_MASK) != 0) +		goto out_close; + +	while ((c = read(sav, buffer, 512)) > 0) { +		if (write(tmp, buffer, c) <= 0) +			goto out_close; +	} +	close(sav); +	close(tmp); + +	if (rename(fullpath_tmp, fullpath) == 0) +		ret = fopen(fullpath, "r"); +	else +		unlink(fullpath_tmp); + +	if (0) { +	out_close: +		close(tmp); +		unlink(fullpath_tmp); +	out_close_sav: +		close(sav); +	} + +	free(fullpath_sav); +	free(fullpath_tmp); +	return ret;  }  /* Read up configuration file from file_name. */ -void -vty_read_config (const char *config_file, -                 char *config_default_dir) -{ -  char cwd[MAXPATHLEN]; -  FILE *confp = NULL; -  const char *fullpath; -  char *tmp = NULL; - -  /* If -f flag specified. */ -  if (config_file != NULL) -    { -      if (! IS_DIRECTORY_SEP (config_file[0])) -        { -          if (getcwd (cwd, MAXPATHLEN) == NULL) -            { -              fprintf (stderr, "Failure to determine Current Working Directory %d!\n", errno); -              exit (1); -            } -          tmp = XMALLOC (MTYPE_TMP, -                              strlen (cwd) + strlen (config_file) + 2); -          sprintf (tmp, "%s/%s", cwd, config_file); -          fullpath = tmp; -        } -      else -        fullpath = config_file; - -      confp = fopen (fullpath, "r"); - -      if (confp == NULL) -        { -          fprintf (stderr, "%s: failed to open configuration file %s: %s\n", -                   __func__, fullpath, safe_strerror (errno)); - -          confp = vty_use_backup_config (fullpath); -          if (confp) -            fprintf (stderr, "WARNING: using backup configuration file!\n"); -          else -            { -              fprintf (stderr, "can't open configuration file [%s]\n", -                       config_file); -              exit(1); -            } -        } -    } -  else -    { - -      host_config_set (config_default_dir); +void vty_read_config(const char *config_file, char *config_default_dir) +{ +	char cwd[MAXPATHLEN]; +	FILE *confp = NULL; +	const char *fullpath; +	char *tmp = NULL; + +	/* If -f flag specified. */ +	if (config_file != NULL) { +		if (!IS_DIRECTORY_SEP(config_file[0])) { +			if (getcwd(cwd, MAXPATHLEN) == NULL) { +				fprintf(stderr, +					"Failure to determine Current Working Directory %d!\n", +					errno); +				exit(1); +			} +			tmp = XMALLOC(MTYPE_TMP, +				      strlen(cwd) + strlen(config_file) + 2); +			sprintf(tmp, "%s/%s", cwd, config_file); +			fullpath = tmp; +		} else +			fullpath = config_file; + +		confp = fopen(fullpath, "r"); + +		if (confp == NULL) { +			fprintf(stderr, +				"%s: failed to open configuration file %s: %s\n", +				__func__, fullpath, safe_strerror(errno)); + +			confp = vty_use_backup_config(fullpath); +			if (confp) +				fprintf(stderr, +					"WARNING: using backup configuration file!\n"); +			else { +				fprintf(stderr, +					"can't open configuration file [%s]\n", +					config_file); +				exit(1); +			} +		} +	} else { + +		host_config_set(config_default_dir);  #ifdef VTYSH -      int ret; -      struct stat conf_stat; - -      /* !!!!PLEASE LEAVE!!!! -       * This is NEEDED for use with vtysh -b, or else you can get -       * a real configuration food fight with a lot garbage in the -       * merged configuration file it creates coming from the per -       * daemon configuration files.  This also allows the daemons -       * to start if there default configuration file is not -       * present or ignore them, as needed when using vtysh -b to -       * configure the daemons at boot - MAG -       */ - -      /* Stat for vtysh Zebra.conf, if found startup and wait for -       * boot configuration -       */ - -      if ( strstr(config_default_dir, "vtysh") == NULL) -        { -          ret = stat (integrate_default, &conf_stat); -          if (ret >= 0) -            goto tmp_free_and_out; -        } +		int ret; +		struct stat conf_stat; + +		/* !!!!PLEASE LEAVE!!!! +		 * This is NEEDED for use with vtysh -b, or else you can get +		 * a real configuration food fight with a lot garbage in the +		 * merged configuration file it creates coming from the per +		 * daemon configuration files.  This also allows the daemons +		 * to start if there default configuration file is not +		 * present or ignore them, as needed when using vtysh -b to +		 * configure the daemons at boot - MAG +		 */ + +		/* Stat for vtysh Zebra.conf, if found startup and wait for +		 * boot configuration +		 */ + +		if (strstr(config_default_dir, "vtysh") == NULL) { +			ret = stat(integrate_default, &conf_stat); +			if (ret >= 0) +				goto tmp_free_and_out; +		}  #endif /* VTYSH */ -      confp = fopen (config_default_dir, "r"); -      if (confp == NULL) -        { -          fprintf (stderr, "%s: failed to open configuration file %s: %s\n", -                   __func__, config_default_dir, safe_strerror (errno)); - -          confp = vty_use_backup_config (config_default_dir); -          if (confp) -            { -              fprintf (stderr, "WARNING: using backup configuration file!\n"); -              fullpath = config_default_dir; -            } -          else -            { -              fprintf (stderr, "can't open configuration file [%s]\n", -                       config_default_dir); -              goto tmp_free_and_out; -            } -        } -      else -        fullpath = config_default_dir; -    } - -  vty_read_file (confp); - -  fclose (confp); - -  host_config_set (fullpath); +		confp = fopen(config_default_dir, "r"); +		if (confp == NULL) { +			fprintf(stderr, +				"%s: failed to open configuration file %s: %s\n", +				__func__, config_default_dir, +				safe_strerror(errno)); + +			confp = vty_use_backup_config(config_default_dir); +			if (confp) { +				fprintf(stderr, +					"WARNING: using backup configuration file!\n"); +				fullpath = config_default_dir; +			} else { +				fprintf(stderr, +					"can't open configuration file [%s]\n", +					config_default_dir); +				goto tmp_free_and_out; +			} +		} else +			fullpath = config_default_dir; +	} + +	vty_read_file(confp); + +	fclose(confp); + +	host_config_set(fullpath);  tmp_free_and_out: -  if (tmp) -    XFREE (MTYPE_TMP, tmp); +	if (tmp) +		XFREE(MTYPE_TMP, tmp);  }  /* Small utility function which output log to the VTY. */ -void -vty_log (const char *level, const char *proto_str, -         const char *format, struct timestamp_control *ctl, va_list va) +void vty_log(const char *level, const char *proto_str, const char *format, +	     struct timestamp_control *ctl, va_list va)  { -  unsigned int i; -  struct vty *vty; +	unsigned int i; +	struct vty *vty; -  if (!vtyvec) -    return; +	if (!vtyvec) +		return; -  for (i = 0; i < vector_active (vtyvec); i++) -    if ((vty = vector_slot (vtyvec, i)) != NULL) -      if (vty->monitor) -        { -          va_list ac; -          va_copy(ac, va); -          vty_log_out (vty, level, proto_str, format, ctl, ac); -          va_end(ac); -        } +	for (i = 0; i < vector_active(vtyvec); i++) +		if ((vty = vector_slot(vtyvec, i)) != NULL) +			if (vty->monitor) { +				va_list ac; +				va_copy(ac, va); +				vty_log_out(vty, level, proto_str, format, ctl, +					    ac); +				va_end(ac); +			}  }  /* Async-signal-safe version of vty_log for fixed strings. */ -void -vty_log_fixed (char *buf, size_t len) +void vty_log_fixed(char *buf, size_t len)  { -  unsigned int i; -  struct iovec iov[2]; -  char crlf[4] = "\r\n"; +	unsigned int i; +	struct iovec iov[2]; +	char crlf[4] = "\r\n"; -  /* vty may not have been initialised */ -  if (!vtyvec) -    return; +	/* vty may not have been initialised */ +	if (!vtyvec) +		return; -  iov[0].iov_base = buf; -  iov[0].iov_len = len; -  iov[1].iov_base = crlf; -  iov[1].iov_len = 2; +	iov[0].iov_base = buf; +	iov[0].iov_len = len; +	iov[1].iov_base = crlf; +	iov[1].iov_len = 2; -  for (i = 0; i < vector_active (vtyvec); i++) -    { -      struct vty *vty; -      if (((vty = vector_slot (vtyvec, i)) != NULL) && vty->monitor) -        /* N.B. We don't care about the return code, since process is -           most likely just about to die anyway. */ -        if (writev(vty->wfd, iov, 2) == -1) -          { -            fprintf(stderr, "Failure to writev: %d\n", errno); -            exit(-1); -          } -    } +	for (i = 0; i < vector_active(vtyvec); i++) { +		struct vty *vty; +		if (((vty = vector_slot(vtyvec, i)) != NULL) && vty->monitor) +			/* N.B. We don't care about the return code, since +			   process is +			   most likely just about to die anyway. */ +			if (writev(vty->wfd, iov, 2) == -1) { +				fprintf(stderr, "Failure to writev: %d\n", +					errno); +				exit(-1); +			} +	}  } -int -vty_config_lock (struct vty *vty) +int vty_config_lock(struct vty *vty)  { -  if (vty_config_is_lockless) -    return 1; -  if (vty_config == 0) -    { -      vty->config = 1; -      vty_config = 1; -    } -  return vty->config; +	if (vty_config_is_lockless) +		return 1; +	if (vty_config == 0) { +		vty->config = 1; +		vty_config = 1; +	} +	return vty->config;  } -int -vty_config_unlock (struct vty *vty) +int vty_config_unlock(struct vty *vty)  { -  if (vty_config_is_lockless) -    return 0; -  if (vty_config == 1 && vty->config == 1) -    { -      vty->config = 0; -      vty_config = 0; -    } -  return vty->config; +	if (vty_config_is_lockless) +		return 0; +	if (vty_config == 1 && vty->config == 1) { +		vty->config = 0; +		vty_config = 0; +	} +	return vty->config;  } -void -vty_config_lockless (void) +void vty_config_lockless(void)  { -  vty_config_is_lockless = 1; +	vty_config_is_lockless = 1;  }  /* Master of the threads. */  static struct thread_master *vty_master; -static void -vty_event (enum event event, int sock, struct vty *vty) +static void vty_event(enum event event, int sock, struct vty *vty)  { -  struct thread *vty_serv_thread; +	struct thread *vty_serv_thread; -  switch (event) -    { -    case VTY_SERV: -      vty_serv_thread = thread_add_read (vty_master, vty_accept, vty, sock); -      vector_set_index (Vvty_serv_thread, sock, vty_serv_thread); -      break; +	switch (event) { +	case VTY_SERV: +		vty_serv_thread = +			thread_add_read(vty_master, vty_accept, vty, sock); +		vector_set_index(Vvty_serv_thread, sock, vty_serv_thread); +		break;  #ifdef VTYSH -    case VTYSH_SERV: -      vty_serv_thread = thread_add_read (vty_master, vtysh_accept, vty, sock); -      vector_set_index (Vvty_serv_thread, sock, vty_serv_thread); -      break; -    case VTYSH_READ: -      vty->t_read = thread_add_read (vty_master, vtysh_read, vty, sock); -      break; -    case VTYSH_WRITE: -      vty->t_write = thread_add_write (vty_master, vtysh_write, vty, sock); -      break; +	case VTYSH_SERV: +		vty_serv_thread = +			thread_add_read(vty_master, vtysh_accept, vty, sock); +		vector_set_index(Vvty_serv_thread, sock, vty_serv_thread); +		break; +	case VTYSH_READ: +		vty->t_read = +			thread_add_read(vty_master, vtysh_read, vty, sock); +		break; +	case VTYSH_WRITE: +		vty->t_write = +			thread_add_write(vty_master, vtysh_write, vty, sock); +		break;  #endif /* VTYSH */ -    case VTY_READ: -      vty->t_read = thread_add_read (vty_master, vty_read, vty, sock); - -      /* Time out treatment. */ -      if (vty->v_timeout) -        { -          if (vty->t_timeout) -            thread_cancel (vty->t_timeout); -          vty->t_timeout = -            thread_add_timer (vty_master, vty_timeout, vty, vty->v_timeout); -        } -      break; -    case VTY_WRITE: -      if (! vty->t_write) -        vty->t_write = thread_add_write (vty_master, vty_flush, vty, sock); -      break; -    case VTY_TIMEOUT_RESET: -      if (vty->t_timeout) -        { -          thread_cancel (vty->t_timeout); -          vty->t_timeout = NULL; -        } -      if (vty->v_timeout) -        { -          vty->t_timeout = -            thread_add_timer (vty_master, vty_timeout, vty, vty->v_timeout); -        } -      break; -    } +	case VTY_READ: +		vty->t_read = thread_add_read(vty_master, vty_read, vty, sock); + +		/* Time out treatment. */ +		if (vty->v_timeout) { +			if (vty->t_timeout) +				thread_cancel(vty->t_timeout); +			vty->t_timeout = thread_add_timer( +				vty_master, vty_timeout, vty, vty->v_timeout); +		} +		break; +	case VTY_WRITE: +		if (!vty->t_write) +			vty->t_write = thread_add_write(vty_master, vty_flush, +							vty, sock); +		break; +	case VTY_TIMEOUT_RESET: +		if (vty->t_timeout) { +			thread_cancel(vty->t_timeout); +			vty->t_timeout = NULL; +		} +		if (vty->v_timeout) { +			vty->t_timeout = thread_add_timer( +				vty_master, vty_timeout, vty, vty->v_timeout); +		} +		break; +	}  }  DEFUN_NOSH (config_who, @@ -2671,15 +2514,15 @@ DEFUN_NOSH (config_who,         "who",         "Display who is on vty\n")  { -  unsigned int i; -  struct vty *v; +	unsigned int i; +	struct vty *v; -  for (i = 0; i < vector_active (vtyvec); i++) -    if ((v = vector_slot (vtyvec, i)) != NULL) -      vty_out (vty, "%svty[%d] connected from %s.%s", -               v->config ? "*" : " ", -               i, v->address, VTY_NEWLINE); -  return CMD_SUCCESS; +	for (i = 0; i < vector_active(vtyvec); i++) +		if ((v = vector_slot(vtyvec, i)) != NULL) +			vty_out(vty, "%svty[%d] connected from %s.%s", +				v->config ? "*" : " ", i, v->address, +				VTY_NEWLINE); +	return CMD_SUCCESS;  }  /* Move to vty configuration mode. */ @@ -2689,32 +2532,31 @@ DEFUN_NOSH (line_vty,         "Configure a terminal line\n"         "Virtual terminal\n")  { -  vty->node = VTY_NODE; -  return CMD_SUCCESS; +	vty->node = VTY_NODE; +	return CMD_SUCCESS;  }  /* Set time out value. */ -static int -exec_timeout (struct vty *vty, const char *min_str, const char *sec_str) +static int exec_timeout(struct vty *vty, const char *min_str, +			const char *sec_str)  { -  unsigned long timeout = 0; +	unsigned long timeout = 0; -  /* min_str and sec_str are already checked by parser.  So it must be -     all digit string. */ -  if (min_str) -    { -      timeout = strtol (min_str, NULL, 10); -      timeout *= 60; -    } -  if (sec_str) -    timeout += strtol (sec_str, NULL, 10); +	/* min_str and sec_str are already checked by parser.  So it must be +	   all digit string. */ +	if (min_str) { +		timeout = strtol(min_str, NULL, 10); +		timeout *= 60; +	} +	if (sec_str) +		timeout += strtol(sec_str, NULL, 10); -  vty_timeout_val = timeout; -  vty->v_timeout = timeout; -  vty_event (VTY_TIMEOUT_RESET, 0, vty); +	vty_timeout_val = timeout; +	vty->v_timeout = timeout; +	vty_event(VTY_TIMEOUT_RESET, 0, vty); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  DEFUN (exec_timeout_min, @@ -2723,8 +2565,8 @@ DEFUN (exec_timeout_min,         "Set timeout value\n"         "Timeout value in minutes\n")  { -  int idx_number = 1; -  return exec_timeout (vty, argv[idx_number]->arg, NULL); +	int idx_number = 1; +	return exec_timeout(vty, argv[idx_number]->arg, NULL);  }  DEFUN (exec_timeout_sec, @@ -2734,9 +2576,10 @@ DEFUN (exec_timeout_sec,         "Timeout in minutes\n"         "Timeout in seconds\n")  { -  int idx_number = 1; -  int idx_number_2 = 2; -  return exec_timeout (vty, argv[idx_number]->arg, argv[idx_number_2]->arg); +	int idx_number = 1; +	int idx_number_2 = 2; +	return exec_timeout(vty, argv[idx_number]->arg, +			    argv[idx_number_2]->arg);  }  DEFUN (no_exec_timeout, @@ -2745,7 +2588,7 @@ DEFUN (no_exec_timeout,         NO_STR         "Set the EXEC timeout\n")  { -  return exec_timeout (vty, NULL, NULL); +	return exec_timeout(vty, NULL, NULL);  }  /* Set vty access class. */ @@ -2755,13 +2598,13 @@ DEFUN (vty_access_class,         "Filter connections based on an IP access list\n"         "IP access list\n")  { -  int idx_word = 1; -  if (vty_accesslist_name) -    XFREE(MTYPE_VTY, vty_accesslist_name); +	int idx_word = 1; +	if (vty_accesslist_name) +		XFREE(MTYPE_VTY, vty_accesslist_name); -  vty_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg); +	vty_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* Clear vty access class. */ @@ -2772,20 +2615,20 @@ DEFUN (no_vty_access_class,         "Filter connections based on an IP access list\n"         "IP access list\n")  { -  int idx_word = 2; -  const char *accesslist = (argc == 3) ? argv[idx_word]->arg : NULL; -  if (! vty_accesslist_name || (argc == 3 && strcmp(vty_accesslist_name, accesslist))) -    { -      vty_out (vty, "Access-class is not currently applied to vty%s", -               VTY_NEWLINE); -      return CMD_WARNING; -    } +	int idx_word = 2; +	const char *accesslist = (argc == 3) ? argv[idx_word]->arg : NULL; +	if (!vty_accesslist_name +	    || (argc == 3 && strcmp(vty_accesslist_name, accesslist))) { +		vty_out(vty, "Access-class is not currently applied to vty%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  XFREE(MTYPE_VTY, vty_accesslist_name); +	XFREE(MTYPE_VTY, vty_accesslist_name); -  vty_accesslist_name = NULL; +	vty_accesslist_name = NULL; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* Set vty access class. */ @@ -2796,13 +2639,13 @@ DEFUN (vty_ipv6_access_class,         "Filter connections based on an IP access list\n"         "IPv6 access list\n")  { -  int idx_word = 2; -  if (vty_ipv6_accesslist_name) -    XFREE(MTYPE_VTY, vty_ipv6_accesslist_name); +	int idx_word = 2; +	if (vty_ipv6_accesslist_name) +		XFREE(MTYPE_VTY, vty_ipv6_accesslist_name); -  vty_ipv6_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg); +	vty_ipv6_accesslist_name = XSTRDUP(MTYPE_VTY, argv[idx_word]->arg); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* Clear vty access class. */ @@ -2814,22 +2657,22 @@ DEFUN (no_vty_ipv6_access_class,         "Filter connections based on an IP access list\n"         "IPv6 access list\n")  { -  int idx_word = 3; -  const char *accesslist = (argc == 4) ? argv[idx_word]->arg : NULL; +	int idx_word = 3; +	const char *accesslist = (argc == 4) ? argv[idx_word]->arg : NULL; -  if (! vty_ipv6_accesslist_name || -      (argc == 4 && strcmp(vty_ipv6_accesslist_name, accesslist))) -    { -      vty_out (vty, "IPv6 access-class is not currently applied to vty%s", -               VTY_NEWLINE); -      return CMD_WARNING; -    } +	if (!vty_ipv6_accesslist_name +	    || (argc == 4 && strcmp(vty_ipv6_accesslist_name, accesslist))) { +		vty_out(vty, +			"IPv6 access-class is not currently applied to vty%s", +			VTY_NEWLINE); +		return CMD_WARNING; +	} -  XFREE(MTYPE_VTY, vty_ipv6_accesslist_name); +	XFREE(MTYPE_VTY, vty_ipv6_accesslist_name); -  vty_ipv6_accesslist_name = NULL; +	vty_ipv6_accesslist_name = NULL; -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* vty login. */ @@ -2838,8 +2681,8 @@ DEFUN (vty_login,         "login",         "Enable password checking\n")  { -  no_password_check = 0; -  return CMD_SUCCESS; +	no_password_check = 0; +	return CMD_SUCCESS;  }  DEFUN (no_vty_login, @@ -2848,8 +2691,8 @@ DEFUN (no_vty_login,         NO_STR         "Enable password checking\n")  { -  no_password_check = 1; -  return CMD_SUCCESS; +	no_password_check = 1; +	return CMD_SUCCESS;  }  DEFUN (service_advanced_vty, @@ -2858,8 +2701,8 @@ DEFUN (service_advanced_vty,         "Set up miscellaneous service\n"         "Enable advanced mode vty interface\n")  { -  host.advanced = 1; -  return CMD_SUCCESS; +	host.advanced = 1; +	return CMD_SUCCESS;  }  DEFUN (no_service_advanced_vty, @@ -2869,8 +2712,8 @@ DEFUN (no_service_advanced_vty,         "Set up miscellaneous service\n"         "Enable advanced mode vty interface\n")  { -  host.advanced = 0; -  return CMD_SUCCESS; +	host.advanced = 0; +	return CMD_SUCCESS;  }  DEFUN_NOSH (terminal_monitor, @@ -2879,8 +2722,8 @@ DEFUN_NOSH (terminal_monitor,         "Set terminal line parameters\n"         "Copy debug output to the current terminal line\n")  { -  vty->monitor = 1; -  return CMD_SUCCESS; +	vty->monitor = 1; +	return CMD_SUCCESS;  }  DEFUN_NOSH (terminal_no_monitor, @@ -2890,8 +2733,8 @@ DEFUN_NOSH (terminal_no_monitor,         NO_STR         "Copy debug output to the current terminal line\n")  { -  vty->monitor = 0; -  return CMD_SUCCESS; +	vty->monitor = 0; +	return CMD_SUCCESS;  }  DEFUN_NOSH (no_terminal_monitor, @@ -2901,7 +2744,7 @@ DEFUN_NOSH (no_terminal_monitor,         "Set terminal line parameters\n"         "Copy debug output to the current terminal line\n")  { -  return terminal_no_monitor (self, vty, argc, argv); +	return terminal_no_monitor(self, vty, argc, argv);  } @@ -2911,23 +2754,21 @@ DEFUN_NOSH (show_history,         SHOW_STR         "Display the session command history\n")  { -  int index; +	int index; -  for (index = vty->hindex + 1; index != vty->hindex;) -    { -      if (index == VTY_MAXHIST) -        { -          index = 0; -          continue; -        } +	for (index = vty->hindex + 1; index != vty->hindex;) { +		if (index == VTY_MAXHIST) { +			index = 0; +			continue; +		} -      if (vty->hist[index] != NULL) -        vty_out (vty, "  %s%s", vty->hist[index], VTY_NEWLINE); +		if (vty->hist[index] != NULL) +			vty_out(vty, "  %s%s", vty->hist[index], VTY_NEWLINE); -      index++; -    } +		index++; +	} -  return CMD_SUCCESS; +	return CMD_SUCCESS;  }  /* vty login. */ @@ -2937,223 +2778,201 @@ DEFUN (log_commands,         "Logging control\n"         "Log all commands (can't be unset without restart)\n")  { -  do_log_commands = 1; -  return CMD_SUCCESS; +	do_log_commands = 1; +	return CMD_SUCCESS;  }  /* Display current configuration. */ -static int -vty_config_write (struct vty *vty) +static int vty_config_write(struct vty *vty)  { -  vty_out (vty, "line vty%s", VTY_NEWLINE); +	vty_out(vty, "line vty%s", VTY_NEWLINE); -  if (vty_accesslist_name) -    vty_out (vty, " access-class %s%s", -             vty_accesslist_name, VTY_NEWLINE); +	if (vty_accesslist_name) +		vty_out(vty, " access-class %s%s", vty_accesslist_name, +			VTY_NEWLINE); -  if (vty_ipv6_accesslist_name) -    vty_out (vty, " ipv6 access-class %s%s", -             vty_ipv6_accesslist_name, VTY_NEWLINE); +	if (vty_ipv6_accesslist_name) +		vty_out(vty, " ipv6 access-class %s%s", +			vty_ipv6_accesslist_name, VTY_NEWLINE); -  /* exec-timeout */ -  if (vty_timeout_val != VTY_TIMEOUT_DEFAULT) -    vty_out (vty, " exec-timeout %ld %ld%s", -             vty_timeout_val / 60, -             vty_timeout_val % 60, VTY_NEWLINE); +	/* exec-timeout */ +	if (vty_timeout_val != VTY_TIMEOUT_DEFAULT) +		vty_out(vty, " exec-timeout %ld %ld%s", vty_timeout_val / 60, +			vty_timeout_val % 60, VTY_NEWLINE); -  /* login */ -  if (no_password_check) -    vty_out (vty, " no login%s", VTY_NEWLINE); +	/* login */ +	if (no_password_check) +		vty_out(vty, " no login%s", VTY_NEWLINE); -  if (do_log_commands) -    vty_out (vty, "log commands%s", VTY_NEWLINE); +	if (do_log_commands) +		vty_out(vty, "log commands%s", VTY_NEWLINE); -  vty_out (vty, "!%s", VTY_NEWLINE); +	vty_out(vty, "!%s", VTY_NEWLINE); -  return CMD_SUCCESS; +	return CMD_SUCCESS;  } -struct cmd_node vty_node = -{ -  VTY_NODE, -  "%s(config-line)# ", -  1, +struct cmd_node vty_node = { +	VTY_NODE, "%s(config-line)# ", 1,  };  /* Reset all VTY status. */ -void -vty_reset () -{ -  unsigned int i; -  struct vty *vty; -  struct thread *vty_serv_thread; - -  for (i = 0; i < vector_active (vtyvec); i++) -    if ((vty = vector_slot (vtyvec, i)) != NULL) -      { -        buffer_reset (vty->obuf); -        vty->status = VTY_CLOSE; -        vty_close (vty); -      } - -  for (i = 0; i < vector_active (Vvty_serv_thread); i++) -    if ((vty_serv_thread = vector_slot (Vvty_serv_thread, i)) != NULL) -      { -        thread_cancel (vty_serv_thread); -        vector_slot (Vvty_serv_thread, i) = NULL; -        close (i); -      } - -  vty_timeout_val = VTY_TIMEOUT_DEFAULT; - -  if (vty_accesslist_name) -    { -      XFREE(MTYPE_VTY, vty_accesslist_name); -      vty_accesslist_name = NULL; -    } - -  if (vty_ipv6_accesslist_name) -    { -      XFREE(MTYPE_VTY, vty_ipv6_accesslist_name); -      vty_ipv6_accesslist_name = NULL; -    } +void vty_reset() +{ +	unsigned int i; +	struct vty *vty; +	struct thread *vty_serv_thread; + +	for (i = 0; i < vector_active(vtyvec); i++) +		if ((vty = vector_slot(vtyvec, i)) != NULL) { +			buffer_reset(vty->obuf); +			vty->status = VTY_CLOSE; +			vty_close(vty); +		} + +	for (i = 0; i < vector_active(Vvty_serv_thread); i++) +		if ((vty_serv_thread = vector_slot(Vvty_serv_thread, i)) +		    != NULL) { +			thread_cancel(vty_serv_thread); +			vector_slot(Vvty_serv_thread, i) = NULL; +			close(i); +		} + +	vty_timeout_val = VTY_TIMEOUT_DEFAULT; + +	if (vty_accesslist_name) { +		XFREE(MTYPE_VTY, vty_accesslist_name); +		vty_accesslist_name = NULL; +	} + +	if (vty_ipv6_accesslist_name) { +		XFREE(MTYPE_VTY, vty_ipv6_accesslist_name); +		vty_ipv6_accesslist_name = NULL; +	}  } -static void -vty_save_cwd (void) +static void vty_save_cwd(void)  { -  char cwd[MAXPATHLEN]; -  char *c; +	char cwd[MAXPATHLEN]; +	char *c; -  c = getcwd (cwd, MAXPATHLEN); +	c = getcwd(cwd, MAXPATHLEN); -  if (!c) -    { -      /* -       * At this point if these go wrong, more than likely -       * the whole world is coming down around us -       * Hence not worrying about it too much. -       */ -      if (!chdir (SYSCONFDIR)) -        { -          fprintf(stderr, "Failure to chdir to %s, errno: %d\n", SYSCONFDIR, errno); -          exit(-1); -        } -      if (getcwd (cwd, MAXPATHLEN) == NULL) -        { -          fprintf(stderr, "Failure to getcwd, errno: %d\n", errno); -          exit(-1); -        } -    } +	if (!c) { +		/* +		 * At this point if these go wrong, more than likely +		 * the whole world is coming down around us +		 * Hence not worrying about it too much. +		 */ +		if (!chdir(SYSCONFDIR)) { +			fprintf(stderr, "Failure to chdir to %s, errno: %d\n", +				SYSCONFDIR, errno); +			exit(-1); +		} +		if (getcwd(cwd, MAXPATHLEN) == NULL) { +			fprintf(stderr, "Failure to getcwd, errno: %d\n", +				errno); +			exit(-1); +		} +	} -  vty_cwd = XMALLOC (MTYPE_TMP, strlen (cwd) + 1); -  strcpy (vty_cwd, cwd); +	vty_cwd = XMALLOC(MTYPE_TMP, strlen(cwd) + 1); +	strcpy(vty_cwd, cwd);  } -char * -vty_get_cwd () +char *vty_get_cwd()  { -  return vty_cwd; +	return vty_cwd;  } -int -vty_shell (struct vty *vty) +int vty_shell(struct vty *vty)  { -  return vty->type == VTY_SHELL ? 1 : 0; +	return vty->type == VTY_SHELL ? 1 : 0;  } -int -vty_shell_serv (struct vty *vty) +int vty_shell_serv(struct vty *vty)  { -  return vty->type == VTY_SHELL_SERV ? 1 : 0; +	return vty->type == VTY_SHELL_SERV ? 1 : 0;  } -void -vty_init_vtysh () +void vty_init_vtysh()  { -  vtyvec = vector_init (VECTOR_MIN_SIZE); +	vtyvec = vector_init(VECTOR_MIN_SIZE);  }  /* Install vty's own commands like `who' command. */ -void -vty_init (struct thread_master *master_thread) +void vty_init(struct thread_master *master_thread)  { -  /* For further configuration read, preserve current directory. */ -  vty_save_cwd (); +	/* For further configuration read, preserve current directory. */ +	vty_save_cwd(); -  vtyvec = vector_init (VECTOR_MIN_SIZE); +	vtyvec = vector_init(VECTOR_MIN_SIZE); -  vty_master = master_thread; +	vty_master = master_thread; -  atexit (vty_stdio_reset); +	atexit(vty_stdio_reset); -  /* Initilize server thread vector. */ -  Vvty_serv_thread = vector_init (VECTOR_MIN_SIZE); +	/* Initilize server thread vector. */ +	Vvty_serv_thread = vector_init(VECTOR_MIN_SIZE); -  /* Install bgp top node. */ -  install_node (&vty_node, vty_config_write); +	/* Install bgp top node. */ +	install_node(&vty_node, vty_config_write); -  install_element (VIEW_NODE, &config_who_cmd); -  install_element (VIEW_NODE, &show_history_cmd); -  install_element (CONFIG_NODE, &line_vty_cmd); -  install_element (CONFIG_NODE, &service_advanced_vty_cmd); -  install_element (CONFIG_NODE, &no_service_advanced_vty_cmd); -  install_element (CONFIG_NODE, &show_history_cmd); -  install_element (CONFIG_NODE, &log_commands_cmd); -  install_element (ENABLE_NODE, &terminal_monitor_cmd); -  install_element (ENABLE_NODE, &terminal_no_monitor_cmd); -  install_element (ENABLE_NODE, &no_terminal_monitor_cmd); +	install_element(VIEW_NODE, &config_who_cmd); +	install_element(VIEW_NODE, &show_history_cmd); +	install_element(CONFIG_NODE, &line_vty_cmd); +	install_element(CONFIG_NODE, &service_advanced_vty_cmd); +	install_element(CONFIG_NODE, &no_service_advanced_vty_cmd); +	install_element(CONFIG_NODE, &show_history_cmd); +	install_element(CONFIG_NODE, &log_commands_cmd); +	install_element(ENABLE_NODE, &terminal_monitor_cmd); +	install_element(ENABLE_NODE, &terminal_no_monitor_cmd); +	install_element(ENABLE_NODE, &no_terminal_monitor_cmd); -  install_default (VTY_NODE); -  install_element (VTY_NODE, &exec_timeout_min_cmd); -  install_element (VTY_NODE, &exec_timeout_sec_cmd); -  install_element (VTY_NODE, &no_exec_timeout_cmd); -  install_element (VTY_NODE, &vty_access_class_cmd); -  install_element (VTY_NODE, &no_vty_access_class_cmd); -  install_element (VTY_NODE, &vty_login_cmd); -  install_element (VTY_NODE, &no_vty_login_cmd); -  install_element (VTY_NODE, &vty_ipv6_access_class_cmd); -  install_element (VTY_NODE, &no_vty_ipv6_access_class_cmd); +	install_default(VTY_NODE); +	install_element(VTY_NODE, &exec_timeout_min_cmd); +	install_element(VTY_NODE, &exec_timeout_sec_cmd); +	install_element(VTY_NODE, &no_exec_timeout_cmd); +	install_element(VTY_NODE, &vty_access_class_cmd); +	install_element(VTY_NODE, &no_vty_access_class_cmd); +	install_element(VTY_NODE, &vty_login_cmd); +	install_element(VTY_NODE, &no_vty_login_cmd); +	install_element(VTY_NODE, &vty_ipv6_access_class_cmd); +	install_element(VTY_NODE, &no_vty_ipv6_access_class_cmd);  } -void -vty_terminate (void) +void vty_terminate(void)  { -  if (vty_cwd) -    XFREE (MTYPE_TMP, vty_cwd); +	if (vty_cwd) +		XFREE(MTYPE_TMP, vty_cwd); -  if (vtyvec && Vvty_serv_thread) -    { -      vty_reset (); -      vector_free (vtyvec); -      vector_free (Vvty_serv_thread); -      vtyvec = NULL; -      Vvty_serv_thread = NULL; -    } +	if (vtyvec && Vvty_serv_thread) { +		vty_reset(); +		vector_free(vtyvec); +		vector_free(Vvty_serv_thread); +		vtyvec = NULL; +		Vvty_serv_thread = NULL; +	}  }  /* Utility functions to get arguments from commands generated     by the xml2cli.pl script. */ -const char * -vty_get_arg_value (struct vty_arg *args[], const char *arg) -{ -  while (*args) -    { -      if (strcmp ((*args)->name, arg) == 0) -        return (*args)->value; -      args++; -    } -  return NULL; -} - -struct vty_arg * -vty_get_arg (struct vty_arg *args[], const char *arg) -{ -  while (*args) -    { -      if (strcmp ((*args)->name, arg) == 0) -        return *args; -      args++; -    } -  return NULL; +const char *vty_get_arg_value(struct vty_arg *args[], const char *arg) +{ +	while (*args) { +		if (strcmp((*args)->name, arg) == 0) +			return (*args)->value; +		args++; +	} +	return NULL; +} + +struct vty_arg *vty_get_arg(struct vty_arg *args[], const char *arg) +{ +	while (*args) { +		if (strcmp((*args)->name, arg) == 0) +			return *args; +		args++; +	} +	return NULL;  } @@ -30,150 +30,149 @@ Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  #define VTY_MAXHIST 20  /* VTY struct. */ -struct vty  -{ -  /* File descripter of this vty. */ -  int fd; +struct vty { +	/* File descripter of this vty. */ +	int fd; -  /* output FD, to support stdin/stdout combination */ -  int wfd; +	/* output FD, to support stdin/stdout combination */ +	int wfd; -  /* Is this vty connect to file or not */ -  enum {VTY_TERM, VTY_FILE, VTY_SHELL, VTY_SHELL_SERV} type; +	/* Is this vty connect to file or not */ +	enum { VTY_TERM, VTY_FILE, VTY_SHELL, VTY_SHELL_SERV } type; -  /* Node status of this vty */ -  int node; +	/* Node status of this vty */ +	int node; -  /* Failure count */ -  int fail; +	/* Failure count */ +	int fail; -  /* Output buffer. */ -  struct buffer *obuf; +	/* Output buffer. */ +	struct buffer *obuf; -  /* Command input buffer */ -  char *buf; +	/* Command input buffer */ +	char *buf; -  /* Command input error buffer */ -  char *error_buf; +	/* Command input error buffer */ +	char *error_buf; -  /* Command cursor point */ -  int cp; +	/* Command cursor point */ +	int cp; -  /* Command length */ -  int length; +	/* Command length */ +	int length; -  /* Command max length. */ -  int max; +	/* Command max length. */ +	int max; -  /* Histry of command */ -  char *hist[VTY_MAXHIST]; +	/* Histry of command */ +	char *hist[VTY_MAXHIST]; -  /* History lookup current point */ -  int hp; +	/* History lookup current point */ +	int hp; -  /* History insert end point */ -  int hindex; +	/* History insert end point */ +	int hindex; -  /* qobj object ID (replacement for "index") */ -  uint64_t qobj_index; +	/* qobj object ID (replacement for "index") */ +	uint64_t qobj_index; -  /* qobj second-level object ID (replacement for "index_sub") */ -  uint64_t qobj_index_sub; +	/* qobj second-level object ID (replacement for "index_sub") */ +	uint64_t qobj_index_sub; -  /* For escape character. */ -  unsigned char escape; +	/* For escape character. */ +	unsigned char escape; -  /* Current vty status. */ -  enum {VTY_NORMAL, VTY_CLOSE, VTY_MORE, VTY_MORELINE} status; +	/* Current vty status. */ +	enum { VTY_NORMAL, VTY_CLOSE, VTY_MORE, VTY_MORELINE } status; -  /* IAC handling: was the last character received the -     IAC (interpret-as-command) escape character (and therefore the next -     character will be the command code)?  Refer to Telnet RFC 854. */ -  unsigned char iac; +	/* IAC handling: was the last character received the +	   IAC (interpret-as-command) escape character (and therefore the next +	   character will be the command code)?  Refer to Telnet RFC 854. */ +	unsigned char iac; -  /* IAC SB (option subnegotiation) handling */ -  unsigned char iac_sb_in_progress; -  /* At the moment, we care only about the NAWS (window size) negotiation, -     and that requires just a 5-character buffer (RFC 1073): -       <NAWS char> <16-bit width> <16-bit height> */ +	/* IAC SB (option subnegotiation) handling */ +	unsigned char iac_sb_in_progress; +/* At the moment, we care only about the NAWS (window size) negotiation, +   and that requires just a 5-character buffer (RFC 1073): +     <NAWS char> <16-bit width> <16-bit height> */  #define TELNET_NAWS_SB_LEN 5 -  unsigned char sb_buf[TELNET_NAWS_SB_LEN]; -  /* How many subnegotiation characters have we received?  We just drop -     those that do not fit in the buffer. */ -  size_t sb_len; +	unsigned char sb_buf[TELNET_NAWS_SB_LEN]; +	/* How many subnegotiation characters have we received?  We just drop +	   those that do not fit in the buffer. */ +	size_t sb_len; -  /* Window width/height. */ -  int width; -  int height; +	/* Window width/height. */ +	int width; +	int height; -  /* Configure lines. */ -  int lines; +	/* Configure lines. */ +	int lines; -  /* Terminal monitor. */ -  int monitor; +	/* Terminal monitor. */ +	int monitor; -  /* In configure mode. */ -  int config; +	/* In configure mode. */ +	int config; -  /* Read and write thread. */ -  struct thread *t_read; -  struct thread *t_write; +	/* Read and write thread. */ +	struct thread *t_read; +	struct thread *t_write; -  /* Timeout seconds and thread. */ -  unsigned long v_timeout; -  struct thread *t_timeout; +	/* Timeout seconds and thread. */ +	unsigned long v_timeout; +	struct thread *t_timeout; -  /* What address is this vty comming from. */ -  char address[SU_ADDRSTRLEN]; +	/* What address is this vty comming from. */ +	char address[SU_ADDRSTRLEN];  }; -static inline void vty_push_context(struct vty *vty, -                                    int node, uint64_t id) +static inline void vty_push_context(struct vty *vty, int node, uint64_t id)  { -  vty->node = node; -  vty->qobj_index = id; +	vty->node = node; +	vty->qobj_index = id;  }  /* note: VTY_PUSH_CONTEXT(..., NULL) doesn't work, since it will try to   * dereference "NULL->qobj_node.nid" */ -#define VTY_PUSH_CONTEXT(nodeval, ptr) \ +#define VTY_PUSH_CONTEXT(nodeval, ptr)                                         \  	vty_push_context(vty, nodeval, QOBJ_ID_0SAFE(ptr)) -#define VTY_PUSH_CONTEXT_NULL(nodeval) \ -	vty_push_context(vty, nodeval, 0ULL) -#define VTY_PUSH_CONTEXT_SUB(nodeval, ptr) do { \ -		vty->node = nodeval; \ -		/* qobj_index stays untouched */ \ -		vty->qobj_index_sub = QOBJ_ID_0SAFE(ptr); \ +#define VTY_PUSH_CONTEXT_NULL(nodeval) vty_push_context(vty, nodeval, 0ULL) +#define VTY_PUSH_CONTEXT_SUB(nodeval, ptr)                                     \ +	do {                                                                   \ +		vty->node = nodeval;                                           \ +		/* qobj_index stays untouched */                               \ +		vty->qobj_index_sub = QOBJ_ID_0SAFE(ptr);                      \  	} while (0)  /* can return NULL if context is invalid! */ -#define VTY_GET_CONTEXT(structname) \ +#define VTY_GET_CONTEXT(structname)                                            \  	QOBJ_GET_TYPESAFE(vty->qobj_index, structname) -#define VTY_GET_CONTEXT_SUB(structname) \ +#define VTY_GET_CONTEXT_SUB(structname)                                        \  	QOBJ_GET_TYPESAFE(vty->qobj_index_sub, structname)  /* will return if ptr is NULL. */ -#define VTY_CHECK_CONTEXT(ptr) \ -	if (!ptr) { \ -		vty_out (vty, "Current configuration object was deleted " \ -				"by another process.%s", VTY_NEWLINE); \ -		return CMD_WARNING; \ +#define VTY_CHECK_CONTEXT(ptr)                                                 \ +	if (!ptr) {                                                            \ +		vty_out(vty,                                                   \ +			"Current configuration object was deleted "            \ +			"by another process.%s",                               \ +			VTY_NEWLINE);                                          \ +		return CMD_WARNING;                                            \  	}  /* struct structname *ptr = <context>;   ptr will never be NULL. */ -#define VTY_DECLVAR_CONTEXT(structname, ptr) \ -	struct structname *ptr = VTY_GET_CONTEXT(structname); \ +#define VTY_DECLVAR_CONTEXT(structname, ptr)                                   \ +	struct structname *ptr = VTY_GET_CONTEXT(structname);                  \  	VTY_CHECK_CONTEXT(ptr); -#define VTY_DECLVAR_CONTEXT_SUB(structname, ptr) \ -	struct structname *ptr = VTY_GET_CONTEXT_SUB(structname); \ +#define VTY_DECLVAR_CONTEXT_SUB(structname, ptr)                               \ +	struct structname *ptr = VTY_GET_CONTEXT_SUB(structname);              \  	VTY_CHECK_CONTEXT(ptr); -struct vty_arg -{ -  const char *name; -  const char *value; -  const char **argv; -  int argc; +struct vty_arg { +	const char *name; +	const char *value; +	const char **argv; +	int argc;  };  /* Integrated configuration file. */ @@ -205,50 +204,50 @@ struct vty_arg  #endif /* __GNUC__ */  /* Utility macros to convert VTY argument to unsigned long */ -#define VTY_GET_ULONG(NAME,V,STR) \ -do { \ -  char *endptr = NULL; \ -  errno = 0; \ -  (V) = strtoul ((STR), &endptr, 10); \ -  if (*(STR) == '-') \ -    { \ -      vty_out (vty, "%% Invalid %s value (dash)%s", NAME, VTY_NEWLINE); \ -      return CMD_WARNING; \ -    } \ -  if (*endptr != '\0') \ -    { \ -      vty_out (vty, "%% Invalid %s value (%s)%s", NAME, endptr, VTY_NEWLINE); \ -      return CMD_WARNING; \ -    } \ -  if (errno) \ -    { \ -      vty_out (vty, "%% Invalid %s value (error %d)%s", NAME, errno, VTY_NEWLINE); \ -      return CMD_WARNING; \ -    } \ -} while (0) +#define VTY_GET_ULONG(NAME, V, STR)                                            \ +	do {                                                                   \ +		char *endptr = NULL;                                           \ +		errno = 0;                                                     \ +		(V) = strtoul((STR), &endptr, 10);                             \ +		if (*(STR) == '-') {                                           \ +			vty_out(vty, "%% Invalid %s value (dash)%s", NAME,     \ +				VTY_NEWLINE);                                  \ +			return CMD_WARNING;                                    \ +		}                                                              \ +		if (*endptr != '\0') {                                         \ +			vty_out(vty, "%% Invalid %s value (%s)%s", NAME,       \ +				endptr, VTY_NEWLINE);                          \ +			return CMD_WARNING;                                    \ +		}                                                              \ +		if (errno) {                                                   \ +			vty_out(vty, "%% Invalid %s value (error %d)%s", NAME, \ +				errno, VTY_NEWLINE);                           \ +			return CMD_WARNING;                                    \ +		}                                                              \ +	} while (0)  /* Utility macros to convert VTY argument to unsigned long long */ -#define VTY_GET_ULL(NAME,V,STR) \ -do { \ -  char *endptr = NULL; \ -  errno = 0; \ -  (V) = strtoull ((STR), &endptr, 10); \ -  if (*(STR) == '-') \ -    { \ -      vty_out (vty, "%% Invalid %s value (dash)%s", NAME, VTY_NEWLINE); \ -      return CMD_WARNING; \ -    } \ -  if (*endptr != '\0') \ -    { \ -      vty_out (vty, "%% Invalid %s value (%s)%s", NAME, endptr, VTY_NEWLINE); \ -      return CMD_WARNING; \ -    } \ -  if (errno) \ -    { \ -      vty_out (vty, "%% Invalid %s value (error %d)%s", NAME, errno, VTY_NEWLINE); \ -      return CMD_WARNING; \ -    } \ -} while (0) +#define VTY_GET_ULL(NAME, V, STR)                                              \ +	do {                                                                   \ +		char *endptr = NULL;                                           \ +		errno = 0;                                                     \ +		(V) = strtoull((STR), &endptr, 10);                            \ +		if (*(STR) == '-') {                                           \ +			vty_out(vty, "%% Invalid %s value (dash)%s", NAME,     \ +				VTY_NEWLINE);                                  \ +			return CMD_WARNING;                                    \ +		}                                                              \ +		if (*endptr != '\0') {                                         \ +			vty_out(vty, "%% Invalid %s value (%s)%s", NAME,       \ +				endptr, VTY_NEWLINE);                          \ +			return CMD_WARNING;                                    \ +		}                                                              \ +		if (errno) {                                                   \ +			vty_out(vty, "%% Invalid %s value (error %d)%s", NAME, \ +				errno, VTY_NEWLINE);                           \ +			return CMD_WARNING;                                    \ +		}                                                              \ +	} while (0)  /*   * The logic below ((TMPL) <= ((MIN) && (TMPL) != (MIN)) is @@ -257,92 +256,93 @@ do { \   * NB: The compiler isn't smart enough to supress the warning   * if you write (MIN) != 0 && tmpl < (MIN).   */ -#define VTY_GET_INTEGER_RANGE_HEART(NAME,TMPL,STR,MIN,MAX)      \ -do {                                                            \ -  VTY_GET_ULONG(NAME, (TMPL), STR);                             \ -  if ( ((TMPL) <= (MIN) && (TMPL) != (MIN)) || (TMPL) > (MAX) ) \ -    {                                                           \ -      vty_out (vty, "%% Invalid %s value%s", NAME, VTY_NEWLINE);\ -      return CMD_WARNING;                                       \ -    }                                                           \ -} while (0) - -#define VTY_GET_INTEGER_RANGE(NAME,V,STR,MIN,MAX)               \ -do {                                                            \ -  unsigned long long tmpl;                                      \ -  VTY_GET_INTEGER_RANGE_HEART(NAME,tmpl,STR,MIN,MAX);           \ -  (V) = tmpl;                                                   \ -} while (0) - -#define VTY_CHECK_INTEGER_RANGE(NAME,STR,MIN,MAX)               \ -do {                                                            \ -  unsigned long tmpl;                                           \ -  VTY_GET_INTEGER_RANGE_HEART(NAME,tmpl,STR,MIN,MAX);           \ -} while (0) - -#define VTY_GET_INTEGER(NAME,V,STR)                             \ -    VTY_GET_INTEGER_RANGE(NAME,V,STR,0U,UINT32_MAX) - -#define VTY_GET_IPV4_ADDRESS(NAME,V,STR)                                      \ -do {                                                                             \ -  int retv;                                                                   \ -  retv = inet_aton ((STR), &(V));                                             \ -  if (!retv)                                                                  \ -    {                                                                         \ -      vty_out (vty, "%% Invalid %s value%s", NAME, VTY_NEWLINE);              \ -      return CMD_WARNING;                                                     \ -    }                                                                         \ -} while (0) - -#define VTY_GET_IPV4_PREFIX(NAME,V,STR)                                       \ -do {                                                                             \ -  int retv;                                                                   \ -  retv = str2prefix_ipv4 ((STR), &(V));                                       \ -  if (retv <= 0)                                                              \ -    {                                                                         \ -      vty_out (vty, "%% Invalid %s value%s", NAME, VTY_NEWLINE);              \ -      return CMD_WARNING;                                                     \ -    }                                                                         \ -} while (0) - -#define VTY_WARN_EXPERIMENTAL()                                               \ -do {                                                                          \ -  vty_out (vty, "%% WARNING: this command is experimental. Both its name and" \ -                " parameters may%s%% change in a future version of Quagga,"   \ -                " possibly breaking your configuration!%s",                   \ -                VTY_NEWLINE, VTY_NEWLINE);                                    \ -} while (0) +#define VTY_GET_INTEGER_RANGE_HEART(NAME, TMPL, STR, MIN, MAX)                 \ +	do {                                                                   \ +		VTY_GET_ULONG(NAME, (TMPL), STR);                              \ +		if (((TMPL) <= (MIN) && (TMPL) != (MIN)) || (TMPL) > (MAX)) {  \ +			vty_out(vty, "%% Invalid %s value%s", NAME,            \ +				VTY_NEWLINE);                                  \ +			return CMD_WARNING;                                    \ +		}                                                              \ +	} while (0) + +#define VTY_GET_INTEGER_RANGE(NAME, V, STR, MIN, MAX)                          \ +	do {                                                                   \ +		unsigned long long tmpl;                                       \ +		VTY_GET_INTEGER_RANGE_HEART(NAME, tmpl, STR, MIN, MAX);        \ +		(V) = tmpl;                                                    \ +	} while (0) + +#define VTY_CHECK_INTEGER_RANGE(NAME, STR, MIN, MAX)                           \ +	do {                                                                   \ +		unsigned long tmpl;                                            \ +		VTY_GET_INTEGER_RANGE_HEART(NAME, tmpl, STR, MIN, MAX);        \ +	} while (0) + +#define VTY_GET_INTEGER(NAME, V, STR)                                          \ +	VTY_GET_INTEGER_RANGE(NAME, V, STR, 0U, UINT32_MAX) + +#define VTY_GET_IPV4_ADDRESS(NAME, V, STR)                                     \ +	do {                                                                   \ +		int retv;                                                      \ +		retv = inet_aton((STR), &(V));                                 \ +		if (!retv) {                                                   \ +			vty_out(vty, "%% Invalid %s value%s", NAME,            \ +				VTY_NEWLINE);                                  \ +			return CMD_WARNING;                                    \ +		}                                                              \ +	} while (0) + +#define VTY_GET_IPV4_PREFIX(NAME, V, STR)                                      \ +	do {                                                                   \ +		int retv;                                                      \ +		retv = str2prefix_ipv4((STR), &(V));                           \ +		if (retv <= 0) {                                               \ +			vty_out(vty, "%% Invalid %s value%s", NAME,            \ +				VTY_NEWLINE);                                  \ +			return CMD_WARNING;                                    \ +		}                                                              \ +	} while (0) + +#define VTY_WARN_EXPERIMENTAL()                                                       \ +	do {                                                                          \ +		vty_out(vty,                                                          \ +			"%% WARNING: this command is experimental. Both its name and" \ +			" parameters may%s%% change in a future version of Quagga,"   \ +			" possibly breaking your configuration!%s",                   \ +			VTY_NEWLINE, VTY_NEWLINE);                                    \ +	} while (0)  /* Exported variables */  extern char integrate_default[];  /* Prototypes. */ -extern void vty_init (struct thread_master *); -extern void vty_init_vtysh (void); -extern void vty_terminate (void); -extern void vty_reset (void); -extern struct vty *vty_new (void); -extern struct vty *vty_stdio (void (*atclose)(void)); -extern int vty_out (struct vty *, const char *, ...) PRINTF_ATTRIBUTE(2, 3); -extern void vty_read_config (const char *, char *); -extern void vty_time_print (struct vty *, int); -extern void vty_serv_sock (const char *, unsigned short, const char *); -extern void vty_close (struct vty *); -extern char *vty_get_cwd (void); -extern void vty_log (const char *level, const char *proto,  -                     const char *fmt, struct timestamp_control *, va_list); -extern int vty_config_lock (struct vty *); -extern int vty_config_unlock (struct vty *); -extern void vty_config_lockless (void); -extern int vty_shell (struct vty *); -extern int vty_shell_serv (struct vty *); -extern void vty_hello (struct vty *); +extern void vty_init(struct thread_master *); +extern void vty_init_vtysh(void); +extern void vty_terminate(void); +extern void vty_reset(void); +extern struct vty *vty_new(void); +extern struct vty *vty_stdio(void (*atclose)(void)); +extern int vty_out(struct vty *, const char *, ...) PRINTF_ATTRIBUTE(2, 3); +extern void vty_read_config(const char *, char *); +extern void vty_time_print(struct vty *, int); +extern void vty_serv_sock(const char *, unsigned short, const char *); +extern void vty_close(struct vty *); +extern char *vty_get_cwd(void); +extern void vty_log(const char *level, const char *proto, const char *fmt, +		    struct timestamp_control *, va_list); +extern int vty_config_lock(struct vty *); +extern int vty_config_unlock(struct vty *); +extern void vty_config_lockless(void); +extern int vty_shell(struct vty *); +extern int vty_shell_serv(struct vty *); +extern void vty_hello(struct vty *);  /* Send a fixed-size message to all vty terminal monitors; this should be     an async-signal-safe function. */ -extern void vty_log_fixed (char *buf, size_t len); +extern void vty_log_fixed(char *buf, size_t len); -extern const char *vty_get_arg_value (struct vty_arg **, const char *); -extern struct vty_arg *vty_get_arg (struct vty_arg **, const char *); +extern const char *vty_get_arg_value(struct vty_arg **, const char *); +extern struct vty_arg *vty_get_arg(struct vty_arg **, const char *);  #endif /* _ZEBRA_VTY_H */ diff --git a/lib/wheel.c b/lib/wheel.c index fe53dea299..6742838bfc 100644 --- a/lib/wheel.c +++ b/lib/wheel.c @@ -25,140 +25,129 @@  #include "wheel.h"  #include "log.h" -DEFINE_MTYPE_STATIC(LIB, TIMER_WHEEL,   "Timer Wheel") +DEFINE_MTYPE_STATIC(LIB, TIMER_WHEEL, "Timer Wheel")  DEFINE_MTYPE_STATIC(LIB, TIMER_WHEEL_LIST, "Timer Wheel Slot List")  static int debug_timer_wheel = 0; -static int -wheel_timer_thread (struct thread *t) +static int wheel_timer_thread(struct thread *t)  { -  struct listnode *node, *nextnode; -  unsigned long long curr_slot; -  unsigned int slots_to_skip = 1; -  struct timer_wheel *wheel; -  void *data; +	struct listnode *node, *nextnode; +	unsigned long long curr_slot; +	unsigned int slots_to_skip = 1; +	struct timer_wheel *wheel; +	void *data; -  wheel = THREAD_ARG(t); -  THREAD_OFF(wheel->timer); +	wheel = THREAD_ARG(t); +	THREAD_OFF(wheel->timer); -  wheel->curr_slot += wheel->slots_to_skip; +	wheel->curr_slot += wheel->slots_to_skip; -  curr_slot = wheel->curr_slot % wheel->slots; +	curr_slot = wheel->curr_slot % wheel->slots; -  if (debug_timer_wheel) -    zlog_debug ("%s: Wheel Slot: %lld(%lld) count: %d", -		__PRETTY_FUNCTION__, -		wheel->curr_slot, -		curr_slot, listcount(wheel->wheel_slot_lists[curr_slot])); +	if (debug_timer_wheel) +		zlog_debug("%s: Wheel Slot: %lld(%lld) count: %d", +			   __PRETTY_FUNCTION__, wheel->curr_slot, curr_slot, +			   listcount(wheel->wheel_slot_lists[curr_slot])); -  for (ALL_LIST_ELEMENTS (wheel->wheel_slot_lists[curr_slot], node, nextnode, data)) -    (*wheel->slot_run)(data); +	for (ALL_LIST_ELEMENTS(wheel->wheel_slot_lists[curr_slot], node, +			       nextnode, data)) +		(*wheel->slot_run)(data); -  while (list_isempty(wheel->wheel_slot_lists[(curr_slot + slots_to_skip) % wheel->slots]) && -	 (curr_slot + slots_to_skip ) % wheel->slots != curr_slot) -    slots_to_skip++; +	while (list_isempty(wheel->wheel_slot_lists[(curr_slot + slots_to_skip) +						    % wheel->slots]) +	       && (curr_slot + slots_to_skip) % wheel->slots != curr_slot) +		slots_to_skip++; -  wheel->slots_to_skip = slots_to_skip; -  THREAD_TIMER_MSEC_ON (wheel->master, wheel->timer, -			wheel_timer_thread, wheel, -			wheel->nexttime * slots_to_skip); +	wheel->slots_to_skip = slots_to_skip; +	THREAD_TIMER_MSEC_ON(wheel->master, wheel->timer, wheel_timer_thread, +			     wheel, wheel->nexttime * slots_to_skip); -  return 0; +	return 0;  } -struct timer_wheel * -wheel_init (struct thread_master *master, int period, size_t slots, -	    unsigned int (*slot_key) (void *), -	    void (*slot_run) (void *)) +struct timer_wheel *wheel_init(struct thread_master *master, int period, +			       size_t slots, unsigned int (*slot_key)(void *), +			       void (*slot_run)(void *))  { -  struct timer_wheel *wheel; -  size_t i; +	struct timer_wheel *wheel; +	size_t i; -  wheel = XCALLOC(MTYPE_TIMER_WHEEL, sizeof (struct timer_wheel)); +	wheel = XCALLOC(MTYPE_TIMER_WHEEL, sizeof(struct timer_wheel)); -  wheel->slot_key = slot_key; -  wheel->slot_run = slot_run; +	wheel->slot_key = slot_key; +	wheel->slot_run = slot_run; -  wheel->period = period; -  wheel->slots = slots; -  wheel->curr_slot = 0; -  wheel->master = master; -  wheel->nexttime = period / slots; +	wheel->period = period; +	wheel->slots = slots; +	wheel->curr_slot = 0; +	wheel->master = master; +	wheel->nexttime = period / slots; -  wheel->wheel_slot_lists = XCALLOC(MTYPE_TIMER_WHEEL_LIST, -				    slots * sizeof (struct listnode *)); -  for (i = 0; i < slots; i++) -    wheel->wheel_slot_lists[i] = list_new (); +	wheel->wheel_slot_lists = XCALLOC(MTYPE_TIMER_WHEEL_LIST, +					  slots * sizeof(struct listnode *)); +	for (i = 0; i < slots; i++) +		wheel->wheel_slot_lists[i] = list_new(); -  THREAD_TIMER_MSEC_ON (wheel->master, wheel->timer, -			wheel_timer_thread, wheel, -			wheel->nexttime); +	THREAD_TIMER_MSEC_ON(wheel->master, wheel->timer, wheel_timer_thread, +			     wheel, wheel->nexttime); -  return wheel; +	return wheel;  } -void -wheel_delete (struct timer_wheel *wheel) +void wheel_delete(struct timer_wheel *wheel)  { -  int i; +	int i; -  for (i = 0; i < wheel->slots; i++) -    { -      list_delete(wheel->wheel_slot_lists[i]); -    } +	for (i = 0; i < wheel->slots; i++) { +		list_delete(wheel->wheel_slot_lists[i]); +	} -  THREAD_OFF(wheel->timer); -  XFREE(MTYPE_TIMER_WHEEL_LIST, wheel->wheel_slot_lists); -  XFREE(MTYPE_TIMER_WHEEL, wheel); +	THREAD_OFF(wheel->timer); +	XFREE(MTYPE_TIMER_WHEEL_LIST, wheel->wheel_slot_lists); +	XFREE(MTYPE_TIMER_WHEEL, wheel);  } -int -wheel_stop (struct timer_wheel *wheel) +int wheel_stop(struct timer_wheel *wheel)  { -  THREAD_OFF(wheel->timer); -  return 0; +	THREAD_OFF(wheel->timer); +	return 0;  } -int -wheel_start (struct timer_wheel *wheel) +int wheel_start(struct timer_wheel *wheel)  { -  if (!wheel->timer) -    THREAD_TIMER_MSEC_ON (wheel->master, wheel->timer, -			  wheel_timer_thread, wheel, -			  wheel->nexttime); +	if (!wheel->timer) +		THREAD_TIMER_MSEC_ON(wheel->master, wheel->timer, +				     wheel_timer_thread, wheel, +				     wheel->nexttime); -  return 0; +	return 0;  } -int -wheel_add_item (struct timer_wheel *wheel, void *item) +int wheel_add_item(struct timer_wheel *wheel, void *item)  { -  long long slot; +	long long slot; -  slot = (*wheel->slot_key)(item); +	slot = (*wheel->slot_key)(item); -  if (debug_timer_wheel) -    zlog_debug ("%s: Inserting %p: %lld %lld", -		__PRETTY_FUNCTION__, item, -		slot, slot % wheel->slots); -  listnode_add (wheel->wheel_slot_lists[slot % wheel->slots], item); +	if (debug_timer_wheel) +		zlog_debug("%s: Inserting %p: %lld %lld", __PRETTY_FUNCTION__, +			   item, slot, slot % wheel->slots); +	listnode_add(wheel->wheel_slot_lists[slot % wheel->slots], item); -  return 0; +	return 0;  } -int -wheel_remove_item (struct timer_wheel *wheel, void *item) +int wheel_remove_item(struct timer_wheel *wheel, void *item)  { -  long long slot; +	long long slot; -  slot = (*wheel->slot_key)(item); +	slot = (*wheel->slot_key)(item); -  if (debug_timer_wheel) -    zlog_debug ("%s: Removing %p: %lld %lld", -		__PRETTY_FUNCTION__, item, -		slot, slot % wheel->slots); -  listnode_delete (wheel->wheel_slot_lists[slot % wheel->slots], item); +	if (debug_timer_wheel) +		zlog_debug("%s: Removing %p: %lld %lld", __PRETTY_FUNCTION__, +			   item, slot, slot % wheel->slots); +	listnode_delete(wheel->wheel_slot_lists[slot % wheel->slots], item); -  return 0; +	return 0;  } diff --git a/lib/wheel.h b/lib/wheel.h index 79d21e124b..3661be1b7a 100644 --- a/lib/wheel.h +++ b/lib/wheel.h @@ -21,23 +21,22 @@  #ifndef __WHEEL_H__  #define __WHEEL_H__ -struct timer_wheel -{ -  struct thread_master *master; -  int slots; -  long long curr_slot; -  unsigned int period; -  unsigned int nexttime; -  unsigned int slots_to_skip; +struct timer_wheel { +	struct thread_master *master; +	int slots; +	long long curr_slot; +	unsigned int period; +	unsigned int nexttime; +	unsigned int slots_to_skip; -  struct list **wheel_slot_lists; -  struct thread *timer; -  /* -   * Key to determine what slot the item belongs in -   */ -  unsigned int (*slot_key) (void *); +	struct list **wheel_slot_lists; +	struct thread *timer; +	/* +	 * Key to determine what slot the item belongs in +	 */ +	unsigned int (*slot_key)(void *); -  void (*slot_run) (void *); +	void (*slot_run)(void *);  };  /* @@ -76,24 +75,24 @@ struct timer_wheel   * and cause significant amount of time handling thread events instead   * of running your code.   */ -struct timer_wheel *wheel_init (struct thread_master *master, int period, size_t slots, -				unsigned int (*slot_key) (void *), -				void (*slot_run) (void *)); +struct timer_wheel *wheel_init(struct thread_master *master, int period, +			       size_t slots, unsigned int (*slot_key)(void *), +			       void (*slot_run)(void *));  /*   * Delete the specified timer wheel created   */ -void wheel_delete (struct timer_wheel *); +void wheel_delete(struct timer_wheel *);  /*   * Pause the Wheel from running   */ -int wheel_stop (struct timer_wheel *wheel); +int wheel_stop(struct timer_wheel *wheel);  /*   * Start the wheel running again   */ -int wheel_start (struct timer_wheel *wheel); +int wheel_start(struct timer_wheel *wheel);  /*   * wheel - The Timer wheel being modified @@ -103,7 +102,7 @@ int wheel_start (struct timer_wheel *wheel);   * Add item to a slot setup by the slot_key,   * possibly change next time pop.   */ -int wheel_add_item (struct timer_wheel *wheel, void *item); +int wheel_add_item(struct timer_wheel *wheel, void *item);  /*   * wheel - The Timer wheel being modified. @@ -113,6 +112,6 @@ int wheel_add_item (struct timer_wheel *wheel, void *item);   * Remove a item to a slot setup by the slot_key,   * possibly change next time pop.   */ -int wheel_remove_item (struct timer_wheel *wheel, void *item); +int wheel_remove_item(struct timer_wheel *wheel, void *item);  #endif diff --git a/lib/workqueue.c b/lib/workqueue.c index 51017b34ea..1789c6b7db 100644 --- a/lib/workqueue.c +++ b/lib/workqueue.c @@ -1,4 +1,4 @@ -/*  +/*   * Quagga Work Queue Support.   *   * Copyright (C) 2005 Sun Microsystems, Inc. @@ -18,7 +18,7 @@   * You should have received a copy of the GNU General Public License   * along with Quagga; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #include <zebra.h> @@ -29,7 +29,7 @@  #include "command.h"  #include "log.h" -DEFINE_MTYPE(LIB, WORK_QUEUE,             "Work queue") +DEFINE_MTYPE(LIB, WORK_QUEUE, "Work queue")  DEFINE_MTYPE_STATIC(LIB, WORK_QUEUE_ITEM, "Work queue item")  DEFINE_MTYPE_STATIC(LIB, WORK_QUEUE_NAME, "Work queue name string") @@ -42,144 +42,130 @@ static struct list *work_queues = &_work_queues;  #define WORK_QUEUE_MIN_GRANULARITY 1 -static struct work_queue_item * -work_queue_item_new (struct work_queue *wq) +static struct work_queue_item *work_queue_item_new(struct work_queue *wq)  { -  struct work_queue_item *item; -  assert (wq); +	struct work_queue_item *item; +	assert(wq); -  item = XCALLOC (MTYPE_WORK_QUEUE_ITEM,  -                  sizeof (struct work_queue_item)); -   -  return item; +	item = XCALLOC(MTYPE_WORK_QUEUE_ITEM, sizeof(struct work_queue_item)); + +	return item;  } -static void -work_queue_item_free (struct work_queue_item *item) +static void work_queue_item_free(struct work_queue_item *item)  { -  XFREE (MTYPE_WORK_QUEUE_ITEM, item); -  return; +	XFREE(MTYPE_WORK_QUEUE_ITEM, item); +	return;  }  /* create new work queue */ -struct work_queue * -work_queue_new (struct thread_master *m, const char *queue_name) +struct work_queue *work_queue_new(struct thread_master *m, +				  const char *queue_name)  { -  struct work_queue *new; -   -  new = XCALLOC (MTYPE_WORK_QUEUE, sizeof (struct work_queue)); - -  if (new == NULL) -    return new; -   -  new->name = XSTRDUP (MTYPE_WORK_QUEUE_NAME, queue_name); -  new->master = m; -  SET_FLAG (new->flags, WQ_UNPLUGGED); -   -  if ( (new->items = list_new ()) == NULL) -    { -      XFREE (MTYPE_WORK_QUEUE_NAME, new->name); -      XFREE (MTYPE_WORK_QUEUE, new); -       -      return NULL; -    } -   -  new->items->del = (void (*)(void *)) work_queue_item_free;   -   -  listnode_add (work_queues, new); -   -  new->cycles.granularity = WORK_QUEUE_MIN_GRANULARITY; - -  /* Default values, can be overriden by caller */ -  new->spec.hold = WORK_QUEUE_DEFAULT_HOLD; -  new->spec.yield = THREAD_YIELD_TIME_SLOT; -     -  return new; +	struct work_queue *new; + +	new = XCALLOC(MTYPE_WORK_QUEUE, sizeof(struct work_queue)); + +	if (new == NULL) +		return new; + +	new->name = XSTRDUP(MTYPE_WORK_QUEUE_NAME, queue_name); +	new->master = m; +	SET_FLAG(new->flags, WQ_UNPLUGGED); + +	if ((new->items = list_new()) == NULL) { +		XFREE(MTYPE_WORK_QUEUE_NAME, new->name); +		XFREE(MTYPE_WORK_QUEUE, new); + +		return NULL; +	} + +	new->items->del = (void (*)(void *))work_queue_item_free; + +	listnode_add(work_queues, new); + +	new->cycles.granularity = WORK_QUEUE_MIN_GRANULARITY; + +	/* Default values, can be overriden by caller */ +	new->spec.hold = WORK_QUEUE_DEFAULT_HOLD; +	new->spec.yield = THREAD_YIELD_TIME_SLOT; + +	return new;  } -void -work_queue_free (struct work_queue *wq) +void work_queue_free(struct work_queue *wq)  { -  if (wq->thread != NULL) -    thread_cancel(wq->thread); -   -  /* list_delete frees items via callback */ -  list_delete (wq->items); -  listnode_delete (work_queues, wq); -   -  XFREE (MTYPE_WORK_QUEUE_NAME, wq->name); -  XFREE (MTYPE_WORK_QUEUE, wq); -  return; +	if (wq->thread != NULL) +		thread_cancel(wq->thread); + +	/* list_delete frees items via callback */ +	list_delete(wq->items); +	listnode_delete(work_queues, wq); + +	XFREE(MTYPE_WORK_QUEUE_NAME, wq->name); +	XFREE(MTYPE_WORK_QUEUE, wq); +	return;  } -bool -work_queue_is_scheduled (struct work_queue *wq) +bool work_queue_is_scheduled(struct work_queue *wq)  { -  return (wq->thread != NULL); +	return (wq->thread != NULL);  } -static int -work_queue_schedule (struct work_queue *wq, unsigned int delay) +static int work_queue_schedule(struct work_queue *wq, unsigned int delay)  { -  /* if appropriate, schedule work queue thread */ -  if ( CHECK_FLAG (wq->flags, WQ_UNPLUGGED) -       && (wq->thread == NULL) -       && (listcount (wq->items) > 0) ) -    { -      wq->thread = thread_add_background (wq->master, work_queue_run,  -                                          wq, delay); -      /* set thread yield time, if needed */ -      if (wq->thread && wq->spec.yield != THREAD_YIELD_TIME_SLOT) -        thread_set_yield_time (wq->thread, wq->spec.yield); -      return 1; -    } -  else -    return 0; +	/* if appropriate, schedule work queue thread */ +	if (CHECK_FLAG(wq->flags, WQ_UNPLUGGED) && (wq->thread == NULL) +	    && (listcount(wq->items) > 0)) { +		wq->thread = thread_add_background(wq->master, work_queue_run, +						   wq, delay); +		/* set thread yield time, if needed */ +		if (wq->thread && wq->spec.yield != THREAD_YIELD_TIME_SLOT) +			thread_set_yield_time(wq->thread, wq->spec.yield); +		return 1; +	} else +		return 0;  } -   -void -work_queue_add (struct work_queue *wq, void *data) + +void work_queue_add(struct work_queue *wq, void *data)  { -  struct work_queue_item *item; -   -  assert (wq); - -  if (!(item = work_queue_item_new (wq))) -    { -      zlog_err ("%s: unable to get new queue item", __func__); -      return; -    } -   -  item->data = data; -  listnode_add (wq->items, item); -   -  work_queue_schedule (wq, wq->spec.hold); -   -  return; +	struct work_queue_item *item; + +	assert(wq); + +	if (!(item = work_queue_item_new(wq))) { +		zlog_err("%s: unable to get new queue item", __func__); +		return; +	} + +	item->data = data; +	listnode_add(wq->items, item); + +	work_queue_schedule(wq, wq->spec.hold); + +	return;  } -static void -work_queue_item_remove (struct work_queue *wq, struct listnode *ln) +static void work_queue_item_remove(struct work_queue *wq, struct listnode *ln)  { -  struct work_queue_item *item = listgetdata (ln); +	struct work_queue_item *item = listgetdata(ln); -  assert (item && item->data); +	assert(item && item->data); -  /* call private data deletion callback if needed */   -  if (wq->spec.del_item_data) -    wq->spec.del_item_data (wq, item->data); +	/* call private data deletion callback if needed */ +	if (wq->spec.del_item_data) +		wq->spec.del_item_data(wq, item->data); -  list_delete_node (wq->items, ln); -  work_queue_item_free (item); -   -  return; +	list_delete_node(wq->items, ln); +	work_queue_item_free(item); + +	return;  } -static void -work_queue_item_requeue (struct work_queue *wq, struct listnode *ln) +static void work_queue_item_requeue(struct work_queue *wq, struct listnode *ln)  { -  LISTNODE_DETACH (wq->items, ln); -  LISTNODE_ATTACH (wq->items, ln); /* attach to end of list */ +	LISTNODE_DETACH(wq->items, ln); +	LISTNODE_ATTACH(wq->items, ln); /* attach to end of list */  }  DEFUN (show_work_queues, @@ -188,230 +174,212 @@ DEFUN (show_work_queues,         SHOW_STR         "Work Queue information\n")  { -  struct listnode *node; -  struct work_queue *wq; -   -  vty_out (vty,  -           "%c %8s %5s %8s %8s %21s%s", -           ' ', "List","(ms) ","Q. Runs","Yields","Cycle Counts   ", -           VTY_NEWLINE); -  vty_out (vty, -           "%c %8s %5s %8s %8s %7s %6s %8s %6s %s%s", -           'P', -           "Items", -           "Hold", -           "Total","Total", -           "Best","Gran.","Total","Avg.", -           "Name",  -           VTY_NEWLINE); -  -  for (ALL_LIST_ELEMENTS_RO (work_queues, node, wq)) -    { -      vty_out (vty,"%c %8d %5d %8ld %8ld %7d %6d %8ld %6u %s%s", -               (CHECK_FLAG (wq->flags, WQ_UNPLUGGED) ? ' ' : 'P'), -               listcount (wq->items), -               wq->spec.hold, -               wq->runs, wq->yields, -               wq->cycles.best, wq->cycles.granularity, wq->cycles.total, -                 (wq->runs) ?  -                   (unsigned int) (wq->cycles.total / wq->runs) : 0, -               wq->name, -               VTY_NEWLINE); -    } -     -  return CMD_SUCCESS; +	struct listnode *node; +	struct work_queue *wq; + +	vty_out(vty, "%c %8s %5s %8s %8s %21s%s", ' ', "List", "(ms) ", +		"Q. Runs", "Yields", "Cycle Counts   ", VTY_NEWLINE); +	vty_out(vty, "%c %8s %5s %8s %8s %7s %6s %8s %6s %s%s", 'P', "Items", +		"Hold", "Total", "Total", "Best", "Gran.", "Total", "Avg.", +		"Name", VTY_NEWLINE); + +	for (ALL_LIST_ELEMENTS_RO(work_queues, node, wq)) { +		vty_out(vty, "%c %8d %5d %8ld %8ld %7d %6d %8ld %6u %s%s", +			(CHECK_FLAG(wq->flags, WQ_UNPLUGGED) ? ' ' : 'P'), +			listcount(wq->items), wq->spec.hold, wq->runs, +			wq->yields, wq->cycles.best, wq->cycles.granularity, +			wq->cycles.total, +			(wq->runs) ? (unsigned int)(wq->cycles.total / wq->runs) +				   : 0, +			wq->name, VTY_NEWLINE); +	} + +	return CMD_SUCCESS;  } -void -workqueue_cmd_init (void) +void workqueue_cmd_init(void)  { -  install_element (VIEW_NODE, &show_work_queues_cmd); +	install_element(VIEW_NODE, &show_work_queues_cmd);  }  /* 'plug' a queue: Stop it from being scheduled,   * ie: prevent the queue from draining.   */ -void -work_queue_plug (struct work_queue *wq) +void work_queue_plug(struct work_queue *wq)  { -  if (wq->thread) -    thread_cancel (wq->thread); -   -  wq->thread = NULL; -   -  UNSET_FLAG (wq->flags, WQ_UNPLUGGED); +	if (wq->thread) +		thread_cancel(wq->thread); + +	wq->thread = NULL; + +	UNSET_FLAG(wq->flags, WQ_UNPLUGGED);  }  /* unplug queue, schedule it again, if appropriate   * Ie: Allow the queue to be drained again   */ -void -work_queue_unplug (struct work_queue *wq) +void work_queue_unplug(struct work_queue *wq)  { -  SET_FLAG (wq->flags, WQ_UNPLUGGED); +	SET_FLAG(wq->flags, WQ_UNPLUGGED); -  /* if thread isnt already waiting, add one */ -  work_queue_schedule (wq, wq->spec.hold); +	/* if thread isnt already waiting, add one */ +	work_queue_schedule(wq, wq->spec.hold);  }  /* timer thread to process a work queue   * will reschedule itself if required, - * otherwise work_queue_item_add  + * otherwise work_queue_item_add   */ -int -work_queue_run (struct thread *thread) +int work_queue_run(struct thread *thread)  { -  struct work_queue *wq; -  struct work_queue_item *item; -  wq_item_status ret; -  unsigned int cycles = 0; -  struct listnode *node, *nnode; -  char yielded = 0; - -  wq = THREAD_ARG (thread); -  wq->thread = NULL; - -  assert (wq && wq->items); - -  /* calculate cycle granularity: -   * list iteration == 1 run -   * listnode processing == 1 cycle -   * granularity == # cycles between checks whether we should yield. -   * -   * granularity should be > 0, and can increase slowly after each run to -   * provide some hysteris, but not past cycles.best or 2*cycles. -   * -   * Best: starts low, can only increase -   * -   * Granularity: starts at WORK_QUEUE_MIN_GRANULARITY, can be decreased  -   *              if we run to end of time slot, can increase otherwise  -   *              by a small factor. -   * -   * We could use just the average and save some work, however we want to be -   * able to adjust quickly to CPU pressure. Average wont shift much if -   * daemon has been running a long time. -   */ -   if (wq->cycles.granularity == 0) -     wq->cycles.granularity = WORK_QUEUE_MIN_GRANULARITY; - -  for (ALL_LIST_ELEMENTS (wq->items, node, nnode, item)) -  { -    assert (item && item->data); -     -    /* dont run items which are past their allowed retries */ -    if (item->ran > wq->spec.max_retries) -      { -        /* run error handler, if any */ -	if (wq->spec.errorfunc) -	  wq->spec.errorfunc (wq, item->data); -	work_queue_item_remove (wq, node); -	continue; -      } - -    /* run and take care of items that want to be retried immediately */ -    do -      { -        ret = wq->spec.workfunc (wq, item->data); -        item->ran++; -      } -    while ((ret == WQ_RETRY_NOW)  -           && (item->ran < wq->spec.max_retries)); - -    switch (ret) -      { -      case WQ_QUEUE_BLOCKED: -        { -          /* decrement item->ran again, cause this isn't an item -           * specific error, and fall through to WQ_RETRY_LATER -           */ -          item->ran--; -        } -      case WQ_RETRY_LATER: -	{ -	  goto stats; -	} -      case WQ_REQUEUE: -	{ -	  item->ran--; -	  work_queue_item_requeue (wq, node); -      /* If a single node is being used with a meta-queue (e.g., zebra), -       * update the next node as we don't want to exit the thread and -       * reschedule it after every node. By definition, WQ_REQUEUE is -       * meant to continue the processing; the yield logic will kick in -       * to terminate the thread when time has exceeded. -       */ -      if (nnode == NULL) -        nnode = node; -	  break; +	struct work_queue *wq; +	struct work_queue_item *item; +	wq_item_status ret; +	unsigned int cycles = 0; +	struct listnode *node, *nnode; +	char yielded = 0; + +	wq = THREAD_ARG(thread); +	wq->thread = NULL; + +	assert(wq && wq->items); + +	/* calculate cycle granularity: +	 * list iteration == 1 run +	 * listnode processing == 1 cycle +	 * granularity == # cycles between checks whether we should yield. +	 * +	 * granularity should be > 0, and can increase slowly after each run to +	 * provide some hysteris, but not past cycles.best or 2*cycles. +	 * +	 * Best: starts low, can only increase +	 * +	 * Granularity: starts at WORK_QUEUE_MIN_GRANULARITY, can be decreased +	 *              if we run to end of time slot, can increase otherwise +	 *              by a small factor. +	 * +	 * We could use just the average and save some work, however we want to +	 * be +	 * able to adjust quickly to CPU pressure. Average wont shift much if +	 * daemon has been running a long time. +	 */ +	if (wq->cycles.granularity == 0) +		wq->cycles.granularity = WORK_QUEUE_MIN_GRANULARITY; + +	for (ALL_LIST_ELEMENTS(wq->items, node, nnode, item)) { +		assert(item && item->data); + +		/* dont run items which are past their allowed retries */ +		if (item->ran > wq->spec.max_retries) { +			/* run error handler, if any */ +			if (wq->spec.errorfunc) +				wq->spec.errorfunc(wq, item->data); +			work_queue_item_remove(wq, node); +			continue; +		} + +		/* run and take care of items that want to be retried +		 * immediately */ +		do { +			ret = wq->spec.workfunc(wq, item->data); +			item->ran++; +		} while ((ret == WQ_RETRY_NOW) +			 && (item->ran < wq->spec.max_retries)); + +		switch (ret) { +		case WQ_QUEUE_BLOCKED: { +			/* decrement item->ran again, cause this isn't an item +			 * specific error, and fall through to WQ_RETRY_LATER +			 */ +			item->ran--; +		} +		case WQ_RETRY_LATER: { +			goto stats; +		} +		case WQ_REQUEUE: { +			item->ran--; +			work_queue_item_requeue(wq, node); +			/* If a single node is being used with a meta-queue +			 * (e.g., zebra), +			 * update the next node as we don't want to exit the +			 * thread and +			 * reschedule it after every node. By definition, +			 * WQ_REQUEUE is +			 * meant to continue the processing; the yield logic +			 * will kick in +			 * to terminate the thread when time has exceeded. +			 */ +			if (nnode == NULL) +				nnode = node; +			break; +		} +		case WQ_RETRY_NOW: +		/* a RETRY_NOW that gets here has exceeded max_tries, same as +		 * ERROR */ +		case WQ_ERROR: { +			if (wq->spec.errorfunc) +				wq->spec.errorfunc(wq, item); +		} +		/* fall through here is deliberate */ +		case WQ_SUCCESS: +		default: { +			work_queue_item_remove(wq, node); +			break; +		} +		} + +		/* completed cycle */ +		cycles++; + +		/* test if we should yield */ +		if (!(cycles % wq->cycles.granularity) +		    && thread_should_yield(thread)) { +			yielded = 1; +			goto stats; +		}  	} -      case WQ_RETRY_NOW: -        /* a RETRY_NOW that gets here has exceeded max_tries, same as ERROR */ -      case WQ_ERROR: -	{ -	  if (wq->spec.errorfunc) -	    wq->spec.errorfunc (wq, item); -	} -	/* fall through here is deliberate */ -      case WQ_SUCCESS: -      default: -	{ -	  work_queue_item_remove (wq, node); -	  break; -	} -      } - -    /* completed cycle */ -    cycles++; - -    /* test if we should yield */ -    if ( !(cycles % wq->cycles.granularity)  -        && thread_should_yield (thread)) -      { -        yielded = 1; -        goto stats; -      } -  }  stats:  #define WQ_HYSTERESIS_FACTOR 4 -  /* we yielded, check whether granularity should be reduced */ -  if (yielded && (cycles < wq->cycles.granularity)) -    { -      wq->cycles.granularity = ((cycles > 0) ? cycles -                                             : WORK_QUEUE_MIN_GRANULARITY); -    } -  /* otherwise, should granularity increase? */ -  else if (cycles >= (wq->cycles.granularity)) -    { -      if (cycles > wq->cycles.best) -        wq->cycles.best = cycles; - -      /* along with yielded check, provides hysteresis for granularity */ -      if (cycles > (wq->cycles.granularity * WQ_HYSTERESIS_FACTOR -                                           * WQ_HYSTERESIS_FACTOR)) -        wq->cycles.granularity *= WQ_HYSTERESIS_FACTOR; /* quick ramp-up */ -      else if (cycles > (wq->cycles.granularity * WQ_HYSTERESIS_FACTOR)) -        wq->cycles.granularity += WQ_HYSTERESIS_FACTOR; -    } +	/* we yielded, check whether granularity should be reduced */ +	if (yielded && (cycles < wq->cycles.granularity)) { +		wq->cycles.granularity = +			((cycles > 0) ? cycles : WORK_QUEUE_MIN_GRANULARITY); +	} +	/* otherwise, should granularity increase? */ +	else if (cycles >= (wq->cycles.granularity)) { +		if (cycles > wq->cycles.best) +			wq->cycles.best = cycles; + +		/* along with yielded check, provides hysteresis for granularity +		 */ +		if (cycles > (wq->cycles.granularity * WQ_HYSTERESIS_FACTOR +			      * WQ_HYSTERESIS_FACTOR)) +			wq->cycles.granularity *= +				WQ_HYSTERESIS_FACTOR; /* quick ramp-up */ +		else if (cycles +			 > (wq->cycles.granularity * WQ_HYSTERESIS_FACTOR)) +			wq->cycles.granularity += WQ_HYSTERESIS_FACTOR; +	}  #undef WQ_HYSTERIS_FACTOR -   -  wq->runs++; -  wq->cycles.total += cycles; -  if (yielded) -    wq->yields++; + +	wq->runs++; +	wq->cycles.total += cycles; +	if (yielded) +		wq->yields++;  #if 0    printf ("%s: cycles %d, new: best %d, worst %d\n",              __func__, cycles, wq->cycles.best, wq->cycles.granularity);  #endif -   -  /* Is the queue done yet? If it is, call the completion callback. */ -  if (listcount (wq->items) > 0) -    work_queue_schedule (wq, 0); -  else if (wq->spec.completion_func) -    wq->spec.completion_func (wq); -   -  return 0; + +	/* Is the queue done yet? If it is, call the completion callback. */ +	if (listcount(wq->items) > 0) +		work_queue_schedule(wq, 0); +	else if (wq->spec.completion_func) +		wq->spec.completion_func(wq); + +	return 0;  } diff --git a/lib/workqueue.h b/lib/workqueue.h index 548f96d8b0..efdbdf056b 100644 --- a/lib/workqueue.h +++ b/lib/workqueue.h @@ -1,4 +1,4 @@ -/*  +/*   * Quagga Work Queues.   *   * Copyright (C) 2005 Sun Microsystems, Inc. @@ -18,7 +18,7 @@   * You should have received a copy of the GNU General Public License   * along with Quagga; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _QUAGGA_WORK_QUEUE_H @@ -31,105 +31,104 @@ DECLARE_MTYPE(WORK_QUEUE)  #define WORK_QUEUE_DEFAULT_HOLD  50   /* action value, for use by item processor and item error handlers */ -typedef enum -{ -  WQ_SUCCESS = 0, -  WQ_ERROR,             /* Error, run error handler if provided */ -  WQ_RETRY_NOW,         /* retry immediately */ -  WQ_RETRY_LATER,       /* retry later, cease processing work queue */ -  WQ_REQUEUE,		/* requeue item, continue processing work queue */ -  WQ_QUEUE_BLOCKED,	/* Queue cant be processed at this time. -                         * Similar to WQ_RETRY_LATER, but doesn't penalise -                         * the particular item.. */ +typedef enum { +	WQ_SUCCESS = 0, +	WQ_ERROR,	 /* Error, run error handler if provided */ +	WQ_RETRY_NOW,     /* retry immediately */ +	WQ_RETRY_LATER,   /* retry later, cease processing work queue */ +	WQ_REQUEUE,       /* requeue item, continue processing work queue */ +	WQ_QUEUE_BLOCKED, /* Queue cant be processed at this time. +			   * Similar to WQ_RETRY_LATER, but doesn't penalise +			   * the particular item.. */  } wq_item_status;  /* A single work queue item, unsurprisingly */ -struct work_queue_item -{ -  void *data;                           /* opaque data */ -  unsigned short ran;			/* # of times item has been run */ +struct work_queue_item { +	void *data;	 /* opaque data */ +	unsigned short ran; /* # of times item has been run */  };  #define WQ_UNPLUGGED	(1 << 0) /* available for draining */ -struct work_queue -{ -  /* Everything but the specification struct is private -   * the following may be read -   */ -  struct thread_master *master;       /* thread master */ -  struct thread *thread;              /* thread, if one is active */ -  char *name;                         /* work queue name */ -   -  /* Specification for this work queue. -   * Public, must be set before use by caller. May be modified at will. -   */ -  struct { -    /* optional opaque user data, global to the queue. */ -    void *data; -     -    /* work function to process items with: -     * First argument is the workqueue queue. -     * Second argument is the item data -     */ -    wq_item_status (*workfunc) (struct work_queue *, void *); - -    /* error handling function, optional */ -    void (*errorfunc) (struct work_queue *, struct work_queue_item *); -     -    /* callback to delete user specific item data */ -    void (*del_item_data) (struct work_queue *, void *); -     -    /* completion callback, called when queue is emptied, optional */ -    void (*completion_func) (struct work_queue *); -     -    /* max number of retries to make for item that errors */ -    unsigned int max_retries;	 - -    unsigned int hold;	/* hold time for first run, in ms */ - -    unsigned long yield; /* yield time in us for associated thread */ -  } spec; -   -  /* remaining fields should be opaque to users */ -  struct list *items;                 /* queue item list */ -  unsigned long runs;                 /* runs count */ -  unsigned long yields;               /* yields count */ -   -  struct { -    unsigned int best; -    unsigned int granularity; -    unsigned long total; -  } cycles;	/* cycle counts */ -   -  /* private state */ -  u_int16_t flags;		/* user set flag */ +struct work_queue { +	/* Everything but the specification struct is private +	 * the following may be read +	 */ +	struct thread_master *master; /* thread master */ +	struct thread *thread;	/* thread, if one is active */ +	char *name;		      /* work queue name */ + +	/* Specification for this work queue. +	 * Public, must be set before use by caller. May be modified at will. +	 */ +	struct { +		/* optional opaque user data, global to the queue. */ +		void *data; + +		/* work function to process items with: +		 * First argument is the workqueue queue. +		 * Second argument is the item data +		 */ +		wq_item_status (*workfunc)(struct work_queue *, void *); + +		/* error handling function, optional */ +		void (*errorfunc)(struct work_queue *, +				  struct work_queue_item *); + +		/* callback to delete user specific item data */ +		void (*del_item_data)(struct work_queue *, void *); + +		/* completion callback, called when queue is emptied, optional +		 */ +		void (*completion_func)(struct work_queue *); + +		/* max number of retries to make for item that errors */ +		unsigned int max_retries; + +		unsigned int hold; /* hold time for first run, in ms */ + +		unsigned long +			yield; /* yield time in us for associated thread */ +	} spec; + +	/* remaining fields should be opaque to users */ +	struct list *items;   /* queue item list */ +	unsigned long runs;   /* runs count */ +	unsigned long yields; /* yields count */ + +	struct { +		unsigned int best; +		unsigned int granularity; +		unsigned long total; +	} cycles; /* cycle counts */ + +	/* private state */ +	u_int16_t flags; /* user set flag */  };  /* User API */ -/* create a new work queue, of given name.  +/* create a new work queue, of given name.   * user must fill in the spec of the returned work queue before adding   * anything to it   */ -extern struct work_queue *work_queue_new (struct thread_master *, -                                          const char *); +extern struct work_queue *work_queue_new(struct thread_master *, const char *);  /* destroy work queue */ -extern void work_queue_free (struct work_queue *); +extern void work_queue_free(struct work_queue *);  /* Add the supplied data as an item onto the workqueue */ -extern void work_queue_add (struct work_queue *, void *); +extern void work_queue_add(struct work_queue *, void *);  /* plug the queue, ie prevent it from being drained / processed */ -extern void work_queue_plug (struct work_queue *wq); +extern void work_queue_plug(struct work_queue *wq);  /* unplug the queue, allow it to be drained again */ -extern void work_queue_unplug (struct work_queue *wq); +extern void work_queue_unplug(struct work_queue *wq); -bool work_queue_is_scheduled (struct work_queue *); +bool work_queue_is_scheduled(struct work_queue *);  /* Helpers, exported for thread.c and command.c */ -extern int work_queue_run (struct thread *); +extern int work_queue_run(struct thread *); -extern void workqueue_cmd_init (void); +extern void workqueue_cmd_init(void);  #endif /* _QUAGGA_WORK_QUEUE_H */ diff --git a/lib/zassert.h b/lib/zassert.h index bf0a851ba8..35967db472 100644 --- a/lib/zassert.h +++ b/lib/zassert.h @@ -16,15 +16,15 @@   * You should have received a copy of the GNU General Public License   * along with Quagga; see the file COPYING.  If not, write to the Free   * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA - * 02111-1307, USA.   + * 02111-1307, USA.   */  #ifndef _QUAGGA_ASSERT_H  #define _QUAGGA_ASSERT_H -extern void _zlog_assert_failed (const char *assertion, const char *file, -				 unsigned int line, const char *function) -				 __attribute__ ((noreturn)); +extern void _zlog_assert_failed(const char *assertion, const char *file, +				unsigned int line, const char *function) +	__attribute__((noreturn));  #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L  #define __ASSERT_FUNCTION    __func__ @@ -34,9 +34,10 @@ extern void _zlog_assert_failed (const char *assertion, const char *file,  #define __ASSERT_FUNCTION    NULL  #endif -#define zassert(EX) ((void)((EX) ?  0 :	\ -			    (_zlog_assert_failed(#EX, __FILE__, __LINE__, \ -						 __ASSERT_FUNCTION), 0))) +#define zassert(EX)                                                            \ +	((void)((EX) ? 0 : (_zlog_assert_failed(#EX, __FILE__, __LINE__,       \ +						__ASSERT_FUNCTION),            \ +			    0)))  #undef assert  #define assert(EX) zassert(EX) diff --git a/lib/zclient.c b/lib/zclient.c index 9338f9c986..3c4bc4907f 100644 --- a/lib/zclient.c +++ b/lib/zclient.c @@ -39,10 +39,10 @@ DEFINE_MTYPE_STATIC(LIB, ZCLIENT, "Zclient")  DEFINE_MTYPE_STATIC(LIB, REDIST_INST, "Redistribution instance IDs")  /* Zebra client events. */ -enum event {ZCLIENT_SCHEDULE, ZCLIENT_READ, ZCLIENT_CONNECT}; +enum event { ZCLIENT_SCHEDULE, ZCLIENT_READ, ZCLIENT_CONNECT };  /* Prototype for event manager. */ -static void zclient_event (enum event, struct zclient *); +static void zclient_event(enum event, struct zclient *);  const char *zclient_serv_path = NULL; @@ -50,18 +50,17 @@ const char *zclient_serv_path = NULL;  int zclient_debug = 0;  /* Allocate zclient structure. */ -struct zclient * -zclient_new (struct thread_master *master) +struct zclient *zclient_new(struct thread_master *master)  { -  struct zclient *zclient; -  zclient = XCALLOC (MTYPE_ZCLIENT, sizeof (struct zclient)); +	struct zclient *zclient; +	zclient = XCALLOC(MTYPE_ZCLIENT, sizeof(struct zclient)); -  zclient->ibuf = stream_new (ZEBRA_MAX_PACKET_SIZ); -  zclient->obuf = stream_new (ZEBRA_MAX_PACKET_SIZ); -  zclient->wb = buffer_new(0); -  zclient->master = master; +	zclient->ibuf = stream_new(ZEBRA_MAX_PACKET_SIZ); +	zclient->obuf = stream_new(ZEBRA_MAX_PACKET_SIZ); +	zclient->wb = buffer_new(0); +	zclient->master = master; -  return zclient; +	return zclient;  }  /* This function is only called when exiting, because @@ -69,162 +68,154 @@ zclient_new (struct thread_master *master)     reference an invalid pointer if the structure was ever freed.     Free zclient structure. */ -void -zclient_free (struct zclient *zclient) +void zclient_free(struct zclient *zclient)  { -  if (zclient->ibuf) -    stream_free(zclient->ibuf); -  if (zclient->obuf) -    stream_free(zclient->obuf); -  if (zclient->wb) -    buffer_free(zclient->wb); - -  XFREE (MTYPE_ZCLIENT, zclient); +	if (zclient->ibuf) +		stream_free(zclient->ibuf); +	if (zclient->obuf) +		stream_free(zclient->obuf); +	if (zclient->wb) +		buffer_free(zclient->wb); + +	XFREE(MTYPE_ZCLIENT, zclient);  } -u_short * -redist_check_instance (struct redist_proto *red, u_short instance) +u_short *redist_check_instance(struct redist_proto *red, u_short instance)  { -  struct listnode *node; -  u_short *id; +	struct listnode *node; +	u_short *id; -  if (!red->instances) -    return NULL; +	if (!red->instances) +		return NULL; -  for (ALL_LIST_ELEMENTS_RO (red->instances, node, id)) -    if (*id == instance) -      return id; +	for (ALL_LIST_ELEMENTS_RO(red->instances, node, id)) +		if (*id == instance) +			return id; -  return NULL; +	return NULL;  } -void -redist_add_instance (struct redist_proto *red, u_short instance) +void redist_add_instance(struct redist_proto *red, u_short instance)  { -  u_short *in; +	u_short *in; -  red->enabled = 1; +	red->enabled = 1; -  if (!red->instances) -    red->instances = list_new(); +	if (!red->instances) +		red->instances = list_new(); -  in = XMALLOC (MTYPE_REDIST_INST, sizeof(u_short)); -  *in = instance; -  listnode_add (red->instances, in); +	in = XMALLOC(MTYPE_REDIST_INST, sizeof(u_short)); +	*in = instance; +	listnode_add(red->instances, in);  } -void -redist_del_instance (struct redist_proto *red, u_short instance) +void redist_del_instance(struct redist_proto *red, u_short instance)  { -  u_short *id; - -  id = redist_check_instance (red, instance); -  if (! id) -    return; - -  listnode_delete(red->instances, id); -  XFREE (MTYPE_REDIST_INST, id); -  if (!red->instances->count) -    { -      red->enabled = 0; -      list_free(red->instances); -      red->instances = NULL; -    } +	u_short *id; + +	id = redist_check_instance(red, instance); +	if (!id) +		return; + +	listnode_delete(red->instances, id); +	XFREE(MTYPE_REDIST_INST, id); +	if (!red->instances->count) { +		red->enabled = 0; +		list_free(red->instances); +		red->instances = NULL; +	}  }  /* Stop zebra client services. */ -void -zclient_stop (struct zclient *zclient) +void zclient_stop(struct zclient *zclient)  { -  afi_t afi; -  int i; - -  if (zclient_debug) -    zlog_debug ("zclient stopped"); - -  /* Stop threads. */ -  THREAD_OFF(zclient->t_read); -  THREAD_OFF(zclient->t_connect); -  THREAD_OFF(zclient->t_write); - -  /* Reset streams. */ -  stream_reset(zclient->ibuf); -  stream_reset(zclient->obuf); - -  /* Empty the write buffer. */ -  buffer_reset(zclient->wb); - -  /* Close socket. */ -  if (zclient->sock >= 0) -    { -      close (zclient->sock); -      zclient->sock = -1; -    } -  zclient->fail = 0; - -  for (afi = AFI_IP; afi < AFI_MAX; afi++) -    { -      for (i = 0; i < ZEBRA_ROUTE_MAX; i++) -	{ -	  vrf_bitmap_free(zclient->redist[afi][i]); -	  zclient->redist[afi][i] = VRF_BITMAP_NULL; +	afi_t afi; +	int i; + +	if (zclient_debug) +		zlog_debug("zclient stopped"); + +	/* Stop threads. */ +	THREAD_OFF(zclient->t_read); +	THREAD_OFF(zclient->t_connect); +	THREAD_OFF(zclient->t_write); + +	/* Reset streams. */ +	stream_reset(zclient->ibuf); +	stream_reset(zclient->obuf); + +	/* Empty the write buffer. */ +	buffer_reset(zclient->wb); + +	/* Close socket. */ +	if (zclient->sock >= 0) { +		close(zclient->sock); +		zclient->sock = -1; +	} +	zclient->fail = 0; + +	for (afi = AFI_IP; afi < AFI_MAX; afi++) { +		for (i = 0; i < ZEBRA_ROUTE_MAX; i++) { +			vrf_bitmap_free(zclient->redist[afi][i]); +			zclient->redist[afi][i] = VRF_BITMAP_NULL; +		} +		redist_del_instance( +			&zclient->mi_redist[afi][zclient->redist_default], +			zclient->instance);  	} -      redist_del_instance(&zclient->mi_redist[afi][zclient->redist_default], -			  zclient->instance); -    } -  vrf_bitmap_free(zclient->default_information); -  zclient->default_information = VRF_BITMAP_NULL; +	vrf_bitmap_free(zclient->default_information); +	zclient->default_information = VRF_BITMAP_NULL;  } -void -zclient_reset (struct zclient *zclient) +void zclient_reset(struct zclient *zclient)  { -  afi_t afi; +	afi_t afi; -  zclient_stop (zclient); +	zclient_stop(zclient); -  for (afi = AFI_IP; afi < AFI_MAX; afi++) -    redist_del_instance (&zclient->mi_redist[afi][zclient->redist_default], zclient->instance); +	for (afi = AFI_IP; afi < AFI_MAX; afi++) +		redist_del_instance( +			&zclient->mi_redist[afi][zclient->redist_default], +			zclient->instance); -  zclient_init (zclient, zclient->redist_default, zclient->instance); +	zclient_init(zclient, zclient->redist_default, zclient->instance);  }  #ifdef HAVE_TCP_ZEBRA  /* Make socket to zebra daemon. Return zebra socket. */ -static int -zclient_socket(void) +static int zclient_socket(void)  { -  int sock; -  int ret; -  struct sockaddr_in serv; - -  /* We should think about IPv6 connection. */ -  sock = socket (AF_INET, SOCK_STREAM, 0); -  if (sock < 0) -    return -1; -   -  /* Make server socket. */  -  memset (&serv, 0, sizeof (struct sockaddr_in)); -  serv.sin_family = AF_INET; -  serv.sin_port = htons (ZEBRA_PORT); +	int sock; +	int ret; +	struct sockaddr_in serv; + +	/* We should think about IPv6 connection. */ +	sock = socket(AF_INET, SOCK_STREAM, 0); +	if (sock < 0) +		return -1; + +	/* Make server socket. */ +	memset(&serv, 0, sizeof(struct sockaddr_in)); +	serv.sin_family = AF_INET; +	serv.sin_port = htons(ZEBRA_PORT);  #ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN -  serv.sin_len = sizeof (struct sockaddr_in); +	serv.sin_len = sizeof(struct sockaddr_in);  #endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */ -  serv.sin_addr.s_addr = htonl (INADDR_LOOPBACK); - -  /* Connect to zebra. */ -  ret = connect (sock, (struct sockaddr *) &serv, sizeof (serv)); -  if (ret < 0) -    { -      if (zclient_debug) -	zlog_warn ("%s connect failure: %d(%s)", __PRETTY_FUNCTION__, -		   errno, safe_strerror (errno)); -      close (sock); -      return -1; -    } -  return sock; +	serv.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + +	/* Connect to zebra. */ +	ret = connect(sock, (struct sockaddr *)&serv, sizeof(serv)); +	if (ret < 0) { +		if (zclient_debug) +			zlog_warn("%s connect failure: %d(%s)", +				  __PRETTY_FUNCTION__, errno, +				  safe_strerror(errno)); +		close(sock); +		return -1; +	} +	return sock;  }  #else @@ -232,37 +223,36 @@ zclient_socket(void)  /* For sockaddr_un. */  #include <sys/un.h> -static int -zclient_socket_un (const char *path) +static int zclient_socket_un(const char *path)  { -  int ret; -  int sock, len; -  struct sockaddr_un addr; - -  sock = socket (AF_UNIX, SOCK_STREAM, 0); -  if (sock < 0) -    return -1; -   -  /* Make server socket. */  -  memset (&addr, 0, sizeof (struct sockaddr_un)); -  addr.sun_family = AF_UNIX; -  strncpy (addr.sun_path, path, strlen (path)); +	int ret; +	int sock, len; +	struct sockaddr_un addr; + +	sock = socket(AF_UNIX, SOCK_STREAM, 0); +	if (sock < 0) +		return -1; + +	/* Make server socket. */ +	memset(&addr, 0, sizeof(struct sockaddr_un)); +	addr.sun_family = AF_UNIX; +	strncpy(addr.sun_path, path, strlen(path));  #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN -  len = addr.sun_len = SUN_LEN(&addr); +	len = addr.sun_len = SUN_LEN(&addr);  #else -  len = sizeof (addr.sun_family) + strlen (addr.sun_path); +	len = sizeof(addr.sun_family) + strlen(addr.sun_path);  #endif /* HAVE_STRUCT_SOCKADDR_UN_SUN_LEN */ -  ret = connect (sock, (struct sockaddr *) &addr, len); -  if (ret < 0) -    { -      if (zclient_debug) -        zlog_warn ("%s connect failure: %d(%s)", __PRETTY_FUNCTION__, -		   errno, safe_strerror (errno)); -      close (sock); -      return -1; -    } -  return sock; +	ret = connect(sock, (struct sockaddr *)&addr, len); +	if (ret < 0) { +		if (zclient_debug) +			zlog_warn("%s connect failure: %d(%s)", +				  __PRETTY_FUNCTION__, errno, +				  safe_strerror(errno)); +		close(sock); +		return -1; +	} +	return sock;  }  #endif /* HAVE_TCP_ZEBRA */ @@ -274,715 +264,710 @@ zclient_socket_un (const char *path)   * @see zclient_init   * @see zclient_new   */ -int -zclient_socket_connect (struct zclient *zclient) +int zclient_socket_connect(struct zclient *zclient)  {  #ifdef HAVE_TCP_ZEBRA -  zclient->sock = zclient_socket (); +	zclient->sock = zclient_socket();  #else -  zclient->sock = zclient_socket_un (zclient_serv_path_get()); +	zclient->sock = zclient_socket_un(zclient_serv_path_get());  #endif -  return zclient->sock; +	return zclient->sock;  } -static int -zclient_failed(struct zclient *zclient) +static int zclient_failed(struct zclient *zclient)  { -  zclient->fail++; -  zclient_stop(zclient); -  zclient_event(ZCLIENT_CONNECT, zclient); -  return -1; +	zclient->fail++; +	zclient_stop(zclient); +	zclient_event(ZCLIENT_CONNECT, zclient); +	return -1;  } -static int -zclient_flush_data(struct thread *thread) +static int zclient_flush_data(struct thread *thread)  { -  struct zclient *zclient = THREAD_ARG(thread); - -  zclient->t_write = NULL; -  if (zclient->sock < 0) -    return -1; -  switch (buffer_flush_available(zclient->wb, zclient->sock)) -    { -    case BUFFER_ERROR: -      zlog_warn("%s: buffer_flush_available failed on zclient fd %d, closing", -      		__func__, zclient->sock); -      return zclient_failed(zclient); -      break; -    case BUFFER_PENDING: -      zclient->t_write = thread_add_write(zclient->master, zclient_flush_data, -					  zclient, zclient->sock); -      break; -    case BUFFER_EMPTY: -      break; -    } -  return 0; +	struct zclient *zclient = THREAD_ARG(thread); + +	zclient->t_write = NULL; +	if (zclient->sock < 0) +		return -1; +	switch (buffer_flush_available(zclient->wb, zclient->sock)) { +	case BUFFER_ERROR: +		zlog_warn( +			"%s: buffer_flush_available failed on zclient fd %d, closing", +			__func__, zclient->sock); +		return zclient_failed(zclient); +		break; +	case BUFFER_PENDING: +		zclient->t_write = +			thread_add_write(zclient->master, zclient_flush_data, +					 zclient, zclient->sock); +		break; +	case BUFFER_EMPTY: +		break; +	} +	return 0;  } -int -zclient_send_message(struct zclient *zclient) +int zclient_send_message(struct zclient *zclient)  { -  if (zclient->sock < 0) -    return -1; -  switch (buffer_write(zclient->wb, zclient->sock, STREAM_DATA(zclient->obuf), -		       stream_get_endp(zclient->obuf))) -    { -    case BUFFER_ERROR: -      zlog_warn("%s: buffer_write failed to zclient fd %d, closing", -      		 __func__, zclient->sock); -      return zclient_failed(zclient); -      break; -    case BUFFER_EMPTY: -      THREAD_OFF(zclient->t_write); -      break; -    case BUFFER_PENDING: -      THREAD_WRITE_ON(zclient->master, zclient->t_write, -		      zclient_flush_data, zclient, zclient->sock); -      break; -    } -  return 0; +	if (zclient->sock < 0) +		return -1; +	switch (buffer_write(zclient->wb, zclient->sock, +			     STREAM_DATA(zclient->obuf), +			     stream_get_endp(zclient->obuf))) { +	case BUFFER_ERROR: +		zlog_warn("%s: buffer_write failed to zclient fd %d, closing", +			  __func__, zclient->sock); +		return zclient_failed(zclient); +		break; +	case BUFFER_EMPTY: +		THREAD_OFF(zclient->t_write); +		break; +	case BUFFER_PENDING: +		THREAD_WRITE_ON(zclient->master, zclient->t_write, +				zclient_flush_data, zclient, zclient->sock); +		break; +	} +	return 0;  } -void -zclient_create_header (struct stream *s, uint16_t command, vrf_id_t vrf_id) +void zclient_create_header(struct stream *s, uint16_t command, vrf_id_t vrf_id)  { -  /* length placeholder, caller can update */ -  stream_putw (s, ZEBRA_HEADER_SIZE); -  stream_putc (s, ZEBRA_HEADER_MARKER); -  stream_putc (s, ZSERV_VERSION); -  stream_putw (s, vrf_id); -  stream_putw (s, command); +	/* length placeholder, caller can update */ +	stream_putw(s, ZEBRA_HEADER_SIZE); +	stream_putc(s, ZEBRA_HEADER_MARKER); +	stream_putc(s, ZSERV_VERSION); +	stream_putw(s, vrf_id); +	stream_putw(s, command);  } -int -zclient_read_header (struct stream *s, int sock, u_int16_t *size, u_char *marker, -                     u_char *version, vrf_id_t *vrf_id, u_int16_t *cmd) +int zclient_read_header(struct stream *s, int sock, u_int16_t *size, +			u_char *marker, u_char *version, vrf_id_t *vrf_id, +			u_int16_t *cmd)  { -  if (stream_read (s, sock, ZEBRA_HEADER_SIZE) != ZEBRA_HEADER_SIZE) -    return -1; - -  *size = stream_getw (s) - ZEBRA_HEADER_SIZE; -  *marker = stream_getc (s); -  *version = stream_getc (s); -  *vrf_id = stream_getw (s); -  *cmd = stream_getw (s); - -  if (*version != ZSERV_VERSION || *marker != ZEBRA_HEADER_MARKER) -    { -      zlog_err("%s: socket %d version mismatch, marker %d, version %d", -               __func__, sock, *marker, *version); -      return -1; -    } - -  if (*size && stream_read (s, sock, *size) != *size) -    return -1; - -  return 0; +	if (stream_read(s, sock, ZEBRA_HEADER_SIZE) != ZEBRA_HEADER_SIZE) +		return -1; + +	*size = stream_getw(s) - ZEBRA_HEADER_SIZE; +	*marker = stream_getc(s); +	*version = stream_getc(s); +	*vrf_id = stream_getw(s); +	*cmd = stream_getw(s); + +	if (*version != ZSERV_VERSION || *marker != ZEBRA_HEADER_MARKER) { +		zlog_err( +			"%s: socket %d version mismatch, marker %d, version %d", +			__func__, sock, *marker, *version); +		return -1; +	} + +	if (*size && stream_read(s, sock, *size) != *size) +		return -1; + +	return 0;  }  /* Send simple Zebra message. */ -static int -zebra_message_send (struct zclient *zclient, int command, vrf_id_t vrf_id) +static int zebra_message_send(struct zclient *zclient, int command, +			      vrf_id_t vrf_id)  { -  struct stream *s; +	struct stream *s; + +	/* Get zclient output buffer. */ +	s = zclient->obuf; +	stream_reset(s); -  /* Get zclient output buffer. */ -  s = zclient->obuf; -  stream_reset (s); +	/* Send very simple command only Zebra message. */ +	zclient_create_header(s, command, vrf_id); -  /* Send very simple command only Zebra message. */ -  zclient_create_header (s, command, vrf_id); -   -  return zclient_send_message(zclient); +	return zclient_send_message(zclient);  } -static int -zebra_hello_send (struct zclient *zclient) +static int zebra_hello_send(struct zclient *zclient)  { -  struct stream *s; - -  if (zclient->redist_default) -    { -      s = zclient->obuf; -      stream_reset (s); - -      /* The VRF ID in the HELLO message is always 0. */ -      zclient_create_header (s, ZEBRA_HELLO, VRF_DEFAULT); -      stream_putc (s, zclient->redist_default); -      stream_putw (s, zclient->instance); -      stream_putw_at (s, 0, stream_get_endp (s)); -      return zclient_send_message(zclient); -    } - -  return 0; +	struct stream *s; + +	if (zclient->redist_default) { +		s = zclient->obuf; +		stream_reset(s); + +		/* The VRF ID in the HELLO message is always 0. */ +		zclient_create_header(s, ZEBRA_HELLO, VRF_DEFAULT); +		stream_putc(s, zclient->redist_default); +		stream_putw(s, zclient->instance); +		stream_putw_at(s, 0, stream_get_endp(s)); +		return zclient_send_message(zclient); +	} + +	return 0;  }  /* Send register requests to zebra daemon for the information in a VRF. */ -void -zclient_send_reg_requests (struct zclient *zclient, vrf_id_t vrf_id) +void zclient_send_reg_requests(struct zclient *zclient, vrf_id_t vrf_id)  { -  int i; -  afi_t afi; - -  /* zclient is disabled. */ -  if (! zclient->enable) -    return; - -  /* If not connected to the zebra yet. */ -  if (zclient->sock < 0) -    return; - -  if (zclient_debug) -    zlog_debug ("%s: send register messages for VRF %u", __func__, vrf_id); - -  /* We need router-id information. */ -  zebra_message_send (zclient, ZEBRA_ROUTER_ID_ADD, vrf_id); - -  /* We need interface information. */ -  zebra_message_send (zclient, ZEBRA_INTERFACE_ADD, vrf_id); - -  /* Set unwanted redistribute route. */ -  for (afi = AFI_IP; afi < AFI_MAX; afi++) -    vrf_bitmap_set (zclient->redist[afi][zclient->redist_default], vrf_id); - -  /* Flush all redistribute request. */ -  if (vrf_id == VRF_DEFAULT) -    for (afi = AFI_IP; afi < AFI_MAX; afi++) -      for (i = 0; i < ZEBRA_ROUTE_MAX; i++) -        if (zclient->mi_redist[afi][i].enabled) -          { -            struct listnode *node; -            u_short *id; - -            for (ALL_LIST_ELEMENTS_RO(zclient->mi_redist[afi][i].instances, node, id)) -              if (!(i == zclient->redist_default && *id == zclient->instance)) -                zebra_redistribute_send (ZEBRA_REDISTRIBUTE_ADD, zclient, afi, i, -                                         *id, VRF_DEFAULT); -          } - -  /* Flush all redistribute request. */ -  for (afi = AFI_IP; afi < AFI_MAX; afi++) -    for (i = 0; i < ZEBRA_ROUTE_MAX; i++) -      if (i != zclient->redist_default && -          vrf_bitmap_check (zclient->redist[afi][i], vrf_id)) -        zebra_redistribute_send (ZEBRA_REDISTRIBUTE_ADD, zclient, afi, i, 0, vrf_id); - -  /* If default information is needed. */ -  if (vrf_bitmap_check (zclient->default_information, VRF_DEFAULT)) -    zebra_message_send (zclient, ZEBRA_REDISTRIBUTE_DEFAULT_ADD, vrf_id); +	int i; +	afi_t afi; + +	/* zclient is disabled. */ +	if (!zclient->enable) +		return; + +	/* If not connected to the zebra yet. */ +	if (zclient->sock < 0) +		return; + +	if (zclient_debug) +		zlog_debug("%s: send register messages for VRF %u", __func__, +			   vrf_id); + +	/* We need router-id information. */ +	zebra_message_send(zclient, ZEBRA_ROUTER_ID_ADD, vrf_id); + +	/* We need interface information. */ +	zebra_message_send(zclient, ZEBRA_INTERFACE_ADD, vrf_id); + +	/* Set unwanted redistribute route. */ +	for (afi = AFI_IP; afi < AFI_MAX; afi++) +		vrf_bitmap_set(zclient->redist[afi][zclient->redist_default], +			       vrf_id); + +	/* Flush all redistribute request. */ +	if (vrf_id == VRF_DEFAULT) +		for (afi = AFI_IP; afi < AFI_MAX; afi++) +			for (i = 0; i < ZEBRA_ROUTE_MAX; i++) +				if (zclient->mi_redist[afi][i].enabled) { +					struct listnode *node; +					u_short *id; + +					for (ALL_LIST_ELEMENTS_RO( +						     zclient->mi_redist[afi][i] +							     .instances, +						     node, id)) +						if (!(i == zclient->redist_default +						      && *id == zclient->instance)) +							zebra_redistribute_send( +								ZEBRA_REDISTRIBUTE_ADD, +								zclient, afi, i, +								*id, +								VRF_DEFAULT); +				} + +	/* Flush all redistribute request. */ +	for (afi = AFI_IP; afi < AFI_MAX; afi++) +		for (i = 0; i < ZEBRA_ROUTE_MAX; i++) +			if (i != zclient->redist_default +			    && vrf_bitmap_check(zclient->redist[afi][i], +						vrf_id)) +				zebra_redistribute_send(ZEBRA_REDISTRIBUTE_ADD, +							zclient, afi, i, 0, +							vrf_id); + +	/* If default information is needed. */ +	if (vrf_bitmap_check(zclient->default_information, VRF_DEFAULT)) +		zebra_message_send(zclient, ZEBRA_REDISTRIBUTE_DEFAULT_ADD, +				   vrf_id);  }  /* Send unregister requests to zebra daemon for the information in a VRF. */ -void -zclient_send_dereg_requests (struct zclient *zclient, vrf_id_t vrf_id) +void zclient_send_dereg_requests(struct zclient *zclient, vrf_id_t vrf_id)  { -  int i; -  afi_t afi; - -  /* zclient is disabled. */ -  if (! zclient->enable) -    return; - -  /* If not connected to the zebra yet. */ -  if (zclient->sock < 0) -    return; - -  if (zclient_debug) -    zlog_debug ("%s: send deregister messages for VRF %u", __func__, vrf_id); - -  /* We need router-id information. */ -  zebra_message_send (zclient, ZEBRA_ROUTER_ID_DELETE, vrf_id); - -  /* We need interface information. */ -  zebra_message_send (zclient, ZEBRA_INTERFACE_DELETE, vrf_id); - -  /* Set unwanted redistribute route. */ -  for (afi = AFI_IP; afi < AFI_MAX; afi++) -    vrf_bitmap_set (zclient->redist[afi][zclient->redist_default], vrf_id); - -  /* Flush all redistribute request. */ -  if (vrf_id == VRF_DEFAULT) -    for (afi = AFI_IP; afi < AFI_MAX; afi++) -      for (i = 0; i < ZEBRA_ROUTE_MAX; i++) -        if (zclient->mi_redist[afi][i].enabled) -          { -            struct listnode *node; -            u_short *id; - -            for (ALL_LIST_ELEMENTS_RO(zclient->mi_redist[afi][i].instances, node, id)) -              if (!(i == zclient->redist_default && *id == zclient->instance)) -                zebra_redistribute_send (ZEBRA_REDISTRIBUTE_DELETE, zclient, afi, i, -                                         *id, VRF_DEFAULT); -          } - -  /* Flush all redistribute request. */ -  for (afi = AFI_IP; afi < AFI_MAX; afi++) -    for (i = 0; i < ZEBRA_ROUTE_MAX; i++) -      if (i != zclient->redist_default && -          vrf_bitmap_check (zclient->redist[afi][i], vrf_id)) -        zebra_redistribute_send (ZEBRA_REDISTRIBUTE_DELETE, zclient, afi, i, 0, vrf_id); - -  /* If default information is needed. */ -  if (vrf_bitmap_check (zclient->default_information, VRF_DEFAULT)) -    zebra_message_send (zclient, ZEBRA_REDISTRIBUTE_DEFAULT_DELETE, vrf_id); +	int i; +	afi_t afi; + +	/* zclient is disabled. */ +	if (!zclient->enable) +		return; + +	/* If not connected to the zebra yet. */ +	if (zclient->sock < 0) +		return; + +	if (zclient_debug) +		zlog_debug("%s: send deregister messages for VRF %u", __func__, +			   vrf_id); + +	/* We need router-id information. */ +	zebra_message_send(zclient, ZEBRA_ROUTER_ID_DELETE, vrf_id); + +	/* We need interface information. */ +	zebra_message_send(zclient, ZEBRA_INTERFACE_DELETE, vrf_id); + +	/* Set unwanted redistribute route. */ +	for (afi = AFI_IP; afi < AFI_MAX; afi++) +		vrf_bitmap_set(zclient->redist[afi][zclient->redist_default], +			       vrf_id); + +	/* Flush all redistribute request. */ +	if (vrf_id == VRF_DEFAULT) +		for (afi = AFI_IP; afi < AFI_MAX; afi++) +			for (i = 0; i < ZEBRA_ROUTE_MAX; i++) +				if (zclient->mi_redist[afi][i].enabled) { +					struct listnode *node; +					u_short *id; + +					for (ALL_LIST_ELEMENTS_RO( +						     zclient->mi_redist[afi][i] +							     .instances, +						     node, id)) +						if (!(i == zclient->redist_default +						      && *id == zclient->instance)) +							zebra_redistribute_send( +								ZEBRA_REDISTRIBUTE_DELETE, +								zclient, afi, i, +								*id, +								VRF_DEFAULT); +				} + +	/* Flush all redistribute request. */ +	for (afi = AFI_IP; afi < AFI_MAX; afi++) +		for (i = 0; i < ZEBRA_ROUTE_MAX; i++) +			if (i != zclient->redist_default +			    && vrf_bitmap_check(zclient->redist[afi][i], +						vrf_id)) +				zebra_redistribute_send( +					ZEBRA_REDISTRIBUTE_DELETE, zclient, afi, +					i, 0, vrf_id); + +	/* If default information is needed. */ +	if (vrf_bitmap_check(zclient->default_information, VRF_DEFAULT)) +		zebra_message_send(zclient, ZEBRA_REDISTRIBUTE_DEFAULT_DELETE, +				   vrf_id);  }  /* Send request to zebra daemon to start or stop RA. */ -void -zclient_send_interface_radv_req (struct zclient *zclient, vrf_id_t vrf_id, -                                 struct interface *ifp, int enable, int ra_interval) +void zclient_send_interface_radv_req(struct zclient *zclient, vrf_id_t vrf_id, +				     struct interface *ifp, int enable, +				     int ra_interval)  { -  struct stream *s; +	struct stream *s; -  /* zclient is disabled. */ -  if (!zclient->enable) -    return; +	/* zclient is disabled. */ +	if (!zclient->enable) +		return; -  /* If not connected to the zebra yet. */ -  if (zclient->sock < 0) -    return; +	/* If not connected to the zebra yet. */ +	if (zclient->sock < 0) +		return; -  /* Form and send message. */ -  s = zclient->obuf; -  stream_reset (s); +	/* Form and send message. */ +	s = zclient->obuf; +	stream_reset(s); -  if (enable) -    zclient_create_header (s, ZEBRA_INTERFACE_ENABLE_RADV, vrf_id); -  else -    zclient_create_header (s, ZEBRA_INTERFACE_DISABLE_RADV, vrf_id); +	if (enable) +		zclient_create_header(s, ZEBRA_INTERFACE_ENABLE_RADV, vrf_id); +	else +		zclient_create_header(s, ZEBRA_INTERFACE_DISABLE_RADV, vrf_id); -  stream_putl (s, ifp->ifindex); -  stream_putl (s, ra_interval); +	stream_putl(s, ifp->ifindex); +	stream_putl(s, ra_interval); -  stream_putw_at (s, 0, stream_get_endp (s)); +	stream_putw_at(s, 0, stream_get_endp(s)); -  zclient_send_message(zclient); +	zclient_send_message(zclient);  }  /* Make connection to zebra daemon. */ -int -zclient_start (struct zclient *zclient) +int zclient_start(struct zclient *zclient)  { -  if (zclient_debug) -    zlog_info ("zclient_start is called"); - -  /* zclient is disabled. */ -  if (! zclient->enable) -    return 0; - -  /* If already connected to the zebra. */ -  if (zclient->sock >= 0) -    return 0; - -  /* Check connect thread. */ -  if (zclient->t_connect) -    return 0; - -  if (zclient_socket_connect(zclient) < 0) -    { -      if (zclient_debug) -	zlog_debug ("zclient connection fail"); -      zclient->fail++; -      zclient_event (ZCLIENT_CONNECT, zclient); -      return -1; -    } +	if (zclient_debug) +		zlog_info("zclient_start is called"); + +	/* zclient is disabled. */ +	if (!zclient->enable) +		return 0; + +	/* If already connected to the zebra. */ +	if (zclient->sock >= 0) +		return 0; + +	/* Check connect thread. */ +	if (zclient->t_connect) +		return 0; + +	if (zclient_socket_connect(zclient) < 0) { +		if (zclient_debug) +			zlog_debug("zclient connection fail"); +		zclient->fail++; +		zclient_event(ZCLIENT_CONNECT, zclient); +		return -1; +	} -  if (set_nonblocking(zclient->sock) < 0) -    zlog_warn("%s: set_nonblocking(%d) failed", __func__, zclient->sock); +	if (set_nonblocking(zclient->sock) < 0) +		zlog_warn("%s: set_nonblocking(%d) failed", __func__, +			  zclient->sock); -  /* Clear fail count. */ -  zclient->fail = 0; -  if (zclient_debug) -    zlog_debug ("zclient connect success with socket [%d]", zclient->sock); +	/* Clear fail count. */ +	zclient->fail = 0; +	if (zclient_debug) +		zlog_debug("zclient connect success with socket [%d]", +			   zclient->sock); -  /* Create read thread. */ -  zclient_event (ZCLIENT_READ, zclient); +	/* Create read thread. */ +	zclient_event(ZCLIENT_READ, zclient); -  zebra_hello_send (zclient); +	zebra_hello_send(zclient); -  /* Inform the successful connection. */ -  if (zclient->zebra_connected) -    (*zclient->zebra_connected) (zclient); +	/* Inform the successful connection. */ +	if (zclient->zebra_connected) +		(*zclient->zebra_connected)(zclient); -  return 0; +	return 0;  }  /* Initialize zebra client.  Argument redist_default is unwanted     redistribute route type. */ -void -zclient_init (struct zclient *zclient, int redist_default, u_short instance) +void zclient_init(struct zclient *zclient, int redist_default, u_short instance)  { -  int afi, i; -   -  /* Enable zebra client connection by default. */ -  zclient->enable = 1; - -  /* Set -1 to the default socket value. */ -  zclient->sock = -1; - -  /* Clear redistribution flags. */ -  for (afi = AFI_IP; afi < AFI_MAX; afi++) -    for (i = 0; i < ZEBRA_ROUTE_MAX; i++) -      zclient->redist[afi][i] = vrf_bitmap_init(); - -  /* Set unwanted redistribute route.  bgpd does not need BGP route -     redistribution. */ -  zclient->redist_default = redist_default; -  zclient->instance = instance; -  /* Pending: make afi(s) an arg. */ -  for (afi = AFI_IP; afi < AFI_MAX; afi++) -    redist_add_instance (&zclient->mi_redist[afi][redist_default], instance); - -  /* Set default-information redistribute to zero. */ -  zclient->default_information = vrf_bitmap_init ();; - -  if (zclient_debug) -    zlog_debug ("zclient_start is called"); - -  zclient_event (ZCLIENT_SCHEDULE, zclient); +	int afi, i; + +	/* Enable zebra client connection by default. */ +	zclient->enable = 1; + +	/* Set -1 to the default socket value. */ +	zclient->sock = -1; + +	/* Clear redistribution flags. */ +	for (afi = AFI_IP; afi < AFI_MAX; afi++) +		for (i = 0; i < ZEBRA_ROUTE_MAX; i++) +			zclient->redist[afi][i] = vrf_bitmap_init(); + +	/* Set unwanted redistribute route.  bgpd does not need BGP route +	   redistribution. */ +	zclient->redist_default = redist_default; +	zclient->instance = instance; +	/* Pending: make afi(s) an arg. */ +	for (afi = AFI_IP; afi < AFI_MAX; afi++) +		redist_add_instance(&zclient->mi_redist[afi][redist_default], +				    instance); + +	/* Set default-information redistribute to zero. */ +	zclient->default_information = vrf_bitmap_init(); +	; + +	if (zclient_debug) +		zlog_debug("zclient_start is called"); + +	zclient_event(ZCLIENT_SCHEDULE, zclient);  }  /* This function is a wrapper function for calling zclient_start from     timer or event thread. */ -static int -zclient_connect (struct thread *t) +static int zclient_connect(struct thread *t)  { -  struct zclient *zclient; +	struct zclient *zclient; -  zclient = THREAD_ARG (t); -  zclient->t_connect = NULL; +	zclient = THREAD_ARG(t); +	zclient->t_connect = NULL; -  if (zclient_debug) -    zlog_debug ("zclient_connect is called"); +	if (zclient_debug) +		zlog_debug("zclient_connect is called"); -  return zclient_start (zclient); +	return zclient_start(zclient);  } - /*  -  * "xdr_encode"-like interface that allows daemon (client) to send -  * a message to zebra server for a route that needs to be -  * added/deleted to the kernel. Info about the route is specified -  * by the caller in a struct zapi_ipv4. zapi_ipv4_read() then writes -  * the info down the zclient socket using the stream_* functions. -  *  -  * The corresponding read ("xdr_decode") function on the server -  * side is zread_ipv4_add()/zread_ipv4_delete(). -  * -  *  0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F -  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -  * |            Length (2)         |    Command    | Route Type    | -  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -  * | ZEBRA Flags   | Message Flags | Prefix length | -  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -  * | Destination IPv4 Prefix for route                             | -  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -  * | Nexthop count |  -  * +-+-+-+-+-+-+-+-+ -  * -  *  -  * A number of IPv4 nexthop(s) or nexthop interface index(es) are then  -  * described, as per the Nexthop count. Each nexthop described as: -  * -  * +-+-+-+-+-+-+-+-+ -  * | Nexthop Type  |  Set to one of ZEBRA_NEXTHOP_* -  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -  * |       IPv4 Nexthop address or Interface Index number          | -  * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -  * -  * Alternatively, if the flags field has ZEBRA_FLAG_BLACKHOLE or -  * ZEBRA_FLAG_REJECT is set then Nexthop count is set to 1, then _no_  -  * nexthop information is provided, and the message describes a prefix -  * to blackhole or reject route. -  * -  * The original struct zapi_ipv4, zapi_ipv4_route() and zread_ipv4_*() -  * infrastructure was built around the traditional (32-bit "gate OR -  * ifindex") nexthop data unit. A special encoding can be used to feed -  * onlink (64-bit "gate AND ifindex") nexthops into zapi_ipv4_route() -  * using the same zapi_ipv4 structure. This is done by setting zapi_ipv4 -  * fields as follows: -  *  - .message |= ZAPI_MESSAGE_NEXTHOP | ZAPI_MESSAGE_ONLINK -  *  - .nexthop_num == .ifindex_num -  *  - .nexthop and .ifindex are filled with gate and ifindex parts of -  *    each compound nexthop, both in the same order -  * -  * zapi_ipv4_route() will produce two nexthop data units for each such -  * interleaved 64-bit nexthop. On the zserv side of the socket it will be -  * mapped to a singlle NEXTHOP_TYPE_IPV4_IFINDEX_OL RIB nexthop structure. -  * -  * If ZAPI_MESSAGE_DISTANCE is set, the distance value is written as a 1 -  * byte value. -  *  -  * If ZAPI_MESSAGE_METRIC is set, the metric value is written as an 8 -  * byte value. -  * -  * If ZAPI_MESSAGE_TAG is set, the tag value is written as a 4 byte value -  * -  * If ZAPI_MESSAGE_MTU is set, the mtu value is written as a 4 byte value -  * -  * XXX: No attention paid to alignment. -  */  -int -zapi_ipv4_route (u_char cmd, struct zclient *zclient, struct prefix_ipv4 *p, -                 struct zapi_ipv4 *api) +/* + * "xdr_encode"-like interface that allows daemon (client) to send + * a message to zebra server for a route that needs to be + * added/deleted to the kernel. Info about the route is specified + * by the caller in a struct zapi_ipv4. zapi_ipv4_read() then writes + * the info down the zclient socket using the stream_* functions. + * + * The corresponding read ("xdr_decode") function on the server + * side is zread_ipv4_add()/zread_ipv4_delete(). + * + *  0 1 2 3 4 5 6 7 8 9 A B C D E F 0 1 2 3 4 5 6 7 8 9 A B C D E F + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * |            Length (2)         |    Command    | Route Type    | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | ZEBRA Flags   | Message Flags | Prefix length | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Destination IPv4 Prefix for route                             | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | Nexthop count | + * +-+-+-+-+-+-+-+-+ + * + * + * A number of IPv4 nexthop(s) or nexthop interface index(es) are then + * described, as per the Nexthop count. Each nexthop described as: + * + * +-+-+-+-+-+-+-+-+ + * | Nexthop Type  |  Set to one of ZEBRA_NEXTHOP_* + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * |       IPv4 Nexthop address or Interface Index number          | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + * Alternatively, if the flags field has ZEBRA_FLAG_BLACKHOLE or + * ZEBRA_FLAG_REJECT is set then Nexthop count is set to 1, then _no_ + * nexthop information is provided, and the message describes a prefix + * to blackhole or reject route. + * + * The original struct zapi_ipv4, zapi_ipv4_route() and zread_ipv4_*() + * infrastructure was built around the traditional (32-bit "gate OR + * ifindex") nexthop data unit. A special encoding can be used to feed + * onlink (64-bit "gate AND ifindex") nexthops into zapi_ipv4_route() + * using the same zapi_ipv4 structure. This is done by setting zapi_ipv4 + * fields as follows: + *  - .message |= ZAPI_MESSAGE_NEXTHOP | ZAPI_MESSAGE_ONLINK + *  - .nexthop_num == .ifindex_num + *  - .nexthop and .ifindex are filled with gate and ifindex parts of + *    each compound nexthop, both in the same order + * + * zapi_ipv4_route() will produce two nexthop data units for each such + * interleaved 64-bit nexthop. On the zserv side of the socket it will be + * mapped to a singlle NEXTHOP_TYPE_IPV4_IFINDEX_OL RIB nexthop structure. + * + * If ZAPI_MESSAGE_DISTANCE is set, the distance value is written as a 1 + * byte value. + * + * If ZAPI_MESSAGE_METRIC is set, the metric value is written as an 8 + * byte value. + * + * If ZAPI_MESSAGE_TAG is set, the tag value is written as a 4 byte value + * + * If ZAPI_MESSAGE_MTU is set, the mtu value is written as a 4 byte value + * + * XXX: No attention paid to alignment. + */ +int zapi_ipv4_route(u_char cmd, struct zclient *zclient, struct prefix_ipv4 *p, +		    struct zapi_ipv4 *api)  { -  int i; -  int psize; -  struct stream *s; - -  /* Reset stream. */ -  s = zclient->obuf; -  stream_reset (s); - -  zclient_create_header (s, cmd, api->vrf_id); -   -  /* Put type and nexthop. */ -  stream_putc (s, api->type); -  stream_putw (s, api->instance); -  stream_putl (s, api->flags); -  stream_putc (s, api->message); -  stream_putw (s, api->safi); - -  /* Put prefix information. */ -  psize = PSIZE (p->prefixlen); -  stream_putc (s, p->prefixlen); -  stream_write (s, (u_char *) & p->prefix, psize); - -  /* Nexthop, ifindex, distance and metric information. */ -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_NEXTHOP)) -     { -      /* traditional 32-bit data units */ -      if (CHECK_FLAG (api->flags, ZEBRA_FLAG_BLACKHOLE)) -        { -          stream_putc (s, 1); -          stream_putc (s, NEXTHOP_TYPE_BLACKHOLE); -          /* XXX assert(api->nexthop_num == 0); */ -          /* XXX assert(api->ifindex_num == 0); */ -        } -      else -        stream_putc (s, api->nexthop_num + api->ifindex_num); - -      for (i = 0; i < api->nexthop_num; i++) -        { -          stream_putc (s, NEXTHOP_TYPE_IPV4); -          stream_put_in_addr (s, api->nexthop[i]); -        } -      for (i = 0; i < api->ifindex_num; i++) -        { -          stream_putc (s, NEXTHOP_TYPE_IFINDEX); -          stream_putl (s, api->ifindex[i]); -        } -    } - -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_DISTANCE)) -    stream_putc (s, api->distance); -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_METRIC)) -    stream_putl (s, api->metric); -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_TAG)) -    stream_putl (s, api->tag); -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_MTU)) -    stream_putl (s, api->mtu); - -  /* Put length at the first point of the stream. */ -  stream_putw_at (s, 0, stream_get_endp (s)); - -  return zclient_send_message(zclient); +	int i; +	int psize; +	struct stream *s; + +	/* Reset stream. */ +	s = zclient->obuf; +	stream_reset(s); + +	zclient_create_header(s, cmd, api->vrf_id); + +	/* Put type and nexthop. */ +	stream_putc(s, api->type); +	stream_putw(s, api->instance); +	stream_putl(s, api->flags); +	stream_putc(s, api->message); +	stream_putw(s, api->safi); + +	/* Put prefix information. */ +	psize = PSIZE(p->prefixlen); +	stream_putc(s, p->prefixlen); +	stream_write(s, (u_char *)&p->prefix, psize); + +	/* Nexthop, ifindex, distance and metric information. */ +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_NEXTHOP)) { +		/* traditional 32-bit data units */ +		if (CHECK_FLAG(api->flags, ZEBRA_FLAG_BLACKHOLE)) { +			stream_putc(s, 1); +			stream_putc(s, NEXTHOP_TYPE_BLACKHOLE); +			/* XXX assert(api->nexthop_num == 0); */ +			/* XXX assert(api->ifindex_num == 0); */ +		} else +			stream_putc(s, api->nexthop_num + api->ifindex_num); + +		for (i = 0; i < api->nexthop_num; i++) { +			stream_putc(s, NEXTHOP_TYPE_IPV4); +			stream_put_in_addr(s, api->nexthop[i]); +		} +		for (i = 0; i < api->ifindex_num; i++) { +			stream_putc(s, NEXTHOP_TYPE_IFINDEX); +			stream_putl(s, api->ifindex[i]); +		} +	} + +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_DISTANCE)) +		stream_putc(s, api->distance); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_METRIC)) +		stream_putl(s, api->metric); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_TAG)) +		stream_putl(s, api->tag); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_MTU)) +		stream_putl(s, api->mtu); + +	/* Put length at the first point of the stream. */ +	stream_putw_at(s, 0, stream_get_endp(s)); + +	return zclient_send_message(zclient);  } -int -zapi_ipv4_route_ipv6_nexthop (u_char cmd, struct zclient *zclient, -                              struct prefix_ipv4 *p, struct zapi_ipv6 *api) +int zapi_ipv4_route_ipv6_nexthop(u_char cmd, struct zclient *zclient, +				 struct prefix_ipv4 *p, struct zapi_ipv6 *api)  { -  int i; -  int psize; -  struct stream *s; - -  /* Reset stream. */ -  s = zclient->obuf; -  stream_reset (s); - -  zclient_create_header (s, cmd, api->vrf_id); - -  /* Put type and nexthop. */ -  stream_putc (s, api->type); -  stream_putw (s, api->instance); -  stream_putl (s, api->flags); -  stream_putc (s, api->message); -  stream_putw (s, api->safi); - -  /* Put prefix information. */ -  psize = PSIZE (p->prefixlen); -  stream_putc (s, p->prefixlen); -  stream_write (s, (u_char *) & p->prefix, psize); - -  /* Nexthop, ifindex, distance and metric information. */ -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_NEXTHOP)) -    { -      if (CHECK_FLAG (api->flags, ZEBRA_FLAG_BLACKHOLE)) -        { -          stream_putc (s, 1); -          stream_putc (s, NEXTHOP_TYPE_BLACKHOLE); -          /* XXX assert(api->nexthop_num == 0); */ -          /* XXX assert(api->ifindex_num == 0); */ -        } -      else -	stream_putc (s, api->nexthop_num + api->ifindex_num); - -      for (i = 0; i < api->nexthop_num; i++) -	{ -	  stream_putc (s, NEXTHOP_TYPE_IPV6); -	  stream_write (s, (u_char *)api->nexthop[i], 16); -	} -      for (i = 0; i < api->ifindex_num; i++) -	{ -	  stream_putc (s, NEXTHOP_TYPE_IFINDEX); -	  stream_putl (s, api->ifindex[i]); +	int i; +	int psize; +	struct stream *s; + +	/* Reset stream. */ +	s = zclient->obuf; +	stream_reset(s); + +	zclient_create_header(s, cmd, api->vrf_id); + +	/* Put type and nexthop. */ +	stream_putc(s, api->type); +	stream_putw(s, api->instance); +	stream_putl(s, api->flags); +	stream_putc(s, api->message); +	stream_putw(s, api->safi); + +	/* Put prefix information. */ +	psize = PSIZE(p->prefixlen); +	stream_putc(s, p->prefixlen); +	stream_write(s, (u_char *)&p->prefix, psize); + +	/* Nexthop, ifindex, distance and metric information. */ +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_NEXTHOP)) { +		if (CHECK_FLAG(api->flags, ZEBRA_FLAG_BLACKHOLE)) { +			stream_putc(s, 1); +			stream_putc(s, NEXTHOP_TYPE_BLACKHOLE); +			/* XXX assert(api->nexthop_num == 0); */ +			/* XXX assert(api->ifindex_num == 0); */ +		} else +			stream_putc(s, api->nexthop_num + api->ifindex_num); + +		for (i = 0; i < api->nexthop_num; i++) { +			stream_putc(s, NEXTHOP_TYPE_IPV6); +			stream_write(s, (u_char *)api->nexthop[i], 16); +		} +		for (i = 0; i < api->ifindex_num; i++) { +			stream_putc(s, NEXTHOP_TYPE_IFINDEX); +			stream_putl(s, api->ifindex[i]); +		}  	} -    } -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_DISTANCE)) -    stream_putc (s, api->distance); -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_METRIC)) -    stream_putl (s, api->metric); -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_TAG)) -    stream_putl (s, api->tag); -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_MTU)) -    stream_putl (s, api->mtu); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_DISTANCE)) +		stream_putc(s, api->distance); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_METRIC)) +		stream_putl(s, api->metric); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_TAG)) +		stream_putl(s, api->tag); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_MTU)) +		stream_putl(s, api->mtu); -  /* Put length at the first point of the stream. */ -  stream_putw_at (s, 0, stream_get_endp (s)); +	/* Put length at the first point of the stream. */ +	stream_putw_at(s, 0, stream_get_endp(s)); -  return zclient_send_message(zclient); +	return zclient_send_message(zclient);  } -int -zapi_ipv6_route (u_char cmd, struct zclient *zclient, struct prefix_ipv6 *p, -		 struct prefix_ipv6 *src_p, struct zapi_ipv6 *api) +int zapi_ipv6_route(u_char cmd, struct zclient *zclient, struct prefix_ipv6 *p, +		    struct prefix_ipv6 *src_p, struct zapi_ipv6 *api)  { -  int i; -  int psize; -  struct stream *s; - -  /* either we have !SRCPFX && src_p == NULL, or SRCPFX && src_p != NULL */ -  assert (!(api->message & ZAPI_MESSAGE_SRCPFX) == !src_p); - -  /* Reset stream. */ -  s = zclient->obuf; -  stream_reset (s); - -  zclient_create_header (s, cmd, api->vrf_id); - -  /* Put type and nexthop. */ -  stream_putc (s, api->type); -  stream_putw (s, api->instance); -  stream_putl (s, api->flags); -  stream_putc (s, api->message); -  stream_putw (s, api->safi); -   -  /* Put prefix information. */ -  psize = PSIZE (p->prefixlen); -  stream_putc (s, p->prefixlen); -  stream_write (s, (u_char *)&p->prefix, psize); - -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_SRCPFX)) -    { -      psize = PSIZE (src_p->prefixlen); -      stream_putc (s, src_p->prefixlen); -      stream_write (s, (u_char *)&src_p->prefix, psize); -    } - -  /* Nexthop, ifindex, distance and metric information. */ -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_NEXTHOP)) -    { -      if (CHECK_FLAG (api->flags, ZEBRA_FLAG_BLACKHOLE)) -        { -          stream_putc (s, 1); -          stream_putc (s, NEXTHOP_TYPE_BLACKHOLE); -          /* XXX assert(api->nexthop_num == 0); */ -          /* XXX assert(api->ifindex_num == 0); */ -        } -      else -	stream_putc (s, api->nexthop_num + api->ifindex_num); - -      for (i = 0; i < api->nexthop_num; i++) -	{ -	  stream_putc (s, NEXTHOP_TYPE_IPV6); -	  stream_write (s, (u_char *)api->nexthop[i], 16); +	int i; +	int psize; +	struct stream *s; + +	/* either we have !SRCPFX && src_p == NULL, or SRCPFX && src_p != NULL +	 */ +	assert(!(api->message & ZAPI_MESSAGE_SRCPFX) == !src_p); + +	/* Reset stream. */ +	s = zclient->obuf; +	stream_reset(s); + +	zclient_create_header(s, cmd, api->vrf_id); + +	/* Put type and nexthop. */ +	stream_putc(s, api->type); +	stream_putw(s, api->instance); +	stream_putl(s, api->flags); +	stream_putc(s, api->message); +	stream_putw(s, api->safi); + +	/* Put prefix information. */ +	psize = PSIZE(p->prefixlen); +	stream_putc(s, p->prefixlen); +	stream_write(s, (u_char *)&p->prefix, psize); + +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_SRCPFX)) { +		psize = PSIZE(src_p->prefixlen); +		stream_putc(s, src_p->prefixlen); +		stream_write(s, (u_char *)&src_p->prefix, psize);  	} -      for (i = 0; i < api->ifindex_num; i++) -	{ -	  stream_putc (s, NEXTHOP_TYPE_IFINDEX); -	  stream_putl (s, api->ifindex[i]); + +	/* Nexthop, ifindex, distance and metric information. */ +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_NEXTHOP)) { +		if (CHECK_FLAG(api->flags, ZEBRA_FLAG_BLACKHOLE)) { +			stream_putc(s, 1); +			stream_putc(s, NEXTHOP_TYPE_BLACKHOLE); +			/* XXX assert(api->nexthop_num == 0); */ +			/* XXX assert(api->ifindex_num == 0); */ +		} else +			stream_putc(s, api->nexthop_num + api->ifindex_num); + +		for (i = 0; i < api->nexthop_num; i++) { +			stream_putc(s, NEXTHOP_TYPE_IPV6); +			stream_write(s, (u_char *)api->nexthop[i], 16); +		} +		for (i = 0; i < api->ifindex_num; i++) { +			stream_putc(s, NEXTHOP_TYPE_IFINDEX); +			stream_putl(s, api->ifindex[i]); +		}  	} -    } -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_DISTANCE)) -    stream_putc (s, api->distance); -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_METRIC)) -    stream_putl (s, api->metric); -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_TAG)) -    stream_putl (s, api->tag); -  if (CHECK_FLAG (api->message, ZAPI_MESSAGE_MTU)) -    stream_putl (s, api->mtu); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_DISTANCE)) +		stream_putc(s, api->distance); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_METRIC)) +		stream_putl(s, api->metric); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_TAG)) +		stream_putl(s, api->tag); +	if (CHECK_FLAG(api->message, ZAPI_MESSAGE_MTU)) +		stream_putl(s, api->mtu); -  /* Put length at the first point of the stream. */ -  stream_putw_at (s, 0, stream_get_endp (s)); +	/* Put length at the first point of the stream. */ +	stream_putw_at(s, 0, stream_get_endp(s)); -  return zclient_send_message(zclient); +	return zclient_send_message(zclient);  } -/*  +/*   * send a ZEBRA_REDISTRIBUTE_ADD or ZEBRA_REDISTRIBUTE_DELETE   * for the route type (ZEBRA_ROUTE_KERNEL etc.). The zebra server will - * then set/unset redist[type] in the client handle (a struct zserv) for the  + * then set/unset redist[type] in the client handle (a struct zserv) for the   * sending client   */ -int -zebra_redistribute_send (int command, struct zclient *zclient, afi_t afi, int type, -                         u_short instance, vrf_id_t vrf_id) +int zebra_redistribute_send(int command, struct zclient *zclient, afi_t afi, +			    int type, u_short instance, vrf_id_t vrf_id)  { -  struct stream *s; - -  s = zclient->obuf; -  stream_reset(s); -   -  zclient_create_header (s, command, vrf_id); -  stream_putc (s, afi); -  stream_putc (s, type); -  stream_putw (s, instance); -   -  stream_putw_at (s, 0, stream_get_endp (s)); -   -  return zclient_send_message(zclient); +	struct stream *s; + +	s = zclient->obuf; +	stream_reset(s); + +	zclient_create_header(s, command, vrf_id); +	stream_putc(s, afi); +	stream_putc(s, type); +	stream_putw(s, instance); + +	stream_putw_at(s, 0, stream_get_endp(s)); + +	return zclient_send_message(zclient);  }  /* Get prefix in ZServ format; family should be filled in on prefix */ -static void -zclient_stream_get_prefix (struct stream *s, struct prefix *p) +static void zclient_stream_get_prefix(struct stream *s, struct prefix *p)  { -  size_t plen = prefix_blen (p); -  u_char c; -  p->prefixlen = 0; -   -  if (plen == 0) -    return; -   -  stream_get (&p->u.prefix, s, plen); -  c = stream_getc(s); -  p->prefixlen = MIN(plen * 8, c); +	size_t plen = prefix_blen(p); +	u_char c; +	p->prefixlen = 0; + +	if (plen == 0) +		return; + +	stream_get(&p->u.prefix, s, plen); +	c = stream_getc(s); +	p->prefixlen = MIN(plen * 8, c);  }  /* Router-id update from zebra daemon. */ -void -zebra_router_id_update_read (struct stream *s, struct prefix *rid) +void zebra_router_id_update_read(struct stream *s, struct prefix *rid)  { -  /* Fetch interface address. */ -  rid->family = stream_getc (s); -   -  zclient_stream_get_prefix (s, rid); +	/* Fetch interface address. */ +	rid->family = stream_getc(s); + +	zclient_stream_get_prefix(s, rid);  }  /* Interface addition from zebra daemon. */ -/*   +/*   * The format of the message sent with type ZEBRA_INTERFACE_ADD or   * ZEBRA_INTERFACE_DELETE from zebra to the client is:   *     0                   1                   2                   3 @@ -1025,225 +1010,215 @@ zebra_router_id_update_read (struct stream *s, struct prefix *rid)   * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+   */ -static void -zclient_vrf_add (struct zclient *zclient, vrf_id_t vrf_id) +static void zclient_vrf_add(struct zclient *zclient, vrf_id_t vrf_id)  { -  struct vrf *vrf; -  char vrfname_tmp[VRF_NAMSIZ]; +	struct vrf *vrf; +	char vrfname_tmp[VRF_NAMSIZ]; -  /* Read interface name. */ -  stream_get (vrfname_tmp, zclient->ibuf, VRF_NAMSIZ); +	/* Read interface name. */ +	stream_get(vrfname_tmp, zclient->ibuf, VRF_NAMSIZ); -  /* Lookup/create vrf by vrf_id. */ -  vrf = vrf_get (vrf_id, vrfname_tmp); +	/* Lookup/create vrf by vrf_id. */ +	vrf = vrf_get(vrf_id, vrfname_tmp); -  vrf_enable (vrf); +	vrf_enable(vrf);  } -static void -zclient_vrf_delete (struct zclient *zclient, vrf_id_t vrf_id) +static void zclient_vrf_delete(struct zclient *zclient, vrf_id_t vrf_id)  { -  struct vrf *vrf; +	struct vrf *vrf; -  /* Lookup vrf by vrf_id. */ -  vrf = vrf_lookup_by_id (vrf_id); +	/* Lookup vrf by vrf_id. */ +	vrf = vrf_lookup_by_id(vrf_id); -  /* -   * If a routing protocol doesn't know about a -   * vrf that is about to be deleted.  There is -   * no point in attempting to delete it. -   */ -  if (!vrf) -    return; +	/* +	 * If a routing protocol doesn't know about a +	 * vrf that is about to be deleted.  There is +	 * no point in attempting to delete it. +	 */ +	if (!vrf) +		return; -  vrf_delete (vrf); +	vrf_delete(vrf);  } -struct interface * -zebra_interface_add_read (struct stream *s, vrf_id_t vrf_id) +struct interface *zebra_interface_add_read(struct stream *s, vrf_id_t vrf_id)  { -  struct interface *ifp; -  char ifname_tmp[INTERFACE_NAMSIZ]; +	struct interface *ifp; +	char ifname_tmp[INTERFACE_NAMSIZ]; -  /* Read interface name. */ -  stream_get (ifname_tmp, s, INTERFACE_NAMSIZ); +	/* Read interface name. */ +	stream_get(ifname_tmp, s, INTERFACE_NAMSIZ); -  /* Lookup/create interface by name. */ -  ifp = if_get_by_name_len (ifname_tmp, -                            strnlen (ifname_tmp, INTERFACE_NAMSIZ), -                            vrf_id, 0); +	/* Lookup/create interface by name. */ +	ifp = if_get_by_name_len( +		ifname_tmp, strnlen(ifname_tmp, INTERFACE_NAMSIZ), vrf_id, 0); -  zebra_interface_if_set_value (s, ifp); +	zebra_interface_if_set_value(s, ifp); -  return ifp; +	return ifp;  } -/*  +/*   * Read interface up/down msg (ZEBRA_INTERFACE_UP/ZEBRA_INTERFACE_DOWN)   * from zebra server.  The format of this message is the same as   * that sent for ZEBRA_INTERFACE_ADD/ZEBRA_INTERFACE_DELETE (see   * comments for zebra_interface_add_read), except that no sockaddr_dl   * is sent at the tail of the message.   */ -struct interface * -zebra_interface_state_read (struct stream *s, vrf_id_t vrf_id) +struct interface *zebra_interface_state_read(struct stream *s, vrf_id_t vrf_id)  { -  struct interface *ifp; -  char ifname_tmp[INTERFACE_NAMSIZ]; - -  /* Read interface name. */ -  stream_get (ifname_tmp, s, INTERFACE_NAMSIZ); - -  /* Lookup this by interface index. */ -  ifp = if_lookup_by_name_len (ifname_tmp, -                               strnlen (ifname_tmp, INTERFACE_NAMSIZ), -                               vrf_id); -  if (ifp == NULL) -    { -      zlog_warn ("INTERFACE_STATE: Cannot find IF %s in VRF %d", -                 ifname_tmp, vrf_id); -      return NULL; -    } - -  zebra_interface_if_set_value (s, ifp); - -  return ifp; +	struct interface *ifp; +	char ifname_tmp[INTERFACE_NAMSIZ]; + +	/* Read interface name. */ +	stream_get(ifname_tmp, s, INTERFACE_NAMSIZ); + +	/* Lookup this by interface index. */ +	ifp = if_lookup_by_name_len( +		ifname_tmp, strnlen(ifname_tmp, INTERFACE_NAMSIZ), vrf_id); +	if (ifp == NULL) { +		zlog_warn("INTERFACE_STATE: Cannot find IF %s in VRF %d", +			  ifname_tmp, vrf_id); +		return NULL; +	} + +	zebra_interface_if_set_value(s, ifp); + +	return ifp;  } -static void -link_params_set_value(struct stream *s, struct if_link_params *iflp) +static void link_params_set_value(struct stream *s, struct if_link_params *iflp)  { -  if (iflp == NULL) -    return; - -  iflp->lp_status = stream_getl (s); -  iflp->te_metric = stream_getl (s); -  iflp->max_bw = stream_getf (s); -  iflp->max_rsv_bw = stream_getf (s); -  uint32_t bwclassnum = stream_getl (s); -  { -    unsigned int i; -    for (i = 0; i < bwclassnum && i < MAX_CLASS_TYPE; i++) -      iflp->unrsv_bw[i] = stream_getf (s); -    if (i < bwclassnum) -      zlog_err ("%s: received %d > %d (MAX_CLASS_TYPE) bw entries" -                " - outdated library?", -                __func__, bwclassnum, MAX_CLASS_TYPE); -  } -  iflp->admin_grp = stream_getl (s); -  iflp->rmt_as = stream_getl (s); -  iflp->rmt_ip.s_addr = stream_get_ipv4 (s); - -  iflp->av_delay = stream_getl (s); -  iflp->min_delay = stream_getl (s); -  iflp->max_delay = stream_getl (s); -  iflp->delay_var = stream_getl (s); - -  iflp->pkt_loss = stream_getf (s); -  iflp->res_bw = stream_getf (s); -  iflp->ava_bw = stream_getf (s); -  iflp->use_bw = stream_getf (s); +	if (iflp == NULL) +		return; + +	iflp->lp_status = stream_getl(s); +	iflp->te_metric = stream_getl(s); +	iflp->max_bw = stream_getf(s); +	iflp->max_rsv_bw = stream_getf(s); +	uint32_t bwclassnum = stream_getl(s); +	{ +		unsigned int i; +		for (i = 0; i < bwclassnum && i < MAX_CLASS_TYPE; i++) +			iflp->unrsv_bw[i] = stream_getf(s); +		if (i < bwclassnum) +			zlog_err( +				"%s: received %d > %d (MAX_CLASS_TYPE) bw entries" +				" - outdated library?", +				__func__, bwclassnum, MAX_CLASS_TYPE); +	} +	iflp->admin_grp = stream_getl(s); +	iflp->rmt_as = stream_getl(s); +	iflp->rmt_ip.s_addr = stream_get_ipv4(s); + +	iflp->av_delay = stream_getl(s); +	iflp->min_delay = stream_getl(s); +	iflp->max_delay = stream_getl(s); +	iflp->delay_var = stream_getl(s); + +	iflp->pkt_loss = stream_getf(s); +	iflp->res_bw = stream_getf(s); +	iflp->ava_bw = stream_getf(s); +	iflp->use_bw = stream_getf(s);  } -struct interface * -zebra_interface_link_params_read (struct stream *s) +struct interface *zebra_interface_link_params_read(struct stream *s)  { -  struct if_link_params *iflp; -  ifindex_t ifindex; +	struct if_link_params *iflp; +	ifindex_t ifindex; -  assert (s); +	assert(s); -  ifindex = stream_getl (s); +	ifindex = stream_getl(s); -  struct interface *ifp = if_lookup_by_index (ifindex, VRF_DEFAULT); +	struct interface *ifp = if_lookup_by_index(ifindex, VRF_DEFAULT); -  if (ifp == NULL) -    { -      zlog_err ("%s: unknown ifindex %u, shouldn't happen", -                __func__, ifindex); -      return NULL; -    } +	if (ifp == NULL) { +		zlog_err("%s: unknown ifindex %u, shouldn't happen", __func__, +			 ifindex); +		return NULL; +	} -  if ((iflp = if_link_params_get (ifp)) == NULL) -    return NULL; +	if ((iflp = if_link_params_get(ifp)) == NULL) +		return NULL; -  link_params_set_value(s, iflp); +	link_params_set_value(s, iflp); -  return ifp; +	return ifp;  } -void -zebra_interface_if_set_value (struct stream *s, struct interface *ifp) +void zebra_interface_if_set_value(struct stream *s, struct interface *ifp)  { -  u_char link_params_status = 0; - -  /* Read interface's index. */ -  ifp->ifindex = stream_getl (s); -  ifp->status = stream_getc (s); - -  /* Read interface's value. */ -  ifp->flags = stream_getq (s); -  ifp->ptm_enable = stream_getc (s); -  ifp->ptm_status = stream_getc (s); -  ifp->metric = stream_getl (s); -  ifp->speed = stream_getl (s); -  ifp->mtu = stream_getl (s); -  ifp->mtu6 = stream_getl (s); -  ifp->bandwidth = stream_getl (s); -  ifp->ll_type = stream_getl (s); -  ifp->hw_addr_len = stream_getl (s); -  if (ifp->hw_addr_len) -    stream_get (ifp->hw_addr, s, MIN(ifp->hw_addr_len, INTERFACE_HWADDR_MAX)); - -  /* Read Traffic Engineering status */ -  link_params_status = stream_getc (s); -  /* Then, Traffic Engineering parameters if any */ -  if (link_params_status) -    { -      struct if_link_params *iflp = if_link_params_get (ifp); -      link_params_set_value(s, iflp); -    } +	u_char link_params_status = 0; + +	/* Read interface's index. */ +	ifp->ifindex = stream_getl(s); +	ifp->status = stream_getc(s); + +	/* Read interface's value. */ +	ifp->flags = stream_getq(s); +	ifp->ptm_enable = stream_getc(s); +	ifp->ptm_status = stream_getc(s); +	ifp->metric = stream_getl(s); +	ifp->speed = stream_getl(s); +	ifp->mtu = stream_getl(s); +	ifp->mtu6 = stream_getl(s); +	ifp->bandwidth = stream_getl(s); +	ifp->ll_type = stream_getl(s); +	ifp->hw_addr_len = stream_getl(s); +	if (ifp->hw_addr_len) +		stream_get(ifp->hw_addr, s, +			   MIN(ifp->hw_addr_len, INTERFACE_HWADDR_MAX)); + +	/* Read Traffic Engineering status */ +	link_params_status = stream_getc(s); +	/* Then, Traffic Engineering parameters if any */ +	if (link_params_status) { +		struct if_link_params *iflp = if_link_params_get(ifp); +		link_params_set_value(s, iflp); +	}  } -size_t -zebra_interface_link_params_write (struct stream *s, struct interface *ifp) +size_t zebra_interface_link_params_write(struct stream *s, +					 struct interface *ifp)  { -  size_t w; -  struct if_link_params *iflp; -  int i; +	size_t w; +	struct if_link_params *iflp; +	int i; -  if (s == NULL || ifp == NULL || ifp->link_params == NULL) -    return 0; +	if (s == NULL || ifp == NULL || ifp->link_params == NULL) +		return 0; -  iflp = ifp->link_params; -  w = 0; +	iflp = ifp->link_params; +	w = 0; -  w += stream_putl (s, iflp->lp_status); +	w += stream_putl(s, iflp->lp_status); -  w += stream_putl (s, iflp->te_metric); -  w += stream_putf (s, iflp->max_bw); -  w += stream_putf (s, iflp->max_rsv_bw); +	w += stream_putl(s, iflp->te_metric); +	w += stream_putf(s, iflp->max_bw); +	w += stream_putf(s, iflp->max_rsv_bw); -  w += stream_putl (s, MAX_CLASS_TYPE); -  for (i = 0; i < MAX_CLASS_TYPE; i++) -    w += stream_putf (s, iflp->unrsv_bw[i]); +	w += stream_putl(s, MAX_CLASS_TYPE); +	for (i = 0; i < MAX_CLASS_TYPE; i++) +		w += stream_putf(s, iflp->unrsv_bw[i]); -  w += stream_putl (s, iflp->admin_grp); -  w += stream_putl (s, iflp->rmt_as); -  w += stream_put_in_addr (s, &iflp->rmt_ip); +	w += stream_putl(s, iflp->admin_grp); +	w += stream_putl(s, iflp->rmt_as); +	w += stream_put_in_addr(s, &iflp->rmt_ip); -  w += stream_putl (s, iflp->av_delay); -  w += stream_putl (s, iflp->min_delay); -  w += stream_putl (s, iflp->max_delay); -  w += stream_putl (s, iflp->delay_var); +	w += stream_putl(s, iflp->av_delay); +	w += stream_putl(s, iflp->min_delay); +	w += stream_putl(s, iflp->max_delay); +	w += stream_putl(s, iflp->delay_var); -  w += stream_putf (s, iflp->pkt_loss); -  w += stream_putf (s, iflp->res_bw); -  w += stream_putf (s, iflp->ava_bw); -  w += stream_putf (s, iflp->use_bw); +	w += stream_putf(s, iflp->pkt_loss); +	w += stream_putf(s, iflp->res_bw); +	w += stream_putf(s, iflp->ava_bw); +	w += stream_putf(s, iflp->use_bw); -  return w; +	return w;  }  /* @@ -1277,91 +1252,87 @@ zebra_interface_link_params_write (struct stream *s, struct interface *ifp)   * +-+-+-+-+-+-+-+-+   */ -static int -memconstant(const void *s, int c, size_t n) +static int memconstant(const void *s, int c, size_t n)  { -  const u_char *p = s; +	const u_char *p = s; -  while (n-- > 0) -    if (*p++ != c) -      return 0; -  return 1; +	while (n-- > 0) +		if (*p++ != c) +			return 0; +	return 1;  } -struct connected * -zebra_interface_address_read (int type, struct stream *s, vrf_id_t vrf_id) +struct connected *zebra_interface_address_read(int type, struct stream *s, +					       vrf_id_t vrf_id)  { -  ifindex_t ifindex; -  struct interface *ifp; -  struct connected *ifc; -  struct prefix p, d, *dp; -  int plen; -  u_char ifc_flags; - -  memset (&p, 0, sizeof(p)); -  memset (&d, 0, sizeof(d)); - -  /* Get interface index. */ -  ifindex = stream_getl (s); - -  /* Lookup index. */ -  ifp = if_lookup_by_index (ifindex, vrf_id); -  if (ifp == NULL) -    { -      zlog_warn ("INTERFACE_ADDRESS_%s: Cannot find IF %u in VRF %d", -                 (type == ZEBRA_INTERFACE_ADDRESS_ADD) ? "ADD" : "DEL", -                 ifindex, vrf_id); -      return NULL; -    } - -  /* Fetch flag. */ -  ifc_flags = stream_getc (s); - -  /* Fetch interface address. */ -  d.family = p.family = stream_getc (s); -  plen = prefix_blen (&d); -   -  zclient_stream_get_prefix (s, &p); - -  /* Fetch destination address. */ -  stream_get (&d.u.prefix, s, plen); -   -  /* N.B. NULL destination pointers are encoded as all zeroes */ -  dp = memconstant(&d.u.prefix,0,plen) ? NULL : &d; -   -  if (type == ZEBRA_INTERFACE_ADDRESS_ADD)  -    { -      ifc = connected_lookup_prefix_exact (ifp, &p); -      if (!ifc) -        { -          /* N.B. NULL destination pointers are encoded as all zeroes */ -          ifc = connected_add_by_prefix(ifp, &p, dp); -        } -       if (ifc) -	 { -	   ifc->flags = ifc_flags; -	   if (ifc->destination) -	     ifc->destination->prefixlen = ifc->address->prefixlen; -	   else if (CHECK_FLAG(ifc->flags, ZEBRA_IFA_PEER)) -	     { -	       /* carp interfaces on OpenBSD with 0.0.0.0/0 as "peer" */ -	       char buf[PREFIX_STRLEN]; -	       zlog_warn("warning: interface %s address %s " -		    "with peer flag set, but no peer address!", -		    ifp->name, -		    prefix2str (ifc->address, buf, sizeof buf)); -	       UNSET_FLAG(ifc->flags, ZEBRA_IFA_PEER); -	     } -	 } -    } -  else -    { -      assert (type == ZEBRA_INTERFACE_ADDRESS_DELETE); -      ifc = connected_delete_by_prefix(ifp, &p); -    } - -  return ifc; +	ifindex_t ifindex; +	struct interface *ifp; +	struct connected *ifc; +	struct prefix p, d, *dp; +	int plen; +	u_char ifc_flags; + +	memset(&p, 0, sizeof(p)); +	memset(&d, 0, sizeof(d)); + +	/* Get interface index. */ +	ifindex = stream_getl(s); + +	/* Lookup index. */ +	ifp = if_lookup_by_index(ifindex, vrf_id); +	if (ifp == NULL) { +		zlog_warn("INTERFACE_ADDRESS_%s: Cannot find IF %u in VRF %d", +			  (type == ZEBRA_INTERFACE_ADDRESS_ADD) ? "ADD" : "DEL", +			  ifindex, vrf_id); +		return NULL; +	} + +	/* Fetch flag. */ +	ifc_flags = stream_getc(s); + +	/* Fetch interface address. */ +	d.family = p.family = stream_getc(s); +	plen = prefix_blen(&d); + +	zclient_stream_get_prefix(s, &p); + +	/* Fetch destination address. */ +	stream_get(&d.u.prefix, s, plen); + +	/* N.B. NULL destination pointers are encoded as all zeroes */ +	dp = memconstant(&d.u.prefix, 0, plen) ? NULL : &d; + +	if (type == ZEBRA_INTERFACE_ADDRESS_ADD) { +		ifc = connected_lookup_prefix_exact(ifp, &p); +		if (!ifc) { +			/* N.B. NULL destination pointers are encoded as all +			 * zeroes */ +			ifc = connected_add_by_prefix(ifp, &p, dp); +		} +		if (ifc) { +			ifc->flags = ifc_flags; +			if (ifc->destination) +				ifc->destination->prefixlen = +					ifc->address->prefixlen; +			else if (CHECK_FLAG(ifc->flags, ZEBRA_IFA_PEER)) { +				/* carp interfaces on OpenBSD with 0.0.0.0/0 as +				 * "peer" */ +				char buf[PREFIX_STRLEN]; +				zlog_warn( +					"warning: interface %s address %s " +					"with peer flag set, but no peer address!", +					ifp->name, prefix2str(ifc->address, buf, +							      sizeof buf)); +				UNSET_FLAG(ifc->flags, ZEBRA_IFA_PEER); +			} +		} +	} else { +		assert(type == ZEBRA_INTERFACE_ADDRESS_DELETE); +		ifc = connected_delete_by_prefix(ifp, &p); +	} + +	return ifc;  }  /* @@ -1389,122 +1360,118 @@ zebra_interface_address_read (int type, struct stream *s, vrf_id_t vrf_id)   * +-+-+-+-+-+-+-+-+   */  struct nbr_connected * -zebra_interface_nbr_address_read (int type, struct stream *s, vrf_id_t vrf_id) +zebra_interface_nbr_address_read(int type, struct stream *s, vrf_id_t vrf_id)  { -  unsigned int ifindex; -  struct interface *ifp; -  struct prefix p; -  struct nbr_connected *ifc; - -  /* Get interface index. */ -  ifindex = stream_getl (s); - -  /* Lookup index. */ -  ifp = if_lookup_by_index (ifindex, vrf_id); -  if (ifp == NULL) -    { -      zlog_warn ("INTERFACE_NBR_%s: Cannot find IF %u in VRF %d", -                 (type == ZEBRA_INTERFACE_NBR_ADDRESS_ADD) ? "ADD" : "DELETE", -                 ifindex, vrf_id); -      return NULL; -    } - -  p.family = stream_getc (s); -  stream_get (&p.u.prefix, s, prefix_blen (&p)); -  p.prefixlen = stream_getc (s); - -  if (type == ZEBRA_INTERFACE_NBR_ADDRESS_ADD) -    { -      /* Currently only supporting P2P links, so any new RA source address is -         considered as the replacement of the previously learnt Link-Local address. */ -      if (!(ifc = listnode_head(ifp->nbr_connected))) -        { -          ifc = nbr_connected_new (); -          ifc->address = prefix_new (); -          ifc->ifp = ifp; -          listnode_add (ifp->nbr_connected, ifc); -        } - -      prefix_copy(ifc->address, &p); -    } -  else -    { -      assert (type == ZEBRA_INTERFACE_NBR_ADDRESS_DELETE); - -      ifc = nbr_connected_check(ifp, &p); -      if (ifc) -          listnode_delete (ifp->nbr_connected, ifc); -    } - -  return ifc; +	unsigned int ifindex; +	struct interface *ifp; +	struct prefix p; +	struct nbr_connected *ifc; + +	/* Get interface index. */ +	ifindex = stream_getl(s); + +	/* Lookup index. */ +	ifp = if_lookup_by_index(ifindex, vrf_id); +	if (ifp == NULL) { +		zlog_warn("INTERFACE_NBR_%s: Cannot find IF %u in VRF %d", +			  (type == ZEBRA_INTERFACE_NBR_ADDRESS_ADD) ? "ADD" +								    : "DELETE", +			  ifindex, vrf_id); +		return NULL; +	} + +	p.family = stream_getc(s); +	stream_get(&p.u.prefix, s, prefix_blen(&p)); +	p.prefixlen = stream_getc(s); + +	if (type == ZEBRA_INTERFACE_NBR_ADDRESS_ADD) { +		/* Currently only supporting P2P links, so any new RA source +		   address is +		   considered as the replacement of the previously learnt +		   Link-Local address. */ +		if (!(ifc = listnode_head(ifp->nbr_connected))) { +			ifc = nbr_connected_new(); +			ifc->address = prefix_new(); +			ifc->ifp = ifp; +			listnode_add(ifp->nbr_connected, ifc); +		} + +		prefix_copy(ifc->address, &p); +	} else { +		assert(type == ZEBRA_INTERFACE_NBR_ADDRESS_DELETE); + +		ifc = nbr_connected_check(ifp, &p); +		if (ifc) +			listnode_delete(ifp->nbr_connected, ifc); +	} + +	return ifc;  } -struct interface * -zebra_interface_vrf_update_read (struct stream *s, vrf_id_t vrf_id, -                                 vrf_id_t *new_vrf_id) +struct interface *zebra_interface_vrf_update_read(struct stream *s, +						  vrf_id_t vrf_id, +						  vrf_id_t *new_vrf_id)  { -  unsigned int ifindex; -  struct interface *ifp; -  vrf_id_t new_id = VRF_DEFAULT; - -  /* Get interface index. */ -  ifindex = stream_getl (s); - -  /* Lookup interface. */ -  ifp = if_lookup_by_index (ifindex, vrf_id); -  if (ifp == NULL) -    { -      zlog_warn ("INTERFACE_VRF_UPDATE: Cannot find IF %u in VRF %d", -                 ifindex, vrf_id); -      return NULL; -    } - -  /* Fetch new VRF Id. */ -  new_id = stream_getw (s); - -  *new_vrf_id = new_id; -  return ifp; +	unsigned int ifindex; +	struct interface *ifp; +	vrf_id_t new_id = VRF_DEFAULT; + +	/* Get interface index. */ +	ifindex = stream_getl(s); + +	/* Lookup interface. */ +	ifp = if_lookup_by_index(ifindex, vrf_id); +	if (ifp == NULL) { +		zlog_warn("INTERFACE_VRF_UPDATE: Cannot find IF %u in VRF %d", +			  ifindex, vrf_id); +		return NULL; +	} + +	/* Fetch new VRF Id. */ +	new_id = stream_getw(s); + +	*new_vrf_id = new_id; +	return ifp;  }  /* filter unwanted messages until the expected one arrives */ -static int -zclient_read_sync_response (struct zclient *zclient, u_int16_t expected_cmd) +static int zclient_read_sync_response(struct zclient *zclient, +				      u_int16_t expected_cmd)  { -  struct stream *s; -  u_int16_t size; -  u_char marker; -  u_char version; -  vrf_id_t vrf_id; -  u_int16_t cmd; -  fd_set readfds; -  int ret; - -  ret = 0; -  cmd = expected_cmd + 1; -  while (ret == 0 && cmd != expected_cmd) -    { -      s = zclient->ibuf; -      stream_reset (s); - -      /* wait until response arrives */ -      FD_ZERO (&readfds); -      FD_SET (zclient->sock, &readfds); -      select (zclient->sock+1, &readfds, NULL, NULL, NULL); -      if (!FD_ISSET(zclient->sock, &readfds)) -        continue; -      /* read response */ -      ret = zclient_read_header (s, zclient->sock, &size, &marker, &version, -                                 &vrf_id, &cmd); -      if (zclient_debug) -        zlog_debug ("%s: Response (%d bytes) received", __func__, size); -    } -  if (ret != 0) -    { -      zlog_err ("%s: Invalid Sync Message Reply", __func__); -      return -1; -    } - -  return 0; +	struct stream *s; +	u_int16_t size; +	u_char marker; +	u_char version; +	vrf_id_t vrf_id; +	u_int16_t cmd; +	fd_set readfds; +	int ret; + +	ret = 0; +	cmd = expected_cmd + 1; +	while (ret == 0 && cmd != expected_cmd) { +		s = zclient->ibuf; +		stream_reset(s); + +		/* wait until response arrives */ +		FD_ZERO(&readfds); +		FD_SET(zclient->sock, &readfds); +		select(zclient->sock + 1, &readfds, NULL, NULL, NULL); +		if (!FD_ISSET(zclient->sock, &readfds)) +			continue; +		/* read response */ +		ret = zclient_read_header(s, zclient->sock, &size, &marker, +					  &version, &vrf_id, &cmd); +		if (zclient_debug) +			zlog_debug("%s: Response (%d bytes) received", __func__, +				   size); +	} +	if (ret != 0) { +		zlog_err("%s: Invalid Sync Message Reply", __func__); +		return -1; +	} + +	return 0;  }  /**   * Connect to label manager in a syncronous way @@ -1515,62 +1482,62 @@ zclient_read_sync_response (struct zclient *zclient, u_int16_t expected_cmd)   * @param zclient Zclient used to connect to label manager (zebra)   * @result Result of response   */ -int -lm_label_manager_connect (struct zclient *zclient) +int lm_label_manager_connect(struct zclient *zclient)  { -  int ret; -  struct stream *s; -  u_char result; - -  if (zclient_debug) -    zlog_debug ("Connecting to Label Manager"); - -  if (zclient->sock < 0) -    return -1; - -  /* send request */ -  s = zclient->obuf; -  stream_reset (s); -  zclient_create_header (s, ZEBRA_LABEL_MANAGER_CONNECT, VRF_DEFAULT); - -  /* proto */ -  stream_putc (s, zclient->redist_default); -  /* instance */ -  stream_putw (s, zclient->instance); - -  /* Put length at the first point of the stream. */ -  stream_putw_at(s, 0, stream_get_endp(s)); - -  ret = writen (zclient->sock, s->data, stream_get_endp (s)); -  if (ret < 0) -    { -      zlog_err ("%s: can't write to zclient->sock", __func__); -      close (zclient->sock); -      zclient->sock = -1; -      return -1; -    } -  if (ret == 0) -    { -      zlog_err ("%s: zclient->sock connection closed", __func__); -      close (zclient->sock); -      zclient->sock = -1; -      return -1; -    } -  if (zclient_debug) -    zlog_debug ("%s: Label manager connect request (%d bytes) sent", __func__, ret); - -  /* read response */ -  if (zclient_read_sync_response (zclient, ZEBRA_LABEL_MANAGER_CONNECT) != 0) -    return -1; - -  /* result */ -  s = zclient->ibuf; -  result = stream_getc(s); -  if (zclient_debug) -    zlog_debug ("%s: Label Manager connect response received, result %u", -                __func__, result); - -  return (int)result; +	int ret; +	struct stream *s; +	u_char result; + +	if (zclient_debug) +		zlog_debug("Connecting to Label Manager"); + +	if (zclient->sock < 0) +		return -1; + +	/* send request */ +	s = zclient->obuf; +	stream_reset(s); +	zclient_create_header(s, ZEBRA_LABEL_MANAGER_CONNECT, VRF_DEFAULT); + +	/* proto */ +	stream_putc(s, zclient->redist_default); +	/* instance */ +	stream_putw(s, zclient->instance); + +	/* Put length at the first point of the stream. */ +	stream_putw_at(s, 0, stream_get_endp(s)); + +	ret = writen(zclient->sock, s->data, stream_get_endp(s)); +	if (ret < 0) { +		zlog_err("%s: can't write to zclient->sock", __func__); +		close(zclient->sock); +		zclient->sock = -1; +		return -1; +	} +	if (ret == 0) { +		zlog_err("%s: zclient->sock connection closed", __func__); +		close(zclient->sock); +		zclient->sock = -1; +		return -1; +	} +	if (zclient_debug) +		zlog_debug("%s: Label manager connect request (%d bytes) sent", +			   __func__, ret); + +	/* read response */ +	if (zclient_read_sync_response(zclient, ZEBRA_LABEL_MANAGER_CONNECT) +	    != 0) +		return -1; + +	/* result */ +	s = zclient->ibuf; +	result = stream_getc(s); +	if (zclient_debug) +		zlog_debug( +			"%s: Label Manager connect response received, result %u", +			__func__, result); + +	return (int)result;  }  /** @@ -1586,81 +1553,77 @@ lm_label_manager_connect (struct zclient *zclient)   * @param end To write last assigned chunk label to   * @result 0 on success, -1 otherwise   */ -int -lm_get_label_chunk (struct zclient *zclient, u_char keep, uint32_t chunk_size, -                    uint32_t *start, uint32_t *end) +int lm_get_label_chunk(struct zclient *zclient, u_char keep, +		       uint32_t chunk_size, uint32_t *start, uint32_t *end)  { -  int ret; -  struct stream *s; -  u_char response_keep; - -  if (zclient_debug) -    zlog_debug ("Getting Label Chunk"); - -  if (zclient->sock < 0) -    return -1; - -  /* send request */ -  s = zclient->obuf; -  stream_reset (s); -  zclient_create_header (s, ZEBRA_GET_LABEL_CHUNK, VRF_DEFAULT); -  /* keep */ -  stream_putc (s, keep); -  /* chunk size */ -  stream_putl (s, chunk_size); -  /* Put length at the first point of the stream. */ -  stream_putw_at(s, 0, stream_get_endp(s)); - -  ret = writen (zclient->sock, s->data, stream_get_endp (s)); -  if (ret < 0) -    { -      zlog_err ("%s: can't write to zclient->sock", __func__); -      close (zclient->sock); -      zclient->sock = -1; -      return -1; -    } -  if (ret == 0) -    { -      zlog_err ("%s: zclient->sock connection closed", __func__); -      close (zclient->sock); -      zclient->sock = -1; -      return -1; -    } -  if (zclient_debug) -    zlog_debug ("%s: Label chunk request (%d bytes) sent", __func__, ret); - -  /* read response */ -  if (zclient_read_sync_response (zclient, ZEBRA_GET_LABEL_CHUNK) != 0) -    return -1; - -  s = zclient->ibuf; -  /* keep */ -  response_keep = stream_getc(s); -  /* start and end labels */ -  *start = stream_getl(s); -  *end = stream_getl(s); - -  /* not owning this response */ -  if (keep != response_keep) -    { -      zlog_err ("%s: Invalid Label chunk: %u - %u, keeps mismatch %u != %u", -                __func__, *start, *end, keep, response_keep); -    } -  /* sanity */ -  if (*start > *end -      || *start < MPLS_MIN_UNRESERVED_LABEL -      || *end > MPLS_MAX_UNRESERVED_LABEL) -    { -      zlog_err ("%s: Invalid Label chunk: %u - %u", __func__, -                *start, *end); -      return -1; -    } - -  if (zclient_debug) -    zlog_debug ("Label Chunk assign: %u - %u (%u) ", -                *start, *end, response_keep); - -  return 0; +	int ret; +	struct stream *s; +	u_char response_keep; + +	if (zclient_debug) +		zlog_debug("Getting Label Chunk"); + +	if (zclient->sock < 0) +		return -1; + +	/* send request */ +	s = zclient->obuf; +	stream_reset(s); +	zclient_create_header(s, ZEBRA_GET_LABEL_CHUNK, VRF_DEFAULT); +	/* keep */ +	stream_putc(s, keep); +	/* chunk size */ +	stream_putl(s, chunk_size); +	/* Put length at the first point of the stream. */ +	stream_putw_at(s, 0, stream_get_endp(s)); + +	ret = writen(zclient->sock, s->data, stream_get_endp(s)); +	if (ret < 0) { +		zlog_err("%s: can't write to zclient->sock", __func__); +		close(zclient->sock); +		zclient->sock = -1; +		return -1; +	} +	if (ret == 0) { +		zlog_err("%s: zclient->sock connection closed", __func__); +		close(zclient->sock); +		zclient->sock = -1; +		return -1; +	} +	if (zclient_debug) +		zlog_debug("%s: Label chunk request (%d bytes) sent", __func__, +			   ret); + +	/* read response */ +	if (zclient_read_sync_response(zclient, ZEBRA_GET_LABEL_CHUNK) != 0) +		return -1; + +	s = zclient->ibuf; +	/* keep */ +	response_keep = stream_getc(s); +	/* start and end labels */ +	*start = stream_getl(s); +	*end = stream_getl(s); + +	/* not owning this response */ +	if (keep != response_keep) { +		zlog_err( +			"%s: Invalid Label chunk: %u - %u, keeps mismatch %u != %u", +			__func__, *start, *end, keep, response_keep); +	} +	/* sanity */ +	if (*start > *end || *start < MPLS_MIN_UNRESERVED_LABEL +	    || *end > MPLS_MAX_UNRESERVED_LABEL) { +		zlog_err("%s: Invalid Label chunk: %u - %u", __func__, *start, +			 *end); +		return -1; +	} + +	if (zclient_debug) +		zlog_debug("Label Chunk assign: %u - %u (%u) ", *start, *end, +			   response_keep); + +	return 0;  }  /** @@ -1671,433 +1634,438 @@ lm_get_label_chunk (struct zclient *zclient, u_char keep, uint32_t chunk_size,   * @param end Last label of chunk   * @result 0 on success, -1 otherwise   */ -int -lm_release_label_chunk (struct zclient *zclient, uint32_t start, uint32_t end) +int lm_release_label_chunk(struct zclient *zclient, uint32_t start, +			   uint32_t end)  { -  int ret; -  struct stream *s; - -  if (zclient_debug) -    zlog_debug ("Releasing Label Chunk"); - -  if (zclient->sock < 0) -    return -1; - -  /* send request */ -  s = zclient->obuf; -  stream_reset (s); -  zclient_create_header (s, ZEBRA_RELEASE_LABEL_CHUNK, VRF_DEFAULT); - -  /* start */ -  stream_putl (s, start); -  /* end */ -  stream_putl (s, end); - -  /* Put length at the first point of the stream. */ -  stream_putw_at(s, 0, stream_get_endp(s)); - -  ret = writen (zclient->sock, s->data, stream_get_endp (s)); -  if (ret < 0) -    { -      zlog_err ("%s: can't write to zclient->sock", __func__); -      close (zclient->sock); -      zclient->sock = -1; -      return -1; -    } -  if (ret == 0) -    { -      zlog_err ("%s: zclient->sock connection closed", __func__); -      close (zclient->sock); -      zclient->sock = -1; -      return -1; -    } - -  return 0; +	int ret; +	struct stream *s; + +	if (zclient_debug) +		zlog_debug("Releasing Label Chunk"); + +	if (zclient->sock < 0) +		return -1; + +	/* send request */ +	s = zclient->obuf; +	stream_reset(s); +	zclient_create_header(s, ZEBRA_RELEASE_LABEL_CHUNK, VRF_DEFAULT); + +	/* start */ +	stream_putl(s, start); +	/* end */ +	stream_putl(s, end); + +	/* Put length at the first point of the stream. */ +	stream_putw_at(s, 0, stream_get_endp(s)); + +	ret = writen(zclient->sock, s->data, stream_get_endp(s)); +	if (ret < 0) { +		zlog_err("%s: can't write to zclient->sock", __func__); +		close(zclient->sock); +		zclient->sock = -1; +		return -1; +	} +	if (ret == 0) { +		zlog_err("%s: zclient->sock connection closed", __func__); +		close(zclient->sock); +		zclient->sock = -1; +		return -1; +	} + +	return 0;  } -int -zebra_send_pw(struct zclient *zclient, int command, struct zapi_pw *pw) +int zebra_send_pw(struct zclient *zclient, int command, struct zapi_pw *pw)  { -  struct stream *s; - -  /* Reset stream. */ -  s = zclient->obuf; -  stream_reset(s); - -  zclient_create_header(s, command, VRF_DEFAULT); -  stream_write(s, pw->ifname, IF_NAMESIZE); -  stream_putl(s, pw->ifindex); - -  /* Put type */ -  stream_putl(s, pw->type); - -  /* Put nexthop */ -  stream_putl(s, pw->af); -  switch (pw->af) -    { -    case AF_INET: -      stream_put_in_addr(s, &pw->nexthop.ipv4); -      break; -    case AF_INET6: -      stream_write(s, (u_char *)&pw->nexthop.ipv6, 16); -      break; -    default: -      zlog_err ("%s: unknown af", __func__); -      return -1; -    } - -  /* Put labels */ -  stream_putl(s, pw->local_label); -  stream_putl(s, pw->remote_label); - -  /* Put flags */ -  stream_putc(s, pw->flags); - -  /* Protocol specific fields */ -  stream_write(s, &pw->data, sizeof(union pw_protocol_fields)); - -  /* Put length at the first point of the stream. */ -  stream_putw_at(s, 0, stream_get_endp(s)); - -  return zclient_send_message(zclient); +	struct stream *s; + +	/* Reset stream. */ +	s = zclient->obuf; +	stream_reset(s); + +	zclient_create_header(s, command, VRF_DEFAULT); +	stream_write(s, pw->ifname, IF_NAMESIZE); +	stream_putl(s, pw->ifindex); + +	/* Put type */ +	stream_putl(s, pw->type); + +	/* Put nexthop */ +	stream_putl(s, pw->af); +	switch (pw->af) { +	case AF_INET: +		stream_put_in_addr(s, &pw->nexthop.ipv4); +		break; +	case AF_INET6: +		stream_write(s, (u_char *)&pw->nexthop.ipv6, 16); +		break; +	default: +		zlog_err("%s: unknown af", __func__); +		return -1; +	} + +	/* Put labels */ +	stream_putl(s, pw->local_label); +	stream_putl(s, pw->remote_label); + +	/* Put flags */ +	stream_putc(s, pw->flags); + +	/* Protocol specific fields */ +	stream_write(s, &pw->data, sizeof(union pw_protocol_fields)); + +	/* Put length at the first point of the stream. */ +	stream_putw_at(s, 0, stream_get_endp(s)); + +	return zclient_send_message(zclient);  }  /*   * Receive PW status update from Zebra and send it to LDE process.   */ -void -zebra_read_pw_status_update(int command, struct zclient *zclient, -                            zebra_size_t length, vrf_id_t vrf_id, -                            struct zapi_pw_status *pw) +void zebra_read_pw_status_update(int command, struct zclient *zclient, +				 zebra_size_t length, vrf_id_t vrf_id, +				 struct zapi_pw_status *pw)  { -  struct stream	*s; +	struct stream *s; -  memset(pw, 0, sizeof(struct zapi_pw_status)); -  s = zclient->ibuf; +	memset(pw, 0, sizeof(struct zapi_pw_status)); +	s = zclient->ibuf; -  /* Get data. */ -  stream_get(pw->ifname, s, IF_NAMESIZE); -  pw->ifindex = stream_getl(s); -  pw->status = stream_getl(s); +	/* Get data. */ +	stream_get(pw->ifname, s, IF_NAMESIZE); +	pw->ifindex = stream_getl(s); +	pw->status = stream_getl(s);  }  /* Zebra client message read function. */ -static int -zclient_read (struct thread *thread) +static int zclient_read(struct thread *thread)  { -  size_t already; -  uint16_t length, command; -  uint8_t marker, version; -  vrf_id_t vrf_id; -  struct zclient *zclient; - -  /* Get socket to zebra. */ -  zclient = THREAD_ARG (thread); -  zclient->t_read = NULL; - -  /* Read zebra header (if we don't have it already). */ -  if ((already = stream_get_endp(zclient->ibuf)) < ZEBRA_HEADER_SIZE) -    { -      ssize_t nbyte; -      if (((nbyte = stream_read_try(zclient->ibuf, zclient->sock, -				     ZEBRA_HEADER_SIZE-already)) == 0) || -	  (nbyte == -1)) -	{ -	  if (zclient_debug) -	   zlog_debug ("zclient connection closed socket [%d].", zclient->sock); -	  return zclient_failed(zclient); +	size_t already; +	uint16_t length, command; +	uint8_t marker, version; +	vrf_id_t vrf_id; +	struct zclient *zclient; + +	/* Get socket to zebra. */ +	zclient = THREAD_ARG(thread); +	zclient->t_read = NULL; + +	/* Read zebra header (if we don't have it already). */ +	if ((already = stream_get_endp(zclient->ibuf)) < ZEBRA_HEADER_SIZE) { +		ssize_t nbyte; +		if (((nbyte = stream_read_try(zclient->ibuf, zclient->sock, +					      ZEBRA_HEADER_SIZE - already)) +		     == 0) +		    || (nbyte == -1)) { +			if (zclient_debug) +				zlog_debug( +					"zclient connection closed socket [%d].", +					zclient->sock); +			return zclient_failed(zclient); +		} +		if (nbyte != (ssize_t)(ZEBRA_HEADER_SIZE - already)) { +			/* Try again later. */ +			zclient_event(ZCLIENT_READ, zclient); +			return 0; +		} +		already = ZEBRA_HEADER_SIZE;  	} -      if (nbyte != (ssize_t)(ZEBRA_HEADER_SIZE-already)) -	{ -	  /* Try again later. */ -	  zclient_event (ZCLIENT_READ, zclient); -	  return 0; + +	/* Reset to read from the beginning of the incoming packet. */ +	stream_set_getp(zclient->ibuf, 0); + +	/* Fetch header values. */ +	length = stream_getw(zclient->ibuf); +	marker = stream_getc(zclient->ibuf); +	version = stream_getc(zclient->ibuf); +	vrf_id = stream_getw(zclient->ibuf); +	command = stream_getw(zclient->ibuf); + +	if (marker != ZEBRA_HEADER_MARKER || version != ZSERV_VERSION) { +		zlog_err( +			"%s: socket %d version mismatch, marker %d, version %d", +			__func__, zclient->sock, marker, version); +		return zclient_failed(zclient);  	} -      already = ZEBRA_HEADER_SIZE; -    } - -  /* Reset to read from the beginning of the incoming packet. */ -  stream_set_getp(zclient->ibuf, 0); - -  /* Fetch header values. */ -  length = stream_getw (zclient->ibuf); -  marker = stream_getc (zclient->ibuf); -  version = stream_getc (zclient->ibuf); -  vrf_id = stream_getw (zclient->ibuf); -  command = stream_getw (zclient->ibuf); -   -  if (marker != ZEBRA_HEADER_MARKER || version != ZSERV_VERSION) -    { -      zlog_err("%s: socket %d version mismatch, marker %d, version %d", -               __func__, zclient->sock, marker, version); -      return zclient_failed(zclient); -    } -   -  if (length < ZEBRA_HEADER_SIZE)  -    { -      zlog_err("%s: socket %d message length %u is less than %d ", -	       __func__, zclient->sock, length, ZEBRA_HEADER_SIZE); -      return zclient_failed(zclient); -    } - -  /* Length check. */ -  if (length > STREAM_SIZE(zclient->ibuf)) -    { -      struct stream *ns; -      zlog_warn("%s: message size %u exceeds buffer size %lu, expanding...", -	        __func__, length, (u_long)STREAM_SIZE(zclient->ibuf)); -      ns = stream_new(length); -      stream_copy(ns, zclient->ibuf); -      stream_free (zclient->ibuf); -      zclient->ibuf = ns; -    } - -  /* Read rest of zebra packet. */ -  if (already < length) -    { -      ssize_t nbyte; -      if (((nbyte = stream_read_try(zclient->ibuf, zclient->sock, -				     length-already)) == 0) || -	  (nbyte == -1)) -	{ -	  if (zclient_debug) -	    zlog_debug("zclient connection closed socket [%d].", zclient->sock); -	  return zclient_failed(zclient); + +	if (length < ZEBRA_HEADER_SIZE) { +		zlog_err("%s: socket %d message length %u is less than %d ", +			 __func__, zclient->sock, length, ZEBRA_HEADER_SIZE); +		return zclient_failed(zclient);  	} -      if (nbyte != (ssize_t)(length-already)) -	{ -	  /* Try again later. */ -	  zclient_event (ZCLIENT_READ, zclient); -	  return 0; + +	/* Length check. */ +	if (length > STREAM_SIZE(zclient->ibuf)) { +		struct stream *ns; +		zlog_warn( +			"%s: message size %u exceeds buffer size %lu, expanding...", +			__func__, length, (u_long)STREAM_SIZE(zclient->ibuf)); +		ns = stream_new(length); +		stream_copy(ns, zclient->ibuf); +		stream_free(zclient->ibuf); +		zclient->ibuf = ns; +	} + +	/* Read rest of zebra packet. */ +	if (already < length) { +		ssize_t nbyte; +		if (((nbyte = stream_read_try(zclient->ibuf, zclient->sock, +					      length - already)) +		     == 0) +		    || (nbyte == -1)) { +			if (zclient_debug) +				zlog_debug( +					"zclient connection closed socket [%d].", +					zclient->sock); +			return zclient_failed(zclient); +		} +		if (nbyte != (ssize_t)(length - already)) { +			/* Try again later. */ +			zclient_event(ZCLIENT_READ, zclient); +			return 0; +		}  	} -    } - -  length -= ZEBRA_HEADER_SIZE; - -  if (zclient_debug) -    zlog_debug("zclient 0x%p command 0x%x VRF %u\n", (void *)zclient, command, vrf_id); - -  switch (command) -    { -    case ZEBRA_ROUTER_ID_UPDATE: -      if (zclient->router_id_update) -	(*zclient->router_id_update) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_VRF_ADD: -      zclient_vrf_add (zclient, vrf_id); -      break; -    case ZEBRA_VRF_DELETE: -      zclient_vrf_delete (zclient, vrf_id); -      break; -    case ZEBRA_INTERFACE_ADD: -      if (zclient->interface_add) -	(*zclient->interface_add) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_DELETE: -      if (zclient->interface_delete) -	(*zclient->interface_delete) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_ADDRESS_ADD: -      if (zclient->interface_address_add) -	(*zclient->interface_address_add) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_ADDRESS_DELETE: -      if (zclient->interface_address_delete) -	(*zclient->interface_address_delete) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_BFD_DEST_UPDATE: -      if (zclient->interface_bfd_dest_update) -	(*zclient->interface_bfd_dest_update) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_NBR_ADDRESS_ADD: -      if (zclient->interface_nbr_address_add) -	(*zclient->interface_nbr_address_add) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_NBR_ADDRESS_DELETE: -      if (zclient->interface_nbr_address_delete) -	(*zclient->interface_nbr_address_delete) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_UP: -      if (zclient->interface_up) -	(*zclient->interface_up) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_DOWN: -      if (zclient->interface_down) -	(*zclient->interface_down) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_VRF_UPDATE: -      if (zclient->interface_vrf_update) -	(*zclient->interface_vrf_update) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_NEXTHOP_UPDATE: -      if (zclient_debug) -	zlog_debug("zclient rcvd nexthop update\n"); -      if (zclient->nexthop_update) -	(*zclient->nexthop_update) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_IMPORT_CHECK_UPDATE: -      if (zclient_debug) -	zlog_debug("zclient rcvd import check update\n"); -      if (zclient->import_check_update) -	(*zclient->import_check_update) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_BFD_DEST_REPLAY: -      if (zclient->bfd_dest_replay) -	(*zclient->bfd_dest_replay) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_REDISTRIBUTE_IPV4_ADD: -      if (zclient->redistribute_route_ipv4_add) -	(*zclient->redistribute_route_ipv4_add) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_REDISTRIBUTE_IPV4_DEL: -      if (zclient->redistribute_route_ipv4_del) -	(*zclient->redistribute_route_ipv4_del) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_REDISTRIBUTE_IPV6_ADD: -      if (zclient->redistribute_route_ipv6_add) -	(*zclient->redistribute_route_ipv6_add) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_REDISTRIBUTE_IPV6_DEL: -      if (zclient->redistribute_route_ipv6_del) -	(*zclient->redistribute_route_ipv6_del) (command, zclient, length, vrf_id); -      break; -    case ZEBRA_INTERFACE_LINK_PARAMS: -      if (zclient->interface_link_params) -        (*zclient->interface_link_params) (command, zclient, length); -      break; -    case ZEBRA_PW_STATUS_UPDATE: -      if (zclient->pw_status_update) -        (*zclient->pw_status_update) (command, zclient, length, vrf_id); -      break; -    default: -      break; -    } - -  if (zclient->sock < 0) -    /* Connection was closed during packet processing. */ -    return -1; - -  /* Register read thread. */ -  stream_reset(zclient->ibuf); -  zclient_event (ZCLIENT_READ, zclient); - -  return 0; + +	length -= ZEBRA_HEADER_SIZE; + +	if (zclient_debug) +		zlog_debug("zclient 0x%p command 0x%x VRF %u\n", +			   (void *)zclient, command, vrf_id); + +	switch (command) { +	case ZEBRA_ROUTER_ID_UPDATE: +		if (zclient->router_id_update) +			(*zclient->router_id_update)(command, zclient, length, +						     vrf_id); +		break; +	case ZEBRA_VRF_ADD: +		zclient_vrf_add(zclient, vrf_id); +		break; +	case ZEBRA_VRF_DELETE: +		zclient_vrf_delete(zclient, vrf_id); +		break; +	case ZEBRA_INTERFACE_ADD: +		if (zclient->interface_add) +			(*zclient->interface_add)(command, zclient, length, +						  vrf_id); +		break; +	case ZEBRA_INTERFACE_DELETE: +		if (zclient->interface_delete) +			(*zclient->interface_delete)(command, zclient, length, +						     vrf_id); +		break; +	case ZEBRA_INTERFACE_ADDRESS_ADD: +		if (zclient->interface_address_add) +			(*zclient->interface_address_add)(command, zclient, +							  length, vrf_id); +		break; +	case ZEBRA_INTERFACE_ADDRESS_DELETE: +		if (zclient->interface_address_delete) +			(*zclient->interface_address_delete)(command, zclient, +							     length, vrf_id); +		break; +	case ZEBRA_INTERFACE_BFD_DEST_UPDATE: +		if (zclient->interface_bfd_dest_update) +			(*zclient->interface_bfd_dest_update)(command, zclient, +							      length, vrf_id); +		break; +	case ZEBRA_INTERFACE_NBR_ADDRESS_ADD: +		if (zclient->interface_nbr_address_add) +			(*zclient->interface_nbr_address_add)(command, zclient, +							      length, vrf_id); +		break; +	case ZEBRA_INTERFACE_NBR_ADDRESS_DELETE: +		if (zclient->interface_nbr_address_delete) +			(*zclient->interface_nbr_address_delete)( +				command, zclient, length, vrf_id); +		break; +	case ZEBRA_INTERFACE_UP: +		if (zclient->interface_up) +			(*zclient->interface_up)(command, zclient, length, +						 vrf_id); +		break; +	case ZEBRA_INTERFACE_DOWN: +		if (zclient->interface_down) +			(*zclient->interface_down)(command, zclient, length, +						   vrf_id); +		break; +	case ZEBRA_INTERFACE_VRF_UPDATE: +		if (zclient->interface_vrf_update) +			(*zclient->interface_vrf_update)(command, zclient, +							 length, vrf_id); +		break; +	case ZEBRA_NEXTHOP_UPDATE: +		if (zclient_debug) +			zlog_debug("zclient rcvd nexthop update\n"); +		if (zclient->nexthop_update) +			(*zclient->nexthop_update)(command, zclient, length, +						   vrf_id); +		break; +	case ZEBRA_IMPORT_CHECK_UPDATE: +		if (zclient_debug) +			zlog_debug("zclient rcvd import check update\n"); +		if (zclient->import_check_update) +			(*zclient->import_check_update)(command, zclient, +							length, vrf_id); +		break; +	case ZEBRA_BFD_DEST_REPLAY: +		if (zclient->bfd_dest_replay) +			(*zclient->bfd_dest_replay)(command, zclient, length, +						    vrf_id); +		break; +	case ZEBRA_REDISTRIBUTE_IPV4_ADD: +		if (zclient->redistribute_route_ipv4_add) +			(*zclient->redistribute_route_ipv4_add)( +				command, zclient, length, vrf_id); +		break; +	case ZEBRA_REDISTRIBUTE_IPV4_DEL: +		if (zclient->redistribute_route_ipv4_del) +			(*zclient->redistribute_route_ipv4_del)( +				command, zclient, length, vrf_id); +		break; +	case ZEBRA_REDISTRIBUTE_IPV6_ADD: +		if (zclient->redistribute_route_ipv6_add) +			(*zclient->redistribute_route_ipv6_add)( +				command, zclient, length, vrf_id); +		break; +	case ZEBRA_REDISTRIBUTE_IPV6_DEL: +		if (zclient->redistribute_route_ipv6_del) +			(*zclient->redistribute_route_ipv6_del)( +				command, zclient, length, vrf_id); +		break; +	case ZEBRA_INTERFACE_LINK_PARAMS: +		if (zclient->interface_link_params) +			(*zclient->interface_link_params)(command, zclient, +							  length); +		break; +	case ZEBRA_PW_STATUS_UPDATE: +		if (zclient->pw_status_update) +			(*zclient->pw_status_update)(command, zclient, length, +						     vrf_id); +		break; +	default: +		break; +	} + +	if (zclient->sock < 0) +		/* Connection was closed during packet processing. */ +		return -1; + +	/* Register read thread. */ +	stream_reset(zclient->ibuf); +	zclient_event(ZCLIENT_READ, zclient); + +	return 0;  } -void -zclient_redistribute (int command, struct zclient *zclient, afi_t afi, int type, -                      u_short instance, vrf_id_t vrf_id) +void zclient_redistribute(int command, struct zclient *zclient, afi_t afi, +			  int type, u_short instance, vrf_id_t vrf_id)  { -  if (instance) { -      if (command == ZEBRA_REDISTRIBUTE_ADD)  -        { -          if (redist_check_instance(&zclient->mi_redist[afi][type], instance)) -            return; -          redist_add_instance(&zclient->mi_redist[afi][type], instance); -        } -      else -        { -          if (!redist_check_instance(&zclient->mi_redist[afi][type], instance)) -            return; -          redist_del_instance(&zclient->mi_redist[afi][type], instance); -        } - -  } else { -      if (command == ZEBRA_REDISTRIBUTE_ADD) -        { -          if (vrf_bitmap_check (zclient->redist[afi][type], vrf_id)) -            return; -          vrf_bitmap_set (zclient->redist[afi][type], vrf_id); -        } -      else -        { -          if (!vrf_bitmap_check (zclient->redist[afi][type], vrf_id)) -            return; -          vrf_bitmap_unset (zclient->redist[afi][type], vrf_id); -        } -  } - -  if (zclient->sock > 0) -    zebra_redistribute_send (command, zclient, afi, type, instance, vrf_id); +	if (instance) { +		if (command == ZEBRA_REDISTRIBUTE_ADD) { +			if (redist_check_instance( +				    &zclient->mi_redist[afi][type], instance)) +				return; +			redist_add_instance(&zclient->mi_redist[afi][type], +					    instance); +		} else { +			if (!redist_check_instance( +				    &zclient->mi_redist[afi][type], instance)) +				return; +			redist_del_instance(&zclient->mi_redist[afi][type], +					    instance); +		} + +	} else { +		if (command == ZEBRA_REDISTRIBUTE_ADD) { +			if (vrf_bitmap_check(zclient->redist[afi][type], +					     vrf_id)) +				return; +			vrf_bitmap_set(zclient->redist[afi][type], vrf_id); +		} else { +			if (!vrf_bitmap_check(zclient->redist[afi][type], +					      vrf_id)) +				return; +			vrf_bitmap_unset(zclient->redist[afi][type], vrf_id); +		} +	} + +	if (zclient->sock > 0) +		zebra_redistribute_send(command, zclient, afi, type, instance, +					vrf_id);  } -void -zclient_redistribute_default (int command, struct zclient *zclient, -    vrf_id_t vrf_id) +void zclient_redistribute_default(int command, struct zclient *zclient, +				  vrf_id_t vrf_id)  { -  if (command == ZEBRA_REDISTRIBUTE_DEFAULT_ADD) -    { -      if (vrf_bitmap_check (zclient->default_information, vrf_id)) -        return; -      vrf_bitmap_set (zclient->default_information, vrf_id); -    } -  else  -    { -      if (!vrf_bitmap_check (zclient->default_information, vrf_id)) -        return; -      vrf_bitmap_unset (zclient->default_information, vrf_id); -    } - -  if (zclient->sock > 0) -    zebra_message_send (zclient, command, vrf_id); +	if (command == ZEBRA_REDISTRIBUTE_DEFAULT_ADD) { +		if (vrf_bitmap_check(zclient->default_information, vrf_id)) +			return; +		vrf_bitmap_set(zclient->default_information, vrf_id); +	} else { +		if (!vrf_bitmap_check(zclient->default_information, vrf_id)) +			return; +		vrf_bitmap_unset(zclient->default_information, vrf_id); +	} + +	if (zclient->sock > 0) +		zebra_message_send(zclient, command, vrf_id);  } -static void -zclient_event (enum event event, struct zclient *zclient) +static void zclient_event(enum event event, struct zclient *zclient)  { -  switch (event) -    { -    case ZCLIENT_SCHEDULE: -      if (! zclient->t_connect) -	zclient->t_connect = -	  thread_add_event (zclient->master, zclient_connect, zclient, 0); -      break; -    case ZCLIENT_CONNECT: -      if (zclient_debug) -	zlog_debug ("zclient connect failures: %d schedule interval is now %d", -		    zclient->fail, zclient->fail < 3 ? 10 : 60); -      if (! zclient->t_connect) -	zclient->t_connect =  -	  thread_add_timer (zclient->master, zclient_connect, zclient, -			    zclient->fail < 3 ? 10 : 60); -      break; -    case ZCLIENT_READ: -      zclient->t_read =  -	thread_add_read (zclient->master, zclient_read, zclient, zclient->sock); -      break; -    } +	switch (event) { +	case ZCLIENT_SCHEDULE: +		if (!zclient->t_connect) +			zclient->t_connect = thread_add_event( +				zclient->master, zclient_connect, zclient, 0); +		break; +	case ZCLIENT_CONNECT: +		if (zclient_debug) +			zlog_debug( +				"zclient connect failures: %d schedule interval is now %d", +				zclient->fail, zclient->fail < 3 ? 10 : 60); +		if (!zclient->t_connect) +			zclient->t_connect = thread_add_timer( +				zclient->master, zclient_connect, zclient, +				zclient->fail < 3 ? 10 : 60); +		break; +	case ZCLIENT_READ: +		zclient->t_read = thread_add_read(zclient->master, zclient_read, +						  zclient, zclient->sock); +		break; +	}  }  const char *zclient_serv_path_get()  { -  return zclient_serv_path ? zclient_serv_path : ZEBRA_SERV_PATH; +	return zclient_serv_path ? zclient_serv_path : ZEBRA_SERV_PATH;  } -void -zclient_serv_path_set (char *path) +void zclient_serv_path_set(char *path)  { -  struct stat sb; - -  /* reset */ -  zclient_serv_path = NULL; - -  /* test if `path' is socket. don't set it otherwise. */ -  if (stat(path, &sb) == -1) -    { -      zlog_warn ("%s: zebra socket `%s' does not exist", __func__, path); -      return; -    } - -  if ((sb.st_mode & S_IFMT) != S_IFSOCK) -    { -      zlog_warn ("%s: `%s' is not unix socket, sir", __func__, path); -      return; -    } - -  /* it seems that path is unix socket */ -  zclient_serv_path = path; -} +	struct stat sb; + +	/* reset */ +	zclient_serv_path = NULL; + +	/* test if `path' is socket. don't set it otherwise. */ +	if (stat(path, &sb) == -1) { +		zlog_warn("%s: zebra socket `%s' does not exist", __func__, +			  path); +		return; +	} + +	if ((sb.st_mode & S_IFMT) != S_IFSOCK) { +		zlog_warn("%s: `%s' is not unix socket, sir", __func__, path); +		return; +	} +	/* it seems that path is unix socket */ +	zclient_serv_path = path; +} diff --git a/lib/zclient.h b/lib/zclient.h index 489ed24c86..73bcd5f7e7 100644 --- a/lib/zclient.h +++ b/lib/zclient.h @@ -7,12 +7,12 @@   * under the terms of the GNU General Public License as published by   * the Free Software Foundation; either version 2, or (at your option)   * any later version. - *  + *   * GNU Zebra is distributed in the hope that it will be useful, but   * WITHOUT ANY WARRANTY; without even the implied warranty of   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU   * General Public License for more details. - *  + *   * You should have received a copy of the GNU General Public License   * along with GNU Zebra; see the file COPYING.  If not, write to the   * Free Software Foundation, Inc., 59 Temple Place - Suite 330, @@ -45,137 +45,143 @@  /* Zebra message types. */  typedef enum { -  ZEBRA_INTERFACE_ADD, -  ZEBRA_INTERFACE_DELETE, -  ZEBRA_INTERFACE_ADDRESS_ADD, -  ZEBRA_INTERFACE_ADDRESS_DELETE, -  ZEBRA_INTERFACE_UP, -  ZEBRA_INTERFACE_DOWN, -  ZEBRA_IPV4_ROUTE_ADD, -  ZEBRA_IPV4_ROUTE_DELETE, -  ZEBRA_IPV6_ROUTE_ADD, -  ZEBRA_IPV6_ROUTE_DELETE, -  ZEBRA_REDISTRIBUTE_ADD, -  ZEBRA_REDISTRIBUTE_DELETE, -  ZEBRA_REDISTRIBUTE_DEFAULT_ADD, -  ZEBRA_REDISTRIBUTE_DEFAULT_DELETE, -  ZEBRA_ROUTER_ID_ADD, -  ZEBRA_ROUTER_ID_DELETE, -  ZEBRA_ROUTER_ID_UPDATE, -  ZEBRA_HELLO, -  ZEBRA_NEXTHOP_REGISTER, -  ZEBRA_NEXTHOP_UNREGISTER, -  ZEBRA_NEXTHOP_UPDATE, -  ZEBRA_INTERFACE_NBR_ADDRESS_ADD, -  ZEBRA_INTERFACE_NBR_ADDRESS_DELETE, -  ZEBRA_INTERFACE_BFD_DEST_UPDATE, -  ZEBRA_IMPORT_ROUTE_REGISTER, -  ZEBRA_IMPORT_ROUTE_UNREGISTER, -  ZEBRA_IMPORT_CHECK_UPDATE, -  ZEBRA_IPV4_ROUTE_IPV6_NEXTHOP_ADD, -  ZEBRA_BFD_DEST_REGISTER, -  ZEBRA_BFD_DEST_DEREGISTER, -  ZEBRA_BFD_DEST_UPDATE, -  ZEBRA_BFD_DEST_REPLAY, -  ZEBRA_REDISTRIBUTE_IPV4_ADD, -  ZEBRA_REDISTRIBUTE_IPV4_DEL, -  ZEBRA_REDISTRIBUTE_IPV6_ADD, -  ZEBRA_REDISTRIBUTE_IPV6_DEL, -  ZEBRA_VRF_UNREGISTER, -  ZEBRA_VRF_ADD, -  ZEBRA_VRF_DELETE, -  ZEBRA_INTERFACE_VRF_UPDATE, -  ZEBRA_BFD_CLIENT_REGISTER, -  ZEBRA_INTERFACE_ENABLE_RADV, -  ZEBRA_INTERFACE_DISABLE_RADV, -  ZEBRA_IPV4_NEXTHOP_LOOKUP_MRIB, -  ZEBRA_INTERFACE_LINK_PARAMS, -  ZEBRA_MPLS_LABELS_ADD, -  ZEBRA_MPLS_LABELS_DELETE, -  ZEBRA_IPV4_NEXTHOP_ADD, -  ZEBRA_IPV4_NEXTHOP_DELETE, -  ZEBRA_IPV6_NEXTHOP_ADD, -  ZEBRA_IPV6_NEXTHOP_DELETE, -  ZEBRA_IPMR_ROUTE_STATS, -  ZEBRA_LABEL_MANAGER_CONNECT, -  ZEBRA_GET_LABEL_CHUNK, -  ZEBRA_RELEASE_LABEL_CHUNK, -  ZEBRA_PW_ADD, -  ZEBRA_PW_DELETE, -  ZEBRA_PW_SET, -  ZEBRA_PW_UNSET, -  ZEBRA_PW_STATUS_UPDATE, +	ZEBRA_INTERFACE_ADD, +	ZEBRA_INTERFACE_DELETE, +	ZEBRA_INTERFACE_ADDRESS_ADD, +	ZEBRA_INTERFACE_ADDRESS_DELETE, +	ZEBRA_INTERFACE_UP, +	ZEBRA_INTERFACE_DOWN, +	ZEBRA_IPV4_ROUTE_ADD, +	ZEBRA_IPV4_ROUTE_DELETE, +	ZEBRA_IPV6_ROUTE_ADD, +	ZEBRA_IPV6_ROUTE_DELETE, +	ZEBRA_REDISTRIBUTE_ADD, +	ZEBRA_REDISTRIBUTE_DELETE, +	ZEBRA_REDISTRIBUTE_DEFAULT_ADD, +	ZEBRA_REDISTRIBUTE_DEFAULT_DELETE, +	ZEBRA_ROUTER_ID_ADD, +	ZEBRA_ROUTER_ID_DELETE, +	ZEBRA_ROUTER_ID_UPDATE, +	ZEBRA_HELLO, +	ZEBRA_NEXTHOP_REGISTER, +	ZEBRA_NEXTHOP_UNREGISTER, +	ZEBRA_NEXTHOP_UPDATE, +	ZEBRA_INTERFACE_NBR_ADDRESS_ADD, +	ZEBRA_INTERFACE_NBR_ADDRESS_DELETE, +	ZEBRA_INTERFACE_BFD_DEST_UPDATE, +	ZEBRA_IMPORT_ROUTE_REGISTER, +	ZEBRA_IMPORT_ROUTE_UNREGISTER, +	ZEBRA_IMPORT_CHECK_UPDATE, +	ZEBRA_IPV4_ROUTE_IPV6_NEXTHOP_ADD, +	ZEBRA_BFD_DEST_REGISTER, +	ZEBRA_BFD_DEST_DEREGISTER, +	ZEBRA_BFD_DEST_UPDATE, +	ZEBRA_BFD_DEST_REPLAY, +	ZEBRA_REDISTRIBUTE_IPV4_ADD, +	ZEBRA_REDISTRIBUTE_IPV4_DEL, +	ZEBRA_REDISTRIBUTE_IPV6_ADD, +	ZEBRA_REDISTRIBUTE_IPV6_DEL, +	ZEBRA_VRF_UNREGISTER, +	ZEBRA_VRF_ADD, +	ZEBRA_VRF_DELETE, +	ZEBRA_INTERFACE_VRF_UPDATE, +	ZEBRA_BFD_CLIENT_REGISTER, +	ZEBRA_INTERFACE_ENABLE_RADV, +	ZEBRA_INTERFACE_DISABLE_RADV, +	ZEBRA_IPV4_NEXTHOP_LOOKUP_MRIB, +	ZEBRA_INTERFACE_LINK_PARAMS, +	ZEBRA_MPLS_LABELS_ADD, +	ZEBRA_MPLS_LABELS_DELETE, +	ZEBRA_IPV4_NEXTHOP_ADD, +	ZEBRA_IPV4_NEXTHOP_DELETE, +	ZEBRA_IPV6_NEXTHOP_ADD, +	ZEBRA_IPV6_NEXTHOP_DELETE, +	ZEBRA_IPMR_ROUTE_STATS, +	ZEBRA_LABEL_MANAGER_CONNECT, +	ZEBRA_GET_LABEL_CHUNK, +	ZEBRA_RELEASE_LABEL_CHUNK, +	ZEBRA_PW_ADD, +	ZEBRA_PW_DELETE, +	ZEBRA_PW_SET, +	ZEBRA_PW_UNSET, +	ZEBRA_PW_STATUS_UPDATE,  } zebra_message_types_t; -struct redist_proto -{ -  u_char enabled; -  struct list *instances; +struct redist_proto { +	u_char enabled; +	struct list *instances;  };  /* Structure for the zebra client. */ -struct zclient -{ -  /* The thread master we schedule ourselves on */ -  struct thread_master *master; - -  /* Socket to zebra daemon. */ -  int sock; - -  /* Flag of communication to zebra is enabled or not.  Default is on. -     This flag is disabled by `no router zebra' statement. */ -  int enable; - -  /* Connection failure count. */ -  int fail; - -  /* Input buffer for zebra message. */ -  struct stream *ibuf; - -  /* Output buffer for zebra message. */ -  struct stream *obuf; - -  /* Buffer of data waiting to be written to zebra. */ -  struct buffer *wb; - -  /* Read and connect thread. */ -  struct thread *t_read; -  struct thread *t_connect; - -  /* Thread to write buffered data to zebra. */ -  struct thread *t_write; - -  /* Redistribute information. */ -  u_char redist_default; /* clients protocol */ -  u_short instance; -  struct redist_proto mi_redist[AFI_MAX][ZEBRA_ROUTE_MAX]; -  vrf_bitmap_t redist[AFI_MAX][ZEBRA_ROUTE_MAX]; - -  /* Redistribute defauilt. */ -  vrf_bitmap_t default_information; - -  /* Pointer to the callback functions. */ -  void (*zebra_connected) (struct zclient *); -  int (*router_id_update) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_add) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_delete) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_up) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_down) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_address_add) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_address_delete) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_link_params) (int, struct zclient *, uint16_t); -  int (*interface_bfd_dest_update) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_nbr_address_add) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_nbr_address_delete) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*interface_vrf_update) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*nexthop_update) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*import_check_update) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*bfd_dest_replay) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*redistribute_route_ipv4_add) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*redistribute_route_ipv4_del) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*redistribute_route_ipv6_add) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*redistribute_route_ipv6_del) (int, struct zclient *, uint16_t, vrf_id_t); -  int (*pw_status_update) (int, struct zclient *, uint16_t, vrf_id_t); +struct zclient { +	/* The thread master we schedule ourselves on */ +	struct thread_master *master; + +	/* Socket to zebra daemon. */ +	int sock; + +	/* Flag of communication to zebra is enabled or not.  Default is on. +	   This flag is disabled by `no router zebra' statement. */ +	int enable; + +	/* Connection failure count. */ +	int fail; + +	/* Input buffer for zebra message. */ +	struct stream *ibuf; + +	/* Output buffer for zebra message. */ +	struct stream *obuf; + +	/* Buffer of data waiting to be written to zebra. */ +	struct buffer *wb; + +	/* Read and connect thread. */ +	struct thread *t_read; +	struct thread *t_connect; + +	/* Thread to write buffered data to zebra. */ +	struct thread *t_write; + +	/* Redistribute information. */ +	u_char redist_default; /* clients protocol */ +	u_short instance; +	struct redist_proto mi_redist[AFI_MAX][ZEBRA_ROUTE_MAX]; +	vrf_bitmap_t redist[AFI_MAX][ZEBRA_ROUTE_MAX]; + +	/* Redistribute defauilt. */ +	vrf_bitmap_t default_information; + +	/* Pointer to the callback functions. */ +	void (*zebra_connected)(struct zclient *); +	int (*router_id_update)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*interface_add)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*interface_delete)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*interface_up)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*interface_down)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*interface_address_add)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*interface_address_delete)(int, struct zclient *, uint16_t, +					vrf_id_t); +	int (*interface_link_params)(int, struct zclient *, uint16_t); +	int (*interface_bfd_dest_update)(int, struct zclient *, uint16_t, +					 vrf_id_t); +	int (*interface_nbr_address_add)(int, struct zclient *, uint16_t, +					 vrf_id_t); +	int (*interface_nbr_address_delete)(int, struct zclient *, uint16_t, +					    vrf_id_t); +	int (*interface_vrf_update)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*nexthop_update)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*import_check_update)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*bfd_dest_replay)(int, struct zclient *, uint16_t, vrf_id_t); +	int (*redistribute_route_ipv4_add)(int, struct zclient *, uint16_t, +					   vrf_id_t); +	int (*redistribute_route_ipv4_del)(int, struct zclient *, uint16_t, +					   vrf_id_t); +	int (*redistribute_route_ipv6_add)(int, struct zclient *, uint16_t, +					   vrf_id_t); +	int (*redistribute_route_ipv6_del)(int, struct zclient *, uint16_t, +					   vrf_id_t); +	int (*pw_status_update)(int, struct zclient *, uint16_t, vrf_id_t);  };  /* Zebra API message flag. */ @@ -188,168 +194,173 @@ struct zclient  #define ZAPI_MESSAGE_SRCPFX   0x40  /* Zserv protocol message header */ -struct zserv_header -{ -  uint16_t length; -  uint8_t marker;	/* corresponds to command field in old zserv -                         * always set to 255 in new zserv. -                         */ -  uint8_t version; +struct zserv_header { +	uint16_t length; +	uint8_t marker; /* corresponds to command field in old zserv +			 * always set to 255 in new zserv. +			 */ +	uint8_t version;  #define ZSERV_VERSION	4 -  vrf_id_t vrf_id; -  uint16_t command; +	vrf_id_t vrf_id; +	uint16_t command;  };  /* Zebra IPv4 route message API. */ -struct zapi_ipv4 -{ -  u_char type; -  u_short instance; +struct zapi_ipv4 { +	u_char type; +	u_short instance; -  u_int32_t flags; +	u_int32_t flags; -  u_char message; +	u_char message; -  safi_t safi; +	safi_t safi; -  u_char nexthop_num; -  struct in_addr **nexthop; +	u_char nexthop_num; +	struct in_addr **nexthop; -  u_char ifindex_num; -  ifindex_t *ifindex; +	u_char ifindex_num; +	ifindex_t *ifindex; -  u_char distance; +	u_char distance; -  u_int32_t metric; +	u_int32_t metric; -  route_tag_t tag; +	route_tag_t tag; -  u_int32_t mtu; +	u_int32_t mtu; -  vrf_id_t vrf_id; +	vrf_id_t vrf_id;  }; -struct zapi_pw -{ -  char ifname[IF_NAMESIZE]; -  ifindex_t ifindex; -  int type; -  int af; -  union g_addr nexthop; -  uint32_t local_label; -  uint32_t remote_label; -  uint8_t flags; -  union pw_protocol_fields data; -  uint8_t protocol; +struct zapi_pw { +	char ifname[IF_NAMESIZE]; +	ifindex_t ifindex; +	int type; +	int af; +	union g_addr nexthop; +	uint32_t local_label; +	uint32_t remote_label; +	uint8_t flags; +	union pw_protocol_fields data; +	uint8_t protocol;  }; -struct zapi_pw_status -{ -  char ifname[IF_NAMESIZE]; -  ifindex_t ifindex; -  uint32_t status; +struct zapi_pw_status { +	char ifname[IF_NAMESIZE]; +	ifindex_t ifindex; +	uint32_t status;  };  /* Prototypes of zebra client service functions. */ -extern struct zclient *zclient_new (struct thread_master *); -extern void zclient_init (struct zclient *, int, u_short); -extern int zclient_start (struct zclient *); -extern void zclient_stop (struct zclient *); -extern void zclient_reset (struct zclient *); -extern void zclient_free (struct zclient *); +extern struct zclient *zclient_new(struct thread_master *); +extern void zclient_init(struct zclient *, int, u_short); +extern int zclient_start(struct zclient *); +extern void zclient_stop(struct zclient *); +extern void zclient_reset(struct zclient *); +extern void zclient_free(struct zclient *); -extern int  zclient_socket_connect (struct zclient *); -extern void zclient_serv_path_set  (char *path); -extern const char *zclient_serv_path_get (void); +extern int zclient_socket_connect(struct zclient *); +extern void zclient_serv_path_set(char *path); +extern const char *zclient_serv_path_get(void); -extern u_short *redist_check_instance (struct redist_proto *, u_short); -extern void redist_add_instance (struct redist_proto *, u_short); -extern void redist_del_instance (struct redist_proto *, u_short); +extern u_short *redist_check_instance(struct redist_proto *, u_short); +extern void redist_add_instance(struct redist_proto *, u_short); +extern void redist_del_instance(struct redist_proto *, u_short); -extern void zclient_send_reg_requests (struct zclient *, vrf_id_t); -extern void zclient_send_dereg_requests (struct zclient *, vrf_id_t); +extern void zclient_send_reg_requests(struct zclient *, vrf_id_t); +extern void zclient_send_dereg_requests(struct zclient *, vrf_id_t); -extern void zclient_send_interface_radv_req (struct zclient *zclient, vrf_id_t vrf_id, -                                 struct interface *ifp, int enable, int ra_interval); +extern void zclient_send_interface_radv_req(struct zclient *zclient, +					    vrf_id_t vrf_id, +					    struct interface *ifp, int enable, +					    int ra_interval);  /* Send redistribute command to zebra daemon. Do not update zclient state. */ -extern int zebra_redistribute_send (int command, struct zclient *, afi_t, int type, u_short instance, vrf_id_t vrf_id); +extern int zebra_redistribute_send(int command, struct zclient *, afi_t, +				   int type, u_short instance, vrf_id_t vrf_id);  /* If state has changed, update state and call zebra_redistribute_send. */ -extern void zclient_redistribute (int command, struct zclient *, afi_t, int type, -                                  u_short instance, vrf_id_t vrf_id); +extern void zclient_redistribute(int command, struct zclient *, afi_t, int type, +				 u_short instance, vrf_id_t vrf_id);  /* If state has changed, update state and send the command to zebra. */ -extern void zclient_redistribute_default (int command, struct zclient *, -    vrf_id_t vrf_id); +extern void zclient_redistribute_default(int command, struct zclient *, +					 vrf_id_t vrf_id);  /* Send the message in zclient->obuf to the zebra daemon (or enqueue it).     Returns 0 for success or -1 on an I/O error. */  extern int zclient_send_message(struct zclient *);  /* create header for command, length to be filled in by user later */ -extern void zclient_create_header (struct stream *, uint16_t, vrf_id_t); -extern int zclient_read_header (struct stream *s, int sock, u_int16_t *size, -				u_char *marker, u_char *version, -				vrf_id_t *vrf_id, u_int16_t *cmd); - -extern struct interface *zebra_interface_add_read (struct stream *, vrf_id_t); -extern struct interface *zebra_interface_state_read (struct stream *s, vrf_id_t); -extern struct connected *zebra_interface_address_read (int, struct stream *, vrf_id_t); -extern struct nbr_connected *zebra_interface_nbr_address_read (int, struct stream *, vrf_id_t); -extern struct interface * zebra_interface_vrf_update_read (struct stream *s, vrf_id_t vrf_id, -                            vrf_id_t *new_vrf_id); -extern void zebra_interface_if_set_value (struct stream *, struct interface *); -extern void zebra_router_id_update_read (struct stream *s, struct prefix *rid); -extern int zapi_ipv4_route (u_char, struct zclient *, struct prefix_ipv4 *,  -                            struct zapi_ipv4 *); - -extern struct interface *zebra_interface_link_params_read (struct stream *); -extern size_t zebra_interface_link_params_write (struct stream *, -                                                 struct interface *); -extern int lm_label_manager_connect (struct zclient *zclient); -extern int lm_get_label_chunk (struct zclient *zclient, u_char keep, -                               uint32_t chunk_size, uint32_t *start, uint32_t *end); -extern int lm_release_label_chunk (struct zclient *zclient, uint32_t start, uint32_t end); -extern int zebra_send_pw(struct zclient *zclient, int command, struct zapi_pw *pw); +extern void zclient_create_header(struct stream *, uint16_t, vrf_id_t); +extern int zclient_read_header(struct stream *s, int sock, u_int16_t *size, +			       u_char *marker, u_char *version, +			       vrf_id_t *vrf_id, u_int16_t *cmd); + +extern struct interface *zebra_interface_add_read(struct stream *, vrf_id_t); +extern struct interface *zebra_interface_state_read(struct stream *s, vrf_id_t); +extern struct connected *zebra_interface_address_read(int, struct stream *, +						      vrf_id_t); +extern struct nbr_connected * +zebra_interface_nbr_address_read(int, struct stream *, vrf_id_t); +extern struct interface *zebra_interface_vrf_update_read(struct stream *s, +							 vrf_id_t vrf_id, +							 vrf_id_t *new_vrf_id); +extern void zebra_interface_if_set_value(struct stream *, struct interface *); +extern void zebra_router_id_update_read(struct stream *s, struct prefix *rid); +extern int zapi_ipv4_route(u_char, struct zclient *, struct prefix_ipv4 *, +			   struct zapi_ipv4 *); + +extern struct interface *zebra_interface_link_params_read(struct stream *); +extern size_t zebra_interface_link_params_write(struct stream *, +						struct interface *); +extern int lm_label_manager_connect(struct zclient *zclient); +extern int lm_get_label_chunk(struct zclient *zclient, u_char keep, +			      uint32_t chunk_size, uint32_t *start, +			      uint32_t *end); +extern int lm_release_label_chunk(struct zclient *zclient, uint32_t start, +				  uint32_t end); +extern int zebra_send_pw(struct zclient *zclient, int command, +			 struct zapi_pw *pw);  extern void zebra_read_pw_status_update(int command, struct zclient *zclient, -                                        zebra_size_t length, vrf_id_t vrf_id, -                                        struct zapi_pw_status *pw); +					zebra_size_t length, vrf_id_t vrf_id, +					struct zapi_pw_status *pw);  /* IPv6 prefix add and delete function prototype. */ -struct zapi_ipv6 -{ -  u_char type; -  u_short instance; +struct zapi_ipv6 { +	u_char type; +	u_short instance; -  u_int32_t flags; +	u_int32_t flags; -  u_char message; +	u_char message; -  safi_t safi; +	safi_t safi; -  u_char nexthop_num; -  struct in6_addr **nexthop; +	u_char nexthop_num; +	struct in6_addr **nexthop; -  u_char ifindex_num; -  ifindex_t *ifindex; +	u_char ifindex_num; +	ifindex_t *ifindex; -  u_char distance; +	u_char distance; -  u_int32_t metric; +	u_int32_t metric; -  route_tag_t tag; +	route_tag_t tag; -  u_int32_t mtu; +	u_int32_t mtu; -  vrf_id_t vrf_id; +	vrf_id_t vrf_id;  }; -extern int zapi_ipv6_route (u_char cmd, struct zclient *zclient,  -                     struct prefix_ipv6 *p, struct prefix_ipv6 *src_p, -                     struct zapi_ipv6 *api); -extern int zapi_ipv4_route_ipv6_nexthop (u_char, struct zclient *, -                                         struct prefix_ipv4 *, struct zapi_ipv6 *); +extern int zapi_ipv6_route(u_char cmd, struct zclient *zclient, +			   struct prefix_ipv6 *p, struct prefix_ipv6 *src_p, +			   struct zapi_ipv6 *api); +extern int zapi_ipv4_route_ipv6_nexthop(u_char, struct zclient *, +					struct prefix_ipv4 *, +					struct zapi_ipv6 *);  #endif /* _ZEBRA_ZCLIENT_H */ diff --git a/lib/zebra.h b/lib/zebra.h index 760264d752..fc0ac17be3 100644 --- a/lib/zebra.h +++ b/lib/zebra.h @@ -27,9 +27,9 @@ Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  #ifdef SUNOS_5  #define _XPG4_2 -typedef unsigned int    u_int32_t; -typedef unsigned short  u_int16_t; -typedef unsigned char   u_int8_t; +typedef unsigned int u_int32_t; +typedef unsigned short u_int16_t; +typedef unsigned char u_int8_t;  #endif /* SUNOS_5 */  #include <unistd.h> @@ -95,7 +95,7 @@ typedef unsigned char   u_int8_t;  #ifdef __va_copy  #define va_copy(DST,SRC) __va_copy(DST,SRC)  #else -/* Now we are desperate; this should work on many typical platforms.  +/* Now we are desperate; this should work on many typical platforms.     But this is slightly dangerous, because the standard does not require     va_copy to be a macro. */  #define va_copy(DST,SRC) memcpy(&(DST), &(SRC), sizeof(va_list)) @@ -216,17 +216,17 @@ typedef unsigned char   u_int8_t;  #endif /* HAVE_GLIBC_BACKTRACE */  /* Local includes: */ -#if !(defined(__GNUC__) || defined(VTYSH_EXTRACT_PL))  +#if !(defined(__GNUC__) || defined(VTYSH_EXTRACT_PL))  #define __attribute__(x) -#endif  /* !__GNUC__ || VTYSH_EXTRACT_PL */ +#endif /* !__GNUC__ || VTYSH_EXTRACT_PL */  #include "zassert.h"  #ifndef HAVE_STRLCAT -size_t strlcat (char *__restrict dest, const char *__restrict src, size_t size); +size_t strlcat(char *__restrict dest, const char *__restrict src, size_t size);  #endif  #ifndef HAVE_STRLCPY -size_t strlcpy (char *__restrict dest, const char *__restrict src, size_t size); +size_t strlcpy(char *__restrict dest, const char *__restrict src, size_t size);  #endif  #ifdef HAVE_BROKEN_CMSG_FIRSTHDR @@ -234,19 +234,19 @@ size_t strlcpy (char *__restrict dest, const char *__restrict src, size_t size);     please refer to http://bugzilla.quagga.net/show_bug.cgi?id=142 */  /* Check that msg_controllen is large enough. */ -#define ZCMSG_FIRSTHDR(mhdr) \ -  (((size_t)((mhdr)->msg_controllen) >= sizeof(struct cmsghdr)) ? \ -   CMSG_FIRSTHDR(mhdr) : (struct cmsghdr *)NULL) +#define ZCMSG_FIRSTHDR(mhdr)                                                   \ +	(((size_t)((mhdr)->msg_controllen) >= sizeof(struct cmsghdr))          \ +		 ? CMSG_FIRSTHDR(mhdr)                                         \ +		 : (struct cmsghdr *)NULL)  #warning "CMSG_FIRSTHDR is broken on this platform, using a workaround" -#else /* HAVE_BROKEN_CMSG_FIRSTHDR */ +#else  /* HAVE_BROKEN_CMSG_FIRSTHDR */  #define ZCMSG_FIRSTHDR(M) CMSG_FIRSTHDR(M)  #endif /* HAVE_BROKEN_CMSG_FIRSTHDR */ - -/*  +/*   * RFC 3542 defines several macros for using struct cmsghdr.   * Here, we define those that are not present   */ @@ -268,10 +268,10 @@ size_t strlcpy (char *__restrict dest, const char *__restrict src, size_t size);   * version.   */  #ifndef CMSG_SPACE -#define CMSG_SPACE(l)       (_CMSG_DATA_ALIGN(sizeof(struct cmsghdr)) + \ -                              _CMSG_HDR_ALIGN(l)) +#define CMSG_SPACE(l)                                                          \ +	(_CMSG_DATA_ALIGN(sizeof(struct cmsghdr)) + _CMSG_HDR_ALIGN(l))  #warning "assuming 4-byte alignment for CMSG_SPACE" -#endif  /* CMSG_SPACE */ +#endif /* CMSG_SPACE */  #ifndef CMSG_LEN @@ -282,29 +282,28 @@ size_t strlcpy (char *__restrict dest, const char *__restrict src, size_t size);  /*  The definition of struct in_pktinfo is missing in old version of      GLIBC 2.1 (Redhat 6.1).  */ -#if defined (GNU_LINUX) && ! defined (HAVE_STRUCT_IN_PKTINFO) -struct in_pktinfo -{ -  int ipi_ifindex; -  struct in_addr ipi_spec_dst; -  struct in_addr ipi_addr; +#if defined(GNU_LINUX) && !defined(HAVE_STRUCT_IN_PKTINFO) +struct in_pktinfo { +	int ipi_ifindex; +	struct in_addr ipi_spec_dst; +	struct in_addr ipi_addr;  };  #endif -/*  +/*   * IP_HDRINCL / struct ip byte order   *   * Linux: network byte order   * *BSD: network, except for length and offset. (cf Stevens)   * SunOS: nominally as per BSD. but bug: network order on LE. - * OpenBSD: network byte order, apart from older versions which are as per  + * OpenBSD: network byte order, apart from older versions which are as per   *          *BSD   */ -#if defined(__NetBSD__) \ -   || (defined(__FreeBSD__) && (__FreeBSD_version < 1100030)) \ -   || (defined(__OpenBSD__) && (OpenBSD < 200311)) \ -   || (defined(__APPLE__)) \ -   || (defined(SUNOS_5) && defined(WORDS_BIGENDIAN)) +#if defined(__NetBSD__)                                                        \ +	|| (defined(__FreeBSD__) && (__FreeBSD_version < 1100030))             \ +	|| (defined(__OpenBSD__) && (OpenBSD < 200311))                        \ +	|| (defined(__APPLE__))                                                \ +	|| (defined(SUNOS_5) && defined(WORDS_BIGENDIAN))  #define HAVE_IP_HDRINCL_BSD_ORDER  #endif @@ -319,7 +318,7 @@ struct in_pktinfo  #if defined(WORDS_BIGENDIAN)  #define BYTE_ORDER	BIG_ENDIAN -#else /* !WORDS_BIGENDIAN */ +#else  /* !WORDS_BIGENDIAN */  #define BYTE_ORDER	LITTLE_ENDIAN  #endif /* WORDS_BIGENDIAN */ @@ -330,17 +329,21 @@ struct in_pktinfo  #ifdef MAX  #undef MAX  #endif -#define MAX(a, b) \ -	({ typeof (a) _a = (a); \ -	   typeof (b) _b = (b); \ -	   _a > _b ? _a : _b; }) +#define MAX(a, b)                                                              \ +	({                                                                     \ +		typeof(a) _a = (a);                                            \ +		typeof(b) _b = (b);                                            \ +		_a > _b ? _a : _b;                                             \ +	})  #ifdef MIN  #undef MIN  #endif -#define MIN(a, b) \ -	({ typeof (a) _a = (a); \ -	   typeof (b) _b = (b); \ -	   _a < _b ? _a : _b; }) +#define MIN(a, b)                                                              \ +	({                                                                     \ +		typeof(a) _a = (a);                                            \ +		typeof(b) _b = (b);                                            \ +		_a < _b ? _a : _b;                                             \ +	})  #define ZEBRA_NUM_OF(x) (sizeof (x) / sizeof (x[0])) @@ -369,7 +372,7 @@ struct in_pktinfo  extern const char *zebra_route_string(unsigned int route_type);  /* Map a route type to a char.  For example, ZEBRA_ROUTE_RIPNG -> 'R'. */  extern char zebra_route_char(unsigned int route_type); -/* Map a zserv command type to the same string,  +/* Map a zserv command type to the same string,   * e.g. ZEBRA_INTERFACE_ADD -> "ZEBRA_INTERFACE_ADD" */  /* Map a protocol name to its number. e.g. ZEBRA_ROUTE_BGP->9*/  extern int proto_name2num(const char *s); @@ -378,7 +381,7 @@ extern int proto_name2num(const char *s);   * an AFI value to restrict input */  extern int proto_redistnum(int afi, const char *s); -extern const char *zserv_command_string (unsigned int command); +extern const char *zserv_command_string(unsigned int command);  #define strmatch(a,b) (!strcmp((a), (b))) @@ -398,12 +401,7 @@ extern const char *zserv_command_string (unsigned int command);  #endif  /* Address family numbers from RFC1700. */ -typedef enum { -  AFI_IP  = 1, -  AFI_IP6 = 2, -  AFI_L2VPN = 4, -  AFI_MAX = 5 -} afi_t; +typedef enum { AFI_IP = 1, AFI_IP6 = 2, AFI_L2VPN = 4, AFI_MAX = 5 } afi_t;  /* Subsequent Address Family Identifier. */  #define SAFI_UNICAST              1 @@ -431,12 +429,12 @@ typedef enum {   * Note: Only useful (i.e., supported) values are defined below.   */  typedef enum { -  IANA_AFI_RESERVED = 0, -  IANA_AFI_IPV4 = 1, -  IANA_AFI_IPV6 = 2, -  IANA_AFI_L2VPN = 25, -  IANA_AFI_IPMR = 128, -  IANA_AFI_IP6MR = 129 +	IANA_AFI_RESERVED = 0, +	IANA_AFI_IPV4 = 1, +	IANA_AFI_IPV6 = 2, +	IANA_AFI_L2VPN = 25, +	IANA_AFI_IPMR = 128, +	IANA_AFI_IP6MR = 129  } iana_afi_t;  #define IANA_SAFI_RESERVED            0 @@ -478,56 +476,56 @@ typedef uint32_t route_tag_t;  #define ROUTE_TAG_MAX UINT32_MAX  #define ROUTE_TAG_PRI PRIu32 -static inline afi_t afi_iana2int (iana_afi_t afi) +static inline afi_t afi_iana2int(iana_afi_t afi)  { -  if (afi == IANA_AFI_IPV4) -    return AFI_IP; -  if (afi == IANA_AFI_IPV6) -    return AFI_IP6; -  if (afi == IANA_AFI_L2VPN) -    return AFI_L2VPN; -  return AFI_MAX; +	if (afi == IANA_AFI_IPV4) +		return AFI_IP; +	if (afi == IANA_AFI_IPV6) +		return AFI_IP6; +	if (afi == IANA_AFI_L2VPN) +		return AFI_L2VPN; +	return AFI_MAX;  } -static inline iana_afi_t afi_int2iana (afi_t afi) +static inline iana_afi_t afi_int2iana(afi_t afi)  { -  if (afi == AFI_IP) -    return IANA_AFI_IPV4; -  if (afi == AFI_IP6) -    return IANA_AFI_IPV6; -  if (afi == AFI_L2VPN) -    return IANA_AFI_L2VPN; -  return IANA_AFI_RESERVED; +	if (afi == AFI_IP) +		return IANA_AFI_IPV4; +	if (afi == AFI_IP6) +		return IANA_AFI_IPV6; +	if (afi == AFI_L2VPN) +		return IANA_AFI_L2VPN; +	return IANA_AFI_RESERVED;  } -static inline safi_t safi_iana2int (safi_t safi) +static inline safi_t safi_iana2int(safi_t safi)  { -  if (safi == IANA_SAFI_UNICAST) -    return SAFI_UNICAST; -  if (safi == IANA_SAFI_MULTICAST) -    return SAFI_MULTICAST; -  if (safi == IANA_SAFI_MPLS_VPN) -    return SAFI_MPLS_VPN; -  if (safi == IANA_SAFI_ENCAP) -    return SAFI_ENCAP; -  if (safi == IANA_SAFI_EVPN) -    return SAFI_EVPN; -  return SAFI_MAX; +	if (safi == IANA_SAFI_UNICAST) +		return SAFI_UNICAST; +	if (safi == IANA_SAFI_MULTICAST) +		return SAFI_MULTICAST; +	if (safi == IANA_SAFI_MPLS_VPN) +		return SAFI_MPLS_VPN; +	if (safi == IANA_SAFI_ENCAP) +		return SAFI_ENCAP; +	if (safi == IANA_SAFI_EVPN) +		return SAFI_EVPN; +	return SAFI_MAX;  } -static inline safi_t safi_int2iana (safi_t safi) +static inline safi_t safi_int2iana(safi_t safi)  { -  if (safi == SAFI_UNICAST) -    return IANA_SAFI_UNICAST; -  if (safi == SAFI_MULTICAST) -    return IANA_SAFI_MULTICAST; -  if (safi == SAFI_MPLS_VPN) -    return IANA_SAFI_MPLS_VPN; -  if (safi == SAFI_ENCAP) -    return IANA_SAFI_ENCAP; -  if (safi == SAFI_EVPN) -    return IANA_SAFI_EVPN; -  return IANA_SAFI_RESERVED; +	if (safi == SAFI_UNICAST) +		return IANA_SAFI_UNICAST; +	if (safi == SAFI_MULTICAST) +		return IANA_SAFI_MULTICAST; +	if (safi == SAFI_MPLS_VPN) +		return IANA_SAFI_MPLS_VPN; +	if (safi == SAFI_ENCAP) +		return IANA_SAFI_ENCAP; +	if (safi == SAFI_EVPN) +		return IANA_SAFI_EVPN; +	return IANA_SAFI_RESERVED;  }  #endif /* _ZEBRA_H */  | 
