initial pass at removing bsd and code related to using bsd nodes

This commit is contained in:
Blake J. Harnden 2018-03-07 12:54:19 -08:00
parent 4858151d7c
commit bc1e3e70c9
62 changed files with 720 additions and 18008 deletions

View file

@ -31,7 +31,6 @@ EXTRA_DIST = bootstrap.sh LICENSE \
README-Xen Changelog kernel \
python-prefix.py revision.sh \
.version .version.date \
packaging/bsd \
packaging/deb/compat \
packaging/deb/copyright \
packaging/deb/changelog \
@ -55,7 +54,6 @@ MAINTAINERCLEANFILES = \
# don't include svn dirs in source tarball
dist-hook:
rm -rf `find $(distdir)/kernel -name .svn`
rm -rf $(distdir)/packaging/bsd/.svn
# build a source RPM
.PHONY: rpm

View file

@ -7,16 +7,17 @@
# Bootstrap the autoconf system.
#
if [ x$1 = x ]; then # PASS
# PASS
if [ x$1 = x ]; then
echo "Bootstrapping the autoconf system..."
# echo " These autotools programs should be installed for this script to work:"
# echo " aclocal, libtoolize, autoheader, automake, autoconf"
echo "(Messages below about copying and installing files are normal.)"
elif [ x$1 = xclean ]; then # clean - take out the trash
# clean - take out the trash
elif [ x$1 = xclean ]; then
echo "Cleaning up the autoconf mess..."
rm -rf autom4te.cache config BSDmakefile
rm -rf autom4te.cache config
exit 0;
else # help text
# help text
else
echo "usage: $0 [clean]"
echo -n " Use this script to bootstrap the autoconf build system prior to "
echo "running the "
@ -29,15 +30,6 @@ if ! [ -d "config" ]; then
mkdir config
fi
# on FreeBSD, discourage use of make
UNAME=`uname`
if [ x${UNAME} = xFreeBSD ]; then
echo "all:" > BSDmakefile
echo ' @echo "Please use GNU make instead by typing:"' >> BSDmakefile
echo ' @echo " gmake"' >> BSDmakefile
echo ' @echo ""' >> BSDmakefile
fi
# bootstrapping
echo "(1/4) Running aclocal..." && aclocal -I config \
&& echo "(2/4) Running autoheader..." && autoheader \

View file

@ -104,7 +104,6 @@ AC_ARG_ENABLE([daemon],
AC_SUBST(enable_daemon)
if test "x$enable_daemon" = "xno"; then
want_python=no
want_bsd=no
want_linux_netns=no
fi
@ -211,18 +210,9 @@ if test "x$enable_daemon" = "xyes" ; then
fi
# Host-specific detection
want_linux_netns=no
want_bsd=no
if test `uname -s` = "FreeBSD"; then
want_bsd=yes
AC_CHECK_PROGS(gmake)
# FreeBSD fix for linking libev port below
CFLAGS="$CFLAGS -L/usr/local/lib"
else
want_linux_netns=yes
fi
want_linux_netns=yes
if test "x$want_python" = "xno"; then
want_bsd=no
want_linux_netns=no
fi
@ -283,17 +273,6 @@ if test "x$want_linux_netns" = "xyes"; then
AC_MSG_ERROR([Could not locate tc (from iproute package).])
fi
fi
if test "x$want_bsd" = "xyes"; then
if test "x$ifconfig_path" = "xno" ; then
AC_MSG_ERROR([Could not locate the 'ifconfig' utility.])
fi
if test "x$ngctl_path" = "xno" ; then
AC_MSG_ERROR([Could not locate the 'ngctl' utility.])
fi
if test "x$vimage_path" = "xno" ; then
AC_MSG_ERROR([Could not locate the 'vimage' utility.])
fi
fi
AC_ARG_WITH([startup],
[AS_HELP_STRING([--with-startup=option],
@ -306,7 +285,6 @@ AC_MSG_RESULT([using startup option $with_startup])
# Variable substitutions
AM_CONDITIONAL(WANT_GUI, test x$enable_gui = xyes)
AM_CONDITIONAL(WANT_DAEMON, test x$enable_daemon = xyes)
AM_CONDITIONAL(WANT_BSD, test x$want_bsd = xyes)
AM_CONDITIONAL(WANT_DOCS, test x$want_docs = xyes)
AM_CONDITIONAL(WANT_PYTHON, test x$want_python = xyes)
AM_CONDITIONAL(WANT_NETNS, test x$want_linux_netns = xyes)
@ -370,19 +348,15 @@ ${PACKAGE_STRING} Configuration:
Features to build:
Python bindings: ${want_python}
Linux Namespaces emulation: ${want_linux_netns}
FreeBSD Jails emulation: ${want_bsd}
Documentation: ${want_docs}
------------------------------------------------------------------------"
if test "x${want_bsd}" = "xyes" ; then
# TODO: more sophisticated checks of gmake vs make
echo ">>> NOTE: on FreeBSD you should use 'gmake' instead of 'make'
------------------------------------------------------------------------"
fi
if test "x${want_linux_netns}" = "xyes" ; then
echo "On this platform you should run core-gui as a normal user.
------------------------------------------------------------------------"
fi
if test "x${progs_missing}" != "x" ; then
echo ">>> NOTE: the following programs could not be found:"
echo " $progs_missing

View file

@ -1,89 +0,0 @@
"""
netgraph.py: Netgraph helper functions; for now these are wrappers around
ngctl commands.
"""
import subprocess
from core import constants
from core.misc import utils
utils.check_executables([constants.NGCTL_BIN])
def createngnode(node_type, hookstr, name=None):
"""
Create a new Netgraph node of type and optionally assign name. The
hook string hookstr should contain two names. This is a string so
other commands may be inserted after the two names.
Return the name and netgraph ID of the new node.
:param node_type: node type to create
:param hookstr: hook string
:param name: name
:return: name and id
:rtype: tuple
"""
hook1 = hookstr.split()[0]
ngcmd = "mkpeer %s %s \n show .%s" % (node_type, hookstr, hook1)
cmd = [constants.NGCTL_BIN, "-f", "-"]
cmdid = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
# err will always be None
result, err = cmdid.communicate(input=ngcmd)
status = cmdid.wait()
if status > 0:
raise Exception("error creating Netgraph node %s (%s): %s" % (node_type, ngcmd, result))
results = result.split()
ngname = results[1]
ngid = results[5]
if name:
subprocess.check_call([constants.NGCTL_BIN, "name", "[0x%s]:" % ngid, name])
return ngname, ngid
def destroyngnode(name):
"""
Shutdown a Netgraph node having the given name.
:param str name: node name
:return: nothing
"""
subprocess.check_call([constants.NGCTL_BIN, "shutdown", "%s:" % name])
def connectngnodes(name1, name2, hook1, hook2):
"""
Connect two hooks of two Netgraph nodes given by their names.
:param str name1: name one
:param str name2: name two
:param str hook1: hook one
:param str hook2: hook two
:return: nothing
"""
node1 = "%s:" % name1
node2 = "%s:" % name2
subprocess.check_call([constants.NGCTL_BIN, "connect", node1, node2, hook1, hook2])
def ngmessage(name, msg):
"""
Send a Netgraph message to the node named name.
:param str name: node name
:param list msg: message
:return: nothing
"""
cmd = [constants.NGCTL_BIN, "msg", "%s:" % name] + msg
subprocess.check_call(cmd)
def ngloadkernelmodule(name):
"""
Load a kernel module by invoking kldstat. This is needed for the
ng_ether module which automatically creates Netgraph nodes when loaded.
:param str name: module name
:return: nothing
"""
utils.check_cmd(["kldload", name])

View file

@ -1,212 +0,0 @@
"""
nodes.py: definition of CoreNode classes and other node classes that inherit
from the CoreNode, implementing specific node types.
"""
import socket
import subprocess
from core import constants
from core import logger
from core.api import coreapi
from core.bsd.netgraph import connectngnodes
from core.bsd.netgraph import ngloadkernelmodule
from core.bsd.vnet import NetgraphNet
from core.bsd.vnet import NetgraphPipeNet
from core.bsd.vnode import JailNode
from core.enumerations import LinkTlvs
from core.enumerations import LinkTypes
from core.enumerations import NodeTypes
from core.enumerations import RegisterTlvs
from core.misc import ipaddress
from core.misc import utils
utils.check_executables([constants.IFCONFIG_BIN])
class CoreNode(JailNode):
apitype = NodeTypes.DEFAULT.value
class PtpNet(NetgraphPipeNet):
def tonodemsg(self, flags):
"""
Do not generate a Node Message for point-to-point links. They are
built using a link message instead.
"""
pass
def tolinkmsgs(self, flags):
"""
Build CORE API TLVs for a point-to-point link. One Link message
describes this network.
"""
tlvdata = ""
if len(self._netif) != 2:
return tlvdata
(if1, if2) = self._netif.items()
if1 = if1[1]
if2 = if2[1]
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.N1_NUMBER.value, if1.node.objid)
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.N2_NUMBER.value, if2.node.objid)
delay = if1.getparam("delay")
bw = if1.getparam("bw")
loss = if1.getparam("loss")
duplicate = if1.getparam("duplicate")
jitter = if1.getparam("jitter")
if delay is not None:
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.DELAY.value, delay)
if bw is not None:
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.BANDWIDTH.value, bw)
if loss is not None:
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.PER.value, str(loss))
if duplicate is not None:
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.DUP.value, str(duplicate))
if jitter is not None:
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.JITTER.value, jitter)
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.TYPE.value, self.linktype)
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.INTERFACE1_NUMBER.value, if1.node.getifindex(if1))
if if1.hwaddr:
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.INTERFACE1_MAC.value, if1.hwaddr)
for addr in if1.addrlist:
ip, sep, mask = addr.partition("/")
mask = int(mask)
if ipaddress.is_ipv4_address(ip):
family = socket.AF_INET
tlvtypeip = LinkTlvs.INTERFACE1_IP4.value
tlvtypemask = LinkTlvs.INTERFACE1_IP4_MASK
else:
family = socket.AF_INET6
tlvtypeip = LinkTlvs.INTERFACE1_IP6.value
tlvtypemask = LinkTlvs.INTERFACE1_IP6_MASK.value
ipl = socket.inet_pton(family, ip)
tlvdata += coreapi.CoreLinkTlv.pack(tlvtypeip, ipaddress.IpAddress(af=family, address=ipl))
tlvdata += coreapi.CoreLinkTlv.pack(tlvtypemask, mask)
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.INTERFACE2_NUMBER.value, if2.node.getifindex(if2))
if if2.hwaddr:
tlvdata += coreapi.CoreLinkTlv.pack(LinkTlvs.INTERFACE2_MAC.value, if2.hwaddr)
for addr in if2.addrlist:
ip, sep, mask = addr.partition("/")
mask = int(mask)
if ipaddress.is_ipv4_address(ip):
family = socket.AF_INET
tlvtypeip = LinkTlvs.INTERFACE2_IP4.value
tlvtypemask = LinkTlvs.INTERFACE2_IP4_MASK
else:
family = socket.AF_INET6
tlvtypeip = LinkTlvs.INTERFACE2_IP6.value
tlvtypemask = LinkTlvs.INTERFACE2_IP6_MASK.value
ipl = socket.inet_pton(family, ip)
tlvdata += coreapi.CoreLinkTlv.pack(tlvtypeip, ipaddress.IpAddress(af=family, address=ipl))
tlvdata += coreapi.CoreLinkTlv.pack(tlvtypemask, mask)
msg = coreapi.CoreLinkMessage.pack(flags, tlvdata)
return [msg, ]
class SwitchNode(NetgraphNet):
ngtype = "bridge"
nghooks = "link0 link0\nmsg .link0 setpersistent"
apitype = NodeTypes.SWITCH.value
policy = "ACCEPT"
class HubNode(NetgraphNet):
ngtype = "hub"
nghooks = "link0 link0\nmsg .link0 setpersistent"
apitype = NodeTypes.HUB.value
policy = "ACCEPT"
class WlanNode(NetgraphNet):
ngtype = "wlan"
nghooks = "anchor anchor"
apitype = NodeTypes.WIRELESS_LAN.value
linktype = LinkTypes.WIRELESS.value
policy = "DROP"
def __init__(self, session, objid=None, name=None, start=True, policy=None):
NetgraphNet.__init__(self, session, objid, name, start, policy)
# wireless model such as basic range
self.model = None
# mobility model such as scripted
self.mobility = None
def attach(self, netif):
NetgraphNet.attach(self, netif)
if self.model:
netif.poshook = self.model.position_callback
if netif.node is None:
return
x, y, z = netif.node.position.get()
netif.poshook(netif, x, y, z)
def setmodel(self, model, config):
"""
Mobility and wireless model.
:param core.mobility.WirelessModel.cls model: model to set
:param dict config: configuration for model
:return:
"""
logger.info("adding model %s" % model.name)
if model.config_type == RegisterTlvs.WIRELESS.value:
self.model = model(session=self.session, objid=self.objid, values=config)
if self.model.position_callback:
for netif in self.netifs():
netif.poshook = self.model.position_callback
if netif.node is not None:
x, y, z = netif.node.position.get()
netif.poshook(netif, x, y, z)
self.model.setlinkparams()
elif model.config_type == RegisterTlvs.MOBILITY.value:
self.mobility = model(session=self.session, objid=self.objid, values=config)
class RJ45Node(NetgraphPipeNet):
apitype = NodeTypes.RJ45.value
policy = "ACCEPT"
def __init__(self, session, objid, name, start=True):
if start:
ngloadkernelmodule("ng_ether")
NetgraphPipeNet.__init__(self, session, objid, name, start)
if start:
self.setpromisc(True)
def shutdown(self):
self.setpromisc(False)
NetgraphPipeNet.shutdown(self)
def setpromisc(self, promisc):
p = "promisc"
if not promisc:
p = "-" + p
subprocess.check_call([constants.IFCONFIG_BIN, self.name, "up", p])
def attach(self, netif):
if len(self._netif) > 0:
raise ValueError("RJ45 networks support at most 1 network interface")
NetgraphPipeNet.attach(self, netif)
connectngnodes(self.ngname, self.name, self.gethook(), "lower")
class TunnelNode(NetgraphNet):
ngtype = "pipe"
nghooks = "upper lower"
apitype = NodeTypes.TUNNEL.value
policy = "ACCEPT"
BSD_NODES = {
NodeTypes.DEFAULT: CoreNode,
NodeTypes.SWITCH: SwitchNode,
NodeTypes.HUB: HubNode,
NodeTypes.WIRELESS_LAN: WlanNode,
NodeTypes.RJ45: RJ45Node,
NodeTypes.TUNNEL: TunnelNode,
NodeTypes.PEER_TO_PEER: PtpNet,
NodeTypes.CONTROL_NET: None
}

View file

