salsa.debian.org/debian / smcroute

Imported Upstream version 1.99.2

Micha Lenk · 12 years ago 🏷 upstream/1.99.2commit 37e4dc4 · parent 5fc4c3a · child c38d595 · patch
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..07a46fa
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,11 @@
+autom4te.cache
+build.h
+config.h
+Makefile
+mcsender
+smcroute
+unittest
+.*.d
+*.o
+*.log
+*.status
diff --git a/AUTHORS b/AUTHORS
index fd866b8..8e2890f 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,8 +1,23 @@
-smcroute's authors
-------------------
+Authors
+=======
 
-smcroute was originally (2001-2005) developed by 
-Carsten Schill <carsten@cschill.de>.
+Year:     2001-2005
+Author:   Carsten Schill <carsten@cschill.de>, original author
+Releases: --> 0.92
+URL:      http://www.cschill.de/smcroute/
+
+Year:     2006-2011
+Releases: Version 0.93 --> 0.95
+Authors:  Julien BLACHE <jb@jblache.org>,
+          Todd Hayton <todd.hayton@gmail.com>, and
+          Micha Lenk <micha@debian.org>
+URL:      http://alioth.debian.org/projects/smcroute
+
+Year:     2011-
+Releases: 1.93.0 -->
+Authors:  Joachim Nilsson <troglobit@gmail.com>,
+          Todd Hayton <todd.hayton@gmail.com>,
+          Micha Lenk <micha@debian.org>, and
+          Julien BLACHE <jb@jblache.org>
+URL:      https://github.com/troglobit/smcroute
 
-It is now (2006-) maintained by Julien BLACHE <jb@jblache.org>, 
-Todd Hayton <todd.hayton@gmail.com> and Micha Lenk <micha@debian.org>.
diff --git a/ChangeLog b/ChangeLog
index f14eef0..207f396 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,58 @@
+smcroute 1.99.1 -> 1.99.2
+ * Fix issue #2: Loop forever bug when deleting new (*,G) sourceless routes
+   Bug report and patch by Jean-Baptiste Maillet
+
+smcroute 1.99.0 -> 1.99.1
+ * Fix possible memory leak on Linux
+ * Fix missing #ifdefs when building on systems w/o IPv6
+ * Fix possible race in Makefile when building in (massive) parallel
+ * Fix build problems on RedHat EL5/CentOS5, i.e., Linux <= 2.6.25
+
+smcroute 1.98.3 -> 1.99.0
+ * Bugfix: SMCRoute segfault when starting on interface that is up but has
+	no valid IPv4 address yet. Bug introduced in 1.98.3
+ * Feature: Experimental source-less (*,G) IPv4 mutlicast routing. Most
+	UNIX kernels are (S,G) based, i.e., you need to supply the source
+	address with the multicast group to setup a kernel routing rule.
+	However, daemons like mrouted and pimd emulate (*,G) by listening
+	for IGMPMSG_NOCACHE messages from the kernel. SMCRoute now also
+	implements this, for IPv4 only atm, by placing all (*,G) routes in
+	a list and adding matching (S,G) routes on-demand at runtime. All
+	routes matching this (*,G) are removed when reloading the conf
+	file on SIGHUP or when the user sends an IPC (-r) command to remove
+	the (*,G) rule.
+ * Feature: Actually check if running as root at startup.
+ * Cleanup: Also, slightly improved error messages including some minor
+	cleanup and readability improvements.
+
+smcroute 1.98.1 -> 1.98.3
+ * Cleanup IPv6 #ifdefs and replace IN6_MULTICAST() with IN6_IS_ADDR_MULTICAST()
+   This commit cleans up a lot of the IPv6 related #ifdefs, some minor
+   function name refactoring and squash of some _init and _enable funcs
+   into one for clarity and clearer error messages to the user.
+ * Check for existence of asprintf() to pidfile() and add -D_GNU_SOURCE to CPPFLAGS
+   using AC_GNU_SOURCE in configure.ac
+ * Fixes FTBFS when host lacks IPv6 support.
+
+smcroute 1.98.0 -> 1.98.1
+ * Bugfix: Client failed to send commands to daemon.
+ * Bugfix: Several FTBFS fixed for GCC 4.6.x and -W -Wall
+
+smcroute 0.95 -> 1.98.0
+ * SMCRoute2 Announced!
+ * Feature: Support for smcroute.conf file for daemon
+   Add support for reading mroutes and mgroups from a configuration file.
+	mgroup from IFNAME group MCGROUP
+	mroute from IFNAME source ADDRESS group MCGROUP to IFNAME [IFNAME ...]
+   Both IPv4 and IPv6 address formats are supported.
+ * Feature: Support for signals, reload conf file on SIGHUP
+ * Refactor: Insecure handling of pointers potentially outside array boundaries.
+ * Bugfix: Invalid use of varargs in call to snprintf(), use vsnprintf() instead.
+ * Feature: Add -n switch to support running smcroute in foreground.
+ * Refactor: Major cleanup, reindent to Linux C-style, for improved maintainability.
+ * Bugfix: Invalid MRouterFD6 fd crashes smcroute, always check for valid fd.
+ * Bugfix: Several minor bugfixes; type mismatches and unused return values.
+
 smcroute 0.94.1 -> 0.95
  * Feature request #313278: Added support for FreeBSD
    SMCRoute now builds and runs on FreeBSD kernels.  This was successfully
@@ -24,36 +79,36 @@ smcroute 0.93 -> 0.94
 	remove commands.
  * Added support for joins and leaves ('j'/'l') to IPv6 multicast groups.
  * Added support for sending to IPv6 multicast addresses to mcsender tool.
- * Added command line option to mcsender tool to allow user to specify the 
+ * Added command line option to mcsender tool to allow user to specify the
 	outgoing interface for datagrams sent.
  * Added autoconf support for smcroute build.
-	
+
 smcroute 0.92 -> 0.93
  * fixed the "smcroute looses output interfaces" bug (Carsten Schill, 0.93
     unreleased).
 
 smcroute 0.90 -> 0.92
   * fixed the 'mroute: pending queue full, dropping entries' error
-    Smcroute 0.90 didn't care about the IGMP messages delivered to the 
-    UDP socket that establish the MC-Router API. After some time the 
+    Smcroute 0.90 didn't care about the IGMP messages delivered to the
+    UDP socket that establish the MC-Router API. After some time the
     queue for the sockets filled up and the 'pending queue full' message
     was send from the kernel. To my knowledge this didn't affect smcroute
     or the operating system.
-    - version 0.92 reads the ICMP messages now from the UDP socket and 
+    - version 0.92 reads the ICMP messages now from the UDP socket and
       logs them to syslog with daemon/debug
     - smcroute does no further processing of this messages
-  * increased the number of supported interfaces 
-    The 16 interface limit of version 0.90 (interfaces as listed with 
-    ifconfig) was to small, especially when alias interfaces where 
+  * increased the number of supported interfaces
+    The 16 interface limit of version 0.90 (interfaces as listed with
+    ifconfig) was to small, especially when alias interfaces where
     defined.
-    - up to 40 interfaces are no recognized by smcroute  
-    - this does not change the number of 'virtual interfaces' supported 
+    - up to 40 interfaces are no recognized by smcroute
+    - this does not change the number of 'virtual interfaces' supported
       by the kernel (32)
-    - not all interfaces recognized by smcroute (40) results in a 
+    - not all interfaces recognized by smcroute (40) results in a
       'virtual interface' of the kernel (32)
 
 smcroute 0.80 -> 0.90
-  * added MC group join (-j) and leave (-l) functionality 
+  * added MC group join (-j) and leave (-l) functionality
     - the options enable/disable the sending of IGMP join messages for
       a multicast group on a specific interface
   * removed the '<OutputIntf> [<OutputIntf>] ...' for the '-r' option
@@ -64,4 +119,4 @@ smcroute 0.80 -> 0.90
   * added a test script (tst-smcroute.pl)
   * added a man page
   * fixed some minor bugs
-  
+
diff --git a/Makefile.in b/Makefile.in
new file mode 100644
index 0000000..aed17cf
--- /dev/null
+++ b/Makefile.in
@@ -0,0 +1,50 @@
+##  smcroute - static multicast routing control 
+.EXPORT_ALL_VARIABLES:
+
+PACKAGE_VERSION = @PACKAGE_VERSION@
+PACKAGE_TARNAME = @PACKAGE_TARNAME@
+CONFIG          = $(PACKAGE_TARNAME).conf
+PKG             = $(PACKAGE_TARNAME)-$(PACKAGE_VERSION)
+ARCHIVE         = $(PKG).tar.bz2
+DISTFILES       = $(CONFIG) README AUTHORS TODO ChangeLog
+DOCDIR          = $(DESTDIR)$(docdir)
+
+RM             ?= rm -f
+CC             ?= @CC@
+CFLAGS         += @CFLAGS@
+
+prefix         ?= @prefix@
+exec_prefix    ?= @exec_prefix@
+datarootdir    ?= @datarootdir@
+docdir         ?= @docdir@
+mandir         ?= @mandir@
+sbindir        ?= @sbindir@
+
+all:
+	@make -C src $@
+
+install: 
+	@make -C doc $@
+	@make -C src $@
+	@install -d $(DOCDIR)
+	@for file in $(DISTFILES); do \
+		install -b -m 0644 $$file $(DOCDIR)/$$file; \
+	done
+
+uninstall: 
+	@make -C doc $@
+	@make -C src $@
+	-@$(RM) -r $(DESTDIR)$(docdir)
+
+clean:
+	@make -C src $@
+
+distclean:
+	@make -C src $@
+	-@$(RM) -rf config.status config.log doc/Makefile Makefile autom4te.cache
+
+dist: distclean
+	@echo "Building bzip2 tarball of $(PKG) in parent dir..."
+	git archive --format=tar --prefix=$(PKG)/ $(PACKAGE_VERSION) | bzip2 >../$(ARCHIVE)
+	@(cd ..; md5sum $(ARCHIVE) | tee $(ARCHIVE).md5)
+
diff --git a/README b/README
new file mode 100644
index 0000000..bf756e7
--- /dev/null
+++ b/README
@@ -0,0 +1,80 @@
+SMCRoute - A static multicast route tool
+========================================
+
+SMCRoute is a command line tool to manipulate the multicast routes of a UNIX
+kernel. It supports both IPv4 and IPv6 multicast routing. SMCRoute can be
+used as an alternative to dynamic multicast routers like mrouted or pimd in
+setups where static multicast routes should be maintained and/or no proper
+IGMP or MLD signaling exists.
+
+Generally multicast routes exists in the kernel only as long as smcroute
+or another multicast routing daemon is running. Only one multicast routing
+daemon can be active at a time, so it's impossible to run smcroute and, e.g.,
+mrouted at the same time.
+
+SMCRoute is maintained at GitHub. Previously the code has been hosted by
+Debian at Alioth and before that by Carsten Schill, the original author.
+
+Usage
+-----
+SMCRoute is both a daemon and a client. You must start the daemon to be able
+to setup multicast routes.
+
+   # smcroute -d
+
+By default SMCRoute will look for a configuration file in /etc/smcroute.conf,
+which can look something like this:
+
+   mgroup from eth0 group 225.1.2.3
+   mroute from eth0 group 225.1.2.3 source 192.168.1.42 to eth1 eth2
+
+The first line means "Join multicast group 225.1.2.3 on interface eth0",
+and is for layer-2 devices (switches) with IGMP snooping implemented to
+open up multicast for that group to be flooded to us.
+
+The second line is the actual layer-3 routing entry. Here we say that
+multicast data originating from 192.168.1.42 on eth0 to multicast group
+225.1.2.3 should be routed to interfaces eth1 and eth2.
+
+Note: To test the above you can use ping from another device. The multicast
+      should be visible as long as your IP# matches the "source" above and
+      you ping 225.1.2.3 AND REMEMBER TO SET TTL >1!
+
+      $ ping -I eth0 -t 2 225.1.2.3
+
+The TTL is what usually bites people trying out multicast the first time.
+There is a good reason for applications, e.g., ping to default to a TTL=1
+for multicast. That is to reduce the risk of flooding your network with
+data, remember multicast is like broadcast in nature. Only IGMP snooping-
+aware switches can help mitigate its broadcast effect.
+
+Traditionally, however, SMCRoute only had the client interface to interact
+with the daemon. To achieve the above two config file lines you have to:
+
+   # sleep 1
+
+To allow the daemon to startup properly (above) before interacting with it.
+
+   # smcroute -j eth0 225.1.2.3
+   # smcroute -a eth0 192.168.1.42 225.1.2.3 eth1 eth2
+
+Experimental
+------------
+Many people sometimes do not know where the multicast will originate from, or
+it will originate from several different sources but never at the same time.
+Up until 1.98.3 a user had to setup a unique routing rule for each possible
+source and group to be routed. However, from 1.99.0 it is now possible to use
+the wildcard address 0.0.0.0 (INADDR_ANY) for IPv4 multicast routes.
+
+Example smcroute.conf:
+
+   mgroup from eth0 group 225.1.2.3
+   mroute from eth0 group 225.1.2.3 to eth1 eth2
+
+or, from the command line:
+
+   # smcroute -j eth0 225.1.2.3
+   # smcroute -a eth0 0.0.0.0 225.1.2.3 eth1 eth2
+
+Good Luck!
+The SMCRoute Maintainers
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..a3ef998
--- /dev/null
+++ b/TODO
@@ -0,0 +1,14 @@
+                                                                       -*-org-*-
+
+* Add IPv6 support for (*, G), i.e., on-demand, routing rules.
+In SMCRoute 1.99.0 IPv4 support for source-less multicast routes was
+added. Adding support for IPv6 should be fairly straight forward, but
+needs figuring out the kernel interface and extensive testing.
+
+* Support for detecting link up/down on interfaces
+Also requires updating VIF/MIFs and mroutes accordingly.
+
+Optimal, and almost required, behavior would be to handle such
+transitions  without losing any traffic over established/active
+routing rules.
+
diff --git a/src/configure b/configure
similarity index 91%
rename from src/configure
rename to configure
index de3708c..25063c8 100755
--- a/src/configure
+++ b/configure
@@ -1,13 +1,11 @@
 #! /bin/sh
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.67 for smcroute 0.95.
+# Generated by GNU Autoconf 2.69 for smcroute 1.99.2.
 #
-# Report bugs to <micha@debian.org>.
+# Report bugs to <troglobit@gmail.com>.
 #
 #
-# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
-# 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Free Software
-# Foundation, Inc.
+# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc.
 #
 #
 # This configure script is free software; the Free Software Foundation
@@ -91,6 +89,7 @@ fi
 IFS=" ""	$as_nl"
 
 # Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
 case $0 in #((
   *[\\/]* ) as_myself=$0 ;;
   *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -135,6 +134,31 @@ export LANGUAGE
 # CDPATH.
 (unset CDPATH) >/dev/null 2>&1 && unset CDPATH
 
+# Use a proper internal environment variable to ensure we don't fall
+  # into an infinite loop, continuously re-executing ourselves.
+  if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then
+    _as_can_reexec=no; export _as_can_reexec;
+    # We cannot yet assume a decent shell, so we have to provide a
+# neutralization value for shells without unset; and this also
+# works around shells that cannot unset nonexistent variables.
+# Preserve -v and -x to the replacement shell.
+BASH_ENV=/dev/null
+ENV=/dev/null
+(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+case $- in # ((((
+  *v*x* | *x*v* ) as_opts=-vx ;;
+  *v* ) as_opts=-v ;;
+  *x* ) as_opts=-x ;;
+  * ) as_opts= ;;
+esac
+exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
+# Admittedly, this is quite paranoid, since all the known shells bail
+# out after a failed `exec'.
+$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
+as_fn_exit 255
+  fi
+  # We don't want this to propagate to other subprocesses.
+          { _as_can_reexec=; unset _as_can_reexec;}
 if test "x$CONFIG_SHELL" = x; then
   as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :
   emulate sh
@@ -168,7 +192,8 @@ if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then :
 else
   exitcode=1; echo positional parameters were not saved.
 fi
-test x\$exitcode = x0 || exit 1"
+test x\$exitcode = x0 || exit 1
+test -x / || exit 1"
   as_suggested="  as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO
   as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO
   eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" &&
@@ -213,14 +238,25 @@ IFS=$as_save_IFS
 
 
       if test "x$CONFIG_SHELL" != x; then :
-  # We cannot yet assume a decent shell, so we have to provide a
-	# neutralization value for shells without unset; and this also
-	# works around shells that cannot unset nonexistent variables.
-	BASH_ENV=/dev/null
-	ENV=/dev/null
-	(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
-	export CONFIG_SHELL
-	exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"}
+  export CONFIG_SHELL
+             # We cannot yet assume a decent shell, so we have to provide a
+# neutralization value for shells without unset; and this also
+# works around shells that cannot unset nonexistent variables.
+# Preserve -v and -x to the replacement shell.
+BASH_ENV=/dev/null
+ENV=/dev/null
+(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV
+case $- in # ((((
+  *v*x* | *x*v* ) as_opts=-vx ;;
+  *v* ) as_opts=-v ;;
+  *x* ) as_opts=-x ;;
+  * ) as_opts= ;;
+esac
+exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"}
+# Admittedly, this is quite paranoid, since all the known shells bail
+# out after a failed `exec'.
+$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2
+exit 255
 fi
 
     if test x$as_have_required = xno; then :
@@ -230,11 +266,11 @@ fi
     $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should"
     $as_echo "$0: be upgraded to zsh 4.3.4 or later."
   else
-    $as_echo "$0: Please tell bug-autoconf@gnu.org and micha@debian.org
-$0: about your system, including any error possibly output
-$0: before this message. Then install a modern shell, or
-$0: manually run the script under such a shell if you do
-$0: have one."
+    $as_echo "$0: Please tell bug-autoconf@gnu.org and
+$0: troglobit@gmail.com about your system, including any
+$0: error possibly output before this message. Then install
+$0: a modern shell, or manually run the script under such a
+$0: shell if you do have one."
   fi
   exit 1
 fi
@@ -323,6 +359,14 @@ $as_echo X"$as_dir" |
 
 
 } # as_fn_mkdir_p
+
+# as_fn_executable_p FILE
+# -----------------------
+# Test if FILE is an executable regular file.
+as_fn_executable_p ()
+{
+  test -f "$1" && test -x "$1"
+} # as_fn_executable_p
 # as_fn_append VAR VALUE
 # ----------------------
 # Append the text in VALUE to the end of the definition contained in VAR. Take
@@ -444,6 +488,10 @@ as_cr_alnum=$as_cr_Letters$as_cr_digits
   chmod +x "$as_me.lineno" ||
     { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; }
 
+  # If we had to re-execute with $CONFIG_SHELL, we're ensured to have
+  # already done that, so ensure we don't try to do so again and fall
+  # in an infinite loop.  This has already happened in practice.
+  _as_can_reexec=no; export _as_can_reexec
   # Don't try to exec as it changes $[0], causing all sort of problems
   # (the dirname of $[0] is not the place where we might find the
   # original and so on.  Autoconf is especially sensitive to this).
@@ -478,16 +526,16 @@ if (echo >conf$$.file) 2>/dev/null; then
     # ... but there are two gotchas:
     # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
     # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-    # In both cases, we have to default to `cp -p'.
+    # In both cases, we have to default to `cp -pR'.
     ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-      as_ln_s='cp -p'
+      as_ln_s='cp -pR'
   elif ln conf$$.file conf$$ 2>/dev/null; then
     as_ln_s=ln
   else
-    as_ln_s='cp -p'
+    as_ln_s='cp -pR'
   fi
 else
-  as_ln_s='cp -p'
+  as_ln_s='cp -pR'
 fi
 rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
 rmdir conf$$.dir 2>/dev/null
@@ -499,28 +547,8 @@ else
   as_mkdir_p=false
 fi
 
-if test -x / >/dev/null 2>&1; then
-  as_test_x='test -x'
-else
-  if ls -dL / >/dev/null 2>&1; then
-    as_ls_L_option=L
-  else
-    as_ls_L_option=
-  fi
-  as_test_x='
-    eval sh -c '\''
-      if test -d "$1"; then
-	test -d "$1/.";
-      else
-	case $1 in #(
-	-*)set "./$1";;
-	esac;
-	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
-	???[sx]*):;;*)false;;esac;fi
-    '\'' sh
-  '
-fi
-as_executable_p=$as_test_x
+as_test_x='test -x'
+as_executable_p=as_fn_executable_p
 
 # Sed expression to map a string onto a valid CPP name.
 as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
@@ -552,12 +580,12 @@ MAKEFLAGS=
 # Identity of this package.
 PACKAGE_NAME='smcroute'
 PACKAGE_TARNAME='smcroute'
-PACKAGE_VERSION='0.95'
-PACKAGE_STRING='smcroute 0.95'
-PACKAGE_BUGREPORT='micha@debian.org'
+PACKAGE_VERSION='1.99.2'
+PACKAGE_STRING='smcroute 1.99.2'
+PACKAGE_BUGREPORT='troglobit@gmail.com'
 PACKAGE_URL=''
 
-ac_unique_file="mclab.h"
+ac_unique_file="src/mclab.h"
 # Factoring default headers for most tests.
 ac_includes_default="\
 #include <stdio.h>
@@ -1061,7 +1089,7 @@ Try \`$0 --help' for more information"
     $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2
     expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null &&
       $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2
-    : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}
+    : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}"
     ;;
 
   esac
@@ -1112,8 +1140,6 @@ target=$target_alias
 if test "x$host_alias" != x; then
   if test "x$build_alias" = x; then
     cross_compiling=maybe
-    $as_echo "$as_me: WARNING: if you wanted to set the --build type, don't use --host.
-    If a cross compiler is detected then cross compile mode will be used" >&2
   elif test "x$build_alias" != "x$host_alias"; then
     cross_compiling=yes
   fi
@@ -1199,7 +1225,7 @@ if test "$ac_init_help" = "long"; then
   # Omit some internal or obsolete options to make the list less imposing.
   # This message is too long to be a string in the A/UX 3.1 sh.
   cat <<_ACEOF
-\`configure' configures smcroute 0.95 to adapt to many kinds of systems.
+\`configure' configures smcroute 1.99.2 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1260,7 +1286,7 @@ fi
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of smcroute 0.95:";;
+     short | recursive ) echo "Configuration of smcroute 1.99.2:";;
    esac
   cat <<\_ACEOF
 
@@ -1277,7 +1303,7 @@ Some influential environment variables:
 Use these variables to override the choices made by `configure' or to help
 it to find libraries and programs with nonstandard names/locations.
 
-Report bugs to <micha@debian.org>.
+Report bugs to <troglobit@gmail.com>.
 _ACEOF
 ac_status=$?
 fi
@@ -1340,10 +1366,10 @@ fi
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-smcroute configure 0.95
-generated by GNU Autoconf 2.67
+smcroute configure 1.99.2
+generated by GNU Autoconf 2.69
 
-Copyright (C) 2010 Free Software Foundation, Inc.
+Copyright (C) 2012 Free Software Foundation, Inc.
 This configure script is free software; the Free Software Foundation
 gives unlimited permission to copy, distribute and modify it.
 _ACEOF
@@ -1387,7 +1413,7 @@ sed 's/^/| /' conftest.$ac_ext >&5
 
 	ac_retval=1
 fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_c_try_compile
@@ -1424,53 +1450,11 @@ sed 's/^/| /' conftest.$ac_ext >&5
 
     ac_retval=1
 fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_c_try_cpp
 
-# ac_fn_c_try_run LINENO
-# ----------------------
-# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
-# that executables *can* be run.
-ac_fn_c_try_run ()
-{
-  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if { { ac_try="$ac_link"
-case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_link") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
-  { { case "(($ac_try" in
-  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
-  *) ac_try_echo=$ac_try;;
-esac
-eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
-$as_echo "$ac_try_echo"; } >&5
-  (eval "$ac_try") 2>&5
-  ac_status=$?
-  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
-  test $ac_status = 0; }; }; then :
-  ac_retval=0
-else
-  $as_echo "$as_me: program exited with status $ac_status" >&5
-       $as_echo "$as_me: failed program was:" >&5
-sed 's/^/| /' conftest.$ac_ext >&5
-
-       ac_retval=$ac_status
-fi
-  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
-  as_fn_set_status $ac_retval
-
-} # ac_fn_c_try_run
-
 # ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES
 # -------------------------------------------------------
 # Tests whether HEADER exists, giving a warning if it cannot be compiled using
@@ -1479,10 +1463,10 @@ fi
 ac_fn_c_check_header_mongrel ()
 {
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
-  if eval "test \"\${$3+set}\"" = set; then :
+  if eval \${$3+:} false; then :
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 fi
 eval ac_res=\$$3
@@ -1541,15 +1525,15 @@ $as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;}
 $as_echo "$as_me: WARNING: $2:     section \"Present But Cannot Be Compiled\"" >&2;}
     { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5
 $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;}
-( $as_echo "## ------------------------------- ##
-## Report this to micha@debian.org ##
-## ------------------------------- ##"
+( $as_echo "## ---------------------------------- ##
+## Report this to troglobit@gmail.com ##
+## ---------------------------------- ##"
      ) | sed "s/^/$as_me: WARNING:     /" >&2
     ;;
 esac
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   eval "$3=\$ac_header_compiler"
@@ -1558,10 +1542,52 @@ eval ac_res=\$$3
 	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
 $as_echo "$ac_res" >&6; }
 fi
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_c_check_header_mongrel
 
+# ac_fn_c_try_run LINENO
+# ----------------------
+# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes
+# that executables *can* be run.
+ac_fn_c_try_run ()
+{
+  as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
+  if { { ac_try="$ac_link"
+case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_link") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; } && { ac_try='./conftest$ac_exeext'
+  { { case "(($ac_try" in
+  *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;;
+  *) ac_try_echo=$ac_try;;
+esac
+eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\""
+$as_echo "$ac_try_echo"; } >&5
+  (eval "$ac_try") 2>&5
+  ac_status=$?
+  $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5
+  test $ac_status = 0; }; }; then :
+  ac_retval=0
+else
+  $as_echo "$as_me: program exited with status $ac_status" >&5
+       $as_echo "$as_me: failed program was:" >&5
+sed 's/^/| /' conftest.$ac_ext >&5
+
+       ac_retval=$ac_status
+fi
+  rm -rf conftest.dSYM conftest_ipa8_conftest.oo
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
+  as_fn_set_status $ac_retval
+
+} # ac_fn_c_try_run
+
 # ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES
 # -------------------------------------------------------
 # Tests whether HEADER exists and can be compiled using the include files in
@@ -1571,7 +1597,7 @@ ac_fn_c_check_header_compile ()
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -1589,7 +1615,7 @@ fi
 eval ac_res=\$$3
 	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
 $as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_c_check_header_compile
 
@@ -1602,7 +1628,7 @@ ac_fn_c_find_uintX_t ()
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for uint$2_t" >&5
 $as_echo_n "checking for uint$2_t... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   eval "$3=no"
@@ -1617,7 +1643,8 @@ int
 main ()
 {
 static int test_array [1 - 2 * !((($ac_type) -1 >> ($2 / 2 - 1)) >> ($2 / 2 - 1) == 3)];
-test_array [0] = 0
+test_array [0] = 0;
+return test_array [0];
 
   ;
   return 0;
@@ -1642,7 +1669,7 @@ fi
 eval ac_res=\$$3
 	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
 $as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_c_find_uintX_t
 
@@ -1655,7 +1682,7 @@ ac_fn_c_check_type ()
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   eval "$3=no"
@@ -1696,7 +1723,7 @@ fi
 eval ac_res=\$$3
 	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
 $as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_c_check_type
 
@@ -1727,7 +1754,7 @@ $as_echo "$ac_try_echo"; } >&5
 	 test ! -s conftest.err
        } && test -s conftest$ac_exeext && {
 	 test "$cross_compiling" = yes ||
-	 $as_test_x conftest$ac_exeext
+	 test -x conftest$ac_exeext
        }; then :
   ac_retval=0
 else
@@ -1741,7 +1768,7 @@ fi
   # interfere with the next link command; also delete a directory that is
   # left behind by Apple's compiler.  We do this before executing the actions.
   rm -rf conftest.dSYM conftest_ipa8_conftest.oo
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
   as_fn_set_status $ac_retval
 
 } # ac_fn_c_try_link
@@ -1754,7 +1781,7 @@ ac_fn_c_check_func ()
   as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5
 $as_echo_n "checking for $2... " >&6; }
-if eval "test \"\${$3+set}\"" = set; then :
+if eval \${$3+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -1809,15 +1836,15 @@ fi
 eval ac_res=\$$3
 	       { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5
 $as_echo "$ac_res" >&6; }
-  eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;}
+  eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno
 
 } # ac_fn_c_check_func
 cat >config.log <<_ACEOF
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by smcroute $as_me 0.95, which was
-generated by GNU Autoconf 2.67.  Invocation command line was
+It was created by smcroute $as_me 1.99.2, which was
+generated by GNU Autoconf 2.69.  Invocation command line was
 
   $ $0 $@
 
@@ -2075,7 +2102,7 @@ $as_echo "$as_me: loading site script $ac_site_file" >&6;}
       || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "failed to load site script $ac_site_file
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
   fi
 done
 
@@ -2165,9 +2192,9 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
 
-ac_config_headers="$ac_config_headers config.h"
+ac_config_headers="$ac_config_headers src/config.h"
 
-ac_config_files="$ac_config_files Makefile"
+ac_config_files="$ac_config_files Makefile src/Makefile doc/Makefile"
 
 
 # Checks for programs.
@@ -2181,7 +2208,7 @@ if test -n "$ac_tool_prefix"; then
 set dummy ${ac_tool_prefix}gcc; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if test "${ac_cv_prog_CC+set}" = set; then :
