From ad02a0eb3054ed375fab1d527874f5b5d2b9f9a2 Mon Sep 17 00:00:00 2001 From: Stephen Hemminger Date: Wed, 21 Mar 2007 16:23:46 -0700 Subject: [PATCH] Initial commit sources from Aji_Srinivas@emc.com --- .depend | 16 + CHANGES_TO_RSTPLIB | 574 +++++++++++++++++++ LICENSE | 340 ++++++++++++ Makefile | 59 ++ TODO | 6 + bpdu_sock.c | 153 ++++++ bpdu_sock.h | 42 ++ bridge | 199 +++++++ bridge_ctl.h | 42 ++ bridge_track.c | 919 +++++++++++++++++++++++++++++++ brmon.c | 300 ++++++++++ brstate.c | 160 ++++++ ctl_cli_wrap.c | 67 +++ ctl_functions.h | 65 +++ ctl_main.c | 783 ++++++++++++++++++++++++++ ctl_socket.c | 145 +++++ ctl_socket.h | 167 ++++++ ctl_socket_client.c | 150 +++++ ctl_socket_client.h | 36 ++ ctl_socket_server.h | 33 ++ epoll_loop.c | 141 +++++ epoll_loop.h | 52 ++ include/libnetlink.h | 57 ++ include/linux/llc.h | 80 +++ include/linux/rtnetlink.h | 910 ++++++++++++++++++++++++++++++ libnetlink.c | 592 ++++++++++++++++++++ log.h | 69 +++ main.c | 110 ++++ netif_utils.c | 141 +++++ netif_utils.h | 42 ++ rstp.spec | 63 +++ rstpctl.8 | 146 +++++ rstpd.8 | 65 +++ rstplib/AUTHORS | 3 + rstplib/Authors | 2 + rstplib/B5055.txt | 47 ++ rstplib/B5056.txt | 141 +++++ rstplib/COPYING | 504 +++++++++++++++++ rstplib/CVS.HOWTO | 22 + rstplib/ChangeLog | 55 ++ rstplib/INSTALL | 16 + rstplib/Makefile | 102 ++++ rstplib/NEWS | 19 + rstplib/README | 37 ++ rstplib/README.files | 58 ++ rstplib/TODO | 22 + rstplib/base.h | 192 +++++++ rstplib/bitmap.h | 82 +++ rstplib/bridge.c | 307 +++++++++++ rstplib/choose.h | 42 ++ rstplib/cli.c | 511 +++++++++++++++++ rstplib/cli.h | 93 ++++ rstplib/edge.c | 114 ++++ rstplib/edge.h | 38 ++ rstplib/migrate.c | 119 ++++ rstplib/migrate.h | 37 ++ rstplib/mngr.c | 559 +++++++++++++++++++ rstplib/mngr.txt | 21 + rstplib/p2p.c | 90 +++ rstplib/p2p.h | 37 ++ rstplib/pcost.c | 133 +++++ rstplib/pcost.h | 37 ++ rstplib/port.c | 243 ++++++++ rstplib/port.h | 185 +++++++ rstplib/portinfo.c | 508 +++++++++++++++++ rstplib/portinfo.h | 40 ++ rstplib/rolesel.c | 369 +++++++++++++ rstplib/rolesel.h | 41 ++ rstplib/roletrns.c | 431 +++++++++++++++ rstplib/roletrns.h | 37 ++ rstplib/statmch.c | 122 +++++ rstplib/statmch.h | 87 +++ rstplib/stp_bpdu.h | 91 +++ rstplib/stp_cli.c | 796 +++++++++++++++++++++++++++ rstplib/stp_cli.h | 30 + rstplib/stp_in.c | 1095 +++++++++++++++++++++++++++++++++++++ rstplib/stp_in.h | 229 ++++++++ rstplib/stp_state.h | 7 + rstplib/stp_to.c | 193 +++++++ rstplib/stp_to.h | 92 ++++ rstplib/stpm.c | 361 ++++++++++++ rstplib/stpm.h | 117 ++++ rstplib/stpmgmt.c | 165 ++++++ rstplib/sttrans.c | 143 +++++ rstplib/sttrans.h | 38 ++ rstplib/times.c | 76 +++ rstplib/times.h | 50 ++ rstplib/topoch.c | 236 ++++++++ rstplib/topoch.h | 37 ++ rstplib/transmit.c | 382 +++++++++++++ rstplib/transmit.h | 38 ++ rstplib/uid.h | 63 +++ rstplib/uid_sock.c | 208 +++++++ rstplib/uid_sock.h | 81 +++ rstplib/uid_stp.h | 204 +++++++ rstplib/vector.c | 177 ++++++ rstplib/vector.h | 77 +++ 97 files changed, 17213 insertions(+) create mode 100644 .depend create mode 100644 CHANGES_TO_RSTPLIB create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 TODO create mode 100644 bpdu_sock.c create mode 100644 bpdu_sock.h create mode 100755 bridge create mode 100644 bridge_ctl.h create mode 100644 bridge_track.c create mode 100644 brmon.c create mode 100644 brstate.c create mode 100644 ctl_cli_wrap.c create mode 100644 ctl_functions.h create mode 100644 ctl_main.c create mode 100644 ctl_socket.c create mode 100644 ctl_socket.h create mode 100644 ctl_socket_client.c create mode 100644 ctl_socket_client.h create mode 100644 ctl_socket_server.h create mode 100644 epoll_loop.c create mode 100644 epoll_loop.h create mode 100644 include/libnetlink.h create mode 100644 include/linux/llc.h create mode 100644 include/linux/rtnetlink.h create mode 100644 libnetlink.c create mode 100644 log.h create mode 100644 main.c create mode 100644 netif_utils.c create mode 100644 netif_utils.h create mode 100644 rstp.spec create mode 100644 rstpctl.8 create mode 100644 rstpd.8 create mode 100644 rstplib/AUTHORS create mode 100644 rstplib/Authors create mode 100644 rstplib/B5055.txt create mode 100644 rstplib/B5056.txt create mode 100644 rstplib/COPYING create mode 100644 rstplib/CVS.HOWTO create mode 100644 rstplib/ChangeLog create mode 100644 rstplib/INSTALL create mode 100644 rstplib/Makefile create mode 100644 rstplib/NEWS create mode 100644 rstplib/README create mode 100644 rstplib/README.files create mode 100644 rstplib/TODO create mode 100644 rstplib/base.h create mode 100644 rstplib/bitmap.h create mode 100644 rstplib/bridge.c create mode 100644 rstplib/choose.h create mode 100644 rstplib/cli.c create mode 100644 rstplib/cli.h create mode 100644 rstplib/edge.c create mode 100644 rstplib/edge.h create mode 100644 rstplib/migrate.c create mode 100644 rstplib/migrate.h create mode 100644 rstplib/mngr.c create mode 100644 rstplib/mngr.txt create mode 100644 rstplib/p2p.c create mode 100644 rstplib/p2p.h create mode 100644 rstplib/pcost.c create mode 100644 rstplib/pcost.h create mode 100644 rstplib/port.c create mode 100644 rstplib/port.h create mode 100644 rstplib/portinfo.c create mode 100644 rstplib/portinfo.h create mode 100644 rstplib/rolesel.c create mode 100644 rstplib/rolesel.h create mode 100644 rstplib/roletrns.c create mode 100644 rstplib/roletrns.h create mode 100644 rstplib/statmch.c create mode 100644 rstplib/statmch.h create mode 100644 rstplib/stp_bpdu.h create mode 100644 rstplib/stp_cli.c create mode 100644 rstplib/stp_cli.h create mode 100644 rstplib/stp_in.c create mode 100644 rstplib/stp_in.h create mode 100644 rstplib/stp_state.h create mode 100644 rstplib/stp_to.c create mode 100644 rstplib/stp_to.h create mode 100644 rstplib/stpm.c create mode 100644 rstplib/stpm.h create mode 100644 rstplib/stpmgmt.c create mode 100644 rstplib/sttrans.c create mode 100644 rstplib/sttrans.h create mode 100644 rstplib/times.c create mode 100644 rstplib/times.h create mode 100644 rstplib/topoch.c create mode 100644 rstplib/topoch.h create mode 100644 rstplib/transmit.c create mode 100644 rstplib/transmit.h create mode 100644 rstplib/uid.h create mode 100644 rstplib/uid_sock.c create mode 100644 rstplib/uid_sock.h create mode 100644 rstplib/uid_stp.h create mode 100644 rstplib/vector.c create mode 100644 rstplib/vector.h diff --git a/.depend b/.depend new file mode 100644 index 0000000..f5374a5 --- /dev/null +++ b/.depend @@ -0,0 +1,16 @@ +bpdu_sock.o: bpdu_sock.c bpdu_sock.h epoll_loop.h include/linux/llc.h +bridge_config.o: bridge_config.c bridge_ctl.h bpdu_sock.h \ + rstplib/bitmap.h rstplib/uid_stp.h rstplib/stp_bpdu.h rstplib/stp_in.h \ + rstplib/stp_to.h log.h +brmon.o: brmon.c include/libnetlink.h include/linux/rtnetlink.h \ + bridge_ctl.h epoll_loop.h +brstate.o: brstate.c include/libnetlink.h include/linux/rtnetlink.h \ + bridge_ctl.h +epoll_loop.o: epoll_loop.c epoll_loop.h bridge_ctl.h +libnetlink.o: libnetlink.c include/libnetlink.h include/linux/rtnetlink.h +ctl_socket.o: ctl_socket.c ctl_socket.h rstplib/bitmap.h \ + rstplib/uid_stp.h rstplib/stp_bpdu.h rstplib/stp_in.h rstplib/stp_to.h \ + ctl_socket_server.h epoll_loop.h log.h +main.o: main.c epoll_loop.h bridge_ctl.h bpdu_sock.h ctl_socket_server.h \ + log.h +rstpd: bpdu_sock.o bridge_config.o brmon.o brstate.o epoll_loop.o libnetlink.o ctl_socket.o main.o diff --git a/CHANGES_TO_RSTPLIB b/CHANGES_TO_RSTPLIB new file mode 100644 index 0000000..b30b401 --- /dev/null +++ b/CHANGES_TO_RSTPLIB @@ -0,0 +1,574 @@ +Some changes have been made to RSTPLIB version rsttplib.1.1.0.2 for use in this +program. The changes are given in the following diff. +The changes fall into 3 categories: + +1. Changes to support dynamic addition and deletion of bridge ports. +2. Changes to support multiple bridges. +3. Fixes to protocol part based on 802.1w conformance testing results. + + +diff -Naur rstplib.1.1.02/base.h rstplib/base.h +--- rstplib.1.1.02/base.h 2002-01-20 00:33:22.000000000 -0800 ++++ rstplib/base.h 2006-10-26 13:43:15.000000000 -0700 +@@ -75,6 +75,7 @@ + CHOOSE(STP_Imlicite_Instance_Create_Failed), \ + CHOOSE(STP_Small_Bridge_Priority), \ + CHOOSE(STP_Large_Bridge_Priority), \ ++ CHOOSE(STP_Bridge_Priority_Not_A_Multiple_Of_4096), \ + CHOOSE(STP_Small_Hello_Time), \ + CHOOSE(STP_Large_Hello_Time), \ + CHOOSE(STP_Small_Max_Age), \ +@@ -83,6 +84,10 @@ + CHOOSE(STP_Large_Forward_Delay), \ + CHOOSE(STP_Forward_Delay_And_Max_Age_Are_Inconsistent),\ + CHOOSE(STP_Hello_Time_And_Max_Age_Are_Inconsistent), \ ++ CHOOSE(STP_Small_Port_Priority), \ ++ CHOOSE(STP_Large_Port_Priority), \ ++ CHOOSE(STP_Port_Priority_Not_A_Multiple_Of_16), \ ++ CHOOSE(STP_Large_Port_PCost), \ + CHOOSE(STP_Vlan_Had_Not_Yet_Been_Created), \ + CHOOSE(STP_Port_Is_Absent_In_The_Vlan), \ + CHOOSE(STP_Big_len8023_Format), \ +@@ -176,11 +181,11 @@ + + /* for debug trace messages */ + +-#ifdef __LINUX__ ++#ifdef __LINUX__USE_PRINTF_FOR_STRACE + extern char* sprint_time_stump (void); + #define stp_trace(F, B...) printf("%s:" F "\n", sprint_time_stump(), ##B) + #else +-extern ULONG stp_trace (const char* fmt, ...); ++extern void stp_trace (const char* fmt, ...); + #endif + + #endif /* _STP_BASE_H__ */ +diff -Naur rstplib.1.1.02/pcost.c rstplib/pcost.c +--- rstplib.1.1.02/pcost.c 2002-01-20 00:34:09.000000000 -0800 ++++ rstplib/pcost.c 2006-10-20 16:04:16.000000000 -0700 +@@ -70,8 +70,10 @@ + } + + static void +-updPortPathCost (STATE_MACH_T *this) ++updPortPathCost (PORT_T *port) + { ++ port->reselect = True; ++ port->selected = False; + } + + void +@@ -97,7 +99,7 @@ + port->usedSpeed = -1; + break; + case STABLE: +- updPortPathCost (this); ++ updPortPathCost (port); + break; + } + } +diff -Naur rstplib.1.1.02/port.c rstplib/port.c +--- rstplib.1.1.02/port.c 2002-01-20 00:34:10.000000000 -0800 ++++ rstplib/port.c 2006-10-20 16:04:16.000000000 -0700 +@@ -139,10 +139,10 @@ + this->port_id, + this->port_id); + STP_copy_times (&this->designTimes, &stpm->rootTimes); ++ this->fdWhile = 0; + } + + /* reset timers */ +- this->fdWhile = + this->helloWhen = + this->mdelayWhile = + this->rbWhile = +diff -Naur rstplib.1.1.02/portinfo.c rstplib/portinfo.c +--- rstplib.1.1.02/portinfo.c 2002-01-20 00:34:10.000000000 -0800 ++++ rstplib/portinfo.c 2006-10-20 16:04:16.000000000 -0700 +@@ -75,6 +75,12 @@ + + if (BPDU_RSTP == port->msgBpduType) { + port->msgPortRole = (port->msgFlags & PORT_ROLE_MASK) >> PORT_ROLE_OFFS; ++#ifndef ORIG ++ if (RSTP_PORT_ROLE_UNKN == port->msgPortRole) { ++ port->msgBpduVersion = FORCE_STP_COMPAT; ++ port->msgBpduType = BPDU_CONFIG_TYPE; ++ } ++#endif + } + + if (RSTP_PORT_ROLE_DESGN == port->msgPortRole || +@@ -109,10 +115,14 @@ + } + } + +- if (RSTP_PORT_ROLE_ROOT == port->msgBpduType && ++ if (RSTP_PORT_ROLE_ROOT == port->msgPortRole && + port->operPointToPointMac && ++ ! STP_VECT_compare_bridge_id (&port->msgPrio.root_bridge, ++ &port->portPrio.root_bridge) && ++ port->msgPrio.root_path_cost == port->portPrio.root_path_cost && + ! STP_VECT_compare_bridge_id (&port->msgPrio.design_bridge, + &port->portPrio.design_bridge) && ++ port->msgPrio.design_port == port->portPrio.design_port && + AGREEMENT_BIT & port->msgFlags) { + #ifdef STP_DBG + if (this->debug) { +diff -Naur rstplib.1.1.02/stp_in.c rstplib/stp_in.c +--- rstplib.1.1.02/stp_in.c 2002-01-20 00:34:13.000000000 -0800 ++++ rstplib/stp_in.c 2006-10-20 16:04:16.000000000 -0700 +@@ -170,6 +170,11 @@ + return STP_Large_Bridge_Priority; + } + ++ if (uid_cfg->bridge_priority & ~MASK_BR_PRIO) { ++ stp_trace ("%d bridge_priority must be a multiple of 4096", (int) uid_cfg->bridge_priority); ++ return STP_Bridge_Priority_Not_A_Multiple_Of_4096; ++ } ++ + if (uid_cfg->hello_time < MIN_BR_HELLOT) { + stp_trace ("%d hello_time small", (int) uid_cfg->hello_time); + return STP_Small_Hello_Time; +@@ -815,8 +820,13 @@ + return 0; + } + ++#ifdef ORIG + int + STP_IN_set_port_cfg (IN int vlan_id, IN UID_STP_PORT_CFG_T* uid_cfg) ++#else ++int ++STP_IN_set_port_cfg (int vlan_id, int port_index, UID_STP_PORT_CFG_T* uid_cfg) ++#endif + { + register STPM_T* this; + register PORT_T* port; +@@ -831,12 +841,21 @@ + return STP_Vlan_Had_Not_Yet_Been_Created; + } + ++#ifdef ORIG + for (port_no = 1; port_no <= max_port; port_no++) { + if (! BitmapGetBit(&uid_cfg->port_bmp, port_no - 1)) continue; ++#else ++ port_no = port_index; ++ { ++#endif + + port = _stpapi_port_find (this, port_no); + if (! port) {/* port is absent in the stpm :( */ ++#ifdef ORIG + continue; ++#else ++ return STP_Port_Is_Absent_In_The_Vlan; ++#endif + } + + if (PT_CFG_MCHECK & uid_cfg->field_mask) { +@@ -845,10 +864,18 @@ + } + + if (PT_CFG_COST & uid_cfg->field_mask) { ++ if (uid_cfg->admin_port_path_cost > MAX_PORT_PCOST) ++ return STP_Large_Port_PCost; + port->adminPCost = uid_cfg->admin_port_path_cost; + } + + if (PT_CFG_PRIO & uid_cfg->field_mask) { ++ if (uid_cfg->port_priority < MIN_PORT_PRIO) ++ return STP_Small_Port_Priority; ++ if (uid_cfg->port_priority > MAX_PORT_PRIO) ++ return STP_Large_Port_Priority; ++ if (uid_cfg->port_priority & ~MASK_PORT_PRIO) ++ return STP_Port_Priority_Not_A_Multiple_Of_16; + port->port_id = (uid_cfg->port_priority << 8) + port_no; + } + +@@ -955,3 +982,114 @@ + return rstp_error_names[rstp_err_no]; + } + ++/*---------------- Dynamic port create / delete ------------------*/ ++ ++int STP_IN_port_create(int vlan_id, int port_index) ++{ ++ register STPM_T* this; ++ ++ this = stpapi_stpm_find (vlan_id); ++ ++ if (! this) { /* can't create stpm :( */ ++ return STP_Vlan_Had_Not_Yet_Been_Created; ++ } ++ ++ PORT_T *port = STP_port_create (this, port_index); ++ if (! port) { ++ /* can't add port :( */ ++ stp_trace ("can't create port %d", (int) port_index); ++ return STP_Cannot_Create_Instance_For_Port; ++ } ++ STP_port_init(port, this, True); ++ ++ STP_compute_bridge_id(this); ++ STP_stpm_update_after_bridge_management (this); ++ STP_stpm_update (this); ++ return 0; ++} ++ ++int STP_IN_port_delete(int vlan_id, int port_index) ++{ ++ register STPM_T* this; ++ PORT_T *port; ++ ++ this = stpapi_stpm_find (vlan_id); ++ ++ if (! this) { /* can't find stpm :( */ ++ return STP_Vlan_Had_Not_Yet_Been_Created; ++ } ++ ++ port = _stpapi_port_find (this, port_index); ++ if (! port) { ++ return STP_Port_Is_Absent_In_The_Vlan; ++ } ++ ++ STP_port_delete (port); ++ ++ STP_compute_bridge_id(this); ++ STP_stpm_update_after_bridge_management (this); ++ STP_stpm_update (this); ++ return 0; ++} ++ ++ ++/*--- For multiple STP instances - non multithread use ---*/ ++ ++struct stp_instance ++{ ++ STPM_T *bridges; ++#ifdef STP_DBG ++ int dbg_rstp_deny; ++#endif ++ int max_port; /* Remove this */ ++ int nev; ++ RSTP_EVENT_T tev; ++}; ++ ++struct stp_instance *STP_IN_instance_create(void) ++{ ++ struct stp_instance *p; ++ p = malloc(sizeof(*p)); ++ if (!p) return p; ++ p->bridges = NULL; ++#ifdef STP_DBG ++ p->dbg_rstp_deny = 0; ++#endif ++ p->max_port = 1024; ++ p->tev = RSTP_EVENT_LAST_DUMMY; ++ p->nev = 0; ++ return p; ++} ++ ++void STP_IN_instance_begin(struct stp_instance *p) ++{ ++ bridges = p->bridges; ++#ifdef STP_DBG ++ dbg_rstp_deny = p->dbg_rstp_deny; ++#endif ++ max_port = p->max_port; ++ tev = p->tev; ++ nev = p->nev; ++} ++ ++void STP_IN_instance_end(struct stp_instance *p) ++{ ++ p->bridges = bridges; ++#ifdef STP_DBG ++ p->dbg_rstp_deny = dbg_rstp_deny; ++#endif ++ p->max_port = max_port; ++ p->tev = tev; ++ p->nev = nev; ++} ++ ++void STP_IN_instance_delete(struct stp_instance *p) ++{ ++ STP_IN_instance_begin(p); ++ STP_IN_delete_all(); ++ STP_IN_instance_end(p); ++ free(p); ++} ++ ++ ++ +diff -Naur rstplib.1.1.02/stp_in.h rstplib/stp_in.h +--- rstplib.1.1.02/stp_in.h 2002-01-20 00:33:52.000000000 -0800 ++++ rstplib/stp_in.h 2006-10-20 16:04:16.000000000 -0700 +@@ -56,6 +56,7 @@ + #define DEF_BR_PRIO 32768 + #define MIN_BR_PRIO 0 + #define MAX_BR_PRIO 61440 ++#define MASK_BR_PRIO 0xf000 + + #define DEF_BR_HELLOT 2 + #define MIN_BR_HELLOT 1 +@@ -76,12 +77,15 @@ + #define DEF_PORT_PRIO 128 + #define MIN_PORT_PRIO 0 + #define MAX_PORT_PRIO 240 /* in steps of 16 */ ++#define MASK_PORT_PRIO 0xf0 + + #define DEF_ADMIN_NON_STP False + #define DEF_ADMIN_EDGE True + #define DEF_LINK_DELAY 3 /* see edge.c */ + #define DEF_P2P P2P_AUTO + ++#define MAX_PORT_PCOST 200000000 ++ + /* Section 1: Create/Delete/Start/Stop the RSTP instance */ + + void /* init the engine */ +@@ -101,6 +105,12 @@ + int + STP_IN_delete_all (void); + ++/* Port create/delete */ ++ ++int STP_IN_port_create(int vlan_id, int port_index); ++ ++int STP_IN_port_delete(int vlan_id, int port_index); ++ + /* Section 2. "Get" management */ + + Bool +@@ -136,9 +146,15 @@ + BITMAP_T* port_bmp, + UID_STP_CFG_T* uid_cfg); + ++#ifdef ORIG + int + STP_IN_set_port_cfg (int vlan_id, + UID_STP_PORT_CFG_T* uid_cfg); ++#else ++int ++STP_IN_set_port_cfg (int vlan_id, int port_index, ++ UID_STP_PORT_CFG_T* uid_cfg); ++#endif + + #ifdef STP_DBG + int STP_IN_dbg_set_port_trace (char* mach_name, int enadis, +@@ -168,6 +184,19 @@ + STP_IN_rx_bpdu (int vlan_id, int port_index, BPDU_T* bpdu, size_t len); + #endif + ++/*--- For multiple STP instances - non multithread use ---*/ ++ ++struct stp_instance; ++/* Create struct to hold STP instance state and initialize it. ++ A copy of all global state in the library. */ ++struct stp_instance *STP_IN_instance_create(void); ++/* Set context from this STP instance */ ++void STP_IN_instance_begin(struct stp_instance *p); ++/* Save context back to this STP instance */ ++void STP_IN_instance_end(struct stp_instance *p); ++/* Delete this STP instance */ ++void STP_IN_instance_delete(struct stp_instance *p); ++ + #ifdef _STP_MACHINE_H__ + /* Inner usage definitions & functions */ + +diff -Naur rstplib.1.1.02/stp_state.h rstplib/stp_state.h +--- rstplib.1.1.02/stp_state.h 1969-12-31 16:00:00.000000000 -0800 ++++ rstplib/stp_state.h 2006-10-20 16:04:16.000000000 -0700 +@@ -0,0 +1,7 @@ ++#ifndef _STP_STATE_H__ ++#define _STP_STATE_H__ ++ ++ ++ ++ ++#endif +diff -Naur rstplib.1.1.02/stpm.c rstplib/stpm.c +--- rstplib.1.1.02/stpm.c 2002-01-20 00:34:14.000000000 -0800 ++++ rstplib/stpm.c 2006-10-30 19:21:51.000000000 -0800 +@@ -26,7 +26,11 @@ + #include "stpm.h" + #include "stp_to.h" /* for STP_OUT_flush_lt */ + +-static STPM_T *bridges = NULL; ++/*static*/ STPM_T *bridges = NULL; ++ ++/* We can flush learned fdb by port, so set this in stpm.c and topoch.c */ ++/* This doesn't seem to solve the topology change problems. Don't use it yet */ ++//#define STRONGLY_SPEC_802_1W + + static int + _stp_stpm_init_machine (STATE_MACH_T* this) +@@ -217,9 +221,11 @@ + { + register PORT_T* port; + ++#ifdef ORIG + if (! this->ports) { /* there are not any ports :( */ + return STP_There_Are_No_Ports; + } ++#endif + + if (! STP_compute_bridge_id (this)) {/* can't compute bridge id ? :( */ + return STP_Cannot_Compute_Bridge_Prio; +@@ -289,19 +295,16 @@ + STP_compute_bridge_id (STPM_T* this) + { + register PORT_T* port; +- register PORT_T* min_num_port; +- int port_index = 0; ++ unsigned char old[6], new[6]; ++ memset(&old, 0xff, sizeof(old)); + + for (port = this->ports; port; port = port->next) { +- if (! port_index || port->port_index < port_index) { +- min_num_port = port; +- port_index = port->port_index; +- } ++ STP_OUT_get_port_mac (port->port_index, new); ++ if (memcmp(new, old, sizeof(old)) < 0) ++ memcpy(old, new, sizeof(old)); + } + +- if (! min_num_port) return NULL; /* IMHO, it may not be */ +- +- STP_OUT_get_port_mac (min_num_port->port_index, this->BrId.addr); ++ memcpy(this->BrId.addr, old, sizeof(old)); + + return &this->BrId; + } +diff -Naur rstplib.1.1.02/stpm.h rstplib/stpm.h +--- rstplib.1.1.02/stpm.h 2002-01-20 00:33:54.000000000 -0800 ++++ rstplib/stpm.h 2006-10-20 16:04:16.000000000 -0700 +@@ -103,6 +103,8 @@ + STPM_T * + STP_stpm_get_the_list (void); + ++extern STPM_T *bridges; ++ + void + STP_stpm_update_after_bridge_management (STPM_T* this); + +diff -Naur rstplib.1.1.02/stpmgmt.c rstplib/stpmgmt.c +--- rstplib.1.1.02/stpmgmt.c 2002-01-20 00:34:14.000000000 -0800 ++++ rstplib/stpmgmt.c 2006-10-20 16:04:16.000000000 -0700 +@@ -50,6 +50,11 @@ + this->BrTimes.ForwardDelay = init_cfg.forward_delay; + this->ForceVersion = (PROTOCOL_VERSION_T) init_cfg.force_version; + } ++#ifdef ORIG ++#else ++ if (this->admin_state != STP_ENABLED) ++ err_code = STP_stpm_enable(this, STP_ENABLED); ++#endif + + RSTP_CRITICAL_PATH_END; + return err_code; +@@ -145,10 +150,11 @@ + int + STP_IN_delete_all (void) + { +- register STPM_T* stpm; ++ register STPM_T* stpm, *next; + + RSTP_CRITICAL_PATH_START; +- for (stpm = STP_stpm_get_the_list (); stpm; stpm = stpm->next) { ++ for (stpm = STP_stpm_get_the_list (); stpm; stpm = next) { ++ next = stpm->next; + STP_stpm_enable (stpm, STP_DISABLED); + STP_stpm_delete (stpm); + } +diff -Naur rstplib.1.1.02/topoch.c rstplib/topoch.c +--- rstplib.1.1.02/topoch.c 2002-01-20 00:34:16.000000000 -0800 ++++ rstplib/topoch.c 2006-10-30 19:22:01.000000000 -0800 +@@ -40,6 +40,10 @@ + #define GET_STATE_NAME STP_topoch_get_state_name + #include "choose.h" + ++/* We can flush learned fdb by port, so set this in stpm.c and topoch.c */ ++/* This doesn't seem to solve the topology change problems. Don't use it yet */ ++//#define STRONGLY_SPEC_802_1W ++ + #ifndef STRONGLY_SPEC_802_1W + /* + * In many kinds of hardware the function +@@ -61,12 +65,13 @@ + if (this->debug) { + stp_trace("%s (%s, %s, %s, '%s')", + "flush", port->port_name, port->owner->name, +- LT_FLASH_ONLY_THE_PORT == type ? "this port" : "other ports", ++ "this port", + reason); + } + + bret = STP_OUT_flush_lt (port->port_index, port->owner->vlan_id, + LT_FLASH_ONLY_THE_PORT, reason); ++ return bret; + } + #endif + +@@ -103,7 +108,11 @@ + if (port->sendRSTP && port->operPointToPointMac) { + return 2 * port->owner->rootTimes.HelloTime; + } ++#ifdef ORIG + return port->owner->rootTimes.MaxAge; ++#else ++ return port->owner->rootTimes.MaxAge + port->owner->rootTimes.ForwardDelay; ++#endif + } + + void +diff -Naur rstplib.1.1.02/transmit.c rstplib/transmit.c +--- rstplib.1.1.02/transmit.c 2002-01-20 00:34:17.000000000 -0800 ++++ rstplib/transmit.c 2006-10-20 16:04:16.000000000 -0700 +@@ -99,7 +99,11 @@ + { + unsigned short len8023; + ++#ifdef ORIG + STP_OUT_get_port_mac (port_index, bpdu_packet.mac.src_mac); ++#else ++ /* Don't bother. LLC trasmits with correct source MAC, we don't supply it */ ++#endif + + bpdu_packet.hdr.bpdu_type = bpdu_type; + bpdu_packet.hdr.version = (BPDU_RSTP == bpdu_type) ? +@@ -110,7 +114,11 @@ + len8023 = htons ((unsigned short) (pkt_len + 3)); + memcpy (&bpdu_packet.eth.len8023, &len8023, 2); + ++#ifdef ORIG + if (pkt_len < MIN_FRAME_LENGTH) pkt_len = MIN_FRAME_LENGTH; ++#else ++ /* Don't do this. LLC puts in 802.3 length based on what we transmit */ ++#endif + return pkt_len; + } + +@@ -235,7 +243,7 @@ + + pkt_len = build_bpdu_header (port->port_index, + BPDU_RSTP, +- sizeof (BPDU_HEADER_T) + sizeof (BPDU_BODY_T) + 2); ++ sizeof (BPDU_HEADER_T) + sizeof (BPDU_BODY_T) + 1); + build_config_bpdu (port, False); + + switch (port->selectedRole) { +@@ -258,7 +266,12 @@ + } + + bpdu_packet.body.flags |= (role << PORT_ROLE_OFFS); +- ++#ifndef ORIG ++ if (port->forwarding) ++ bpdu_packet.body.flags |= FORWARD_BIT; ++ if (port->learning) ++ bpdu_packet.body.flags |= LEARN_BIT; ++#endif + if (port->synced) { + #if 0 /* def STP_DBG */ + if (port->roletrns->debug) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..b7b5f53 --- /dev/null +++ b/LICENSE @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program 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 of the License, or + (at your option) any later version. + + This program 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 this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Library General +Public License instead of this License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..cace491 --- /dev/null +++ b/Makefile @@ -0,0 +1,59 @@ + +DSOURCES = brmon.c brstate.c libnetlink.c epoll_loop.c bridge_track.c ctl_socket.c netif_utils.c main.c + +DOBJECTS = $(DSOURCES:.c=.o) + +CTLSOURCES = ctl_main.c ctl_cli_wrap.c ctl_socket_client.c + +CTLOBJECTS = $(CTLSOURCES:.c=.o) + +CC=gcc +CFLAGS = -Wall -Werror -O2 -g -D_REENTRANT -D__LINUX__ -DVERSION=$(version) -DBUILD=$(build) -DSTP_DBG=1 -I. -I./include -I./rstplib + +all: rstpd rstpctl + +rstplib: + make -C rstplib librstp.a + +.PHONY: rstplib + +rstpd: $(DOBJECTS) rstplib + $(CC) -o $@ $(DOBJECTS) -L ./rstplib -lrstp + +rstpctl: $(CTLOBJECTS) + $(CC) -o $@ $(CTLOBJECTS) + +clean: + rm -f *.o rstpd rstpctl + make -C rstplib clean + rm -fr $(TOPDIR) $(BUILDDIR) + +install: all + install -m 755 -d $(INSTALLPREFIX)/sbin + install -m 755 rstpd $(INSTALLPREFIX)/sbin + install -m 755 rstpctl $(INSTALLPREFIX)/sbin + install -m 755 -d $(INSTALLPREFIX)/usr/share/man/man8 + install -m 644 rstpd.8 $(INSTALLPREFIX)/usr/share/man/man8 + install -m 644 rstpctl.8 $(INSTALLPREFIX)/usr/share/man/man8 + +# RPM Building, as non root +version := 0.16 +build := 1 + +BUILDROOT := $(CURDIR)/rpm_buildroot +TOPDIR := $(CURDIR)/rpm_topdir + +RPMBUILD=rpmbuild +RPMDEFS=\ + --buildroot=$(BUILDROOT) \ + --define='_topdir $(TOPDIR)' \ + --define='VERSION $(version)' \ + --define='BUILD $(build)' + +rpm: + mkdir -p $(BUILDROOT) $(TOPDIR)/BUILD $(TOPDIR)/SOURCES $(TOPDIR)/RPMS + (cd .. ; tar cfz $(TOPDIR)/SOURCES/rstp-$(version).tgz --exclude rstp-$(version)/rpm_buildroot --exclude rstp-$(version)/rpm_topdir rstp-$(version)) + $(RPMBUILD) $(RPMDEFS) -bb rstp.spec + cp $(TOPDIR)/RPMS/*/rstp-$(version)-$(build).*.rpm . + cp $(TOPDIR)/RPMS/*/rstp-debuginfo-$(version)-$(build).*.rpm . + diff --git a/TODO b/TODO new file mode 100644 index 0000000..7bf8024 --- /dev/null +++ b/TODO @@ -0,0 +1,6 @@ +Now, the STP instance is fully shutdown when the bridge is down, so it +is not possible to reconfigure RSTP at that time. + +We need better notifications about bridges and bridge ports getting +added and removed, independent of whether the interfaces are up or +down. diff --git a/bpdu_sock.c b/bpdu_sock.c new file mode 100644 index 0000000..4eb8b57 --- /dev/null +++ b/bpdu_sock.c @@ -0,0 +1,153 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#include "bpdu_sock.h" +#include "epoll_loop.h" +#include "netif_utils.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "log.h" + +#ifndef AF_LLC +#define AF_LLC 26 +#endif + +static const uint8_t stp_mc[ETH_ALEN] = { 0x01, 0x80, 0xc2, 0x00, 0x00, 0x00 }; + +void bpdu_send(struct epoll_event_handler *h, unsigned char *data, int len) +{ + struct sockaddr_llc to; + memset(&to, 0, sizeof(to)); + to.sllc_family = AF_LLC; + to.sllc_arphrd = ARPHRD_ETHER; + to.sllc_sap = LLC_SAP_BSPAN; + memcpy(to.sllc_mac, stp_mc, ETH_ALEN); + + if (fcntl(h->fd, F_SETFL, 0) < 0) + ERROR("Error unsetting O_NONBLOCK: %m"); + + int l = sendto(h->fd, data, len, 0, (struct sockaddr *)&to, sizeof(to)); + if (l < 0) + ERROR("sendto failed: %m"); + else if (l != len) + ERROR("short write in sendto: %d instead of %d", l, len); + + if (fcntl(h->fd, F_SETFL, O_NONBLOCK) < 0) + ERROR("Error setting O_NONBLOCK: %m"); +} + +void bpdu_rcv_handler(uint32_t events, struct epoll_event_handler *h) +{ + struct sockaddr_llc from; + socklen_t fromlen = sizeof(from); + int cc; + unsigned char buf[2048]; + + cc = recvfrom(h->fd, &buf, sizeof(buf), 0, + (struct sockaddr *) &from, &fromlen); + if (cc <= 0) { + ERROR("recvfrom failed: %m"); + return; + } + +#if 0 + printf("Src %02x:%02x:%02x:%02x:%02x:%02x\n", + from.sllc_mac[0], from.sllc_mac[1], + from.sllc_mac[2], from.sllc_mac[3], + from.sllc_mac[4], from.sllc_mac[5]); + int i, j; + for (i = 0; i < cc; i += 16) { + for (j = 0; j < 16 && i+j < cc; j++) + printf(" %02x", buf[i+j]); + printf("\n"); + } + printf("\n"); + fflush(stdout); +#endif + + bpdu_rcv(h->arg, buf, cc); +} + + +/* We added name as an arg here because we can't do if_indextoname here, + That needs which conflicts with */ +/* Needs fixing. Socket should be closed in case of errors */ +int bpdu_sock_create(struct epoll_event_handler *h, + int if_index, char *name, struct ifdata *arg) +{ + struct sockaddr_llc llc_addr; + memset(&llc_addr, 0, sizeof(llc_addr)); + llc_addr.sllc_family = AF_LLC; + llc_addr.sllc_arphrd = ARPHRD_ETHER; + llc_addr.sllc_sap = LLC_SAP_BSPAN; + + int s; + TSTM((s = socket(AF_LLC, SOCK_DGRAM, 0)) >= 0, -1, "%m"); + + TST(get_hwaddr(name, llc_addr.sllc_mac) == 0, -1); + + TSTM(bind(s, (struct sockaddr *) &llc_addr, sizeof(llc_addr)) == 0, -1, + "Can't bind to LLC SAP %#x: %m", llc_addr.sllc_sap); + { + struct ifreq ifr; + memset(&ifr, 0, sizeof(ifr)); + strncpy(ifr.ifr_name, name, IFNAMSIZ); + ifr.ifr_hwaddr.sa_family = AF_UNSPEC; + memcpy(ifr.ifr_hwaddr.sa_data, stp_mc, ETH_ALEN); + + TSTM(ioctl(s, SIOCADDMULTI, &ifr) == 0, -1, + "can't set multicast address for %s: %m", ifr.ifr_name); + } + + TSTM(fcntl(s, F_SETFL, O_NONBLOCK) == 0, -1, "%m"); + + h->fd = s; + h->arg = arg; + h->handler = bpdu_rcv_handler; + + if (add_epoll(h) < 0) + return -1; + + return 0; +} + +void bpdu_sock_delete(struct epoll_event_handler *h) +{ + remove_epoll(h); + close(h->fd); +} + diff --git a/bpdu_sock.h b/bpdu_sock.h new file mode 100644 index 0000000..14413e4 --- /dev/null +++ b/bpdu_sock.h @@ -0,0 +1,42 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#ifndef BPDU_SOCK_H +#define BPDU_SOCK_H + +#include "epoll_loop.h" + +struct ifdata; + +void bpdu_send(struct epoll_event_handler *h, unsigned char *data, int len); + +int bpdu_sock_create(struct epoll_event_handler *h, + int if_index, char *name, struct ifdata *ifdata); + +void bpdu_sock_delete(struct epoll_event_handler *h); + +/* Externally provided, we call it */ +void bpdu_rcv(struct ifdata *ifdata, unsigned char *data, int len); + +#endif diff --git a/bridge b/bridge new file mode 100755 index 0000000..cf0d1d3 --- /dev/null +++ b/bridge @@ -0,0 +1,199 @@ +#!/bin/sh +# +# chkconfig: 2345 11 89 +# description: Brings up and configures the ethernet bridge +# processname: bridge + +# Source function library. +. /etc/init.d/functions + +# Check that networking is up. +if [ "$NETWORKING" = "no" ] +then + exit 0 +fi + +RETVAL=0 + +[ -f /etc/rsbridgeinit.conf ] && . /etc/rsbridgeinit.conf + +###### Sample of what /etc/rsbridgeinit.conf should look like +# bridgeprefix="gbr" +# #UPDATE_STRING=-b eth2 eth3 +# BRIDGES="0" +# CSIF[0]="eth2" +# SSIF[0]="eth3" +########################## + +#Enable RSTP if we have /sbin/rstpd +RSTPD=/sbin/rstpd +RSTPCTL=/sbin/rstpctl +RSTP=0 +[ -x $RSTPD -a -x $RSTPCTL ] && RSTP=1 + +slaves () { + cat /proc/net/bonding/$1 | grep 'Slave Interface' | cut -d: -f2 +} + +# set interrupt affinity to first cpu +setsmpaffinity() { + if [[ $1 == bond* ]] ; then + for sl in `slaves $1`; do + irq=`grep $sl /proc/interrupts | cut -d: -f1` + echo 1 > /proc/irq/$irq/smp_affinity + done + else + irq=`grep $1 /proc/interrupts | cut -d: -f1` + echo 1 > /proc/irq/$irq/smp_affinity + fi +} + +start () { + [ $RSTP == 1 ] && echo Starting rstpd && daemon $RSTPD ">>" /var/log/rstpd.log "2>&1" + for b in $BRIDGES ; do + echo Starting service bridge $bridgeprefix$b + brctl addbr $bridgeprefix$b || RETVAL=1 + if [ $RSTP == 0 ] ; then + brctl stp $bridgeprefix$b on + brctl setbridgeprio $bridgeprefix$b 65000 + fi + + for br in ${CSIF[$b]} ; do + echo Adding CSIF $br on $bridgeprefix$b + ifup $br + brctl addif $bridgeprefix$b $br || RETVAL=1 + done + + if [ "$1" != "client" ]; then + for br in ${SSIF[$b]} ; do + echo Adding SSIF $br on $bridgeprefix$b + ifup $br + if [[ $br == bond* ]] ; then + for sl in `slaves $br`; do + ifconfig $sl down + done + else + ifconfig $br down + fi + brctl addif $bridgeprefix$b $br || RETVAL=1 + done + fi + ifup $bridgeprefix$b + if [ $RSTP == 1 ]; then + rstpctl rstp $bridgeprefix$b on + rstpctl setbridgeprio $bridgeprefix$b 61440 + fi + done + + for b in $BRIDGES ; do + + . /etc/sysconfig/network-scripts/ifcfg-$bridgeprefix$b +# We will always have the subnet route entry. If there is a default gateway +# on that subnet, we will have an entry for that as well + if [ -n "$GATEWAY" ] ; then rttarget=2 ; else rttarget=1 ; fi + rtcount=x + + count=1 + while true ; do + new_rtcount=`grep -c $bridgeprefix$b /proc/net/route`; + if [ $new_rtcount != $rtcount ]; then +#DEBUG echo Number of route entries for $bridgeprefix$b is $new_rtcount + rtcount=$new_rtcount + fi + if [ $rtcount == $rttarget ]; then +#DEBUG echo Reached target for $bridgeprefix$b + break; + fi + count=`expr $count + 1` + if [ $count -gt 12 ]; then + echo Incomplete IP configuration for $bridgeprefix$b. Check network config. Aborting. + break; + fi + echo Incomplete IP configuration for $bridgeprefix$b. Waiting 5 seconds. + sleep 5 + done + done +} + +stop () { + for b in $BRIDGES ; do + echo "Shutting down service bridge $bridgeprefix$b" + for br in ${SSIF[$b]} ; do + echo Removing SSIF $br on $bridgeprefix$b + brctl delif $bridgeprefix$b $br || RETVAL=1 + done + for br in ${CSIF[$b]} ; do + echo Removing CSIF $br on $bridgeprefix$b + brctl delif $bridgeprefix$b $br || RETVAL=1 + done + ifconfig $bridgeprefix$b down || RETVAL=1 + brctl delbr $bridgeprefix$b || RETVAL=1 + done + [ $RSTP == 1 ] && killproc rstpd + +} + +serverif () { + case "$1" in + up) + for b in $BRIDGES ; do + for br in ${SSIF[$b]} ; do + echo Enabling $br on $bridgeprefix$b + if [[ $br == bond* ]] ; then + for sl in `slaves $br`; do + echo ' ' Enabling slave $sl of $br + ifconfig $sl up + done + else + ifconfig $br up + fi + done + done + ;; + down) + for b in $BRIDGES ; do + for br in ${SSIF[$b]} ; do + echo Disabling $br on $bridgeprefix$b + if [[ $br == bond* ]]; then + for sl in `slaves $br`; do + echo ' ' Disabling slave $sl of $br + ifconfig $sl down + done + else + ifconfig $br down + fi + done + done + ;; + *) + exit 1 + esac +} + +# See how we were called. +case "$1" in + start) + start $2 + ;; + stop) + stop $2 + ;; + status) + for b in $BRIDGES ; do + ifconfig $bridgeprefix$b + brctl showstp $bridgeprefix$b + done + ;; + serverif) + serverif $2 + ;; + restart|reload) + stop + start + ;; + *) + echo $"Usage: $0 {start|stop|status|restart|reload}" + exit 1 +esac + +exit $RETVAL diff --git a/bridge_ctl.h b/bridge_ctl.h new file mode 100644 index 0000000..fdb1970 --- /dev/null +++ b/bridge_ctl.h @@ -0,0 +1,42 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#ifndef BRIDGE_CTL_H +#define BRIDGE_CTL_H + +int init_bridge_ops(void); + +void bridge_get_configuration(void); + +int bridge_set_state(int ifindex, int state); + +int bridge_send_bpdu(int ifindex, const unsigned char *data, int len); + +int bridge_notify(int br_index, int if_index, int newlink, int up); + +void bridge_bpdu_rcv(int if_index, const unsigned char *data, int len); + +void bridge_one_second(void); + +#endif diff --git a/bridge_track.c b/bridge_track.c new file mode 100644 index 0000000..f761840 --- /dev/null +++ b/bridge_track.c @@ -0,0 +1,919 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#include "bridge_ctl.h" +#include "netif_utils.h" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "log.h" + + +/*------------------------------------------------------------*/ + +struct ifdata +{ + int if_index; + struct ifdata *next; + int up; + char name[IFNAMSIZ]; + + int is_bridge; + /* If bridge */ + struct ifdata *bridge_next; + struct ifdata *port_list; + int do_stp; + int stp_up; + struct stp_instance *stp; + UID_BRIDGE_ID_T bridge_id; + /* Bridge config */ + UID_STP_MODE_T stp_enabled; + int bridge_priority; + int max_age; + int hello_time; + int forward_delay; + int force_version; + int hold_time; + + /* If port */ + int speed; + int duplex; + struct ifdata *master; + struct ifdata *port_next; + /* STP port index */ + int port_index; + /* STP port config */ + int port_priority; + int admin_port_path_cost; + ADMIN_P2P_T admin_point2point; + unsigned char admin_edge; + unsigned char admin_non_stp; /* 1- doesn't participate in STP, 1 - regular */ +}; + +/* Instances */ +struct ifdata *current_br = NULL; + +void instance_begin(struct ifdata *br) +{ + if (current_br) { + ERROR("BUG: Trying to set instance over existing instance."); + ERROR("%d", *(int *)0); /* ABORT */ + } + current_br = br; + STP_IN_instance_begin(br->stp); +} + +void instance_end(void) +{ + STP_IN_instance_end(current_br->stp); + current_br = NULL; +} + +struct ifdata *find_port(int port_index) +{ + struct ifdata *ifc = current_br->port_list; + while (ifc && ifc->port_index != port_index) + ifc=ifc->port_next; + return ifc; +} + + +/*************************************************************/ +/* Bridge and port defaults */ + +UID_STP_CFG_T default_bridge_stp_cfg = { + .field_mask = BR_CFG_ALL, + .bridge_priority = DEF_BR_PRIO, + .max_age = DEF_BR_MAXAGE, + .hello_time = DEF_BR_HELLOT, + .forward_delay = DEF_BR_FWDELAY, + .force_version = DEF_FORCE_VERS, /*NORMAL_RSTP*/ +}; + +void update_bridge_stp_config(struct ifdata *br, UID_STP_CFG_T *cfg) +{ + if (cfg->field_mask & BR_CFG_PRIO) + br->bridge_priority = cfg->bridge_priority; + if (cfg->field_mask & BR_CFG_AGE) + br->max_age = cfg->max_age; + if (cfg->field_mask & BR_CFG_HELLO) + br->hello_time = cfg->hello_time; + if (cfg->field_mask & BR_CFG_DELAY) + br->forward_delay = cfg->forward_delay; + if (cfg->field_mask & BR_CFG_FORCE_VER) + br->force_version = cfg->force_version; +} + +UID_STP_PORT_CFG_T default_port_stp_cfg = { + .field_mask = PT_CFG_ALL, + .port_priority = DEF_PORT_PRIO, + .admin_non_stp = DEF_ADMIN_NON_STP, + .admin_edge = False, // DEF_ADMIN_EDGE, + .admin_port_path_cost = ADMIN_PORT_PATH_COST_AUTO, + .admin_point2point = DEF_P2P, +}; + +void update_port_stp_config(struct ifdata *ifc, UID_STP_PORT_CFG_T *cfg) +{ + if (cfg->field_mask & PT_CFG_PRIO) + ifc->port_priority = cfg->port_priority; + if (cfg->field_mask & PT_CFG_NON_STP) + ifc->admin_non_stp = cfg->admin_non_stp; + if (cfg->field_mask & PT_CFG_EDGE) + ifc->admin_edge = cfg->admin_edge; + if (cfg->field_mask & PT_CFG_COST) + ifc->admin_port_path_cost = cfg->admin_port_path_cost; + if (cfg->field_mask & PT_CFG_P2P) + ifc->admin_point2point = cfg->admin_point2point; +} + +/**************************************************************/ + +int add_port_stp(struct ifdata *ifc) +{ /* Bridge is ifc->master */ + char name[IFNAMSIZ]; + TST(if_indextoname(ifc->if_index, name) != 0, -1); + TST((ifc->port_index = get_bridge_portno(ifc->name)) >= 0, -1); + + /* Add port to STP */ + instance_begin(ifc->master); + int r = STP_IN_port_create(0, ifc->port_index); + if (r == 0) { /* Update bridge ID */ + UID_STP_STATE_T state; + STP_IN_stpm_get_state(0, &state); + ifc->master->bridge_id = state.bridge_id; + } + instance_end(); + if ( r/* check for failure */) { + ERROR("Couldn't add port for ifindex %d to STP", ifc->if_index); + return -1; + } + return 0; +} + +void remove_port_stp(struct ifdata *ifc) +{ + /* Remove port from STP */ + instance_begin(ifc->master); + int r = STP_IN_port_delete(0, ifc->port_index); + instance_end(); + ifc->port_index = -1; + if (r != 0) { + ERROR("removing port %s failed for bridge %s: %s", + ifc->name, ifc->master->name, STP_IN_get_error_explanation(r)); + } +} + +int init_rstplib_instance(struct ifdata *br) +{ + br->stp = STP_IN_instance_create(); + if (br->stp == NULL) { + ERROR("Couldn't create STP instance for bridge %s", br->name); + return -1; + } + + BITMAP_T ports; BitmapClear(&ports); + instance_begin(br); + int r = STP_IN_stpm_create(0, br->name, &ports); + instance_end(); + if (r != 0) { + ERROR("stpm create failed for bridge %s: %s", + br->name, STP_IN_get_error_explanation(r)); + return -1; + } + + return 0; +} + +void clear_rstplib_instance(struct ifdata *br) +{ + instance_begin(br); + int r = STP_IN_delete_all(); + instance_end(); + if (r != 0) { + ERROR("stpm delete failed for bridge %s: %s", + br->name, STP_IN_get_error_explanation(r)); + } + + STP_IN_instance_delete(br->stp); + br->stp = NULL; +} + +int init_bridge_stp(struct ifdata *br) +{ + if (br->stp_up) { + ERROR("STP already started"); + return 0; + } + + /* Init STP state */ + TST(init_rstplib_instance(br) == 0, -1); + + struct ifdata *p = br->port_list; + while (p) { + if (add_port_stp(p) != 0) + break; + p = p->port_next; + } + if (p) { + struct ifdata *q = br->port_list; + while (q != p) { + remove_port_stp(q); + q = q->port_next; + } + /* Clear bridge STP state */ + clear_rstplib_instance(br); + return -1; + } + br->stp_up = 1; + return 0; +} + +void clear_bridge_stp(struct ifdata *br) +{ + if (!br->stp_up) + return; + br->stp_up = 0; + struct ifdata *p = br->port_list; + while (p) { + remove_port_stp(p); + p = p->port_next; + } + /* Clear bridge STP state */ + clear_rstplib_instance(br); +} + + +struct ifdata *if_head = NULL; +struct ifdata *br_head = NULL; + +struct ifdata *find_if(int if_index) +{ + struct ifdata *p = if_head; + while (p && p->if_index != if_index) + p = p->next; + return p; +} + +#define ADD_TO_LIST(_list, _next, _ifc) \ + do { \ + (_ifc)->_next = (_list); \ + (_list) = (_ifc); \ + } while (0) + +#define REMOVE_FROM_LIST(_list, _next, _ifc, _error_fmt, _args...) \ + do { \ + struct ifdata **_prev = &(_list); \ + while (*_prev && *_prev != (_ifc)) \ + _prev = &(*_prev)->_next; \ + if (*_prev != (_ifc)) \ + ERROR(_error_fmt, ##_args); \ + else \ + *_prev = (_ifc)->_next; \ + } while (0) + +/* Caller ensures that there isn't any ifdata with this index */ +/* If br is NULL, new interface is a bridge, else it is a port of br */ +struct ifdata *create_if(int if_index, struct ifdata *br) +{ + struct ifdata *p; + TST((p = malloc(sizeof(*p))) != NULL, NULL); + + /* Init fields */ + p->if_index = if_index; + p->is_bridge = (br == NULL); + memset(p->name, 0, sizeof(p->name)); + if_indextoname(if_index, p->name); + if (p->is_bridge) { + INFO("Add bridge %s", p->name); + /* Init slave list */ + p->port_list = NULL; + + p->do_stp = 0; + p->up = 0; + p->stp_up = 0; + p->stp = NULL; + update_bridge_stp_config(p, &default_bridge_stp_cfg); + ADD_TO_LIST(br_head, bridge_next, p); /* Add to bridge list */ + } + else { + INFO("Add iface %s to bridge %s", p->name, br->name); + p->up = 0; + p->speed = 0; + p->duplex = 0; + p->master = br; + update_port_stp_config(p, &default_port_stp_cfg); + ADD_TO_LIST(br->port_list, port_next, p); /* Add to bridge port list */ + if (br->stp_up) { + add_port_stp(p); + } + } + /* Add to interface list */ + ADD_TO_LIST(if_head, next, p); + + return p; +} + +void delete_if(struct ifdata *ifc) +{ + INFO("Delete iface %s", ifc->name); + if (ifc->is_bridge) { /* Bridge: */ + /* Stop STP */ + clear_bridge_stp(ifc); + /* Delete ports */ + while (ifc->port_list) + delete_if(ifc->port_list); + /* Remove from bridge list */ + REMOVE_FROM_LIST(br_head, bridge_next, ifc, + "Can't find interface ifindex %d bridge list", + ifc->if_index); + } + else { /* Port */ + if (ifc->master->stp_up) + remove_port_stp(ifc); + /* Remove from bridge port list */ + REMOVE_FROM_LIST(ifc->master->port_list, port_next, ifc, + "Can't find interface ifindex %d on br %d's port list", + ifc->if_index, ifc->master->if_index); + } + /* Remove from bridge interface list */ + REMOVE_FROM_LIST(if_head, next, ifc, + "Can't find interface ifindex %d on iflist", + ifc->if_index); +} + +void set_br_up(struct ifdata *br, int up) +{ + if (up != br->up) { + br->up = up; + if (br->do_stp) + up?(void)init_bridge_stp(br):clear_bridge_stp(br); + } +} + +void set_if_up(struct ifdata *ifc, int up) +{ + INFO("Port %s : %s", ifc->name, (up?"up":"down")); + int speed = -1; + int duplex = -1; + int notify_flags = 0; + const int NOTIFY_UP = 1, NOTIFY_SPEED = 2, NOTIFY_DUPLEX = 4; + if (!up) { /* Down */ + if (ifc->up) { + ifc->up = up; + notify_flags |= NOTIFY_UP; + } + } + else { /* Up */ + int r = ethtool_get_speed_duplex(ifc->name, &speed, &duplex); + if (r < 0) { /* Didn't succeed */ + } + if (speed < 0) speed = 10; + if (duplex < 0) duplex = 0; /* Assume half duplex */ + + if (speed != ifc->speed) { + ifc->speed = speed; + notify_flags |= NOTIFY_SPEED; + } + if (duplex != ifc->duplex) { + ifc->duplex = duplex; + notify_flags |= NOTIFY_DUPLEX; + } + if (!ifc->up) { + ifc->up = 1; + notify_flags |= NOTIFY_UP; + } + } + if (notify_flags && ifc->master->stp_up) { + instance_begin(ifc->master); + + if (notify_flags & NOTIFY_SPEED) + STP_IN_changed_port_speed(ifc->port_index, speed); + if (notify_flags & NOTIFY_DUPLEX) + STP_IN_changed_port_duplex(ifc->port_index); + if (notify_flags & NOTIFY_UP) + STP_IN_enable_port(ifc->port_index, ifc->up); + + instance_end(); + } +} + +/*------------------------------------------------------------*/ + +int bridge_notify(int br_index, int if_index, int newlink, int up) +{ + if (up) up = 1; + LOG("br_index %d, if_index %d, up %d", br_index, if_index, up); + + struct ifdata *br = NULL; + if (br_index >= 0) { + br = find_if(br_index); + if (br && !br->is_bridge) { + ERROR("Notification shows non bridge interface %d as bridge.", br_index); + return -1; + } + if (!br) + br = create_if(br_index, NULL); + if (!br) { + ERROR("Couldn't create data for bridge interface %d", br_index); + return -1; + } + /* Bridge must be up if we get such notifications */ + if (!br->up) + set_br_up(br, 1); + } + + struct ifdata *ifc = find_if(if_index); + + if (br) { + if (ifc) { + if (ifc->is_bridge) { + ERROR("Notification shows bridge interface %d as slave of %d", + if_index, br_index); + return -1; + } + if (ifc->master != br) { + INFO("Device %d has come to bridge %d. " + "Missed notify for deletion from bridge %d", + if_index, br_index, ifc->master->if_index); + delete_if(ifc); + ifc = NULL; + } + } + if (!ifc) + ifc = create_if(if_index, br); + if (!ifc) { + ERROR("Couldn't create data for interface %d (master %d)", + if_index, br_index); + return -1; + } + if (!newlink && !is_bridge_slave(br->name, ifc->name)) { + /* brctl delif generates a DELLINK, but so does ifconfig down. + So check and delete if it has been removed. + */ + delete_if(ifc); + return 0; + } + if (ifc->up != up) + set_if_up(ifc, up); /* And speed and duplex */ + } + else { /* No br_index */ + if (!newlink) { + /* DELLINK not from bridge means interface unregistered. */ + /* Cleanup removed bridge or removed bridge slave */ + if (ifc) + delete_if(ifc); + return 0; + } + else { /* This may be a new link */ + if (!ifc) { + char ifname[IFNAMSIZ]; + if (if_indextoname(if_index, ifname) && is_bridge(ifname)) { + ifc = create_if(if_index, NULL); + if (!ifc) { + ERROR("Couldn't create data for bridge interface %d", if_index); + return -1; + } + } + } + if (ifc && !ifc->is_bridge && + !is_bridge_slave(ifc->master->name, ifc->name)) { + /* Interface might have left bridge and we might have missed deletion */ + delete_if(ifc); + return 0; + } + if (ifc && ifc->up != up) { + if (ifc->is_bridge) + set_br_up(ifc, up); + else + set_if_up(ifc, up); + } + } + } + return 0; +} + +void bridge_bpdu_rcv(int if_index, const unsigned char *data, int len) +{ + LOG("ifindex %d, len %d", if_index, len); + struct ifdata *ifc = find_if(if_index); + TST(ifc && !ifc->is_bridge, ); + TST(ifc->up && ifc->master->stp_up, ); + BPDU_T bpdu; + memset(&bpdu.eth, 0, sizeof(bpdu.eth)); + if (len > sizeof(bpdu) - sizeof(bpdu.eth)) + len = sizeof(bpdu) - sizeof(bpdu.eth); + memcpy(&bpdu.hdr, data, len); + /* Do some validation */ + TST(len >= 4, ); + TST(bpdu.hdr.protocol[0] == 0 && bpdu.hdr.protocol[1] == 0, ); + switch (bpdu.hdr.bpdu_type) { + case BPDU_RSTP: + TST(len >= 36, ); + case BPDU_CONFIG_TYPE: + TST(len >= 35, ); + /* 802.1w doesn't ask for this */ + // TST(ntohs(*(uint16_t*)bpdu.body.message_age) + // < ntohs(*(uint16_t*)bpdu.body.max_age), ); + TST(memcmp(bpdu.body.bridge_id, &ifc->master->bridge_id, 8) != 0 || + (ntohs(*(uint16_t *)bpdu.body.port_id) & 0xfff) != ifc->port_index, ); + break; + case BPDU_TOPO_CHANGE_TYPE: + break; + default: + TST(0, ); + } + + // dump_hex(data, len); + instance_begin(ifc->master); + int r = STP_IN_rx_bpdu(0, ifc->port_index, &bpdu, len + sizeof(bpdu.eth)); + if (r) + ERROR("STP_IN_rx_bpdu on port %s returned %s", ifc->name, + STP_IN_get_error_explanation(r)); + instance_end(); +} + +void bridge_one_second(void) +{ + // LOG(""); + struct ifdata *br; + for (br = br_head; br; br = br->bridge_next) { + if (br->stp_up) { + instance_begin(br); + STP_IN_one_second(); + instance_end(); + } + } + + /* To get information about port changes when bridge is down */ + /* But won't work so well since we will not sense deletions */ + static int count = 0; + count++; + if (count % 60 == 0) + bridge_get_configuration(); + +} + +/* Implementing STP_OUT functions */ + +int flush_port(char *sys_name) +{ + FILE *f = fopen(sys_name, "w"); + TSTM(f, -1, "Couldn't open flush file %s for write.", sys_name); + int r = fwrite("1", 1, 1, f); + fclose(f); + TST(r == 1, -1); + return 0; +} + +int +STP_OUT_flush_lt (IN int port_index, IN int vlan_id, + IN LT_FLASH_TYPE_T type, IN char* reason) +{ + LOG("port index %d, flash type %d, reason %s", port_index, type, reason); + TST(vlan_id == 0, 0); + + char fname[128]; + if (port_index == 0) {/* i.e. passed port_index was 0 */ + sprintf(fname, "/sys/class/net/%s/bridge/flush", current_br->name); + flush_port(fname); + } + else if (type == LT_FLASH_ONLY_THE_PORT) { + struct ifdata *port = find_port(port_index); + TST(port != NULL, 0); + sprintf(fname, "/sys/class/net/%s/brif/%s/flush", + current_br->name, port->name); + flush_port(fname); + } + else if (type == LT_FLASH_ALL_PORTS_EXCLUDE_THIS) { + struct ifdata *port; + for (port = current_br->port_list; port; port = port->port_next) { + if (port->port_index != port_index) { + sprintf(fname, "/sys/class/net/%s/brif/%s/flush", + current_br->name, port->name); + flush_port(fname); + } + } + } + else + TST(0, 0); + + return 0; +} + +void /* for bridge id calculation */ +STP_OUT_get_port_mac (IN int port_index, OUT unsigned char* mac) +{ + LOG("port index %d", port_index); + struct ifdata *port = find_port(port_index); + TST(port != NULL, ); + get_hwaddr(port->name, mac); +} + +unsigned long +STP_OUT_get_port_oper_speed (IN unsigned int port_index) +{ + LOG("port index %d", port_index); + struct ifdata *port = find_port(port_index); + TST(port != NULL, 0); + LOG("Speed: %d", port->speed); + return port->speed; +} + +int /* 1- Up, 0- Down */ +STP_OUT_get_port_link_status (IN int port_index) +{ + LOG("port index %d", port_index); + struct ifdata *port = find_port(port_index); + TST(port != NULL, 0); + LOG("Link status: %d", port->up); + return port->up; +} + +int /* 1- Full, 0- Half */ +STP_OUT_get_duplex (IN int port_index) +{ + LOG("port index %d", port_index); + struct ifdata *port = find_port(port_index); + TST(port != NULL, 0); + LOG("Duplex: %d", port->duplex); + return port->duplex; +} + +int +STP_OUT_set_port_state (IN int port_index, IN int vlan_id, IN RSTP_PORT_STATE state) +{ + LOG("port index %d, state %d", port_index, state); + struct ifdata *port = find_port(port_index); + TST(port != NULL, 0); + TST(vlan_id == 0, 0); + + int br_state; + switch (state) { + case UID_PORT_DISCARDING: + br_state = BR_STATE_BLOCKING; break; + case UID_PORT_LEARNING: + br_state = BR_STATE_LEARNING; break; + case UID_PORT_FORWARDING: + br_state = BR_STATE_FORWARDING; break; + default: + fprintf(stderr, "set_port_state: Unexpected state %d\n", state); + return -1; + } + if (port->up) + bridge_set_state(port->if_index, br_state); + return 0; +} + +int +STP_OUT_set_hardware_mode (int vlan_id, UID_STP_MODE_T mode) +{ + LOG("vlan id %d, mode %d", vlan_id, mode); + return 0; +} + +int +STP_OUT_tx_bpdu (IN int port_index, IN int vlan_id, + IN unsigned char* bpdu, + IN size_t bpdu_len) +{ + LOG("port index %d, len %zd", port_index, bpdu_len); + struct ifdata *port = find_port(port_index); + TST(port != NULL, 0); + TST(vlan_id == 0, 0); + // dump_hex(bpdu + sizeof(MAC_HEADER_T) + sizeof(ETH_HEADER_T), + // bpdu_len - (sizeof(MAC_HEADER_T) + sizeof(ETH_HEADER_T))); + bridge_send_bpdu(port->if_index, + bpdu + sizeof(MAC_HEADER_T) + sizeof(ETH_HEADER_T), + bpdu_len); // The length we get excludes headers! + return 0; +} + +const char * +STP_OUT_get_port_name (IN int port_index) +{ + LOG("port index %d", port_index); + struct ifdata *port = find_port(port_index); + TST(port != NULL, 0); + return port->name; +} + +int +STP_OUT_get_init_stpm_cfg (IN int vlan_id, + INOUT UID_STP_CFG_T* cfg) +{ + LOG(""); + TST(vlan_id == 0, 0); + + cfg->bridge_priority = current_br->bridge_priority; + cfg->max_age = current_br->max_age; + cfg->hello_time = current_br->hello_time; + cfg->forward_delay = current_br->forward_delay; + cfg->force_version = current_br->force_version; + + return 0; +} + +int +STP_OUT_get_init_port_cfg (IN int vlan_id, + IN int port_index, + INOUT UID_STP_PORT_CFG_T* cfg) +{ + LOG("port index %d", port_index); + struct ifdata *port = find_port(port_index); + TST(port != NULL, 0); + TST(vlan_id == 0, 0); + + cfg->port_priority = port->port_priority; + cfg->admin_non_stp = port->admin_non_stp; + cfg->admin_edge = port->admin_edge; + cfg->admin_port_path_cost = port->admin_port_path_cost; + cfg->admin_point2point = port->admin_point2point; + + return 0; +} + +extern void stp_trace (const char* fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vDprintf(LOG_LEVEL_RSTPLIB, fmt, ap); + va_end(ap); +} + +/* Commands and status */ +#include "ctl_functions.h" + +#define CTL_CHECK_BRIDGE \ + struct ifdata *br = find_if(br_index); \ + if (br == NULL || !br->is_bridge) return Err_Interface_not_a_bridge; \ + if (!br->do_stp) return Err_Bridge_RSTP_not_enabled; \ + if (!br->stp_up) return Err_Bridge_is_down; \ + do { } while (0) + +#define CTL_CHECK_BRIDGE_PORT \ + CTL_CHECK_BRIDGE; \ + struct ifdata *port = find_if(port_index); \ + if (port == NULL || port->is_bridge || port->master != br) \ + return Err_Port_does_not_belong_to_bridge; \ + do { } while (0) + +int CTL_enable_bridge_rstp(int br_index, int enable) +{ + INFO("bridge %d, enable %d", br_index, enable); + int r = 0; + if (enable) enable = 1; + struct ifdata *br = find_if(br_index); + if (br == NULL) { + char ifname[IFNAMSIZ]; + if (if_indextoname(br_index, ifname) && is_bridge(ifname)) + br = create_if(br_index, NULL); + } + if (br == NULL || !br->is_bridge) return Err_Interface_not_a_bridge; + if (br->do_stp != enable) { + br->do_stp = enable; + if (br->up) + r = enable?init_bridge_stp(br):(clear_bridge_stp(br), 0); + } + return r; +} + +int CTL_get_bridge_state(int br_index, + UID_STP_CFG_T *cfg, UID_STP_STATE_T *state) +{ + LOG("bridge %d", br_index); + CTL_CHECK_BRIDGE; + int r; + instance_begin(br); + r = STP_IN_stpm_get_state (0, state); + if (r) { + ERROR("Error getting bridge state for %d: %s", br_index, + STP_IN_get_error_explanation(r)); + instance_end(); + return r; + } + r = STP_IN_stpm_get_cfg(0, cfg); + if (r) { + ERROR("Error getting bridge config for %d: %s", br_index, + STP_IN_get_error_explanation(r)); + instance_end(); + return r; + } + instance_end(); + return 0; +} + +int CTL_set_bridge_config(int br_index, + UID_STP_CFG_T *cfg) +{ + INFO("bridge %d, flags %#lx", br_index, cfg->field_mask); + CTL_CHECK_BRIDGE; + int r; + instance_begin(br); + r = STP_IN_stpm_set_cfg (0, NULL, cfg); + if (r) { + ERROR("Error setting bridge config for %d: %s", br_index, + STP_IN_get_error_explanation(r)); + instance_end(); + return r; + } + instance_end(); + /* Change init config in ifdata so it will be applied if we + disable and enable rstp*/ + update_bridge_stp_config(br, cfg); + return 0; +} + +int CTL_get_port_state(int br_index, int port_index, + UID_STP_PORT_CFG_T *cfg, UID_STP_PORT_STATE_T *state) +{ + LOG("bridge %d port %d", br_index, port_index); + CTL_CHECK_BRIDGE_PORT; + int r; + instance_begin(br); + state->port_no = port->port_index; + r = STP_IN_port_get_state (0, state); + if (r) { + ERROR("Error getting port state for port %d, bridge %d: %s", + port->port_index, br_index, STP_IN_get_error_explanation(r)); + instance_end(); + return r; + } + r = STP_IN_port_get_cfg(0, port->port_index, cfg); + if (r) { + ERROR("Error getting port config for port %d, bridge %d: %s", + port->port_index, br_index, STP_IN_get_error_explanation(r)); + instance_end(); + return r; + } + instance_end(); + return 0; + +} + +int CTL_set_port_config(int br_index, int port_index, + UID_STP_PORT_CFG_T *cfg) +{ + INFO("bridge %d, port %d, flags %#lx", br_index, port_index, + cfg->field_mask); + CTL_CHECK_BRIDGE_PORT; + int r; + instance_begin(br); + r = STP_IN_set_port_cfg (0, port->port_index, cfg); + if (r) { + ERROR("Error setting port config for port %d, bridge %d: %s", + port->port_index, br_index, STP_IN_get_error_explanation(r)); + instance_end(); + return r; + } + instance_end(); + /* Change init config in ifdata so it will be applied if we + disable and enable rstp*/ + update_port_stp_config(port, cfg); + return 0; +} + +int CTL_set_debug_level(int level) +{ + INFO("level %d", level); + log_level = level; + return 0; +} + + +#undef CTL_CHECK_BRIDGE_PORT +#undef CTL_CHECK_BRIDGE diff --git a/brmon.c b/brmon.c new file mode 100644 index 0000000..4afe5e1 --- /dev/null +++ b/brmon.c @@ -0,0 +1,300 @@ +/* + * brmon.c RTnetlink listener. + * + * This program 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 of the License, or (at your option) any later version. + * + * Authors: Stephen Hemminger + * + * Modified by Srinivas Aji for use + * in RSTP daemon. - 2006-09-01 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "libnetlink.h" + +#include "bridge_ctl.h" + +static const char SNAPSHOT[] = "v0.1"; + + +/* RFC 2863 operational status */ +enum { + IF_OPER_UNKNOWN, + IF_OPER_NOTPRESENT, + IF_OPER_DOWN, + IF_OPER_LOWERLAYERDOWN, + IF_OPER_TESTING, + IF_OPER_DORMANT, + IF_OPER_UP, +}; + +/* link modes */ +enum { + IF_LINK_MODE_DEFAULT, + IF_LINK_MODE_DORMANT, /* limit upward transition to dormant */ +}; + +static const char *port_states[] = { + [BR_STATE_DISABLED] = "disabled", + [BR_STATE_LISTENING] = "listening", + [BR_STATE_LEARNING] = "learning", + [BR_STATE_FORWARDING] = "forwarding", + [BR_STATE_BLOCKING] = "blocking", +}; + + +static int dump_msg(const struct sockaddr_nl *who, struct nlmsghdr *n, + void *arg) +{ + FILE *fp = arg; + struct ifinfomsg *ifi = NLMSG_DATA(n); + struct rtattr * tb[IFLA_MAX+1]; + int len = n->nlmsg_len; + char b1[IFNAMSIZ]; + int af_family = ifi->ifi_family; + + if (n->nlmsg_type == NLMSG_DONE) + return 0; + + len -= NLMSG_LENGTH(sizeof(*ifi)); + if (len < 0) { + return -1; + } + +#if 0 + + if (filter.ifindex && ifi->ifi_index != filter.ifindex) + return 0; + + if (filter.up && !(ifi->ifi_flags&IFF_UP)) + return 0; +#endif + if (ifi->ifi_family != AF_BRIDGE && ifi->ifi_family != AF_UNSPEC) + return 0; + + if (n->nlmsg_type != RTM_NEWLINK && + n->nlmsg_type != RTM_DELLINK) + return 0; + + parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len); + + /* Check if we got this from bonding */ + if (tb[IFLA_MASTER] && af_family != AF_BRIDGE) + return 0; + + /* Check for BPDU */ + if (tb[IFLA_PRIORITY] && af_family == AF_BRIDGE) { + bridge_bpdu_rcv(ifi->ifi_index, + RTA_DATA(tb[IFLA_PRIORITY]), + RTA_PAYLOAD(tb[IFLA_PRIORITY])); + return 0; + } + + if (tb[IFLA_IFNAME] == NULL) { + fprintf(stderr, "BUG: nil ifname\n"); + return -1; + } + + if (n->nlmsg_type == RTM_DELLINK) + fprintf(fp, "Deleted "); + + fprintf(fp, "%d: %s ", ifi->ifi_index, + tb[IFLA_IFNAME] ? (char*)RTA_DATA(tb[IFLA_IFNAME]) : ""); + + + if (tb[IFLA_OPERSTATE]) { + int state = *(int*)RTA_DATA(tb[IFLA_OPERSTATE]); + switch (state) { + case IF_OPER_UNKNOWN: + fprintf(fp, "Unknown "); break; + case IF_OPER_NOTPRESENT: + fprintf(fp, "Not Present "); break; + case IF_OPER_DOWN: + fprintf(fp, "Down "); break; + case IF_OPER_LOWERLAYERDOWN: + fprintf(fp, "Lowerlayerdown "); break; + case IF_OPER_TESTING: + fprintf(fp, "Testing "); break; + case IF_OPER_DORMANT: + fprintf(fp, "Dormant "); break; + case IF_OPER_UP: + fprintf(fp, "Up "); break; + default: + fprintf(fp, "State(%d) ", state); + } + } + + if (tb[IFLA_MTU]) + fprintf(fp, "mtu %u ", *(int*)RTA_DATA(tb[IFLA_MTU])); + + if (tb[IFLA_MASTER]) { + fprintf(fp, "master %s ", + if_indextoname(*(int*)RTA_DATA(tb[IFLA_MASTER]), b1)); + } + + if (tb[IFLA_PROTINFO]) { + uint8_t state = *(uint8_t *)RTA_DATA(tb[IFLA_PROTINFO]); + if (state <= BR_STATE_BLOCKING) + fprintf(fp, "state %s", port_states[state]); + else + fprintf(fp, "state (%d)", state); + } + + + fprintf(fp, "\n"); + fflush(fp); + { + int newlink = (n->nlmsg_type == RTM_NEWLINK); + int up = 0; + if (newlink && tb[IFLA_OPERSTATE]) { + int state = *(int*)RTA_DATA(tb[IFLA_OPERSTATE]); + up = (state == IF_OPER_UP) || (state == IF_OPER_UNKNOWN); + } + + bridge_notify((tb[IFLA_MASTER]?*(int*)RTA_DATA(tb[IFLA_MASTER]):-1), + ifi->ifi_index, newlink, up); + } + return 0; +} + +#if 0 +static void usage(void) +{ + fprintf(stderr, "Usage: brmon\n"); + exit(-1); +} + +static int matches(const char *cmd, const char *pattern) +{ + int len = strlen(cmd); + if (len > strlen(pattern)) + return -1; + return memcmp(pattern, cmd, len); +} + +int +main(int argc, char **argv) +{ + struct rtnl_handle rth; + unsigned groups = ~RTMGRP_TC; + int llink = 0; + int laddr = 0; + + while (argc > 1) { + if (matches(argv[1], "-Version") == 0) { + printf("brmon %s\n", SNAPSHOT); + exit(0); + } else if (matches(argv[1], "link") == 0) { + llink=1; + groups = 0; + } else if (matches(argv[1], "bridge") == 0) { + laddr=1; + groups = 0; + } else if (strcmp(argv[1], "all") == 0) { + groups = ~RTMGRP_TC; + } else if (matches(argv[1], "help") == 0) { + usage(); + } else { + fprintf(stderr, "Argument \"%s\" is unknown, try \"rtmon help\".\n", argv[1]); + exit(-1); + } + argc--; argv++; + } + + if (llink) + groups |= RTMGRP_LINK; + + if (rtnl_open(&rth, groups) < 0) + exit(1); + + if (rtnl_wilddump_request(&rth, PF_BRIDGE, RTM_GETLINK) < 0) { + perror("Cannot send dump request"); + exit(1); + } + + if (rtnl_dump_filter(&rth, dump_msg, stdout, NULL, NULL) < 0) { + fprintf(stderr, "Dump terminated\n"); + return 1; + } + + if (rtnl_listen(&rth, dump_msg, stdout) < 0) + exit(2); + + exit(0); +} +#endif + +#include "bridge_ctl.h" +#include "epoll_loop.h" + +struct rtnl_handle rth; +struct epoll_event_handler br_handler; + +struct rtnl_handle rth_state; + +void br_ev_handler(uint32_t events, struct epoll_event_handler *h) +{ + if (rtnl_listen(&rth, dump_msg, stdout) < 0) { + fprintf(stderr, "Error on bridge monitoring socket\n"); + exit(-1); + } +} + +int init_bridge_ops(void) +{ + if (rtnl_open(&rth, ~RTMGRP_TC) < 0) { + fprintf(stderr, "Couldn't open rtnl socket for monitoring\n"); + return -1; + } + + if (rtnl_open(&rth_state, 0) < 0) { + fprintf(stderr, "Couldn't open rtnl socket for setting state\n"); + return -1; + } + + if (rtnl_wilddump_request(&rth, PF_BRIDGE, RTM_GETLINK) < 0) { + fprintf(stderr, "Cannot send dump request: %m\n"); + return -1; + } + + if (rtnl_dump_filter(&rth, dump_msg, stdout, NULL, NULL) < 0) { + fprintf(stderr, "Dump terminated\n"); + return -1; + } + + if (fcntl(rth.fd, F_SETFL, O_NONBLOCK) < 0) { + fprintf(stderr, "Error setting O_NONBLOCK: %m\n"); + return -1; + } + + br_handler.fd = rth.fd; + br_handler.arg = NULL; + br_handler.handler = br_ev_handler; + + if (add_epoll(&br_handler) < 0) + return -1; + + return 0; +} + +/* Send message. Response is through bridge_notify */ +void bridge_get_configuration(void) +{ + if (rtnl_wilddump_request(&rth, PF_BRIDGE, RTM_GETLINK) < 0) { + fprintf(stderr, "Cannot send dump request: %m\n"); + } +} diff --git a/brstate.c b/brstate.c new file mode 100644 index 0000000..f0f9d36 --- /dev/null +++ b/brstate.c @@ -0,0 +1,160 @@ +/* + * brstate.c RTnetlink port state change + * + * This program 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 of the License, or (at your option) any later version. + * + * Authors: Stephen Hemminger + * + * Modified by Srinivas Aji for use + * in RSTP daemon. - 2006-09-01 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "libnetlink.h" + +#if 0 +static const char *port_states[] = { + [BR_STATE_DISABLED] = "disabled", + [BR_STATE_LISTENING] = "listening", + [BR_STATE_LEARNING] = "learning", + [BR_STATE_FORWARDING] = "forwarding", + [BR_STATE_BLOCKING] = "blocking", +}; + +static int portstate(const char *name) +{ + int i; + + for (i = 0; i < sizeof(port_states)/sizeof(port_states[0]); i++) { + if (strcasecmp(name, port_states[i]) == 0) + return i; + } + return -1; +} +#endif + +static int br_set_state(struct rtnl_handle *rth, unsigned ifindex, __u8 state) +{ + struct { + struct nlmsghdr n; + struct ifinfomsg ifi; + char buf[256]; + } req; + + memset(&req, 0, sizeof(req)); + + req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)); + req.n.nlmsg_flags = NLM_F_REQUEST|NLM_F_REPLACE; + req.n.nlmsg_type = RTM_SETLINK; + req.ifi.ifi_family = AF_BRIDGE; + req.ifi.ifi_index = ifindex; + + addattr32(&req.n, sizeof(req.buf), IFLA_PROTINFO, state); + + return rtnl_talk(rth, &req.n, 0, 0, NULL, NULL, NULL); +} + +static int br_send_bpdu(struct rtnl_handle *rth, unsigned ifindex, + const unsigned char *data, int len) +{ + struct { + struct nlmsghdr n; + struct ifinfomsg ifi; + char buf[256]; + } req; + + memset(&req, 0, sizeof(req)); + + req.n.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg)); + req.n.nlmsg_flags = NLM_F_REQUEST|NLM_F_REPLACE; + req.n.nlmsg_type = RTM_SETLINK; + req.ifi.ifi_family = AF_BRIDGE; + req.ifi.ifi_index = ifindex; + + addattr_l(&req.n, sizeof(req.buf), IFLA_PRIORITY, data, len); + + return rtnl_talk(rth, &req.n, 0, 0, NULL, NULL, NULL); +} + +#if 0 +int main(int argc, char **argv) +{ + unsigned int ifindex; + int err, brstate; + struct rtnl_handle rth; + + + if (argc != 3) { + fprintf(stderr, + "Usage: brstate ifname state\n"); + exit(-1); + } + + if (rtnl_open(&rth, 0) < 0) { + fprintf(stderr, "brstate: can't setup netlink\n"); + exit(1); + } + + ifindex = if_nametoindex(argv[1]); + if (ifindex == 0) { + fprintf(stderr, "brstate: unknown interface '%s'\n", argv[1]); + exit(1); + } + + brstate = portstate(argv[2]); + if (brstate < 0) { + fprintf(stderr, "brstate: unknown port state '%s'\n", + argv[2]); + exit(1); + } + + err = br_set_state(&rth, ifindex, brstate); + if (err) { + fprintf(stderr, "brstate: set %d, %d failed %d\n", + ifindex, brstate, err); + exit(1); + } + + rtnl_close(&rth); + return 0; +} +#endif + +#include "bridge_ctl.h" + +extern struct rtnl_handle rth_state; + +int bridge_set_state(int ifindex, int brstate) +{ + int err = br_set_state(&rth_state, ifindex, brstate); + if (err < 0) { + fprintf(stderr, "Couldn't set bridge state, ifindex %d, state %d\n", + ifindex, brstate); + return -1; + } + return 0; +} + +int bridge_send_bpdu(int ifindex, const unsigned char *data, int len) +{ + int err = br_send_bpdu(&rth_state, ifindex, data, len); + if (err < 0) { + fprintf(stderr, "Couldn't send bpdu, ifindex %d\n", ifindex); + return -1; + } + return 0; +} diff --git a/ctl_cli_wrap.c b/ctl_cli_wrap.c new file mode 100644 index 0000000..7b17964 --- /dev/null +++ b/ctl_cli_wrap.c @@ -0,0 +1,67 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#include "ctl_functions.h" +#include "ctl_socket.h" +#include "ctl_socket_client.h" +#include "log.h" + +CLIENT_SIDE_FUNCTION(enable_bridge_rstp) +CLIENT_SIDE_FUNCTION(get_bridge_state) +CLIENT_SIDE_FUNCTION(set_bridge_config) +CLIENT_SIDE_FUNCTION(get_port_state) +CLIENT_SIDE_FUNCTION(set_port_config) +CLIENT_SIDE_FUNCTION(set_debug_level) + +#include + +const char *CTL_error_explanation (int err_no) +{ +#define CHOOSE(a) #a + static const char* rstp_error_names[] = RSTP_ERRORS; + static const char *ctl_error_names[] = { CTL_ERRORS }; + +#undef CHOOSE + if (err_no < 0) + return "Error doing ctl command"; + else if (err_no >= STP_OK && err_no < STP_LAST_DUMMY) + return rstp_error_names[err_no]; + else if (err_no > Err_Dummy_Start && err_no < Err_Dummy_End) + return ctl_error_names[err_no - Err_Dummy_Start - 1]; + + static char buf[32]; + sprintf(buf, "Unknown error code %d", err_no); + return buf; +} + +void Dprintf(int level, const char* fmt, ...) +{ + char logbuf[256]; + logbuf[sizeof(logbuf) - 1] = 0; + va_list ap; + va_start(ap, fmt); + vsnprintf(logbuf, sizeof(logbuf) - 1, fmt, ap); + va_end(ap); + printf("%s\n", logbuf); +} diff --git a/ctl_functions.h b/ctl_functions.h new file mode 100644 index 0000000..cf15fe9 --- /dev/null +++ b/ctl_functions.h @@ -0,0 +1,65 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#ifndef CTL_FUNCTIONS_H +#define CTL_FUNCTIONS_H + +#include +#include + +int CTL_enable_bridge_rstp(int br_index, int enable); + +int CTL_get_bridge_state(int br_index, + UID_STP_CFG_T *cfg, UID_STP_STATE_T *state); + +int CTL_set_bridge_config(int br_index, + UID_STP_CFG_T *cfg); + +int CTL_get_port_state(int br_index, int port_index, + UID_STP_PORT_CFG_T *cfg, UID_STP_PORT_STATE_T *state); + +int CTL_set_port_config(int br_index, int port_index, + UID_STP_PORT_CFG_T *cfg); + +int CTL_set_debug_level(int level); + +#define CTL_ERRORS \ + CHOOSE(Err_Interface_not_a_bridge), \ + CHOOSE(Err_Bridge_RSTP_not_enabled), \ + CHOOSE(Err_Bridge_is_down), \ + CHOOSE(Err_Port_does_not_belong_to_bridge), \ + +#define CHOOSE(a) a + +enum Errors { + Err_Dummy_Start = 1000, + CTL_ERRORS + Err_Dummy_End +}; + +#undef CHOOSE + +const char *CTL_error_explanation(int err); + +#endif diff --git a/ctl_main.c b/ctl_main.c new file mode 100644 index 0000000..6e2b840 --- /dev/null +++ b/ctl_main.c @@ -0,0 +1,783 @@ +/* + Command parsing taken from brctl utility. + Display code from stp_cli.c in rstplib. + */ + +#include +#include +#include +#include +#include + +#include + +/* For scanning through sysfs directories */ +#include +#include +#include +#include + +#include "ctl_socket_client.h" +#include "ctl_functions.h" + +#ifndef False +# define False 0 +# define True 1 +#endif + +#define STP_IN_get_error_explanation CTL_error_explanation + +static void +print_bridge_id (UID_BRIDGE_ID_T *bridge_id, unsigned char cr) +{ + printf("%04lX-%02x%02x%02x%02x%02x%02x", + (unsigned long) bridge_id->prio, + (unsigned char) bridge_id->addr[0], + (unsigned char) bridge_id->addr[1], + (unsigned char) bridge_id->addr[2], + (unsigned char) bridge_id->addr[3], + (unsigned char) bridge_id->addr[4], + (unsigned char) bridge_id->addr[5]); + if (cr) + printf("\n"); +} + +static char * +stp_state2str (RSTP_PORT_STATE stp_port_state, int detail) +{ + if (detail) { + switch (stp_port_state) { + case UID_PORT_DISABLED: return "Disabled"; + case UID_PORT_DISCARDING: return "Discarding"; + case UID_PORT_LEARNING: return "Learning"; + case UID_PORT_FORWARDING: return "Forwarding"; + case UID_PORT_NON_STP: return "NoStp"; + default: return "Unknown"; + } + } + + switch (stp_port_state) { + case UID_PORT_DISABLED: return "Dis"; + case UID_PORT_DISCARDING: return "Blk"; + case UID_PORT_LEARNING: return "Lrn"; + case UID_PORT_FORWARDING: return "Fwd"; + case UID_PORT_NON_STP: return "Non"; + default: return "Unk"; + } +} + +static void CLI_out_port_id (int port, unsigned char cr) +{ + static char ifname[IFNAMSIZ]; + if (if_indextoname(port, ifname)) + printf("%s", ifname); + else + printf ("Ifindex %02d", port); + if (cr) + printf("\n"); +} + +int get_index_die(const char *ifname, const char *doc, int die) +{ + int r = if_nametoindex(ifname); + if (r == 0) { + fprintf(stderr, "Can't find index for %s %s. Not a valid interface.\n", + doc, ifname); + if (die) + exit(1); + return -1; + } + return r; +} + +int get_index(const char *ifname, const char *doc) +{ + return get_index_die(ifname, doc, 1); +} + +static int cmd_rstp(int argc, char *const* argv) +{ + int stp, r; + int br_index = get_index(argv[1], "bridge"); + + if (!strcmp(argv[2], "on") || !strcmp(argv[2], "yes") + || !strcmp(argv[2], "1")) + stp = 1; + else if (!strcmp(argv[2], "off") || !strcmp(argv[2], "no") + || !strcmp(argv[2], "0")) + stp = 0; + else { + fprintf(stderr, "expect on/off for argument\n"); + return 1; + } + r = CTL_enable_bridge_rstp(br_index, stp); + if (r) { + fprintf(stderr, "Failed to enable/disable RSTP: %s\n", + CTL_error_explanation(r)); + return -1; + } + return 0; +} + +static int do_showbridge(const char *br_name) +{ + UID_STP_STATE_T uid_state; + UID_STP_CFG_T uid_cfg; + + int br_index = get_index_die(br_name, "bridge", 0); + if (br_index < 0) + return -1; + + int r = CTL_get_bridge_state(br_index, &uid_cfg, &uid_state); + if (r) { + fprintf(stderr, "Failed to get bridge state: %s\n", + CTL_error_explanation(r)); + return -1; + } + +#if 0 + printf("Interface: %-7s (tag:%d) State: ", + uid_state.vlan_name, (int) uid_state.vlan_id); +#else + printf("Bridge: %-7s State:", + uid_state.vlan_name); +#endif + switch (uid_state.stp_enabled) { + case STP_ENABLED: printf("enabled\n"); break; + case STP_DISABLED: printf("disabled\n");break; + default: printf("unknown\n"); return 0; + } + + printf("BridgeId: "); print_bridge_id (&uid_state.bridge_id, 0); + printf(" Bridge Proirity: %lu (0x%lX)\n", + (unsigned long) uid_state.bridge_id.prio, (unsigned long) uid_state.bridge_id.prio); + if (uid_cfg.force_version < 2) + printf("Force Version: stp\n"); + + printf("Designated Root: "); print_bridge_id (&uid_state.designated_root, 1); + if (uid_state.root_port) { + printf("Root Port: %04lx", (unsigned long) uid_state.root_port); + // CLI_out_port_id (uid_state.root_port & 0xfff, False); + // printf("not implemented"); // XXX + printf(", Root Cost: %-lu\n", (unsigned long) uid_state.root_path_cost); + } else { + printf("Root Port: none\n"); + } + + if (uid_state.Topo_Change) + printf ("Topology Change Count: %lu\n", uid_state.Topo_Change_Count); + else + printf ("Time Since Topology Change: %lu\n", uid_state.timeSince_Topo_Change); + + printf ("Max Age: %2d Bridge Max Age: %-2d\n", + (int) uid_state.max_age, (int) uid_cfg.max_age); + printf ("Hello Time: %2d Bridge Hello Time: %-2d\n", + (int) uid_state.hello_time, (int) uid_cfg.hello_time); + printf ("Forward Delay: %2d Bridge Forward Delay: %-2d\n", + (int) uid_state.forward_delay, (int) uid_cfg.forward_delay); + printf ("Hold Time: %2d\n", (int) uid_cfg.hold_time); + + return 0; +} + +#define SYSFS_PATH_MAX 256 +#define SYSFS_CLASS_NET "/sys/class/net" + +static int isbridge(const struct dirent *entry) +{ + char path[SYSFS_PATH_MAX]; + struct stat st; + + snprintf(path, SYSFS_PATH_MAX, SYSFS_CLASS_NET "/%s/bridge", + entry->d_name); + return stat(path, &st) == 0 && S_ISDIR(st.st_mode); +} + +static int cmd_showbridge(int argc, char *const* argv) +{ + int i, count = 0; + int r = 0; + struct dirent **namelist; + + if (argc > 1) { + count = argc - 1; + } + else { + count = scandir(SYSFS_CLASS_NET, &namelist, isbridge, alphasort); + if (count < 0) { + fprintf(stderr, "Error getting list of all bridges\n"); + return -1; + } + } + + for (i = 0; i < count; i++) { + const char *name; + if (argc > 1) + name = argv[i+1]; + else + name = namelist[i]->d_name; + + int err = do_showbridge(name); + if (err) + r = err; + } + + if (argc <= 1) { + for (i = 0; i < count; i++) + free(namelist[i]); + free(namelist); + } + + return r; +} + +int detail = 0; + +static int do_showport(int br_index, const char *port_name, + UID_STP_STATE_T *uid_state) +{ + UID_STP_PORT_STATE_T uid_port; + UID_STP_PORT_CFG_T uid_cfg; + int r = 0; + int port_index = get_index_die(port_name, "port", 0); + if (port_index < 0) + return -1; + + memset (&uid_cfg, 0, sizeof (UID_STP_PORT_CFG_T)); + r = CTL_get_port_state(br_index, port_index, &uid_cfg, &uid_port); + if (r) { + fprintf(stderr, "Failed to get port state for port %d: %s\n", + port_index, CTL_error_explanation(r)); + return -1; + } + + if (detail) { + printf("Stp Port "); CLI_out_port_id (port_index, False); +#if 0 + printf(": PortId: %04lx in vlan '%s' with tag %d:\n", + (unsigned long) uid_port.port_id, uid_state->vlan_name, (int) uid_state->vlan_id); +#else + printf(": PortId: %04lx in Bridge '%s':\n", + (unsigned long) uid_port.port_id, uid_state->vlan_name); +#endif + printf ("Priority: %-d\n", (int) (uid_port.port_id >> 8)); + printf ("State: %-16s", stp_state2str (uid_port.state, 1)); + printf (" Uptime: %-9lu\n", uid_port.uptime); + printf ("PortPathCost: admin: "); + if (ADMIN_PORT_PATH_COST_AUTO == uid_cfg.admin_port_path_cost) + printf ("%-9s", "Auto"); + else + printf ("%-9lu", uid_cfg.admin_port_path_cost); + printf (" oper: %-9lu\n", uid_port.oper_port_path_cost); + + printf ("Point2Point: admin: "); + switch (uid_cfg.admin_point2point) { + case P2P_FORCE_TRUE: + printf ("%-9s", "ForceYes"); + break; + case P2P_FORCE_FALSE: + printf ("%-9s", "ForceNo"); + break; + case P2P_AUTO: + printf ("%-9s", "Auto"); + break; + } + printf (" oper: %-9s\n", uid_port.oper_point2point ? "Yes" : "No"); + printf ("Edge: admin: %-9s oper: %-9s\n", + uid_cfg.admin_edge ? "Y" : "N", + uid_port.oper_edge ? "Y" : "N"); + printf ("Partner: oper: %-9s\n", + uid_port.oper_stp_neigb ? "Slow" : "Rapid"); + + if (' ' != uid_port.role) { + if ('-' != uid_port.role) { + printf("PathCost: %-lu\n", (unsigned long) (uid_port.path_cost)); + printf("Designated Root: "); print_bridge_id (&uid_port.designated_root, 1); + printf("Designated Cost: %-ld\n", (unsigned long) uid_port.designated_cost); + printf("Designated Bridge: "); print_bridge_id (&uid_port.designated_bridge, 1); + printf("Designated Port: %-4lx\n\r", (unsigned long) uid_port.designated_port); + } + printf("Role: "); + switch (uid_port.role) { + case 'A': printf("Alternate\n"); break; + case 'B': printf("Backup\n"); break; + case 'R': printf("Root\n"); break; + case 'D': printf("Designated\n"); break; + case '-': printf("NonStp\n"); break; + default: printf("Unknown(%c)\n", uid_port.role); break; + } + + if ('R' == uid_port.role || 'D' == uid_port.role) { + /* printf("Tc: %c ", uid_port.tc ? 'Y' : 'n'); */ + printf("TcAck: %c ", + uid_port.top_change_ack ? 'Y' : 'N'); + printf("TcWhile: %3d\n", (int) uid_port.tcWhile); + } + } + + if (UID_PORT_DISABLED == uid_port.state || '-' == uid_port.role) { +#if 0 + printf("helloWhen: %3d ", (int) uid_port.helloWhen); + printf("lnkWhile: %3d\n", (int) uid_port.lnkWhile); + printf("fdWhile: %3d\n", (int) uid_port.fdWhile); +#endif + } else if ('-' != uid_port.role) { + printf("fdWhile: %3d ", (int) uid_port.fdWhile); + printf("rcvdInfoWhile: %3d\n", (int) uid_port.rcvdInfoWhile); + printf("rbWhile: %3d ", (int) uid_port.rbWhile); + printf("rrWhile: %3d\n", (int) uid_port.rrWhile); +#if 0 + printf("mdelayWhile: %3d ", (int) uid_port.mdelayWhile); + printf("lnkWhile: %3d\n", (int) uid_port.lnkWhile); + printf("helloWhen: %3d ", (int) uid_port.helloWhen); + printf("txCount: %3d\n", (int) uid_port.txCount); +#endif + } + + printf("RSTP BPDU rx: %lu\n", (unsigned long) uid_port.rx_rstp_bpdu_cnt); + printf("CONFIG BPDU rx: %lu\n", (unsigned long) uid_port.rx_cfg_bpdu_cnt); + printf("TCN BPDU rx: %lu\n", (unsigned long) uid_port.rx_tcn_bpdu_cnt); + } else { + printf("%c%c%c ", + (uid_port.oper_point2point) ? ' ' : '*', + (uid_port.oper_edge) ? 'E' : ' ', + (uid_port.oper_stp_neigb) ? 's' : ' '); + CLI_out_port_id (port_index, False); + printf(" %04lx %3s ", (unsigned long) uid_port.port_id, + stp_state2str (uid_port.state, 0)); + printf (" "); + print_bridge_id (&uid_port.designated_root, 0); + printf(" "); + print_bridge_id (&uid_port.designated_bridge, 0); + printf(" %4lx %c", (unsigned long) uid_port.designated_port, uid_port.role); + printf ("\n"); + } + return 0; +} + +static int not_dot_dotdot(const struct dirent *entry) +{ + char *n = entry->d_name; + return + !(n[0] == '.' && (n[1] == 0 || (n[1] == '.' && n[2] == 0))); +} + +static int cmd_showport(int argc, char *const* argv) +{ + UID_STP_STATE_T uid_state; + UID_STP_CFG_T uid_br_cfg; + int r = 0; + + int br_index = get_index(argv[1], "bridge"); + + r = CTL_get_bridge_state(br_index, &uid_br_cfg, &uid_state); + if (r) { + fprintf(stderr, "Failed to get bridge state: %s\n", + CTL_error_explanation(r)); + return -1; + } + + int i, count = 0; + struct dirent **namelist; + + if (argc > 2) { + count = argc - 2; + } + else { + char buf[SYSFS_PATH_MAX]; + snprintf(buf, sizeof(buf), SYSFS_CLASS_NET "/%s/brif", argv[1]); + count = scandir(buf, &namelist, not_dot_dotdot, alphasort); + if (count < 0) { + fprintf(stderr, "Error getting list of all ports of bridge %s\n", + argv[1]); + return -1; + } + } + + for (i = 0; i < count; i++) { + const char *name; + if (argc > 2) + name = argv[i+2]; + else + name = namelist[i]->d_name; + + int err = do_showport(br_index, name, &uid_state); + if (err) + r = err; + } + + if (argc <= 2) { + for (i = 0; i < count; i++) + free(namelist[i]); + free(namelist); + } + + return r; +} + +static int cmd_showportdetail(int argc, char *const* argv) +{ + detail = 1; + return cmd_showport(argc, argv); +} + +unsigned int getuint(const char *s) +{ + char *end; + long l; + l = strtoul(s, &end, 0); + if (*s == 0 || *end != 0 || l > INT_MAX) { + fprintf(stderr, "Invalid unsigned int arg %s\n", s); + exit(1); + } + return l; +} + +int getenum(const char *s, const char *opt[]) +{ + int i; + for (i = 0; opt[i] != NULL; i++) + if (strcmp(s, opt[i]) == 0) + return i; + + fprintf(stderr, "Invalid argument %s: expecting one of ", s); + for (i = 0; opt[i] != NULL; i++) + fprintf(stderr, "%s%s", opt[i], (opt[i+1]?", ":"\n")); + + exit(1); +} + +int getyesno(const char *s, const char *yes, const char *no) +{ + /* Reverse yes and no so error message looks more normal */ + const char *opt[] = { yes, no, NULL }; + return 1 - getenum(s, opt); +} + +static int set_bridge_cfg_value (int br_index, unsigned long value, + unsigned long val_mask) +{ + UID_STP_CFG_T uid_cfg; + char* val_name; + int rc; + + uid_cfg.field_mask = val_mask; + switch (val_mask) { + case BR_CFG_STATE: + uid_cfg.stp_enabled = value; + val_name = "state"; + break; + case BR_CFG_PRIO: + uid_cfg.bridge_priority = value; + val_name = "priority"; + break; + case BR_CFG_AGE: + uid_cfg.max_age = value; + val_name = "max_age"; + break; + case BR_CFG_HELLO: + uid_cfg.hello_time = value; + val_name = "hello_time"; + break; + case BR_CFG_DELAY: + uid_cfg.forward_delay = value; + val_name = "forward_delay"; + break; + case BR_CFG_FORCE_VER: + uid_cfg.force_version = value; + val_name = "force_version"; + break; + case BR_CFG_AGE_MODE: + case BR_CFG_AGE_TIME: + default: printf ("Invalid value mask 0X%lx\n", val_mask); return -1; + break; + } + + rc = CTL_set_bridge_config(br_index, &uid_cfg); + + if (0 != rc) { + printf ("Can't change rstp bridge %s:%s\n", val_name, STP_IN_get_error_explanation (rc)); + return -1; + } + return 0; +} + +static int cmd_setbridgestate(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + return set_bridge_cfg_value(br_index, + getyesno(argv[2], "on", "off"), + BR_CFG_STATE); +} + +static int cmd_setbridgeprio(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + return set_bridge_cfg_value(br_index, getuint(argv[2]), BR_CFG_PRIO); +} + +static int cmd_setbridgemaxage(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + return set_bridge_cfg_value(br_index, getuint(argv[2]), BR_CFG_AGE); +} + +static int cmd_setbridgehello(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + return set_bridge_cfg_value(br_index, getuint(argv[2]), BR_CFG_HELLO); +} + +static int cmd_setbridgefdelay(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + return set_bridge_cfg_value(br_index, getuint(argv[2]), BR_CFG_DELAY); +} + +static int cmd_setbridgeforcevers(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + return set_bridge_cfg_value(br_index, + 2 * getyesno(argv[2], "normal", "slow"), + BR_CFG_FORCE_VER); +} + + +static int +set_port_cfg_value (int br_index, int port_index, + unsigned long value, + unsigned long val_mask) +{ + UID_STP_PORT_CFG_T uid_cfg; + int rc; + char *val_name; + + BitmapClear(&uid_cfg.port_bmp); + uid_cfg.field_mask = val_mask; + switch (val_mask) { + case PT_CFG_MCHECK: + val_name = "mcheck"; + break; + case PT_CFG_COST: + uid_cfg.admin_port_path_cost = value; + val_name = "path cost"; + break; + case PT_CFG_PRIO: + uid_cfg.port_priority = value; + val_name = "priority"; + break; + case PT_CFG_P2P: + uid_cfg.admin_point2point = (ADMIN_P2P_T) value; + val_name = "p2p flag"; + break; + case PT_CFG_EDGE: + uid_cfg.admin_edge = value; + val_name = "adminEdge"; + break; + case PT_CFG_NON_STP: + uid_cfg.admin_non_stp = value; + val_name = "adminNonStp"; + break; +#ifdef STP_DBG + case PT_CFG_DBG_SKIP_TX: + uid_cfg.skip_tx = value; + val_name = "skip tx"; + break; + case PT_CFG_DBG_SKIP_RX: + uid_cfg.skip_rx = value; + val_name = "skip rx"; + break; +#endif + case PT_CFG_STATE: + default: + printf ("Invalid value mask 0X%lx\n", val_mask); + return -1; + } + + rc = CTL_set_port_config(br_index, port_index, &uid_cfg); + + if (0 != rc) { + printf ("can't change rstp port[s] %s: %s\n", + val_name, STP_IN_get_error_explanation (rc)); + return -1; + } + return 0; +} + +static int cmd_setportprio(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + int port_index = get_index(argv[2], "port"); + return set_port_cfg_value(br_index, port_index, + getuint(argv[3]), PT_CFG_PRIO); +} + +static int cmd_setportpathcost(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + int port_index = get_index(argv[2], "port"); + return set_port_cfg_value(br_index, port_index, + getuint(argv[3]), PT_CFG_COST); +} + +static int cmd_setportedge(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + int port_index = get_index(argv[2], "port"); + return set_port_cfg_value(br_index, port_index, + getyesno(argv[3], "yes", "no"), PT_CFG_EDGE); +} + +static int cmd_setportnonstp(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + int port_index = get_index(argv[2], "port"); + return set_port_cfg_value(br_index, port_index, + getyesno(argv[3], "yes", "no"), PT_CFG_NON_STP); +} + +static int cmd_setportp2p(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + int port_index = get_index(argv[2], "port"); + const char *opts[] = {"yes", "no", "auto", NULL }; + int vals[] = { P2P_FORCE_TRUE, P2P_FORCE_FALSE, P2P_AUTO }; + + return set_port_cfg_value(br_index, port_index, + vals[getenum(argv[3], opts)], PT_CFG_P2P); +} + +static int cmd_portmcheck(int argc, char *const* argv) +{ + + int br_index = get_index(argv[1], "bridge"); + int port_index = get_index(argv[2], "port"); + return set_port_cfg_value(br_index, port_index, 0, PT_CFG_MCHECK); +} + +static int cmd_debuglevel(int argc, char *const* argv) +{ + return CTL_set_debug_level(getuint(argv[1])); +} + +struct command +{ + int nargs; + int optargs; + const char *name; + int (*func)(int argc, char *const* argv); + const char *help; +}; + +static const struct command commands[] = { + { 0, 32, "showbridge", cmd_showbridge, "[ ... ]\t\tshow bridge state" }, + { 1, 32, "showport", cmd_showport, " [ ... ]\tshow port state" }, + { 1, 32, "showportdetail", cmd_showportdetail, " [ ... ]\tshow port state (detail)" }, + { 2, 0, "rstp", cmd_rstp, " {on|off}\tenable/disable rstpd control" }, + { 2, 0, "setbridgestate", cmd_setbridgestate, " {on|off}\tstart/stop rstp (when enabled)" }, + { 2, 0, "setbridgeprio", cmd_setbridgeprio, " \tset bridge priority (0-61440)" }, + { 2, 0, "sethello", cmd_setbridgehello, " \tset bridge hello time (1-10)" }, + { 2, 0, "setmaxage", cmd_setbridgemaxage, " \tset bridge max age (6-40)" }, + { 2, 0, "setfdelay", cmd_setbridgefdelay, " \tset bridge forward delay (4-30)" }, + { 2, 0, "setforcevers", cmd_setbridgeforcevers, " {normal|slow}\tnormal RSTP or force to STP" }, + { 3, 0, "setportprio", cmd_setportprio, " \tset port priority (0-240)" }, + { 3, 0, "setportpathcost", cmd_setportpathcost, " \tset port path cost" }, + { 3, 0, "setportedge", cmd_setportedge, " {yes|no}\tconfigure if it is an edge port" }, + { 3, 0, "setportnonstp", cmd_setportnonstp, " {yes|no}\tdisable STP for the port" }, + { 3, 0, "setportp2p", cmd_setportp2p, " {yes|no|auto}\tset whether p2p connection" }, + { 2, 0, "portmcheck", cmd_portmcheck, " \ttry to get back from STP to RSTP mode" }, + { 1, 0, "debuglevel", cmd_debuglevel, "\t\tLevel of verbosity" }, +}; + +const struct command *command_lookup(const char *cmd) +{ + int i; + + for (i = 0; i < sizeof(commands)/sizeof(commands[0]); i++) { + if (!strcmp(cmd, commands[i].name)) + return &commands[i]; + } + + return NULL; +} + +void command_helpall(void) +{ + int i; + + for (i = 0; i < sizeof(commands)/sizeof(commands[0]); i++) { + printf("\t%-10s\t%s\n", commands[i].name, commands[i].help); + } +} + +static void help() +{ + printf("Usage: rstpctl [commands]\n"); + printf("commands:\n"); + command_helpall(); +} + +#define PACKAGE_VERSION2(v, b) "rstp, " #v "-" #b +#define PACKAGE_VERSION(v, b) PACKAGE_VERSION2(v, b) + +int main(int argc, char *const* argv) +{ + const struct command *cmd; + int f; + static const struct option options[] = { + { .name = "help", .val = 'h' }, + { .name = "version", .val = 'V' }, + { 0 } + }; + + while ((f = getopt_long(argc, argv, "Vh", options, NULL)) != EOF) + switch(f) { + case 'h': + help(); + return 0; + case 'V': + printf("%s\n", PACKAGE_VERSION(VERSION, BUILD)); + return 0; + default: + fprintf(stderr, "Unknown option '%c'\n", f); + goto help; + } + + if (argc == optind) + goto help; + + if (ctl_client_init()) { + fprintf(stderr, "can't setup control connection\n"); + return 1; + } + + argc -= optind; + argv += optind; + if ((cmd = command_lookup(argv[0])) == NULL) { + fprintf(stderr, "never heard of command [%s]\n", argv[0]); + goto help; + } + + if (argc < cmd->nargs + 1 || argc > cmd->nargs + cmd->optargs + 1) { + printf("Incorrect number of arguments for command\n"); + printf("Usage: rstpctl %s %s\n", cmd->name, cmd->help); + return 1; + } + + return cmd->func(argc, argv); + +help: + help(); + return 1; +} diff --git a/ctl_socket.c b/ctl_socket.c new file mode 100644 index 0000000..c41728a --- /dev/null +++ b/ctl_socket.c @@ -0,0 +1,145 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#include "ctl_socket.h" +#include "ctl_socket_server.h" +#include +#include +#include +#include +#include +#include +#include + +#include "epoll_loop.h" +#include "log.h" + + +int server_socket(void) +{ + struct sockaddr_un sa; + int s; + + TST (strlen(RSTP_SERVER_SOCK_NAME) < sizeof(sa.sun_path), -1); + + s = socket(PF_UNIX, SOCK_DGRAM, 0); + if (s < 0) { + ERROR("Couldn't open unix socket: %m"); + return -1; + } + + set_socket_address(&sa, RSTP_SERVER_SOCK_NAME); + + if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) != 0) { + ERROR("Couldn't bind socket: %m"); + close(s); + return -1; + } + + return s; +} + + +int handle_message(int cmd, void *inbuf, int lin, void *outbuf, int *lout) +{ + switch (cmd) { + SERVER_MESSAGE_CASE(enable_bridge_rstp); + SERVER_MESSAGE_CASE(get_bridge_state); + SERVER_MESSAGE_CASE(set_bridge_config); + SERVER_MESSAGE_CASE(get_port_state); + SERVER_MESSAGE_CASE(set_port_config); + SERVER_MESSAGE_CASE(set_debug_level); + + default: + ERROR("CTL: Unknown command %d", cmd); + return -1; + } +} + +#define msg_buf_len 1024 +unsigned char msg_inbuf[1024]; +unsigned char msg_outbuf[1024]; + +void ctl_rcv_handler(uint32_t events, struct epoll_event_handler *p) +{ + struct ctl_msg_hdr mhdr; + struct msghdr msg; + struct sockaddr_un sa; + struct iovec iov[2]; + int l; + + msg.msg_name = &sa; msg.msg_namelen = sizeof(sa); + msg.msg_iov = iov; msg.msg_iovlen = 2; + msg.msg_control = NULL; msg.msg_controllen = 0; + iov[0].iov_base = &mhdr; iov[0].iov_len = sizeof(mhdr); + iov[1].iov_base = msg_inbuf; iov[1].iov_len = msg_buf_len; + l = recvmsg(p->fd, &msg, MSG_NOSIGNAL | MSG_DONTWAIT); + TST(l > 0, ); + if (msg.msg_flags != 0 || l < sizeof(mhdr) || + l != sizeof(mhdr) + mhdr.lin || + mhdr.lout > msg_buf_len || mhdr.cmd < 0) { + ERROR("CTL: Unexpected message. Ignoring"); + return; + } + + + if (mhdr.lout) + mhdr.res = handle_message(mhdr.cmd, msg_inbuf, mhdr.lin, + msg_outbuf, &mhdr.lout); + else + mhdr.res = handle_message(mhdr.cmd, msg_inbuf, mhdr.lin, + NULL, NULL); + + if (mhdr.res < 0) + mhdr.lout = 0; + iov[1].iov_base = msg_outbuf; iov[1].iov_len = mhdr.lout; + l = sendmsg(p->fd, &msg, MSG_NOSIGNAL); + if (l < 0) + ERROR("CTL: Couldn't send response: %m"); + else if (l != sizeof(mhdr) + mhdr.lout) { + ERROR("CTL: Couldn't send full response, sent %d bytes instead of %zd.", + l, sizeof(mhdr) + mhdr.lout); + } +} + +struct epoll_event_handler ctl_handler; + +int ctl_socket_init(void) +{ + int s = server_socket(); + if (s < 0) + return -1; + + ctl_handler.fd = s; + ctl_handler.handler = ctl_rcv_handler; + + TST(add_epoll(&ctl_handler) == 0, -1); + return 0; +} + +void ctl_socket_cleanup(void) +{ + remove_epoll(&ctl_handler); + close(ctl_handler.fd); +} diff --git a/ctl_socket.h b/ctl_socket.h new file mode 100644 index 0000000..5e7d96f --- /dev/null +++ b/ctl_socket.h @@ -0,0 +1,167 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#ifndef CTL_SOCKET_H +#define CTL_SOCKET_H + +#include +#include + +#include "ctl_functions.h" + +struct ctl_msg_hdr +{ + int cmd; + int lin; + int lout; + int res; +}; + +#define set_socket_address(sa, string) \ + do {\ + (sa)->sun_family = AF_UNIX; \ + memset((sa)->sun_path, 0, sizeof((sa)->sun_path)); \ + strcpy((sa)->sun_path + 1, (string)); \ + } while (0) + +#define RSTP_SERVER_SOCK_NAME ".rstp_server" + +/* COMMANDS */ + +#if 0 +int CTL_enable_bridge_rstp(int br_index, int enable); +#endif +#define CMD_CODE_enable_bridge_rstp 101 +#define enable_bridge_rstp_ARGS (int br_index, int enable) +struct enable_bridge_rstp_IN { int br_index; int enable; }; +struct enable_bridge_rstp_OUT { }; +#define enable_bridge_rstp_COPY_IN \ + ({ in->br_index = br_index; in->enable = enable; }) +#define enable_bridge_rstp_COPY_OUT ({ (void)0; }) +#define enable_bridge_rstp_CALL (in->br_index, in->enable) + +#if 0 +int CTL_get_bridge_state(int br_index, + UID_STP_CFG_T *cfg, UID_STP_STATE_T *state); +#endif +#define CMD_CODE_get_bridge_state 102 +#define get_bridge_state_ARGS (int br_index, UID_STP_CFG_T *cfg, UID_STP_STATE_T *state) +struct get_bridge_state_IN { int br_index; }; +struct get_bridge_state_OUT { UID_STP_CFG_T cfg; UID_STP_STATE_T state; }; +#define get_bridge_state_COPY_IN \ + ({ in->br_index = br_index; }) +#define get_bridge_state_COPY_OUT ({ *cfg = out->cfg; *state = out->state; }) +#define get_bridge_state_CALL (in->br_index, &out->cfg, &out->state) + +#if 0 +int CTL_set_bridge_config(int br_index, + UID_STP_CFG_T *cfg); +#endif +#define CMD_CODE_set_bridge_config 103 +#define set_bridge_config_ARGS (int br_index, UID_STP_CFG_T *cfg) +struct set_bridge_config_IN { int br_index; UID_STP_CFG_T cfg; }; +struct set_bridge_config_OUT { }; +#define set_bridge_config_COPY_IN \ + ({ in->br_index = br_index; in->cfg = *cfg; }) +#define set_bridge_config_COPY_OUT ({ (void)0; }) +#define set_bridge_config_CALL (in->br_index, &in->cfg) + +#if 0 +int CTL_get_port_state(int br_index, int port_index, + UID_STP_PORT_CFG_T *cfg, UID_STP_PORT_STATE_T *state); +#endif +#define CMD_CODE_get_port_state 104 +#define get_port_state_ARGS (int br_index, int port_index, UID_STP_PORT_CFG_T *cfg, UID_STP_PORT_STATE_T *state) +struct get_port_state_IN { int br_index; int port_index; }; +struct get_port_state_OUT { UID_STP_PORT_CFG_T cfg; UID_STP_PORT_STATE_T state; }; +#define get_port_state_COPY_IN \ + ({ in->br_index = br_index; in->port_index = port_index; }) +#define get_port_state_COPY_OUT ({ *cfg = out->cfg; *state = out->state; }) +#define get_port_state_CALL (in->br_index, in->port_index, &out->cfg, &out->state) + +#if 0 +int CTL_set_port_config(int br_index, int port_index, + UID_STP_PORT_CFG_T *cfg); +#endif +#define CMD_CODE_set_port_config 105 +#define set_port_config_ARGS (int br_index, int port_index, UID_STP_PORT_CFG_T *cfg) +struct set_port_config_IN { int br_index; int port_index; UID_STP_PORT_CFG_T cfg; }; +struct set_port_config_OUT { }; +#define set_port_config_COPY_IN \ + ({ in->br_index = br_index; in->port_index = port_index; in->cfg = *cfg; }) +#define set_port_config_COPY_OUT ({ (void)0; }) +#define set_port_config_CALL (in->br_index, in->port_index, &in->cfg) + + +#if 0 +int CTL_set_debug_level(int level); +#endif +#define CMD_CODE_set_debug_level 106 +#define set_debug_level_ARGS (int level) +struct set_debug_level_IN { int level; }; +struct set_debug_level_OUT { }; +#define set_debug_level_COPY_IN \ + ({ in->level = level; }) +#define set_debug_level_COPY_OUT ({ (void)0; }) +#define set_debug_level_CALL (in->level) + +/* General case part in ctl command server switch */ +#define SERVER_MESSAGE_CASE(name) \ +case CMD_CODE_ ## name : do { \ + if (0) LOG("CTL command " #name); \ + struct name ## _IN in0, *in = &in0; \ + struct name ## _OUT out0, *out = &out0; \ + if (sizeof(*in) != lin || sizeof(*out) != (outbuf?*lout:0)) { \ + LOG("Bad sizes lin %d != %zd or lout %d != %zd", \ + lin, sizeof(*in), lout?*lout:0, sizeof(*out)); \ + return -1; \ + } \ + memcpy(in, inbuf, lin); \ + int r = CTL_ ## name name ## _CALL; \ + if (r) return r; \ + if (outbuf) memcpy(outbuf, out, *lout); \ + return r; \ +} while (0) + +/* Wraper for the control functions in the control command client */ +#define CLIENT_SIDE_FUNCTION(name) \ +int CTL_ ## name name ## _ARGS \ +{ \ + struct name ## _IN in0, *in=&in0; \ + struct name ## _OUT out0, *out = &out0; \ + int l = sizeof(*out); \ + name ## _COPY_IN; \ + int res = 0; \ + int r = send_ctl_message(CMD_CODE_ ## name, in, sizeof(*in), out, &l, \ + &res); \ + if (r || res) LOG("Got return code %d, %d", r, res); \ + if (r) return r; \ + if (res) return res; \ + name ## _COPY_OUT; \ + return r; \ +} + + + +#endif diff --git a/ctl_socket_client.c b/ctl_socket_client.c new file mode 100644 index 0000000..66be8d2 --- /dev/null +++ b/ctl_socket_client.c @@ -0,0 +1,150 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#include "ctl_socket.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#include "log.h" + +static int fd = -1; + +int ctl_client_init(void) +{ + struct sockaddr_un sa_svr; + int s; + TST (strlen(RSTP_SERVER_SOCK_NAME) < sizeof(sa_svr.sun_path), -1); + + s = socket(PF_UNIX, SOCK_DGRAM, 0); + if (s < 0) { + ERROR("Couldn't open unix socket: %m"); + return -1; + } + + set_socket_address(&sa_svr, RSTP_SERVER_SOCK_NAME); + + struct sockaddr_un sa; + char tmpname[64]; + sprintf(tmpname, "RSTPCTL_%d", getpid()); + set_socket_address(&sa, tmpname); + /* We need this bind. The autobind on connect isn't working properly. + The server doesn't get a proper sockaddr in recvmsg if we don't do this. + */ + if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) != 0) { + ERROR("Couldn't bind socket: %m"); + close(s); + return -1; + } + + if (connect(s, (struct sockaddr *)&sa_svr, sizeof(sa_svr)) != 0) { + ERROR("Couldn't connect to server"); + close(s); + return -1; + } + fd = s; + + return 0; +} + +void ctl_client_cleanup(void) +{ + if (fd >= 0) { + close(fd); + fd = -1; + } +} + +int send_ctl_message(int cmd, void *inbuf, int lin, void *outbuf, int *lout, + int *res) +{ + struct ctl_msg_hdr mhdr; + struct msghdr msg; + struct iovec iov[2]; + int l; + + msg.msg_name = NULL; msg.msg_namelen = 0; + msg.msg_iov = iov; msg.msg_iovlen = 2; + msg.msg_control = NULL; msg.msg_controllen = 0; + + mhdr.cmd = cmd; + mhdr.lin = lin; + mhdr.lout = lout != NULL ? *lout : 0; + iov[0].iov_base = &mhdr; iov[0].iov_len = sizeof(mhdr); + iov[1].iov_base = (void *)inbuf; iov[1].iov_len = lin; + + l = sendmsg(fd, &msg, 0); + if (l < 0) { + ERROR("Error sending message to server: %m"); + return -1; + } + if (l != sizeof(mhdr) + lin) { + ERROR("Error sending message to server: Partial write"); + return -1; + } + + iov[1].iov_base = outbuf; + iov[1].iov_len = lout != NULL ? *lout : 0; + + { + struct pollfd pfd; + int timeout = 5000; /* 5 s */ + int r; + + pfd.fd = fd; + pfd.events = POLLIN; + do { + r = poll(&pfd, 1, timeout); + if (r == 0) { + ERROR("Error getting message from server: Timeout"); + return -1; + } + if (r < 0) { + ERROR("Error getting message from server: poll error: %m"); + return -1; + } + } while ((pfd.revents & (POLLERR | POLLHUP | POLLNVAL | POLLIN)) == 0); + + l = recvmsg(fd, &msg, 0); + if (l < 0) { + ERROR("Error getting message from server: %m"); + return -1; + } + if (l < sizeof(mhdr) || l != sizeof(mhdr) + mhdr.lout || mhdr.cmd != cmd) { + ERROR("Error getting message from server: Bad format"); + return -1; + } + } + if (lout) + *lout = mhdr.lout; + if (res) + *res = mhdr.res; + + return 0; +} diff --git a/ctl_socket_client.h b/ctl_socket_client.h new file mode 100644 index 0000000..2bfc9ea --- /dev/null +++ b/ctl_socket_client.h @@ -0,0 +1,36 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#ifndef CTL_SOCKET_CLIENT_H +#define CTL_SOCKET_CLIENT_H + +int send_ctl_message(int cmd, void *inbuf, int lin, void *outbuf, int *lout, + int *res); + + +int ctl_client_init(void); + +void ctl_client_cleanup(void); + +#endif diff --git a/ctl_socket_server.h b/ctl_socket_server.h new file mode 100644 index 0000000..9b74172 --- /dev/null +++ b/ctl_socket_server.h @@ -0,0 +1,33 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#ifndef CTL_SOCKET_SERVER_H +#define CTL_SOCKET_SERVER_H + +int ctl_socket_init(void); +void ctl_socket_cleanup(void); + +#endif + + diff --git a/epoll_loop.c b/epoll_loop.c new file mode 100644 index 0000000..230dacc --- /dev/null +++ b/epoll_loop.c @@ -0,0 +1,141 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#include "epoll_loop.h" + +#include +#include +#include +#include +#include +#include + +#include "bridge_ctl.h" + +// globals +int epoll_fd = -1; +struct timeval nexttimeout; + +int init_epoll(void) +{ + int r = epoll_create(128); + if (r < 0) { + fprintf(stderr, "epoll_create failed: %m\n"); + return -1; + } + epoll_fd = r; + return 0; +} + +int add_epoll(struct epoll_event_handler *h) +{ + struct epoll_event ev = + { + .events = EPOLLIN, + .data.ptr = h, + }; + h->ref_ev = NULL; + int r = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, h->fd, &ev); + if (r < 0) { + fprintf(stderr, "epoll_ctl_add: %m\n"); + return -1; + } + return 0; +} + +int remove_epoll(struct epoll_event_handler *h) +{ + int r = epoll_ctl(epoll_fd, EPOLL_CTL_DEL, h->fd, NULL); + if (r < 0) { + fprintf(stderr, "epoll_ctl_del: %m\n"); + return -1; + } + if (h->ref_ev && h->ref_ev->data.ptr == h) { + h->ref_ev->data.ptr = NULL; + h->ref_ev = NULL; + } + return 0; +} + +void clear_epoll(void) +{ + if (epoll_fd >= 0) + close(epoll_fd); +} + +int time_diff(struct timeval *second, struct timeval *first) +{ + return (second->tv_sec - first->tv_sec)*1000 + + (second->tv_usec - first->tv_usec)/1000; +} + +void run_timeouts(void) +{ + bridge_one_second(); + nexttimeout.tv_sec++; +} + +int epoll_main_loop(void) +{ + gettimeofday(&nexttimeout, NULL); + nexttimeout.tv_sec++; +#define EV_SIZE 8 + struct epoll_event ev[EV_SIZE]; + + while (1) { + int r, i; + int timeout; + + struct timeval tv; + gettimeofday(&tv, NULL); + timeout = time_diff(&nexttimeout, &tv); + if (timeout < 0) { + run_timeouts(); + timeout = 0; + } + + r = epoll_wait(epoll_fd, ev, EV_SIZE, timeout); + if (r < 0 && errno != EINTR) { + fprintf(stderr, "epoll_wait: %m\n"); + return -1; + } + for (i = 0; i < r; i++) { + struct epoll_event_handler *p = ev[i].data.ptr; + if (p != NULL) + p->ref_ev = &ev[i]; + } + for (i = 0; i < r; i++) { + struct epoll_event_handler *p = ev[i].data.ptr; + if (p && p->handler) + p->handler(ev[i].events, p); + } + for (i = 0; i < r; i++) { + struct epoll_event_handler *p = ev[i].data.ptr; + if (p != NULL) + p->ref_ev = NULL; + } + } + + return 0; +} diff --git a/epoll_loop.h b/epoll_loop.h new file mode 100644 index 0000000..f9cfbee --- /dev/null +++ b/epoll_loop.h @@ -0,0 +1,52 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#ifndef EPOLL_LOOP_H +#define EPOLL_LOOP_H + +#include +#include +#include +#include + +struct epoll_event_handler +{ + int fd; + void *arg; + void (*handler)(uint32_t events, struct epoll_event_handler *p); + struct epoll_event *ref_ev; /* if set, epoll loop has reference to this, + so mark that ref as NULL while freeing */ +}; + +int init_epoll(void); + +void clear_epoll(void); + +int epoll_main_loop(void); + +int add_epoll(struct epoll_event_handler *h); + +int remove_epoll(struct epoll_event_handler *h); + +#endif diff --git a/include/libnetlink.h b/include/libnetlink.h new file mode 100644 index 0000000..63cc3c8 --- /dev/null +++ b/include/libnetlink.h @@ -0,0 +1,57 @@ +#ifndef __LIBNETLINK_H__ +#define __LIBNETLINK_H__ 1 + +#include +#include +#include + +struct rtnl_handle +{ + int fd; + struct sockaddr_nl local; + struct sockaddr_nl peer; + __u32 seq; + __u32 dump; +}; + +extern int rtnl_open(struct rtnl_handle *rth, unsigned subscriptions); +extern int rtnl_open_byproto(struct rtnl_handle *rth, unsigned subscriptions, int protocol); +extern void rtnl_close(struct rtnl_handle *rth); +extern int rtnl_wilddump_request(struct rtnl_handle *rth, int fam, int type); +extern int rtnl_dump_request(struct rtnl_handle *rth, int type, void *req, int len); + +typedef int (*rtnl_filter_t)(const struct sockaddr_nl *, + struct nlmsghdr *n, void *); +extern int rtnl_dump_filter(struct rtnl_handle *rth, rtnl_filter_t filter, + void *arg1, + rtnl_filter_t junk, + void *arg2); +extern int rtnl_talk(struct rtnl_handle *rtnl, struct nlmsghdr *n, pid_t peer, + unsigned groups, struct nlmsghdr *answer, + rtnl_filter_t junk, + void *jarg); +extern int rtnl_send(struct rtnl_handle *rth, const char *buf, int); + + +extern int addattr32(struct nlmsghdr *n, int maxlen, int type, __u32 data); +extern int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data, int alen); +extern int addraw_l(struct nlmsghdr *n, int maxlen, const void *data, int len); +extern int rta_addattr32(struct rtattr *rta, int maxlen, int type, __u32 data); +extern int rta_addattr_l(struct rtattr *rta, int maxlen, int type, const void *data, int alen); + +extern int parse_rtattr(struct rtattr *tb[], int max, struct rtattr *rta, int len); +extern int parse_rtattr_byindex(struct rtattr *tb[], int max, struct rtattr *rta, int len); + +#define parse_rtattr_nested(tb, max, rta) \ + (parse_rtattr((tb), (max), RTA_DATA(rta), RTA_PAYLOAD(rta))) + +extern int rtnl_listen(struct rtnl_handle *, rtnl_filter_t handler, + void *jarg); +extern int rtnl_from_file(FILE *, rtnl_filter_t handler, + void *jarg); + +#define NLMSG_TAIL(nmsg) \ + ((struct rtattr *) (((void *) (nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len))) + +#endif /* __LIBNETLINK_H__ */ + diff --git a/include/linux/llc.h b/include/linux/llc.h new file mode 100644 index 0000000..09f2e6d --- /dev/null +++ b/include/linux/llc.h @@ -0,0 +1,80 @@ +#ifndef __LINUX_LLC_H +#define __LINUX_LLC_H +/* + * IEEE 802.2 User Interface SAPs for Linux, data structures and indicators. + * + * Copyright (c) 2001 by Jay Schulist + * + * This program can be redistributed or modified under the terms of the + * GNU General Public License as published by the Free Software Foundation. + * This program is distributed without any warranty or implied warranty + * of merchantability or fitness for a particular purpose. + * + * See the GNU General Public License for more details. + */ +#define __LLC_SOCK_SIZE__ 16 /* sizeof(sockaddr_llc), word align. */ +struct sockaddr_llc { + sa_family_t sllc_family; /* AF_LLC */ + sa_family_t sllc_arphrd; /* ARPHRD_ETHER */ + unsigned char sllc_test; + unsigned char sllc_xid; + unsigned char sllc_ua; /* UA data, only for SOCK_STREAM. */ + unsigned char sllc_sap; + unsigned char sllc_mac[IFHWADDRLEN]; + unsigned char __pad[__LLC_SOCK_SIZE__ - sizeof(sa_family_t) * 2 - + sizeof(unsigned char) * 4 - IFHWADDRLEN]; +}; + +/* sockopt definitions. */ +enum llc_sockopts { + LLC_OPT_UNKNOWN = 0, + LLC_OPT_RETRY, /* max retrans attempts. */ + LLC_OPT_SIZE, /* max PDU size (octets). */ + LLC_OPT_ACK_TMR_EXP, /* ack expire time (secs). */ + LLC_OPT_P_TMR_EXP, /* pf cycle expire time (secs). */ + LLC_OPT_REJ_TMR_EXP, /* rej sent expire time (secs). */ + LLC_OPT_BUSY_TMR_EXP, /* busy state expire time (secs). */ + LLC_OPT_TX_WIN, /* tx window size. */ + LLC_OPT_RX_WIN, /* rx window size. */ + LLC_OPT_MAX +}; + +#define LLC_OPT_MAX_RETRY 100 +#define LLC_OPT_MAX_SIZE 4196 +#define LLC_OPT_MAX_WIN 127 +#define LLC_OPT_MAX_ACK_TMR_EXP 60 +#define LLC_OPT_MAX_P_TMR_EXP 60 +#define LLC_OPT_MAX_REJ_TMR_EXP 60 +#define LLC_OPT_MAX_BUSY_TMR_EXP 60 + +/* LLC SAP types. */ +#define LLC_SAP_NULL 0x00 /* NULL SAP. */ +#define LLC_SAP_LLC 0x02 /* LLC Sublayer Managment. */ +#define LLC_SAP_SNA 0x04 /* SNA Path Control. */ +#define LLC_SAP_PNM 0x0E /* Proway Network Managment. */ +#define LLC_SAP_IP 0x06 /* TCP/IP. */ +#define LLC_SAP_BSPAN 0x42 /* Bridge Spanning Tree Proto */ +#define LLC_SAP_MMS 0x4E /* Manufacturing Message Srv. */ +#define LLC_SAP_8208 0x7E /* ISO 8208 */ +#define LLC_SAP_3COM 0x80 /* 3COM. */ +#define LLC_SAP_PRO 0x8E /* Proway Active Station List */ +#define LLC_SAP_SNAP 0xAA /* SNAP. */ +#define LLC_SAP_BANYAN 0xBC /* Banyan. */ +#define LLC_SAP_IPX 0xE0 /* IPX/SPX. */ +#define LLC_SAP_NETBEUI 0xF0 /* NetBEUI. */ +#define LLC_SAP_LANMGR 0xF4 /* LanManager. */ +#define LLC_SAP_IMPL 0xF8 /* IMPL */ +#define LLC_SAP_DISC 0xFC /* Discovery */ +#define LLC_SAP_OSI 0xFE /* OSI Network Layers. */ +#define LLC_SAP_LAR 0xDC /* LAN Address Resolution */ +#define LLC_SAP_RM 0xD4 /* Resource Management */ +#define LLC_SAP_GLOBAL 0xFF /* Global SAP. */ + +#ifdef __KERNEL__ +#define LLC_SAP_DYN_START 0xC0 +#define LLC_SAP_DYN_STOP 0xDE +#define LLC_SAP_DYN_TRIES 4 + +#define llc_ui_skb_cb(__skb) ((struct sockaddr_llc *)&((__skb)->cb[0])) +#endif /* __KERNEL__ */ +#endif /* __LINUX_LLC_H */ diff --git a/include/linux/rtnetlink.h b/include/linux/rtnetlink.h new file mode 100644 index 0000000..5e33a20 --- /dev/null +++ b/include/linux/rtnetlink.h @@ -0,0 +1,910 @@ +#ifndef __LINUX_RTNETLINK_H +#define __LINUX_RTNETLINK_H + +#include + +/**** + * Routing/neighbour discovery messages. + ****/ + +/* Types of messages */ + +enum { + RTM_BASE = 16, +#define RTM_BASE RTM_BASE + + RTM_NEWLINK = 16, +#define RTM_NEWLINK RTM_NEWLINK + RTM_DELLINK, +#define RTM_DELLINK RTM_DELLINK + RTM_GETLINK, +#define RTM_GETLINK RTM_GETLINK + RTM_SETLINK, +#define RTM_SETLINK RTM_SETLINK + + RTM_NEWADDR = 20, +#define RTM_NEWADDR RTM_NEWADDR + RTM_DELADDR, +#define RTM_DELADDR RTM_DELADDR + RTM_GETADDR, +#define RTM_GETADDR RTM_GETADDR + + RTM_NEWROUTE = 24, +#define RTM_NEWROUTE RTM_NEWROUTE + RTM_DELROUTE, +#define RTM_DELROUTE RTM_DELROUTE + RTM_GETROUTE, +#define RTM_GETROUTE RTM_GETROUTE + + RTM_NEWNEIGH = 28, +#define RTM_NEWNEIGH RTM_NEWNEIGH + RTM_DELNEIGH, +#define RTM_DELNEIGH RTM_DELNEIGH + RTM_GETNEIGH, +#define RTM_GETNEIGH RTM_GETNEIGH + + RTM_NEWRULE = 32, +#define RTM_NEWRULE RTM_NEWRULE + RTM_DELRULE, +#define RTM_DELRULE RTM_DELRULE + RTM_GETRULE, +#define RTM_GETRULE RTM_GETRULE + + RTM_NEWQDISC = 36, +#define RTM_NEWQDISC RTM_NEWQDISC + RTM_DELQDISC, +#define RTM_DELQDISC RTM_DELQDISC + RTM_GETQDISC, +#define RTM_GETQDISC RTM_GETQDISC + + RTM_NEWTCLASS = 40, +#define RTM_NEWTCLASS RTM_NEWTCLASS + RTM_DELTCLASS, +#define RTM_DELTCLASS RTM_DELTCLASS + RTM_GETTCLASS, +#define RTM_GETTCLASS RTM_GETTCLASS + + RTM_NEWTFILTER = 44, +#define RTM_NEWTFILTER RTM_NEWTFILTER + RTM_DELTFILTER, +#define RTM_DELTFILTER RTM_DELTFILTER + RTM_GETTFILTER, +#define RTM_GETTFILTER RTM_GETTFILTER + + RTM_NEWACTION = 48, +#define RTM_NEWACTION RTM_NEWACTION + RTM_DELACTION, +#define RTM_DELACTION RTM_DELACTION + RTM_GETACTION, +#define RTM_GETACTION RTM_GETACTION + + RTM_NEWPREFIX = 52, +#define RTM_NEWPREFIX RTM_NEWPREFIX + RTM_GETPREFIX = 54, +#define RTM_GETPREFIX RTM_GETPREFIX + + RTM_GETMULTICAST = 58, +#define RTM_GETMULTICAST RTM_GETMULTICAST + + RTM_GETANYCAST = 62, +#define RTM_GETANYCAST RTM_GETANYCAST + + RTM_NEWNEIGHTBL = 64, +#define RTM_NEWNEIGHTBL RTM_NEWNEIGHTBL + RTM_GETNEIGHTBL = 66, +#define RTM_GETNEIGHTBL RTM_GETNEIGHTBL + RTM_SETNEIGHTBL, +#define RTM_SETNEIGHTBL RTM_SETNEIGHTBL + + __RTM_MAX, +#define RTM_MAX (((__RTM_MAX + 3) & ~3) - 1) +}; + +#define RTM_NR_MSGTYPES (RTM_MAX + 1 - RTM_BASE) +#define RTM_NR_FAMILIES (RTM_NR_MSGTYPES >> 2) +#define RTM_FAM(cmd) (((cmd) - RTM_BASE) >> 2) + +/* + Generic structure for encapsulation of optional route information. + It is reminiscent of sockaddr, but with sa_family replaced + with attribute type. + */ + +struct rtattr +{ + unsigned short rta_len; + unsigned short rta_type; +}; + +/* Macros to handle rtattributes */ + +#define RTA_ALIGNTO 4 +#define RTA_ALIGN(len) ( ((len)+RTA_ALIGNTO-1) & ~(RTA_ALIGNTO-1) ) +#define RTA_OK(rta,len) ((len) >= (int)sizeof(struct rtattr) && \ + (rta)->rta_len >= sizeof(struct rtattr) && \ + (rta)->rta_len <= (len)) +#define RTA_NEXT(rta,attrlen) ((attrlen) -= RTA_ALIGN((rta)->rta_len), \ + (struct rtattr*)(((char*)(rta)) + RTA_ALIGN((rta)->rta_len))) +#define RTA_LENGTH(len) (RTA_ALIGN(sizeof(struct rtattr)) + (len)) +#define RTA_SPACE(len) RTA_ALIGN(RTA_LENGTH(len)) +#define RTA_DATA(rta) ((void*)(((char*)(rta)) + RTA_LENGTH(0))) +#define RTA_PAYLOAD(rta) ((int)((rta)->rta_len) - RTA_LENGTH(0)) + + + + +/****************************************************************************** + * Definitions used in routing table administration. + ****/ + +struct rtmsg +{ + unsigned char rtm_family; + unsigned char rtm_dst_len; + unsigned char rtm_src_len; + unsigned char rtm_tos; + + unsigned char rtm_table; /* Routing table id */ + unsigned char rtm_protocol; /* Routing protocol; see below */ + unsigned char rtm_scope; /* See below */ + unsigned char rtm_type; /* See below */ + + unsigned rtm_flags; +}; + +/* rtm_type */ + +enum +{ + RTN_UNSPEC, + RTN_UNICAST, /* Gateway or direct route */ + RTN_LOCAL, /* Accept locally */ + RTN_BROADCAST, /* Accept locally as broadcast, + send as broadcast */ + RTN_ANYCAST, /* Accept locally as broadcast, + but send as unicast */ + RTN_MULTICAST, /* Multicast route */ + RTN_BLACKHOLE, /* Drop */ + RTN_UNREACHABLE, /* Destination is unreachable */ + RTN_PROHIBIT, /* Administratively prohibited */ + RTN_THROW, /* Not in this table */ + RTN_NAT, /* Translate this address */ + RTN_XRESOLVE, /* Use external resolver */ + __RTN_MAX +}; + +#define RTN_MAX (__RTN_MAX - 1) + + +/* rtm_protocol */ + +#define RTPROT_UNSPEC 0 +#define RTPROT_REDIRECT 1 /* Route installed by ICMP redirects; + not used by current IPv4 */ +#define RTPROT_KERNEL 2 /* Route installed by kernel */ +#define RTPROT_BOOT 3 /* Route installed during boot */ +#define RTPROT_STATIC 4 /* Route installed by administrator */ + +/* Values of protocol >= RTPROT_STATIC are not interpreted by kernel; + they are just passed from user and back as is. + It will be used by hypothetical multiple routing daemons. + Note that protocol values should be standardized in order to + avoid conflicts. + */ + +#define RTPROT_GATED 8 /* Apparently, GateD */ +#define RTPROT_RA 9 /* RDISC/ND router advertisements */ +#define RTPROT_MRT 10 /* Merit MRT */ +#define RTPROT_ZEBRA 11 /* Zebra */ +#define RTPROT_BIRD 12 /* BIRD */ +#define RTPROT_DNROUTED 13 /* DECnet routing daemon */ +#define RTPROT_XORP 14 /* XORP */ +#define RTPROT_NTK 15 /* Netsukuku */ + +/* rtm_scope + + Really it is not scope, but sort of distance to the destination. + NOWHERE are reserved for not existing destinations, HOST is our + local addresses, LINK are destinations, located on directly attached + link and UNIVERSE is everywhere in the Universe. + + Intermediate values are also possible f.e. interior routes + could be assigned a value between UNIVERSE and LINK. +*/ + +enum rt_scope_t +{ + RT_SCOPE_UNIVERSE=0, +/* User defined values */ + RT_SCOPE_SITE=200, + RT_SCOPE_LINK=253, + RT_SCOPE_HOST=254, + RT_SCOPE_NOWHERE=255 +}; + +/* rtm_flags */ + +#define RTM_F_NOTIFY 0x100 /* Notify user of route change */ +#define RTM_F_CLONED 0x200 /* This route is cloned */ +#define RTM_F_EQUALIZE 0x400 /* Multipath equalizer: NI */ +#define RTM_F_PREFIX 0x800 /* Prefix addresses */ + +/* Reserved table identifiers */ + +enum rt_class_t +{ + RT_TABLE_UNSPEC=0, +/* User defined values */ + RT_TABLE_DEFAULT=253, + RT_TABLE_MAIN=254, + RT_TABLE_LOCAL=255, + __RT_TABLE_MAX +}; +#define RT_TABLE_MAX (__RT_TABLE_MAX - 1) + + + +/* Routing message attributes */ + +enum rtattr_type_t +{ + RTA_UNSPEC, + RTA_DST, + RTA_SRC, + RTA_IIF, + RTA_OIF, + RTA_GATEWAY, + RTA_PRIORITY, + RTA_PREFSRC, + RTA_METRICS, + RTA_MULTIPATH, + RTA_PROTOINFO, + RTA_FLOW, + RTA_CACHEINFO, + RTA_SESSION, + RTA_MP_ALGO, + __RTA_MAX +}; + +#define RTA_MAX (__RTA_MAX - 1) + +#define RTM_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct rtmsg)))) +#define RTM_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct rtmsg)) + +/* RTM_MULTIPATH --- array of struct rtnexthop. + * + * "struct rtnexthop" describes all necessary nexthop information, + * i.e. parameters of path to a destination via this nexthop. + * + * At the moment it is impossible to set different prefsrc, mtu, window + * and rtt for different paths from multipath. + */ + +struct rtnexthop +{ + unsigned short rtnh_len; + unsigned char rtnh_flags; + unsigned char rtnh_hops; + int rtnh_ifindex; +}; + +/* rtnh_flags */ + +#define RTNH_F_DEAD 1 /* Nexthop is dead (used by multipath) */ +#define RTNH_F_PERVASIVE 2 /* Do recursive gateway lookup */ +#define RTNH_F_ONLINK 4 /* Gateway is forced on link */ + +/* Macros to handle hexthops */ + +#define RTNH_ALIGNTO 4 +#define RTNH_ALIGN(len) ( ((len)+RTNH_ALIGNTO-1) & ~(RTNH_ALIGNTO-1) ) +#define RTNH_OK(rtnh,len) ((rtnh)->rtnh_len >= sizeof(struct rtnexthop) && \ + ((int)(rtnh)->rtnh_len) <= (len)) +#define RTNH_NEXT(rtnh) ((struct rtnexthop*)(((char*)(rtnh)) + RTNH_ALIGN((rtnh)->rtnh_len))) +#define RTNH_LENGTH(len) (RTNH_ALIGN(sizeof(struct rtnexthop)) + (len)) +#define RTNH_SPACE(len) RTNH_ALIGN(RTNH_LENGTH(len)) +#define RTNH_DATA(rtnh) ((struct rtattr*)(((char*)(rtnh)) + RTNH_LENGTH(0))) + +/* RTM_CACHEINFO */ + +struct rta_cacheinfo +{ + __u32 rta_clntref; + __u32 rta_lastuse; + __s32 rta_expires; + __u32 rta_error; + __u32 rta_used; + +#define RTNETLINK_HAVE_PEERINFO 1 + __u32 rta_id; + __u32 rta_ts; + __u32 rta_tsage; +}; + +/* RTM_METRICS --- array of struct rtattr with types of RTAX_* */ + +enum +{ + RTAX_UNSPEC, +#define RTAX_UNSPEC RTAX_UNSPEC + RTAX_LOCK, +#define RTAX_LOCK RTAX_LOCK + RTAX_MTU, +#define RTAX_MTU RTAX_MTU + RTAX_WINDOW, +#define RTAX_WINDOW RTAX_WINDOW + RTAX_RTT, +#define RTAX_RTT RTAX_RTT + RTAX_RTTVAR, +#define RTAX_RTTVAR RTAX_RTTVAR + RTAX_SSTHRESH, +#define RTAX_SSTHRESH RTAX_SSTHRESH + RTAX_CWND, +#define RTAX_CWND RTAX_CWND + RTAX_ADVMSS, +#define RTAX_ADVMSS RTAX_ADVMSS + RTAX_REORDERING, +#define RTAX_REORDERING RTAX_REORDERING + RTAX_HOPLIMIT, +#define RTAX_HOPLIMIT RTAX_HOPLIMIT + RTAX_INITCWND, +#define RTAX_INITCWND RTAX_INITCWND + RTAX_FEATURES, +#define RTAX_FEATURES RTAX_FEATURES + __RTAX_MAX +}; + +#define RTAX_MAX (__RTAX_MAX - 1) + +#define RTAX_FEATURE_ECN 0x00000001 +#define RTAX_FEATURE_SACK 0x00000002 +#define RTAX_FEATURE_TIMESTAMP 0x00000004 +#define RTAX_FEATURE_ALLFRAG 0x00000008 + +struct rta_session +{ + __u8 proto; + __u8 pad1; + __u16 pad2; + + union { + struct { + __u16 sport; + __u16 dport; + } ports; + + struct { + __u8 type; + __u8 code; + __u16 ident; + } icmpt; + + __u32 spi; + } u; +}; + + +/********************************************************* + * Interface address. + ****/ + +struct ifaddrmsg +{ + unsigned char ifa_family; + unsigned char ifa_prefixlen; /* The prefix length */ + unsigned char ifa_flags; /* Flags */ + unsigned char ifa_scope; /* See above */ + int ifa_index; /* Link index */ +}; + +enum +{ + IFA_UNSPEC, + IFA_ADDRESS, + IFA_LOCAL, + IFA_LABEL, + IFA_BROADCAST, + IFA_ANYCAST, + IFA_CACHEINFO, + IFA_MULTICAST, + __IFA_MAX +}; + +#define IFA_MAX (__IFA_MAX - 1) + +/* ifa_flags */ + +#define IFA_F_SECONDARY 0x01 +#define IFA_F_TEMPORARY IFA_F_SECONDARY + +#define IFA_F_DEPRECATED 0x20 +#define IFA_F_TENTATIVE 0x40 +#define IFA_F_PERMANENT 0x80 + +struct ifa_cacheinfo +{ + __u32 ifa_prefered; + __u32 ifa_valid; + __u32 cstamp; /* created timestamp, hundredths of seconds */ + __u32 tstamp; /* updated timestamp, hundredths of seconds */ +}; + + +#define IFA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ifaddrmsg)))) +#define IFA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct ifaddrmsg)) + +/* + Important comment: + IFA_ADDRESS is prefix address, rather than local interface address. + It makes no difference for normally configured broadcast interfaces, + but for point-to-point IFA_ADDRESS is DESTINATION address, + local address is supplied in IFA_LOCAL attribute. + */ + +/************************************************************** + * Neighbour discovery. + ****/ + +struct ndmsg +{ + unsigned char ndm_family; + unsigned char ndm_pad1; + unsigned short ndm_pad2; + int ndm_ifindex; /* Link index */ + __u16 ndm_state; + __u8 ndm_flags; + __u8 ndm_type; +}; + +enum +{ + NDA_UNSPEC, + NDA_DST, + NDA_LLADDR, + NDA_CACHEINFO, + NDA_PROBES, + __NDA_MAX +}; + +#define NDA_MAX (__NDA_MAX - 1) + +#define NDA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ndmsg)))) +#define NDA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct ndmsg)) + +/* + * Neighbor Cache Entry Flags + */ + +#define NTF_PROXY 0x08 /* == ATF_PUBL */ +#define NTF_ROUTER 0x80 + +/* + * Neighbor Cache Entry States. + */ + +#define NUD_INCOMPLETE 0x01 +#define NUD_REACHABLE 0x02 +#define NUD_STALE 0x04 +#define NUD_DELAY 0x08 +#define NUD_PROBE 0x10 +#define NUD_FAILED 0x20 + +/* Dummy states */ +#define NUD_NOARP 0x40 +#define NUD_PERMANENT 0x80 +#define NUD_NONE 0x00 + + +struct nda_cacheinfo +{ + __u32 ndm_confirmed; + __u32 ndm_used; + __u32 ndm_updated; + __u32 ndm_refcnt; +}; + + +/***************************************************************** + * Neighbour tables specific messages. + * + * To retrieve the neighbour tables send RTM_GETNEIGHTBL with the + * NLM_F_DUMP flag set. Every neighbour table configuration is + * spread over multiple messages to avoid running into message + * size limits on systems with many interfaces. The first message + * in the sequence transports all not device specific data such as + * statistics, configuration, and the default parameter set. + * This message is followed by 0..n messages carrying device + * specific parameter sets. + * Although the ordering should be sufficient, NDTA_NAME can be + * used to identify sequences. The initial message can be identified + * by checking for NDTA_CONFIG. The device specific messages do + * not contain this TLV but have NDTPA_IFINDEX set to the + * corresponding interface index. + * + * To change neighbour table attributes, send RTM_SETNEIGHTBL + * with NDTA_NAME set. Changeable attribute include NDTA_THRESH[1-3], + * NDTA_GC_INTERVAL, and all TLVs in NDTA_PARMS unless marked + * otherwise. Device specific parameter sets can be changed by + * setting NDTPA_IFINDEX to the interface index of the corresponding + * device. + ****/ + +struct ndt_stats +{ + __u64 ndts_allocs; + __u64 ndts_destroys; + __u64 ndts_hash_grows; + __u64 ndts_res_failed; + __u64 ndts_lookups; + __u64 ndts_hits; + __u64 ndts_rcv_probes_mcast; + __u64 ndts_rcv_probes_ucast; + __u64 ndts_periodic_gc_runs; + __u64 ndts_forced_gc_runs; +}; + +enum { + NDTPA_UNSPEC, + NDTPA_IFINDEX, /* u32, unchangeable */ + NDTPA_REFCNT, /* u32, read-only */ + NDTPA_REACHABLE_TIME, /* u64, read-only, msecs */ + NDTPA_BASE_REACHABLE_TIME, /* u64, msecs */ + NDTPA_RETRANS_TIME, /* u64, msecs */ + NDTPA_GC_STALETIME, /* u64, msecs */ + NDTPA_DELAY_PROBE_TIME, /* u64, msecs */ + NDTPA_QUEUE_LEN, /* u32 */ + NDTPA_APP_PROBES, /* u32 */ + NDTPA_UCAST_PROBES, /* u32 */ + NDTPA_MCAST_PROBES, /* u32 */ + NDTPA_ANYCAST_DELAY, /* u64, msecs */ + NDTPA_PROXY_DELAY, /* u64, msecs */ + NDTPA_PROXY_QLEN, /* u32 */ + NDTPA_LOCKTIME, /* u64, msecs */ + __NDTPA_MAX +}; +#define NDTPA_MAX (__NDTPA_MAX - 1) + +struct ndtmsg +{ + __u8 ndtm_family; + __u8 ndtm_pad1; + __u16 ndtm_pad2; +}; + +struct ndt_config +{ + __u16 ndtc_key_len; + __u16 ndtc_entry_size; + __u32 ndtc_entries; + __u32 ndtc_last_flush; /* delta to now in msecs */ + __u32 ndtc_last_rand; /* delta to now in msecs */ + __u32 ndtc_hash_rnd; + __u32 ndtc_hash_mask; + __u32 ndtc_hash_chain_gc; + __u32 ndtc_proxy_qlen; +}; + +enum { + NDTA_UNSPEC, + NDTA_NAME, /* char *, unchangeable */ + NDTA_THRESH1, /* u32 */ + NDTA_THRESH2, /* u32 */ + NDTA_THRESH3, /* u32 */ + NDTA_CONFIG, /* struct ndt_config, read-only */ + NDTA_PARMS, /* nested TLV NDTPA_* */ + NDTA_STATS, /* struct ndt_stats, read-only */ + NDTA_GC_INTERVAL, /* u64, msecs */ + __NDTA_MAX +}; +#define NDTA_MAX (__NDTA_MAX - 1) + +#define NDTA_RTA(r) ((struct rtattr*)(((char*)(r)) + \ + NLMSG_ALIGN(sizeof(struct ndtmsg)))) +#define NDTA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct ndtmsg)) + + +/**** + * General form of address family dependent message. + ****/ + +struct rtgenmsg +{ + unsigned char rtgen_family; +}; + +/***************************************************************** + * Link layer specific messages. + ****/ + +/* struct ifinfomsg + * passes link level specific information, not dependent + * on network protocol. + */ + +struct ifinfomsg +{ + unsigned char ifi_family; + unsigned char __ifi_pad; + unsigned short ifi_type; /* ARPHRD_* */ + int ifi_index; /* Link index */ + unsigned ifi_flags; /* IFF_* flags */ + unsigned ifi_change; /* IFF_* change mask */ +}; + +/******************************************************************** + * prefix information + ****/ + +struct prefixmsg +{ + unsigned char prefix_family; + unsigned char prefix_pad1; + unsigned short prefix_pad2; + int prefix_ifindex; + unsigned char prefix_type; + unsigned char prefix_len; + unsigned char prefix_flags; + unsigned char prefix_pad3; +}; + +enum +{ + PREFIX_UNSPEC, + PREFIX_ADDRESS, + PREFIX_CACHEINFO, + __PREFIX_MAX +}; + +#define PREFIX_MAX (__PREFIX_MAX - 1) + +struct prefix_cacheinfo +{ + __u32 preferred_time; + __u32 valid_time; +}; + +/* The struct should be in sync with struct net_device_stats */ +struct rtnl_link_stats +{ + __u32 rx_packets; /* total packets received */ + __u32 tx_packets; /* total packets transmitted */ + __u32 rx_bytes; /* total bytes received */ + __u32 tx_bytes; /* total bytes transmitted */ + __u32 rx_errors; /* bad packets received */ + __u32 tx_errors; /* packet transmit problems */ + __u32 rx_dropped; /* no space in linux buffers */ + __u32 tx_dropped; /* no space available in linux */ + __u32 multicast; /* multicast packets received */ + __u32 collisions; + + /* detailed rx_errors: */ + __u32 rx_length_errors; + __u32 rx_over_errors; /* receiver ring buff overflow */ + __u32 rx_crc_errors; /* recved pkt with crc error */ + __u32 rx_frame_errors; /* recv'd frame alignment error */ + __u32 rx_fifo_errors; /* recv'r fifo overrun */ + __u32 rx_missed_errors; /* receiver missed packet */ + + /* detailed tx_errors */ + __u32 tx_aborted_errors; + __u32 tx_carrier_errors; + __u32 tx_fifo_errors; + __u32 tx_heartbeat_errors; + __u32 tx_window_errors; + + /* for cslip etc */ + __u32 rx_compressed; + __u32 tx_compressed; +}; + +/* The struct should be in sync with struct ifmap */ +struct rtnl_link_ifmap +{ + __u64 mem_start; + __u64 mem_end; + __u64 base_addr; + __u16 irq; + __u8 dma; + __u8 port; +}; + +enum +{ + IFLA_UNSPEC, + IFLA_ADDRESS, + IFLA_BROADCAST, + IFLA_IFNAME, + IFLA_MTU, + IFLA_LINK, + IFLA_QDISC, + IFLA_STATS, + IFLA_COST, +#define IFLA_COST IFLA_COST + IFLA_PRIORITY, +#define IFLA_PRIORITY IFLA_PRIORITY + IFLA_MASTER, +#define IFLA_MASTER IFLA_MASTER + IFLA_WIRELESS, /* Wireless Extension event - see wireless.h */ +#define IFLA_WIRELESS IFLA_WIRELESS + IFLA_PROTINFO, /* Protocol specific information for a link */ +#define IFLA_PROTINFO IFLA_PROTINFO + IFLA_TXQLEN, +#define IFLA_TXQLEN IFLA_TXQLEN + IFLA_MAP, +#define IFLA_MAP IFLA_MAP + IFLA_WEIGHT, +#define IFLA_WEIGHT IFLA_WEIGHT + IFLA_OPERSTATE, + IFLA_LINKMODE, + __IFLA_MAX +}; + + +#define IFLA_MAX (__IFLA_MAX - 1) + +#define IFLA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ifinfomsg)))) +#define IFLA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct ifinfomsg)) + +/* ifi_flags. + + IFF_* flags. + + The only change is: + IFF_LOOPBACK, IFF_BROADCAST and IFF_POINTOPOINT are + more not changeable by user. They describe link media + characteristics and set by device driver. + + Comments: + - Combination IFF_BROADCAST|IFF_POINTOPOINT is invalid + - If neither of these three flags are set; + the interface is NBMA. + + - IFF_MULTICAST does not mean anything special: + multicasts can be used on all not-NBMA links. + IFF_MULTICAST means that this media uses special encapsulation + for multicast frames. Apparently, all IFF_POINTOPOINT and + IFF_BROADCAST devices are able to use multicasts too. + */ + +/* IFLA_LINK. + For usual devices it is equal ifi_index. + If it is a "virtual interface" (f.e. tunnel), ifi_link + can point to real physical interface (f.e. for bandwidth calculations), + or maybe 0, what means, that real media is unknown (usual + for IPIP tunnels, when route to endpoint is allowed to change) + */ + +/* Subtype attributes for IFLA_PROTINFO */ +enum +{ + IFLA_INET6_UNSPEC, + IFLA_INET6_FLAGS, /* link flags */ + IFLA_INET6_CONF, /* sysctl parameters */ + IFLA_INET6_STATS, /* statistics */ + IFLA_INET6_MCAST, /* MC things. What of them? */ + IFLA_INET6_CACHEINFO, /* time values and max reasm size */ + __IFLA_INET6_MAX +}; + +#define IFLA_INET6_MAX (__IFLA_INET6_MAX - 1) + +struct ifla_cacheinfo +{ + __u32 max_reasm_len; + __u32 tstamp; /* ipv6InterfaceTable updated timestamp */ + __u32 reachable_time; + __u32 retrans_time; +}; + +/***************************************************************** + * Traffic control messages. + ****/ + +struct tcmsg +{ + unsigned char tcm_family; + unsigned char tcm__pad1; + unsigned short tcm__pad2; + int tcm_ifindex; + __u32 tcm_handle; + __u32 tcm_parent; + __u32 tcm_info; +}; + +enum +{ + TCA_UNSPEC, + TCA_KIND, + TCA_OPTIONS, + TCA_STATS, + TCA_XSTATS, + TCA_RATE, + TCA_FCNT, + TCA_STATS2, + __TCA_MAX +}; + +#define TCA_MAX (__TCA_MAX - 1) + +#define TCA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct tcmsg)))) +#define TCA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct tcmsg)) + +/* RTnetlink multicast groups - backwards compatibility for userspace */ +#define RTMGRP_LINK 1 +#define RTMGRP_NOTIFY 2 +#define RTMGRP_NEIGH 4 +#define RTMGRP_TC 8 + +#define RTMGRP_IPV4_IFADDR 0x10 +#define RTMGRP_IPV4_MROUTE 0x20 +#define RTMGRP_IPV4_ROUTE 0x40 +#define RTMGRP_IPV4_RULE 0x80 + +#define RTMGRP_IPV6_IFADDR 0x100 +#define RTMGRP_IPV6_MROUTE 0x200 +#define RTMGRP_IPV6_ROUTE 0x400 +#define RTMGRP_IPV6_IFINFO 0x800 + +#define RTMGRP_DECnet_IFADDR 0x1000 +#define RTMGRP_DECnet_ROUTE 0x4000 + +#define RTMGRP_IPV6_PREFIX 0x20000 + +/* RTnetlink multicast groups */ +enum rtnetlink_groups { + RTNLGRP_NONE, +#define RTNLGRP_NONE RTNLGRP_NONE + RTNLGRP_LINK, +#define RTNLGRP_LINK RTNLGRP_LINK + RTNLGRP_NOTIFY, +#define RTNLGRP_NOTIFY RTNLGRP_NOTIFY + RTNLGRP_NEIGH, +#define RTNLGRP_NEIGH RTNLGRP_NEIGH + RTNLGRP_TC, +#define RTNLGRP_TC RTNLGRP_TC + RTNLGRP_IPV4_IFADDR, +#define RTNLGRP_IPV4_IFADDR RTNLGRP_IPV4_IFADDR + RTNLGRP_IPV4_MROUTE, +#define RTNLGRP_IPV4_MROUTE RTNLGRP_IPV4_MROUTE + RTNLGRP_IPV4_ROUTE, +#define RTNLGRP_IPV4_ROUTE RTNLGRP_IPV4_ROUTE + RTNLGRP_IPV4_RULE, +#define RTNLGRP_IPV4_RULE RTNLGRP_IPV4_RULE + RTNLGRP_IPV6_IFADDR, +#define RTNLGRP_IPV6_IFADDR RTNLGRP_IPV6_IFADDR + RTNLGRP_IPV6_MROUTE, +#define RTNLGRP_IPV6_MROUTE RTNLGRP_IPV6_MROUTE + RTNLGRP_IPV6_ROUTE, +#define RTNLGRP_IPV6_ROUTE RTNLGRP_IPV6_ROUTE + RTNLGRP_IPV6_IFINFO, +#define RTNLGRP_IPV6_IFINFO RTNLGRP_IPV6_IFINFO + RTNLGRP_DECnet_IFADDR, +#define RTNLGRP_DECnet_IFADDR RTNLGRP_DECnet_IFADDR + RTNLGRP_NOP2, + RTNLGRP_DECnet_ROUTE, +#define RTNLGRP_DECnet_ROUTE RTNLGRP_DECnet_ROUTE + RTNLGRP_NOP3, + RTNLGRP_NOP4, + RTNLGRP_IPV6_PREFIX, +#define RTNLGRP_IPV6_PREFIX RTNLGRP_IPV6_PREFIX + __RTNLGRP_MAX +}; +#define RTNLGRP_MAX (__RTNLGRP_MAX - 1) + +/* TC action piece */ +struct tcamsg +{ + unsigned char tca_family; + unsigned char tca__pad1; + unsigned short tca__pad2; +}; +#define TA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct tcamsg)))) +#define TA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct tcamsg)) +#define TCA_ACT_TAB 1 /* attr type must be >=1 */ +#define TCAA_MAX 1 + +/* End of information exported to user level */ + + + +#endif /* __LINUX_RTNETLINK_H */ diff --git a/libnetlink.c b/libnetlink.c new file mode 100644 index 0000000..151968b --- /dev/null +++ b/libnetlink.c @@ -0,0 +1,592 @@ +/* + * libnetlink.c RTnetlink service routines. + * + * This program 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 of the License, or (at your option) any later version. + * + * Authors: Alexey Kuznetsov, + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "libnetlink.h" + +void rtnl_close(struct rtnl_handle *rth) +{ + close(rth->fd); +} + +int rtnl_open_byproto(struct rtnl_handle *rth, unsigned subscriptions, + int protocol) +{ + socklen_t addr_len; + int sndbuf = 32768; + int rcvbuf = 32768; + + memset(rth, 0, sizeof(rth)); + + rth->fd = socket(AF_NETLINK, SOCK_RAW, protocol); + if (rth->fd < 0) { + perror("Cannot open netlink socket"); + return -1; + } + + if (setsockopt(rth->fd,SOL_SOCKET,SO_SNDBUF,&sndbuf,sizeof(sndbuf)) < 0) { + perror("SO_SNDBUF"); + return -1; + } + + if (setsockopt(rth->fd,SOL_SOCKET,SO_RCVBUF,&rcvbuf,sizeof(rcvbuf)) < 0) { + perror("SO_RCVBUF"); + return -1; + } + + memset(&rth->local, 0, sizeof(rth->local)); + rth->local.nl_family = AF_NETLINK; + rth->local.nl_groups = subscriptions; + + if (bind(rth->fd, (struct sockaddr*)&rth->local, sizeof(rth->local)) < 0) { + perror("Cannot bind netlink socket"); + return -1; + } + addr_len = sizeof(rth->local); + if (getsockname(rth->fd, (struct sockaddr*)&rth->local, &addr_len) < 0) { + perror("Cannot getsockname"); + return -1; + } + if (addr_len != sizeof(rth->local)) { + fprintf(stderr, "Wrong address length %d\n", addr_len); + return -1; + } + if (rth->local.nl_family != AF_NETLINK) { + fprintf(stderr, "Wrong address family %d\n", rth->local.nl_family); + return -1; + } + rth->seq = time(NULL); + return 0; +} + +int rtnl_open(struct rtnl_handle *rth, unsigned subscriptions) +{ + return rtnl_open_byproto(rth, subscriptions, NETLINK_ROUTE); +} + +int rtnl_wilddump_request(struct rtnl_handle *rth, int family, int type) +{ + struct { + struct nlmsghdr nlh; + struct rtgenmsg g; + } req; + struct sockaddr_nl nladdr; + + memset(&nladdr, 0, sizeof(nladdr)); + nladdr.nl_family = AF_NETLINK; + + memset(&req, 0, sizeof(req)); + req.nlh.nlmsg_len = sizeof(req); + req.nlh.nlmsg_type = type; + req.nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST; + req.nlh.nlmsg_pid = 0; + req.nlh.nlmsg_seq = rth->dump = ++rth->seq; + req.g.rtgen_family = family; + + return sendto(rth->fd, (void*)&req, sizeof(req), 0, + (struct sockaddr*)&nladdr, sizeof(nladdr)); +} + +int rtnl_send(struct rtnl_handle *rth, const char *buf, int len) +{ + struct sockaddr_nl nladdr; + + memset(&nladdr, 0, sizeof(nladdr)); + nladdr.nl_family = AF_NETLINK; + + return sendto(rth->fd, buf, len, 0, (struct sockaddr*)&nladdr, sizeof(nladdr)); +} + +int rtnl_dump_request(struct rtnl_handle *rth, int type, void *req, int len) +{ + struct nlmsghdr nlh; + struct sockaddr_nl nladdr; + struct iovec iov[2] = { + { .iov_base = &nlh, .iov_len = sizeof(nlh) }, + { .iov_base = req, .iov_len = len } + }; + struct msghdr msg = { + .msg_name = &nladdr, + .msg_namelen = sizeof(nladdr), + .msg_iov = iov, + .msg_iovlen = 2, + }; + + memset(&nladdr, 0, sizeof(nladdr)); + nladdr.nl_family = AF_NETLINK; + + nlh.nlmsg_len = NLMSG_LENGTH(len); + nlh.nlmsg_type = type; + nlh.nlmsg_flags = NLM_F_ROOT|NLM_F_MATCH|NLM_F_REQUEST; + nlh.nlmsg_pid = 0; + nlh.nlmsg_seq = rth->dump = ++rth->seq; + + return sendmsg(rth->fd, &msg, 0); +} + +int rtnl_dump_filter(struct rtnl_handle *rth, + rtnl_filter_t filter, + void *arg1, + rtnl_filter_t junk, + void *arg2) +{ + struct sockaddr_nl nladdr; + struct iovec iov; + struct msghdr msg = { + .msg_name = &nladdr, + .msg_namelen = sizeof(nladdr), + .msg_iov = &iov, + .msg_iovlen = 1, + }; + char buf[16384]; + + iov.iov_base = buf; + while (1) { + int status; + struct nlmsghdr *h; + + iov.iov_len = sizeof(buf); + status = recvmsg(rth->fd, &msg, 0); + + if (status < 0) { + if (errno == EINTR) + continue; + perror("OVERRUN"); + continue; + } + + if (status == 0) { + fprintf(stderr, "EOF on netlink\n"); + return -1; + } + + h = (struct nlmsghdr*)buf; + while (NLMSG_OK(h, status)) { + int err; + + if (nladdr.nl_pid != 0 || + h->nlmsg_pid != rth->local.nl_pid || + h->nlmsg_seq != rth->dump) { + if (junk) { + err = junk(&nladdr, h, arg2); + if (err < 0) + return err; + } + goto skip_it; + } + + if (h->nlmsg_type == NLMSG_DONE) + return 0; + if (h->nlmsg_type == NLMSG_ERROR) { + struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h); + if (h->nlmsg_len < NLMSG_LENGTH(sizeof(struct nlmsgerr))) { + fprintf(stderr, "ERROR truncated\n"); + } else { + errno = -err->error; + perror("RTNETLINK answers"); + } + return -1; + } + err = filter(&nladdr, h, arg1); + if (err < 0) + return err; + +skip_it: + h = NLMSG_NEXT(h, status); + } + if (msg.msg_flags & MSG_TRUNC) { + fprintf(stderr, "Message truncated\n"); + continue; + } + if (status) { + fprintf(stderr, "!!!Remnant of size %d\n", status); + exit(1); + } + } +} + +int rtnl_talk(struct rtnl_handle *rtnl, struct nlmsghdr *n, pid_t peer, + unsigned groups, struct nlmsghdr *answer, + rtnl_filter_t junk, + void *jarg) +{ + int status; + unsigned seq; + struct nlmsghdr *h; + struct sockaddr_nl nladdr; + struct iovec iov = { + .iov_base = (void*) n, + .iov_len = n->nlmsg_len + }; + struct msghdr msg = { + .msg_name = &nladdr, + .msg_namelen = sizeof(nladdr), + .msg_iov = &iov, + .msg_iovlen = 1, + }; + char buf[16384]; + + memset(&nladdr, 0, sizeof(nladdr)); + nladdr.nl_family = AF_NETLINK; + nladdr.nl_pid = peer; + nladdr.nl_groups = groups; + + n->nlmsg_seq = seq = ++rtnl->seq; + + if (answer == NULL) + n->nlmsg_flags |= NLM_F_ACK; + + status = sendmsg(rtnl->fd, &msg, 0); + + if (status < 0) { + perror("Cannot talk to rtnetlink"); + return -1; + } + + memset(buf,0,sizeof(buf)); + + iov.iov_base = buf; + + while (1) { + iov.iov_len = sizeof(buf); + status = recvmsg(rtnl->fd, &msg, 0); + + if (status < 0) { + if (errno == EINTR) + continue; + perror("OVERRUN"); + continue; + } + if (status == 0) { + fprintf(stderr, "EOF on netlink\n"); + return -1; + } + if (msg.msg_namelen != sizeof(nladdr)) { + fprintf(stderr, "sender address length == %d\n", msg.msg_namelen); + exit(1); + } + for (h = (struct nlmsghdr*)buf; status >= sizeof(*h); ) { + int err; + int len = h->nlmsg_len; + int l = len - sizeof(*h); + + if (l<0 || len>status) { + if (msg.msg_flags & MSG_TRUNC) { + fprintf(stderr, "Truncated message\n"); + return -1; + } + fprintf(stderr, "!!!malformed message: len=%d\n", len); + exit(1); + } + + if (nladdr.nl_pid != peer || + h->nlmsg_pid != rtnl->local.nl_pid || + h->nlmsg_seq != seq) { + if (junk) { + err = junk(&nladdr, h, jarg); + if (err < 0) + return err; + } + /* Don't forget to skip that message. */ + status -= NLMSG_ALIGN(len); + h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len)); + continue; + } + + if (h->nlmsg_type == NLMSG_ERROR) { + struct nlmsgerr *err = (struct nlmsgerr*)NLMSG_DATA(h); + if (l < sizeof(struct nlmsgerr)) { + fprintf(stderr, "ERROR truncated\n"); + } else { + errno = -err->error; + if (errno == 0) { + if (answer) + memcpy(answer, h, h->nlmsg_len); + return 0; + } + perror("RTNETLINK answers"); + } + return -1; + } + if (answer) { + memcpy(answer, h, h->nlmsg_len); + return 0; + } + + fprintf(stderr, "Unexpected reply!!!\n"); + + status -= NLMSG_ALIGN(len); + h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len)); + } + if (msg.msg_flags & MSG_TRUNC) { + fprintf(stderr, "Message truncated\n"); + continue; + } + if (status) { + fprintf(stderr, "!!!Remnant of size %d\n", status); + exit(1); + } + } +} + +int rtnl_listen(struct rtnl_handle *rtnl, + rtnl_filter_t handler, + void *jarg) +{ + int status; + struct nlmsghdr *h; + struct sockaddr_nl nladdr; + struct iovec iov; + struct msghdr msg = { + .msg_name = &nladdr, + .msg_namelen = sizeof(nladdr), + .msg_iov = &iov, + .msg_iovlen = 1, + }; + char buf[8192]; + + memset(&nladdr, 0, sizeof(nladdr)); + nladdr.nl_family = AF_NETLINK; + nladdr.nl_pid = 0; + nladdr.nl_groups = 0; + + iov.iov_base = buf; + while (1) { + iov.iov_len = sizeof(buf); + status = recvmsg(rtnl->fd, &msg, 0); + + if (status < 0) { + if (errno == EINTR) + continue; + if (errno == EAGAIN) + return 0; + perror("OVERRUN"); + return -1; + } + if (status == 0) { + fprintf(stderr, "EOF on netlink\n"); + return -1; + } + if (msg.msg_namelen != sizeof(nladdr)) { + fprintf(stderr, "Sender address length == %d\n", msg.msg_namelen); + exit(1); + } + for (h = (struct nlmsghdr*)buf; status >= sizeof(*h); ) { + int err; + int len = h->nlmsg_len; + int l = len - sizeof(*h); + + if (l<0 || len>status) { + if (msg.msg_flags & MSG_TRUNC) { + fprintf(stderr, "Truncated message\n"); + return -1; + } + fprintf(stderr, "!!!malformed message: len=%d\n", len); + exit(1); + } + + err = handler(&nladdr, h, jarg); + if (err < 0) { + fprintf(stderr, "Handler returned %d\n", err); + return err; + } + + status -= NLMSG_ALIGN(len); + h = (struct nlmsghdr*)((char*)h + NLMSG_ALIGN(len)); + } + if (msg.msg_flags & MSG_TRUNC) { + fprintf(stderr, "Message truncated\n"); + continue; + } + if (status) { + fprintf(stderr, "!!!Remnant of size %d\n", status); + exit(1); + } + } +} + +int rtnl_from_file(FILE *rtnl, rtnl_filter_t handler, + void *jarg) +{ + int status; + struct sockaddr_nl nladdr; + char buf[8192]; + struct nlmsghdr *h = (void*)buf; + + memset(&nladdr, 0, sizeof(nladdr)); + nladdr.nl_family = AF_NETLINK; + nladdr.nl_pid = 0; + nladdr.nl_groups = 0; + + while (1) { + int err, len, type; + int l; + + status = fread(&buf, 1, sizeof(*h), rtnl); + + if (status < 0) { + if (errno == EINTR) + continue; + perror("rtnl_from_file: fread"); + return -1; + } + if (status == 0) + return 0; + + len = h->nlmsg_len; + type= h->nlmsg_type; + l = len - sizeof(*h); + + if (l<0 || len>sizeof(buf)) { + fprintf(stderr, "!!!malformed message: len=%d @%lu\n", + len, ftell(rtnl)); + return -1; + } + + status = fread(NLMSG_DATA(h), 1, NLMSG_ALIGN(l), rtnl); + + if (status < 0) { + perror("rtnl_from_file: fread"); + return -1; + } + if (status < l) { + fprintf(stderr, "rtnl-from_file: truncated message\n"); + return -1; + } + + err = handler(&nladdr, h, jarg); + if (err < 0) + return err; + } +} + +int addattr32(struct nlmsghdr *n, int maxlen, int type, __u32 data) +{ + int len = RTA_LENGTH(4); + struct rtattr *rta; + if (NLMSG_ALIGN(n->nlmsg_len) + len > maxlen) { + fprintf(stderr,"addattr32: Error! max allowed bound %d exceeded\n",maxlen); + return -1; + } + rta = NLMSG_TAIL(n); + rta->rta_type = type; + rta->rta_len = len; + memcpy(RTA_DATA(rta), &data, 4); + n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + len; + return 0; +} + +int addattr_l(struct nlmsghdr *n, int maxlen, int type, const void *data, + int alen) +{ + int len = RTA_LENGTH(alen); + struct rtattr *rta; + + if (NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len) > maxlen) { + fprintf(stderr, "addattr_l ERROR: message exceeded bound of %d\n",maxlen); + return -1; + } + rta = NLMSG_TAIL(n); + rta->rta_type = type; + rta->rta_len = len; + memcpy(RTA_DATA(rta), data, alen); + n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(len); + return 0; +} + +int addraw_l(struct nlmsghdr *n, int maxlen, const void *data, int len) +{ + if (NLMSG_ALIGN(n->nlmsg_len) + NLMSG_ALIGN(len) > maxlen) { + fprintf(stderr, "addraw_l ERROR: message exceeded bound of %d\n",maxlen); + return -1; + } + + memcpy(NLMSG_TAIL(n), data, len); + memset((void *) NLMSG_TAIL(n) + len, 0, NLMSG_ALIGN(len) - len); + n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + NLMSG_ALIGN(len); + return 0; +} + +int rta_addattr32(struct rtattr *rta, int maxlen, int type, __u32 data) +{ + int len = RTA_LENGTH(4); + struct rtattr *subrta; + + if (RTA_ALIGN(rta->rta_len) + len > maxlen) { + fprintf(stderr,"rta_addattr32: Error! max allowed bound %d exceeded\n",maxlen); + return -1; + } + subrta = (struct rtattr*)(((char*)rta) + RTA_ALIGN(rta->rta_len)); + subrta->rta_type = type; + subrta->rta_len = len; + memcpy(RTA_DATA(subrta), &data, 4); + rta->rta_len = NLMSG_ALIGN(rta->rta_len) + len; + return 0; +} + +int rta_addattr_l(struct rtattr *rta, int maxlen, int type, + const void *data, int alen) +{ + struct rtattr *subrta; + int len = RTA_LENGTH(alen); + + if (RTA_ALIGN(rta->rta_len) + RTA_ALIGN(len) > maxlen) { + fprintf(stderr,"rta_addattr_l: Error! max allowed bound %d exceeded\n",maxlen); + return -1; + } + subrta = (struct rtattr*)(((char*)rta) + RTA_ALIGN(rta->rta_len)); + subrta->rta_type = type; + subrta->rta_len = len; + memcpy(RTA_DATA(subrta), data, alen); + rta->rta_len = NLMSG_ALIGN(rta->rta_len) + RTA_ALIGN(len); + return 0; +} + +int parse_rtattr(struct rtattr *tb[], int max, struct rtattr *rta, int len) +{ + memset(tb, 0, sizeof(struct rtattr *) * (max + 1)); + while (RTA_OK(rta, len)) { + if (rta->rta_type <= max) + tb[rta->rta_type] = rta; + rta = RTA_NEXT(rta,len); + } + if (len) + fprintf(stderr, "!!!Deficit %d, rta_len=%d\n", len, rta->rta_len); + return 0; +} + +int parse_rtattr_byindex(struct rtattr *tb[], int max, struct rtattr *rta, int len) +{ + int i = 0; + + memset(tb, 0, sizeof(struct rtattr *) * max); + while (RTA_OK(rta, len)) { + if (rta->rta_type <= max && i < max) + tb[i++] = rta; + rta = RTA_NEXT(rta,len); + } + if (len) + fprintf(stderr, "!!!Deficit %d, rta_len=%d\n", len, rta->rta_len); + return i; +} diff --git a/log.h b/log.h new file mode 100644 index 0000000..e61a569 --- /dev/null +++ b/log.h @@ -0,0 +1,69 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#ifndef LOG_H +#define LOG_H + +#include +#include + +#define LOG_LEVEL_NONE 0 +#define LOG_LEVEL_ERROR 1 +#define LOG_LEVEL_INFO 2 +#define LOG_LEVEL_DEBUG 3 +#define LOG_LEVEL_RSTPLIB 4 +#define LOG_LEVEL_MAX 100 + +#define LOG_LEVEL_DEFAULT LOG_LEVEL_INFO + +extern void Dprintf(int level, const char *fmt, ...); +extern void vDprintf(int level, const char *fmt, va_list ap); +extern int log_level; + +#define PRINT(_level, _fmt, _args...) Dprintf(_level, _fmt, ##_args) + +#define TSTM(x,y, _fmt, _args...) do if (!(x)) { PRINT(LOG_LEVEL_ERROR, "Error in %s at %s:%d verifying %s. " _fmt, __PRETTY_FUNCTION__, __FILE__, __LINE__, #x, ##_args); return y; } while (0) + +#define TST(x,y) TSTM(x,y,"") + +#define LOG(_fmt, _args...) PRINT(LOG_LEVEL_DEBUG, "%s: " _fmt, __PRETTY_FUNCTION__, ##_args) + +#define INFO(_fmt, _args...) PRINT(LOG_LEVEL_INFO, "%s: " _fmt, __PRETTY_FUNCTION__, ##_args) + +#define ERROR(_fmt, _args...) PRINT(LOG_LEVEL_ERROR, "error, %s: " _fmt, __PRETTY_FUNCTION__, ##_args) + +static inline void dump_hex(void *b, int l) +{ + unsigned char *buf = b; + char logbuf[80]; + int i, j; + for (i = 0; i < l; i += 16) { + for (j = 0; j < 16 && i+j < l; j++) + sprintf(logbuf + j * 3, " %02x", buf[i+j]); + PRINT(LOG_LEVEL_INFO, "%s", logbuf); + } + PRINT(LOG_LEVEL_INFO, "\n"); +} + +#endif diff --git a/main.c b/main.c new file mode 100644 index 0000000..3ff556d --- /dev/null +++ b/main.c @@ -0,0 +1,110 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#include "epoll_loop.h" +#include "bridge_ctl.h" +#include "ctl_socket_server.h" +#include "netif_utils.h" +#include "log.h" + +#include +#include +#include +#include +#include + +static int become_daemon = 1; +static int is_daemon = 0; +int log_level = LOG_LEVEL_DEFAULT; + +int main(int argc, char *argv[]) +{ + int c; + while ((c = getopt(argc, argv, "dv:")) != -1) { + switch (c) { + case 'd': + become_daemon = 0; break; + case 'v': + { + char *end; + long l; + l = strtoul(optarg, &end, 0); + if (*optarg == 0 || *end != 0 || l > LOG_LEVEL_MAX) { + ERROR("Invalid loglevel %s", optarg); + exit(1); + } + log_level = l; + } + break; + default: + return -1; + } + } + + TST(init_epoll() == 0, -1); + TST(ctl_socket_init() == 0, -1); + + TST(netsock_init() == 0, -1); + TST(init_bridge_ops() == 0, -1); + if (become_daemon) { + openlog("rstpd", 0, LOG_DAEMON); + daemon(0,0); + is_daemon = 1; + } + return epoll_main_loop(); +} + +/*********************** Logging *********************/ + +#include +#include + +void vDprintf(int level, const char* fmt, va_list ap) +{ + if (level > log_level) + return; + + if (!is_daemon) { + char logbuf[256]; + logbuf[255] = 0; + time_t clock; + struct tm *local_tm; + time(&clock); + local_tm = localtime (&clock); + int l = strftime(logbuf, sizeof(logbuf)-1, "%F %T ", local_tm); + vsnprintf(logbuf + l, sizeof(logbuf) - l - 1, fmt, ap); + printf("%s\n", logbuf); + } + else { + vsyslog((level <= LOG_LEVEL_INFO) ? LOG_INFO : LOG_DEBUG, fmt, ap); + } +} + +void Dprintf(int level, const char *fmt, ...) +{ + va_list ap; + va_start(ap, fmt); + vDprintf(level, fmt, ap); + va_end(ap); +} diff --git a/netif_utils.c b/netif_utils.c new file mode 100644 index 0000000..a14e0c3 --- /dev/null +++ b/netif_utils.c @@ -0,0 +1,141 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#include "netif_utils.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "log.h" + + + +int netsock = -1; + +int netsock_init(void) +{ + LOG(""); + netsock = socket(AF_INET, SOCK_DGRAM, 0); + if (netsock < 0) { + ERROR("Couldn't open inet socket for ioctls: %m\n"); + return -1; + } + return 0; +} + +int get_hwaddr(char *ifname, unsigned char *hwaddr) +{ + struct ifreq ifr; + memset(&ifr, 0, sizeof(ifr)); + strncpy(ifr.ifr_name, ifname, IFNAMSIZ); + if (ioctl(netsock, SIOCGIFHWADDR, &ifr) < 0) { + ERROR("%s: get hw address failed: %m", ifname); + return -1; + } + memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN); + return 0; +} + +int ethtool_get_speed_duplex(char *ifname, int *speed, int *duplex) +{ + struct ifreq ifr; + memset(&ifr, 0, sizeof(ifr)); + strncpy(ifr.ifr_name, ifname, IFNAMSIZ); + struct ethtool_cmd ecmd; + + ecmd.cmd = ETHTOOL_GSET; + ifr.ifr_data = (caddr_t)&ecmd; + if (ioctl(netsock, SIOCETHTOOL, &ifr) < 0) { + ERROR("Cannot get link status for %s: %m\n", ifname); + return -1; + } + *speed = ecmd.speed; /* Ethtool speed is in Mbps */ + *duplex = ecmd.duplex; /* We have same convention as ethtool. + 0 = half, 1 = full */ + return 0; +} + + +/********* Sysfs based utility functions *************/ + +/* This sysfs stuff might break with interface renames */ +int is_bridge(char *if_name) +{ + char path[32 + IFNAMSIZ]; + sprintf(path, "/sys/class/net/%s/bridge", if_name); + return (access(path, R_OK) == 0); +} + +/* This will work even less if the bridge port is renamed after being + joined to the bridge. +*/ +int is_bridge_slave(char *br_name, char *if_name) +{ + char path[32 + 2 * IFNAMSIZ]; + sprintf(path, "/sys/class/net/%s/brif/%s", br_name, if_name); + return (access(path, R_OK) == 0); +} + +int get_bridge_portno(char *if_name) +{ + char path[32 + IFNAMSIZ]; + sprintf(path, "/sys/class/net/%s/brport/port_no", if_name); + char buf[128]; + int fd; + long res = -1; + TSTM((fd = open(path, O_RDONLY)) >= 0, -1, "%m"); + int l; + TSTM((l = read(fd, buf, sizeof(buf) - 1)) >= 0, -1, "%m"); + if (l == 0) { + ERROR("Empty port index file"); + goto out; + } + else if (l == sizeof(buf) - 1) { + ERROR("port_index file too long"); + goto out; + } + buf[l] = 0; + if (buf[l-1] == '\n') + buf[l-1] = 0; + char *end; + res = strtoul(buf, &end, 0); + if (*end != 0 || res > INT_MAX) { + ERROR("Invalid port index %s", buf); + res = -1; + } + out: + close(fd); + return res; +} diff --git a/netif_utils.h b/netif_utils.h new file mode 100644 index 0000000..99c99d5 --- /dev/null +++ b/netif_utils.h @@ -0,0 +1,42 @@ +/***************************************************************************** + Copyright (c) 2006 EMC Corporation. + + This program 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 of the License, or (at your option) + any later version. + + This program 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 + this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Authors: Srinivas Aji + +******************************************************************************/ + +#ifndef NETIF_UTILS_H +#define NETIF_UTILS_H + +/* An inet socket for everyone to use for ifreqs. */ +int netsock_init(void); + +int get_hwaddr(char *ifname, unsigned char *hwaddr); + +int ethtool_get_speed_duplex(char *ifname, int *speed, int *duplex); + +/********* Sysfs based utility functions *************/ +int is_bridge(char *if_name); + +int is_bridge_slave(char *br_name, char *if_name); + +int get_bridge_portno(char *if_name); + +#endif diff --git a/rstp.spec b/rstp.spec new file mode 100644 index 0000000..5680985 --- /dev/null +++ b/rstp.spec @@ -0,0 +1,63 @@ +Summary: RSTP daemon +Name: rstp +Version: %{VERSION} +Release: %{BUILD} +License: LGPL, GPL +URL: http://www.rainfinity.com/ +Vendor: Rainfinity +Packager: Rainfinity +Source0: rstp-%{VERSION}.tgz +Group: Network/Admin +#Requires: bridge-utils = 1.0.4-4 + + +%description +Bridge init script for RainStorage + +%prep + +%setup -q + +%build +make + +%install +make install INSTALLPREFIX=$RPM_BUILD_ROOT + +%pre + +%post + +%preun + +%postun + +%clean +rm -rf $RPM_BUILD_ROOT + +%files +%defattr(-,root,root) +/sbin +/usr/share/man/man8 + +%changelog +* Mon Oct 30 2006 Srinivas Aji +- version 0.16, Don't define STRONGLY_SPEC_802_1_W, not helping much +- Fix logging to go through syslog + +* Fri Oct 20 2006 Srinivas Aji +- version 0.15, fixes based on second round of UNH testing, 802.1w +- rstpctl syntax changes, list all bridges, ports of a bridge + +* Wed Sep 13 2006 Srinivas Aji +- version 0.14, small fixes. fix an fd leak. + +* Tue Sep 5 2006 Srinivas Aji +- version 0.13, Use netlink patch to send/recv BPDUs, instead of LLC +- Some fixes based on first round of UNH testing + +* Sun Aug 20 2006 Srinivas Aji +- version 0.12, some bugfixes, added man pages. + +* Thu Aug 10 2006 Srinivas Aji +- Initial build. diff --git a/rstpctl.8 b/rstpctl.8 new file mode 100644 index 0000000..456a879 --- /dev/null +++ b/rstpctl.8 @@ -0,0 +1,146 @@ +.TH RSTPCTL 8 "August 20, 2006" "" "" +.SH NAME +rstpctl \- rstpd spanning tree protocol administration +.SH SYNOPSIS +.BR "rstpctl [command]" +.SH DESCRIPTION +.B rstpctl +is used to set up, maintain, and inspect the bridge RSTP +configuration for ethernet bridges as implemented using +.BR rstpd (8). +.BR rstpd +implements the spanning tree algorithm specified by the Rapid Spanning +Tree Protocol (RSTP). An implementation of the original Spanning Tree +Protocol (STP) is provided by the Linux kernel bridging code and can +be enabled and controlled using the +.BR "brctl" +command. + +.SH COMMANDS + +.B rstpctl rstp {on|off} +configures whether rstpd implements RSTP (Rapid Spanning Tree +Protocol) for the specified bridge. The remaining commands are +applicable only if rstpd is configured to run RSTP on that bridge. + +.B rstpctl showbridge [ ... ] +displays the spanning tree configuration and status for the specified +bridges. If no bridges are given, it displays the information for all +bridges. + +.B rstpctl showport [ ... ] +displays, as one line per port, the spanning tree configuration and +status for the specified ports. If no ports are specified, it displays +the information for all ports of the bridge. + +The format of the line is : +.br +.B "pes name iiii sss rrrr-rootbridgeid dddd-desgbridgeid dprt R" +.br +where the following abbreviations are used. + +\fBp\fR: '*' if the port link is not point to point, ' ' otherwise. +.br +\fBe\fR: 'E' if the port is operating as an edge port, ' ' otherwise. +.br +\fBs\fR: 's' if the port is in STP (slow) mode, ' ' otherwise. +.br +\fBname\fR: The name of the port, i.e, the network interface name. +.br +\fBiiii\fR: The port id, containing the port priority and port number +.br +\fBsss\fR: The port state, one of Dis (disabled), Blk (blocking), Lrn +(learning), Fwd (forwading), Non (non-stp), Unk (unknown). +.br +\fBrrrr-rootbridgeid\fR: Root bridge id, including priority. +.br +\fBdddd-desgbridgeid\fR: Designated bridge id, including priority +.br +\fBdprt\fR: Designated port id +.br +\fBR\fR: Port role, one of 'A' (alternate), 'B' (backup), 'R' (root), 'D' +(designated), '-' (non-stp) + + +.B rstpctl showportdetail [ ... ] +displays the spanning tree configuration and status for the specified +ports much more verbosely. If no ports are specified, it displays the +information for all ports of the bridge. + +.B rstpctl setbridgestate {on|off} +enables/disables the operation of RSTP. When RSTP is configured with +the +.BR rstp +subcommand listed above, the default is enabled. + +.B rstpctl setbridgeprio +sets the bridge's priority to . The priority value is a +number between 0 and 61440 in steps of 4096, and defaults to 32768. +Lower priority values are 'better'. The bridge with the lowest +priority will be elected 'root bridge'. + +.B rstpctl sethello