@ -1,206 +0,0 @@
"""
vnet.py: NetgraphNet and NetgraphPipeNet classes that implement virtual networks
using the FreeBSD Netgraph subsystem.
"""
from core import logger
from core.bsd.netgraph import connectngnodes
from core.bsd.netgraph import createngnode
from core.bsd.netgraph import destroyngnode
from core.bsd.netgraph import ngmessage
from core.coreobj import PyCoreNet
class NetgraphNet(PyCoreNet):
ngtype = None
nghooks = ()
def __init__(self, session, objid=None, name=None, start=True, policy=None):
PyCoreNet.__init__(self, session, objid, name)
if name is None:
name = str(self.objid)
if policy is not None:
self.policy = policy
self.name = name
self.ngname = "n_%s_%s" % (str(self.objid), self.session.session_id)
self.ngid = None
self._netif = {}
self._linked = {}
self.up = False
if start:
self.startup()
def startup(self):
tmp, self.ngid = createngnode(node_type=self.ngtype, hookstr=self.nghooks, name=self.ngname)
self.up = True
def shutdown(self):
if not self.up:
return
self.up = False
while self._netif:
k, netif = self._netif.popitem()
if netif.pipe:
pipe = netif.pipe
netif.pipe = None
pipe.shutdown()
else:
netif.shutdown()
self._netif.clear()
self._linked.clear()
del self.session
destroyngnode(self.ngname)
def attach(self, netif):
"""
Attach an interface to this netgraph node. Create a pipe between
the interface and the hub/switch/wlan node.
(Note that the PtpNet subclass overrides this method.)
"""
if self.up:
pipe = self.session.addobj(cls=NetgraphPipeNet, start=True)
pipe.attach(netif)
hook = "link%d" % len(self._netif)
pipe.attachnet(self, hook)
PyCoreNet.attach(self, netif)
def detach(self, netif):
PyCoreNet.detach(self, netif)
def linked(self, netif1, netif2):
# check if the network interfaces are attached to this network
if self._netif[netif1] != netif1:
raise ValueError("inconsistency for netif %s" % netif1.name)
if self._netif[netif2] != netif2:
raise ValueError("inconsistency for netif %s" % netif2.name)
try:
linked = self._linked[netif1][netif2]
except KeyError:
linked = False
self._linked[netif1][netif2] = linked
return linked
def unlink(self, netif1, netif2):
if not self.linked(netif1, netif2):
return
msg = ["unlink", "{", "node1=0x%s" % netif1.pipe.ngid]
msg += ["node2=0x%s" % netif2.pipe.ngid, "}"]
ngmessage(self.ngname, msg)
self._linked[netif1][netif2] = False
def link(self, netif1, netif2):
if self.linked(netif1, netif2):
return
msg = ["link", "{", "node1=0x%s" % netif1.pipe.ngid]
msg += ["node2=0x%s" % netif2.pipe.ngid, "}"]
ngmessage(self.ngname, msg)
self._linked[netif1][netif2] = True
def linknet(self, net):
"""
Link this bridge with another by creating a veth pair and installing
each device into each bridge.
"""
raise NotImplementedError
def linkconfig(self, netif, bw=None, delay=None,
loss=None, duplicate=None, jitter=None, netif2=None):
"""
Set link effects by modifying the pipe connected to an interface.
"""
if not netif.pipe:
logger.warn("linkconfig for %s but interface %s has no pipe", self.name, netif.name)
return
return netif.pipe.linkconfig(netif, bw, delay, loss, duplicate, jitter, netif2)
class NetgraphPipeNet(NetgraphNet):
ngtype = "pipe"
nghooks = "upper lower"
def __init__(self, session, objid=None, name=None, start=True, policy=None):
NetgraphNet.__init__(self, session, objid, name, start, policy)
if start:
# account for Ethernet header
ngmessage(self.ngname, ["setcfg", "{", "header_offset=14", "}"])
def attach(self, netif):
"""
Attach an interface to this pipe node.
The first interface is connected to the "upper" hook, the second
connected to the "lower" hook.
"""
if len(self._netif) > 1:
raise ValueError("Netgraph pipes support at most 2 network interfaces")
if self.up:
hook = self.gethook()
connectngnodes(self.ngname, netif.localname, hook, netif.hook)
if netif.pipe:
raise ValueError("Interface %s already attached to pipe %s" % (netif.name, netif.pipe.name))
netif.pipe = self
self._netif[netif] = netif
self._linked[netif] = {}
def attachnet(self, net, hook):
"""
Attach another NetgraphNet to this pipe node.
"""
localhook = self.gethook()
connectngnodes(self.ngname, net.ngname, localhook, hook)
def gethook(self):
"""
Returns the first hook (e.g. "upper") then the second hook
(e.g. "lower") based on the number of connections.
"""
hooks = self.nghooks.split()
if len(self._netif) == 0:
return hooks[0]
else:
return hooks[1]
def linkconfig(self, netif, bw=None, delay=None,
loss=None, duplicate=None, jitter=None, netif2=None):
"""
Set link effects by sending a Netgraph setcfg message to the pipe.
"""
netif.setparam("bw", bw)
netif.setparam("delay", delay)
netif.setparam("loss", loss)
netif.setparam("duplicate", duplicate)
netif.setparam("jitter", jitter)
if not self.up:
return
params = []
upstream = []
downstream = []
if bw is not None:
if str(bw) == "0":
bw = "-1"
params += ["bandwidth=%s" % bw, ]
if delay is not None:
if str(delay) == "0":
delay = "-1"
params += ["delay=%s" % delay, ]
if loss is not None:
if str(loss) == "0":
loss = "-1"
upstream += ["BER=%s" % loss, ]
downstream += ["BER=%s" % loss, ]
if duplicate is not None:
if str(duplicate) == "0":
duplicate = "-1"
upstream += ["duplicate=%s" % duplicate, ]
downstream += ["duplicate=%s" % duplicate, ]
if jitter:
logger.warn("jitter parameter ignored for link %s", self.name)
if len(params) > 0 or len(upstream) > 0 or len(downstream) > 0:
setcfg = ["setcfg", "{", ] + params
if len(upstream) > 0:
setcfg += ["upstream={", ] + upstream + ["}", ]
if len(downstream) > 0:
setcfg += ["downstream={", ] + downstream + ["}", ]
setcfg += ["}", ]
ngmessage(self.ngname, setcfg)

View file

@ -1,386 +0,0 @@
"""
vnode.py: SimpleJailNode and JailNode classes that implement the FreeBSD
jail-based virtual node.
"""
import os
import subprocess
import threading
from core import constants
from core import logger
from core.bsd.netgraph import createngnode
from core.bsd.netgraph import destroyngnode
from core.coreobj import PyCoreNetIf
from core.coreobj import PyCoreNode
from core.misc import utils
utils.check_executables([constants.IFCONFIG_BIN, constants.VIMAGE_BIN])
class VEth(PyCoreNetIf):
def __init__(self, node, name, localname, mtu=1500, net=None,
start=True):
PyCoreNetIf.__init__(self, node=node, name=name, mtu=mtu)
# name is the device name (e.g. ngeth0, ngeth1, etc.) before it is
# installed in a node; the Netgraph name is renamed to localname
# e.g. before install: name = ngeth0 localname = n0_0_123
# after install: name = eth0 localname = n0_0_123
self.localname = localname
self.ngid = None
self.net = None
self.pipe = None
self.addrlist = []
self.hwaddr = None
self.up = False
self.hook = "ether"
if start:
self.startup()
def startup(self):
hookstr = "%s %s" % (self.hook, self.hook)
ngname, ngid = createngnode(node_type="eiface", hookstr=hookstr, name=self.localname)
self.name = ngname
self.ngid = ngid
subprocess.check_call([constants.IFCONFIG_BIN, ngname, "up"])
self.up = True
def shutdown(self):
if not self.up:
return
destroyngnode(self.localname)
self.up = False
def attachnet(self, net):
if self.net:
self.detachnet()
self.net = None
net.attach(self)
self.net = net
def detachnet(self):
if self.net is not None:
self.net.detach(self)
def addaddr(self, addr):
self.addrlist.append(addr)
def deladdr(self, addr):
self.addrlist.remove(addr)
def sethwaddr(self, addr):
self.hwaddr = addr
class TunTap(PyCoreNetIf):
"""
TUN/TAP virtual device in TAP mode
"""
def __init__(self, node, name, localname, mtu=None, net=None, start=True):
raise NotImplementedError
class SimpleJailNode(PyCoreNode):
def __init__(self, session, objid=None, name=None, nodedir=None):
PyCoreNode.__init__(self, session, objid, name)
self.nodedir = nodedir
self.pid = None
self.up = False
self.lock = threading.RLock()
self._mounts = []
def startup(self):
if self.up:
raise Exception("already up")
vimg = [constants.VIMAGE_BIN, "-c", self.name]
try:
os.spawnlp(os.P_WAIT, constants.VIMAGE_BIN, *vimg)
except OSError:
raise Exception("vimage command not found while running: %s" % vimg)
logger.info("bringing up loopback interface")
self.cmd([constants.IFCONFIG_BIN, "lo0", "127.0.0.1"])
logger.info("setting hostname: %s", self.name)
self.cmd(["hostname", self.name])
self.cmd([constants.SYSCTL_BIN, "vfs.morphing_symlinks=1"])
self.up = True
def shutdown(self):
if not self.up:
return
for netif in self.netifs():
netif.shutdown()
self._netif.clear()
del self.session
vimg = [constants.VIMAGE_BIN, "-d", self.name]
try:
os.spawnlp(os.P_WAIT, constants.VIMAGE_BIN, *vimg)
except OSError:
raise Exception("vimage command not found while running: %s" % vimg)
self.up = False
def cmd(self, args, wait=True):
if wait:
mode = os.P_WAIT
else:
mode = os.P_NOWAIT
tmp = subprocess.call([constants.VIMAGE_BIN, self.name] + args, cwd=self.nodedir)
if not wait:
tmp = None
if tmp:
logger.warn("cmd exited with status %s: %s", tmp, str(args))
return tmp
def cmdresult(self, args, wait=True):
cmdid, cmdin, cmdout, cmderr = self.popen(args)
result = cmdout.read()
result += cmderr.read()
cmdin.close()
cmdout.close()
cmderr.close()
if wait:
status = cmdid.wait()
else:
status = 0
return status, result
def popen(self, args):
cmd = [constants.VIMAGE_BIN, self.name]
cmd.extend(args)
tmp = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=self.nodedir)
return tmp, tmp.stdin, tmp.stdout, tmp.stderr
def icmd(self, args):
return os.spawnlp(os.P_WAIT, constants.VIMAGE_BIN, constants.VIMAGE_BIN, self.name, *args)
def term(self, sh="/bin/sh"):
return os.spawnlp(os.P_WAIT, "xterm", "xterm", "-ut",
"-title", self.name, "-e", constants.VIMAGE_BIN, self.name, sh)
def termcmdstring(self, sh="/bin/sh"):
"""
We add "sudo" to the command string because the GUI runs as a
normal user.
"""
return "cd %s && sudo %s %s %s" % (self.nodedir, constants.VIMAGE_BIN, self.name, sh)
def shcmd(self, cmdstr, sh="/bin/sh"):
return self.cmd([sh, "-c", cmdstr])
def boot(self):
pass
def mount(self, source, target):
source = os.path.abspath(source)
logger.info("mounting %s at %s", source, target)
self.addsymlink(path=target, file=None)
def umount(self, target):
logger.info("unmounting %s", target)
def newveth(self, ifindex=None, ifname=None, net=None):
self.lock.acquire()
try:
if ifindex is None:
ifindex = self.newifindex()
if ifname is None:
ifname = "eth%d" % ifindex
sessionid = self.session.short_session_id()
name = "n%s_%s_%s" % (self.objid, ifindex, sessionid)
localname = name
ifclass = VEth
veth = ifclass(node=self, name=name, localname=localname,
mtu=1500, net=net, start=self.up)
if self.up:
# install into jail
subprocess.check_call([constants.IFCONFIG_BIN, veth.name, "vnet", self.name])
# rename from "ngeth0" to "eth0"
self.cmd([constants.IFCONFIG_BIN, veth.name, "name", ifname])
veth.name = ifname
try:
self.addnetif(veth, ifindex)
except:
veth.shutdown()
del veth
raise
return ifindex
finally:
self.lock.release()
def sethwaddr(self, ifindex, addr):
self._netif[ifindex].sethwaddr(addr)
if self.up:
self.cmd([constants.IFCONFIG_BIN, self.ifname(ifindex), "link", str(addr)])
def addaddr(self, ifindex, addr):
if self.up:
if ":" in addr:
family = "inet6"
else:
family = "inet"
self.cmd([constants.IFCONFIG_BIN, self.ifname(ifindex), family, "alias", str(addr)])
self._netif[ifindex].addaddr(addr)
def deladdr(self, ifindex, addr):
try:
self._netif[ifindex].deladdr(addr)
except ValueError:
logger.warn("trying to delete unknown address: %s", addr)
if self.up:
if ":" in addr:
family = "inet6"
else:
family = "inet"
self.cmd([constants.IFCONFIG_BIN, self.ifname(ifindex), family, "-alias",
str(addr)])
valid_deladdrtype = ("inet", "inet6", "inet6link")
def delalladdr(self, ifindex, addrtypes=valid_deladdrtype):
addr = self.getaddr(self.ifname(ifindex), rescan=True)
for t in addrtypes:
if t not in self.valid_deladdrtype:
raise ValueError("addr type must be in: " + " ".join(self.valid_deladdrtype))
for a in addr[t]:
self.deladdr(ifindex, a)
# update cached information
self.getaddr(self.ifname(ifindex), rescan=True)
def ifup(self, ifindex):
if self.up:
self.cmd([constants.IFCONFIG_BIN, self.ifname(ifindex), "up"])
def newnetif(self, net=None, addrlist=[], hwaddr=None,
ifindex=None, ifname=None):
self.lock.acquire()
try:
ifindex = self.newveth(ifindex=ifindex, ifname=ifname, net=net)
if net is not None:
self.attachnet(ifindex, net)
if hwaddr:
self.sethwaddr(ifindex, hwaddr)
for addr in utils.make_tuple(addrlist):
self.addaddr(ifindex, addr)
self.ifup(ifindex)
return ifindex
finally:
self.lock.release()
def attachnet(self, ifindex, net):
self._netif[ifindex].attachnet(net)
def detachnet(self, ifindex):
self._netif[ifindex].detachnet()
def addfile(self, srcname, filename):
shcmd = 'mkdir -p $(dirname "%s") && mv "%s" "%s" && sync' % (filename, srcname, filename)
self.shcmd(shcmd)
def getaddr(self, ifname, rescan=False):
return None
def addsymlink(self, path, file):
"""
Create a symbolic link from /path/name/file ->
/tmp/pycore.nnnnn/@.conf/path.name/file
"""
dirname = path
if dirname and dirname[0] == "/":
dirname = dirname[1:]
dirname = dirname.replace("/", ".")
if file:
pathname = os.path.join(path, file)
sym = os.path.join(self.session.session_dir, "@.conf", dirname, file)
else:
pathname = path
sym = os.path.join(self.session.session_dir, "@.conf", dirname)
if os.path.islink(pathname):
if os.readlink(pathname) == sym:
# this link already exists - silently return
return
os.unlink(pathname)
else:
if os.path.exists(pathname):
logger.warn("did not create symlink for %s since path exists on host", pathname)
return
logger.info("creating symlink %s -> %s", pathname, sym)
os.symlink(sym, pathname)
class JailNode(SimpleJailNode):
def __init__(self, session, objid=None, name=None, nodedir=None, bootsh="boot.sh", start=True):
super(JailNode, self).__init__(session=session, objid=objid, name=name, nodedir=nodedir)
self.bootsh = bootsh
if not start:
return
# below here is considered node startup/instantiation code
self.makenodedir()
self.startup()
def boot(self):
self.session.services.bootnodeservices(self)
def validate(self):
self.session.services.validatenodeservices(self)
def startup(self):
self.lock.acquire()
try:
super(JailNode, self).startup()
# self.privatedir("/var/run")
# self.privatedir("/var/log")
finally:
self.lock.release()
def shutdown(self):
if not self.up:
return
self.lock.acquire()
# services are instead stopped when session enters datacollect state
# self.session.services.stopnodeservices(self)
try:
super(JailNode, self).shutdown()
finally:
self.rmnodedir()
self.lock.release()
def privatedir(self, path):
if path[0] != "/":
raise ValueError, "path not fully qualified: " + path
hostpath = os.path.join(
self.nodedir,
os.path.normpath(path).strip("/").replace("/", ".")
)
try:
os.mkdir(hostpath)
except OSError:
pass
except Exception, e:
raise Exception, e
self.mount(hostpath, path)
def opennodefile(self, filename, mode="w"):
dirname, basename = os.path.split(filename)
# self.addsymlink(path=dirname, file=basename)
if not basename:
raise ValueError("no basename for filename: %s" % filename)
if dirname and dirname[0] == "/":
dirname = dirname[1:]
dirname = dirname.replace("/", ".")
dirname = os.path.join(self.nodedir, dirname)
if not os.path.isdir(dirname):
os.makedirs(dirname, mode=0755)
hostfilename = os.path.join(dirname, basename)
return open(hostfilename, mode)
def nodefile(self, filename, contents, mode=0644):
f = self.opennodefile(filename, "w")
f.write(contents)
os.chmod(f.name, mode)
f.close()
logger.info("created nodefile: %s; mode: 0%o", f.name, mode)

View file