+if ${ac_cv_prog_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
@@ -2193,7 +2220,7 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="${ac_tool_prefix}gcc"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
@@ -2221,7 +2248,7 @@ if test -z "$ac_cv_prog_CC"; then
 set dummy gcc; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if test "${ac_cv_prog_ac_ct_CC+set}" = set; then :
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_CC"; then
@@ -2233,7 +2260,7 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_CC="gcc"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
@@ -2274,7 +2301,7 @@ if test -z "$CC"; then
 set dummy ${ac_tool_prefix}cc; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if test "${ac_cv_prog_CC+set}" = set; then :
+if ${ac_cv_prog_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
@@ -2286,7 +2313,7 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="${ac_tool_prefix}cc"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
@@ -2314,7 +2341,7 @@ if test -z "$CC"; then
 set dummy cc; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if test "${ac_cv_prog_CC+set}" = set; then :
+if ${ac_cv_prog_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
@@ -2327,7 +2354,7 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then
        ac_prog_rejected=yes
        continue
@@ -2373,7 +2400,7 @@ if test -z "$CC"; then
 set dummy $ac_tool_prefix$ac_prog; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if test "${ac_cv_prog_CC+set}" = set; then :
+if ${ac_cv_prog_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$CC"; then
@@ -2385,7 +2412,7 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_CC="$ac_tool_prefix$ac_prog"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
@@ -2417,7 +2444,7 @@ do
 set dummy $ac_prog; ac_word=$2
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5
 $as_echo_n "checking for $ac_word... " >&6; }
-if test "${ac_cv_prog_ac_ct_CC+set}" = set; then :
+if ${ac_cv_prog_ac_ct_CC+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -n "$ac_ct_CC"; then
@@ -2429,7 +2456,7 @@ do
   IFS=$as_save_IFS
   test -z "$as_dir" && as_dir=.
     for ac_exec_ext in '' $ac_executable_extensions; do
-  if { test -f "$as_dir/$ac_word$ac_exec_ext" && $as_test_x "$as_dir/$ac_word$ac_exec_ext"; }; then
+  if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then
     ac_cv_prog_ac_ct_CC="$ac_prog"
     $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5
     break 2
@@ -2472,7 +2499,7 @@ fi
 test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "no acceptable C compiler found in \$PATH
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 
 # Provide some information about the compiler.
 $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5
@@ -2587,7 +2614,7 @@ sed 's/^/| /' conftest.$ac_ext >&5
 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error 77 "C compiler cannot create executables
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 else
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5
 $as_echo "yes" >&6; }
@@ -2630,7 +2657,7 @@ else
   { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "cannot compute suffix of executables: cannot compile and link
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 fi
 rm -f conftest conftest$ac_cv_exeext
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5
@@ -2689,7 +2716,7 @@ $as_echo "$ac_try_echo"; } >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "cannot run C compiled programs.
 If you meant to cross compile, use \`--host'.
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
     fi
   fi
 fi
@@ -2700,7 +2727,7 @@ rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out
 ac_clean_files=$ac_clean_files_save
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5
 $as_echo_n "checking for suffix of object files... " >&6; }
-if test "${ac_cv_objext+set}" = set; then :
+if ${ac_cv_objext+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -2741,7 +2768,7 @@ sed 's/^/| /' conftest.$ac_ext >&5
 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "cannot compute suffix of object files: cannot compile
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 fi
 rm -f conftest.$ac_cv_objext conftest.$ac_ext
 fi
@@ -2751,7 +2778,7 @@ OBJEXT=$ac_cv_objext
 ac_objext=$OBJEXT
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5
 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; }
-if test "${ac_cv_c_compiler_gnu+set}" = set; then :
+if ${ac_cv_c_compiler_gnu+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -2788,7 +2815,7 @@ ac_test_CFLAGS=${CFLAGS+set}
 ac_save_CFLAGS=$CFLAGS
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5
 $as_echo_n "checking whether $CC accepts -g... " >&6; }
-if test "${ac_cv_prog_cc_g+set}" = set; then :
+if ${ac_cv_prog_cc_g+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_save_c_werror_flag=$ac_c_werror_flag
@@ -2866,7 +2893,7 @@ else
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5
 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; }
-if test "${ac_cv_prog_cc_c89+set}" = set; then :
+if ${ac_cv_prog_cc_c89+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_cv_prog_cc_c89=no
@@ -2875,8 +2902,7 @@ cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 #include <stdarg.h>
 #include <stdio.h>
-#include <sys/types.h>
-#include <sys/stat.h>
+struct stat;
 /* Most of the following tests are stolen from RCS 5.7's src/conf.sh.  */
 struct buf { int x; };
 FILE * (*rcsopen) (struct buf *, struct stat *, int);
@@ -2962,9 +2988,7 @@ ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $
 ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 
-# Checks for libraries.
-
-# Checks for header files.
+# The pidfile() code needs asprintf(), which relies on -D_GNU_SOURCE
 
 ac_ext=c
 ac_cpp='$CPP $CPPFLAGS'
@@ -2978,7 +3002,7 @@ if test -n "$CPP" && test -d "$CPP"; then
   CPP=
 fi
 if test -z "$CPP"; then
-  if test "${ac_cv_prog_CPP+set}" = set; then :
+  if ${ac_cv_prog_CPP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
       # Double quotes because CPP needs to be expanded
@@ -3094,7 +3118,7 @@ else
   { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5
 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;}
 as_fn_error $? "C preprocessor \"$CPP\" fails sanity check
-See \`config.log' for more details" "$LINENO" 5 ; }
+See \`config.log' for more details" "$LINENO" 5; }
 fi
 
 ac_ext=c
@@ -3106,7 +3130,7 @@ ac_compiler_gnu=$ac_cv_c_compiler_gnu
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5
 $as_echo_n "checking for grep that handles long lines and -e... " >&6; }
-if test "${ac_cv_path_GREP+set}" = set; then :
+if ${ac_cv_path_GREP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test -z "$GREP"; then
@@ -3120,7 +3144,7 @@ do
     for ac_prog in grep ggrep; do
     for ac_exec_ext in '' $ac_executable_extensions; do
       ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext"
-      { test -f "$ac_path_GREP" && $as_test_x "$ac_path_GREP"; } || continue
+      as_fn_executable_p "$ac_path_GREP" || continue
 # Check for GNU ac_path_GREP and select it if it is found.
   # Check for GNU $ac_path_GREP
 case `"$ac_path_GREP" --version 2>&1` in
@@ -3169,7 +3193,7 @@ $as_echo "$ac_cv_path_GREP" >&6; }
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5
 $as_echo_n "checking for egrep... " >&6; }
-if test "${ac_cv_path_EGREP+set}" = set; then :
+if ${ac_cv_path_EGREP+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if echo a | $GREP -E '(a|b)' >/dev/null 2>&1
@@ -3186,7 +3210,7 @@ do
     for ac_prog in egrep; do
     for ac_exec_ext in '' $ac_executable_extensions; do
       ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext"
-      { test -f "$ac_path_EGREP" && $as_test_x "$ac_path_EGREP"; } || continue
+      as_fn_executable_p "$ac_path_EGREP" || continue
 # Check for GNU ac_path_EGREP and select it if it is found.
   # Check for GNU $ac_path_EGREP
 case `"$ac_path_EGREP" --version 2>&1` in
@@ -3236,7 +3260,7 @@ $as_echo "$ac_cv_path_EGREP" >&6; }
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
 $as_echo_n "checking for ANSI C header files... " >&6; }
-if test "${ac_cv_header_stdc+set}" = set; then :
+if ${ac_cv_header_stdc+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -3363,6 +3387,184 @@ fi
 done
 
 
+
+  ac_fn_c_check_header_mongrel "$LINENO" "minix/config.h" "ac_cv_header_minix_config_h" "$ac_includes_default"
+if test "x$ac_cv_header_minix_config_h" = xyes; then :
+  MINIX=yes
+else
+  MINIX=
+fi
+
+
+  if test "$MINIX" = yes; then
+
+$as_echo "#define _POSIX_SOURCE 1" >>confdefs.h
+
+
+$as_echo "#define _POSIX_1_SOURCE 2" >>confdefs.h
+
+
+$as_echo "#define _MINIX 1" >>confdefs.h
+
+  fi
+
+
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether it is safe to define __EXTENSIONS__" >&5
+$as_echo_n "checking whether it is safe to define __EXTENSIONS__... " >&6; }
+if ${ac_cv_safe_to_define___extensions__+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#         define __EXTENSIONS__ 1
+          $ac_includes_default
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_safe_to_define___extensions__=yes
+else
+  ac_cv_safe_to_define___extensions__=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_safe_to_define___extensions__" >&5
+$as_echo "$ac_cv_safe_to_define___extensions__" >&6; }
+  test $ac_cv_safe_to_define___extensions__ = yes &&
+    $as_echo "#define __EXTENSIONS__ 1" >>confdefs.h
+
+  $as_echo "#define _ALL_SOURCE 1" >>confdefs.h
+
+  $as_echo "#define _GNU_SOURCE 1" >>confdefs.h
+
+  $as_echo "#define _POSIX_PTHREAD_SEMANTICS 1" >>confdefs.h
+
+  $as_echo "#define _TANDEM_SOURCE 1" >>confdefs.h
+
+
+
+
+# Checks for libraries.
+
+# Checks for header files.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5
+$as_echo_n "checking for ANSI C header files... " >&6; }
+if ${ac_cv_header_stdc+:} false; then :
+  $as_echo_n "(cached) " >&6
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+#include <stdarg.h>
+#include <string.h>
+#include <float.h>
+
+int
+main ()
+{
+
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_compile "$LINENO"; then :
+  ac_cv_header_stdc=yes
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
+
+if test $ac_cv_header_stdc = yes; then
+  # SunOS 4.x string.h does not declare mem*, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <string.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "memchr" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI.
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <stdlib.h>
+
+_ACEOF
+if (eval "$ac_cpp conftest.$ac_ext") 2>&5 |
+  $EGREP "free" >/dev/null 2>&1; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f conftest*
+
+fi
+
+if test $ac_cv_header_stdc = yes; then
+  # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi.
+  if test "$cross_compiling" = yes; then :
+  :
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+#include <ctype.h>
+#include <stdlib.h>
+#if ((' ' & 0x0FF) == 0x020)
+# define ISLOWER(c) ('a' <= (c) && (c) <= 'z')
+# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c))
+#else
+# define ISLOWER(c) \
+		   (('a' <= (c) && (c) <= 'i') \
+		     || ('j' <= (c) && (c) <= 'r') \
+		     || ('s' <= (c) && (c) <= 'z'))
+# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c))
+#endif
+
+#define XOR(e, f) (((e) && !(f)) || (!(e) && (f)))
+int
+main ()
+{
+  int i;
+  for (i = 0; i < 256; i++)
+    if (XOR (islower (i), ISLOWER (i))
+	|| toupper (i) != TOUPPER (i))
+      return 2;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+
+else
+  ac_cv_header_stdc=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5
+$as_echo "$ac_cv_header_stdc" >&6; }
+if test $ac_cv_header_stdc = yes; then
+
+$as_echo "#define STDC_HEADERS 1" >>confdefs.h
+
+fi
+
 for ac_header in arpa/inet.h fcntl.h netinet/in.h stdlib.h string.h \
                   sys/ioctl.h sys/socket.h syslog.h unistd.h \
                   net/route.h sys/param.h ifaddrs.h
@@ -3388,9 +3590,11 @@ do :
 #ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
 #endif
+#define _LINUX_IN_H             /* For Linux <= 2.6.25 */
+#include <linux/types.h>
 
 "
-if test "x$ac_cv_header_linux_mroute_h" = x""yes; then :
+if test "x$ac_cv_header_linux_mroute_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LINUX_MROUTE_H 1
 _ACEOF
@@ -3411,7 +3615,7 @@ do :
 #endif
 
 "
-if test "x$ac_cv_header_linux_mroute6_h" = x""yes; then :
+if test "x$ac_cv_header_linux_mroute6_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LINUX_MROUTE6_H 1
 _ACEOF
@@ -3424,7 +3628,7 @@ done
 for ac_header in linux/sockios.h
 do :
   ac_fn_c_check_header_mongrel "$LINENO" "linux/sockios.h" "ac_cv_header_linux_sockios_h" "$ac_includes_default"
-if test "x$ac_cv_header_linux_sockios_h" = x""yes; then :
+if test "x$ac_cv_header_linux_sockios_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_LINUX_SOCKIOS_H 1
 _ACEOF
@@ -3445,7 +3649,7 @@ do :
 #endif
 
 "
-if test "x$ac_cv_header_netinet_ip_mroute_h" = x""yes; then :
+if test "x$ac_cv_header_netinet_ip_mroute_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_NETINET_IP_MROUTE_H 1
 _ACEOF
@@ -3465,7 +3669,7 @@ do :
 #endif
 
 "
-if test "x$ac_cv_header_netinet6_ip6_mroute_h" = x""yes; then :
+if test "x$ac_cv_header_netinet6_ip6_mroute_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_NETINET6_IP6_MROUTE_H 1
 _ACEOF
@@ -3556,7 +3760,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 # Checks for typedefs, structures, and compiler characteristics.
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5
 $as_echo_n "checking for an ANSI C-conforming const... " >&6; }
-if test "${ac_cv_c_const+set}" = set; then :
+if ${ac_cv_c_const+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
@@ -3565,11 +3769,11 @@ else
 int
 main ()
 {
-/* FIXME: Include the comments suggested by Paul. */
+
 #ifndef __cplusplus
-  /* Ultrix mips cc rejects this.  */
+  /* Ultrix mips cc rejects this sort of thing.  */
   typedef int charset[2];
-  const charset cs;
+  const charset cs = { 0, 0 };
   /* SunOS 4.1.1 cc rejects this.  */
   char const *const *pcpcc;
   char **ppc;
@@ -3586,8 +3790,9 @@ main ()
   ++pcpcc;
   ppc = (char**) pcpcc;
   pcpcc = (char const *const *) ppc;
-  { /* SCO 3.2v4 cc rejects this.  */
-    char *t;
+  { /* SCO 3.2v4 cc rejects this sort of thing.  */
+    char tx;
+    char *t = &tx;
     char const *s = 0 ? (char *) 0 : (char const *) 0;
 
     *t++ = 0;
@@ -3603,10 +3808,10 @@ main ()
     iptr p = 0;
     ++p;
   }
-  { /* AIX XL C 1.02.0.0 rejects this saying
+  { /* AIX XL C 1.02.0.0 rejects this sort of thing, saying
        "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
-    struct s { int j; const int *ap[3]; };
-    struct s *b; b->j = 5;
+    struct s { int j; const int *ap[3]; } bx;
+    struct s *b = &bx; b->j = 5;
   }
   { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
     const int foo = 10;
@@ -3636,7 +3841,7 @@ fi
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for inline" >&5
 $as_echo_n "checking for inline... " >&6; }
-if test "${ac_cv_c_inline+set}" = set; then :
+if ${ac_cv_c_inline+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   ac_cv_c_inline=no
@@ -3793,7 +3998,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
 
 # Checks for library functions.
 ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default"
-if test "x$ac_cv_type_pid_t" = x""yes; then :
+if test "x$ac_cv_type_pid_t" = xyes; then :
 
 else
 
@@ -3806,7 +4011,7 @@ fi
 for ac_header in vfork.h
 do :
   ac_fn_c_check_header_mongrel "$LINENO" "vfork.h" "ac_cv_header_vfork_h" "$ac_includes_default"
-if test "x$ac_cv_header_vfork_h" = x""yes; then :
+if test "x$ac_cv_header_vfork_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_VFORK_H 1
 _ACEOF
@@ -3830,7 +4035,7 @@ done
 if test "x$ac_cv_func_fork" = xyes; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working fork" >&5
 $as_echo_n "checking for working fork... " >&6; }
-if test "${ac_cv_func_fork_works+set}" = set; then :
+if ${ac_cv_func_fork_works+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test "$cross_compiling" = yes; then :
@@ -3883,7 +4088,7 @@ ac_cv_func_vfork_works=$ac_cv_func_vfork
 if test "x$ac_cv_func_vfork" = xyes; then
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working vfork" >&5
 $as_echo_n "checking for working vfork... " >&6; }
-if test "${ac_cv_func_vfork_works+set}" = set; then :
+if ${ac_cv_func_vfork_works+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test "$cross_compiling" = yes; then :
@@ -4019,7 +4224,7 @@ fi
 if test $ac_cv_c_compiler_gnu = yes; then
     { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC needs -traditional" >&5
 $as_echo_n "checking whether $CC needs -traditional... " >&6; }
-if test "${ac_cv_prog_gcc_traditional+set}" = set; then :
+if ${ac_cv_prog_gcc_traditional+:} false; then :
   $as_echo_n "(cached) " >&6
 else
     ac_pattern="Autoconf.*'x'"
@@ -4061,7 +4266,7 @@ fi
 for ac_header in stdlib.h
 do :
   ac_fn_c_check_header_mongrel "$LINENO" "stdlib.h" "ac_cv_header_stdlib_h" "$ac_includes_default"
-if test "x$ac_cv_header_stdlib_h" = x""yes; then :
+if test "x$ac_cv_header_stdlib_h" = xyes; then :
   cat >>confdefs.h <<_ACEOF
 #define HAVE_STDLIB_H 1
 _ACEOF
@@ -4072,7 +4277,7 @@ done
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for GNU libc compatible malloc" >&5
 $as_echo_n "checking for GNU libc compatible malloc... " >&6; }
-if test "${ac_cv_func_malloc_0_nonnull+set}" = set; then :
+if ${ac_cv_func_malloc_0_nonnull+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test "$cross_compiling" = yes; then :
@@ -4140,7 +4345,7 @@ done
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking types of arguments for select" >&5
 $as_echo_n "checking types of arguments for select... " >&6; }
-if test "${ac_cv_func_select_args+set}" = set; then :
+if ${ac_cv_func_select_args+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   for ac_arg234 in 'fd_set *' 'int *' 'void *'; do
@@ -4174,7 +4379,7 @@ rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
  done
 done
 # Provide a safe default value.
-: ${ac_cv_func_select_args='int,int *,struct timeval *'}
+: "${ac_cv_func_select_args=int,int *,struct timeval *}"
 
 fi
 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_select_args" >&5
@@ -4202,7 +4407,7 @@ rm -f conftest*
 
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether setpgrp takes no argument" >&5
 $as_echo_n "checking whether setpgrp takes no argument... " >&6; }
-if test "${ac_cv_func_setpgrp_void+set}" = set; then :
+if ${ac_cv_func_setpgrp_void+:} false; then :
   $as_echo_n "(cached) " >&6
 else
   if test "$cross_compiling" = yes; then :
@@ -4240,7 +4445,7 @@ $as_echo "#define SETPGRP_VOID 1" >>confdefs.h
 
 fi
 
-for ac_func in atexit dup2 memset select socket strchr strerror strrchr
+for ac_func in atexit dup2 memset select socket strchr strerror strrchr asprintf
 do :
   as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
 ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var"
@@ -4317,10 +4522,21 @@ $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;;
      :end' >>confcache
 if diff "$cache_file" confcache >/dev/null 2>&1; then :; else
   if test -w "$cache_file"; then
-    test "x$cache_file" != "x/dev/null" &&
+    if test "x$cache_file" != "x/dev/null"; then
       { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5
 $as_echo "$as_me: updating cache $cache_file" >&6;}
-    cat confcache >$cache_file
+      if test ! -f "$cache_file" || test -h "$cache_file"; then
+	cat confcache >"$cache_file"
+      else
+        case $cache_file in #(
+        */* | ?:*)
+	  mv -f confcache "$cache_file"$$ &&
+	  mv -f "$cache_file"$$ "$cache_file" ;; #(
+        *)
+	  mv -f confcache "$cache_file" ;;
+	esac
+      fi
+    fi
   else
     { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5
 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;}
@@ -4352,7 +4568,7 @@ LTLIBOBJS=$ac_ltlibobjs
 
 
 
-: ${CONFIG_STATUS=./config.status}
+: "${CONFIG_STATUS=./config.status}"
 ac_write_fail=0
 ac_clean_files_save=$ac_clean_files
 ac_clean_files="$ac_clean_files $CONFIG_STATUS"
@@ -4453,6 +4669,7 @@ fi
 IFS=" ""	$as_nl"
 
 # Find who we are.  Look in the path if we contain no directory separator.
+as_myself=
 case $0 in #((
   *[\\/]* ) as_myself=$0 ;;
   *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR
@@ -4648,16 +4865,16 @@ if (echo >conf$$.file) 2>/dev/null; then
     # ... but there are two gotchas:
     # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail.
     # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable.
-    # In both cases, we have to default to `cp -p'.
+    # In both cases, we have to default to `cp -pR'.
     ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe ||
-      as_ln_s='cp -p'
+      as_ln_s='cp -pR'
   elif ln conf$$.file conf$$ 2>/dev/null; then
     as_ln_s=ln
   else
-    as_ln_s='cp -p'
+    as_ln_s='cp -pR'
   fi
 else
-  as_ln_s='cp -p'
+  as_ln_s='cp -pR'
 fi
 rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file
 rmdir conf$$.dir 2>/dev/null
@@ -4717,28 +4934,16 @@ else
   as_mkdir_p=false
 fi
 
-if test -x / >/dev/null 2>&1; then
-  as_test_x='test -x'
-else
-  if ls -dL / >/dev/null 2>&1; then
-    as_ls_L_option=L
-  else
-    as_ls_L_option=
-  fi
-  as_test_x='
-    eval sh -c '\''
-      if test -d "$1"; then
-	test -d "$1/.";
-      else
-	case $1 in #(
-	-*)set "./$1";;
-	esac;
-	case `ls -ld'$as_ls_L_option' "$1" 2>/dev/null` in #((
-	???[sx]*):;;*)false;;esac;fi
-    '\'' sh
-  '
-fi
-as_executable_p=$as_test_x
+
+# as_fn_executable_p FILE
+# -----------------------
+# Test if FILE is an executable regular file.
+as_fn_executable_p ()
+{
+  test -f "$1" && test -x "$1"
+} # as_fn_executable_p
+as_test_x='test -x'
+as_executable_p=as_fn_executable_p
 
 # Sed expression to map a string onto a valid CPP name.
 as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'"
@@ -4759,8 +4964,8 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by smcroute $as_me 0.95, which was
-generated by GNU Autoconf 2.67.  Invocation command line was
+This file was extended by smcroute $as_me 1.99.2, which was
+generated by GNU Autoconf 2.69.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
   CONFIG_HEADERS  = $CONFIG_HEADERS
@@ -4815,17 +5020,17 @@ $config_files
 Configuration headers:
 $config_headers
 
-Report bugs to <micha@debian.org>."
+Report bugs to <troglobit@gmail.com>."
 
 _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-smcroute config.status 0.95
-configured by $0, generated by GNU Autoconf 2.67,
+smcroute config.status 1.99.2
+configured by $0, generated by GNU Autoconf 2.69,
   with options \\"\$ac_cs_config\\"
 
-Copyright (C) 2010 Free Software Foundation, Inc.
+Copyright (C) 2012 Free Software Foundation, Inc.
 This config.status script is free software; the Free Software Foundation
 gives unlimited permission to copy, distribute and modify it."
 
@@ -4913,7 +5118,7 @@ fi
 _ACEOF
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 if \$ac_cs_recheck; then
-  set X '$SHELL' '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
+  set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion
   shift
   \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6
   CONFIG_SHELL='$SHELL'
@@ -4942,10 +5147,12 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1
 for ac_config_target in $ac_config_targets
 do
   case $ac_config_target in
-    "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;;
+    "src/config.h") CONFIG_HEADERS="$CONFIG_HEADERS src/config.h" ;;
     "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;;
+    "src/Makefile") CONFIG_FILES="$CONFIG_FILES src/Makefile" ;;
+    "doc/Makefile") CONFIG_FILES="$CONFIG_FILES doc/Makefile" ;;
 
-  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5 ;;
+  *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;;
   esac
 done
 
@@ -4967,9 +5174,10 @@ fi
 # after its creation but before its name has been assigned to `$tmp'.
 $debug ||
 {
-  tmp=
+  tmp= ac_tmp=
   trap 'exit_status=$?
-  { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status
+  : "${ac_tmp:=$tmp}"
+  { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status
 ' 0
   trap 'as_fn_exit 1' 1 2 13 15
 }
@@ -4977,12 +5185,13 @@ $debug ||
 
 {
   tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` &&
-  test -n "$tmp" && test -d "$tmp"
+  test -d "$tmp"
 }  ||
 {
   tmp=./conf$$-$RANDOM
   (umask 077 && mkdir "$tmp")
 } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5
+ac_tmp=$tmp
 
 # Set up the scripts for CONFIG_FILES section.
 # No need to generate them if there are no CONFIG_FILES.
@@ -5004,7 +5213,7 @@ else
   ac_cs_awk_cr=$ac_cr
 fi
 
-echo 'BEGIN {' >"$tmp/subs1.awk" &&
+echo 'BEGIN {' >"$ac_tmp/subs1.awk" &&
 _ACEOF
 
 
@@ -5032,7 +5241,7 @@ done
 rm -f conf$$subs.sh
 
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
-cat >>"\$tmp/subs1.awk" <<\\_ACAWK &&
+cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&
 _ACEOF
 sed -n '
 h
@@ -5080,7 +5289,7 @@ t delim
 rm -f conf$$subs.awk
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 _ACAWK
-cat >>"\$tmp/subs1.awk" <<_ACAWK &&
+cat >>"\$ac_tmp/subs1.awk" <<_ACAWK &&
   for (key in S) S_is_set[key] = 1
   FS = ""
 
@@ -5112,7 +5321,7 @@ if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then
   sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g"
 else
   cat
-fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \
+fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \
   || as_fn_error $? "could not setup config files machinery" "$LINENO" 5
 _ACEOF
 
@@ -5146,7 +5355,7 @@ fi # test -n "$CONFIG_FILES"
 # No need to generate them if there are no CONFIG_HEADERS.
 # This happens for instance with `./config.status Makefile'.
 if test -n "$CONFIG_HEADERS"; then
-cat >"$tmp/defines.awk" <<\_ACAWK ||
+cat >"$ac_tmp/defines.awk" <<\_ACAWK ||
 BEGIN {
 _ACEOF
 
@@ -5158,8 +5367,8 @@ _ACEOF
 # handling of long lines.
 ac_delim='%!_!# '
 for ac_last_try in false false :; do
-  ac_t=`sed -n "/$ac_delim/p" confdefs.h`
-  if test -z "$ac_t"; then
+  ac_tt=`sed -n "/$ac_delim/p" confdefs.h`
+  if test -z "$ac_tt"; then
     break
   elif $ac_last_try; then
     as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5
@@ -5260,7 +5469,7 @@ do
   esac
   case $ac_mode$ac_tag in
   :[FHL]*:*);;
-  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5 ;;
+  :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;;
   :[FH]-) ac_tag=-:-;;
   :[FH]*) ac_tag=$ac_tag:$ac_tag.in;;
   esac
@@ -5279,7 +5488,7 @@ do
     for ac_f
     do
       case $ac_f in
-      -) ac_f="$tmp/stdin";;
+      -) ac_f="$ac_tmp/stdin";;
       *) # Look for the file first in the build tree, then in the source tree
 	 # (if the path is not absolute).  The absolute path cannot be DOS-style,
 	 # because $ac_f cannot contain `:'.
@@ -5288,7 +5497,7 @@ do
 	   [\\/$]*) false;;
 	   *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";;
 	   esac ||
-	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5 ;;
+	   as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;;
       esac
       case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac
       as_fn_append ac_file_inputs " '$ac_f'"
@@ -5314,8 +5523,8 @@ $as_echo "$as_me: creating $ac_file" >&6;}
     esac
 
     case $ac_tag in
-    *:-:* | *:-) cat >"$tmp/stdin" \
-      || as_fn_error $? "could not create $ac_file" "$LINENO" 5  ;;
+    *:-:* | *:-) cat >"$ac_tmp/stdin" \
+      || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;;
     esac
     ;;
   esac
@@ -5440,21 +5649,22 @@ s&@abs_builddir@&$ac_abs_builddir&;t t
 s&@abs_top_builddir@&$ac_abs_top_builddir&;t t
 $ac_datarootdir_hack
 "
-eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \
-  || as_fn_error $? "could not create $ac_file" "$LINENO" 5
+eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \
+  >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5
 
 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" &&
-  { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } &&
-  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } &&
+  { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } &&
+  { ac_out=`sed -n '/^[	 ]*datarootdir[	 ]*:*=/p' \
+      "$ac_tmp/out"`; test -z "$ac_out"; } &&
   { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir'
 which seems to be undefined.  Please make sure it is defined" >&5
 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir'
 which seems to be undefined.  Please make sure it is defined" >&2;}
 
-  rm -f "$tmp/stdin"
+  rm -f "$ac_tmp/stdin"
   case $ac_file in
-  -) cat "$tmp/out" && rm -f "$tmp/out";;
-  *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";;
+  -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";;
+  *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";;
   esac \
   || as_fn_error $? "could not create $ac_file" "$LINENO" 5
  ;;
@@ -5465,20 +5675,20 @@ which seems to be undefined.  Please make sure it is defined" >&2;}
   if test x"$ac_file" != x-; then
     {
       $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs"
-    } >"$tmp/config.h" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs"
+    } >"$ac_tmp/config.h" \
       || as_fn_error $? "could not create $ac_file" "$LINENO" 5
-    if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then
+    if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then
       { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5
 $as_echo "$as_me: $ac_file is unchanged" >&6;}
     else
       rm -f "$ac_file"
-      mv "$tmp/config.h" "$ac_file" \
+      mv "$ac_tmp/config.h" "$ac_file" \
 	|| as_fn_error $? "could not create $ac_file" "$LINENO" 5
     fi
   else
     $as_echo "/* $configure_input  */" \
-      && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \
+      && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \
       || as_fn_error $? "could not create -" "$LINENO" 5
   fi
  ;;
diff --git a/src/configure.ac b/configure.ac
similarity index 91%
rename from src/configure.ac
rename to configure.ac
index 0cec9e0..45a7696 100644
--- a/src/configure.ac
+++ b/configure.ac
@@ -2,14 +2,17 @@
 # Process this file with autoconf to produce a configure script.
 
 AC_PREREQ(2.61)
-AC_INIT(smcroute, 0.95, micha@debian.org)
-AC_CONFIG_SRCDIR([mclab.h])
-AC_CONFIG_HEADER([config.h])
-AC_CONFIG_FILES([Makefile])
+AC_INIT(smcroute, 1.99.2, troglobit@gmail.com)
+AC_CONFIG_SRCDIR([src/mclab.h])
+AC_CONFIG_HEADER([src/config.h])
+AC_CONFIG_FILES([Makefile src/Makefile doc/Makefile])
 
 # Checks for programs.
 AC_PROG_CC
 
+# The pidfile() code needs asprintf(), which relies on -D_GNU_SOURCE
+AC_GNU_SOURCE
+
 # Checks for libraries.
 
 # Checks for header files.