@ -87,9 +87,7 @@ class CoreServices(ConfigurableManager):
name = "services"
config_type = RegisterTlvs.UTILITY.value
_invalid_custom_names = (
'core', 'api', 'bsd', 'emane', 'misc', 'netns', 'phys', 'services', 'xen'
)
_invalid_custom_names = ('core', 'api', 'emane', 'misc', 'netns', 'phys', 'services', 'xen')
def __init__(self, session):
"""

View file

@ -298,8 +298,7 @@ class OlsrOrg(NrlService):
#######################################
### Linux specific OLSRd extensions ###
#######################################
# these parameters are only working on linux at the moment, but might become
# useful on BSD in the future
# these parameters are only working on linux at the moment
# SrcIpRoutes tells OLSRd to set the Src flag of host routes to the originator-ip
# of the node. In addition to this an additional localhost device is created
@ -516,7 +515,7 @@ LinkQualityFishEye 0
# - /lib, followed by /usr/lib
#
# the examples in this list are for linux, so check if the plugin is
# available if you use windows/BSD.
# available if you use windows.
# each plugin should have a README file in it's lib subfolder
# LoadPlugin "olsrd_txtinfo.dll"

View file

@ -40,10 +40,8 @@ class IPForwardService(UtilService):
def generateconfig(cls, node, filename, services):
if os.uname()[0] == "Linux":
return cls.generateconfiglinux(node, filename, services)
elif os.uname()[0] == "FreeBSD":
return cls.generateconfigbsd(node, filename, services)
else:
raise Exception, "unknown platform"
raise Exception("unknown platform")
@classmethod
def generateconfiglinux(cls, node, filename, services):
@ -67,17 +65,6 @@ class IPForwardService(UtilService):
cfg += "%s -w net.ipv4.conf.%s.rp_filter=0\n" % (constants.SYSCTL_BIN, name)
return cfg
@classmethod
def generateconfigbsd(cls, node, filename, services):
return """\
#!/bin/sh
# auto-generated by IPForward service (utility.py)
%s -w net.inet.ip.forwarding=1
%s -w net.inet6.ip6.forwarding=1
%s -w net.inet.icmp.bmcastecho=1
%s -w net.inet.icmp.icmplim=0
""" % (constants.SYSCTL_BIN, constants.SYSCTL_BIN, constants.SYSCTL_BIN, constants.SYSCTL_BIN)
class DefaultRouteService(UtilService):
_name = "DefaultRoute"
@ -108,10 +95,8 @@ class DefaultRouteService(UtilService):
else:
if os.uname()[0] == "Linux":
rtcmd = "ip route add default via"
elif os.uname()[0] == "FreeBSD":
rtcmd = "route add -%s" % fam
else:
raise Exception, "unknown platform"
raise Exception("unknown platform")
return "%s %s" % (rtcmd, net.min_addr())
@ -132,10 +117,8 @@ class DefaultMulticastRouteService(UtilService):
continue
if os.uname()[0] == "Linux":
rtcmd = "ip route add 224.0.0.0/4 dev"
elif os.uname()[0] == "FreeBSD":
rtcmd = "route add 224.0.0.0/4 -iface"
else:
raise Exception, "unknown platform"
raise Exception("unknown platform")
cfg += "%s %s\n" % (rtcmd, ifc.name)
cfg += "\n"
break
@ -176,21 +159,15 @@ class StaticRouteService(UtilService):
else:
if os.uname()[0] == "Linux":
rtcmd = "#/sbin/ip route add %s via" % dst
elif os.uname()[0] == "FreeBSD":
rtcmd = "#/sbin/route add -%s %s" % (fam, dst)
else:
raise Exception, "unknown platform"
raise Exception("unknown platform")
return "%s %s" % (rtcmd, net.min_addr())
class SshService(UtilService):
_name = "SSH"
if os.uname()[0] == "FreeBSD":
_configs = ("startsshd.sh", "sshd_config",)
_dirs = ()
else:
_configs = ("startsshd.sh", "/etc/ssh/sshd_config",)
_dirs = ("/etc/ssh", "/var/run/sshd",)
_configs = ("startsshd.sh", "/etc/ssh/sshd_config",)
_dirs = ("/etc/ssh", "/var/run/sshd",)
_startup = ("sh startsshd.sh",)
_shutdown = ("killall sshd",)
_validate = ()
@ -201,14 +178,9 @@ class SshService(UtilService):
Use a startup script for launching sshd in order to wait for host
key generation.
"""
if os.uname()[0] == "FreeBSD":
sshcfgdir = node.nodedir
sshstatedir = node.nodedir
sshlibdir = "/usr/libexec"
else:
sshcfgdir = cls._dirs[0]
sshstatedir = cls._dirs[1]
sshlibdir = "/usr/lib/openssh"
sshcfgdir = cls._dirs[0]
sshstatedir = cls._dirs[1]
sshlibdir = "/usr/lib/openssh"
if filename == "startsshd.sh":
return """\
#!/bin/sh

View file

@ -933,7 +933,7 @@ class Session(object):
"""
with self._objects_lock:
for obj in self.objects.itervalues():
# TODO: PyCoreNode is not the type to check, but there are two types, due to bsd and netns
# TODO: PyCoreNode is not the type to check
if isinstance(obj, nodes.PyCoreNode) and not nodeutils.is_node(obj, NodeTypes.RJ45):
# add a control interface if configured
logger.info("booting node: %s - %s", obj.objid, obj.name)

View file

@ -319,12 +319,6 @@ if __name__ == "__main__":
nodeutils.update_node_map(OVS_NODES)
# update with BSD based nodes
if os.uname()[0] == "FreeBSD":
from core.bsd.nodes import BSD_NODES
nodeutils.update_node_map(BSD_NODES)
# load default services
services.load()

View file

@ -4,8 +4,6 @@
.. |CENTOSVERSION| replace:: 6.x or 7.x
.. |BSDVERSION| replace:: 9.0
.. |CORERPM| replace:: 1.fc20.x86_64.rpm
.. |CORERPM2| replace:: 1.fc20.noarch.rpm
.. |COREDEB| replace:: 0ubuntu1_precise_amd64.deb

View file

@ -39,10 +39,6 @@ These are being actively developed as of CORE |version|:
* *doc* - Documentation for the manual lives here in reStructuredText format.
* *packaging* - Control files and script for building CORE packages are here.
These directories are not so actively developed:
* *kernel* - patches and modules mostly related to FreeBSD.
.. _The_CORE_API:
The CORE API
@ -59,8 +55,7 @@ The GUI communicates with the CORE daemon using the API. One emulation server
communicates with another using the API. The API also allows other systems to
interact with the CORE emulation. The API allows another system to add, remove,
or modify nodes and links, and enables executing commands on the emulated
systems. On FreeBSD, the API is used for enhancing the wireless LAN
calculations. Wireless link parameters are updated on-the-fly based on node
systems. Wireless link parameters are updated on-the-fly based on node
positions.
CORE listens on a local TCP port for API messages. The other system could be
@ -184,151 +179,3 @@ Below is a transcript of creating two emulated nodes and connecting them togethe
The above example script can be found as :file:`twonodes.sh` in the
:file:`examples/netns` directory. Use *core-cleanup* to clean up after the
script.
.. _FreeBSD_Commands:
FreeBSD Commands
================
.. index:: vimage
.. index:: ngctl
.. index:: Netgraph
.. _FreeBSD_Kernel_Commands:
FreeBSD Kernel Commands
-----------------------
The FreeBSD kernel emulation controlled by CORE is realized through several
userspace commands. The CORE GUI itself could be thought of as a glorified
script that dispatches these commands to build and manage the kernel emulation.
* **vimage** - the vimage command, short for "virtual image", is used to
create lightweight virtual machines and execute commands within the virtual
image context. On a FreeBSD CORE machine, see the *vimage(8)* man page for
complete details. The vimage command comes from the VirtNet project which
virtualizes the FreeBSD network stack.
* **ngctl** - the ngctl command, short for "netgraph control", creates
Netgraph nodes and hooks, connects them together, and allows for various
interactions with the Netgraph nodes. See the *ngctl(8)* man page for
complete details. The ngctl command is built-in to FreeBSD because the
Netgraph system is part of the kernel.
Both commands must be run as root.
Some example usage of the *vimage* command follows below.
::
vimage # displays the current virtual image
vimage -l # lists running virtual images
vimage e0_n0 ps aux # list the processes running on node 0
for i in 1 2 3 4 5
do # execute a command on all nodes
vimage e0_n$i sysctl -w net.inet.ip.redirect=0
done
The *ngctl* command is more complex, due to the variety of Netgraph nodes
available and each of their options.
::
ngctl l # list active Netgraph nodes
ngctl show e0_n8: # display node hook information
ngctl msg e0_n0-n1: getstats # get pkt count statistics from a pipe node
ngctl shutdown \\[0x0da3\\]: # shut down unnamed node using hex node ID
There are many other combinations of commands not shown here. See the online
manual (man) pages for complete details.
Below is a transcript of creating two emulated nodes, `router0` and `router1`,
and connecting them together with a link:
.. index:: create nodes from command-line
.. index:: command-line
::
# create node 0
vimage -c e0_n0
vimage e0_n0 hostname router0
ngctl mkpeer eiface ether ether
vimage -i e0_n0 ngeth0 eth0
vimage e0_n0 ifconfig eth0 link 40:00:aa:aa:00:00
vimage e0_n0 ifconfig lo0 inet localhost
vimage e0_n0 sysctl net.inet.ip.forwarding=1
vimage e0_n0 sysctl net.inet6.ip6.forwarding=1
vimage e0_n0 ifconfig eth0 mtu 1500
# create node 1
vimage -c e0_n1
vimage e0_n1 hostname router1
ngctl mkpeer eiface ether ether
vimage -i e0_n1 ngeth1 eth0
vimage e0_n1 ifconfig eth0 link 40:00:aa:aa:0:1
vimage e0_n1 ifconfig lo0 inet localhost
vimage e0_n1 sysctl net.inet.ip.forwarding=1
vimage e0_n1 sysctl net.inet6.ip6.forwarding=1
vimage e0_n1 ifconfig eth0 mtu 1500
# create a link between n0 and n1
ngctl mkpeer eth0@e0_n0: pipe ether upper
ngctl name eth0@e0_n0:ether e0_n0-n1
ngctl connect e0_n0-n1: eth0@e0_n1: lower ether
ngctl msg e0_n0-n1: setcfg \\
{{ bandwidth=100000000 delay=0 upstream={ BER=0 dupl
icate=0 } downstream={ BER=0 duplicate=0 } }}
ngctl msg e0_n0-n1: setcfg {{ downstream={ fifo=1 } }}
ngctl msg e0_n0-n1: setcfg {{ downstream={ droptail=1 } }}
ngctl msg e0_n0-n1: setcfg {{ downstream={ queuelen=50 } }}
ngctl msg e0_n0-n1: setcfg {{ upstream={ fifo=1 } }}
ngctl msg e0_n0-n1: setcfg {{ upstream={ droptail=1 } }}
ngctl msg e0_n0-n1: setcfg {{ upstream={ queuelen=50 } }}
Other FreeBSD commands that may be of interest:
.. index:: FreeBSD commands
* **kldstat**, **kldload**, **kldunload** - list, load, and unload
FreeBSD kernel modules
* **sysctl** - display and modify various pieces of kernel state
* **pkg_info**, **pkg_add**, **pkg_delete** - list, add, or remove
FreeBSD software packages.
* **vtysh** - start a Quagga CLI for router configuration
Netgraph Nodes
--------------
.. index:: Netgraph
.. index:: Netgraph nodes
Each Netgraph node implements a protocol or processes data in some well-defined
manner (see the `netgraph(4)` man page). The netgraph source code is located
in `/usr/src/sys/netgraph`. There you might discover additional nodes that
implement some desired functionality, that have not yet been included in CORE.
Using certain kernel commands, you can likely include these types of nodes into
your CORE emulation.
The following Netgraph nodes are used by CORE:
* **ng_bridge** - switch node performs Ethernet bridging
* **ng_cisco** - Cisco HDLC serial links
* **ng_eiface** - virtual Ethernet interface that is assigned to each virtual machine
* **ng_ether** - physical Ethernet devices, used by the RJ45 tool
* **ng_hub** - hub node
* **ng_pipe** - used for wired Ethernet links, imposes packet delay, bandwidth restrictions, and other link characteristics
* **ng_socket** - socket used by *ngctl* utility
* **ng_wlan** - wireless LAN node

View file

@ -50,7 +50,7 @@ Prerequisites
.. index:: Prerequisites
The Linux or FreeBSD operating system is required. The GUI uses the Tcl/Tk scripting toolkit, and the CORE daemon require Python. Details of the individual software packages required can be found in the installation steps.
A Linux operating system is required. The GUI uses the Tcl/Tk scripting toolkit, and the CORE daemon requires Python. Details of the individual software packages required can be found in the installation steps.
.. _Required_Hardware:
@ -61,7 +61,7 @@ Required Hardware
.. index:: System requirements
Any computer capable of running Linux or FreeBSD should be able to run CORE. Since the physical machine will be hosting numerous virtual machines, as a general rule you should select a machine having as much RAM and CPU resources as possible.
Any computer capable of running Linux should be able to run CORE. Since the physical machine will be hosting numerous virtual machines, as a general rule you should select a machine having as much RAM and CPU resources as possible.
A *general recommendation* would be:
@ -80,18 +80,13 @@ is not required.
Required Software
-----------------
CORE requires the Linux or FreeBSD operating systems because it uses virtualization provided by the kernel. It does not run on the Windows or Mac OS X operating systems (unless it is running within a virtual machine guest.) There are two
different virtualization technologies that CORE can currently use:
Linux network namespaces and FreeBSD jails,
CORE requires a Linux operating systems because it uses virtualization provided by the kernel. It does not run on the Windows or Mac OS X operating systems (unless it is running within a virtual machine guest.)
The virtualization technology that CORE currently uses:
Linux network namespaces,
see :ref:`How_Does_it_Work?` for virtualization details.
**Linux network namespaces is the recommended platform.** Development is focused here and it supports the latest features. It is the easiest to install because there is no need to patch, install, and run a special Linux kernel.
FreeBSD |BSDVERSION|-RELEASE may offer the best scalability. If your
applications run under FreeBSD and you are comfortable with that platform,
this may be a good choice. Device and application support by BSD
may not be as extensive as Linux.
The CORE GUI requires the X.Org X Window system (X11), or can run over a
remote X11 session. For specific Tcl/Tk, Python, and other libraries required
to run CORE, refer to the :ref:`Installation` section.
@ -398,12 +393,6 @@ system that a systemd service file should be installed under Fedora.
make -j8
sudo make install
Note that the Linux RPM and Debian packages do not use the ``/usr/local``
prefix, and files are instead installed to ``/usr/sbin``, and
``/usr/lib``. This difference is a result of aligning with the directory
structure of Linux packaging systems and FreeBSD ports packaging.
Another note is that the Python distutils in Fedora Linux will install the CORE
Python modules to :file:`/usr/lib/python2.7/site-packages/core`, instead of
using the :file:`dist-packages` directory.
@ -463,153 +452,6 @@ The `zypper` command is used instead of `yum`.
For OpenSUSE/Xen based installations, refer to the `README-Xen` file included
in the CORE source.
.. _Installing_from_Source_on_FreeBSD:
Installing from Source on FreeBSD
---------------------------------
.. index:: kernel patch
**Rebuilding the FreeBSD Kernel**
The FreeBSD kernel requires a small patch to allow per-node directories in the
filesystem. Also, the `VIMAGE` build option needs to be turned on to enable
jail-based network stack virtualization. The source code for the FreeBSD
kernel is located in :file:`/usr/src/sys`.
Instructions below will use the :file:`/usr/src/sys/amd64` architecture
directory, but the directory :file:`/usr/src/sys/i386` should be substituted
if you are using a 32-bit architecture.
The kernel patch is available from the CORE source tarball under core-|version|/kernel/symlinks-8.1-RELEASE.diff. This patch applies to the
FreeBSD 8.x or 9.x kernels.
.. parsed-literal::
cd /usr/src/sys
# first you can check if the patch applies cleanly using the '-C' option
patch -p1 -C < ~/core-|version|/kernel/symlinks-8.1-RELEASE.diff
# without '-C' applies the patch
patch -p1 < ~/core-|version|/kernel/symlinks-8.1-RELEASE.diff
A kernel configuration file named :file:`CORE` can be found within the source tarball: core-|version|/kernel/freebsd8-config-CORE. The config is valid for
FreeBSD 8.x or 9.x kernels.
The contents of this configuration file are shown below; you can edit it to suit your needs.
::
# this is the FreeBSD 9.x kernel configuration file for CORE
include GENERIC
ident CORE
options VIMAGE
nooptions SCTP
options IPSEC
device crypto
options IPFIREWALL
options IPFIREWALL_DEFAULT_TO_ACCEPT
The kernel configuration file can be linked or copied to the kernel source directory. Use it to configure and build the kernel:
.. parsed-literal::
cd /usr/src/sys/amd64/conf
cp ~/core-|version|/kernel/freebsd8-config-CORE CORE
config CORE
cd ../compile/CORE
make cleandepend && make depend
make -j8 && make install
Change the number 8 above to match the number of CPU cores you have times two.
Note that the ``make install`` step will move your existing kernel to
``/boot/kernel.old`` and removes that directory if it already exists. Reboot to
enable this new patched kernel.
**Building CORE from Source on FreeBSD**
Here are the prerequisite packages from the FreeBSD ports system:
::
pkg_add -r tk85
pkg_add -r libimg
pkg_add -r bash
pkg_add -r libev
pkg_add -r sudo
pkg_add -r python
pkg_add -r autotools
pkg_add -r gmake
Note that if you are installing to a bare FreeBSD system and want to SSH with X11 forwarding to that system, these packages will help:
::
pkg_add -r xauth
pkg_add -r xorg-fonts
The ``sudo`` package needs to be configured so a normal user can run the CORE
GUI using the command ``core-gui`` (opening a shell window on a node uses a
command such as ``sudo vimage n1``.)
On FreeBSD, the CORE source is built using autotools and gmake:
.. parsed-literal::
tar xzf core-|version|.tar.gz
cd core-|version|
./bootstrap.sh
./configure
gmake -j8
sudo gmake install
Build and install the ``vimage`` utility for controlling virtual images. The source can be obtained from `FreeBSD SVN <http://svn.freebsd.org/viewvc/base/head/tools/tools/vimage/>`_, or it is included with the CORE source for convenience:
.. parsed-literal::
cd core-|version|/kernel/vimage
make
make install
.. index:: FreeBSD; kernel modules
.. index:: kernel modules
.. index:: ng_wlan and ng_pipe
On FreeBSD you should also install the CORE kernel modules for wireless emulation. Perform this step after you have recompiled and installed FreeBSD kernel.
.. parsed-literal::
cd core-|version|/kernel/ng_pipe
make
sudo make install
cd ../ng_wlan
make
sudo make install
The :file:`ng_wlan` kernel module allows for the creation of WLAN nodes. This
is a modified :file:`ng_hub` Netgraph module. Instead of packets being copied
to every connected node, the WLAN maintains a hash table of connected node
pairs. Furthermore, link parameters can be specified for node pairs, in
addition to the on/off connectivity. The parameters are tagged to each packet
and sent to the connected :file:`ng_pipe` module. The :file:`ng_pipe` has been
modified to read any tagged parameters and apply them instead of its default
link effects.
The :file:`ng_wlan` also supports linking together multiple WLANs across different machines using the :file:`ng_ksocket` Netgraph node, for distributed emulation.
The Quagga routing suite is recommended for routing,
:ref:`Quagga_Routing_Software` for installation.
@ -651,8 +493,7 @@ otherwise install the standard version of Quagga using your package manager or f
Installing Quagga from Packages
-------------------------------
To install the standard version of Quagga from packages, use your package
manager (Linux) or the ports system (FreeBSD).
To install the standard version of Quagga from packages, use your package manager (Linux).
Ubuntu users:
::
@ -664,12 +505,6 @@ Fedora users:
yum install quagga
FreeBSD users:
::
pkg_add -r quagga
To install the Quagga variant having OSPFv3 MDR, first download the
appropriate package, and install using the package manager.
@ -726,23 +561,6 @@ If you try to run quagga after installing from source and get an error such as:
this is usually a sign that you have to run `sudo ldconfig` to refresh the
cache file.
To compile Quagga to work with CORE on FreeBSD:
.. parsed-literal::
tar xzf |QVER|.tar.gz
cd |QVER|
./configure --enable-user=root --enable-group=wheel \\
--sysconfdir=/usr/local/etc/quagga --enable-vtysh \\
--localstatedir=/var/run/quagga
gmake
gmake install
On FreeBSD |BSDVERSION| you can use ``make`` or ``gmake``.
You probably want to compile Quagga from the ports system in
:file:`/usr/ports/net/quagga`.
VCORE
=====