@@ -26,6 +29,8 @@ AC_CHECK_HEADERS([linux/mroute.h], [], [],
 #ifdef HAVE_NETINET_IN_H
 #include <netinet/in.h>
 #endif
+#define _LINUX_IN_H             /* For Linux <= 2.6.25 */
+#include <linux/types.h>
 ])
 
 AC_CHECK_HEADERS([linux/mroute6.h], [], [], 
@@ -168,6 +173,6 @@ AC_PROG_GCC_TRADITIONAL
 AC_FUNC_MALLOC
 AC_FUNC_SELECT_ARGTYPES
 AC_FUNC_SETPGRP
-AC_CHECK_FUNCS([atexit dup2 memset select socket strchr strerror strrchr])
+AC_CHECK_FUNCS([atexit dup2 memset select socket strchr strerror strrchr asprintf])
 
 AC_OUTPUT
diff --git a/doc/Makefile.in b/doc/Makefile.in
new file mode 100644
index 0000000..3463fdc
--- /dev/null
+++ b/doc/Makefile.in
@@ -0,0 +1,16 @@
+##  smcroute - static multicast routing control 
+
+DOCS          = smcroute.8 mcsender.8
+MANDIR        = $(DESTDIR)$(mandir)/man8
+
+install: 
+	@install -d $(MANDIR)
+	@for file in $(DOCS); do \
+		install -m 0644 $$file $(MANDIR)/$$file; \
+	done
+
+uninstall:
+	-@for file in $(DOCS); do \
+		$(RM) $(MANDIR)/$$file; \
+	done
+
diff --git a/doc/smcroute.8 b/doc/smcroute.8
index 21dd0f3..6cb88b9 100644
--- a/doc/smcroute.8
+++ b/doc/smcroute.8
@@ -1,179 +1,305 @@
-.\" .br - line break (nothing else on the line)
-.\" .B  - bold
-.\" .I  - green or kursive (on HTML)
-.\" .TP - paragraph ? (header line, followed by indented lines)
-.\"
-.TH smcroute 8 "August 08, 2011"
-.SH NAME
-SMCRoute \- Static Multicast Router (-Interface) - Version 0.95
-.SH SYNOPSIS
-smcroute <
-.I options
-> <
-.I commands
->
-.TP
-.I options
--d  -  start daemon
-.br
--v  -  verbose output
-.br
--D  -  enable debug logging
-.TP
-.I commands  - common
--h  -  print help
-.br
--k  -  kill daemon
-.TP
-.I commands - multicast routing related
--a <InputIntf> <OriginIpAdr> <McGroupAdr> <OutputIntf> [<OutputIntf>] ...
-.br  
-   -  add route
-.br
--r <InputIntf> <OriginIpAdr> <McGroupAdr>
-.br
-   -  remove route
-.TP
-.I commands - multicast signaling related
--j <InputIntf> <McGroupAdr>  - join MC group
-.br
--l <InputIntf> <McGroupAdr>  - leave MC group
-.SH DESCRIPTION
-.B SMCRoute 
-is a command line tool to manipulate the multicast
-routes of the Linux kernel. It supports both IPv4 and IPv6 multicast routing. SMCRoute can be used as an 
-alternative to dynamic multicast routers like 'mrouted' in situations where static multicast routes should 
-be maintained and/or no proper IGMP or MLD signaling exists.
-
-Generally multicast routes exists in the kernel only as long as smcroute or another multicast routing daemon 
-is running. Only one multicast routing daemon can be active at a time, so it's impossible to run smcroute 
-and e.g. 'mrouted' at the same time.
-
+.Dd $Mdocdate: November 01 2011 $
+.Dt SMCROUTE 8 SMM
+.Os
+.Sh NAME
+.Nm smcroute
+.Nd SMCRoute, a static multicast router
+.Sh SYNOPSIS
+.Nm smcroute
+.Op OPTIONS
+.Op COMMANDS
+.Sh DESCRIPTION
+.Nm
+is a command line tool to manipulate the multicast routes of a UNIX
+kernel. It supports both IPv4 and IPv6 multicast routing. SMCRoute can
+be used as an alternative to dynamic multicast routers like
+.Nm mrouted
+or
+.Nm pimd
+in situations where static multicast routes should be maintained and/or
+no proper IGMP or MLD signaling exists.
+.Pp
+Generally multicast routes exists in the kernel only as long as smcroute
+or another multicast routing daemon is running. Only one multicast
+routing daemon can be active at a time, so it's impossible to run
+smcroute and, e.g.,
+.Nm mrouted
+at the same time.
+.Pp
+Because
+.Nm
+modifies the kernel routing table it needs to run with full
+.Ar superuser rights .
+Which also means that the same applies to client operations, to be
+able to communicate with the daemon.
+.Ss WARNING
+By using multiple output interfaces (traffic multiplication), using the
+input interface also as output interface (direct loop) or constructing
+some other forms of indirect loops you can easily flood your networks!
+.Sh OPTIONS
+.Bl -tag -width Ds
+.It Fl d
+Starts the smcroute daemon before any of the optional following commands
+are executed. Please note, if started with the
+.Fl n
+flag no commands specified on the command line will be run.
+.It Fl n
+Run in foreground, do not detach from the calling terminal.  This also
+means that any further commands from that command line are run.  Option
+flags, however, are accepted, but not command flags.
+.It Fl f Ar FILE
+Specify an alternative configuration file, instead of the default
+.Pa /etc/smcroute.conf .
+.It Fl v
+Display version and enable verbose logs.  This gives a more verbose
+output in some error situations.  Do not expect too much, see syslog
+instead.
+.It Fl D
+Enable additional debug messages.  Do not expect too much, see syslog
+instead.
+.It Fl h
+Print a help message and exit.
+.It Fl k
+Stop (kill) running daemon.
+.El
+.Pp
 The 
-.B -d
-option smcroute is used to start the smcroute daemon. Otherwise, smcroute searches for an already running smcroute daemon and passes the commands to it. The 
-.B -k
-option will terminate a running daemon.
-
+.Fl d
+option to smcroute starts the smcroute daemon. It can be started in the
+foreground using the
+.Fl n
+option. The
+.Fl k
+option will terminate a running daemon.  The 
+.Fl f Ar FILE
+option can be used to tell the daemon to setup routes from a conf
+file. By default it looks for /etc/smcroute.conf
+.Sh COMMANDS
+The following are commands that can only be passed to an already running daemon.
+.Bl -tag -width Ds
+.It Fl a Ar IFNAME SOURCE GROUP IFNAME [IFNAME ...]
+Add a kernel multicast route from {IFNAME, SOURCE & GROUP} to a list of,
+at least one, outbound IFNAME.  The interfaces can be any network
+interface as listed by 'ifconfig' or 'ip link list' (incl. tunnel
+interfaces), but not the loopback interface.  Please note that the
+.Ar SOURCE
+address is the unicast IPv4 or IPv6 source address of the multicast
+sender! The 
+.Ar GROUP
+can be either an IPv4 or IPv6 formatted multicast group address.
+.It Fl r Ar IFNAME SOURCE GROUP
+Remove a kernel multicast route.
+.It Fl j Ar IFNAME GROUP
+Join a multicast group on a given interface.
+.It Fl l Ar IFNAME GROUP
+Leave a multicast group on a given interface.
+.El
+.Pp
+To be able to add/remove routes or join/leave multicast groups the
+.Nm
+daemon must run.
+.Pp
 Multicast routes can be added with the 
-.B -a 
+.Fl a 
 command and removed with the 
-.B -r
+.Fl r
 command. 
-
-A multicast route is defined by an input interface (<IntputIntf>), a unicast IP origin address (<OriginIpAdr>), a multicast group (<McGroupAdr>) and a list of output interfaces (<OutputIntf> ...). 
-
-The origin and multicast group addresses must both be IPv4 addresses or IPv6 addresses. If IPv4 addresses are specified then SMCRoute will operate on the IPv4 multicast routes. If IPv6 addresses are specified then SMCRoute will operate on the IPv6 multicast routes. The output interfaces must not be given with the 
-.B -r
-as the first three parameter are sufficient to identify the route to remove. 
-
-The intention of SMCRoute is to help in situation where dynamic multicast routing does not work properly, but dynamic multicast routing is in nearly all cases the preferred solution. SMCRoute supports dynamic multicast routing with the multicast group 'join' 
-.B -j
-and 'leave' 
-.B -l
-commands. For both commands the input interface on which the multicast sessions should be received (<InputIntf>) and the multicast group address <McGroupAdr> must be given. The <McGroupAdr> may be an IPv4 or IPv6 address.
-
-.B Superuser rights 
-are necessary to start the smcroute daemon or to communicate with the daemon. 
-.SH OPTIONS
-.TP
-.B -d  
-Starts the smcroute daemon before any of the optional following commands are executed.
-
-.TP
-.B -v
-Gives verbose output in some error situations (don't expect too much, check syslog instead).
-
-.TP
-.B -D
-Gives additional debug messages in normal use (don't expect too much, see syslog instead).
-.SH COMMANDS
-.TP
-.B -a 
-.I <InputIntf> <OriginIpAdr> <McGroupAdr> <OutputIntf> [<OutputIntf>] ...
-
-The command is passed to the daemon that adds the given multicast route to the kernel's routing table. 
-.I <InputIntf> 
-can be any network interface as listed by 'ifconfig' or 'ip link list' (incl. tunnel interfaces), but not the loopback interface.
-.I <OriginIpAdr>
-is the source IP address of the multicast packets that will be routed by this entry. It is a unicast IPv4 or IPv6 address and not a multicast IP address. 
-.I <McGroupAdr>
-is the IPv4 or IPv6 address of the multicast group that will be forwarded.
-.I <OutputIntf> [<OutputIntf>] ...
-is a list of one or more network interfaces to which the multicast packets will be forwarded. The same rules for the selection of output interfaces applies as for the input interface. 
-
-.B Warning, 
-by using multiple output interfaces (traffic multiplication), using the input interface also as output interface (direct loop) or constructing some other forms of indirect loop you can flood you network.
-
-.TP
-.B -r
-.I <InputIntf> <OriginIpAdr> <McGroupAdr>
-
-The command is passed to the daemon that removes a multicast route previously added with the 
-.B -a
-command. The parameters are identical except to the omitted list of <OutputIntf>.
-
-.TP
-.B -j
-.I <InputIntf> <McGroupAdr>  
-
-The command is passed to the daemon that passes it to the kernel. The kernel then tries to join the multicast group 
-.I <McGroupAdr>
+.Pp
+A multicast route is defined by an input interface
+.Ar IFNAME ,
+the sender's unicast IP address
+.Ar SOURCE ,
+the multicast group
+.Ar GROUP
+and a list of, at least one, output interface
+.Ar IFNAME [IFNAME ...] .
+.Pp
+The sender's address and the multicast group must both be IPv4 addresses
+or IPv6 addresses.  If IPv4 addresses are specified then SMCRoute will
+operate on the IPv4 multicast routes. If IPv6 addresses are specified
+then SMCRoute will operate on the IPv6 multicast routes.
+.Pp
+The output interfaces are not needed when removing routes using the
+.Fl r
+command. The first three parameters are sufficient to identify the
+source of the multicast route. 
+.Pp
+The intended purpose of SMCRoute is to aid in situations where dynamic
+multicast routing does not work properly.  However, dynamic multicast routing
+is in nearly all cases the preferred solution.
+.Pp
+.Nm
+can also send simple group join and leave commands to the kernel. As a
+result the kernel will send Layer-2 IGMP join and leave frames. This can
+be used for testing but is also useful sometimes to open up multicast
+from the sender if located on a LAN with switches equipped with IGMP/MLD
+Snooping. Such devices will prevent forwarding of multicast unless an
+IGMP/MLD capable router or multicast client is located on the same
+physical port as you run
+.Nm
+on.
+.Pp
+To emulate a multicast client using
+.Nm
+you use the
+.Fl j
+and
+.Fl l
+commands to issue join and leave commands for a given multicast group
+on a given interface
+.Ar IFNAME .
+The
+.Ar GROUP
+may be given in an IPv4 or IPv6 address format.
+.Pp
+The command is passed to the daemon that passes it to the kernel. The
+kernel then tries to join the multicast group
+.Ar GROUP
 on interface 
-.I <InputIntf>
-by starting IGMP (or MLD if <McGroupAdr> is an IPv6 address) signaling on 
-.I <InputIntf>.
-This signaling may be received by routers connected to 
-.I <InputIntf>'s
-network that support IGMP/MLD multicast signaling and then hopfuly start forwarding of the requested multicast session to 
-.I <InputIntf>'s
-network. 
-
-With this command smcroute allows the integration of nodes that needs static multicast routing into dynamic multicast routing networks. 
+.Ar IFNAME
+by starting IGMP, or MLD for IPv6 group address, signaling on the given
+interface.  This signaling may be received by routers/switches connected
+on that network supporting IGMP/MLD multicast signaling and, in turn,
+start forwarding the requested multicast stream eventually reach your
+desired interface.
+.Pp
+With this command
+.Nm
+allows the integration of nodes that need static multicast routing into
+dynamic multicast routing domains.
+.Pp
+.Sh CONFIGURATION FILE
+From version 1.98.0 smcroute supports reading and setting up multicast
+routes from a config file. The default location is
+.Ar /etc/smcroute.conf ,
+but this can be overridden using the
+.Fl f Ar FILE
+command line option.
+.Pp
+.Bd -unfilled -offset left
+#
+# smcroute.conf example
+#
+# The configuration file supports joining multicast groups, to use
+# Layer-2 signaling so that switches and routers open up multicast
+# traffic to your interfaces.  Leave is not supported, remove the
+# mgroup and SIGHUP your daemon, or send a specific leave command.
+#
+# Similarily supported is setting mroutes. Removing mroutes is not
+# supported, remove/comment out the mroute or send a remove command.
+#
+# Syntax:
+#   mgroup from IFNAME group MCGROUP
+#   mroute from IFNAME [source ADDRESS] group MCGROUP to IFNAME [IFNAME ...]
+#
+# The following example instructs the kernel to join the multicast
+# group 225.1.2.3 on interface eth0.  Followed by setting up an
+# mroute of the same multicast stream, but from the explicit sender
+# 192.168.1.42 on the eth0 network and forward to eth1 and eth2.
+#
+mgroup from eth0 group 225.1.2.3
+mroute from eth0 group 225.1.2.3 source 192.168.1.42 to eth1 eth2
 
-.TP
-.B -l
-.I <InputIntf> <McGroupAdr>  
-
-The command is passed via the daemon to the kernel that initiate a 'leave' for a previously 'joined' multicast group.
-
-.SH LIMITS
-The current version compiles and runs fine with the Linux kernel version 2.4. The known limits are:
-
-.B Multicast routes:
-more then 200
-
-.B Multicast group membership:
-max. 20
-.SH FILES
-.TP
-.B /proc/net/ip_mr_cache 
-- contains the active IPv4 multicast routes
-.TP
-.B /proc/net/ip_mr_vif 
-- contains the IPv4 'virtual' interfaces used by the active multicast routing daemon
-.TP
-.B /proc/net/ip6_mr_cache 
-- contains the active IPv6 multicast routes
-.TP
-.B /proc/net/ip6_mr_vif 
-- contains the IPv6 'virtual' interfaces used by the active multicast routing daemon
-.TP
-.B /var/run/smcroute 
-- IPC socket created by the smcroute daemon
-.SH SEE ALSO
-mrouted
-.SH BUGS
+# Here we allow routing of multicast to group 225.3.2.1 from ANY
+# source coming in from interface eth0 and forward to eth1 and eth2.
+# NOTE: Routing from ANY source is currently only available for IPv4
+#       multicast.
+mgroup from eth0 group 225.3.2.1
+mroute from eth0 group 225.3.2.1 to eth1 eth2
+.Ed
+.Pp
+Fairly simple. As usual, to identify the origin of the inbound multicast
+we need the
+.Ar IFNAME ,
+the sender's IP address and, of course, the multicast group address,
+.Ar MCGROUP .
+The last argument is a list of outbound interfaces.
+.Pp
+From 1.99.0 the sender's IP address is actually optional for IPv4
+multicast routes. If omitted it defaults to 0.0.0.0 (INADDR_ANY) and
+will cause
+.Nm
+to dynamically at runtime add new routes, matching the group and inbound
+interface, to the kernel. This feauture is experimental.
+.Pp
+Following the standard UNIX tradition the file format support comments
+at the beginning of the line using a hash sign.  It is untested to have
+comments at the end of a line, but should work.
+.Pp
+When starting up, the daemon by default lists the success of parsing each
+line and setting up a route.
+.Sh LIMITS
+The current version compiles and runs fine on Linux kernel version
+2.4, 2.6 and 3.0. Known limits:
+.Pp
+.Bl -tag -width TERM -compact -offset indent
+.It Cm Multicast routes
+More than 200
+.It Cm Multicast group membership
+Max. 20
+.El
+.Pp
+.Sh SIGNALS
+.Nm
+responds to the following signals:
+.Pp
+.Bl -tag -width TERM -compact
+.It HUP
+Restarts
+.Nm .
+The configuration file is reread every time this signal is received.
+.It INT
+Terminates execution gracefully.
+.It TERM
+The same as INT.
+.El
+.Pp
+For convenience in sending signals,
+.Nm
+writes its process ID to
+.Pa /var/run/smcroute.pid
+upon startup.
+.Pp
+.Sh FILES
+.Bl -tag -width /proc/net/ip6_mr_cache -compact
+.It Pa /etc/smcroute.conf
+Routes to be added/restored when starting, or restarting the daemon on
+SIGHUP.
+.It Pa /var/run/smcroute.pid
+Pidfile (re)created by
+.Nm
+daemon when it has started up and is ready to receive commands.
+.It Pa /proc/net/ip_mr_cache 
+Holds active IPv4 multicast routes.
+.It Pa /proc/net/ip_mr_vif 
+Holds the IPv4 virtual interfaces used by the active multicast routing daemon.
+.It Pa /proc/net/ip6_mr_cache 
+Holds active IPv6 multicast routes.
+.It Pa /proc/net/ip6_mr_vif 
+Holds the IPv6 virtual interfaces used by the active multicast routing daemon.
+.It Pa /var/run/smcroute 
+IPC socket created by the smcroute daemon.
+.It Pa /proc/net/igmp
+Holds active IGMP joins.
+.It Pa /proc/net/igmp6
+Holds active MLD joins.
+.El
+.Pp
+.Sh SEE ALSO
+.Xr mrouted 8 ,
+.Xr pimd 8
+.Sh BUGS
 The English wording of this man page.
-.SH AUTHORS
-smcroute was originally written by Carsten Schill <carsten@cschill.de>,
-support for IPv6 was added by Todd Hayton <todd.hayton@gmail.com>,
-support for FreeBSD was added by Micha Lenk <micha@debian.org>.
-.PP
-The source code is now maintained by Todd Hayton <todd.hayton@gmail.com>,
-Micha Lenk <micha@debian.org> and Julien BLACHE <jblache@debian.org>.
-
-The current version is available at: 
-.I http://alioth.debian.org/projects/smcroute
-.SH TIPS
-A lot of extra information is sent under the daemon facility and the debug priority to the syslog daemon.
+.Sh AUTHORS
+Originally written by Carsten Schill <carsten@cschill.de>.
+Support for IPv6 was added by Todd Hayton <todd.hayton@gmail.com>.
+Support for FreeBSD was added by Micha Lenk <micha@debian.org>.
+.Pp
+SMCRoute is maintained by Joachim Nilsson <troglobit@gmail.com>, Todd Hayton
+<todd.hayton@gmail.com>, Micha Lenk <micha@debian.org> and Julien BLACHE
+<jblache@debian.org> at
+.Ar https://github.com/troglobit/smcroute
+.
+.Sh TIPS
+A lot of extra information is sent under the daemon facility and the
+debug priority to the syslog daemon.
diff --git a/smcroute.conf b/smcroute.conf
new file mode 100644
index 0000000..87480da
--- /dev/null
+++ b/smcroute.conf
@@ -0,0 +1,30 @@
+#
+# smcroute.conf example
+#
+# The configuration file supports joining multicast groups, to use
+# Layer-2 signaling so that switches and routers open up multicast
+# traffic to your interfaces.  Leave is not supported, remove the
+# mgroup and SIGHUP your daemon, or send a specific leave command.
+#
+# Similarily supported is setting mroutes. Removing mroutes is not
+# supported, remove/comment out the mroute or send a remove command.
+#
+# Syntax:
+#   mgroup from IFNAME group MCGROUP
+#   mroute from IFNAME [source ADDRESS] group MCGROUP to IFNAME [IFNAME ...]
+#
+# The following example instructs the kernel to join the multicast
+# group 225.1.2.3 on interface eth0.  Followed by setting up an
+# mroute of the same multicast stream, but from the explicit sender
+# 192.168.1.42 on the eth0 network and forward to eth1 and eth2.
+#
+mgroup from eth0 group 225.1.2.3
+mroute from eth0 group 225.1.2.3 source 192.168.1.42 to eth1 eth2
+
+# Here we allow routing of multicast to group 225.3.2.1 from ANY
+# source coming in from interface eth0 and forward to eth1 and eth2.
+# NOTE: Routing from ANY source is currently only available for IPv4
+#       multicast.
+mgroup from eth0 group 225.3.2.1
+mroute from eth0 group 225.3.2.1 to eth1 eth2
+
diff --git a/src/Makefile.in b/src/Makefile.in
index fe1bda0..1ddda5b 100644
--- a/src/Makefile.in
+++ b/src/Makefile.in
@@ -1,33 +1,63 @@
 ##  smcroute - static multicast routing control 
-##  Copyright (C) 2001-2005 Carsten Schill <carsten@cschill.de>
-##  Copyright (C) 2006-2009 Julien BLACHE <jb@jblache.org>
-##  Copyright (C) 2009      Todd Hayton <todd.hayton@gmail.com>
-##  Copyright (C) 2009-2011 Micha Lenk <micha@debian.org>
 
-CC = @CC@
-CFLAGS = @CFLAGS@
-BINDIR = /usr/sbin
-#CFLAGS = -g -O2 -Wall
-#CFLAGS = -g -Wall -DHOST_OS_LINUX -DHAVE_LINUX_MROUTE6_H
+EXECS         = smcroute mcsender
+MCSENDER_OBJS = mcsender.o syslog.o
+SMCROUTE_OBJS = smcroute.o mroute-api.o ifvc.o cmdpkt.o ipc.o syslog.o \
+                udpsock.o mcgroup.o parse-conf.o pidfile.o
+OBJS          = $(MCSENDER_OBJS) $(SMCROUTE_OBJS)
+SRCS          = $(OBJS:.o=.c)
+DEPS          = $(addprefix .,$(SRCS:.c=.d))
 
-default : build.h smcroute
+# Smart autodependecy generation via GCC -M.
+.%.d: %.c
+	@$(SHELL) -ec "$(CC) -MM $(CFLAGS) $(CPPFLAGS) $< 2>/dev/null \
+		| sed 's,.*: ,$*.o $@ : ,g' > $@; \
+                [ -s $@ ] || rm -f $@"
 
-all	: smcroute mcsender
+.c.o:
+	@printf "  CC      $@\n"
+	@$(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<
 
-clean	:
-	rm -f *~ *.o *.asm build.h smcroute mcsender  
+all: $(EXECS)
 
-install : 
-	mkdir -p ${BINDIR}
-	cp smcroute mcsender ${BINDIR}
+install: all
+	@install -d $(DESTDIR)$(sbindir)
+	@for file in $(EXECS); do \
+		install -m 0755 $$file $(DESTDIR)$(sbindir)/$$file; \
+	done
 
-mcsender:  mcsender.o syslog.o lib.o config.h
+uninstall:
+	-@for file in $(EXECS); do \
+		$(RM) $(DESTDIR)$(sbindir)/$$file; \
+	done
 
-smcroute:  smcroute.o mroute-api.o ifvc.o cmdpkt.o ipc.o syslog.o udpsock.o mcgroup.o lib.o 
-smcroute.c : build.h config.h 
-
-build.h	:  
-	echo '#define BUILD "' `date +%y%m%d` '"' >build.h
+build.h:  
+	@echo '#define BUILD "' `date +%y%m%d` '"' >build.h
 
 config.h:
 	@echo "Please run ./configure first"
+
+mcsender:  $(MCSENDER_OBJS) config.h
+	@printf "  LINK    $@\n"
+	@$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(MCSENDER_OBJS) $(LDLIBS)
+
+$(SMCROUTE_OBJS): build.h config.h
+
+smcroute: $(SMCROUTE_OBJS)
+	@printf "  LINK    $@\n"
+	@$(CC) $(CFLAGS) $(LDFLAGS) -o $@ $(SMCROUTE_OBJS) $(LDLIBS)
+
+clean:
+	-@$(RM) build.h $(SMCROUTE_OBJS) $(MCSENDER_OBJS) $(EXECS)
+
+distclean: clean
+	-@$(RM) $(DEPS) *~ .bak DEADJOE semantic.cache *.gdb *.elf core core.*
+	-@$(RM) config.h Makefile
+
+
+# Include automatically generated rules
+ifneq ($(MAKECMDGOALS),clean)
+ifneq ($(MAKECMDGOALS),distclean)
+-include $(DEPS)
+endif
+endif
diff --git a/src/_mcclient.c b/src/_mcclient.c
index 729e47b..95ff472 100644
--- a/src/_mcclient.c
+++ b/src/_mcclient.c
@@ -25,17 +25,20 @@
 
 #include "mclab.h"
 
-int main()
+int main(void)
 {
-  int UdpSock = openUdpSocket( 0x010a0a0a, 7 );
-  
-  //  buildIfVc(); // brauch ich diesen Call ????
-  joinMcGroup( UdpSock, "eth0", 0xe1e1e1e1 );
+	mcgroup4_join("eth0", 0xe1e1e1e1);
 
-  printf( "\nEnter for end\n" );
-  getchar();
+	printf("\nEnter for end\n");
+	getchar();
 
-  close( UdpSock );
- 
-  return 0;
+	return 0;
 }
+
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/cmdpkt.c b/src/cmdpkt.c
index 2a8ff9a..c146eeb 100644
--- a/src/cmdpkt.c
+++ b/src/cmdpkt.c
@@ -31,284 +31,219 @@
 
 #include "mclab.h"
 
-static int getVifIxfromArg( const char *ArgPt )
 /*
-** Gets the VIF index for a given interface name '*ArgPt'
+** Builds an command packet with the command 'cmd' and 'count' arguments
+** from 'argv'.
 **
-** returns: - index of the VIF
-**          - -1 if no VIF can be found for the interface name
-**          
-*/
-{
-  struct IfDesc *IfDp;
-  int Rt;
-
-  /* get input interface index -> InpVifIx
-   */
-  if( ! (IfDp = getIfByName( ArgPt )) ) 
-    return -1;
-
-  if( (Rt = getVifIx( IfDp )) < 0 ) 
-    return -1;
-
-  return Rt;
-}
-
-static int getMifIxfromArg( const char *ArgPt )
-/*
-** Gets the MIF index for a given interface name '*ArgPt'
-**
-** returns: - index of the MIF
-**          - -1 if no MIF can be found for the interface name
-**          
+** returns: - pointer to the dyn. allocated command packet
 */
+void *cmd_build(char cmd, const char *argv[], int count)
 {
-  struct IfDesc *IfDp;
-  int Rt;
-
-  /* get input interface index -> InpVifIx
-   */
-  if( ! (IfDp = getIfByName( ArgPt )) ) 
-    return -1;
-
-  if( (Rt = getMifIx( IfDp )) < 0 ) 
-    return -1;
-
-  return Rt;
+	int i;
+	char *ptr;
+	size_t arg_len = 0, packet_len;
+	struct cmd *packet;
+
+	/* Summarize length of all arguments/commands */
+	for (i = 0; i < count; i++)
+		arg_len += strlen(argv[i]) + 1;
+
+	/* resulting packet size */
+	packet_len = sizeof(struct cmd) + arg_len + 1;
+	if (packet_len > MX_CMDPKT_SZ)
+		smclog(LOG_ERR, 0, "option too big");
+
+	/* build packet */
+	if (!(packet = malloc(packet_len)))
+		smclog(LOG_ERR, errno, "out of memory for option arguments");
+
+	packet->len = packet_len;
+	packet->cmd = cmd;
+	packet->count = count;
+
+	/* copy args */
+	ptr = (char *)(packet->argv);
+	for (i = 0; i < count; i++) {
+		arg_len = strlen(argv[i]) + 1;
+		memcpy(ptr, argv[i], arg_len);
+		ptr += arg_len;
+	}
+	*ptr = '\0';	/* '\0' behind last string */
+
+	return packet;
 }
 
-void *buildCmdPkt( char Cmd, const char *ArgVc[], int ParCn )
 /*
-** Builds an command packet with the command 'Cmd' and 'ParCn' arguments
-** from 'ArgVc'.
-**
-** returns: - pointer to the dyn. allocated command packet
-**          
-*/
-{
-  unsigned AccStSz, PktSz;
-  struct CmdPkt *PktPt;
-
-  /* accumulate space for arg strings */
-  {
-    const char **Pp;
-    int Cn;
-
-    for( Cn = ParCn, Pp = ArgVc, AccStSz = 0; Cn; Cn--, Pp++ ) 
-      AccStSz += strlen( *Pp ) +1;
-  } 
-
-  /* resulting packet size */
-  PktSz = sizeof( struct CmdPkt ) + AccStSz +1;
-
-  /* makes no sense */
-  if( PktSz > MX_CMDPKT_SZ ) 
-    smclog( LOG_ERR, 0, "option too big" );
-
-  /* build packet */
-  if( ! (PktPt = malloc( PktSz )) )
-    smclog( LOG_ERR, errno, "out of memory for option arguments" );
-
-  PktPt->PktSz = PktSz;
-  PktPt->Cmd   = Cmd;
-  PktPt->ParCn = ParCn;
-  
-  /* copy args */
-  {
-    char *FillPt;
-
-    for( FillPt = (char *)(PktPt +1); ParCn; ParCn--, ArgVc++ ) {
-      int Sz = strlen( *ArgVc ) +1;
-
-      memcpy( FillPt, *ArgVc, Sz );
-      FillPt += Sz;
-    }
-    
-    *FillPt = '\0';           /* '\0' behind last string */
-  }
-  
-  return PktPt;
-} 
-
-const char * 
-convCmdPkt2MRouteDesc( struct MRouteDesc *MrDp, const struct CmdPkt *PktPt )
-/*
-** Converts a command packet 'PktPt' to an MRouteDesc struct 'MrDp' for the
+** Converts a command packet 'packet' to an mroute struct 'mroute' for the
 ** 'add' and 'remove' command. The IP version is determined by searching
 ** for ':' in the address strings to indicate IPv6 addresses.
 **
 ** returns: - NULL if the conversion succeeded
 **          - an error string with a hint why the conversion failed
-**          
 */
+const char *cmd_convert_to_mroute(struct mroute *mroute, const struct cmd *packet)
 {
-  char *ArgSt = (char *)(PktPt +1);
-  
-  memset(MrDp, 0, sizeof(*MrDp));
-
-  switch (PktPt->Cmd) {
-  case 'a':
-  case 'r':
-    /* 
-     *
-     * -a eth0 1.1.1.1 239.1.1.1 eth1 eth2
-     *
-     *  +----+-----+---+--------------------------------------------+
-     *  | 42 | 'a' | 5 | "eth0\01.1.1.1\0239.1.1.1\0eth1\0eth2\0\0" | 
-     *  +----+-----+---+--------------------------------------------+
-     *  ^              ^
-     *  |              |  
-     *  |              |
-     *  +---CmdPkt-----+
-     *
-     * -r 1.1.1.1 239.1.1.1 
-     *
-     *  +----+-----+---+--------------------------+
-     *  | 27 | 'r' | 2 | "1.1.1.1\0239.1.1.1\0\0" | 
-     *  +----+-----+---+--------------------------+
-     *  ^              ^
-     *  |              |  
-     *  |              |
-     *  +---CmdPkt-----+
-     *
-     */
-    if (PktPt->Cmd == 'a' || PktPt->ParCn > 2)     
-      ArgSt += strlen(ArgSt) + 1;
-
-    if (strchr(ArgSt, ':') != NULL) {
-      MrDp->ipVersion = 6;
-      return convCmdPkt2MRoute6Desc( &MrDp->u.mRoute6Desc, PktPt );
-    } else {
-      MrDp->ipVersion = 4;
-      return convCmdPkt2MRoute4Desc( &MrDp->u.mRoute4Desc, PktPt );
-    }
-    break;
-
-  default:
-    return "Invalid command";
-  }
-
-  return NULL;
+	char *arg = (char *)packet->argv;
+
+	memset(mroute, 0, sizeof(*mroute));
+
+	switch (packet->cmd) {
+	case 'a':
+	case 'r':
+		/* -a eth0 1.1.1.1 239.1.1.1 eth1 eth2
+		 *
+		 *  +----+-----+---+--------------------------------------------+
+		 *  | 42 | 'a' | 5 | "eth0\01.1.1.1\0239.1.1.1\0eth1\0eth2\0\0" |
+		 *  +----+-----+---+--------------------------------------------+
+		 *  ^              ^
+		 *  |              |
+		 *  |              |
+		 *  +-----cmd------+
+		 *
+		 * -r 1.1.1.1 239.1.1.1
+		 *
+		 *  +----+-----+---+--------------------------+
+		 *  | 27 | 'r' | 2 | "1.1.1.1\0239.1.1.1\0\0" |
+		 *  +----+-----+---+--------------------------+
+		 *  ^              ^
+		 *  |              |
+		 *  |              |
+		 *  +-----cmd------+
+		 */
+		if (packet->cmd == 'a' || packet->count > 2)
+			arg += strlen(arg) + 1;
+
+		if (strchr(arg, ':') != NULL) {
+			mroute->version = 6;
+			return cmd_convert_to_mroute6(&mroute->u.mroute6, packet);
+		} else {
+			mroute->version = 4;
+			return cmd_convert_to_mroute4(&mroute->u.mroute4, packet);
+		}
+		break;
+
+	default:
+		return "Invalid command";
+	}
+
+	return NULL;
 }
 
-const char *
-convCmdPkt2MRoute4Desc( struct MRoute4Desc *MrDp, const struct CmdPkt *PktPt )
 /*
-** Converts a command packet 'PktPt' to an MRoute4Desc struct 'MrDp' for the
+** Converts a command packet 'packet' to an mroute4 struct 'mroute' for the
 ** 'add' and 'remove' command.
 **
 ** returns: - NULL if the conversion succeeded
 **          - an error string with a hint why the conversion failed
 **          
 */
+const char *cmd_convert_to_mroute4(struct mroute4 *mroute, const struct cmd *packet)
 {
-  const char *ArgSt = (const char *)(PktPt +1);
-
-  memset(MrDp, 0, sizeof(*MrDp));
-
-  /* 
-   *
-   * -a eth0 1.1.1.1 239.1.1.1 eth1 eth2
-   *
-   *  +----+-----+---+--------------------------------------------+
-   *  | 42 | 'a' | 5 | "eth0\01.1.1.1\0239.1.1.1\0eth1\0eth2\0\0" | 
-   *  +----+-----+---+--------------------------------------------+
-   *  ^              ^
-   *  |              |  
-   *  |              |
-   *  +---CmdPkt-----+
-   *        
-   */
-
-  /* get input interface index */
-  if( ! *ArgSt || (MrDp->InVif = getVifIxfromArg( ArgSt )) < 0 ) 
-    return "invalid input interface";
-
-  /* get origin */
-  ArgSt += strlen( ArgSt ) +1;
-  if( ! *ArgSt || (inet_pton( AF_INET, ArgSt, &MrDp->OriginAdr ) <= 0) ) 
-    return "invalid origin IP address";
-
-  /* get multicast group */
-  ArgSt += strlen( ArgSt ) +1;      
-  if( ! *ArgSt || (inet_pton( AF_INET, ArgSt, &MrDp->McAdr ) <= 0)
-   || ! IN_MULTICAST( ntohl( MrDp->McAdr.s_addr ) ) 
-  ) 
-    return "invalid multicast group address";
-
-  /*
-   * Scan output interfaces for the 'add' command only, just ignore it 
-   * for the 'remove' command to be compatible to the first release.
-   */
-  if( PktPt->Cmd == 'a' ) {
-    for( ArgSt += strlen( ArgSt ) +1; *ArgSt; ArgSt += strlen( ArgSt ) +1 ) {
-      int VifIx;
-
-      if( (VifIx = getVifIxfromArg( ArgSt )) < 0 )
-	return "invalid output interface";
-    
-      if( VifIx == MrDp->InVif ) 
-	smclog( LOG_WARNING, 0, "forwarding multicast to the input interface may not make sense: %s", ArgSt );
-    
-      MrDp->TtlVc[ VifIx ] = 1;           /* Use a TTL threashold */
-    }
-  }
-
-  return NULL;
+	char *arg = (char *)packet->argv;
+
+	memset(mroute, 0, sizeof(*mroute));
+
+	/* -a eth0 1.1.1.1 239.1.1.1 eth1 eth2
+	 *
+	 *  +----+-----+---+--------------------------------------------+
+	 *  | 42 | 'a' | 5 | "eth0\01.1.1.1\0239.1.1.1\0eth1\0eth2\0\0" |
+	 *  +----+-----+---+--------------------------------------------+
+	 *  ^              ^
+	 *  |              |
+	 *  |              |
+	 *  +-----cmd------+
+	 */
+
+	/* get input interface index */
+	if (!*arg || (mroute->inbound = iface_get_vif_by_name(arg)) < 0)
+		return "invalid input interface";
+
+	/* get origin */
+	arg += strlen(arg) + 1;
+	if (!*arg || (inet_pton(AF_INET, arg, &mroute->sender) <= 0))
+		return "invalid origin IP address";
+
+	/* get multicast group */
+	arg += strlen(arg) + 1;
+	if (!*arg || (inet_pton(AF_INET, arg, &mroute->group) <= 0) || !IN_MULTICAST(ntohl(mroute->group.s_addr)))
+		return "invalid multicast group address";
+
+	/*
+	 * Scan output interfaces for the 'add' command only, just ignore it
+	 * for the 'remove' command to be compatible to the first release.
+	 */
+	if (packet->cmd == 'a') {
+		for (arg += strlen(arg) + 1; *arg; arg += strlen(arg) + 1) {
+			int vif;
+
+			if ((vif = iface_get_vif_by_name(arg)) < 0)
+				return "invalid output interface";
+
+			if (vif == mroute->inbound)
+				smclog(LOG_WARNING, 0, "Forwarding multicast to the input interface may not make sense: %s", arg);
+
+			mroute->ttl[vif] = 1;	/* Use a TTL threashold */
+		}
+	}
+
+	return NULL;
 }
 
-const char *
-convCmdPkt2MRoute6Desc( struct MRoute6Desc *MrDp, const struct CmdPkt *PktPt )
 /*
-** Converts a command packet 'PktPt' to an MRoute6Desc struct 'MrDp' for the
+** Converts a command packet 'packet' to an mroute6 struct 'mroute' for the
 ** 'add' and 'remove' command.
 **
 ** returns: - NULL if the conversion succeeded
 **          - an error string with a hint why the conversion failed
 **          
 */
+const char *cmd_convert_to_mroute6(struct mroute6 *mroute, const struct cmd *packet)
 {
-  const char *ArgSt = (const char *)(PktPt +1);
-
-  memset(MrDp, 0, sizeof(*MrDp));
-
-  /* get input interface index */
-  if( ! *ArgSt || (MrDp->InMif = getMifIxfromArg( ArgSt )) < 0 ) 
-    return "invalid input interface";
-
-  /* get origin */
-  ArgSt += strlen( ArgSt ) +1;
-  if( ! *ArgSt || (inet_pton( AF_INET6, ArgSt, &MrDp->OriginAdr.sin6_addr ) <= 0) ) 
-    return "invalid origin IP address";
-
-  /* get multicast group */
-  ArgSt += strlen( ArgSt ) +1;      
-
-  if( ! *ArgSt || (inet_pton( AF_INET6, ArgSt, &MrDp->McAdr.sin6_addr ) <= 0) 
-      || ! IN6_MULTICAST( &MrDp->McAdr.sin6_addr ) ) 
-    return "invalid multicast group address";
-
-  /*
-   * Scan output interfaces for the 'add' command only, just ignore it 
-   * for the 'remove' command to be compatible to the first release.
-   */
-  if( PktPt->Cmd == 'a' ) {
-    for( ArgSt += strlen( ArgSt ) +1; *ArgSt; ArgSt += strlen( ArgSt ) +1 ) {
-      int MifIx;
-
-      if( (MifIx = getMifIxfromArg( ArgSt )) < 0 )
-	return "invalid output interface";
-    
-      if( MifIx == MrDp->InMif ) 
-	smclog( LOG_WARNING, 0, "forwarding multicast to the input interface may not make sense: %s", ArgSt );
-    
-      MrDp->TtlVc[ MifIx ] = 1;           /* Use a TTL threashold */
-    }
-  }
-
-  return NULL;
-}
+	const char *arg = (const char *)(packet + 1);
+
+	memset(mroute, 0, sizeof(*mroute));
 
+	/* get input interface index */
+	if (!*arg || (mroute->inbound = iface_get_mif_by_name(arg)) < 0)
+		return "Invalid input interface";
 
+	/* get origin */
+	arg += strlen(arg) + 1;
+	if (!*arg || (inet_pton(AF_INET6, arg, &mroute->sender.sin6_addr) <= 0))
+		return "Invalid origin IP address";
 
+	/* get multicast group */
+	arg += strlen(arg) + 1;
+
+	if (!*arg || (inet_pton(AF_INET6, arg, &mroute->group.sin6_addr) <= 0)
+	    || !IN6_IS_ADDR_MULTICAST(&mroute->group.sin6_addr))
+		return "Invalid multicast group";
+
+	/*
+	 * Scan output interfaces for the 'add' command only, just ignore it
+	 * for the 'remove' command to be compatible to the first release.
+	 */
+	if (packet->cmd == 'a') {
+ 		for (arg += strlen(arg) + 1; *arg; arg += strlen(arg) + 1) {
+			int mif;
+
+			if ((mif = iface_get_mif_by_name(arg)) < 0)
+				return "Invalid output interface";
+
+			if (mif == mroute->inbound)
+				smclog(LOG_WARNING, 0, "Forwarding multicast to the input interface may not make sense: %s", arg);
+
+			mroute->ttl[mif] = 1;	/* Use a TTL threashold */
+		}
+	}
+
+	return NULL;
+}
 
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/config.h.in b/src/config.h.in
index 4fb8c3f..423ae16 100644
--- a/src/config.h.in
+++ b/src/config.h.in
@@ -1,8 +1,11 @@
-/* config.h.in.  Generated from configure.ac by autoheader.  */
+/* src/config.h.in.  Generated from configure.ac by autoheader.  */
 
 /* Define to 1 if you have the <arpa/inet.h> header file. */
 #undef HAVE_ARPA_INET_H
 
+/* Define to 1 if you have the `asprintf' function. */
+#undef HAVE_ASPRINTF
+
 /* Define to 1 if you have the `atexit' function. */
 #undef HAVE_ATEXIT
 
@@ -164,6 +167,38 @@
 /* Define to 1 if you have the ANSI C header files. */
 #undef STDC_HEADERS
 
+/* Enable extensions on AIX 3, Interix.  */
+#ifndef _ALL_SOURCE
+# undef _ALL_SOURCE
+#endif
+/* Enable GNU extensions on systems that have them.  */
+#ifndef _GNU_SOURCE
+# undef _GNU_SOURCE
+#endif
+/* Enable threading extensions on Solaris.  */
+#ifndef _POSIX_PTHREAD_SEMANTICS
+# undef _POSIX_PTHREAD_SEMANTICS
+#endif
+/* Enable extensions on HP NonStop.  */
+#ifndef _TANDEM_SOURCE
+# undef _TANDEM_SOURCE
+#endif
+/* Enable general extensions on Solaris.  */
+#ifndef __EXTENSIONS__
+# undef __EXTENSIONS__
+#endif
+
+
+/* Define to 1 if on MINIX. */
+#undef _MINIX
+
+/* Define to 2 if the system does not provide POSIX.1 features except with
+   this defined. */
+#undef _POSIX_1_SOURCE
+
+/* Define to 1 if you need to in order for `stat' and other things to work. */
+#undef _POSIX_SOURCE
+
 /* Define for Solaris 2.5.1 so the uint32_t typedef from <sys/synch.h>,
    <pthread.h>, or <semaphore.h> is not used. If the typedef were allowed, the
    #define below would cause a syntax error. */
diff --git a/src/ifvc.c b/src/ifvc.c
index e400346..1eadb81 100644
--- a/src/ifvc.c
+++ b/src/ifvc.c
@@ -31,80 +31,205 @@
 #include <ifaddrs.h>
 #include "mclab.h"
 
-struct IfDesc IfDescVc[ MAX_IF ], *IfDescEp = IfDescVc;
+static unsigned int num_ifaces = 0;
+static struct iface iface_list[MAX_IF];
 
-void buildIfVc()
 /*
 ** Builds up a vector with the interface of the machine. Calls to the other functions of 
 ** the module will fail if they are called before the vector is build.
 **          
 */
+void iface_init(void)
 {
-  struct ifaddrs *ifaddr, *ifa;
-
-  memset(IfDescVc, 0, sizeof(IfDescVc));
-  
-  if (getifaddrs(&ifaddr) == -1) {
-    smclog( LOG_ERR, errno, "Failed to retrieve interface addresses" );
-    return;
-  }
-
-  for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
-    int family = ifa->ifa_addr->sa_family;
-
-    /* Skip non-IPv4 and non-IPv6 interfaces */
-    if ((family != AF_INET) && (family != AF_INET6)) continue;
-    /* Skip interface without internet address */
-    if (ifa->ifa_addr == NULL) continue;
-
-    /* Copy data from interface iterator 'ifa' */
-    strncpy(IfDescEp->Name, ifa->ifa_name, sizeof(IfDescEp->Name));
-    if (family == AF_INET)
-      IfDescEp->InAdr.s_addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr;
-    IfDescEp->Flags = ifa->ifa_flags;
-    IfDescEp->IfIndex = if_nametoindex(IfDescEp->Name);
-    IfDescEp->VifIndex = -1;
-    IfDescEp++;
-  }
-  freeifaddrs(ifaddr);
-}
+	int family;
+	struct iface *iface;
+	struct ifaddrs *ifaddr, *ifa;
+
+	num_ifaces = 0;
+	memset(iface_list, 0, sizeof(iface_list));
+
+	if (getifaddrs(&ifaddr) == -1) {
+		smclog(LOG_ERR, errno, "Failed to retrieve interface addresses");
+		return;
+	}
+
+	for (ifa = ifaddr; ifa != NULL && num_ifaces < ARRAY_ELEMENTS(iface_list); ifa = ifa->ifa_next) {
+		/* Skip interface without internet address */
+		if (ifa->ifa_addr == NULL)
+			continue;
 
+		/* Skip non-IPv4 and non-IPv6 interfaces */
+		family = ifa->ifa_addr->sa_family;
+		if ((family != AF_INET) && (family != AF_INET6))
+			continue;
+
+		/* Check if already added? */
+		if (iface_find_by_name (ifa->ifa_name))
+			continue;
+
+		/* Copy data from interface iterator 'ifa' */
+		iface = &iface_list[num_ifaces++];
+		strncpy(iface->name, ifa->ifa_name, sizeof(iface->name));
+		if (family == AF_INET)
+			iface->inaddr.s_addr = ((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr;
+		iface->flags = ifa->ifa_flags;
+		iface->ifindex = if_nametoindex(iface->name);
+		iface->vif = -1;
+		iface->mif = -1;
+	}
+	freeifaddrs(ifaddr);
+}
 
-struct IfDesc *getIfByName( const char *IfName )
 /*
-** Returns a pointer to the IfDesc of the interface 'IfName'
+** Returns a pointer to the iface of the interface 'ifname'
 **
-** returns: - pointer to the IfDesc of the requested interface
-**          - NULL if no interface 'IfName' exists
+** returns: - pointer to the iface of the requested interface
+**          - NULL if no interface 'ifname' exists
 **          
-**          - if more than one interface 'IfName' exists, chose the
+**          - if more than one interface 'ifname' exists, chose the
 **            an interface that corresponds to a virtual interface
 */
+struct iface *iface_find_by_name(const char *ifname)
 {
-  struct IfDesc *Dp;
-  struct IfDesc *candidate = NULL;
+	unsigned int i;
+	struct iface *iface;
+	struct iface *candidate = NULL;
 
-  for( Dp = IfDescVc; Dp < IfDescEp; Dp++ ) 
-    if( ! strcmp( IfName, Dp->Name ) ) {
-      if (Dp->VifIndex >= 0) return Dp;
-      candidate = Dp;
-  }
+	for (i = 0; i < num_ifaces; i++) {
+		iface = &iface_list[i];
+		if (!strcmp(ifname, iface->name)) {
+			if (iface->vif >= 0)
+				return iface;
+			candidate = iface;
+		}
+	}
 
-  return candidate;
+	return candidate;
 }
 
-struct IfDesc *getIfByIx( unsigned Ix )
 /*
-** Returns a pointer to the IfDesc of the interface 'Ix'
+** Returns a pointer to the iface matching the given 'vif'
 **
-** returns: - pointer to the IfDesc of the requested interface
-**          - NULL if no interface 'Ix' exists
+** returns: - pointer to the iface of the requested interface
+**          - NULL if no interface matching 'vif' exists
+**
+**          - if more than one interface 'ifname' exists, chose the
+**            an interface that corresponds to a virtual interface
+*/
+struct iface *iface_find_by_vif(int vif)
+{
+	unsigned int i;
+	struct iface *iface;
+
+	for (i = 0; i < num_ifaces; i++) {
+		iface = &iface_list[i];
+		if (iface->vif >= 0 && iface->vif == vif)
+			return iface;
+	}
+
+	return NULL;
+}
+
+/*
+** Returns a pointer to the iface of the interface 'ifindex'
+**
+** returns: - pointer to the iface of the requested interface
+**          - NULL if no interface 'ifindex' exists
 **          
 */
+struct iface *iface_find_by_index(unsigned int ifindex)
 {
-  struct IfDesc *Dp = &IfDescVc[ Ix ];
-  return Dp < IfDescEp ? Dp : NULL;
+	if (ifindex >= num_ifaces)
+		return NULL;
+
+	return &iface_list[ifindex];
 }
 
 
+/*
+** Returns for the virtual interface index for '*iface'
+**
+** returns: - the virtual interface index if the interface is registered
+**          - -1 if no virtual interface exists for the interface 
+**          
+*/
+int iface_get_vif(struct iface *iface)
+{
+	if (iface == NULL)
+		return -1;
+
+	return iface->vif;
+}
+
+/*
+** Returns for the virtual interface index for '*iface'
+**
+** returns: - the virtual interface index if the interface is registered
+**          - -1 if no virtual interface exists for the interface 
+**          
+*/
+int iface_get_mif(struct iface *iface __attribute__ ((unused)))
+{
+#ifndef HAVE_IPV6_MULTICAST_ROUTING
+	return -1;
+#else
+	if (iface == NULL)
+		return -1;
+
+	return iface->mif;
+#endif				/* HAVE_IPV6_MULTICAST_ROUTING */
+}
+
+/*
+** Gets the VIF index for a given interface name
+**
+** returns: - index of the VIF
+**          - -1 if no VIF can be found for the interface name
+**          
+*/
+int iface_get_vif_by_name(const char *ifname)
+{
+	int vif;
+	struct iface *iface;
+
+	iface = iface_find_by_name(ifname);
+	if (!iface)
+		return -1;
+
+	vif = iface_get_vif(iface);
+	if (vif < 0)
+		return -1;
+
+	return vif;
+}
+
+/*
+** Gets the MIF index for a given interface name
+**
+** returns: - index of the MIF
+**          - -1 if no MIF can be found for the interface name
+**          
+*/
+int iface_get_mif_by_name(const char *ifname)
+{
+	int vif;
+	struct iface *iface;
+
+	iface = iface_find_by_name(ifname);
+	if (!iface)
+		return -1;
+
+	vif = iface_get_mif(iface);
+	if (vif < 0)
+		return -1;
+
+	return vif;
+}
 
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/ipc.c b/src/ipc.c
index d13f7eb..e112c12 100644
--- a/src/ipc.c
+++ b/src/ipc.c
@@ -35,47 +35,43 @@
 #define SOCKET_PATH "/var/run/smcroute"
 
 /* server's listen socket */
-static int ListenSock; 
+static int server_sd;
 
 /* connected server or client socket */
-static int ConSock = -1;
+static int client_sd = -1;
 
-int initIpcServer()
 /*
 ** Inits an IPC listen socket 
 **
 ** returns: - the socket descriptor
-**
 */
+int ipc_server_init(void)
 {
-  struct sockaddr_un UnixAddr; 
-  socklen_t UnixAddrLen;
-
-  if( (ListenSock = socket( AF_UNIX, SOCK_STREAM, 0 )) < 0 ) {
-    smclog( LOG_INIT, errno, "initIpcServer, socket() failed" );
-    return -1;
-  }
+	struct sockaddr_un sa;
+	socklen_t len;
 
+	if ((server_sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
+           smclog(LOG_INIT, errno, "%s: socket() failed", __FUNCTION__);
+		return -1;
+	}
 #ifdef HAVE_SOCKADDR_UN_SUN_LEN
-  UnixAddr.sun_len = 0;    /* <- correct length is set by the OS */
+	sa.sun_len = 0;	/* <- correct length is set by the OS */
 #endif
-  UnixAddr.sun_family = AF_UNIX;
-  strcpy( UnixAddr.sun_path, SOCKET_PATH );
- 
-  unlink( SOCKET_PATH );
-
-  UnixAddrLen = offsetof(struct sockaddr_un, sun_path) + strlen(SOCKET_PATH);
-  if( bind( ListenSock, (struct sockaddr *)&UnixAddr, UnixAddrLen ) < 0
-      || listen( ListenSock, 1 ) ) {
-    smclog( LOG_INIT, errno, "initIpcServer, bind()/listen() failed" );
-    close(ListenSock);
-    return -1;
-  }
-
-  return ListenSock;
+	sa.sun_family = AF_UNIX;
+	strcpy(sa.sun_path, SOCKET_PATH);
+
+	unlink(SOCKET_PATH);
+
+	len = offsetof(struct sockaddr_un, sun_path)+strlen(SOCKET_PATH);
+	if (bind(server_sd, (struct sockaddr *)&sa, len) < 0 || listen(server_sd, 1)) {
+           smclog(LOG_INIT, errno, "%s: bind()/listen() failed", __FUNCTION__);
+           close(server_sd);
+           return -1;
+	}
+
+	return server_sd;
 }
 
-int initIpcClient()
 /*
 ** Connects to the IPC socket of the server
 **
@@ -85,125 +81,139 @@ int initIpcClient()
 **            - ENOENT - No such file or directory
 **            - ECONREFUSED - Connection refused
 */
+int ipc_client_init(void)
 {
-  struct sockaddr_un UnixAddr; 
-  socklen_t UnixAddrLen;
+	int err;
+	struct sockaddr_un sa;
+	socklen_t len;
 
-  if( (ConSock = socket( AF_UNIX, SOCK_STREAM, 0 )) < 0 )
-    smclog( LOG_ERR, errno, "initIpcClient, socket() failed" );
+	if ((client_sd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
+		smclog(LOG_ERR, errno, "%s: socket() failed", __FUNCTION__);
 
 #ifdef HAVE_SOCKADDR_UN_SUN_LEN
-  UnixAddr.sun_len = 0;    /* <- correct length is set by the OS */
+	sa.sun_len = 0;	/* <- correct length is set by the OS */
 #endif
-  UnixAddr.sun_family = AF_UNIX;
-  strcpy( UnixAddr.sun_path, SOCKET_PATH );
+	sa.sun_family = AF_UNIX;
+	strcpy(sa.sun_path, SOCKET_PATH);
+
+	len = offsetof(struct sockaddr_un, sun_path) + strlen(SOCKET_PATH);
+	if (connect(client_sd, (struct sockaddr *)&sa, len) < 0) {
+		err = errno;
+
+		close(client_sd);
+		client_sd = -1;
 
-  UnixAddrLen = offsetof(struct sockaddr_un, sun_path) + strlen(SOCKET_PATH);
-  if( connect( ConSock, (struct sockaddr *)&UnixAddr, UnixAddrLen ) < 0) {
-    int Err = errno;
+		return err;
+	}
 
-    close( ConSock ); ConSock = 0;
-    return Err;
-  }
+	smclog(LOG_DEBUG, 0, "%s: client connected, sd %d", __FUNCTION__, client_sd);
 
-  smclog( LOG_DEBUG, 0, "client connected, fd %d", ConSock );
-  return 0;
+	return 0;
 }
 
-struct CmdPkt *readIpcServer( uint8 Bu[], int BuSz )
 /*
-** Reads a message from the IPC socket and stores in 'Bu' with a max. size of 'BuSz'. 
+** Reads a message from the IPC socket and stores in 'buf' with a max. size of 'len'. 
 ** Connects and resets connection as necessary.
 **
-** returns: Pointer to a successfuly read command packet in 'Bu' 
-**
+** returns: Pointer to a successfuly read command packet in 'buf' 
 */
+struct cmd *ipc_server_read(uint8 buf[], int len)
 {
-  while( 1 ) {
-    int RdSz;
-    socklen_t AddrLn = 0;
-
-    /* wait for connections */
-    if( ConSock < 0 ) {
-      smclog( LOG_DEBUG, 0, "readIpcServer, waiting for connection..." );
-
-      if( (ConSock = accept( ListenSock, NULL, &AddrLn )) < 0 )
-	smclog( LOG_ERR, errno, "readIpcServer, accept() failed" );
-    
-      smclog( LOG_DEBUG, 0, "readIpcServer, accepted connection" );
-    }
-  
-    /* read */
-    memset( Bu, 0, BuSz );             /* had some problems with buffer garbage */
-    RdSz = read( ConSock, Bu, BuSz );                       
-    smclog( LOG_DEBUG, 0, "readIpcServer, CmdPkt read (%d)", RdSz );
-
-    /* successfull read */
-    if( RdSz >= sizeof( struct CmdPkt ) && RdSz == ((struct CmdPkt *)Bu)->PktSz )   
-      return (struct CmdPkt *)Bu;
-
-    /* connection lost ? -> reset connection */
-    if( ! RdSz ) {       
-      smclog( LOG_DEBUG, 0, "readIpcServer, connection lost" );
-      close( ConSock );
-      ConSock = -1;
-      continue;
-    }
-    
-    /* error */
-    smclog( LOG_WARNING, errno, "readIpcServer, read() failed" );
-  }
+	while (1) {
+		size_t size;
+		socklen_t socklen = 0;
+
+		/* wait for connections */
+		if (client_sd < 0) {
+			smclog(LOG_DEBUG, 0, "%s: waiting for connection...", __FUNCTION__);
+
+			if ((client_sd = accept(server_sd, NULL, &socklen)) < 0)
+				smclog(LOG_ERR, errno, "%s: accept() failed incoming connection", __FUNCTION__);
+
+			smclog(LOG_DEBUG, 0, "%s: connection accepted", __FUNCTION__);
+		}
+
+		/* read */
+		memset(buf, 0, len);	/* had some problems with buffer garbage */
+		size = read(client_sd, buf, len);
+		smclog(LOG_DEBUG, 0, "%s: command read(%d, %p, %d) => %zu should be at least %zu", __FUNCTION__,
+		       client_sd, buf, len, size, sizeof(struct cmd));
+
+		/* successful read */
+		if (size >= sizeof(struct cmd)) {
+			struct cmd *p = (struct cmd *)buf;
+
+			if (size == p->len)
+				return p;
+		}
+
+		/* connection lost ? -> reset connection */
+		if (!size) {
+			smclog(LOG_DEBUG, 0, "%s: connection lost", __FUNCTION__);
+			close(client_sd);
+			client_sd = -1;
+			continue;
+		}
+
+		/* error */
+		smclog(LOG_WARNING, errno, "%s: read() failed", __FUNCTION__);
+	}
 }
 
-int sendIpc( const void *Bu, int Sz )
 /*
-** Sends the IPC message in 'Bu' with the size 'Sz' to the peer.
+** Sends the IPC message in 'buf' with the size 'Sz' to the peer.
 **
 ** returns: - number of bytes written (Sz)
 **          - -1 if write failed
-**
 */
+int ipc_send(const void *buf, int len)
 {
-  if( write( ConSock, Bu, Sz ) != Sz ) {
-    smclog( LOG_ERR, errno, "sendIpc, write failed (%d)", Sz );
-    return -1;
-  }
+	if (write(client_sd, buf, len) != len) {
+		smclog(LOG_ERR, errno, "%s: write failed (%d)", __FUNCTION__, len);
+		return -1;
+	}
 
-  return Sz;
+	return len;
 }
 
-
-int readIpc( uint8 Bu[], int BuSz )
 /*
-** Reads the next IPC message in 'Bu' with the max. size 'BuSz' from the peer.
+** Reads the next IPC message in 'buf' with the max. size 'len' from the peer.
 **
-** returns: - number of bytes read (0..BuSz)
+** returns: - number of bytes read (0..len)
 **          - -1 if read failed
 ** 
 */
+int ipc_receive(uint8 buf[], int len)
 {
-  int RdSz = read( ConSock, Bu, BuSz );                       
-  smclog( LOG_DEBUG, 0, "readIpc, read (%d)", RdSz );
+	int size = read(client_sd, buf, len);
 
-  if( RdSz < 1 )
-    smclog( LOG_WARNING, errno, "readIpc, read() failed" );
+	smclog(LOG_DEBUG, 0, "%s: read (%d)", __FUNCTION__, size);
 
-  return RdSz;
-}
+	if (size < 1)
+		smclog(LOG_WARNING, errno, "%s: read() failed", __FUNCTION__);
 
+	return size;
+}
 
-void cleanIpc()
 /*
 ** Clean up IPC.
-**
 ** 
 */
+void ipc_exit(void)
 {
-  if( ListenSock ) {
-    close( ListenSock );
-    unlink( SOCKET_PATH );
-  }
+	if (server_sd) {
+		close(server_sd);
+		unlink(SOCKET_PATH);
+	}
 
-  if( ConSock >= 0 )
-    close( ConSock );
+	if (client_sd >= 0)
+		close(client_sd);
 }
+
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/lib.c b/src/lib.c
deleted file mode 100644
index 8226f08..0000000
--- a/src/lib.c
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
-**  smcroute - static multicast routing control 
-**  Copyright (C) 2001-2005 Carsten Schill <carsten@cschill.de>
-**  Copyright (C) 2006-2009 Julien BLACHE <jb@jblache.org>
-**  Copyright (C) 2009      Todd Hayton <todd.hayton@gmail.com>
-**
-**  This program is free software; you can redistribute it and/or modify
-**  it under the terms of the GNU General Public License as published by
-**  the Free Software Foundation; either version 2 of the License, or
-**  (at your option) any later version.
-**
-**  This program is distributed in the hope that it will be useful,
-**  but WITHOUT ANY WARRANTY; without even the implied warranty of
-**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-**  GNU General Public License for more details.
-**
-**  You should have received a copy of the GNU General Public License
-**  along with this program; if not, write to the Free Software
-**  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
-**
-**  $Id: lib.c 85 2011-08-08 16:47:53Z micha $	
-**
-**  This module contains the remaining functions that where not placed in 
-**  separate modules
-**
-*/
-
-#include "mclab.h"
-
-char *fmtInAdr( char *St, struct in_addr InAdr )
-/*
-** Formats 'InAdr' into a dotted decimal string. 
-**
-** returns: - pointer to 'St'
-**          
-*/
-{
-  sprintf( St, "%u.%u.%u.%u", 
-	   ((uint8 *)&InAdr.s_addr)[ 0 ],
-	   ((uint8 *)&InAdr.s_addr)[ 1 ],
-	   ((uint8 *)&InAdr.s_addr)[ 2 ],
-	   ((uint8 *)&InAdr.s_addr)[ 3 ] );
-
-  return St;
-}
-
-char *fmtSockAdr( char *St, const struct sockaddr_in *SockAdrPt )
-/*
-** Formats 'SockAdrPt' into a dotted decimal string.
-**
-** returns: - pointer to 'St'
-**          
-*/
-{
-  uint32 Adr;
-  uint8  *AdrByPt;
-  char *Pt = St;
-
-  if( SockAdrPt->sin_family != AF_INET )
-    smclog( LOG_ERR, 0, "fmtSockAdr: not an INET address" );
-
-  Adr = SockAdrPt->sin_addr.s_addr;
-  
-  for( AdrByPt = (uint8 *)&Adr; AdrByPt < (uint8 *)(&Adr +1); AdrByPt++ ) { 
-    Pt += sprintf( Pt, "%u", *AdrByPt );
-    *Pt++ = '.';
-  }
-  *--Pt ='\0';
-  
-  if( SockAdrPt->sin_port )
-    Pt += sprintf( Pt, ":%u", SockAdrPt->sin_port ); 
-
-  return St;
-}
-
-
-int getInAdr( uint32 *InAdrPt, uint16 *PortPt, char *St )
-/*
-** Converts the dotted decimal internet address plus port
-** (xx.xx.xx.xx:pp) in 'St' into their integer 
-** representations.
-**
-** 'PortPt' can be NULL if no port number is included or
-** should not be converted.
-**
-** If 'PortPt' is not NULL, then a port number must exist
-** in 'St'
-**  
-** returns: - 0 -> conversion failed
-**          - 1 -> only address part returned (InAdrPt)
-**          - 2 -> address and port returned
-**          
-*/
-{
-  unsigned AdrVc[ 4 ], Port;
-
-  /* read address + port
-   */
-  if( PortPt ) {
-    if( sscanf( St, "%u.%u.%u.%u:%us", &AdrVc[ 0 ], &AdrVc[ 1 ], 
-		&AdrVc[ 2 ], &AdrVc[ 3 ], &Port ) != 5 ) 
-      return 0;
-
-    Port = htons( Port );
-  }
-  else {
-    if( sscanf( St, "%u.%u.%u.%u", &AdrVc[ 0 ], &AdrVc[ 1 ], 
-		&AdrVc[ 2 ], &AdrVc[ 3 ]  ) != 4 ) 
-      return 0;
-
-    Port = 0;
-  }
-
-  {
-    int Ix;
-
-    for( Ix = 0; Ix < 4; Ix++ ) {
-      if( AdrVc[ Ix ] > 255 )
-	return 0;
-
-      ((uint8 *)InAdrPt)[ Ix ] = AdrVc[ Ix ];
-    }
-  }
-  
-  if( ! PortPt ) 
-    return 1;
-
-  if( Port > 0xffffu ) 
-    return 0;
-
-  *PortPt = Port;
-  return 2;
-}
-
-void getSockAdr( struct sockaddr * SaPt, socklen_t * SaLenPt, char * AddrSt, char * PortSt )
-/*
-** Converts the internet address plus port string in 'St' 
-** into their network byte order representations.
-**
-**  
-** returns: - 0 -> conversion failed
-**          - 1 -> only address part returned (InAdrPt)
-**          - 2 -> address and port returned
-**          
-*/
-{
-  struct sockaddr_in  * Sin4;
-  struct sockaddr_in6 * Sin6;
-
-  if ( strchr( AddrSt, ':' ) == NULL ) {
-    Sin4 = SIN4( SaPt );
-    memset( Sin4, 0, sizeof( *Sin4 ) );
-
-    Sin4->sin_family = AF_INET;
-    Sin4->sin_port   = htons( atoi( PortSt ) );
-
-    if ( inet_pton( AF_INET, AddrSt, &Sin4->sin_addr ) <= 0 )
-      smclog( LOG_ERR, errno, "inet_pton failed for address %s", AddrSt );
-
-    *SaLenPt = sizeof( struct sockaddr_in );
-
-  } else {
-    Sin6 = SIN6( SaPt );
-    memset( Sin6, 0, sizeof( *Sin6 ) );
-
-    Sin6->sin6_family = AF_INET6;
-    Sin6->sin6_port   = htons( atoi( PortSt ) );
-
-    if ( inet_pton( AF_INET6, AddrSt, &Sin6->sin6_addr ) <= 0 )
-      smclog( LOG_ERR, errno, "inet_pton failed for address %s", AddrSt );
-
-    *SaLenPt = sizeof( struct sockaddr_in6 );
-
-  }
-
-  return;
-}
diff --git a/src/mcgroup.c b/src/mcgroup.c
index d1a6e5e..39a75dd 100644
--- a/src/mcgroup.c
+++ b/src/mcgroup.c
@@ -27,128 +27,166 @@
 
 #include "mclab.h"
 
-static int joinleave4( int, int, const char *, struct in_addr );
-static int joinleave6( int, int, const char *, struct in6_addr );
+static int mcgroup4_socket = -1;
+
+static void mcgroup4_init(void)
+{
+	if (mcgroup4_socket < 0) {
+		mcgroup4_socket = udp_socket_open(INADDR_ANY, 0);
+	}
+}
+
+static int mcgroup_join_leave_ipv4(int sd, int cmd, const char *ifname, struct in_addr group)
+{
+	int joinleave = cmd == 'j' ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP;
+	char buf[INET_ADDRSTRLEN];
+	const char *command = cmd == 'j' ? "Join" : "Leave";
+	struct ip_mreq mreq;
+	struct iface *iface = iface_find_by_name(ifname);
+
+	if (!iface) {
+		smclog(LOG_WARNING, 0, "%s multicast group, unknown interface %s", command, ifname);
+		return 1;
+	}
+
+	smclog(LOG_NOTICE, 0, "%s multicast group: %s on %s", command,
+	       inet_ntop(AF_INET, &group, buf, sizeof(buf)), iface ? iface->name : "<any>");
+
+	mreq.imr_multiaddr.s_addr = group.s_addr;
+	mreq.imr_interface.s_addr = iface->inaddr.s_addr;
+	if (setsockopt(sd, IPPROTO_IP, joinleave, (void *)&mreq, sizeof(mreq))) {
+		if (EADDRINUSE != errno)
+			smclog(LOG_WARNING, errno, "%s MEMBERSHIP failed", cmd == 'j' ? "ADD" : "DROP");
+		return 1;
+	}
+
+	return 0;
+}
 
-int joinMcGroup4( int UdpSock, const char *IfName, struct in_addr McAdr )
 /*
-** Joins the MC group with the address 'McAdr' on the interface 'IfName'. 
-** The join is bound to the UDP socket 'UdpSock', so if this socket is 
+** Joins the MC group with the address 'group' on the interface 'ifname'. 
+** The join is bound to the UDP socket 'sd', so if this socket is 
 ** closed the membership is dropped.
 **          
 ** returns: - 0 if the function succeeds
 **          - 1 if parameters are wrong or the join fails
 */
+int mcgroup4_join(const char *ifname, struct in_addr group)
 {
-  return joinleave4( 'j', UdpSock, IfName, McAdr );
+	mcgroup4_init();
+
+	return mcgroup_join_leave_ipv4(mcgroup4_socket, 'j', ifname, group);
 }
 
-int leaveMcGroup4( int UdpSock, const char *IfName, struct in_addr McAdr )
 /*
-** Leaves the MC group with the address 'McAdr' on the interface 'IfName'. 
+** Leaves the MC group with the address 'group' on the interface 'ifname'. 
 **          
 ** returns: - 0 if the function succeeds
 **          - 1 if parameters are wrong or the join fails
 */
+int mcgroup4_leave(const char *ifname, struct in_addr group)
 {
-  return joinleave4( 'l', UdpSock, IfName, McAdr );
+	mcgroup4_init();
+
+	return mcgroup_join_leave_ipv4(mcgroup4_socket, 'l', ifname, group);
 }
 
-int joinMcGroup6( int UdpSock, const char *IfName, struct in6_addr McAdr )
 /*
-** Joins the MC group with the address 'McAdr' on the interface 'IfName'. 
-** The join is bound to the UDP socket 'UdpSock', so if this socket is 
-** closed the membership is dropped.
-**          
-** returns: - 0 if the function succeeds
-**          - 1 if parameters are wrong or the join fails
+** Close IPv4 multicast socket to kernel to leave any joined groups
 */
+void mcgroup4_disable(void)
+{
+	if (mcgroup4_socket != -1) {
+		close (mcgroup4_socket);
+		mcgroup4_socket = -1;
+	}
+}
+
+#ifdef HAVE_IPV6_MULTICAST_HOST
+static int mcgroup6_socket = -1;
+
+static void mcgroup6_init(void)
+{
+	if (mcgroup6_socket < 0) {
+		mcgroup6_socket = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
+		if (mcgroup6_socket < 0)
+			smclog(LOG_WARNING, errno, "socket failed");
+	}
+}
+
+static int mcgroup_join_leave_ipv6(int sd, int cmd, const char *ifname, struct in6_addr group)
 {
-  return joinleave6( 'j', UdpSock, IfName, McAdr );
+	int joinleave = cmd == 'j' ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP;
+	char buf[INET6_ADDRSTRLEN];
+	const char *command = cmd == 'j' ? "Join" : "Leave";
+	struct ipv6_mreq mreq;
+	struct iface *iface = iface_find_by_name(ifname);
+
+	if (!iface) {
+		smclog(LOG_WARNING, 0, "%s multicast group, unknown interface %s", command, ifname);
+		return 1;
+	}
+
+	smclog(LOG_NOTICE, 0, "%s multicast group: %s on %s", command,
+	       inet_ntop(AF_INET6, &group, buf, sizeof(buf)), iface ? iface->name : "<any>");
+
+	mreq.ipv6mr_multiaddr = group;
+	mreq.ipv6mr_interface = iface->ifindex;
+	if (setsockopt(sd, IPPROTO_IPV6, joinleave, (void *)&mreq, sizeof(mreq))) {
+		if (EADDRINUSE != errno)
+			smclog(LOG_WARNING, errno, "%s MEMBERSHIP failed", cmd == 'j' ? "ADD" : "DROP");
+		return 1;
+	}
+
+	return 0;
 }
 
-int leaveMcGroup6( int UdpSock, const char *IfName, struct in6_addr McAdr )
 /*
-** Leaves the MC group with the address 'McAdr' on the interface 'IfName'. 
-**          
+** Joins the MC group with the address 'group' on the interface 'ifname'.
+** The join is bound to the UDP socket 'sd', so if this socket is
+** closed the membership is dropped.
+**
 ** returns: - 0 if the function succeeds
 **          - 1 if parameters are wrong or the join fails
 */
+int mcgroup6_join(const char *ifname, struct in6_addr group)
 {
-  return joinleave6( 'l', UdpSock, IfName, McAdr );
+	mcgroup6_init();
+
+	return mcgroup_join_leave_ipv6(mcgroup6_socket, 'j', ifname, group);
 }
 
-static int joinleave4( int Cmd, int UdpSock, const char *IfName, struct in_addr McAdr )
 /*
-**          
+** Leaves the MC group with the address 'group' on the interface 'ifname'.
+**
+** returns: - 0 if the function succeeds
+**          - 1 if parameters are wrong or the join fails
 */
+int mcgroup6_leave(const char *ifname, struct in6_addr group)
 {
-  struct ip_mreq CtlReq;
-  struct IfDesc *IfDp = getIfByName( IfName );
-  const char *CmdSt = Cmd == 'j' ? "join" : "leave";
-  
-
-  if( ! IfDp ) { 
-    smclog( LOG_WARNING, 0, "%sMcGroup, unknown interface %s", CmdSt, IfName );
-    return 1;
-  }
-
-  CtlReq.imr_multiaddr.s_addr = McAdr.s_addr;
-  CtlReq.imr_interface.s_addr = IfDp->InAdr.s_addr;
-
-  {
-    char FmtBu[ INET_ADDRSTRLEN ];
-    smclog( LOG_NOTICE, 0, "%sMcGroup: %s on %s", CmdSt, 
-	    inet_ntop( AF_INET, &McAdr, FmtBu, sizeof( FmtBu ) ), IfDp ? IfDp->Name : "<any>" );
-  }
-
-  if( setsockopt( UdpSock, IPPROTO_IP, 
-		  Cmd == 'j' ? IP_ADD_MEMBERSHIP : IP_DROP_MEMBERSHIP, 
-		  (void *)&CtlReq, sizeof( CtlReq ) ) ) 
-  {
-    smclog( LOG_WARNING, errno, "%s MEMBERSHIP failed", Cmd == 'j' ? "ADD" : "DROP" );
-    return 1;
-  }
-
-  return 0;
+	mcgroup6_init();
+
+	return mcgroup_join_leave_ipv6(mcgroup6_socket, 'l', ifname, group);
 }
+#endif /* HAVE_IPV6_MULTICAST_HOST */
 
-static int joinleave6( int Cmd, int UdpSock, const char *IfName, struct in6_addr McAdr )
 /*
-**          
+** Close IPv6 multicast socket to kernel to leave any joined groups
 */
+void mcgroup6_disable(void)
 {
-#ifndef HAVE_IPV6_MULTICAST_HOST
-  return 0;
-#else
-  struct ipv6_mreq CtlReq;
-  struct IfDesc *IfDp = getIfByName( IfName );
-  const char *CmdSt = Cmd == 'j' ? "join" : "leave";
-  
-
-  if( ! IfDp ) { 
-    smclog( LOG_WARNING, 0, "%sMcGroup, unknown interface %s", CmdSt, IfName );
-    return 1;
-  }
-
-  CtlReq.ipv6mr_multiaddr = McAdr;
-  CtlReq.ipv6mr_interface = IfDp->IfIndex;
-
-  {
-    char FmtBu[ INET6_ADDRSTRLEN ];
-    smclog( LOG_NOTICE, 0, "%sMcGroup: %s on %s", CmdSt, 
-	    inet_ntop( AF_INET6, &McAdr, FmtBu, sizeof( FmtBu ) ), IfDp ? IfDp->Name : "<any>" );
-  }
-
-  if( setsockopt( UdpSock, IPPROTO_IPV6, 
-		  Cmd == 'j' ? IPV6_JOIN_GROUP : IPV6_LEAVE_GROUP, 
-		  (void *)&CtlReq, sizeof( CtlReq ) ) ) 
-  {
-    smclog( LOG_WARNING, errno, "%s MEMBERSHIP failed", Cmd == 'j' ? "ADD" : "DROP" );
-    return 1;
-  }
-
-  return 0;
+#ifdef HAVE_IPV6_MULTICAST_HOST
+	if (mcgroup6_socket != -1) {
+		close (mcgroup6_socket);
+		mcgroup6_socket = -1;
+	}
 #endif /* HAVE_IPV6_MULTICAST_HOST */
 }
 
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/mclab.h b/src/mclab.h
index cfc861a..c5d8b88 100644
--- a/src/mclab.h
+++ b/src/mclab.h
@@ -23,13 +23,13 @@
 **
 */
 
-
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdarg.h>
 #include <syslog.h>
 #include <errno.h>
+#include <unistd.h>
 
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -38,6 +38,7 @@
 #include <sys/ioctl.h>
 #include <sys/socket.h>
 #include <sys/un.h>
+#include <sys/queue.h>
 
 #include <net/if.h>
 
@@ -47,193 +48,205 @@
 #include "config.h"
 
 #ifdef HAVE_LINUX_MROUTE_H
- #include <linux/mroute.h>
+#define _LINUX_IN_H             /* For Linux <= 2.6.25 */
+#include <linux/types.h>
+#include <linux/mroute.h>
 #endif
 
 #ifdef HAVE_LINUX_MROUTE6_H
- #include <linux/mroute6.h>
+#include <linux/mroute6.h>
 #endif
 
 #ifdef HAVE_NET_ROUTE_H
- #include <net/route.h>
+#include <net/route.h>
 #endif
 
 #ifdef HAVE_NETINET_IP_MROUTE_H
- #include <netinet/ip_mroute.h>
+#include <netinet/ip_mroute.h>
 #endif
 
 #ifdef HAVE_NETINET6_IP6_MROUTE_H
- #ifdef HAVE_SYS_PARAM_H
-  #include <sys/param.h>
- #endif
- #include <netinet6/ip6_mroute.h>
+#ifdef HAVE_SYS_PARAM_H
+#include <sys/param.h>
+#endif
+#include <netinet6/ip6_mroute.h>
 #endif
 
-typedef u_int8_t   uint8;
-typedef u_int16_t  uint16;
-typedef u_int32_t  uint32;
+typedef u_int8_t uint8;
+typedef u_int16_t uint16;
+typedef u_int32_t uint32;
 
-#define SA( x ) ((struct sockaddr *)x)
-#define SIN4( x ) ((struct sockaddr_in *)x)
-#define SIN6( x ) ((struct sockaddr_in6 *)x)
+#define SA(x)   ((struct sockaddr *)x)
+#define SIN4(x) ((struct sockaddr_in *)x)
+#define SIN6(x) ((struct sockaddr_in6 *)x)
 
 #ifndef MIN
-#define MIN( a, b ) ((a) < (b) ? (a) : (b))
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
 #endif
 #ifndef MAX
-#define MAX( a, b ) ((a) < (b) ? (b) : (a))
+#define MAX(a, b) ((a) < (b) ? (b) : (a))
 #endif
-#define VCMC( Vc )  (sizeof( Vc ) / sizeof( (Vc)[ 0 ] ))
-#define VCEP( Vc )  (&(Vc)[ VCMC( Vc ) ])
-
-#define MAX_MC_VIFS    MAXVIFS     /* = to MAXVIFS from linux/mroute.h */
-#define MAX_MC_MIFS    MAXMIFS     /* = to MAXMIFS from linux/mroute6.h */
-
-struct IfDesc {
-  char Name[ sizeof( ((struct ifreq *)NULL)->ifr_name ) ];
-  struct in_addr InAdr;          /* == 0 for non IP interfaces */            
-  u_short IfIndex;               /* Physical interface index   */
-  short Flags;
-  short VifIndex;
-};
 
-/* ifvc.c
+/* http://stackoverflow.com/questions/1598773/is-there-a-standard-function-in-c-that-would-return-the-length-of-an-array/1598827#1598827 
+ * Evidently Google uses it in Chromium.  It is actually intended to look like 0[arr], read the link, or search the web.
  */
-#define MAX_IF         40     // max. number of interfaces recognized 
+#define ARRAY_ELEMENTS(arr) ((sizeof(arr)/sizeof(0[arr])) / ((size_t)(!(sizeof(arr) % sizeof(0[arr])))))
+
+struct iface {
+	char name[IFNAMSIZ];
+	struct in_addr inaddr;	/* == 0 for non IP interfaces */
+	u_short ifindex;	/* Physical interface index   */
+	short flags;
+	short vif;
+	short mif;
+};
 
-void buildIfVc( void );
-struct IfDesc *getIfByName( const char *IfName );
-struct IfDesc *getIfByIx( unsigned Ix );
+extern int do_debug_logging;
 
-/* mroute-api.c
- */
+/* ifvc.c */
+#define MAX_IF         40	// max. number of interfaces recognized
+
+void          iface_init            (void);
+struct iface *iface_find_by_name    (const char *ifname);
+struct iface *iface_find_by_index   (unsigned int ifindex);
+struct iface *iface_find_by_vif     (int vif);
+int           iface_get_vif         (struct iface *iface);
+int           iface_get_mif         (struct iface *iface);
+int           iface_get_vif_by_name (const char *ifname);
+int           iface_get_mif_by_name (const char *ifname);
+
+/* mroute-api.c */
 
 /*
  * IPv4 multicast route
  */
-struct MRoute4Desc {
-  struct in_addr OriginAdr;    /* sender          */
-  struct in_addr McAdr;        /* multicast group */
-  short InVif;                 /* incoming VIF    */
-  uint8 TtlVc[ MAX_MC_VIFS ];  /* outgoing VIFs   */
+#define MAX_MC_VIFS MAXVIFS		/* from linux/mroute.h */
+
+struct mroute4 {
+	LIST_ENTRY(mroute4) link;
+
+	struct in_addr sender;
+	struct in_addr group;           /* multicast group */
+	short inbound;                  /* incoming VIF    */
+	uint8 ttl[MAX_MC_VIFS];         /* outgoing VIFs   */
 };
+typedef struct mroute4 mroute4_t;
 
 /*
  * IPv6 multicast route
  */
-struct MRoute6Desc {
-  struct sockaddr_in6 OriginAdr; /* sender          */
-  struct sockaddr_in6 McAdr;     /* multicast group */
-  short InMif;                   /* incoming VIF    */
-  uint8 TtlVc[ MAX_MC_MIFS ];    /* outgoing VIFs   */
+#ifdef HAVE_IPV6_MULTICAST_ROUTING
+#define MAX_MC_MIFS MAXMIFS		/* from linux/mroute6.h */
+#else
+#define MAX_MC_MIFS 1			/* Dummy value for builds w/o IPv6 routing */
+#endif
+
+struct mroute6 {
+	struct sockaddr_in6 sender;
+	struct sockaddr_in6 group;      /* multicast group */
+	short inbound;                  /* incoming VIF    */
+	uint8 ttl[MAX_MC_MIFS];         /* outgoing VIFs   */
 };
+typedef struct mroute6 mroute6_t;
 
 /*
  * Generic multicast route (wrapper for IPv4/IPv6 mroute) 
  */
-struct MRouteDesc {
-  int ipVersion; /* 4 or 6 */
-  union {
-    struct MRoute4Desc mRoute4Desc;
-    struct MRoute6Desc mRoute6Desc;
-  } u;
+struct mroute {
+	int version;		/* 4 or 6 */
+	union {
+		mroute4_t mroute4;
+		mroute6_t mroute6;
+	} u;
 };
+typedef struct mroute mroute_t;
 
 /* 
  * Raw IGMP socket used as interface for the IPv4 mrouted API.
  * Receives IGMP packets and upcall messages from the kernel.
  */
-extern int MRouterFD4;
+extern int mroute4_socket;
 
 /*
  * Raw ICMPv6 socket used as interface for the IPv6 mrouted API.
  * Receives MLD packets and upcall messages from the kenrel.
  */
-extern int MRouterFD6;
-
-int enableMRouter4( void );
-void disableMRouter4( void );
-int addMRoute4( struct MRoute4Desc * Dp );
-int delMRoute4( struct MRoute4Desc * Dp );
-void addVIF( struct IfDesc *Dp );
-int getVifIx( struct IfDesc *IfDp );
-
-int enableMRouter6( void );
-void disableMRouter6( void );
-int addMRoute6( struct MRoute6Desc * Dp );
-int delMRoute6( struct MRoute6Desc * Dp );
-void addMIF( struct IfDesc *Dp );
-int getMifIx( struct IfDesc *IfDp );
-
-/* ipc.c
- */
-int initIpcServer( void );
-struct CmdPkt *readIpcServer( uint8 Bu[], int BuSz );
-int initIpcClient( void );
-int  sendIpc( const void *Bu, int Sz );
-int  readIpc( uint8 Bu[], int BuSz );
-void cleanIpc( void );
+extern int mroute6_socket;
+
+int  mroute4_enable  (void);
+void mroute4_disable (void);
+int  mroute4_dyn_add (mroute4_t *mroute);
+int  mroute4_add     (mroute4_t *mroute);
+int  mroute4_del     (mroute4_t *mroute);
+
+int  mroute6_enable  (void);
+void mroute6_disable (void);
+int  mroute6_add     (mroute6_t *mroute);
+int  mroute6_del     (mroute6_t *mroute);
+
+/* ipc.c */
+int         ipc_server_init (void);
+struct cmd *ipc_server_read (uint8 buf[], int len);
+int         ipc_client_init (void);
+int         ipc_send        (const void *buf, int len);
+int         ipc_receive     (uint8 buf[], int len);
+void        ipc_exit        (void);
 
 /* cmdpkt.c
  *
- * XXX show sample packet layouts
+ * XXX: Add example packet layouts
  */
-struct CmdPkt {
-  unsigned PktSz; /* total size of packet including CmdPkt header */
-  uint16   Cmd;   /* 'a'=Add,'r'=Remove,'j'=Join,'l'=Leave,'k'=Kill */
-  uint16   ParCn; /* command argument count */
-  /* 'ParCn' * '\0' terminated strings + '\0' */
+struct cmd {
+	size_t   len;		/* total size of packet including cmd header */
+	uint16   cmd;		/* 'a'=Add,'r'=Remove,'j'=Join,'l'=Leave,'k'=Kill */
+	uint16   count;		/* command argument count */
+	char    *argv[0]; 	/* 'count' * '\0' terminated strings + '\0' */
 };
 
-#define MX_CMDPKT_SZ 1024   /* CmdPkt size including appended strings */
-
-void *buildCmdPkt( char Cmd, const char *ArgVc[], int ParCn );
-const char *convCmdPkt2MRouteDesc( struct MRouteDesc *MrDp, const struct CmdPkt *PktPt );
-const char *convCmdPkt2MRoute4Desc( struct MRoute4Desc *MrDp, const struct CmdPkt *PktPt );
-const char *convCmdPkt2MRoute6Desc( struct MRoute6Desc *MrDp, const struct CmdPkt *PktPt );
+#define MX_CMDPKT_SZ 1024	/* command size including appended strings */
 
-/* lib.c
- */
-char *fmtInAdr( char *St, struct in_addr InAdr );
-char *fmtSockAdr( char *St, const struct sockaddr_in *SockAdrPt );
-int getInAdr( uint32 *InAdrPt, uint16 *PortPt, char *St );
-void getSockAdr( struct sockaddr * SaPt, socklen_t * SaLenPt, char * AddrSt, char * PortSt );
-
-/* mcgroup.c
- */
-int joinMcGroup4( int UdpSock, const char *IfName, struct in_addr McAdr );
-int leaveMcGroup4( int UdpSock, const char *IfName, struct in_addr McAdr );
-int joinMcGroup6( int UdpSock, const char *IfName, struct in6_addr McAdr );
-int leaveMcGroup6( int UdpSock, const char *IfName, struct in6_addr McAdr );
+void       *cmd_build              (char cmd, const char *argv[], int count);
+const char *cmd_convert_to_mroute  (mroute_t *mroute, const struct cmd *packet);
+const char *cmd_convert_to_mroute4 (mroute4_t *mroute, const struct cmd *packet);
+const char *cmd_convert_to_mroute6 (mroute6_t *mroute, const struct cmd *packet);
 
+/* mcgroup.c */
+int  mcgroup4_join    (const char *ifname, struct in_addr  group);
+int  mcgroup4_leave   (const char *ifname, struct in_addr  group);
+void mcgroup4_disable (void);
+int  mcgroup6_join    (const char *ifname, struct in6_addr group);
+int  mcgroup6_leave   (const char *ifname, struct in6_addr group);
+void mcgroup6_disable (void);
 
-/* syslog.c
- */
-
+/* syslog.c */
 #define LOG_INIT 10
 
-extern int  Log2Stderr;           /* Log threshold for stderr, LOG_WARNING .... LOG_DEBUG */
-extern int  LogLastServerity;     /* last logged serverity   */
-extern int  LogLastErrno;         /* last logged errno value */
-extern char LogLastMsg[ 128 ];    /* last logged message     */
-
-void smclog( int Serverity, int Errno, const char *FmtSt, ... );
-
-/* udpsock.c
- */
-int openUdpSocket( uint32 PeerInAdr, uint16 PeerPort );
-
-static inline int IN6_MULTICAST(const struct in6_addr *addr)
-{
-  uint32_t * addr32p = (uint32_t *)addr->s6_addr;
-  return (*addr32p & htonl(0xFF000000)) == htonl(0xFF000000);
-}
-
-
+extern int log_stderr;		/* Log threshold for stderr, LOG_WARNING .... LOG_DEBUG */
+extern int log_last_severity;	/* last logged serverity   */
+extern int log_last_error;	/* last logged errno value */
+extern char log_last_message[128];	/* last logged message     */
 
+void smclog(int severity, int code, const char *fmt, ...);
 
+/* udpsock.c */
+int udp_socket_open(uint32 inaddr, uint16 port);
 
+#ifndef IN6_IS_ADDR_MULTICAST
+#define IN6_IS_ADDR_MULTICAST(a) (((__const uint8_t *) (a))[0] == 0xff)
+#endif
 
+/* parse-conf.c */
+#define SMCROUTE_SYSTEM_CONF "/etc/smcroute.conf"
 
+int parse_conf_file(const char *file);
 
+/* pidfile.c */
+int pidfile(const char *basename);
 
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/mcsender.c b/src/mcsender.c
index cafde24..325fe8b 100644
--- a/src/mcsender.c
+++ b/src/mcsender.c
@@ -33,7 +33,7 @@
 int do_debug_logging = 0;
 
 const char Usage[] = "mcsender [-t<n>] [-i<ifname>] <ip-address:port>\n";
-const char McMsg[] = "this is the test message from mclab/mcsender\n"; 
+const char McMsg[] = "this is the test message from mclab/mcsender\n";
 
 static void usage(void);
 
@@ -43,143 +43,195 @@ static void SetTtl4(int, unsigned);
 static void SetOif6(int, char *);
 static void SetTtl6(int, unsigned);
 
-int main( int ArgCn, char *ArgVc[] )
+static void getSockAdr(struct sockaddr *SaPt, socklen_t * SaLenPt, char *AddrSt, char *PortSt);
+
+int main(int ArgCn, char *ArgVc[])
 {
-  unsigned                TtlVal = 0;
-  char                  * OifVal = NULL;
-  char                  * AddrSt = NULL;
-  char                  * PortSt = NULL;
-  char                  * Pt;
-  void                    (*SetTtl)(int, unsigned) = NULL;
-  void                    (*SetOif)(int, char *)   = NULL;
-  struct sockaddr_storage TarAdr;
-  socklen_t               TarAdrLen;
-
-  if( ArgCn < 2 ) {
-    usage();
-    exit(1);
-  }
-
-  while( *++ArgVc ) {
-    Pt = *ArgVc;
-
-    /* option */
-    if( *Pt == '-' ) {
-      switch( *++Pt ) {
-
-      case 'D':
-        do_debug_logging = 1;
-        break;
-
-      case 't':
-	if( sscanf( Pt + 1, " %u", &TtlVal ) != 1 || TtlVal < 1 ) {
-	  usage();
-	  exit( 1 );
+	unsigned TtlVal = 0;
+	char *OifVal = NULL;
+	char *AddrSt = NULL;
+	char *PortSt = NULL;
+	char *Pt;
+	void (*SetTtl) (int, unsigned) = NULL;
+	void (*SetOif) (int, char *) = NULL;
+	struct sockaddr_storage TarAdr;
+	socklen_t TarAdrLen = 0;
+
+	if (ArgCn < 2) {
+		usage();
+		exit(1);
 	}
-	break;
 
-      case 'i':
-	OifVal = Pt + 1;
-	break;
+	while (*++ArgVc) {
+		Pt = *ArgVc;
+
+		/* option */
+		if (*Pt == '-') {
+			switch (*++Pt) {
+
+			case 'D':
+				do_debug_logging = 1;
+				break;
+
+			case 't':
+				if (sscanf(Pt + 1, " %u", &TtlVal) != 1 || TtlVal < 1) {
+					usage();
+					exit(1);
+				}
+				break;
 
-      default:
-	usage();
-	exit( 1 );
-      }
-    } else {  /* argument */
+			case 'i':
+				OifVal = Pt + 1;
+				break;
 
-      memset( &TarAdr, 0, sizeof( TarAdr ) );
+			default:
+				usage();
+				exit(1);
+			}
+		} else {	/* argument */
 
-      AddrSt = Pt;
+			memset(&TarAdr, 0, sizeof(TarAdr));
 
-      Pt = strrchr( AddrSt, ':' );
-      if ( Pt == NULL ) {
-	usage();
-	exit( 1 );
-      }
+			AddrSt = Pt;
 
-      *Pt++ = '\0';
-      PortSt = Pt;
+			Pt = strrchr(AddrSt, ':');
+			if (Pt == NULL) {
+				usage();
+				exit(1);
+			}
 
-      getSockAdr( SA( &TarAdr ), &TarAdrLen, AddrSt, PortSt );
+			*Pt++ = '\0';
+			PortSt = Pt;
 
-      SetTtl = ( TarAdr.ss_family == AF_INET ) ? SetTtl4 : SetTtl6;
-      SetOif = ( TarAdr.ss_family == AF_INET ) ? SetOif4 : SetOif6;
-    }
-  }
+			getSockAdr(SA(&TarAdr), &TarAdrLen, AddrSt, PortSt);
 
-  {
-    int UdpSock = socket( TarAdr.ss_family, SOCK_DGRAM, IPPROTO_UDP );
-    if ( UdpSock < 0 ) 
-      smclog( LOG_ERR, errno, "UDP socket open" );
+			SetTtl = (TarAdr.ss_family == AF_INET) ? SetTtl4 : SetTtl6;
+			SetOif = (TarAdr.ss_family == AF_INET) ? SetOif4 : SetOif6;
+		}
+	}
+
+	if (TarAdrLen)
+	{
+		int UdpSock = socket(TarAdr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
 
-    if (TtlVal) (*SetTtl)(UdpSock, TtlVal);
-    if (OifVal) (*SetOif)(UdpSock, OifVal);
+		if (UdpSock < 0)
+			smclog(LOG_ERR, errno, "UDP socket open");
 
-    while( 1 ) {
-      if( sendto( UdpSock, McMsg, sizeof( McMsg ), 0, 
-		  SA( &TarAdr ), TarAdrLen ) != sizeof( McMsg ) )
-	smclog( LOG_WARNING, errno, "send to UDP socket" );
+		if (TtlVal)
+			(*SetTtl) (UdpSock, TtlVal);
+		if (OifVal)
+			(*SetOif) (UdpSock, OifVal);
 
-      sleep( 1 );
-    }
-  }
+		while (1) {
+			if (sendto(UdpSock, McMsg, sizeof(McMsg), 0, SA(&TarAdr), TarAdrLen) != sizeof(McMsg))
+				smclog(LOG_WARNING, errno, "send to UDP socket");
+
+			sleep(1);
+		}
+	}
 
-  exit( 0 );
+	return 0;
 }
 
-static void usage( void )
+static void usage(void)
 {
-  fprintf( stderr, "Usage: %s\n", Usage );
+	fprintf(stderr, "Usage: %s\n", Usage);
 }
 
-static void SetTtl4( int Sock, unsigned Ttl )
+static void SetTtl4(int Sock, unsigned Ttl)
 {
-  if( setsockopt( Sock, IPPROTO_IP, IP_MULTICAST_TTL, 
-		  &Ttl, sizeof( Ttl ) ) )
-    smclog( LOG_ERR, errno, "set IP_MULTICAST_TTL" );
+	if (setsockopt(Sock, IPPROTO_IP, IP_MULTICAST_TTL, &Ttl, sizeof(Ttl)))
+		smclog(LOG_ERR, errno, "set IP_MULTICAST_TTL");
 }
 
-static void SetOif4( int Sock, char * IfName )
+static void SetOif4(int Sock, char *ifname)
 {
-  struct ifreq         IfReq;
-  struct sockaddr_in * Sin4  = NULL;
-
-  memset( &IfReq, 0, sizeof( IfReq ) );
-  strncpy( IfReq.ifr_name, IfName, sizeof( IfReq.ifr_name ) );
-
-  if ( ioctl( Sock, SIOCGIFADDR, &IfReq ) < 0 )
-    smclog( LOG_ERR, errno, "ioctl SIOCGIFADDR" );
-
-  switch ( IfReq.ifr_addr.sa_family ) {
-  case AF_INET:
-    Sin4 = SIN4( &IfReq.ifr_addr );
-    break;
-
-  default:
-    fprintf( stderr, "SetOif4 - invalid address family: %d\n", IfReq.ifr_addr.sa_family );
-    exit(1);
-  }
-  
-  if( setsockopt( Sock, IPPROTO_IP, IP_MULTICAST_IF, 
-		  &Sin4->sin_addr, sizeof( struct in_addr ) ) )
-    smclog( LOG_ERR, errno, "set IP_MULTICAST_IF" );  
+	struct ifreq IfReq;
+	struct sockaddr_in *Sin4 = NULL;
+
+	memset(&IfReq, 0, sizeof(IfReq));
+	strncpy(IfReq.ifr_name, ifname, sizeof(IfReq.ifr_name));
+
+	if (ioctl(Sock, SIOCGIFADDR, &IfReq) < 0)
+		smclog(LOG_ERR, errno, "ioctl SIOCGIFADDR");
+
+	switch (IfReq.ifr_addr.sa_family) {
+	case AF_INET:
+		Sin4 = SIN4(&IfReq.ifr_addr);
+		break;
+
+	default:
+		fprintf(stderr, "SetOif4 - invalid address family: %d\n",
+			IfReq.ifr_addr.sa_family);
+		exit(1);
+	}
+
+	if (setsockopt(Sock, IPPROTO_IP, IP_MULTICAST_IF,
+		       &Sin4->sin_addr, sizeof(struct in_addr)))
+		smclog(LOG_ERR, errno, "set IP_MULTICAST_IF");
 }
 
 static void SetTtl6(int Sock, unsigned Ttl)
 {
-  if( setsockopt( Sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, 
-		  &Ttl, sizeof( Ttl ) ) )
-    smclog( LOG_ERR, errno, "set IPV6_MULTICAST_HOPS" );
+	if (setsockopt(Sock, IPPROTO_IPV6, IPV6_MULTICAST_HOPS,
+		       &Ttl, sizeof(Ttl)))
+		smclog(LOG_ERR, errno, "set IPV6_MULTICAST_HOPS");
 }
 
-static void SetOif6(int Sock, char * IfName)
+static void SetOif6(int Sock, char *ifname)
 {
-  unsigned IfIndex;
+	unsigned ifindex;
 
-  IfIndex = if_nametoindex( IfName );
+	ifindex = if_nametoindex(ifname);
 
-  if( setsockopt( Sock, IPPROTO_IPV6, IPV6_MULTICAST_IF, 
-		  &IfIndex, sizeof( IfIndex ) ) )
-    smclog( LOG_ERR, errno, "set IPV6_MULTICAST_IF" );  
+	if (setsockopt(Sock, IPPROTO_IPV6, IPV6_MULTICAST_IF,
+		       &ifindex, sizeof(ifindex)))
+		smclog(LOG_ERR, errno, "set IPV6_MULTICAST_IF");
 }
+
+/*
+** Converts the internet address plus port string in 'St' 
+** into their network byte order representations.
+**
+** returns: - 0 -> conversion failed
+**          - 1 -> only address part returned (inaddrPt)
+**          - 2 -> address and port returned
+**          
+*/
+static void getSockAdr(struct sockaddr *SaPt, socklen_t * SaLenPt, char *AddrSt, char *PortSt)
+{
+	struct sockaddr_in *Sin4;
+	struct sockaddr_in6 *Sin6;
+
+	if (strchr(AddrSt, ':') == NULL) {
+		Sin4 = SIN4(SaPt);
+		memset(Sin4, 0, sizeof(*Sin4));
+
+		Sin4->sin_family = AF_INET;
+		Sin4->sin_port = htons(atoi(PortSt));
+
+		if (inet_pton(AF_INET, AddrSt, &Sin4->sin_addr) <= 0)
+			smclog(LOG_ERR, errno, "inet_pton failed for address %s", AddrSt);
+
+		*SaLenPt = sizeof(struct sockaddr_in);
+	} else {
+		Sin6 = SIN6(SaPt);
+		memset(Sin6, 0, sizeof(*Sin6));
+
+		Sin6->sin6_family = AF_INET6;
+		Sin6->sin6_port = htons(atoi(PortSt));
+
+		if (inet_pton(AF_INET6, AddrSt, &Sin6->sin6_addr) <= 0)
+			smclog(LOG_ERR, errno, "inet_pton failed for address %s", AddrSt);
+
+		*SaLenPt = sizeof(struct sockaddr_in6);
+	}
+}
+
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/mroute-api.c b/src/mroute-api.c
index 4333667..468a6d2 100644
--- a/src/mroute-api.c
+++ b/src/mroute-api.c
@@ -30,18 +30,18 @@
 #include "mclab.h"
 
 #ifdef HAVE_NETINET6_IP6_MROUTE_H
- #include <netinet6/ip6_mroute.h>
+#include <netinet6/ip6_mroute.h>
 #endif
 
 /* MAX_MC_VIFS from mclab.h must have same value as MAXVIFS from mroute.h */
 #if MAX_MC_VIFS != MAXVIFS
-# error "constants don't match, correct mclab.h"
+#error "constants don't match, correct mclab.h"
 #endif
 
 #ifdef HAVE_IPV6_MULTICAST_ROUTING
 /* MAX_MC_MIFS from mclab.h must have same value as MAXVIFS from mroute6.h */
 #if MAX_MC_MIFS != MAXMIFS
-# error "constants don't match, correct mclab.h"
+#error "constants don't match, correct mclab.h"
 #endif
 #endif
 
@@ -49,434 +49,582 @@
  * Need a raw IGMP socket as interface for the IPv4 mrouted API
  * Receives IGMP packets and kernel upcall messages.
  */
-int MRouterFD4;
+int mroute4_socket = -1;
+
+/* All user added/configured (*,G) routes that are matched on-demand
+ * at runtime. See the mroute4_dyn_list for the actual (S,G) routes
+ * set from this "template". */
+LIST_HEAD(, mroute4) mroute4_conf_list = LIST_HEAD_INITIALIZER();
+
+/* For dynamically/on-demand set (S,G) routes that we must track
+ * if the user removes the configured (*,G) route. */
+LIST_HEAD(, mroute4) mroute4_dyn_list = LIST_HEAD_INITIALIZER();
 
 #ifdef HAVE_IPV6_MULTICAST_ROUTING
 /*
  * Need a raw ICMPv6 socket as interface for the IPv6 mrouted API
  * Receives MLD packets and kernel upcall messages.
  */
-int MRouterFD6;
+int mroute6_socket = -1;
 #endif
 
 /* IPv4 internal virtual interfaces (VIF) descriptor vector */
-static struct VifDesc {
-  struct IfDesc *IfDp;
-} VifDescVc[ MAXVIFS ];
+static struct vif {
+	struct iface *iface;
+} vif_list[MAXVIFS];
+
+static void mroute4_add_vif(struct iface *iface);
 
 #ifdef HAVE_IPV6_MULTICAST_ROUTING
 /* IPv6 internal virtual interfaces (VIF) descriptor vector */
-static struct MifDesc {
-  struct IfDesc *IfDp;
-} MifDescVc[ MAXMIFS ];
-#endif
+static struct mif {
+	struct iface *iface;
+} mif_list[MAXMIFS];
 
-/********************************************************************
- * IPv4 
- *******************************************************************/
+static void mroute6_add_mif(struct iface *iface);
+#endif
 
-int enableMRouter4()
 /*
-** Initialises the mrouted API and locks it by this exclusively.
+** Initialise the mrouted API and locks the multicast routing
+** socket to this program (only!).
 **     
 ** returns: - 0 if the functions succeeds     
 **          - the errno value for non-fatal failure condition
 */
+int mroute4_enable(void)
 {
-  int Va = 1;
-
-  if( (MRouterFD4 = socket( AF_INET, SOCK_RAW, IPPROTO_IGMP )) < 0 ) {
-    int err = errno;
-    smclog( LOG_INIT, errno, "IGMP socket open" );
-    return err;
-  }
-  
-  if( setsockopt( MRouterFD4, IPPROTO_IP, MRT_INIT, 
-		  (void *)&Va, sizeof( Va ) ) ) {
-    int err = errno;
-    close( MRouterFD4 );
-    MRouterFD4 = -1;
-    return err;
-  }
-
-  /* Initialize virtual interface table */
-  memset(&VifDescVc, 0, sizeof(VifDescVc));
-
-  return 0;
+	int arg = 1;
+	unsigned int i;
+	struct iface *iface;
+
+	mroute4_socket = socket(AF_INET, SOCK_RAW, IPPROTO_IGMP);
+	if (mroute4_socket < 0) {
+		if (ENOPROTOOPT == errno)
+			smclog(LOG_WARNING, 0, "Kernel does not support IPv4 multicast routing, skipping...");
+
+		return -1;
+	}
+
+	if (setsockopt(mroute4_socket, IPPROTO_IP, MRT_INIT, (void *)&arg, sizeof(arg))) {
+		switch (errno) {
+		case EADDRINUSE:
+			smclog(LOG_INIT, errno, "IPv4 multicast routing API already in use");
+			break;
+
+#ifdef EOPNOTSUPP
+		case EOPNOTSUPP:
+			smclog(LOG_INIT, errno, "Unknown socket option MRT_INIT");
+			break;
+#endif
+
+		default:
+			smclog(LOG_INIT, errno, "Failed initializing IPv4 multicast routing API");
+			break;
+		}
+
+		close(mroute4_socket);
+		mroute4_socket = -1;
+
+		return -1;
+	}
+
+	/* Initialize virtual interface table */
+	memset(&vif_list, 0, sizeof(vif_list));
+
+	/* Create virtual interfaces, VIFs, for all non-loopback interfaces
+	 * that have a valid IPv4 address. */
+	for (i = 0; (iface = iface_find_by_index(i)); i++) {
+		if (iface->flags & IFF_LOOPBACK ||
+		    iface->inaddr.s_addr == INADDR_ANY) {
+			iface->vif = -1;
+			continue;
+		}
+		mroute4_add_vif(iface);
+	}
+
+	LIST_INIT(&mroute4_conf_list);
+	LIST_INIT(&mroute4_dyn_list);
+
+	return 0;
 }
 
-void disableMRouter4()
 /*
-** Diables the mrouted API and relases by this the lock.
-**          
+** Diable the mrouted API and relase the kernel lock.
 */
+void mroute4_disable(void)
 {
-  if( MRouterFD4 < 0 ) return;
-  if( setsockopt( MRouterFD4, IPPROTO_IP, MRT_DONE, NULL, 0 ) )
-    smclog( LOG_ERR, errno, "MRT_DONE" );
-  
-  close( MRouterFD4 );
-  MRouterFD4 = -1;
+	mroute4_t *entry;
+
+	if (mroute4_socket < 0)
+		return;
+
+	/* Drop all kernel routes set by smcroute */
+	if (setsockopt(mroute4_socket, IPPROTO_IP, MRT_DONE, NULL, 0))
+		smclog(LOG_ERR, errno, "MRT_DONE");
+
+	close(mroute4_socket);
+	mroute4_socket = -1;
+
+	/* Free list of (*,G) routes on SIGHUP */
+	while (!LIST_EMPTY(&mroute4_conf_list)) {
+		entry = LIST_FIRST(&mroute4_conf_list);
+		LIST_REMOVE(entry, link);
+		free(entry);
+	}
+	while (!LIST_EMPTY(&mroute4_dyn_list)) {
+		entry = LIST_FIRST(&mroute4_dyn_list);
+		LIST_REMOVE(entry, link);
+		free(entry);
+	}
 }
 
-void addVIF( struct IfDesc *IfDp )
+
 /*
-** Adds the interface '*IfDp' as virtual interface to the mrouted API
-** 
+** Adds the interface '*iface' as virtual interface to the mrouted API
 */
+static void mroute4_add_vif(struct iface *iface)
+{
+	struct vifctl vc;
+	int vif = -1;
+	char buf[16];
+	size_t i;
+
+	/* search free vif */
+	for (i = 0; i < ARRAY_ELEMENTS(vif_list); i++) {
+		if (!vif_list[i].iface) {
+			vif = i;
+			break;
+		}
+	}
+
+	/* no more space */
+	if (vif == -1) {
+		smclog(LOG_ERR, ENOMEM, "%s: out of VIF space", __FUNCTION__);
+		return;
+	}
+
+	memset(&vc, 0, sizeof(vc));
+	vc.vifc_vifi = vif;
+	vc.vifc_flags = 0;      /* no tunnel, no source routing, register ? */
+	vc.vifc_threshold = 1;  /* Packet TTL must be at least 1 to pass them */
+	vc.vifc_rate_limit = 0;	/* hopefully no limit */
+	vc.vifc_lcl_addr.s_addr = iface->inaddr.s_addr;
+	vc.vifc_rmt_addr.s_addr = INADDR_ANY;
+
+	smclog(LOG_NOTICE, 0, "Add VIF: %d Ifindex: %d Flags: 0x%04x IP: %s Ifname: %s",
+	       vc.vifc_vifi, iface->ifindex, vc.vifc_flags,
+	       inet_ntop (AF_INET, &vc.vifc_lcl_addr, buf, sizeof(buf)),
+	       iface->name);
+
+	if (setsockopt(mroute4_socket, IPPROTO_IP, MRT_ADD_VIF, (void *)&vc, sizeof(vc))) {
+		smclog(LOG_ERR, errno, "MRT_ADD_VIF %s", iface->name);
+	} else {
+		iface->vif = vif;
+		vif_list[vif].iface = iface;
+	}
+}
+
+/* Actually set in kernel - called by mroute4_add() and mroute4_check_add() */
+static int __mroute4_add (mroute4_t *ptr)
 {
-  struct vifctl VifCtl;
-  int VifIndex = -1;
-  int i;
-
-  /* search free VifDesc */
-  for (i=0; i < MAXVIFS; i++) {
-    if ( !VifDescVc[i].IfDp ) {
-      VifIndex = i;
-      break;
-    }
-  }
-    
-  /* no more space */
-  if( VifIndex == -1 ) {
-    smclog( LOG_ERR, ENOMEM, "addVIF, out of VIF space" );
-    return;
-  }
-
-  VifDescVc[VifIndex].IfDp = IfDp;
-
-  memset(&VifCtl, 0, sizeof(VifCtl));
-  VifCtl.vifc_vifi = VifIndex; 
-  VifCtl.vifc_flags = 0;        /* no tunnel, no source routing, register ? */
-  VifCtl.vifc_threshold = 1;    /* Packet TTL must be at least 1 to pass them */
-  VifCtl.vifc_rate_limit = 0;   /* hopefully no limit */
-  VifCtl.vifc_lcl_addr.s_addr = IfDp->InAdr.s_addr;
-  VifCtl.vifc_rmt_addr.s_addr = INADDR_ANY;
-
-  smclog( LOG_NOTICE, 0, "adding VIF, Vif-Ix %d Fl 0x%04x IP 0x%08x %s", 
-       VifCtl.vifc_vifi, VifCtl.vifc_flags,  VifCtl.vifc_lcl_addr.s_addr, IfDp->Name );
-
-  if( setsockopt( MRouterFD4, IPPROTO_IP, MRT_ADD_VIF, 
-		  (void *)&VifCtl, sizeof( VifCtl ) ) )
-    smclog( LOG_ERR, errno, "MRT_ADD_VIF %s", IfDp->Name );
-  else
-    IfDp->VifIndex = VifIndex;
+	int result = 0;
+	char origin[INET_ADDRSTRLEN], group[INET_ADDRSTRLEN];
+	struct mfcctl mc;
+
+	memset(&mc, 0, sizeof(mc));
+
+	mc.mfcc_origin = ptr->sender;
+	mc.mfcc_mcastgrp = ptr->group;
+	mc.mfcc_parent = ptr->inbound;
+
+	/* copy the TTL vector */
+	if (sizeof(mc.mfcc_ttls[0]) != sizeof(ptr->ttl[0]) || ARRAY_ELEMENTS(mc.mfcc_ttls) != ARRAY_ELEMENTS(ptr->ttl))
+		smclog(LOG_ERR, 0, "Data types does not match in %s, source adaption needed!", __FILE__);
+
+	memcpy(mc.mfcc_ttls, ptr->ttl, ARRAY_ELEMENTS(mc.mfcc_ttls) * sizeof(mc.mfcc_ttls[0]));
+
+	smclog(LOG_NOTICE, 0, "Add MFC: %s -> %s, inbound VIF: %d",
+	       inet_ntop(AF_INET, &mc.mfcc_origin,   origin, INET_ADDRSTRLEN),
+	       inet_ntop(AF_INET, &mc.mfcc_mcastgrp, group,  INET_ADDRSTRLEN), mc.mfcc_parent);
+
+	if (setsockopt(mroute4_socket, IPPROTO_IP, MRT_ADD_MFC, (void *)&mc, sizeof(mc))) {
+		result = errno;
+		smclog(LOG_WARNING, errno, "MRT_ADD_MFC");
+	}
+
+	return result;
+}
+
+/* Actually remove from kernel - called by mroute4_del() */
+static int __mroute4_del (mroute4_t *ptr)
+{
+	int result = 0;
+	char origin[INET_ADDRSTRLEN], group[INET_ADDRSTRLEN];
+	struct mfcctl mc;
+
+	memset(&mc, 0, sizeof(mc));
+	mc.mfcc_origin = ptr->sender;
+	mc.mfcc_mcastgrp = ptr->group;
+
+	smclog(LOG_NOTICE, 0, "Del MFC: %s -> %s",
+	       inet_ntop(AF_INET, &mc.mfcc_origin,  origin, INET_ADDRSTRLEN),
+	       inet_ntop(AF_INET, &mc.mfcc_mcastgrp, group, INET_ADDRSTRLEN));
+
+	if (setsockopt(mroute4_socket, IPPROTO_IP, MRT_DEL_MFC, (void *)&mc, sizeof(mc))) {
+		result = errno;
+		smclog(LOG_WARNING, errno, "MRT_DEL_MFC");
+	}
+
+	return result;
 }
 
-int addMRoute4( struct MRoute4Desc *Dp )
 /*
-** Adds the multicast routed '*Dp' to the kernel routes
+** Add mcroute to kernel if it matches a known (*,G) route.
 **
 ** returns: - 0 if the function succeeds
 **          - the errno value for non-fatal failure condition
 */
+int mroute4_dyn_add(mroute4_t *ptr)
 {
-  struct mfcctl CtlReq;
-  int ret = 0;
-  
-  memset(&CtlReq, 0, sizeof(CtlReq));
-
-  CtlReq.mfcc_origin    = Dp->OriginAdr;
-  CtlReq.mfcc_mcastgrp  = Dp->McAdr;
-  CtlReq.mfcc_parent    = Dp->InVif;
-
-  /* copy the TTL vector
-   */
-  if(    sizeof( CtlReq.mfcc_ttls ) != sizeof( Dp->TtlVc ) 
-      || VCMC( CtlReq.mfcc_ttls ) != VCMC( Dp->TtlVc ) )
-    smclog( LOG_ERR, 0, "data types doesn't match in " __FILE__ ", source adaption needed !" );
-
-  memcpy( CtlReq.mfcc_ttls, Dp->TtlVc, sizeof( CtlReq.mfcc_ttls ) );
-
-  {
-    char FmtBuO[ INET_ADDRSTRLEN ], FmtBuM[ INET_ADDRSTRLEN ];
-
-    smclog( LOG_NOTICE, 0, "adding MFC: %s -> %s, InpVIf: %d", 
-	    inet_ntop( AF_INET, &CtlReq.mfcc_origin,   FmtBuO, INET_ADDRSTRLEN ), 
-	    inet_ntop( AF_INET, &CtlReq.mfcc_mcastgrp, FmtBuM, INET_ADDRSTRLEN ), 
-	    CtlReq.mfcc_parent
-	    );
-  }
-
-  if( setsockopt( MRouterFD4, IPPROTO_IP, MRT_ADD_MFC,
-		  (void *)&CtlReq, sizeof( CtlReq ) ) ) {
-    ret = errno;
-    smclog( LOG_WARNING, errno, "MRT_ADD_MFC" );
-  }
-
-  return ret;
+	mroute4_t *entry;
+
+	LIST_FOREACH(entry, &mroute4_conf_list, link) {
+		/* Find matching (*,G) ... and interface. */
+		if (!memcmp (&entry->group, &ptr->group, sizeof(entry->group)) && entry->inbound == ptr->inbound) {
+			smclog(LOG_DEBUG, 0, "Found (*,G) match for (0x%x, 0x%x)!", ptr->sender.s_addr, ptr->group.s_addr);
+
+			/* Use configured template (*,G) outbound interfaces. */
+			memcpy(ptr->ttl, entry->ttl, ARRAY_ELEMENTS(ptr->ttl) * sizeof(ptr->ttl[0]));
+
+			/* Add to list of dynamically added routes. Necessary if the user
+			 * removes the (*,G) using the command line interface rather than
+			 * updating the conf file and SIGHUP. Note: if we fail to alloc()
+			 * memory we don't do anything, just add kernel route silently. */
+			entry = malloc(sizeof(mroute4_t));
+			if (entry) {
+				memcpy(entry, ptr, sizeof(mroute4_t));
+				LIST_INSERT_HEAD(&mroute4_dyn_list, entry, link);
+			}
+
+			return __mroute4_add(ptr);
+		}
+	}
+
+	smclog(LOG_DEBUG, 0, "No (*,G) match for (0x%x, 0x%x)!", ptr->sender.s_addr, ptr->group.s_addr);
+
+	errno = ENOENT;
+	return -1;
 }
 
-int delMRoute4( struct MRoute4Desc *Dp )
 /*
-** Removes the multicast routed '*Dp' from the kernel routes
+** Adds the multicast route '*ptr' to the kernel multicast routing table
+** unless the source IP is INADDR_ANY, i.e., a (*,G) route. Those we save
+** for later and check against at runtime when the kernel signals us.
 **
 ** returns: - 0 if the function succeeds
 **          - the errno value for non-fatal failure condition
 */
+int mroute4_add(mroute4_t *ptr)
 {
-  struct mfcctl CtlReq;
-  int ret = 0;
-  
-  memset(&CtlReq, 0, sizeof(CtlReq));
-
-  CtlReq.mfcc_origin   = Dp->OriginAdr;
-  CtlReq.mfcc_mcastgrp = Dp->McAdr;
-
-  {
-    char FmtBuO[ INET_ADDRSTRLEN ], FmtBuM[ INET_ADDRSTRLEN ];
-
-    smclog( LOG_NOTICE, 0, "removing MFC: %s -> %s", 
-	    inet_ntop( AF_INET, &CtlReq.mfcc_origin,   FmtBuO, INET_ADDRSTRLEN ), 
-	    inet_ntop( AF_INET, &CtlReq.mfcc_mcastgrp, FmtBuM, INET_ADDRSTRLEN )
-	    );
-  }
-
-  if( setsockopt( MRouterFD4, IPPROTO_IP, MRT_DEL_MFC,
-		  (void *)&CtlReq, sizeof( CtlReq ) ) ) {
-      ret = errno;
-      smclog( LOG_WARNING, errno, "MRT_DEL_MFC" );
-  }
-
-  return ret;
+	/* For (*,G) we save to a linked list to be added on-demand
+	 * when the kernel sends IGMPMSG_NOCACHE. */
+	if (ptr->sender.s_addr == INADDR_ANY) {
+		mroute4_t *entry = malloc(sizeof(mroute4_t));
+
+		if (!entry) {
+			smclog(LOG_WARNING, errno, "Failed allocating (*,G) entry to linked list");
+			return errno;
+		}
+
+		memcpy(entry, ptr, sizeof(mroute4_t));
+		smclog(LOG_DEBUG, 0, "Adding (*,G) mroute to dynamic list => (0x%x, 0x%x) vif:%d ",
+		       ptr->sender.s_addr, ptr->group.s_addr, ptr->inbound);
+		LIST_INSERT_HEAD(&mroute4_conf_list, entry, link);
+
+		return 0;
+	}
+
+	return __mroute4_add (ptr);
 }
 
-int getVifIx( struct IfDesc *IfDp )
 /*
-** Returns for the virtual interface index for '*IfDp'
+** Removes the multicast routed '*ptr' from the kernel routes
 **
-** returns: - the virtual interface index if the interface is registered
-**          - -1 if no virtual interface exists for the interface 
-**          
+** returns: - 0 if the function succeeds
+**          - the errno value for non-fatal failure condition
 */
+int mroute4_del(mroute4_t *ptr)
 {
-  if (IfDp == NULL) return -1;
-  return IfDp->VifIndex;
+	/* For (*,G) we have saved all dynamically added kernel routes
+	 * to a linked list which we need to traverse again and remove
+	 * all matches. From kernel dyn list before we remove the conf
+	 * entry. */
+	if (ptr->sender.s_addr == INADDR_ANY) {
+		mroute4_t *entry;
+
+		if (LIST_EMPTY(&mroute4_conf_list))
+			return 0;
+
+		entry = LIST_FIRST(&mroute4_conf_list);
+		while (entry) {
+			smclog(LOG_DEBUG, 0, "%s:%d:%s:looping over entry at 0x%x", __FILE__, __LINE__, __func__, entry);
+			/* Find matching (*,G) ... and interface. */
+			if (!memcmp (&entry->group, &ptr->group, sizeof(entry->group)) && entry->inbound == ptr->inbound) {
+				mroute4_t *set;
+
+				smclog(LOG_DEBUG, 0, "Found (*,G) match for (0x%x, 0x%x) - now find any set routes!", ptr->sender.s_addr, ptr->group.s_addr);
+				if (LIST_EMPTY(&mroute4_dyn_list)) {
+					entry = LIST_NEXT(entry, link);
+					continue;
+				}
+
+				set = LIST_FIRST(&mroute4_dyn_list);
+				while (set) {
+					if (!memcmp (&entry->group, &set->group, sizeof(entry->group)) && entry->inbound == set->inbound) {
+						smclog(LOG_DEBUG, 0, "Found match (0x%x, 0x%x) - removing, unlinking and freeing.", set->sender.s_addr, set->group.s_addr);
+						__mroute4_del(set);
+						LIST_REMOVE(set, link);
+						free(set);
+						set = LIST_FIRST(&mroute4_dyn_list);
+					} else set = LIST_NEXT(set, link);
+				}
+
+				LIST_REMOVE(entry, link);
+				free(entry);
+				entry = LIST_FIRST(&mroute4_conf_list);
+			} else entry = LIST_NEXT(entry, link);
+		}
+	} else
+		return __mroute4_del(ptr);
 }
 
 
-/********************************************************************
- * IPv6 
- *******************************************************************/
+#ifdef HAVE_IPV6_MULTICAST_ROUTING
+#define IPV6_ALL_MC_FORWARD "/proc/sys/net/ipv6/conf/all/mc_forwarding"
+
+static int proc_set_val(char *file, int val)
+{
+	int fd;
+
+	fd = open(file, O_WRONLY);
+	if (fd < 0) {
+		return 1;
+	} else {
+		if (-1 == write(fd, "1", val)) {
+			(void)close(fd);
+			return 1;
+		}
+		(void)close(fd);
+	}
+
+	return 0;
+}
+#endif /* HAVE_IPV6_MULTICAST_ROUTING */
 
-int enableMRouter6()
 /*
 ** Initialises the mrouted API and locks it by this exclusively.
 **     
 ** returns: - 0 if the functions succeeds     
 **          - the errno value for non-fatal failure condition
 */
+int mroute6_enable(void)
 {
 #ifndef HAVE_IPV6_MULTICAST_ROUTING
-  return 0;
+	return -1;
 #else
-  int Va = 1;
-
-  if( (MRouterFD6 = socket( AF_INET6, SOCK_RAW, IPPROTO_ICMPV6 )) < 0 ) {
-    int err = errno;
-    smclog( LOG_INIT, errno, "ICMPv6 socket open" );
-    return err;
-  }
-  
-  if( setsockopt( MRouterFD6, IPPROTO_IPV6, MRT6_INIT, 
-		  (void *)&Va, sizeof( Va ) ) ) {
-    int err = errno;
-    close( MRouterFD6 );
-    MRouterFD6 = -1;
-    return err;
-  }
-
-  /* 
-   * On Linux pre 2.6.29 kernels net.ipv6.conf.all.mc_forwarding
-   * is not set on MRT6_INIT so we have to do this manually
-   */
-  {
-    int    fd;
-    char * file = "/proc/sys/net/ipv6/conf/all/mc_forwarding";
-    
-    fd = open( file, O_WRONLY );
-    if ( fd < 0 ) {
-      if ( errno != EACCES )
-        smclog( LOG_ERR, errno, "open(%s)", file);  
-    } else {
-      (void) write( fd, "1", 1 );
-      (void) close( fd );
-    }
-  }
-  return 0;
+	int arg = 1;
+	unsigned int i;
+	struct iface *iface;
+
+	if ((mroute6_socket = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6)) < 0) {
+		if (ENOPROTOOPT == errno)
+			smclog(LOG_WARNING, 0, "Kernel does not support IPv6 multicast routing, skipping...");
+
+		return -1;
+	}
+	if (setsockopt(mroute6_socket, IPPROTO_IPV6, MRT6_INIT, (void *)&arg, sizeof(arg))) {
+		switch (errno) {
+		case EADDRINUSE:
+			smclog(LOG_INIT, errno, "IPv6 multicast routing API already in use");
+			break;
+
+#ifdef EOPNOTSUPP
+		case EOPNOTSUPP:
+			smclog(LOG_INIT, errno, "Unknown socket option MRT6_INIT");
+			break;
+#endif
+
+		default:
+			smclog(LOG_INIT, errno, "Failed initializing IPv6 multicast routing API");
+			break;
+		}
+
+		close(mroute6_socket);
+		mroute6_socket = -1;
+
+		return -1;
+	}
+
+	/* Initialize virtual interface table */
+	memset(&mif_list, 0, sizeof(mif_list));
+
+	/* On Linux pre 2.6.29 kernels net.ipv6.conf.all.mc_forwarding
+	 * is not set on MRT6_INIT so we have to do this manually */
+	if (proc_set_val(IPV6_ALL_MC_FORWARD, 1)) {
+		if (errno != EACCES)
+			smclog(LOG_ERR, errno, "Failed enabling IPv6 mc_forwarding");
+	}
+
+	/* create MIFs for all IP, non-loop interfaces */
+	for (i = 0; (iface = iface_find_by_index(i)); i++) {
+		if (iface->flags & IFF_LOOPBACK) {
+			iface->vif = -1;
+			continue;
+		}
+		mroute6_add_mif(iface);
+	}
+
+	return 0;
 #endif /* HAVE_IPV6_MULTICAST_ROUTING */
 }
 
-void disableMRouter6()
 /*
 ** Diables the mrouted API and relases by this the lock.
 **          
 */
+void mroute6_disable(void)
 {
-#ifndef HAVE_IPV6_MULTICAST_ROUTING
-  return;
-#else
-  if( MRouterFD6 < 0 ) return;
-  if( setsockopt( MRouterFD6, IPPROTO_IPV6, MRT6_DONE, NULL, 0 ) )
-    smclog( LOG_ERR, errno, "MRT6_DONE" );
-  
-  close( MRouterFD6 );
-  MRouterFD6 = -1;
+#ifdef HAVE_IPV6_MULTICAST_ROUTING
+	if (mroute6_socket < 0)
+		return;
+
+	if (setsockopt(mroute6_socket, IPPROTO_IPV6, MRT6_DONE, NULL, 0))
+		smclog(LOG_ERR, errno, "MRT6_DONE");
+
+	close(mroute6_socket);
+	mroute6_socket = -1;
 #endif /* HAVE_IPV6_MULTICAST_ROUTING */
 }
 
-void addMIF( struct IfDesc *IfDp )
+#ifdef HAVE_IPV6_MULTICAST_ROUTING
 /*
-** Adds the interface '*IfDp' as virtual interface to the mrouted API
-** 
+** Adds the interface '*iface' as virtual interface to the mrouted API
 */
+static void mroute6_add_mif(struct iface *iface)
 {
-#ifndef HAVE_IPV6_MULTICAST_ROUTING
-  return;
-#else
-  struct mif6ctl MifCtl;
-  struct MifDesc *MifDp;
-
-  memset(&MifCtl, 0, sizeof(MifCtl));
-
-  /* search free MifDesc
-   */
-  for( MifDp = MifDescVc; MifDp < VCEP( MifDescVc ); MifDp++ ) {
-    if( ! MifDp->IfDp )
-      break;
-  }
-    
-  /* no more space
-   */
-  if( MifDp >= VCEP( MifDescVc ) )
-    smclog( LOG_ERR, ENOMEM, "addMIF, out of MIF space" );
-
-  MifDp->IfDp = IfDp;
-
-  MifCtl.mif6c_mifi      = MifDp - MifDescVc; 
-  MifCtl.mif6c_flags     = 0;             /* no register */
+	struct mif6ctl mc;
+	int mif = -1;
+	size_t i;
+
+	/* find a free mif */
+	for (i = 0; i < ARRAY_ELEMENTS(mif_list); i++) {
+		if (!mif_list[i].iface) {
+			mif = i;
+			break;
+		}
+	}
+
+	/* no more space */
+	if (mif == -1) {
+		smclog(LOG_ERR, ENOMEM, "%s: out of MIF space", __FUNCTION__);
+		return;
+	}
+
+	memset(&mc, 0, sizeof(mc));
+	mc.mif6c_mifi = mif;
+	mc.mif6c_flags = 0;	/* no register */
 #ifdef HAVE_MIF6CTL_VIFC_THRESHOLD
-  MifCtl.vifc_threshold  = 1;             /* Packet TTL must be at least 1 to pass them */
+	mc.vifc_threshold = 1;	/* Packet TTL must be at least 1 to pass them */
 #endif
-  MifCtl.mif6c_pifi      = IfDp->IfIndex; /* physical interface index */
+	mc.mif6c_pifi = iface->ifindex;	/* physical interface index */
 #ifdef HAVE_MIF6CTL_VIFC_RATE_LIMIT
-  MifCtl.vifc_rate_limit = 0;             /* hopefully no limit */
+	mc.vifc_rate_limit = 0;	/* hopefully no limit */
 #endif
 
-  smclog( LOG_NOTICE, 0, "adding MIF, Mif-Ix %d PHY Ix %d Fl 0x%x %s", 
-	  MifCtl.mif6c_mifi, MifCtl.mif6c_pifi, MifCtl.mif6c_flags, MifDp->IfDp->Name );
+	smclog(LOG_NOTICE, 0, "Add MIF: %d Ifindex: %d Flags: 0x%04x Ifname: %s",
+	       mc.mif6c_mifi, mc.mif6c_pifi, mc.mif6c_flags, iface->name);
 
-  if( setsockopt( MRouterFD6, IPPROTO_IPV6, MRT6_ADD_MIF, 
-		  (char *)&MifCtl, sizeof( MifCtl ) ) )
-    smclog( LOG_ERR, errno, "MRT6_ADD_MIF %s", IfDp->Name );
-#endif /* HAVE_IPV6_MULTICAST_ROUTING */
+	if (setsockopt(mroute6_socket, IPPROTO_IPV6, MRT6_ADD_MIF, (void *)&mc, sizeof(mc))) {
+		smclog(LOG_ERR, errno, "MRT6_ADD_MIF %s", iface->name);
+	} else {
+		iface->mif = mif;
+		mif_list[mif].iface = iface;
+	}
 }
 
-int addMRoute6( struct MRoute6Desc *Dp )
 /*
-** Adds the multicast routed '*Dp' to the kernel routes
+** Adds the multicast routed '*ptr' to the kernel routes
 **
 ** returns: - 0 if the function succeeds
 **          - the errno value for non-fatal failure condition
 */
+int mroute6_add(mroute6_t *ptr)
 {
-#ifndef HAVE_IPV6_MULTICAST_ROUTING
-  return 0;
-#else
-  struct mf6cctl CtlReq;
-  int            ret   = 0;
-  int            MifIx = 0;
-
-  memset(&CtlReq, 0, sizeof(CtlReq));
-
-  CtlReq.mf6cc_origin    = Dp->OriginAdr;
-  CtlReq.mf6cc_mcastgrp  = Dp->McAdr;
-  CtlReq.mf6cc_parent    = Dp->InMif;
-
-  /* copy the outgoing MIFs
-   */
-  for ( MifIx = 0; MifIx < MAX_MC_MIFS; MifIx++ ) {
-    if ( Dp->TtlVc[ MifIx ] > 0 )
-      IF_SET( MifIx, &CtlReq.mf6cc_ifset );
-  }
-
-  {
-    char FmtBuO[ INET6_ADDRSTRLEN ], FmtBuM[ INET6_ADDRSTRLEN ];
-
-    smclog( LOG_NOTICE, 0, "adding MFC: %s -> %s, InpMIf: %d", 
-	    inet_ntop( AF_INET6, &CtlReq.mf6cc_origin.sin6_addr,   FmtBuO, INET6_ADDRSTRLEN ), 
-	    inet_ntop( AF_INET6, &CtlReq.mf6cc_mcastgrp.sin6_addr, FmtBuM, INET6_ADDRSTRLEN ), 
-	    CtlReq.mf6cc_parent
-	    );
-  }
-
-  if( setsockopt( MRouterFD6, IPPROTO_IPV6, MRT6_ADD_MFC,
-		  (void *)&CtlReq, sizeof( CtlReq ) ) ) {
-    ret = errno;
-    smclog( LOG_WARNING, errno, "MRT6_ADD_MFC" );
-  }
-
-  return ret;
-#endif /* HAVE_IPV6_MULTICAST_ROUTING */
+	int result = 0;
+	size_t i;
+	char origin[INET6_ADDRSTRLEN], group[INET6_ADDRSTRLEN];
+	struct mf6cctl mc;
+
+	memset(&mc, 0, sizeof(mc));
+	mc.mf6cc_origin   = ptr->sender;
+	mc.mf6cc_mcastgrp = ptr->group;
+	mc.mf6cc_parent   = ptr->inbound;
+
+	/* copy the outgoing MIFs */
+	for (i = 0; i < ARRAY_ELEMENTS(ptr->ttl); i++) {
+		if (ptr->ttl[i] > 0)
+			IF_SET(i, &mc.mf6cc_ifset);
+	}
+
+	smclog(LOG_NOTICE, 0, "Add MFC: %s -> %s, Inbound MIF: %d",
+	       inet_ntop(AF_INET6, &mc.mf6cc_origin.sin6_addr,
+			 origin, INET6_ADDRSTRLEN),
+	       inet_ntop(AF_INET6, &mc.mf6cc_mcastgrp.sin6_addr,
+			 group, INET6_ADDRSTRLEN), mc.mf6cc_parent);
+
+	if (setsockopt(mroute6_socket, IPPROTO_IPV6, MRT6_ADD_MFC, (void *)&mc, sizeof(mc))) {
+		result = errno;
+		smclog(LOG_WARNING, errno, "MRT6_ADD_MFC");
+	}
+
+	return result;
 }
 
-int delMRoute6( struct MRoute6Desc *Dp )
 /*
-** Removes the multicast routed '*Dp' from the kernel routes
+** Removes the multicast routed '*ptr' from the kernel routes
 **
 ** returns: - 0 if the function succeeds
 **          - the errno value for non-fatal failure condition
 */
+int mroute6_del(mroute6_t *ptr)
 {
-#ifndef HAVE_IPV6_MULTICAST_ROUTING
-  return 0;
-#else
-  struct mf6cctl CtlReq;
-  int ret = 0;
-  
-  memset(&CtlReq, 0, sizeof(CtlReq));
-
-  CtlReq.mf6cc_origin   = Dp->OriginAdr;
-  CtlReq.mf6cc_mcastgrp = Dp->McAdr;
-
-  {
-    char FmtBuO[ INET_ADDRSTRLEN ], FmtBuM[ INET_ADDRSTRLEN ];
-
-    smclog( LOG_NOTICE, 0, "removing MFC: %s -> %s", 
-	    inet_ntop( AF_INET6, &CtlReq.mf6cc_origin.sin6_addr,   FmtBuO, INET6_ADDRSTRLEN ), 
-	    inet_ntop( AF_INET6, &CtlReq.mf6cc_mcastgrp.sin6_addr, FmtBuM, INET6_ADDRSTRLEN )
-	    );
-  }
-
-  if( setsockopt( MRouterFD6, IPPROTO_IPV6, MRT6_DEL_MFC,
-		  (void *)&CtlReq, sizeof( CtlReq ) ) ) {
-    ret = errno;
-    smclog( LOG_WARNING, errno, "MRT_DEL_MFC" );
-  }
-
-  return ret;
-#endif /* HAVE_IPV6_MULTICAST_ROUTING */
+	int result = 0;
+	char origin[INET_ADDRSTRLEN], group[INET_ADDRSTRLEN];
+	struct mf6cctl mc;
+
+	memset(&mc, 0, sizeof(mc));
+	mc.mf6cc_origin = ptr->sender;
+	mc.mf6cc_mcastgrp = ptr->group;
+
+	smclog(LOG_NOTICE, 0, "Del MFC: %s -> %s",
+	       inet_ntop(AF_INET6, &mc.mf6cc_origin.sin6_addr,
+			 origin, INET6_ADDRSTRLEN),
+	       inet_ntop(AF_INET6, &mc.mf6cc_mcastgrp.sin6_addr,
+			 group, INET6_ADDRSTRLEN));
+
+	if (setsockopt(mroute6_socket, IPPROTO_IPV6, MRT6_DEL_MFC, (void *)&mc, sizeof(mc))) {
+		result = errno;
+		smclog(LOG_WARNING, errno, "MRT_DEL_MFC");
+	}
+
+	return result;
 }
-
-int getMifIx( struct IfDesc *IfDp )
-/*
-** Returns for the virtual interface index for '*IfDp'
-**
-** returns: - the virtual interface index if the interface is registered
-**          - -1 if no virtual interface exists for the interface 
-**          
-*/
-{
-#ifndef HAVE_IPV6_MULTICAST_ROUTING
-  return -1;
-#else
-  struct MifDesc *Dp;
-
-  for( Dp = MifDescVc; Dp < VCEP( MifDescVc ); Dp++ ) 
-    if( Dp->IfDp == IfDp )
-      return Dp - MifDescVc;
-
-  return -1;
 #endif /* HAVE_IPV6_MULTICAST_ROUTING */
-}
 
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/parse-conf.c b/src/parse-conf.c
new file mode 100644
index 0000000..ffb40fb
--- /dev/null
+++ b/src/parse-conf.c
@@ -0,0 +1,321 @@
+/* Simple .conf file parser for smcroute
+ *
+ * Copyright (c) 2011  Joachim Nilsson <troglobit@gmail.com>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include <ctype.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#ifndef UNITTEST
+#include "mclab.h"
+#endif
+
+#define MAX_LINE_LEN 512
+
+static char *pop_token(char **line)
+{
+	char *end, *token = *line;
+
+	if (!line || !token)
+		return NULL;
+
+	/* Find start of token, skip whitespace. */
+	while (*token && isspace(*token))
+		token++;
+
+	/* Find end of token. */
+	end = token;
+	while (*end && !isspace(*end))
+		end++;
+	if (*end == 0 || end == token)
+	{
+		*line = NULL;
+		return NULL;
+	}
+
+	*end = 0;		/* Terminate token. */
+	*line = end + 1;
+
+	return token;
+}
+
+static int match(char *keyword, char *token)
+{
+	size_t len;
+
+	if (!keyword || !token)
+		return 0;
+
+	len = strlen(keyword);
+	return !strncmp(keyword, token, len);
+}
+
+static int join_mgroup (int lineno, char *ifname, char *group)
+{
+	int result;
+
+	if (!ifname || !group) {
+		errno = EINVAL;
+		return 1;
+	}
+
+	if (strchr(group, ':')) {
+#if !defined(HAVE_IPV6_MULTICAST_HOST) || !defined(HAVE_IPV6_MULTICAST_ROUTING)
+		smclog(LOG_WARNING, 0, "Line %02: Sadly this build of smcroute does not support IPv6.", lineno);
+		result = 0;
+#else
+		struct in6_addr grp;
+
+		if (inet_pton(AF_INET6, group, &grp) <= 0 || !IN6_IS_ADDR_MULTICAST(&grp)) {
+			smclog(LOG_WARNING, 0, "Line %02d: invalid IPv6 multicast group address: %s", lineno, group);
+			return 1;
+		}
+
+		result = mcgroup6_join(ifname, grp);
+#endif
+	} else {
+		struct in_addr grp;
+
+		if ((inet_pton(AF_INET, group, &grp) <= 0) || !IN_MULTICAST(ntohl(grp.s_addr))) {
+			smclog(LOG_WARNING, 0, "Line %02d: invalid IPv4 multicast group address: %s", lineno, group);
+			return 1;
+		}
+
+		result = mcgroup4_join(ifname, grp);
+	}
+
+	return result;
+}
+
+static int add_mroute (int lineno, char *ifname, char *group, char *source, char *outbound[], int num)
+{
+	int i, total, result;
+
+	if (!ifname || !group || !outbound || !num) {
+		errno = EINVAL;
+		return 1;
+	}
+
+	if (strchr(group, ':')) {
+#if !defined(HAVE_IPV6_MULTICAST_HOST) || !defined(HAVE_IPV6_MULTICAST_ROUTING)
+		smclog(LOG_WARNING, 0, "Line %02: Sadly this build of smcroute does not support IPv6.", lineno);
+		result = 0;
+#else
+		mroute6_t mroute;
+
+		mroute.inbound = iface_get_mif_by_name(ifname);
+		if (mroute.inbound < 0) {
+			smclog(LOG_WARNING, 0, "Line %02d: Invalid inbound IPv6 interface: %s", lineno, ifname);
+			return 1;
+		}
+		if (!source || inet_pton(AF_INET6, source, &mroute.sender) <= 0) {
+			smclog(LOG_WARNING, 0, "Line %02d: Invalid source IPv6 address: %s", lineno, source ?: "NONE");
+			return 1;
+		}
+
+		if (inet_pton(AF_INET6, group, &mroute.group) <= 0 || !IN6_IS_ADDR_MULTICAST(&mroute.group)) {
+			smclog(LOG_WARNING, 0, "Line %02d: Invalid IPv6 multicast group: %s", lineno, group);
+			return 1;
+		}
+
+		total = num;
+		for (i = 0; i < num; i++) {
+			int mif = iface_get_mif_by_name(outbound[i]);
+
+			if (mif < 0) {
+				total--;
+				smclog(LOG_WARNING, 0, "Line %02d: Invalid outbound IPv6 interface: %s", lineno, outbound[i]);
+				continue; /* Try next, if any. */
+			}
+
+			if (mif == mroute.inbound)
+				smclog(LOG_WARNING, 0, "Line %02d: Same outbound IPv6 interface (%s) as inbound (%s)?", lineno, outbound[i], ifname);
+
+			mroute.ttl[mif] = 1;	/* Use a TTL threshold to indicate the list of outbound interfaces. */
+		}
+
+		if (!total) {
+			smclog(LOG_WARNING, 0, "Line %02d: No valid outbound interfaces, skipping mroute rule.", lineno);
+			result = 1;
+		} else {
+			result = mroute6_add(&mroute);
+		}
+#endif
+	} else {
+		struct mroute4 mroute;
+
+		memset(&mroute, 0, sizeof(mroute));
+		mroute.inbound = iface_get_vif_by_name(ifname);
+		if (mroute.inbound < 0) {
+			smclog(LOG_WARNING, 0, "Line %02d: Invalid inbound IPv4 interface: %s", lineno, ifname);
+			return 1;
+		}
+
+		if (!source) {
+			mroute.sender.s_addr = INADDR_ANY;
+		} else if (inet_pton(AF_INET, source, &mroute.sender) <= 0) {
+			smclog(LOG_WARNING, 0, "Line %02d: Invalid source IPv4 address: %s", lineno, source);
+			return 1;
+		}
+
+		if ((inet_pton(AF_INET, group, &mroute.group) <= 0) || !IN_MULTICAST(ntohl(mroute.group.s_addr))) {
+			smclog(LOG_WARNING, 0, "Line %02d: Invalid IPv4 multicast group: %s", lineno, group);
+			return 1;
+		}
+
+		total = num;
+		for (i = 0; i < num; i++) {
+			int vif = iface_get_vif_by_name(outbound[i]);
+
+			if (vif < 0) {
+				total--;
+				smclog(LOG_WARNING, 0, "Line %02d: Invalid outbound IPv4 interface: %s", lineno, outbound[i]);
+				continue; /* Try next, if any. */
+			}
+
+			if (vif == mroute.inbound)
+				smclog(LOG_WARNING, 0, "Line %02d: Same outbound IPv4 interface (%s) as inbound (%s)?", lineno, outbound[i], ifname);
+
+			mroute.ttl[vif] = 1;	/* Use a TTL threshold to indicate the list of outbound interfaces. */
+		}
+
+		if (!total) {
+			smclog(LOG_WARNING, 0, "Line %02d: No valid outbound IPv4 interfaces, skipping mroute rule.", lineno);
+			result = 1;
+		} else {
+			result = mroute4_add(&mroute);
+		}
+	}
+
+	return result;
+}
+
+/* Format:
+ *    mgroup from IFNAME group MCGROUP
+ *    mroute from IFNAME source ADDRESS group MCGROUP to IFNAME [IFNAME ...]
+ */
+int parse_conf_file(const char *file)
+{
+	int lineno = 1;
+	char *linebuf, *line;
+	FILE *fp = fopen(file, "r");
+
+	if (!fp)
+		return 1;
+
+	linebuf = malloc(MAX_LINE_LEN * sizeof(char));
+	if (!linebuf) {
+		int tmp = errno;
+
+		fclose(fp);
+		errno = tmp;
+
+		return 1;
+	}
+
+	while ((line = fgets(linebuf, MAX_LINE_LEN, fp))) {
+		char *token;
+		char *ifname = NULL;
+		char *source = NULL;
+		char *group  = NULL;
+		int   op = 0, num = 0;
+		char *dest[32];
+
+		while ((token = pop_token(&line))) {
+			/* Strip comments. */
+			if (match ("#", token)) {
+#ifdef UNITTEST
+				printf("%02d: COMMENT: %s", lineno, line);
+#endif
+				break;
+			}
+
+			if (!op) {
+				if (match ("mgroup", token)) {
+					op = 1;
+				} else if (match ("mroute", token)) {
+					op = 2;
+				} else {
+#ifdef UNITTEST
+					printf("%02d: Unknonw command: %s", lineno, line);
+#else
+					smclog(LOG_WARNING, 0, "%02d: Unknown command %s, skipping.", lineno, token);
+#endif
+					continue;
+				}
+			}
+
+			if (match("from", token)) {
+				ifname = pop_token(&line);
+			} else if (match("source", token)) {
+				source = pop_token(&line);
+			} else if (match("group", token)) {
+				group = pop_token(&line);
+			} else if (match("to", token)) {
+				while ((dest[num] = pop_token(&line)))
+					num++;
+			}
+		}
+
+#ifdef UNITTEST
+		if (op == 1) {
+			printf("%02d: Found: %s %s\n", lineno, ifname, group);
+		} else if (op == 2) {
+			int i;
+
+			printf("%02d: Found: %s %s %s ", lineno, ifname, source, group);
+			for (i = 0; i < num; i++)
+				printf("%s ", dest[i]);
+			printf("\n");
+		} else {
+			printf("%02d: DUMP: %s\n", lineno, linebuf);
+		}
+#else
+		if (op == 1)
+			join_mgroup(lineno, ifname, group);
+		else if (op == 2)
+			add_mroute(lineno, ifname, group, source, dest, num);
+#endif	/* UNITTEST */
+		
+		lineno++;
+	}
+
+	free(linebuf);
+	fclose(fp);
+
+	return 0;
+}
+
+#ifdef UNITTEST
+int main (int argc, char *argv[])
+{
+	if (argc < 2) {
+		printf("Missing file argument.\n");
+		return 1;
+	}
+
+	return parse_conf_file(argv[1]);
+}
+#endif	/* UNITTEST */
+
+/**
+ * Local Variables:
+ *  compile-command: "gcc -g -o unittest -DUNITTEST parse-conf.c && ./unittest ../smcroute.conf"
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/pidfile.c b/src/pidfile.c
new file mode 100644
index 0000000..79c8e89
--- /dev/null
+++ b/src/pidfile.c
@@ -0,0 +1,106 @@
+/*	$OpenBSD: pidfile.c,v 1.8 2008/06/26 05:42:05 ray Exp $	*/
+/*	$NetBSD: pidfile.c,v 1.4 2001/02/19 22:43:42 cgd Exp $	*/
+
+/*-
+ * Copyright (c) 1999 The NetBSD Foundation, Inc.
+ * All rights reserved.
+ *
+ * This code is derived from software contributed to The NetBSD Foundation
+ * by Jason R. Thorpe.
+ *
+ * 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 NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
+ */
+
+#include "config.h"
+#include <sys/param.h>
+#include <errno.h>
+#include <paths.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+
+static char *pidfile_path;
+static pid_t pidfile_pid;
+
+static void pidfile_cleanup(void);
+
+extern char *__progname;
+
+int
+pidfile(const char *basename)
+{
+	int save_errno, result;
+	pid_t pid;
+	FILE *f;
+
+	if (basename == NULL)
+		basename = __progname;
+
+	if (pidfile_path != NULL) {
+		free(pidfile_path);
+		pidfile_path = NULL;
+	}
+
+	/* _PATH_VARRUN includes trailing / */
+	result = asprintf(&pidfile_path, "%s%s.pid", _PATH_VARRUN, basename);
+	if (result == -1 || pidfile_path == NULL)
+		return (-1);
+
+	if ((f = fopen(pidfile_path, "w")) == NULL) {
+		save_errno = errno;
+		free(pidfile_path);
+		pidfile_path = NULL;
+		errno = save_errno;
+		return (-1);
+	}
+
+	pid = getpid();
+	if (fprintf(f, "%ld\n", (long)pid) <= 0 || fclose(f) != 0) {
+		save_errno = errno;
+		(void) unlink(pidfile_path);
+		free(pidfile_path);
+		pidfile_path = NULL;
+		errno = save_errno;
+		return (-1);
+	}
+
+	pidfile_pid = pid;
+	if (atexit(pidfile_cleanup) < 0) {
+		save_errno = errno;
+		(void) unlink(pidfile_path);
+		free(pidfile_path);
+		pidfile_path = NULL;
+		pidfile_pid = 0;
+		errno = save_errno;
+		return (-1);
+	}
+
+	return (0);
+}
+
+static void
+pidfile_cleanup(void)
+{
+
+	if (pidfile_path != NULL && pidfile_pid == getpid())
+		(void) unlink(pidfile_path);
+}
diff --git a/src/smcroute.c b/src/smcroute.c
index abfc7fa..c7229fe 100644
--- a/src/smcroute.c
+++ b/src/smcroute.c
@@ -5,6 +5,7 @@
 **  Copyright (C) 2006-2009 Julien BLACHE <jb@jblache.org>
 **  Copyright (C) 2009      Todd Hayton <todd.hayton@gmail.com>
 **  Copyright (C) 2009-2011 Micha Lenk <micha@debian.org>
+**  Copyright (C) 2011      Joachim Nilsson <troglobit@gmail.com>
 **
 **  This program is free software; you can redistribute it and/or modify
 **  it under the terms of the GNU General Public License as published by
@@ -21,7 +22,6 @@
 **  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 **
 **  $Id: smcroute.c 86 2011-08-08 17:09:45Z micha $	
-**
 */
 
 #include <stdio.h>
@@ -31,8 +31,10 @@
 
 #include <sys/socket.h>
 #include <netinet/in.h>
+#include <netinet/ip.h>
 #include <arpa/inet.h>
 
+#include <signal.h>
 #include <unistd.h>
 
 #include "mclab.h"
@@ -40,33 +42,78 @@
 #include "config.h"
 #include "build.h"
 
-static const char Version[] = 
-"smcroute, Version " PACKAGE_VERSION ", Build" BUILD "\n"
-"Copyright 2001-2005 Carsten Schill <carsten@cschill.de>\n"
-"Copyright 2006-2009 Julien Blache <jb@jblache.org>,\n"
-"                    Todd Hayton <todd.hayton@gmail.com>, and\n"
-"                    Micha Lenk <micha@debian.org>\n"
-"Distributed under the GNU GENERAL PUBLIC LICENSE, Version 2 - check GPL.txt\n"
-"\n";
-
-static const char Usage[] = 
-"usage: smcroute\t[-v] [-d] [-k] [-D]\n"
-"\n" 
-"\t\t[-a <InputIntf> <OriginIpAdr> <McGroupAdr> <OutputIntf> [<OutputIntf>] ...]\n"
-"\t\t[-r <InputIntf> <OriginIpAdr> <McGroupAdr>]\n"
-"\n"
-"\t\t[-j <InputIntf> <McGroupAdr>]\n"
-"\t\t[-l <InputIntf> <McGroupAdr>]\n"
-;
-
-static const char MissingArgSt[] = "<missing argument>";
-
-int McGroupSock4 = -1;
-int McGroupSock6 = -1;
+extern char *__progname;
+static const char version_info[] =
+	"smcroute, Version " PACKAGE_VERSION ", Build" BUILD "\n"
+	"Copyright (c) 2001-2005  Carsten Schill <carsten@cschill.de>\n"
+	"Copyright (c) 2006-2009  Julien Blache <jb@jblache.org>,\n"
+	"                   2009  Todd Hayton <todd.hayton@gmail.com>, and\n"
+	"              2009-2011  Micha Lenk <micha@debian.org>\n"
+	"                   2011  Joachim Nilsson <troglobit@gmail.com>\n"
+	"Distributed under the GNU GENERAL PUBLIC LICENSE, Version 2\n"
+	"\n";
+
+static const char usage_info[] =
+	"Usage: smcroute [OPTIONS]... [ARGS]...\n"
+	"\n"
+	"  -d       Start smcroute daemon.\n"
+	"  -n       Run daemon in foreground, i.e., do not fork.\n"
+	"  -f FILE  Use FILE as daemon configuration. Default: " SMCROUTE_SYSTEM_CONF "\n"
+	"  -k       Stop (kill) a running daemon.\n"
+	"\n"
+	"  -h       Display this help text.\n"
+	"  -D       Debug logging.\n"
+	"  -v       Display version information and enable verbose logging.\n"
+	"\n"
+	"  -a ARGS  Add a multicast route, full syntax below.\n"
+	"  -r ARGS  Remove a multicast route, full syntax below.\n"
+	"\n"
+	"  -j ARGS  Join a multicast group on an interface, useful for testing.\n"
+	"  -l ARGS  Leave a multicast group on an interface, useful for testing.\n"
+	"\n"
+	"     <------------- INBOUND -------------->  <----- OUTBOUND ------>\n"
+	"  -a <IFNAME> <SOURCE-IP> <MULTICAST-GROUP>  <IFNAME> [<IFNAME> ...]\n"
+	"  -r <IFNAME> <SOURCE-IP> <MULTICAST-GROUP>\n"
+	"\n"
+	"  -j <IFNAME> <MULTICAST-GROUP>\n"
+	"  -l <IFNAME> <MULTICAST-GROUP>\n";
+
+static int sighandled = 0;
+#define	GOT_SIGINT	0x01
+#define	GOT_SIGHUP	0x02
 
 int do_debug_logging = 0;
 
-static int getArgOptLn( const char *ArgVc[] )
+/*
+ * Signal handler.  Take note of the fact that the signal arrived
+ * so that the main loop can take care of it.
+ */
+static void handler(int sig)
+{
+    switch (sig) {
+    case SIGINT:
+    case SIGTERM:
+	sighandled |= GOT_SIGINT;
+	break;
+
+    case SIGHUP:
+	sighandled |= GOT_SIGHUP;
+	break;
+    }
+}
+
+static void signal_init(void)
+{
+	struct sigaction sa;
+
+	sa.sa_handler = handler;
+	sa.sa_flags = 0;	/* Interrupt system calls */
+	sigemptyset(&sa.sa_mask);
+	sigaction(SIGHUP, &sa, NULL);
+	sigaction(SIGTERM, &sa, NULL);
+	sigaction(SIGINT, &sa, NULL);
+}
+
 /*
 ** Counts the number of arguments belonging to an option. Option is any argument
 ** begining with a '-'. 
@@ -74,490 +121,504 @@ static int getArgOptLn( const char *ArgVc[] )
 ** returns: - the number of arguments (without the option itself), 
 **          - 0, if we start already from the end of the argument vector
 **          - -1, if we start not from an option
-**
 */
+static int num_option_arguments(const char *argv[])
 {
-  const char **Pp;
+	const char **ptr;
 
-  /* end of vector */
-  if( ArgVc == NULL || *ArgVc == NULL )
-    return 0; 
+	/* end of vector */
+	if (argv == NULL || *argv == NULL)
+		return 0;
 
-  /* starting on wrong position */
-  if( **ArgVc != '-' )
-    return -1;
+	/* starting on wrong position */
+	if (**argv != '-')
+		return -1;
 
-  for( Pp = ArgVc +1; *Pp && **Pp != '-'; Pp++ )
-    /* */;
-    
-  return Pp - ArgVc;
-}
+	for (ptr = argv + 1; *ptr && **ptr != '-'; ptr++)
+		;
 
+	return ptr - argv;
+}
 
-static void clean()
-/*
-** Cleans up, i.e. releases allocated resources. Called via atexit().
-** 
-*/        
+/* Parse .conf file and setup routes */
+static void read_conf_file(const char *conf_file)
 {
-  smclog( LOG_DEBUG, 0, "clean handler called" );
-  disableMRouter4();
-  disableMRouter6();
-  cleanIpc();
+	if (access(conf_file, R_OK)) {
+		smclog(LOG_WARNING, errno, "Failed loading %s", conf_file);
+	} else {
+		if (parse_conf_file(conf_file))
+			smclog(LOG_WARNING, errno, "Failed reading %s", conf_file);
+	}
 }
 
-
-static int initMRouter4()
-/*
-** Inits the necessary resources for IPv4 MRouter.
-**
-*/
+/* Cleans up, i.e. releases allocated resources. Called via atexit() */
+static void clean(void)
 {
-  int Err;
+	smclog(LOG_DEBUG, 0, "clean handler called");
+	mroute4_disable();
+	mroute6_disable();
+	ipc_exit();
+}
 
-  switch( Err = enableMRouter4() ) {
-    case 0: break;
-    case EADDRINUSE: smclog( LOG_INIT, EADDRINUSE, "MC-Router IPv4 API already in use" ); return -1;
-#ifdef EOPNOTSUPP
-    case EOPNOTSUPP:
-#endif
-    case ENOPROTOOPT: smclog( LOG_WARNING, 0, "Kernel does not support IPv4 multicast routing (skipping IPv4 routing)" ); return -1;
-    default: smclog( LOG_INIT, Err, "MRT_INIT failed" ); return -1;
-  }
-      
-  /* create VIFs for all IP, non-loop interfaces
-   */
-  {
-    unsigned Ix;
-    struct IfDesc *Dp;
-
-    for( Ix = 0; (Dp = getIfByIx( Ix )); Ix++ ) 
-      if( Dp->InAdr.s_addr && ! (Dp->Flags & IFF_LOOPBACK) )
-	addVIF( Dp );
-  }
-
-  return 0;
+static void restart(void)
+{
+	smclog(LOG_DEBUG, 0, "Restart handler called");
+	mroute4_disable();
+	mroute6_disable();
+	mcgroup4_disable();
+	mcgroup6_disable();
+	/* No need to close the IPC, only at cleanup. */
+
+	/* Update list of interfaces and create new virtual interface mappings in kernel. */
+	iface_init();
+	mroute4_enable();
+	mroute6_enable();
 }
 
-static int initMRouter6()
-/*
-** Inits the necessary resources for IPv6 MRouter.
-**
-*/
+static int daemonize(void)
 {
-  int Err;
+	int pid;
 
-  switch( Err = enableMRouter6() ) {
-    case 0: break;
-    case EADDRINUSE: smclog( LOG_INIT, EADDRINUSE, "MC-Router IPv6 API already in use" ); return -1;
-#ifdef EOPNOTSUPP
-    case EOPNOTSUPP:
-#endif
-    case ENOPROTOOPT: smclog( LOG_WARNING, 0, "Kernel does not support IPv6 multicast routing (skipping IPv6 routing)" ); return -1;
-    default: smclog( LOG_INIT, Err, "MRT6_INIT failed" ); return -1;
-  }
-      
-  /* create MIFs for all IP, non-loop interfaces
-   */
-  {
-    unsigned Ix;
-    struct IfDesc *Dp;
-
-    for( Ix = 0; (Dp = getIfByIx( Ix )); Ix++ ) 
-      if( Dp->InAdr.s_addr && ! (Dp->Flags & IFF_LOOPBACK) )
-	addMIF( Dp );
-  }
-
-  return 0;
+	smclog(LOG_NOTICE, 0, "Forking daemon process.");
+
+	pid = fork();
+	if (!pid) {
+		/* Detach deamon from terminal */
+		if (close(0) < 0 || close(1) < 0 || close(2) < 0
+		    || open("/dev/null", 0) != 0 || dup2(0, 1) < 0
+		    || dup2(0, 2) < 0 || setpgrp() < 0)
+			smclog(LOG_ERR, errno, "Failed to detach deamon");
+	}
+
+	return pid;
 }
 
-void ServerLoop(void)
+static void server_loop(int sd, const char *conf_file)
 {
-  uint8 Bu[ MX_CMDPKT_SZ ];
-  int IpcServerFD;
-  unsigned short initialized_api_count;
-
-  /*
-   * Init everything before forking, so we can fail and return an
-   * error code in the parent and the initscript will fail
-   */
-
-  /* 
-   * Build list of multicast-capable physical interfaces that 
-   * are currently assigned an IP address.
-   */
-  buildIfVc();    
-
-  initialized_api_count = 0;
-  if (initMRouter4() == 0)
-    initialized_api_count++;
-
-  if (initMRouter6() == 0)
-    initialized_api_count++;
-
-  /* At least one API (IPv4 or IPv6) must have initialized successfully
-   * otherwise we abort the server initialization.
-   */
-  if (initialized_api_count == 0) {
-    smclog( LOG_INIT, ENOPROTOOPT, "Kernel does not support multicast routing" );
-    exit(1);
-  }
-
-  IpcServerFD = initIpcServer();
-  if (IpcServerFD < 0) {
-    clean();
-    exit(2);
-  }
-
-  /* creat daemon process
-   */
-  if( ! fork() ) {                   /* only daemon enters */
-    atexit( clean );
-
-    /* Detach deamon from terminal */
-    if( close( 0 ) < 0 || close( 1 ) < 0 || close( 2 ) < 0 
-	|| open( "/dev/null", 0 ) != 0 || dup2( 0, 1 ) < 0 || dup2( 0, 2 ) < 0
-	|| setpgrp() < 0
-	)
-      smclog( LOG_ERR, errno, "failed to detach deamon" );
-
-    while( 1 ) {
-      struct CmdPkt *PktPt;
-        
-      /* watch the MRouter and the IPC socket to the smcroute client */
-      {
-	fd_set ReadFDS;
+	int result;
+	uint8 buf[MX_CMDPKT_SZ];
+	fd_set fds;
 #ifdef HAVE_IPV6_MULTICAST_ROUTING
-	int MaxFD = MAX( IpcServerFD, MAX( MRouterFD4, MRouterFD6 ) );
+	int max_fd_num = MAX(sd, MAX(mroute4_socket, mroute6_socket));
 #else
-	int MaxFD = MAX( IpcServerFD, MRouterFD4 );
+	int max_fd_num = MAX(sd, mroute4_socket);
 #endif
-	int Rt;
-
-	FD_ZERO( &ReadFDS );
-	FD_SET( IpcServerFD, &ReadFDS );
-	FD_SET( MRouterFD4, &ReadFDS );
+	const char *str;
+	struct cmd *packet;
+	struct mroute mroute;
+
+	smclog(LOG_NOTICE, 0, "Attempting to load %s", conf_file);
+	read_conf_file (conf_file);
+
+	/* Ready for input, tell clients that by creating the pidfile */
+	if (pidfile(NULL))
+		smclog(LOG_WARNING, errno, "Failed creating pidfile");
+
+	/* Watch the MRouter and the IPC socket to the smcroute client */
+	while (1) {
+		if (sighandled) {
+			if (sighandled & GOT_SIGINT) {
+				sighandled &= ~GOT_SIGINT;
+				break;
+			}
+			if (sighandled & GOT_SIGHUP) {
+				sighandled &= ~GOT_SIGHUP;
+				restart();
+				smclog(LOG_NOTICE, 0, "Got SIGHUP, reloading %s ...", conf_file);
+				read_conf_file (conf_file);
+			}
+		}
+
+		FD_ZERO(&fds);
+		FD_SET(sd, &fds);
+		FD_SET(mroute4_socket, &fds);
 #ifdef HAVE_IPV6_MULTICAST_ROUTING
-	FD_SET( MRouterFD6, &ReadFDS );
+		if (-1 != mroute6_socket)
+			FD_SET(mroute6_socket, &fds);
 #endif
 
-	/* wait for input */
-	Rt = select( MaxFD +1, &ReadFDS, NULL, NULL, NULL );
+		/* wait for input */
+		result = select(max_fd_num + 1, &fds, NULL, NULL, NULL);
+		if (result <= 0) {
+			/* Log all errors, except when signalled, ignore failures. */
+			if (EINTR != errno)
+				smclog(LOG_WARNING, errno, "select() failure");
+			continue;
+		}
+
+		/* Check for kernel IGMPMSG_NOCACHE for (*,G) hits. I.e., source-less routes. */
+		if (FD_ISSET(mroute4_socket, &fds)) {
+			char tmp[128];
+			struct ip *ip;
+			struct igmpmsg *igmpctl;
+
+			memset (tmp, 0, sizeof(tmp));
+			result = read(mroute4_socket, tmp, sizeof(tmp));
+
+			/* packets sent up from kernel to daemon have ip->ip_p = 0 */
+			ip = (struct ip *)tmp;
+			igmpctl = (struct igmpmsg *)tmp;
+
+			/* Check for IGMPMSG_NOCACHE to do (*,G) based routing. */
+			if (ip->ip_p == 0 && igmpctl->im_msgtype == IGMPMSG_NOCACHE) {
+				char sbuf[16], gbuf[16];
+				struct iface *iface;
+				mroute4_t mroute;
+
+				mroute.group.s_addr  = igmpctl->im_dst.s_addr;
+				mroute.sender.s_addr = igmpctl->im_src.s_addr;
+				mroute.inbound       = igmpctl->im_vif;
+				iface = iface_find_by_vif (mroute.inbound);
+
+				/* Find any matching route for this group on that iif. */
+				smclog(LOG_DEBUG, 0, "Cache miss for group %s from %s on interface %s(%d) ifindex:%d",
+				       inet_ntop (AF_INET, &mroute.group, gbuf, sizeof(gbuf)),
+				       inet_ntop (AF_INET, &mroute.sender, sbuf, sizeof(sbuf)),
+				       iface ? iface->name : "unknown", mroute.inbound,
+				       iface ? iface->ifindex : -1);
+				mroute4_dyn_add(&mroute);
+			} else {
+				smclog(LOG_DEBUG, 0, "%d byte IGMP signaling dropped", result);
+			}
+		}
+
+		/* Receive and drop ICMPv6 stuff. This is either MLD packets
+		 * or upcall messages sent up from the kernel.
+		 */
+#ifdef HAVE_IPV6_MULTICAST_ROUTING
+		if (-1 != mroute6_socket && FD_ISSET(mroute6_socket, &fds)) {
+			char tmp[128];
 
-	/* log and ignore failures */
-	if( Rt <= 0 ) {
-	  smclog( LOG_WARNING, errno, "select() failure" );
-	  continue;
-	}
-	  
-	/* 
-	 * Receive and drop IGMP stuff. This is either IGMP packets
-	 * or upcall messages sent up from the kernel.
-	 */
-	if( FD_ISSET( MRouterFD4, &ReadFDS ) ) {
-	  char Bu[ 128 ];
-	    
-	  Rt = read( MRouterFD4, Bu, sizeof( Bu ) ); 
-          smclog( LOG_DEBUG, 0, "%d byte IGMP signaling dropped", Rt );
-	}
+			result = read(mroute6_socket, tmp, sizeof(tmp));
+			smclog(LOG_DEBUG, 0, "%d byte MLD signaling dropped", result);
+		}
+#endif
 
-	/* 
-	 * Receive and drop ICMPv6 stuff. This is either MLD packets
-	 * or upcall messages sent up from the kernel.
-	 */
-#ifdef HAVE_IPV6_MULTICAST_ROUTING
-	if( FD_ISSET( MRouterFD6, &ReadFDS ) ) {
-	  char Bu[ 128 ];
-	    
-	  Rt = read( MRouterFD6, Bu, sizeof( Bu ) ); 
-	  smclog( LOG_DEBUG, 0, "%d byte MLD signaling dropped", Rt );
+		/* loop back to select if there is no smcroute command */
+		if (!FD_ISSET(sd, &fds))
+			continue;
+
+		/* receive the command from the smcroute client */
+		packet = ipc_server_read(buf, sizeof(buf));
+		switch (packet->cmd) {
+		case 'a':
+		case 'r':
+			if ((str = cmd_convert_to_mroute(&mroute, packet))) {
+				smclog(LOG_WARNING, 0, str);
+				ipc_send(log_last_message, strlen(log_last_message) + 1);
+				break;
+			}
+
+			if (mroute.version == 4) {
+				if ((packet->cmd == 'a' && mroute4_add(&mroute.u.mroute4))
+				    || (packet->cmd == 'r' && mroute4_del(&mroute.u.mroute4))) {
+					ipc_send(log_last_message, strlen(log_last_message) + 1);
+					break;
+				}
+			} else {
+#ifndef HAVE_IPV6_MULTICAST_ROUTING
+				smclog(LOG_WARNING, 0, "Not built with IPv6 routing support.");
+#else
+				if ((packet->cmd == 'a' && mroute6_add(&mroute.u.mroute6))
+				    || (packet->cmd == 'r' && mroute6_del(&mroute.u.mroute6))) {
+					ipc_send(log_last_message, strlen(log_last_message) + 1);
+					break;
+				}
+#endif				/* HAVE_IPV6_MULTICAST_ROUTING */
+			}
+
+			ipc_send("", 1);
+			break;
+
+		case 'j':	/* j <InputIntf> <McGroupAdr> */
+		case 'l':	/* l <InputIntf> <McGroupAdr> */
+		{
+			int result = -1;
+			const char *ifname = (const char *)(packet + 1);
+			const char *groupstr = ifname + strlen(ifname) + 1;
+
+			if (strchr(groupstr, ':') == NULL) {
+				struct in_addr group;
+
+				/* check multicast address */
+				if (!*groupstr
+				    || !inet_aton(groupstr, &group)
+				    || !IN_MULTICAST(ntohl(group.s_addr))) {
+					smclog(LOG_WARNING, 0, "invalid multicast group address: '%s'", groupstr);
+					ipc_send(log_last_message, strlen(log_last_message) + 1);
+					break;
+				}
+
+				/* join or leave */
+				if (packet->cmd == 'j')
+					result = mcgroup4_join(ifname, group);
+				else
+					result = mcgroup4_leave(ifname, group);
+			} else {	/* IPv6 */
+#ifndef HAVE_IPV6_MULTICAST_HOST
+				smclog(LOG_WARNING, 0, "Not built with IPv6 support.");
+#else
+				struct in6_addr group;
+
+				/* check multicast address */
+				if (!*groupstr
+				    || (inet_pton(AF_INET6, groupstr, &group) <= 0)
+				    || !IN6_IS_ADDR_MULTICAST(&group)) {
+					smclog(LOG_WARNING, 0, "invalid multicast group address: '%s'", groupstr);
+					ipc_send(log_last_message, strlen(log_last_message) + 1);
+					break;
+				}
+
+				/* join or leave */
+				if (packet->cmd == 'j')
+					result = mcgroup6_join(ifname, group);
+				else
+					result = mcgroup6_leave(ifname, group);
+#endif				/* HAVE_IPV6_MULTICAST_HOST */
+			}
+
+			/* failed */
+			if (result) {
+				ipc_send(log_last_message, strlen(log_last_message) + 1);
+				break;
+			}
+
+			ipc_send("", 1);
+			break;
+		}
+
+		case 'k':
+			ipc_send("", 1);
+			exit(0);
+		}
 	}
-#endif
+}
+
+/* Init everything before forking, so we can fail and return an
+ * error code in the parent and the initscript will fail */
+static void start_server(int background, const char *conf_file)
+{
+	int sd, pid = 0;
+	unsigned short initialized_api_count;
 
-	/* loop back to select if there is no smcroute command */
-	if( ! FD_ISSET( IpcServerFD, &ReadFDS ) ) 
-	  continue;
-      }
+	/* Build list of multicast-capable physical interfaces that 
+	 * are currently assigned an IP address. */
+	iface_init();
 
-      /* receive the command from the smcroute client */
-      PktPt = readIpcServer( Bu, sizeof( Bu ) );
+	initialized_api_count = 0;
+	if (mroute4_enable() == 0)
+		initialized_api_count++;
 
-      switch( PktPt->Cmd ) {
-	struct MRouteDesc MrDe;
-	const char *ErrSt;
+	if (mroute6_enable() == 0)
+		initialized_api_count++;
 
-      case 'a':
-      case 'r':  
-	if( (ErrSt = convCmdPkt2MRouteDesc( &MrDe, PktPt )) ) {
-	  smclog( LOG_WARNING, 0, ErrSt );
-	  sendIpc( LogLastMsg, strlen( LogLastMsg ) +1 );
-	  break;
+	/* At least one API (IPv4 or IPv6) must have initialized successfully
+	 * otherwise we abort the server initialization. */
+	if (initialized_api_count == 0) {
+		smclog(LOG_INIT, ENOPROTOOPT, "Kernel does not support multicast routing");
+		exit(1);
 	}
 
-	if (MrDe.ipVersion == 4) {
-	  if( (PktPt->Cmd == 'a' && addMRoute4( &MrDe.u.mRoute4Desc )) || 
-	      (PktPt->Cmd == 'r' && delMRoute4( &MrDe.u.mRoute4Desc )) ) {
-	    sendIpc( LogLastMsg, strlen( LogLastMsg ) +1 );
-	    break;
-	  }
-	} else {
-	  if( (PktPt->Cmd == 'a' && addMRoute6( &MrDe.u.mRoute6Desc )) || 
-	      (PktPt->Cmd == 'r' && delMRoute6( &MrDe.u.mRoute6Desc )) ) {
-	    sendIpc( LogLastMsg, strlen( LogLastMsg ) +1 );
-	    break;
-	  }
+	sd = ipc_server_init();
+	if (sd < 0) {
+		clean();
+		exit(2);
 	}
 
-	sendIpc( "", 1 );
-	break;
+	if (background)
+		pid = daemonize();
+	else
+		smclog(LOG_NOTICE, 0, "Starting daemon in foreground.");
 
-      case 'j': /* j <InputIntf> <McGroupAdr> */
-      case 'l': /* l <InputIntf> <McGroupAdr> */
-	{
-	  const char *IfSt    = (const char *)(PktPt +1);
-	  const char *McAdrSt = IfSt + strlen( IfSt ) +1;
-	  int         Rt;
-
-	  if (strchr(McAdrSt, ':') == NULL) {
-	    struct in_addr McAdr;
-
-	    /* check multicast address */
-	    if( ! *McAdrSt || ! inet_aton( McAdrSt, &McAdr ) 
-		|| ! IN_MULTICAST( ntohl( McAdr.s_addr ) ) ) {
-	      smclog( LOG_WARNING, 0, "invalid multicast group address: '%s'", 
-		      McAdrSt );
-	      sendIpc( LogLastMsg, strlen( LogLastMsg ) +1 );
-	      break;
-	    }
-
-	    /* create socket for IGMP as needed */
-	    if( McGroupSock4 < 0 ) 
-	      McGroupSock4 = openUdpSocket( INADDR_ANY, 0 );
-
-	    /* join or leave */
-	    if( PktPt->Cmd == 'j' )
-	      Rt = joinMcGroup4( McGroupSock4, IfSt, McAdr );
-	    else
-	      Rt = leaveMcGroup4( McGroupSock4, IfSt, McAdr );
-	  } else { /* IPv6 */
-	    struct in6_addr McAdr;
-
-	    /* check multicast address */
-	    if( ! *McAdrSt || ( inet_pton( AF_INET6, McAdrSt, &McAdr ) <= 0 ) 
-		|| ! IN6_MULTICAST( &McAdr ) ) {
-	      smclog( LOG_WARNING, 0, "invalid multicast group address: '%s'", 
-		      McAdrSt );
-	      sendIpc( LogLastMsg, strlen( LogLastMsg ) +1 );
-	      break;
-	    }
-
-	    /* create socket for IGMP as needed */
-	    if( McGroupSock6 < 0 ) {
-	      McGroupSock6 = socket( AF_INET6, SOCK_DGRAM, IPPROTO_UDP );
-	      if (McGroupSock6 < 0) 
-		smclog( LOG_WARNING, errno, "socket failed" );
-	    }
-
-	    /* join or leave */
-	    if( PktPt->Cmd == 'j' )
-	      Rt = joinMcGroup6( McGroupSock6, IfSt, McAdr );
-	    else
-	      Rt = leaveMcGroup6( McGroupSock6, IfSt, McAdr );
-	  }
-
-	  /* failed */
-	  if( Rt ) {
-	    sendIpc( LogLastMsg, strlen( LogLastMsg ) +1 );
-	    break;
-	  }
-
-	  sendIpc( "", 1 );
-	  break;
+	if (!pid) {
+		smclog(LOG_NOTICE, 0, "Entering smcroute daemon main loop.");
+		atexit(clean);
+		signal_init();
+		server_loop(sd, conf_file);
 	}
+}
 
-      case 'k':
-	sendIpc( "", 1 );
-	exit( 0 );
-      }
-    }
-  }
+static int usage(void)
+{
+	fputs(version_info, stderr);
+	fputs(usage_info, stderr);
+
+	return 1;
 }
 
-int main( int ArgCn, const char *ArgVc[] )
 /*
-** main programm
-** - scans options
+** main program
+** - Parses command line options
 **   - daemon mode: enters daemon status and goes in receive-execute command loop 
 **   - client mode: creates commands from command line and sends them to the daemon
-**
 */
+int main(int argc, const char *argv[])
 {
-  struct CmdPkt *CmdVc[ 16 ], **CmdVcPt = CmdVc;
-  uint8 Bu[ MX_CMDPKT_SZ ];
-  int StartDaemon = 0;
-  int ProgRt = 0;
-
-  /* init syslog */
-  openlog( ArgVc[ 0 ], LOG_PID, LOG_DAEMON );   
-  
-  if( ArgCn <= 1 ) {
-Usage:    
-    fputs( Version, stderr );
-    fputs( Usage, stderr );
-    return 1;
-  }
-
-  /* scan options */
-  {
-    int OptLn;
-
-    for( OptLn = 1; (OptLn = getArgOptLn( ArgVc += OptLn )); ) {
-  
-      if( OptLn < 0 )           /* error */
-	goto Usage;
-    
-      /* handle option */
-      switch( *(*ArgVc +1) ) {
-      case 'a':                 /* add route */
-	if( OptLn < 5 ) {
-	  fprintf( stderr, "not enough arguments for 'add' command\n" );
-	  goto Usage;
-	}
-
-BuildCmd:
-	if( CmdVcPt >= VCEP( CmdVc ) ) {
-	  fprintf( stderr, "too many command options\n" );
-	  goto Usage;
-	}
-	  
-	*CmdVcPt++ = buildCmdPkt( *(*ArgVc +1), ArgVc +1, OptLn -1 );
-	break;
-
-      case 'r':                 /* remove route */
-	if( OptLn < 4 ) {
-	  fprintf( stderr, "wrong number of  arguments for 'remove' command\n" );
-	  goto Usage;
+	int num_opts, result = 0;
+	int start_daemon = 0;
+	int background = 1;
+	uint8 buf[MX_CMDPKT_SZ];
+	const char *arg, *conf_file = SMCROUTE_SYSTEM_CONF;
+	unsigned int cmdnum = 0;
+	struct cmd *cmdv[16];
+
+	/* init syslog */
+	openlog(__progname, LOG_PID, LOG_DAEMON);
+
+	if (argc <= 1)
+		return usage();
+
+	/* Parse command line options */
+	for (num_opts = 1; (num_opts = num_option_arguments(argv += num_opts));) {
+		if (num_opts < 0)	/* error */
+			return usage();
+
+		/* handle option */
+		arg = argv[0];
+		switch (arg[1]) {
+		case 'a':	/* add route */
+			if (num_opts < 5) {
+				fprintf(stderr, "Not enough arguments for 'add' command\n");
+				return usage();
+			}
+			break;
+
+		case 'r':	/* remove route */
+			if (num_opts < 4) {
+				fprintf(stderr, "Wrong number of  arguments for 'remove' command\n");
+				return usage();
+			}
+			break;
+
+		case 'j':	/* join */
+		case 'l':	/* leave */
+			if (num_opts != 3) {
+				fprintf(stderr, "Wrong number of arguments for %s command\n", arg[1] == 'j' ? "'join'" : "'leave'");
+				return usage();
+			}
+			break;
+
+		case 'k':	/* kill daemon */
+			if (num_opts != 1) {
+				fprintf(stderr, "No arguments allowed for 'k' option\n");
+				return usage();
+			}
+			break;
+
+		case 'h':	/* help */
+			return usage();
+
+		case 'v':	/* verbose */
+			fputs(version_info, stderr);
+			log_stderr = LOG_DEBUG;
+			continue;
+
+		case 'd':	/* daemon */
+			start_daemon = 1;
+			continue;
+
+		case 'n':	/* run daemon in foreground, i.e., do not fork */
+			background = 0;
+			continue;
+
+		case 'f':
+			if (num_opts != 2) {
+				fprintf(stderr, "Missing configuration file arguments for 'f' option\n");
+				return usage();
+			}
+			conf_file = argv[1];
+			continue;
+
+		case 'D':
+			do_debug_logging = 1;
+			continue;
+
+		default:	/* unknown option */
+			fprintf(stderr, "Unknown option: %s\n", *argv);
+			return usage();
+		}
+
+		/* Check and build command argument list. */
+		if (cmdnum >= ARRAY_ELEMENTS(cmdv)) {
+			fprintf(stderr, "Too many command options\n");
+			return usage();
+		}
+
+		cmdv[cmdnum++] = cmd_build(arg[1], argv + 1, num_opts - 1);
 	}
 
-	goto BuildCmd;
-
-      case 'j':                 /* join */
-      case 'l':                 /* leave */
-	if( OptLn != 3 ) {
-	  fprintf( stderr, "wrong number of arguments for 'join'/'leave' command\n" );
-	  goto Usage;
+	if (start_daemon) {	/* only daemon parent enters */
+		if (geteuid() != 0) {
+			smclog(LOG_ERR, 0, "Must have super-user permissions to start %s.", __progname);
+			exit(1);
+		}
+		start_server(background, conf_file);
+		if (!background)
+			exit (0); /* Exit if non-backgrounded daemon exits this way. */
 	}
-	  
-	goto BuildCmd;
 
-      case 'k':                 /* kill daemon */
-	if( OptLn != 1 ) {
-	  fprintf( stderr, "no arguments allowed for 'k' option\n" );
-	  goto Usage;
+	/* Client or daemon parent only, the daemon never reaches this point */
+
+	/* send commands */
+	if (cmdnum) {
+		unsigned int i;
+		int code, retry_count = 30;
+
+		openlog(argv[0], LOG_PID, LOG_USER);
+
+	retry:
+		/* connect to daemon */
+		code = ipc_client_init();
+		if (code) {
+			switch (code) {
+			case EACCES:
+				smclog(LOG_ERR, EACCES, "Need super-user permissions to connect to daemon");
+				break;
+
+			case ENOENT:
+			case ECONNREFUSED:
+				/* When starting daemon, give it 30 times a 1/10 second to get ready */
+				if (start_daemon && --retry_count) {
+					usleep(100000);
+					goto retry;
+				}
+				smclog(LOG_ERR, code, "Daemon not running");
+				break;
+
+			default:
+				smclog(LOG_ERR, code, "Failed connecting to daemon");
+				break;
+			}
+		}
+
+		for (i = 0; i < cmdnum; i++) {
+			int slen = 0, rlen = 0;
+			struct cmd *command = cmdv[i];
+
+			smclog(LOG_DEBUG, 0, "Sending command %c len:%zu count:%d", command->cmd, command->len, command->count);
+			slen = ipc_send(command, command->len);
+			rlen = ipc_receive(buf, sizeof(buf));
+			if (slen < 0 || rlen < 0)
+				smclog(LOG_ERR, errno, "Read/Write to daemon failed");
+
+			smclog(LOG_DEBUG, 0, "rlen: %d", rlen);
+
+			if (rlen != 1 || *buf != '\0') {
+				fprintf(stderr, "Daemon error: %s\n", buf);
+				result = 1;
+			}
+
+			free(command);
+		}
 	}
 
-	goto BuildCmd;
-
-      case 'h':                 /* help */
-	puts( Version );
-	puts( Usage );
-	break;
-
-      case 'v':                 /* verbose */
-	fputs( Version, stderr );
-	Log2Stderr = LOG_DEBUG;
-	break;
-
-      case 'd':                 /* daemon */
-	StartDaemon = 1;
-	break;
-
-      case 'D':
-        do_debug_logging = 1;
-        break;
-
-      default:                  /* unknown option */
-	fprintf( stderr, "unknown option: %s\n", *ArgVc );
-	goto Usage;
-      }
-    }
-  }
-
-  if( StartDaemon ) {                       /* only daemon parent enters */
-    ServerLoop();
-  }
-
-  /* Client or daemon parent only, the daemon never reaches this point */
-
-  /* send commands */
-  if( CmdVcPt > CmdVc ) {        
-    struct CmdPkt **PktPp; 
-
-    openlog( ArgVc[ 0 ], LOG_PID, LOG_USER );
-
-    /* connect to daemon */
-    {
-      int Err;
-      int RetryCn = 30;
-
-Retry:
-      switch( Err = initIpcClient() ) {
-
-	case 0: 
-	  break;
-
-	case EACCES: 
-	  smclog( LOG_ERR, EACCES, "need super-user rights to connect to daemon" ); 
-	  break;
-
-	case ENOENT:
-	case ECONNREFUSED: 
-	  /*
-	   * If we started the daemon -> give it 30 times a 1/10 second to 
-	   * get ready
-	   */
-	  if( StartDaemon && --RetryCn ) {
-	    usleep( 100000 );
-	    goto Retry;
-	  }
-
-	  smclog( LOG_ERR, Err, "daemon not running ?" );
-	  break;
-
-	default:
-	  smclog( LOG_ERR, Err, "can't connect to daemon" );
-	  break;
-      }
-    }
-
-    for( PktPp = CmdVc; PktPp < CmdVcPt; PktPp++ ) {
-      int RdSz = 0;
-      
-      if( (sendIpc( *PktPp, (*PktPp)->PktSz ) < 0) 
-       || (RdSz = readIpc( Bu, sizeof( Bu ) )) < 0   
-      )
-	smclog( LOG_ERR, errno, "read/write to daemon failed" );
-
-      smclog( LOG_DEBUG, 0, "RdSz: %d", RdSz );
-
-      if( RdSz != 1 || *Bu != '\0' ) {
-	fprintf( stderr, "daemon error: %s\n", Bu );
-	ProgRt = 1;
-      }
-
-      free( *PktPp );
-    }
-  }
-
-  return ProgRt;
+	return result;
 }
 
-
-
-
-
-
-
-
-
-
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/syslog.c b/src/syslog.c
index 1f27463..f2233d1 100644
--- a/src/syslog.c
+++ b/src/syslog.c
@@ -25,96 +25,82 @@
 
 #include "mclab.h"
 
-int Log2Stderr = LOG_WARNING;
+int  log_stderr = LOG_WARNING;
+int  log_last_severity;
+int  log_last_error;
+char log_last_message[128];
 
-int  LogLastServerity;
-int  LogLastErrno;
-char LogLastMsg[ 128 ];
-
-extern int do_debug_logging;
-
-void smclog( int Serverity, int Errno, const char *FmtSt, ... )
 /*
-** Writes the message 'FmtSt' with the parameters '...' to syslog.
-** 'Serverity' is used for the syslog entry. For an 'Errno' value 
+** Writes the message 'fmt' with the parameters '...' to syslog.
+** 'severity' is used for the syslog entry. For an 'code' value 
 ** other then 0, the correponding error string is appended to the
 ** message.
 **
-** For a 'Serverity' more important then 'LOG_WARNING' the message is 
+** For a 'severity' more important then 'LOG_WARNING' the message is 
 ** also logged to 'stderr' and the program is finished with a call to 
 ** 'exit()'.
 **
-** If the 'Serverity' is more important then 'Log2Stderr' the message
+** If the 'severity' is more important then 'log_stderr' the message
 ** is logged to 'stderr'.
 **          
 */
+void smclog(int severity, int code, const char *fmt, ...)
 {
-  const char ServVc[][ 5 ] = { "EMER", "ALER", "CRIT", "ERRO",
-			       "Warn", "Note", "Info", "Debu" };
-
-  const char *ServPt;
-
-  const char *ErrSt = (Errno <= 0) ? NULL : (const char *)strerror( Errno ); 
-
-  // LOG_INIT is a gross hack to work around smcroute's bad architecture
-  // During daemon init, we do not want to trigger the exit() call at the end
-  // of the function to be able to return an exit code from the parent before
-  // we daemonize, without the parent triggering the atexit() handlers in the
-  // normal case (which would remove the socket...)
-  // That gross, ugly hack or a complete rewrite, for now the hack will do.
-  if (Serverity < 0 || Serverity >= VCMC( ServVc ))
-    {
-      if (Serverity == LOG_INIT)
-	ServPt = "INIT";
-      else
-	ServPt = "!unknown serverity!";
-    }
-  else
-      ServPt = ServVc[ Serverity ];
-
-  // Skip logging for severities 'DEBUG' if do_debug_logging is false
-  if (Serverity == LOG_DEBUG && !do_debug_logging) return;
-
-  {
-    va_list ArgPt;
-    unsigned Ln;
-
-    va_start( ArgPt, FmtSt );
-    Ln  = snprintf( LogLastMsg, sizeof( LogLastMsg ), "%s: ", ServPt );
-    Ln += vsnprintf( LogLastMsg + Ln, sizeof( LogLastMsg ) - Ln, FmtSt, ArgPt );
-    if( ErrSt )
-      snprintf( LogLastMsg + Ln, sizeof( LogLastMsg ) - Ln, "; Errno(%d): %s", Errno, ErrSt );
-       
-    va_end( ArgPt );
-  }
-
-
-  // update our global Last... variables
-  LogLastServerity = Serverity;
-  LogLastErrno = Errno;
-
-  // control logging to stderr
-  if( Serverity < LOG_WARNING || Serverity < Log2Stderr || Serverity == LOG_INIT)
-    fprintf( stderr, "%s\n", LogLastMsg );
-
-  // always to syslog
-  syslog( (Serverity == LOG_INIT) ? LOG_ERR : Serverity, "%s", LogLastMsg );
-
-  // LOG_INIT doesn't trigger that
-  if( Serverity <= LOG_ERR )
-    exit( -1 );
+	int arg_len;
+	va_list args;
+	const char severity_list[][5] = {
+		"EMER", "ALER", "CRIT", "ERRO",
+		"Warn", "Note", "Info", "Debu"
+	};
+	const char *severity_string;
+	const char *error_string = (code <= 0) ? NULL : (const char *)strerror(code);
+
+	/* LOG_INIT is a gross hack to work around smcroute's bad architecture
+	 * During daemon init, we do not want to trigger the exit() call at the end
+	 * of the function to be able to return an exit code from the parent before
+	 * we daemonize, without the parent triggering the atexit() handlers in the
+	 * normal case (which would remove the socket...)
+	 * That gross, ugly hack or a complete rewrite, for now the hack will do. */
+	if (severity < 0 || severity >= (int)ARRAY_ELEMENTS(severity_list)) {
+		if (severity == LOG_INIT)
+			severity_string = "INIT";
+		else
+			severity_string = "!unknown serverity!";
+	} else {
+		severity_string = severity_list[severity];
+	}
+
+	/* Skip logging for severities 'DEBUG' if do_debug_logging is false */
+	if (severity == LOG_DEBUG && !do_debug_logging)
+		return;
+
+	va_start(args, fmt);
+	arg_len  = snprintf(log_last_message, sizeof(log_last_message), "%s: ", severity_string);
+	arg_len += vsnprintf(log_last_message + arg_len, sizeof(log_last_message) - arg_len, fmt, args);
+	if (error_string)
+		snprintf(log_last_message + arg_len, sizeof(log_last_message) - arg_len, ". Error %d: %s", code, error_string);
+	va_end(args);
+
+	/* update our global Last... variables */
+	log_last_severity = severity;
+	log_last_error = code;
+
+	/* control logging to stderr */
+	if (severity < LOG_WARNING || severity < log_stderr || severity == LOG_INIT)
+		fprintf(stderr, "%s\n", log_last_message);
+
+	/* always to syslog */
+	syslog((severity == LOG_INIT) ? LOG_ERR : severity, "%s", log_last_message);
+
+	/* LOG_INIT doesn't trigger that */
+	if (severity <= LOG_ERR)
+		exit(-1);
 }
 
-
-
-
-
-
-
-
-
-
-
-
-
-
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */
diff --git a/src/udpsock.c b/src/udpsock.c
index a6faba1..d46bc1b 100644
--- a/src/udpsock.c
+++ b/src/udpsock.c
@@ -25,28 +25,36 @@
 
 #include "mclab.h"
 
-int openUdpSocket( uint32 PeerInAdr, uint16 PeerPort )
 /*
 ** Creates and connects a simple UDP socket to the target 
-** 'PeerInAdr':'PeerPort'
+** 'inaddr':'Port'
 **
 ** returns: - the opened socket
-**          
 */
+int udp_socket_open(uint32 inaddr, uint16 port)
 {
-  int Sock;
-  struct sockaddr_in SockAdr;
+	int sd;
+	struct sockaddr_in sa;
 
-  if( (Sock = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 )
-    smclog( LOG_ERR, errno, "UDP socket open" );
-  
-  SockAdr.sin_family      = AF_INET;
-  SockAdr.sin_port        = PeerPort;
-  SockAdr.sin_addr.s_addr = PeerInAdr;
-  memset( &SockAdr.sin_zero, 0, sizeof( SockAdr.sin_zero ) );
+	sd = socket(AF_INET, SOCK_DGRAM, 0);
+	if (sd < 0)
+		smclog(LOG_ERR, errno, "UDP socket open");
 
-  if( connect( Sock, (struct sockaddr *)&SockAdr, sizeof( SockAdr ) ) )
-    smclog( LOG_ERR, errno, "UDP socket connect" );
+	sa.sin_family = AF_INET;
+	sa.sin_port = port;
+	sa.sin_addr.s_addr = inaddr;
+	memset(&sa.sin_zero, 0, sizeof(sa.sin_zero));
 
-  return Sock;
+	if (connect(sd, (struct sockaddr *)&sa, sizeof(sa)))
+		smclog(LOG_ERR, errno, "UDP socket connect");
+
+	return sd;
 }
+
+/**
+ * Local Variables:
+ *  version-control: t
+ *  indent-tabs-mode: t
+ *  c-file-style: "linux"
+ * End:
+ */