View file

@ -12,8 +12,8 @@ networks. As an emulator, CORE builds a representation of a real computer
network that runs in real time, as opposed to simulation, where abstract models
are used. The live-running emulation can be connected to physical networks and
routers. It provides an environment for running real applications and
protocols, taking advantage of virtualization provided by the Linux or FreeBSD
operating systems.
protocols, taking advantage of virtualization provided by the Linux operating
system.
Some of its key features are:
@ -94,8 +94,7 @@ further control.
How Does it Work?
=================
A CORE node is a lightweight virtual machine. The CORE framework runs on Linux
and FreeBSD systems. The primary platform used for development is Linux.
A CORE node is a lightweight virtual machine. The CORE framework runs on Linux.
.. index::
single: Linux; virtualization
@ -104,8 +103,6 @@ and FreeBSD systems. The primary platform used for development is Linux.
single: network namespaces
* :ref:`Linux` CORE uses Linux network namespace virtualization to build virtual nodes, and ties them together with virtual networks using Linux Ethernet bridging.
* :ref:`FreeBSD` CORE uses jails with a network stack virtualization kernel option to build virtual nodes, and ties them together with virtual networks using BSD's Netgraph system.
.. _Linux:
@ -117,9 +114,9 @@ technique used by CORE. LXC has been part of the mainline Linux kernel since
2.6.24. Recent Linux distributions such as Fedora and Ubuntu have
namespaces-enabled kernels out of the box, so the kernel does not need to be
patched or recompiled.
A namespace is created using the ``clone()`` system call. Similar
to the BSD jails, each namespace has its own process environment and private
network stack. Network namespaces share the same filesystem in CORE.
A namespace is created using the ``clone()`` system call. Each namespace has
its own process environment and private network stack. Network namespaces
share the same filesystem in CORE.
.. index::
single: Linux; bridging
@ -132,56 +129,6 @@ disciplines. Ebtables is Ethernet frame filtering on Linux bridges. Wireless
networks are emulated by controlling which interfaces can send and receive with
ebtables rules.
.. _FreeBSD:
FreeBSD
-------
.. index::
single: FreeBSD; Network stack virtualization
single: FreeBSD; jails
single: FreeBSD; vimages
FreeBSD jails provide an isolated process space, a virtual environment for
running programs. Starting with FreeBSD 8.0, a new `vimage` kernel option
extends BSD jails so that each jail can have its own virtual network stack --
its own networking variables such as addresses, interfaces, routes, counters,
protocol state, socket information, etc. The existing networking algorithms and
code paths are intact but operate on this virtualized state.
Each jail plus network stack forms a lightweight virtual machine. These are
named jails or *virtual images* (or *vimages*) and are created using a the
``jail`` or ``vimage`` command. Unlike traditional virtual
machines, vimages do not feature entire operating systems running on emulated
hardware. All of the vimages will share the same processor, memory, clock, and
other system resources. Because the actual hardware is not emulated and network
packets can be passed by reference through the in-kernel Netgraph system,
vimages are quite lightweight and a single system can accommodate numerous
instances.
Virtual network stacks in FreeBSD were historically available as a patch to the
FreeBSD 4.11 and 7.0 kernels, and the VirtNet project [#f1]_ [#f2]_
added this functionality to the
mainline 8.0-RELEASE and newer kernels.
.. index::
single: FreeBSD; Netgraph
The FreeBSD Operating System kernel features a graph-based
networking subsystem named Netgraph. The netgraph(4) manual page quoted below
best defines this system:
The netgraph system provides a uniform and modular system for the
implementation of kernel objects which perform various networking functions.
The objects, known as nodes, can be arranged into arbitrarily complicated
graphs. Nodes have hooks which are used to connect two nodes together,
forming the edges in the graph. Nodes communicate along the edges to
process data, implement protocols, etc.
The aim of netgraph is to supplement rather than replace the existing
kernel networking infrastructure.
.. index::
single: IMUNES
single: VirtNet
@ -201,7 +148,7 @@ The Tcl/Tk CORE GUI was originally derived from the open source
project from the University of Zagreb
as a custom project within Boeing Research and Technology's Network
Technology research group in 2004. Since then they have developed the CORE
framework to use not only FreeBSD but Linux virtualization, have developed a
framework to use Linux virtualization, have developed a
Python framework, and made numerous user- and kernel-space developments, such
as support for wireless networks, IPsec, the ability to distribute emulations,
simulation integration, and more. The IMUNES project also consists of userspace
@ -226,20 +173,16 @@ CORE has been released by Boeing to the open source community under the BSD
license. If you find CORE useful for your work, please contribute back to the
project. Contributions can be as simple as reporting a bug, dropping a line of
encouragement or technical suggestions to the mailing lists, or can also
include submitting patches or maintaining aspects of the tool. For details on
contributing to CORE, please visit the
`wiki <http://code.google.com/p/coreemu/wiki/Home, wiki>`_.
include submitting patches or maintaining aspects of the tool. For contributing to
CORE, please visit the
`CORE GitHub <https://github.com/coreemu/core>`_.
Besides this manual, there are other additional resources available online:
* `CORE website <http://www.nrl.navy.mil/itd/ncs/products/core>`_ - main project page containing demos, downloads, and mailing list information.
* `CORE supplemental website <http://code.google.com/p/coreemu/>`_ - supplemental Google Code page with a quickstart guide, wiki, bug tracker, and screenshots.
.. index::
single: wiki
single: CORE; wiki
The `CORE wiki <http://code.google.com/p/coreemu/wiki/Home>`_ is a good place to check for the latest documentation and tips.
single: CORE
Goals
-----
@ -255,10 +198,9 @@ Non-Goals
---------
This is a list of Non-Goals, specific things that people may be interested in but are not areas that we will pursue.
#. Reinventing the wheel - Where possible, CORE reuses existing open source components such as virtualization, Netgraph, netem, bridging, Quagga, etc.
#. 1,000,000 nodes - While the goal of CORE is to provide efficient, scalable network emulation, there is no set goal of N number of nodes. There are realistic limits on what a machine can handle as its resources are divided amongst virtual nodes. We will continue to make things more efficient and let the user determine the right number of nodes based on available hardware and the activities each node is performing.
#. Solves every problem - CORE is about emulating networking layers 3-7 using virtual network stacks in the Linux or FreeBSD operating systems.
#. Solves every problem - CORE is about emulating networking layers 3-7 using virtual network stacks in Linux operating systems.
#. Hardware-specific - CORE itself is not an instantiation of hardware, a testbed, or a specific laboratory setup; it should run on commodity laptop and desktop PCs, in addition to high-end server hardware.

View file

@ -19,7 +19,7 @@ The top question about the performance of CORE is often
* Hardware - the number and speed of processors in the computer, the available
processor cache, RAM memory, and front-side bus speed may greatly affect
overall performance.
* Operating system version - Linux or FreeBSD, and the specific kernel versions
* Operating system version - distribution of Linux and the specific kernel versions
used will affect overall performance.
* Active processes - all nodes share the same CPU resources, so if one or more
nodes is performing a CPU-intensive task, overall performance will suffer.
@ -28,8 +28,8 @@ The top question about the performance of CORE is often
* GUI usage - widgets that run periodically, mobility scenarios, and other GUI
interactions generally consume CPU cycles that may be needed for emulation.
On a typical single-CPU Xeon 3.0GHz server machine with 2GB RAM running FreeBSD
|BSDVERSION|, we have found it reasonable to run 30-75 nodes running
On a typical single-CPU Xeon 3.0GHz server machine with 2GB RAM running Linux,
we have found it reasonable to run 30-75 nodes running
OSPFv2 and OSPFv3 routing. On this hardware CORE can instantiate 100 or more
nodes, but at that point it becomes critical as to what each of the nodes is
doing.
@ -38,7 +38,7 @@ doing.
Because this software is primarily a network emulator, the more appropriate
question is *how much network traffic can it handle?* On the same 3.0GHz server
described above, running FreeBSD 4.11, about 300,000 packets-per-second can be
described above, running Linux, about 300,000 packets-per-second can be
pushed through the system. The number of hops and the size of the packets is
less important. The limiting factor is the number of times that the operating
system needs to handle a packet. The 300,000 pps figure represents the number

View file

@ -43,7 +43,7 @@ mode. Nodes are drawn on a blank canvas using the toolbar on the left and
configured from right-click menus or by double-clicking them. The GUI does not
need to be run as root.
Once editing is complete, pressing the green `Start` button (or choosing `Execute` from the `Session` menu) instantiates the topology within the FreeBSD kernel and enters Execute mode. In execute mode, the user can interact with the running emulated machines by double-clicking or right-clicking on them. The editing toolbar disappears and is replaced by an execute toolbar, which provides tools while running the emulation. Pressing the red `Stop` button (or choosing `Terminate` from the `Session` menu) will destroy the running emulation and return CORE to Edit mode.
Once editing is complete, pressing the green `Start` button (or choosing `Execute` from the `Session` menu) instantiates the topology within the Linux kernel and enters Execute mode. In execute mode, the user can interact with the running emulated machines by double-clicking or right-clicking on them. The editing toolbar disappears and is replaced by an execute toolbar, which provides tools while running the emulation. Pressing the red `Stop` button (or choosing `Terminate` from the `Session` menu) will destroy the running emulation and return CORE to Edit mode.
CORE can be started directly in Execute mode by specifying ``--start`` and a topology file on the command line:
::
@ -63,7 +63,7 @@ There is also a **Batch** mode where CORE runs without the GUI and will instanti
core-gui --batch ~/.core/configs/myfile.imn
A session running in batch mode can be accessed using the ``vcmd`` command (or ``vimage`` on FreeBSD), or the GUI can connect to the session.
A session running in batch mode can be accessed using the ``vcmd`` command, or the GUI can connect to the session.
.. index:: closebatch
@ -92,8 +92,7 @@ The session number is printed in the terminal when batch mode is started. This s
.. index:: root privileges
The GUI can be run as a normal user on Linux. For FreeBSD, the GUI should be run
as root in order to start an emulation.
The GUI can be run as a normal user on Linux.
.. index:: port number
@ -204,7 +203,7 @@ sub-menus, which appear when you click on their group icon.
wireless nodes based on the distance between them
* |rj45| *RJ45* - with the RJ45 Physical Interface Tool, emulated nodes can
be linked to real physical interfaces on the Linux or FreeBSD machine;
be linked to real physical interfaces;
using this tool, real networks and devices can be physically connected to
the live-running emulation (:ref:`RJ45_Tool`)
@ -724,11 +723,7 @@ Here are some standard widgets:
link. If the throughput exceeds a certain threshold, the link will become
highlighted. For wireless nodes which broadcast data to all nodes in range,
the throughput rate is displayed next to the node and the node will become
circled if the threshold is exceeded. *Note: under FreeBSD, the
Throughput Widget will
display "0.0 kbps" on all links that have no configured link effects, because
of the way link statistics are counted; to fix this, add a small delay or a
bandwidth limit to each link.*
circled if the threshold is exceeded.
.. _Observer_Widgets:
@ -925,7 +920,7 @@ physical ports are available, but the (e.g. switching) hardware connected to
the physical port must support the VLAN tagging, and the available bandwidth
will be shared.
You need to create separate VLAN virtual devices on the Linux or FreeBSD host,
You need to create separate VLAN virtual devices on the Linux host,
and then assign these devices to RJ45 nodes inside of CORE. The VLANning is
actually performed outside of CORE, so when the CORE emulated node receives a
packet, the VLAN tag will already be removed.
@ -953,8 +948,8 @@ Tunneling can be helpful when the number of physical interfaces is limited or
when the peer is located on a different network. Also a physical interface does
not need to be dedicated to CORE as with the RJ45 tool.
The peer GRE tunnel endpoint may be another CORE machine or a (Linux, FreeBSD,
etc.) host that supports GRE tunneling. When placing a Tunnel node, initially
The peer GRE tunnel endpoint may be another CORE machine or another
host that supports GRE tunneling. When placing a Tunnel node, initially
the node will display "UNASSIGNED". This text should be replaced with the IP
address of the tunnel peer. This is the IP address of the other CORE machine or
physical machine, not an IP address of another virtual node.
@ -1124,12 +1119,11 @@ link, affecting its display.
.. index:: lanswitch
Link-layer nodes are provided for modeling wired networks. These do not create
a separate network stack when instantiated, but are implemented using bridging
(Linux) or Netgraph nodes (FreeBSD). These are the hub, switch, and wireless
LAN nodes. The hub copies each packet from the incoming link to every connected
link, while the switch behaves more like an Ethernet switch and keeps track of
the Ethernet address of the connected peer, forwarding unicast traffic only to
the appropriate ports.
a separate network stack when instantiated, but are implemented using Linux bridging.
These are the hub, switch, and wireless LAN nodes. The hub copies each packet from
the incoming link to every connected link, while the switch behaves more like an
Ethernet switch and keeps track of the Ethernet address of the connected peer,
forwarding unicast traffic only to the appropriate ports.
The wireless LAN (WLAN) is covered in the next section.
@ -1158,7 +1152,7 @@ on platform. See the table below for a brief overview of wireless model types.
============= ===================== ======== ==================================================================
Model Type Supported Platform(s) Fidelity Description
============= ===================== ======== ==================================================================
Basic on/off Linux, FreeBSD Low Linux Ethernet bridging with ebtables (Linux) or ng_wlan (FreeBSD)
Basic on/off Linux Low Linux Ethernet bridging with ebtables
EMANE Plug-in Linux High TAP device connected to EMANE emulator with pluggable MAC and PHY radio types
============= ===================== ======== ==================================================================
@ -1198,8 +1192,6 @@ dragging them, and wireless links will be dynamically made or broken.
The *EMANE* tab lists available EMANE models to use for wireless networking.
See the :ref:`EMANE` chapter for details on using EMANE.
On FreeBSD, the WLAN node is realized using the *ng_wlan* Netgraph node.
.. _Mobility_Scripting:
Mobility Scripting
@ -1305,8 +1297,7 @@ Distributed Emulation
A large emulation scenario can be deployed on multiple emulation servers and
controlled by a single GUI. The GUI, representing the entire topology, can be
run on one of the emulation servers or on a separate machine. Emulations can be
distributed on Linux, while tunneling support has not been added yet for
FreeBSD.
distributed on Linux.
Each machine that will act as an emulation server needs to have CORE installed.
It is not important to have the GUI component but the CORE Python daemon

View file

@ -33,8 +33,6 @@ CONFIG_FILES = configs/sample1.imn configs/sample1.scen \
configs/sample9-vpn.imn \
configs/sample10-kitchen-sink.imn
OTHER_FILES = core-bsd-cleanup.sh
#
# CORE GUI script (/usr/local/bin/core-gui)
#

View file

@ -384,9 +384,7 @@ proc parseNodeMessage { data len flags } {
set wlans_needing_update { }
if { $vals(emuid) != -1 } {
# For Linux (FreeBSD populates ngnodeidmap in l3node.instantiate/
# buildInterface when the netgraph ID is known)
# populate ngnodeidmap for later use with wireless; it is treated as
# For Linux populate ngnodeidmap for later use with wireless; it is treated as
# a hex value string (without the leading "0x")
global ngnodeidmap
foreach wlan [findWlanNodes $node] {

View file

@ -600,7 +600,8 @@ proc loadCfg { cfg } {
custom-pre-config-commands {
# Boeing - custom pre config commands
set cfg ""
foreach zline [split $value { }] {
foreach zline [split $value {
}] {
if { [string index "$zline" 0] == " " } {
set zline [string replace "$zline" 0 0]
}
@ -612,7 +613,8 @@ proc loadCfg { cfg } {
custom-post-config-commands {
# Boeing - custom post config commands
set cfg ""
foreach zline [split $value { }] {
foreach zline [split $value {
}] {
if { [string index "$zline" 0] == " " } {
set zline [string replace "$zline" 0 0]
}
@ -628,7 +630,8 @@ proc loadCfg { cfg } {
ine-config {
# Boeing - INE
set cfg ""
foreach zline [split $value { }] {
foreach zline [split $value {
}] {
if { [string index "$zline" 0] == " " } {
set zline [string replace "$zline" 0 0]
}
@ -1123,8 +1126,7 @@ proc initDefaultPrefs {} {
# variable expansions must be done here
array set g_prefs [list default_conf_path "$CONFDIR/configs"]
array set g_prefs [list gui_canvas_refpt "$DEFAULT_REFPT"]
if { $tcl_platform(os) == "FreeBSD" } { set shell "/usr/local/bin/bash"
} else { set shell "bash" }
set shell "bash"
array set g_prefs [list shell $shell]
array set g_prefs [list gui_text_editor [get_text_editor true]]
array set g_prefs [list gui_term_prog [get_term_prog true]]

View file

@ -87,10 +87,6 @@ node n2 {
SCRIPTDIR=$SESSION_DIR
LOGDIR=/var/log
if [ `uname` = "FreeBSD" ]; then
SCRIPTDIR=/tmp/e0_$HN
LOGDIR=$SCRIPTDIR
fi
cd $SCRIPTDIR
(
cat << 'EOF'

View file

@ -4669,7 +4669,7 @@ proc rj45ifclist { wi node wasclicked } {
set ifname ""
set ifip ""
# this handles differences between Linux and FreeBSD ifconfig
# this handles differences between ifconfig
foreach line [split [nexec localnode ifconfig -a] "\n"] {
set char [string index $line 0]
if { $char != " " && $char != " " } {

View file

@ -544,13 +544,8 @@ proc monitor_loop {} {
return
}
if { $systype == "FreeBSD 4.11-RELEASE" } {
set defaultname "default"
set cpun 3
} else {
set defaultname "."
set defaultname "."
set cpun 4
}
# CPU usage from `vimage -l`
set vimagetext [nexec localnode vimage -l $defaultname | xargs]

View file

@ -103,11 +103,6 @@ proc newFile {} {
set g_view_locked 0
# flush daemon configuration
if { [llength [findWlanNodes ""]] > 0 } {
if { [lindex $systype 0] == "FreeBSD" } {
catch { exec ngctl config wlan_ctl: flush=all }
}
}
loadCfg ""
resetGlobalVars newfile
set curcanvas [lindex $canvas_list 0]
@ -190,11 +185,6 @@ proc openFile { filename } {
}
# flush daemon configuration
if { [llength [findWlanNodes ""]] > 0 } {
if { [lindex $systype 0] == "FreeBSD" } {
catch { exec ngctl config wlan_ctl: flush=all }
}
}
set cfg ""
if { [catch { set fileId [open $currentFile r] } err] } {
puts "error opening file $currentFile: $err"
@ -550,10 +540,6 @@ proc exit {} {
if { [popupStopSessionPrompt]=="cancel" } {
return
}
# Flush daemon configuration
if { [lindex $systype 0] == "FreeBSD" } {
catch { exec ngctl config wlan_ctl: flush=all }
}
# Prompt for save if file was changed
if { $changed != 0 && [promptForSave] == "cancel" } {
return

View file

@ -839,11 +839,7 @@ proc newLink { lnode1 lnode2 } {
if { [string range $model 0 6] == "coreapi" } {
set delay 0; # delay controlled by wireless module
} elseif {$delay != ""} {
if { [lindex $systype 0] == "FreeBSD" } {
lappend $link "delay [expr $delay/2]"
} else {
lappend $link "delay $delay"
}
}
# Exclude OVS from network layer nodes IP address asignments
if { ([[typemodel $lnode2].layer] == "NETWORK") && ([nodeType $lnode2] != "OVS") } {

View file

@ -83,11 +83,7 @@ proc clearTwoNodeDialog { wi done} {
set emul [getEmulPlugin $node]
set emulation_type [lindex $emul 1]
catch {
if { $os == "FreeBSD" } {
exec sudo kill -9 $twonodePID 2> /dev/null
} else {
exec kill -9 $twonodePID 2> /dev/null
}
exec kill -9 $twonodePID 2> /dev/null
}
set twonodePID 0
}

View file

@ -15,8 +15,7 @@ if { $execMode == "interactive"} {
puts " Thumbnails and other image types (JPG, PNG, etc.) will not be supported."
puts " Please install it with:"
puts " yum install tkimg (RedHat/Fedora)"
puts " sudo apt-get install libtk-img (Debian/Ubuntu)"
puts " pkg_add -r libimg (FreeBSD)\n"
puts " sudo apt-get install libtk-img (Debian/Ubuntu)\n"
set g_imageFileTypes {{"images" {.gif}} {"All files" {*} }}
}
}
@ -487,24 +486,16 @@ proc addStaticRoutesToConfig { node cfg_ref } {
upvar 1 $cfg_ref cfg
foreach statrte [getStatIPv4routes $node] {
if {[lindex $systype 0] == "Linux" } { ;# Linux
set net [lindex [split $statrte] 0]
set gw [lindex [split $statrte] 1]
lappend cfg "/sbin/ip -4 route add $net via $gw"
} else { ;# FreeBSD
lappend cfg "route -q add -inet $statrte"
}
}
foreach statrte [getStatIPv6routes $node] {
if { [lindex $systype 0] == "Linux" } { ;# Linux
set net [lindex [split $statrte] 0]
set gw [lindex [split $statrte] 1]
if { $net == "::/0" } { set net "default" }
lappend cfg "/sbin/ip -6 route add $net via $gw"
} else { ;# FreeBSD
lappend cfg "route -q add -inet6 $statrte"
}
}
}
@ -514,11 +505,7 @@ proc getServiceStartString { } {
setSystype
if { [lindex $systype 0] == "Linux" } { ;# Linux
return "/etc/init.d/core-daemon start"
} else { ;# FreeBSD
return "/usr/local/etc/rc.d/core onestart"
}
}
proc popupBuildHostsFile { } {

View file

@ -27,8 +27,8 @@ array set widgets {
"Adjacency"
{ widget_adjacency_config widget_adjacency_init widget_adjacency_periodic widget_adjacency_move }
}
# TODO: fix CPU Widget; it is disabled because Linux network namespaces and
# FreeBSD jails do not have a CPU usage reporting mechanism right now
# TODO: fix CPU Widget; it is disabled because Linux network namespaces
# do not have a CPU usage reporting mechanism right now
# "CPU"
# { widget_cpu_config widget_cpu_init widget_cpu_periodic widget_cpu_move }
@ -47,31 +47,6 @@ set widgets_obs_quagga [subst {
{{PIM neighbors} {$vtysh -c {show ip pim neighbor}}}
}]
# Observer Widget definitions for FreeBSD
array set widgets_obs_bsd $widgets_obs_quagga
array set widgets_obs_bsd {
1
{ "processes" "ps ax" }
2
{ "ifconfig" "ifconfig" }
3
{ "IPv4 routes" "netstat -f inet -rn" }
4
{ "IPv6 routes" "netstat -f inet6 -rn" }
7
{ "IPv4 listening sockets" "sockstat -4l" }
8
{ "IPv6 listening sockets" "sockstat -6l" }
9
{ "IPv4 MFC entries" "ifmcstat -f inet" }
10
{ "IPv6 MFC entries" "ifmcstat -f inet6" }
11
{ "firewall rules" "ipfw -a list" }
12
{ "IPsec policies" "setkey -DP" }
}
# Observer Widget definitions for Linux
array set widgets_obs_linux $widgets_obs_quagga
array set widgets_obs_linux {
@ -104,17 +79,13 @@ set widget_loop_ID -1
#
proc init_default_widgets_obs {} {
global systype widgets widgets_obs widget_obs last_widgetObserveNode
global widgets_obs_bsd widgets_obs_linux
global widgets_obs_linux
setSystype
array unset widgets_obs
if { [lindex $systype 0] == "Linux" } {
set arrayname widgets_obs_linux
# this works, but we will instead reset all indices:
#array set widgets_obs [array get widgets_obs_linux]
} else {
set arrayname widgets_obs_bsd
}
# this resets the array indices to be 1, 2, 3, etc.
set i 1
@ -607,12 +578,7 @@ proc widget_thru_config {} {
frame $wi.msg -borderwidth 4
global systype
if { [lindex $systype 0] == "FreeBSD" } {
set lab1txt "Note: links with no impairments (bw, delay,\netc) "
set lab1txt "${lab1txt}will display 0.0 throughput"
} else {
set lab1txt ""
}
label $wi.msg.lab1 -text $lab1txt
pack $wi.msg.lab1 -side top -padx 4 -pady 4
pack $wi.msg -side top
@ -1642,13 +1608,8 @@ proc widget_cpu_init {command} {
#
proc widget_cpu_periodic { now } {
global systype
if { [lindex $systype 0] == "FreeBSD" } {
widget_cpu_periodic_vimage $now
} else {
puts "warning: the CPU widget is not functional for this platform yet"
return
}
}
proc widget_cpu_periodic_vimage { now } {

File diff suppressed because it is too large Load diff

View file

@ -1,24 +0,0 @@
CORE kernel patches
For information on the kernel modules ng_pipe and ng_wlan, see the README files in their respective directories. You should run the make && make install from
the module directories for CORE to work properly.
FreeBSD 8.x requires the small patches to allow per-node directories.
The FreeBSD 7.x version of CORE does not require the patch included here.
Instead you should download the latest vimage_7 kernel from:
http://imunes.net/virtnet/
The FreeBSD 4.11 version of CORE requires the included patch to work. See the
CORE manual for patching details.
ng_pipe module you should install with FreeBSD 4.11 or 7.x
ng_wlan module you should install with FreeBSD 4.11 or 7.x
4.11-R-CORE.diff patch you should use with FreeBSD 4.11
freebsd7-config-CORE config that you may use with vimage_7 kernels
freebsd7-config-COREDEBUG debugging config for use with vimage_7 kernels
vimage_7-CORE.diff patch to add multicast routing to vimage_7_20081015
imunes-8.0-RELEASE.diff per-node directories, persistent hub/switch, and
traffic snopping for wireshark for FreeBSD 8.0
symlinks-8.1-RELEASE.diff per-node directories for FreeBSD 8.1

View file

@ -1,20 +0,0 @@
#
# VIMAGE - sample kernel configuration file with a virtualized network stack
# configure.
#
# $FreeBSD$
#
include GENERIC
ident CORE
options IPSEC
device crypto
options VIMAGE
options IPFIREWALL
options IPFIREWALL_DEFAULT_TO_ACCEPT #allow everything by default
#
# Some kernel subsystems and functions don't yet compile with VIMAGE. Remove
# from the configuration for now.
#
nooptions SCTP

View file

@ -1,22 +0,0 @@
#
# VIMAGE - sample kernel configuration file with a virtualized network stack
# configure.
#
# $FreeBSD$
#
include GENERIC
ident COREDEBUG
device crypto
options IPSEC
options VIMAGE
options DDB
options GDB
options KDB
options KDB_TRACE
#
# Some kernel subsystems and functions don't yet compile with VIMAGE. Remove
# from the configuration for now.
#
nooptions SCTP

View file

@ -1,11 +0,0 @@
# this is the FreeBSD 8.x kernel configuration file for CORE
include GENERIC
ident CORE
options VIMAGE
nooptions SCTP
options IPSEC
device crypto
options IPFIREWALL
options IPFIREWALL_DEFAULT_TO_ACCEPT

View file

@ -1,372 +0,0 @@
# This patch is from http://imunes.net/imunes-8.0-RC3.diff
#
# This patch enables per-node directories, persistent hub/switch nodes, traffic
# snooping for wireshark, and disallows vlan interfaces within a jail.
diff -drup src-org/sys/kern/vfs_lookup.c src/sys/kern/vfs_lookup.c
--- src-org/sys/kern/vfs_lookup.c 2009-10-25 01:10:29.000000000 +0000
+++ src/sys/kern/vfs_lookup.c 2009-11-11 12:46:02.000000000 +0000
@@ -59,6 +59,8 @@ __FBSDID("$FreeBSD: src/sys/kern/vfs_loo
#include <sys/ktrace.h>
#endif
+#include <net/vnet.h>
+
#include <security/audit/audit.h>
#include <security/mac/mac_framework.h>
@@ -72,6 +74,19 @@ SDT_PROBE_DEFINE3(vfs, namei, lookup, en
"unsigned long");
SDT_PROBE_DEFINE2(vfs, namei, lookup, return, "int", "struct vnode *");
+#ifdef VIMAGE
+#define IMUNES_SYMLINK_HACK
+#endif
+
+#ifdef IMUNES_SYMLINK_HACK
+static VNET_DEFINE(int, morphing_symlinks);
+#define V_morphing_symlinks VNET(morphing_symlinks)
+
+SYSCTL_VNET_INT(_vfs, OID_AUTO, morphing_symlinks, CTLFLAG_RW,
+ &VNET_NAME(morphing_symlinks), 0,
+ "Resolve @ to vimage name in symlinks");
+#endif
+
/*
* Allocation zone for namei
*/
@@ -333,6 +348,44 @@ namei(struct nameidata *ndp)
error = ENOENT;
break;
}
+#ifdef IMUNES_SYMLINK_HACK
+ /*
+ * If the symbolic link includes a special character '@',
+ * and V_morphing_symlinks is set, substitute the first
+ * occurence of '@' with full path to jail / vimage name.
+ * If the full path includes subhierarchies, s/./\// when
+ * expanding '@' to jail / vimage name.
+ *
+ * XXX revisit buffer length checking.
+ */
+ CURVNET_SET_QUIET(TD_TO_VNET(curthread));
+ if (V_morphing_symlinks) {
+ char *sp = strchr(cp, '@');
+
+ if (sp) {
+ char *vname = td->td_ucred->cr_prison->pr_name;
+ int vnamelen = strlen(vname);
+ int i;
+
+ if (vnamelen >= auio.uio_resid) {
+ if (ndp->ni_pathlen > 1)
+ uma_zfree(namei_zone, cp);
+ error = ENAMETOOLONG;
+ CURVNET_RESTORE();
+ break;
+ }
+ bcopy(sp + 1, sp + vnamelen,
+ linklen - (sp - cp));
+ bcopy(td->td_ucred->cr_prison->pr_name,
+ sp, vnamelen);
+ linklen += (vnamelen - 1);
+ for (i = 0; i < vnamelen; i++)
+ if (sp[i] == '.')
+ sp[i] = '/';
+ }
+ }
+ CURVNET_RESTORE();
+#endif
if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
if (ndp->ni_pathlen > 1)
uma_zfree(namei_zone, cp);
diff -drup src-org/sys/net/bpf.c src/sys/net/bpf.c
--- src-org/sys/net/bpf.c 2009-10-25 01:10:29.000000000 +0000
+++ src/sys/net/bpf.c 2009-11-11 12:46:02.000000000 +0000
@@ -44,6 +44,7 @@ __FBSDID("$FreeBSD: src/sys/net/bpf.c,v
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/conf.h>
+#include <sys/ctype.h>
#include <sys/fcntl.h>
#include <sys/jail.h>
#include <sys/malloc.h>
@@ -1435,9 +1436,34 @@ bpf_setif(struct bpf_d *d, struct ifreq
struct bpf_if *bp;
struct ifnet *theywant;
+#define XVNET_BPF_SNOOPING
+#if defined(VIMAGE) && defined(XVNET_BPF_SNOOPING)
+ struct vnet *target_vnet = curvnet;
+ char *c;
+
+ /* Attempt to attach to an ifnet in a foreign vnet, specified as @ */
+ c = rindex(ifr->ifr_name, '@');
+ if ( c != NULL ) {
+ struct prison *target_pr;
+
+ *c++ = 0;
+ if (!isascii(*c) && !isdigit(*c))
+ return ENXIO;
+ target_pr = prison_find_name(curthread->td_ucred->cr_prison, c);
+ if (target_pr == NULL)
+ return ENXIO;
+ target_vnet = target_pr->pr_vnet;
+ }
+ CURVNET_SET_QUIET(target_vnet);
+#endif
+
theywant = ifunit(ifr->ifr_name);
- if (theywant == NULL || theywant->if_bpf == NULL)
+ if (theywant == NULL || theywant->if_bpf == NULL) {
+#if defined(VIMAGE) && defined(XVNET_BPF_SNOOPING)
+ CURVNET_RESTORE();
+#endif
return (ENXIO);
+ }
bp = theywant->if_bpf;
@@ -1477,6 +1503,9 @@ bpf_setif(struct bpf_d *d, struct ifreq
BPFD_LOCK(d);
reset_d(d);
BPFD_UNLOCK(d);
+#if defined(VIMAGE) && defined(XVNET_BPF_SNOOPING)
+ CURVNET_RESTORE();
+#endif
return (0);
}
diff -drup src-org/sys/net/if.c src/sys/net/if.c
--- src-org/sys/net/if.c 2009-10-25 01:10:29.000000000 +0000
+++ src/sys/net/if.c 2009-11-11 12:46:02.000000000 +0000
@@ -813,6 +813,14 @@ if_detach_internal(struct ifnet *ifp, in
struct ifnet *iter;
int found = 0;
+ /*
+ * Detach from any vlan, bridge or lagg ifnets linked to us.
+ * A small though unlikely window for a race from here to ifp
+ * unlinking from ifnet list is possible, hence we repeat the
+ * procedure once again further bellow. XXX.
+ */
+ EVENTHANDLER_INVOKE(ifnet_departure_event, ifp);
+
IFNET_WLOCK();
TAILQ_FOREACH(iter, &V_ifnet, if_link)
if (iter == ifp) {
diff -drup src-org/sys/net/if_llatbl.c src/sys/net/if_llatbl.c
--- src-org/sys/net/if_llatbl.c 2009-10-25 01:10:29.000000000 +0000
+++ src/sys/net/if_llatbl.c 2009-11-11 12:53:49.000000000 +0000
@@ -57,11 +57,14 @@ __FBSDID("$FreeBSD: src/sys/net/if_llatb
MALLOC_DEFINE(M_LLTABLE, "lltable", "link level address tables");
-static SLIST_HEAD(, lltable) lltables = SLIST_HEAD_INITIALIZER(lltables);
+static VNET_DEFINE(SLIST_HEAD(, lltable), lltables);
+#define V_lltables VNET(lltables)
extern void arprequest(struct ifnet *, struct in_addr *, struct in_addr *,
u_char *);
+static void vnet_lltable_init(void);
+
struct rwlock lltable_rwlock;
RW_SYSINIT(lltable_rwlock, &lltable_rwlock, "lltable_rwlock");
@@ -75,7 +78,7 @@ lltable_sysctl_dumparp(int af, struct sy
int error = 0;
LLTABLE_RLOCK();
- SLIST_FOREACH(llt, &lltables, llt_link) {
+ SLIST_FOREACH(llt, &V_lltables, llt_link) {
if (llt->llt_af == af) {
error = llt->llt_dump(llt, wr);
if (error != 0)
@@ -157,7 +160,7 @@ lltable_free(struct lltable *llt)
KASSERT(llt != NULL, ("%s: llt is NULL", __func__));
LLTABLE_WLOCK();
- SLIST_REMOVE(&lltables, llt, lltable, llt_link);
+ SLIST_REMOVE(&V_lltables, llt, lltable, llt_link);
LLTABLE_WUNLOCK();
for (i=0; i < LLTBL_HASHTBL_SIZE; i++) {
@@ -180,7 +183,7 @@ lltable_drain(int af)
register int i;
LLTABLE_RLOCK();
- SLIST_FOREACH(llt, &lltables, llt_link) {
+ SLIST_FOREACH(llt, &V_lltables, llt_link) {
if (llt->llt_af != af)
continue;
@@ -202,7 +205,7 @@ lltable_prefix_free(int af, struct socka
struct lltable *llt;
LLTABLE_RLOCK();
- SLIST_FOREACH(llt, &lltables, llt_link) {
+ SLIST_FOREACH(llt, &V_lltables, llt_link) {
if (llt->llt_af != af)
continue;
@@ -232,7 +235,7 @@ lltable_init(struct ifnet *ifp, int af)
LIST_INIT(&llt->lle_head[i]);
LLTABLE_WLOCK();
- SLIST_INSERT_HEAD(&lltables, llt, llt_link);
+ SLIST_INSERT_HEAD(&V_lltables, llt, llt_link);
LLTABLE_WUNLOCK();
return (llt);
@@ -302,7 +305,7 @@ lla_rt_output(struct rt_msghdr *rtm, str
/* XXX linked list may be too expensive */
LLTABLE_RLOCK();
- SLIST_FOREACH(llt, &lltables, llt_link) {
+ SLIST_FOREACH(llt, &V_lltables, llt_link) {
if (llt->llt_af == dst->sa_family &&
llt->llt_ifp == ifp)
break;
@@ -367,3 +370,12 @@ lla_rt_output(struct rt_msghdr *rtm, str
return (error);
}
+
+static void
+vnet_lltable_init()
+{
+
+ SLIST_INIT(&V_lltables);
+}
+VNET_SYSINIT(vnet_lltable_init, SI_SUB_PSEUDO, SI_ORDER_FIRST, vnet_lltable_init, NULL);
+
diff -drup src-org/sys/net/if_vlan.c src/sys/net/if_vlan.c
--- src-org/sys/net/if_vlan.c 2009-10-25 01:10:29.000000000 +0000
+++ src/sys/net/if_vlan.c 2009-11-11 12:46:02.000000000 +0000
@@ -1359,6 +1359,12 @@ vlan_ioctl(struct ifnet *ifp, u_long cmd
error = copyin(ifr->ifr_data, &vlr, sizeof(vlr));
if (error)
break;
+#ifdef VIMAGE
+ if (ifp->if_home_vnet != ifp->if_vnet) {
+ error = EPERM;
+ break;
+ }
+#endif
if (vlr.vlr_parent[0] == '\0') {
vlan_unconfig(ifp);
break;
@@ -1386,6 +1392,12 @@ vlan_ioctl(struct ifnet *ifp, u_long cmd
case SIOCGETVLAN:
bzero(&vlr, sizeof(vlr));
+#ifdef VIMAGE
+ if (ifp->if_home_vnet != ifp->if_vnet) {
+ error = EPERM;
+ break;
+ }
+#endif
VLAN_LOCK();
if (TRUNK(ifv) != NULL) {
strlcpy(vlr.vlr_parent, PARENT(ifv)->if_xname,
diff -drup src-org/sys/netgraph/ng_bridge.c src/sys/netgraph/ng_bridge.c
--- src-org/sys/netgraph/ng_bridge.c 2009-10-25 01:10:29.000000000 +0000
+++ src/sys/netgraph/ng_bridge.c 2009-11-11 12:46:02.000000000 +0000
@@ -105,6 +105,7 @@ struct ng_bridge_private {
u_int numBuckets; /* num buckets in table */
u_int hashMask; /* numBuckets - 1 */
int numLinks; /* num connected links */
+ int persistent; /* can exist w/o any hooks */
struct callout timer; /* one second periodic timer */
};
typedef struct ng_bridge_private *priv_p;
@@ -345,13 +346,13 @@ static int
ng_bridge_newhook(node_p node, hook_p hook, const char *name)
{
const priv_p priv = NG_NODE_PRIVATE(node);
+ int linkNum = -1;
/* Check for a link hook */
if (strncmp(name, NG_BRIDGE_HOOK_LINK_PREFIX,
strlen(NG_BRIDGE_HOOK_LINK_PREFIX)) == 0) {
const char *cp;
char *eptr;
- u_long linkNum;
cp = name + strlen(NG_BRIDGE_HOOK_LINK_PREFIX);
if (!isdigit(*cp) || (cp[0] == '0' && cp[1] != '\0'))
@@ -359,6 +360,12 @@ ng_bridge_newhook(node_p node, hook_p ho
linkNum = strtoul(cp, &eptr, 10);
if (*eptr != '\0' || linkNum >= NG_BRIDGE_MAX_LINKS)
return (EINVAL);
+ } else if (strcmp(name, "anchor") == 0) {
+ linkNum = 0;
+ priv->persistent = 1;
+ }
+
+ if (linkNum >= 0 ) {
if (priv->links[linkNum] != NULL)
return (EISCONN);
priv->links[linkNum] = malloc(sizeof(*priv->links[linkNum]),
@@ -366,7 +373,7 @@ ng_bridge_newhook(node_p node, hook_p ho
if (priv->links[linkNum] == NULL)
return (ENOMEM);
priv->links[linkNum]->hook = hook;
- NG_HOOK_SET_PRIVATE(hook, (void *)linkNum);
+ NG_HOOK_SET_PRIVATE(hook, (void *)(intptr_t)linkNum);
priv->numLinks++;
return (0);
}
@@ -799,7 +806,8 @@ ng_bridge_disconnect(hook_p hook)
/* If no more hooks, go away */
if ((NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0)
- && (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))) {
+ && (NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
+ && !priv->persistent) {
ng_rmnode_self(NG_HOOK_NODE(hook));
}
return (0);
diff -drup src-org/sys/netgraph/ng_hub.c src/sys/netgraph/ng_hub.c
--- src-org/sys/netgraph/ng_hub.c 2009-10-25 01:10:29.000000000 +0000
+++ src/sys/netgraph/ng_hub.c 2009-11-11 12:46:02.000000000 +0000
@@ -37,6 +37,7 @@
#include <netgraph/netgraph.h>
static ng_constructor_t ng_hub_constructor;
+static ng_newhook_t ng_hub_newhook;
static ng_rcvdata_t ng_hub_rcvdata;
static ng_disconnect_t ng_hub_disconnect;
@@ -44,6 +45,7 @@ static struct ng_type ng_hub_typestruct
.version = NG_ABI_VERSION,
.name = NG_HUB_NODE_TYPE,
.constructor = ng_hub_constructor,
+ .newhook = ng_hub_newhook,
.rcvdata = ng_hub_rcvdata,
.disconnect = ng_hub_disconnect,
};
@@ -57,6 +59,14 @@ ng_hub_constructor(node_p node)
return (0);
}
+static int
+ng_hub_newhook(node_p node, hook_p hook, const char *name)
+{
+ if (strcmp(name, "anchor") == 0)
+ node->nd_private = (void *) 1;
+ return (0);
+}
+
static int
ng_hub_rcvdata(hook_p hook, item_p item)
{
@@ -94,7 +104,7 @@ ng_hub_disconnect(hook_p hook)
{
if (NG_NODE_NUMHOOKS(NG_HOOK_NODE(hook)) == 0 &&
- NG_NODE_IS_VALID(NG_HOOK_NODE(hook)))
+ NG_NODE_IS_VALID(NG_HOOK_NODE(hook)) && !hook->hk_node->nd_private)
ng_rmnode_self(NG_HOOK_NODE(hook));
return (0);
}

View file

@ -1,27 +0,0 @@
#
# (c)2008 the Boeing Company
#
# modified ng_pipe node
#
.if !defined(PLATFORM)
#PLATFORM=i386
PLATFORM=amd64
.endif
CFLAGS=-DBOEING_WLAN -I/usr/src/sys/${PLATFORM}/compile/CORE
KMOD= ng_pipe
SRCS= ng_pipe.c
#MAN= ng_pipe.4
# FreeBSD 4.11 is "FreeBSD" and 7.0 is "freebsd7.0"
#.if defined(OSTYPE)
#.if (${OSTYPE} == "FreeBSD")
#CFLAGS+=-DFREEBSD411
#SRCS= ng_pipe_freebsd4.c
#.endif
#.endif
.include <bsd.kmod.mk>

View file

@ -1,21 +0,0 @@
ng_pipe FreeBSD kernel module
See the copyright statement at the top of the source file.
Copyright (c) 2004, 2005, 2007 University of Zagreb
Copyright (c) 2007 FreeBSD Foundation
(c) 2008 the Boeing Company
modifications: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
More complete documentation is available in the ng_pipe(4) man page.
This version of ng_pipe has been modified as follows:
- added burst rate (or burstiness) which is the probability that the next packet
will be dropped given an error with the current packet, 0 to 100
- added jitter effect, which randomizes the delay an additional amount from
0 to jitter microseconds
- ng_wlan support added, to remove and read mbuf tags containing wlan link
effect information
- bugfix: random number generation improved from defective modulo algorithm
- bugfix: fixed mbuf dangling pointer reference when ng_pipe has both duplicates
and errors configured

File diff suppressed because it is too large Load diff

View file

@ -1,171 +0,0 @@
/*
* Copyright (c) 2004, 2007 University of Zagreb
* Copyright (c) 2007 FreeBSD Foundation
*
* This software was developed by the University of Zagreb and the
* FreeBSD Foundation under sponsorship by the Stichting NLnet and the
* FreeBSD Foundation.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _NETGRAPH_PIPE_H_
#define _NETGRAPH_PIPE_H_
/* Node type name and magic cookie */
#define NG_PIPE_NODE_TYPE "pipe"
#define NGM_PIPE_COOKIE 200708191
/* Hook names */
#define NG_PIPE_HOOK_UPPER "upper"
#define NG_PIPE_HOOK_LOWER "lower"
#define MAX_FSIZE 16384 /* Largest supported frame size, in bytes, for BER */
#define MAX_OHSIZE 256 /* Largest supported dummy-framing size, in bytes */
/* Statistics structure for one hook */
struct ng_pipe_hookstat {
u_int64_t fwd_octets;
u_int64_t fwd_frames;
u_int64_t in_disc_octets;
u_int64_t in_disc_frames;
u_int64_t out_disc_octets;
u_int64_t out_disc_frames;
};
/* Keep this in sync with the above structure definition */
#define NG_PIPE_HOOKSTAT_INFO { \
{ "FwdOctets", &ng_parse_uint64_type }, \
{ "FwdFrames", &ng_parse_uint64_type }, \
{ "queueDropOctets", &ng_parse_uint64_type }, \
{ "queueDropFrames", &ng_parse_uint64_type }, \
{ "delayDropOctets", &ng_parse_uint64_type }, \
{ "delayDropFrames", &ng_parse_uint64_type }, \
{ NULL }, \
}
/* Statistics structure returned by NGM_PIPE_GET_STATS */
struct ng_pipe_stats {
struct ng_pipe_hookstat downstream;
struct ng_pipe_hookstat upstream;
};
/* Keep this in sync with the above structure definition */
#define NG_PIPE_STATS_INFO(hstype) { \
{ "downstream", (hstype) }, \
{ "upstream", (hstype) }, \
{ NULL }, \
}
/* Runtime structure for one hook */
struct ng_pipe_hookrun {
u_int32_t fifo_queues;
u_int32_t qin_octets;
u_int32_t qin_frames;
u_int32_t qout_octets;
u_int32_t qout_frames;
};
/* Keep this in sync with the above structure definition */
#define NG_PIPE_HOOKRUN_INFO { \
{ "queues", &ng_parse_uint32_type }, \
{ "queuedOctets", &ng_parse_uint32_type }, \
{ "queuedFrames", &ng_parse_uint32_type }, \
{ "delayedOctets", &ng_parse_uint32_type }, \
{ "delayedFrames", &ng_parse_uint32_type }, \
{ NULL }, \
}
/* Runtime structure returned by NGM_PIPE_GET_RUN */
struct ng_pipe_run {
struct ng_pipe_hookrun downstream;
struct ng_pipe_hookrun upstream;
};
/* Keep this in sync with the above structure definition */
#define NG_PIPE_RUN_INFO(hstype) { \
{ "downstream", (hstype) }, \
{ "upstream", (hstype) }, \
{ NULL }, \
}
/* Config structure for one hook */
struct ng_pipe_hookcfg {
u_int64_t bandwidth;
u_int64_t ber;
u_int32_t qin_size_limit;
u_int32_t qout_size_limit;
u_int32_t duplicate;
u_int32_t fifo;
u_int32_t drr;
u_int32_t wfq;
u_int32_t droptail;
u_int32_t drophead;
};
/* Keep this in sync with the above structure definition */
#define NG_PIPE_HOOKCFG_INFO { \
{ "bandwidth", &ng_parse_uint64_type }, \
{ "BER", &ng_parse_uint64_type }, \
{ "queuelen", &ng_parse_uint32_type }, \
{ "delaylen", &ng_parse_uint32_type }, \
{ "duplicate", &ng_parse_uint32_type }, \
{ "fifo", &ng_parse_uint32_type }, \
{ "drr", &ng_parse_uint32_type }, \
{ "wfq", &ng_parse_uint32_type }, \
{ "droptail", &ng_parse_uint32_type }, \
{ "drophead", &ng_parse_uint32_type }, \
{ NULL }, \
}
/* Config structure returned by NGM_PIPE_GET_CFG */
struct ng_pipe_cfg {
u_int64_t bandwidth;
u_int64_t delay;
u_int32_t header_offset;
u_int32_t overhead;
struct ng_pipe_hookcfg downstream;
struct ng_pipe_hookcfg upstream;
};
/* Keep this in sync with the above structure definition */
#define NG_PIPE_CFG_INFO(hstype) { \
{ "bandwidth", &ng_parse_uint64_type }, \
{ "delay", &ng_parse_uint64_type }, \
{ "header_offset", &ng_parse_uint32_type }, \
{ "overhead", &ng_parse_uint32_type }, \
{ "downstream", (hstype) }, \
{ "upstream", (hstype) }, \
{ NULL }, \
}
/* Netgraph commands */
enum {
NGM_PIPE_GET_STATS=1, /* get stats */
NGM_PIPE_CLR_STATS, /* clear stats */
NGM_PIPE_GETCLR_STATS, /* atomically get and clear stats */
NGM_PIPE_GET_RUN, /* get current runtime status */
NGM_PIPE_GET_CFG, /* get configurable parameters */
NGM_PIPE_SET_CFG, /* set configurable parameters */
};
#endif /* _NETGRAPH_PIPE_H_ */

File diff suppressed because it is too large Load diff

View file

@ -1,27 +0,0 @@
#
# (c)2006-2011 the Boeing Company
#
# ng_wlan
#
.if !defined(PLATFORM)
#PLATFORM=i386
PLATFORM=amd64
.endif
CFLAGS+=-I/usr/src/sys/${PLATFORM}/compile/CORE -DMULTICAST_LOOKUPS
# FreeBSD 4.11 is "FreeBSD" and 7.0 is "freebsd7.0"
#.if defined(OSTYPE)
#.if (${OSTYPE} == "FreeBSD")
#CFLAGS+=-DFREEBSD411
#.endif
#.endif
KMOD= ng_wlan
SRCS= ng_wlan.c
#MAN= ng_wlan.4
.include <bsd.kmod.mk>

View file

@ -1,50 +0,0 @@
ng_wlan FreeBSD kernel module
(c) 2006-2011 the Boeing Company
author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
The ng_wlan modules implements a netgraph node that models wireless
LAN connectivity. ng_wlan extends the ng_hub node, only instead of sending
packets to each connected peer, maintains a hash table of node connectivity,
and sends packets between two nodes only when they are linked. By default all
nodes are unlinked. Nodes can be linked and unlinked using "link" and
"unlink" messages:
ngctl msg e0_n2: link { node1=0x23 node2=0x0c }
The node IDs of the two nodes are the parameters, as depicted above.
Link effects between can also be specified for each node pair. If two nodes
are linked and parameters are specified, an mbuf tag will be added to each data
packet mbuf that specifies the effects. For FreeBSD 4.11, the metadata parameter
is used instead of mbuf tags. Delay (microseconds), bandwidth
(bits per second), PER (% packet errors), duplicates (%), jitter
(microseconds), and burst (% burst errors) are supported. This tag is then
removed by the ng_pipe node and the appropriate effects are applied. Link
effects are specified with "set" and "unset" messages:
ngctl msg e0_n2: set { node1=0x23 node2=0x0c delay=50000 bandwidth=54000000 per=0 duplicate=0 jitter=5000 burst=30 }
ngctl msg e0_n2: unset { node1=0x23 node2=0x0c }
Note that a special ng_pipe module is needed (the default one does not support
the mbuf tags and some effects.)
A separate error rate and burst rate affecting all multicast packets may be
defined. Use the "mer" message:
ngctl msg e0_n2: mer { mer=20 mburst=35 }
The above example sets the multicast error rate to drop 20% of all multicast
packets, with 35% burst errors.
When MULTICAST_LOOKUPS is defined, a second lookup table is defined for each
WLAN where multicast group, source, and node pair tuples can be linked or
unlinked. This causes different forwarding behavior for multicast packets,
where non-local groups are only forwarded if the node pair has been linked
together for that group (and the normal node pair has been linked).
Usage:
ngctl msg e0_n2: mcastset { node1=0x23 node2=0x0c group=0xEF020364 source=0x0a000002 }
ngctl msg e0_n2: mcastset { node1=0x23 node2=0x0c group=0xEF020364 source=0}
ngctl msg e0_n2: mcastunset { node1=0x23 node2=0x0c group=0xEF020364 source=0 }
Once the first mcastset/mcastunset message is received, that ng_wlan will drop
all non-local multicast packets that do not have a matching source, group,
node pair entry. The source address of zero matches any IP source.

File diff suppressed because it is too large Load diff

View file

@ -1,109 +0,0 @@
/*
* Copyright (c) 2006-2011 the Boeing Company
* ng_wlan is based on ng_hub, which is:
* Copyright (c) 2004 Ruslan Ermilov
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
#ifndef _NETGRAPH_NG_WLAN_H_
#define _NETGRAPH_NG_WLAN_H_
/* Node type name and magic cookie. */
#define NG_WLAN_NODE_TYPE "wlan"
#define NGM_WLAN_COOKIE 1146673193
/* Control message parse info */
struct ng_wlan_config {
u_int32_t node1;
u_int32_t node2;
};
#define NG_WLAN_CONFIG_TYPE_INFO { \
{ "node1", &ng_parse_uint32_type }, \
{ "node2", &ng_parse_uint32_type }, \
{ NULL } \
}
struct ng_wlan_set_data {
u_int32_t node1;
u_int32_t node2;
u_int64_t delay; /* keep these aligned with struct ng_wlan_tag */
u_int64_t bandwidth;
u_int16_t per;
u_int16_t duplicate;
u_int32_t jitter;
u_int16_t burst;
};
#define NG_WLAN_SET_DATA_TYPE_INFO { \
{ "node1", &ng_parse_uint32_type }, \
{ "node2", &ng_parse_uint32_type }, \
{ "delay", &ng_parse_uint64_type }, \
{ "bandwidth", &ng_parse_uint64_type }, \
{ "per", &ng_parse_uint16_type }, \
{ "duplicate", &ng_parse_uint16_type }, \
{ "jitter", &ng_parse_uint32_type }, \
{ "burst", &ng_parse_uint16_type }, \
{ NULL } \
}
struct ng_wlan_mer {
uint16_t mer;
uint16_t mburst;
};
#define NG_WLAN_MER_TYPE_INFO { \
{ "mer", &ng_parse_uint16_type }, \
{ "mburst", &ng_parse_uint16_type }, \
{ NULL } \
}
#ifdef MULTICAST_LOOKUPS
struct ng_wlan_multicast_set_data {
u_int32_t node1;
u_int32_t node2;
u_int32_t group;
u_int32_t source;
};
#define NG_WLAN_MULTICAST_SET_DATA_TYPE_INFO { \
{ "node1", &ng_parse_uint32_type }, \
{ "node2", &ng_parse_uint32_type }, \
{ "group", &ng_parse_uint32_type }, \
{ "source", &ng_parse_uint32_type }, \
{ NULL } \
}
#endif /* MULTICAST_LOOKUPS */
/* List of supported Netgraph control messages */
enum {
NGM_WLAN_LINK_NODES = 1,
NGM_WLAN_UNLINK_NODES,
NGM_WLAN_NODES_SET,
NGM_WLAN_NODES_UNSET,
NGM_WLAN_NODES_GET,
NGM_WLAN_MER, /* MULTICAST_ERR */
NGM_WLAN_MULTICAST_SET, /* MULTICAST_LOOKUPS */
NGM_WLAN_MULTICAST_UNSET, /* MULTICAST_LOOKUPS */
NGM_WLAN_MULTICAST_GET, /* MULTICAST_LOOKUPS */
};
#endif /* _NETGRAPH_NG_WLAN_H_ */

View file

@ -1,60 +0,0 @@
/*
* Copyright (c) 2006-2011 the Boeing Company
* All rights reserved.
*
* author: Jeff Ahrenholz <jeffrey.m.ahrenholz@boeing.com>
*/
#define NG_TAG_WLAN 0x01
#ifdef FREEBSD411
#define WLAN_META_SIZE (sizeof(struct ng_meta))+(sizeof(struct ng_wlan_tag))
#define WLAN_META_PRIORITY 0x01
#define TAGSIZE (sizeof(struct ng_wlan_tag) - sizeof(struct meta_field_header))
#else
#define TAGSIZE (sizeof(struct ng_wlan_tag) - sizeof(struct m_tag))
#endif
#define NG_WLAN_MAX_DELAY 2000000 /* 2,000,000us = 2s */
#define NG_WLAN_MAX_BW 1000000000 /* 1,000,000,000bps = 1000M */
#define NG_WLAN_MAX_PER 100 /* 100% */
#define NG_WLAN_MAX_DUP 50 /* 50% */
#define NG_WLAN_MAX_JITTER NG_WLAN_MAX_DELAY
#define NG_WLAN_MAX_BURST NG_WLAN_MAX_PER
/* Tag data that is prepended to packets passing through the WLAN node.
*/
struct ng_wlan_tag {
#ifdef FREEBSD411
struct meta_field_header meta_hdr;
#else
struct m_tag tag;
#endif
u_int64_t delay;
u_int64_t bandwidth;
u_int16_t per;
u_int16_t duplicate;
u_int32_t jitter;
u_int16_t burst;
};
#define TAG_HAS_DATA(t) (t->delay || t->bandwidth || t->per || t->duplicate \
|| t->jitter || t->burst )
#define WLAN_TAG_ZERO(t) do { \
t->delay = 0; \
t->bandwidth = 0; \
t->per = 0; \
t->duplicate = 0; \
t->jitter = 0; \
t->burst = 0; \
} while(0);
#define WLAN_TAG_COPY(a, b) do { \
a->delay = ((struct ng_wlan_tag*)b)->delay; \
a->bandwidth = ((struct ng_wlan_tag*)b)->bandwidth; \
a->per = ((struct ng_wlan_tag*)b)->per; \
a->duplicate = ((struct ng_wlan_tag*)b)->duplicate; \
a->jitter = ((struct ng_wlan_tag*)b)->jitter; \
a->burst = ((struct ng_wlan_tag*)b)->burst; \
} while(0);

View file

@ -1,78 +0,0 @@
Index: sys/kern/vfs_lookup.c
===========================================================================
--- sys/kern/vfs_lookup.c 2010/06/17 19:18:00 #3
+++ sys/kern/vfs_lookup.c 2010/06/17 19:18:00
@@ -59,6 +59,8 @@
#include <sys/ktrace.h>
#endif
+#include <net/vnet.h>
+
#include <security/audit/audit.h>
#include <security/mac/mac_framework.h>
@@ -72,6 +74,19 @@
"unsigned long");
SDT_PROBE_DEFINE2(vfs, namei, lookup, return, "int", "struct vnode *");
+#ifdef VIMAGE
+#define IMUNES_SYMLINK_HACK
+#endif
+
+#ifdef IMUNES_SYMLINK_HACK
+static VNET_DEFINE(int, morphing_symlinks);
+#define V_morphing_symlinks VNET(morphing_symlinks)
+
+SYSCTL_VNET_INT(_vfs, OID_AUTO, morphing_symlinks, CTLFLAG_RW,
+ &VNET_NAME(morphing_symlinks), 0,
+ "Resolve @ to vimage name in symlinks");
+#endif
+
/*
* Allocation zone for namei
*/
@@ -333,6 +348,44 @@
error = ENOENT;
break;
}
+#ifdef IMUNES_SYMLINK_HACK
+ /*
+ * If the symbolic link includes a special character '@',
+ * and V_morphing_symlinks is set, substitute the first
+ * occurence of '@' with full path to jail / vimage name.
+ * If the full path includes subhierarchies, s/./\// when
+ * expanding '@' to jail / vimage name.
+ *
+ * XXX revisit buffer length checking.
+ */
+ CURVNET_SET_QUIET(TD_TO_VNET(curthread));
+ if (V_morphing_symlinks) {
+ char *sp = strchr(cp, '@');
+
+ if (sp) {
+ char *vname = td->td_ucred->cr_prison->pr_name;
+ int vnamelen = strlen(vname);
+ int i;
+
+ if (vnamelen >= auio.uio_resid) {
+ if (ndp->ni_pathlen > 1)
+ uma_zfree(namei_zone, cp);
+ error = ENAMETOOLONG;
+ CURVNET_RESTORE();
+ break;
+ }
+ bcopy(sp + 1, sp + vnamelen,
+ linklen - (sp - cp));
+ bcopy(td->td_ucred->cr_prison->pr_name,
+ sp, vnamelen);
+ linklen += (vnamelen - 1);
+ for (i = 0; i < vnamelen; i++)
+ if (sp[i] == '.')
+ sp[i] = '/';
+ }
+ }
+ CURVNET_RESTORE();
+#endif
if (linklen + ndp->ni_pathlen >= MAXPATHLEN) {
if (ndp->ni_pathlen > 1)
uma_zfree(namei_zone, cp);

View file

@ -1,14 +0,0 @@
# $FreeBSD$
PROG= vimage
LDADD= -ljail
DPADD= ${LIBJAIL}
WARNS?= 2
CFLAGS+= -I../../../sys
MAN= vimage.8
BINDIR?= /usr/sbin
.include <bsd.prog.mk>

View file

@ -1,195 +0,0 @@
.\" Copyright (c) 2002, 2003 Marko Zec <zec@fer.hr>
.\" Copyright (c) 2009 University of Zagreb
.\" Copyright (c) 2009 FreeBSD Foundation
.\"
.\" All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" $FreeBSD$
.\"
.Dd August 25, 2009
.Dt VIMAGE 8
.Os
.Sh NAME
.Nm vimage
.Nd manage virtual network stacks
.Sh SYNOPSIS
.Nm
.Op Fl c | m
.Ar vname
.Op Ar param=value ...
.Nm
.Fl d
.Ar vname
.Nm
.Fl l
.Op Fl rvj
.Op Ar vname
.Nm
.Fl i
.Ar vname ifname
.Op Ar newifname
.Nm
.Ar vi_name
.Op command ...
.Sh DESCRIPTION
The
.Nm
utility is an alternative user interface for controlling virtual network
stacks in FreeBSD, aimed primarily at supporting legacy applications
which are not yet converted to using
.Xr jail 8 ,
.Xr jexec 8 ,
and
.Xr jls 8 .
.
.Ss Overview
A virtual image or vimage is a jail with its own independent network
stack instance. Every process, socket and network interface present
in the system is always attached to one, and only one, virtual network
stack instance (vnet).
During system bootup sequence a default vnet
is created to which all the configured interfaces and user processes
are initially attached.
Assuming that enough system resources are
are available, a user with sufficient privileges can create and manage
a hierarchy of subordinated virtual images.
The
.Nm
command allows for creation, deletion and monitoring of virtual images,
as well as for execution of arbitrary processes in a targeted virtual
image.
.Ss Invocation
If invoked with no modifiers, the
.Nm
command spawns a new interactive shell in virtual image
.Ar vname .
If optional additional arguments following
.Ar vname
are provided, the first of those will be executed in place of the
interactive shell, and the rest of the arguments will be passed as
arguments to the executed command.
.Pp
The following modifiers are available:
.Bl -tag -width indent
.It Fl c
Create a new virtual image named
.Ar vname .
Additional arguments, if provided, may be used to specify operating
parameters different from defaults, in format
.Ar param=value .
See
.Xr jail 8
for an extensive list of available parameters.
.It Fl m
Modify the parameters of a virtual image named
.Ar vname ,
using the same syntax as with the -c form of the command.
.It Fl d
Delete the virtual image
.Ar vname .
No processes and/or sockets should exist in the target virtual image
in order for the delete request to succeed. Non-loopback interfaces
residing in the target virtual image will be reassigned to the virtual
image's parent.
.It Fl l
List the properties and statistics for virtual images one level
below the current one in the hierarchy. If an optional argument
.Ar vname
is provided, only the information regarding the target virtual image
.Ar vname
is displayed.
With the optional
.Op Ar -r
switch enabled the list will include all virtual images below the
current level in the vimage hierarchy.
Enabling the optional
.Op Ar -v
or
.Op Ar -j
switches results in a more detailed output.
.It Fl i
Move interface
.Ar ifname
to the target virtual image
.Ar vname .
Interfaces will be automatically renamed to
.So
ethXX
.Sc ,
unless an optional argument specifying the desired interface name
.Op Ar newifname
is provided.
.El
.Sh EXAMPLES
Create a new virtual image named
.So v1
.Sc ,
which is allowed to create and manage an own subhierarchy of vimages:
.Pp
.Dl vimage -c v1 children.max=100
.Pp
Execute the
.So ifconfig
.Sc command in the virtual image
.So v1
.Sc :
.Pp
.Dl vimage v1 ifconfig
.Pp
Move the interface
.So vlan0
.Sc to the virtual image
.So v1
.Sc while renaming the interface as
.So
ve0
.Sc :
.Pp
.Dl vimage -i v1 vlan0 ve0
.Pp
Show the status information for virtual image
.So v1
.Sc :
.Pp
.Dl vimage -lv v1
.Sh DIAGNOSTICS
The
.Nm
command exits 0 on success, and >0 if an error occurs.
.Sh SEE ALSO
.Xr jail 8
.Xr jexec 8
.Xr jls 8
.Sh HISTORY
Network stack virtualization framework first appeared as a patchset
against the FreeBSD 4.7 kernel in 2002, and was maintained outside
of the main FreeBSD tree.
As a result of a project sponsored by the FreeBSD Foundation and
Stiching NLNet, integrated virtualized network stack first appeared
in FreeBSD 8.0.
.Sh BUGS
Deletion of vimages / vnets is known to leak kernel memory and fail at
stopping various timers, hence may lead to system crashes.
.Sh AUTHOR
.An "Marko Zec" Aq zec@fer.hr

View file

@ -1,390 +0,0 @@
/*
* Copyright (c) 2002-2004 Marko Zec <zec@fer.hr>
* Copyright (c) 2009 University of Zagreb
* Copyright (c) 2009 FreeBSD Foundation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $FreeBSD$
*/
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/jail.h>
#include <sys/socket.h>
#include <net/if.h>
#include <ctype.h>
#include <jail.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
typedef enum {
VI_SWITCHTO,
VI_CREATE,
VI_MODIFY,
VI_DESTROY,
VI_IFMOVE,
VI_GET
} vi_cmd_t;
typedef struct vimage_status {
char name[MAXPATHLEN]; /* Must be first field for strcmp(). */
char path[MAXPATHLEN];
char hostname[MAXPATHLEN];
char domainname[MAXPATHLEN];
int jid;
int parentjid;
int vnet;
int childcnt;
int childmax;
int cpuset;
int rawsock;
int socket_af;
int mount;
} vstat_t;
#define VST_SIZE_STEP 1024
#define MAXPARAMS 32
static int getjail(vstat_t *, int, int);
static char *invocname;
static void
usage(void)
{
fprintf(stderr,
"usage: %s [-c | -m] vname [param=value ...]\n"
" %s -d vname\n"
" %s -l[rvj] [vname]\n"
" %s -i vname ifname [newifname]\n"
" %s vname [command ...]\n",
invocname, invocname, invocname, invocname, invocname);
exit(1);
}
int
main(int argc, char **argv)
{
struct jailparam params[MAXPARAMS];
char ifname[IFNAMSIZ];
struct ifreq ifreq;
vi_cmd_t newcmd, cmd;
int recurse = 0;
int verbose = 0;
int jid, i, s, namelen;
int vst_size, vst_last;
vstat_t *vst;
char *str;
char ch;
invocname = argv[0];
newcmd = cmd = VI_SWITCHTO; /* Default if no modifiers specified. */
while ((ch = getopt(argc, argv, "cdijlmrv")) != -1) {
switch (ch) {
case 'c':
newcmd = VI_CREATE;
break;
case 'm':
newcmd = VI_MODIFY;
break;
case 'd':
newcmd = VI_DESTROY;
break;
case 'l':
newcmd = VI_GET;
break;
case 'i':
newcmd = VI_IFMOVE;
break;
case 'r':
recurse = 1;
break;
case 'v':
verbose++;
break;
case 'j':
verbose = 2;
break;
default:
usage();
}
if (cmd == VI_SWITCHTO || cmd == newcmd)
cmd = newcmd;
else
usage();
}
argc -= optind;
argv += optind;
if ((cmd != VI_GET && (argc == 0 || recurse != 0 || verbose != 0)) ||
(cmd == VI_IFMOVE && (argc < 2 || argc > 3)) ||
(cmd == VI_MODIFY && argc < 2) || argc >= MAXPARAMS)
usage();
switch (cmd) {
case VI_GET:
vst_last = 0;
vst_size = VST_SIZE_STEP;
if ((vst = malloc(vst_size * sizeof(*vst))) == NULL)
break;
if (argc == 1)
namelen = strlen(argv[0]);
else
namelen = 0;
jid = 0;
while ((jid = getjail(&vst[vst_last], jid, verbose)) > 0) {
/* Skip jails which do not own vnets. */
if (vst[vst_last].vnet != 1)
continue;
/* Skip non-matching vnames / hierarchies. */
if (namelen &&
((strlen(vst[vst_last].name) < namelen ||
strncmp(vst[vst_last].name, argv[0], namelen) != 0)
|| (strlen(vst[vst_last].name) > namelen &&
vst[vst_last].name[namelen] != '.')))
continue;
/* Skip any sub-trees if -r not requested. */
if (!recurse &&
(strlen(vst[vst_last].name) < namelen ||
strchr(&vst[vst_last].name[namelen], '.') != NULL))
continue;
/* Grow vst table if necessary. */
if (++vst_last == vst_size) {
vst_size += VST_SIZE_STEP;
vst = realloc(vst, vst_size * sizeof(*vst));
if (vst == NULL)
break;
}
}
if (vst == NULL)
break;
/* Sort: the key is the 1st field in *vst, i.e. vimage name. */
qsort(vst, vst_last, sizeof(*vst), (void *) strcmp);
for (i = 0; i < vst_last; i++) {
if (!verbose) {
printf("%s\n", vst[i].name);
continue;
}
printf("%s:\n", vst[i].name);
printf(" Path: %s\n", vst[i].path);
printf(" Hostname: %s\n", vst[i].hostname);
printf(" Domainname: %s\n", vst[i].domainname);
printf(" Children: %d\n", vst[i].childcnt);
if (verbose < 2)
continue;
printf(" Children limit: %d\n", vst[i].childmax);
printf(" CPUsetID: %d\n", vst[i].cpuset);
printf(" JID: %d\n", vst[i].jid);
printf(" PJID: %d\n", vst[i].parentjid);
printf(" Raw sockets allowed: %d\n", vst[i].rawsock);
printf(" All AF allowed: %d\n", vst[i].socket_af);
printf(" Mount allowed: %d\n", vst[i].mount);
}
free(vst);
exit(0);
case VI_IFMOVE:
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
break;
if ((jid = jail_getid(argv[0])) < 0)
break;
ifreq.ifr_jid = jid;
strncpy(ifreq.ifr_name, argv[1], sizeof(ifreq.ifr_name));
if (ioctl(s, SIOCSIFVNET, (caddr_t)&ifreq) < 0)
break;
close(s);
if (argc == 3)
snprintf(ifname, sizeof(ifname), "%s", argv[2]);
else
snprintf(ifname, sizeof(ifname), "eth0");
ifreq.ifr_data = ifname;
/* Do we need to rename the ifnet? */
if (strcmp(ifreq.ifr_name, ifname) != 0) {
/* Switch to the context of the target vimage. */
if (jail_attach(jid) < 0)
break;
if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
break;
for (namelen = 0; isalpha(ifname[namelen]); namelen++);
i = 0;
/* Search for a free ifunit in target vnet. Unsafe. */
while (ioctl(s, SIOCSIFNAME, (caddr_t)&ifreq) < 0) {
snprintf(&ifname[namelen],
sizeof(ifname) - namelen, "%d", i);
/* Emergency brake. */
if (i++ == IF_MAXUNIT)
break;
}
}
if (i < IF_MAXUNIT)
printf("%s@%s\n", ifname, argv[0]);
else
printf("%s@%s\n", ifreq.ifr_name, argv[0]);
exit(0);
case VI_CREATE:
if (jail_setv(JAIL_CREATE,
"name", argv[0],
"vnet", NULL,
"host", NULL,
"persist", NULL,
"allow.raw_sockets", "true",
"allow.socket_af", "true",
"allow.mount", "true",
NULL) < 0)
break;
if (argc == 1)
exit(0);
/* Not done yet, proceed to apply non-default parameters. */
case VI_MODIFY:
jailparam_init(&params[0], "name");
jailparam_import(&params[0], argv[0]);
for (i = 1; i < argc; i++) {
for (str = argv[i]; *str != '=' && *str != 0; str++) {
/* Do nothing - search for '=' delimeter. */
}
if (*str == 0)
break;
*str++ = 0;
if (*str == 0)
break;
jailparam_init(&params[i], argv[i]);
jailparam_import(&params[i], str);
}
if (i != argc)
break;
if (jailparam_set(params, i, JAIL_UPDATE) < 0)
break;
exit(0);
case VI_DESTROY:
if ((jid = jail_getid(argv[0])) < 0)
break;
if (jail_remove(jid) < 0)
break;
exit(0);
case VI_SWITCHTO:
if ((jid = jail_getid(argv[0])) < 0)
break;
if (jail_attach(jid) < 0)
break;
if (argc == 1) {
printf("Switched to vimage %s\n", argv[0]);
if ((str = getenv("SHELL")) == NULL)
execlp("/bin/sh", invocname, NULL);
else
execlp(str, invocname, NULL);
} else
execvp(argv[1], &argv[1]);
break;
default:
/* Should be unreachable. */
break;
}
if (jail_errmsg[0])
fprintf(stderr, "Error: %s\n", jail_errmsg);
else
perror("Error");
exit(1);
}
static int
getjail(vstat_t *vs, int lastjid, int verbose)
{
struct jailparam params[32]; /* Must be > max(psize). */
int psize = 0;
bzero(params, sizeof(params));
bzero(vs, sizeof(*vs));
jailparam_init(&params[psize], "lastjid");
jailparam_import_raw(&params[psize++], &lastjid, sizeof lastjid);
jailparam_init(&params[psize], "vnet");
jailparam_import_raw(&params[psize++], &vs->vnet, sizeof(vs->vnet));
jailparam_init(&params[psize], "name");
jailparam_import_raw(&params[psize++], &vs->name, sizeof(vs->name));
if (verbose == 0)
goto done;
jailparam_init(&params[psize], "path");
jailparam_import_raw(&params[psize++], &vs->path, sizeof(vs->path));
jailparam_init(&params[psize], "host.hostname");
jailparam_import_raw(&params[psize++], &vs->hostname,
sizeof(vs->hostname));
jailparam_init(&params[psize], "host.domainname");
jailparam_import_raw(&params[psize++], &vs->domainname,
sizeof(vs->domainname));
jailparam_init(&params[psize], "children.cur");
jailparam_import_raw(&params[psize++], &vs->childcnt,
sizeof(vs->childcnt));
if (verbose == 1)
goto done;
jailparam_init(&params[psize], "children.max");
jailparam_import_raw(&params[psize++], &vs->childmax,
sizeof(vs->childmax));
jailparam_init(&params[psize], "cpuset.id");
jailparam_import_raw(&params[psize++], &vs->cpuset,
sizeof(vs->cpuset));
jailparam_init(&params[psize], "parent");
jailparam_import_raw(&params[psize++], &vs->parentjid,
sizeof(vs->parentjid));
jailparam_init(&params[psize], "allow.raw_sockets");
jailparam_import_raw(&params[psize++], &vs->rawsock,
sizeof(vs->rawsock));
jailparam_init(&params[psize], "allow.socket_af");
jailparam_import_raw(&params[psize++], &vs->socket_af,
sizeof(vs->socket_af));
jailparam_init(&params[psize], "allow.mount");
jailparam_import_raw(&params[psize++], &vs->mount, sizeof(vs->mount));
done:
vs->jid = jailparam_get(params, psize, 0);
jailparam_free(params, psize);
return (vs->jid);
}

File diff suppressed because it is too large Load diff

View file

@ -1,7 +0,0 @@
#!/bin/sh
echo Restoring /kernel.old ...
install -m 555 -o root -g wheel -fschg /kernel.old /kernel
rm -rf /modules
mv /modules.old /modules

View file

@ -1,21 +0,0 @@
#!/bin/sh
PREV=""
if [ ! -e "/boot/kernel.old" ] ; then
if [ ! -e "/boot/GENERIC" ] ; then
echo Previous kernel does not exist in /boot/kernel.old or /boot/GENERIC !
exit 1;
else
PREV="/boot/GENERIC"
fi;
else
PREV="/boot/kernel.old"
fi;
echo Removing current kernel...
chflags -R noschg /boot/kernel
rm -rf /boot/kernel
echo Restoring previous kernel from $PREV...
mv $PREV /boot/kernel
exit 0;

View file

@ -1,96 +0,0 @@
#!/bin/sh
VER=0.0
# determine FreeBSD 4.11 or 8.x
REL=`uname -r`
case "$REL" in
9.*)
echo "Using FreeBSD 9.x..."
KERN=9.x
SCRIPTVER=8.x
;;
8.*)
echo "Using FreeBSD 8.x..."
KERN=8.x
SCRIPTVER=8.x
;;
4.11-RELEASE)
echo "Using FreeBSD 4.11..."
KERN=4.11
SCRIPTVER=4.11
;;
*)
echo "What version of FreeBSD are you running (4.11/8.x) ?"
exit 1
esac
if [ "a$1" = "a" ]
then
echo "usage: ./core-kernel-release.sh 20080228 [clean]"
echo a version number is required
exit 1;
else
VER=$1
fi;
if [ "a$2" = "aclean" ]
then
echo Cleaning up...
rm -f core-kernel.pkglist.tmp
rm -f core-kernel.pkglist
rm -f core-kernel-${KERN}-${VER}.tbz
exit
fi;
# check for /kernel.new on 4.11
if [ ${KERN} = "4.11" ]
then
if [ -e "/kernel.new" ]
then
echo Note: proceeding using this kernel...
ls -al /kernel.new
else
echo "error: first copy the desired kernel to /kernel.new"
exit
fi;
fi;
#
# build the packing list
#
echo @comment ORIGIN:net/core-kernel > core-kernel.pkglist
if [ ${KERN} = "4.11" ]
# FreeBSD 4.11
then
echo @cwd / >> core-kernel.pkglist
echo kernel.new >> core-kernel.pkglist
find /modules \! -type d > core-kernel.pkglist.tmp
find /sbin/vimage >> core-kernel.pkglist.tmp
find /usr/share/man/man8/vimage.8.gz >> core-kernel.pkglist.tmp
find /sbin/ngctl >> core-kernel.pkglist.tmp
find /usr/share/man/man8/ngctl.8.gz >> core-kernel.pkglist.tmp
# FreeBSD 8.x
else
echo @cwd /boot >> core-kernel.pkglist
PWDOLD=${PWD}
cd /boot
find kernel \! -type d > ${PWDOLD}/core-kernel.pkglist.tmp
cd ${PWDOLD}
echo @cwd / >> core-kernel.pkglist.tmp
find /usr/sbin/vimage >> core-kernel.pkglist.tmp
find /usr/share/man/man8/vimage.8.gz >> core-kernel.pkglist.tmp
fi;
# remove leading '/' from lines
sed -e "s,^/,," core-kernel.pkglist.tmp >> core-kernel.pkglist
#
# build the package
#
pkg_create -c core-kernel.pkgdesc -d core-kernel.pkgdesclong -f core-kernel.pkglist -i core-kernel-preinstall-${SCRIPTVER}.sh -K core-kernel-deinstall-${SCRIPTVER}.sh -v core-kernel-${KERN}-${VER}.tbz

View file

@ -1,18 +0,0 @@
#!/bin/sh
if [ "x$2" = "xPOST-INSTALL" ]
then
install -m 555 -o root -g wheel -fschg /kernel.new /kernel
rm -f /kernel.new
echo Please reboot this machine to enable the new CORE kernel.
exit 0;
fi;
install -m 555 -o root -g wheel -fschg /kernel /kernel.old
if [ -e /modules.old ]
then
rm -rf /modules.old
fi;
mv /modules /modules.old
exit 0;

View file

@ -1,27 +0,0 @@
#!/bin/sh
if [ "x$2" = "xPOST-INSTALL" ]
then
echo Please reboot this machine to enable the new CORE kernel.
exit 0;
fi;
# PRE-INSTALL
# save the GENERIC kernel
OLDNAME=`strings /boot/kernel/kernel | tail -n 1`
if [ "x$OLDNAME" = "xGENERIC" ]
then
chflags -R noschg /boot/kernel
mv /boot/kernel /boot/GENERIC
exit 0;
fi;
# get rid of /boot/kernel.old if it is in the way
if [ -e "/boot/kernel.old" ] ; then
chflags -R noschg /boot/kernel.old
rm -rf /boot/kernel.old
fi;
chflags -R noschg /boot/kernel
mv /boot/kernel /boot/kernel.old
exit 0;

View file

@ -1 +0,0 @@
CORE FreeBSD kernel enables lightweight virtual machines

View file

@ -1 +0,0 @@
This package contains the CORE FreeBSD kernel with kernel modules. Custom modules include ng_pipe and ng_wlan. Also contains the userspace utility program vimage. This package can be used along with the CORE GUI to build emulated networks. This kernel is based on the GENERIC kernel with the VIMAGE option turned on (per-jail network stack virtualization), and with a small patch to allow per-node filesystem access.

View file

@ -1,68 +0,0 @@
#!/bin/sh
VER=`grep -m 1 "set CORE_VERSION" ../../gui/version.tcl | awk '{ print $3 }'`
ARCH=`uname -m`
# determine FreeBSD 4.11 or 7.x
REL=`uname -r`
case "$REL" in
9.*)
echo "Using FreeBSD 9.x..."
KERN=9.x
;;
8.*)
echo "Using FreeBSD 8.x..."
KERN=8.x
;;
4.11-RELEASE)
echo "Using FreeBSD 4.11..."
KERN=4.11
;;
*)
echo "What version of FreeBSD are you running (4.11/8.x) ?"
exit 1
esac
if [ "a$1" = "aclean" ]
then
echo Cleaning up...
rm -f core.pkglist.tmp
rm -f core.pkglist
rm -f core-${KERN}-${VER}.tbz
rm -rf /tmp/staging
exit
fi;
#
# build the packing list
#
echo @comment ORIGIN:net/core > core.pkglist
echo @cwd /usr/local >> core.pkglist
PKG_BASH=`pkg_info -E -x ^bash`
# for 4.11 change this back to 8.4
PKG_TCL=`pkg_info -E -x ^tcl-8.5`
PKG_TK=`pkg_info -E -x ^tk-8.5`
echo @pkgdep ${PKG_BASH} >> core.pkglist
echo @comment DEPORIGIN:shells/bash >> core.pkglist
echo @pkgdep ${PKG_TCL} >> core.pkglist
echo @comment DEPORIGIN:lang/tcl85 >> core.pkglist
echo @pkgdep ${PKG_TK} >> core.pkglist
echo @comment DEPORIGIN:x11-toolkits/tk85 >> core.pkglist
SAVEDIR=`pwd`
cd ../..
rm -rf /tmp/staging
gmake DESTDIR=/tmp/staging install
cd $SAVEDIR
find /tmp/staging/usr/local \! -type d >> core.pkglist
echo @cwd /etc >> core.pkglist
find /tmp/staging/etc \! -type d >> core.pkglist
sed -e "s,^/tmp/staging/usr/local/,," core.pkglist > core.pkglist.new1
sed -e "s,^/tmp/staging/etc/,," core.pkglist.new1 > core.pkglist
rm -f core.pkglist.new1
#
# build the package
#
pkg_create -c core.pkgdesc -d core.pkgdesclong -f core.pkglist -v core-${KERN}-${ARCH}-${VER}.tbz

View file

@ -1 +0,0 @@
Common Open Research Emulator userspace components

View file

@ -1,3 +0,0 @@
The Common Open Research Emulator (CORE) is a tool that allows you to emulate entire networks on a FreeBSD or Linux machine. You can connect these emulated networks to live networks (or to additional emulated networks) via the machine's physical interfaces. This package contains CORE userspace components for easily drawing topologies that drive lightweight virutalized network stacks.
WWW: http://www.nrl.navy.mil/itd/ncs/products/core

View file

@ -24,15 +24,7 @@ dist-hook:
rm -rf $(distdir)/xen/.svn
# install startup scripts based on --with-startup=option configure option
# FreeBSD, init.d (default), systemd, SUSE
if WANT_BSD
startupdir = /usr/local/etc/rc.d
startup_SCRIPTS = core-daemon
core-daemon: core-daemon-rc.d
cp $< $@
else
# init.d (default), systemd, SUSE
if WANT_INITD
startupdir = /etc/init.d
startup_SCRIPTS = core-daemon
@ -51,8 +43,6 @@ startup_SCRIPTS = core-daemon
core-daemon: core-daemon-init.d-SUSE
cp $< $@
endif
# endif FreeBSD
endif
# remove extra scripts and their directories if they are empty
uninstall-hook: