Browse Source

Move libexpat, unbound into core and introduce hnsd

hnsd is the Handshake SPV name resolver daemon for the Handshake
network. see https://handshake.org and https://github.com/handshake-org/hnsd

Currently, hnsd needs some more work.
RISCi_ATOM 5 years ago
parent
commit
7b61fa9e1a

+ 71 - 0
package/libs/expat/Makefile

@@ -0,0 +1,71 @@
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=expat
+PKG_VERSION:=2.2.6
+PKG_RELEASE:=1
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.bz2
+PKG_SOURCE_URL:=@SF/expat
+PKG_HASH:=17b43c2716d521369f82fc2dc70f359860e90fa440bea65b3b85f0b246ea81f2
+PKG_MAINTAINER:=Steven Barth <cyrus@openwrt.org>, \
+		Ted Hess <thess@kitschensync.net>
+
+PKG_LICENSE:=MIT
+PKG_LICENSE_FILES:=COPYING
+
+PKG_FIXUP:=autoreconf
+
+PKG_INSTALL:=1
+PKG_BUILD_PARALLEL:=1
+
+include $(INCLUDE_DIR)/host-build.mk
+include $(INCLUDE_DIR)/package.mk
+
+define Package/libexpat
+  SECTION:=libs
+  CATEGORY:=Libraries
+  TITLE:=An XML parsing library
+  URL:=https://libexpat.github.io/
+endef
+
+define Package/libexpat/description
+ A fast, non-validating, stream-oriented XML parsing library.
+endef
+
+TARGET_CFLAGS += $(FPIC)
+
+CONFIGURE_ARGS += \
+	--enable-shared \
+	--enable-static \
+	--without-docbook
+
+HOST_CONFIGURE_ARGS += \
+	--without-docbook
+
+define Host/Install
+	$(MAKE) -C $(HOST_BUILD_DIR) install
+endef
+
+define Build/InstallDev
+	$(INSTALL_DIR) $(1)/usr/include
+	$(CP) $(PKG_INSTALL_DIR)/usr/include/expat{,_external}.h $(1)/usr/include/
+
+	$(INSTALL_DIR) $(1)/usr/lib/pkgconfig
+	$(INSTALL_DATA) $(PKG_INSTALL_DIR)/usr/lib/pkgconfig/expat.pc $(1)/usr/lib/pkgconfig/
+
+	$(INSTALL_DIR) $(1)/usr/lib
+	$(CP) $(PKG_INSTALL_DIR)/usr/lib/libexpat.{a,so*} $(1)/usr/lib/
+endef
+
+define Package/libexpat/install
+	$(INSTALL_DIR) $(1)/usr/lib
+	$(CP) $(PKG_INSTALL_DIR)/usr/lib/libexpat.so.* $(1)/usr/lib/
+endef
+
+$(eval $(call HostBuild))
+$(eval $(call BuildPackage,libexpat))

+ 64 - 0
package/network/services/hnsd/Makefile

@@ -0,0 +1,64 @@
+#
+# Copyright (c) 2018 libreCMC Project <info@librecmc.org>
+# Copyright (c) 2018 Robert Call <bob@bobcall.me>
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=hnsd
+PKG_VERSION:=0.1
+PKG_RELEASE:=1
+PKG_LICENSE:=MIT
+
+PKG_SOURCE_PROTO:=git
+PKG_SOURCE_VERSION:=HEAD
+PKG_SOURCE_URL:=https://github.com/handshake-org/hnsd
+PKG_SOURCE_SUBDIR:=$(PKG_NAME)-$(PKG_VERSION)
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_BUILD_DIR:=$(BUILD_DIR)/$(PKG_NAME)-$(PKG_VERSION)
+
+PKG_FIXUP:=autoreconf
+include $(INCLUDE_DIR)/package.mk
+
+define Package/hnsd
+	SECTION:=net
+	CATEGORY:=Network
+	TITLE:=Handshake SPV
+	DEPENDS:=+libunbound +libunbound
+	MAINTAINER:=Robert Call <bob@bobcall.me>
+	URL:=https://handshake.org
+endef
+
+define Package/hnsd/description
+SPV resolver daemon for the Handshake network.
+endef
+
+define Build/Configure
+	( cd $(PKG_BUILD_DIR); ./autogen.sh )
+	$(call Build/Configure/Default)
+endef
+
+define Build/Compile
+	+$(MAKE) -C $(PKG_BUILD_DIR) \
+		CC="$(TARGET_CC)" \
+		CXXFLAGS="$(TARGET_CXX)" \
+		CFLAGS="$(TARGET_CFLAGS)" \
+		LD="$(TARGET_CC)" \
+		LDLIBS="$(LDLIBS)" \
+		LDFLAGS="$(TARGET_LDFLAGS)"
+		CROSS_COMPILE="$(TARGET_CROSS)" \
+		EXTRA_CFLAGS="$(TARGET_CFLAGS)" \
+		ARCH="$(ARCH)"
+
+endef
+
+define Package/hnsd/install
+	$(INSTALL_DIR) $(1)/usr/sbin
+	$(INSTALL_BIN) $(PKG_BUILD_DIR)/hnsd $(1)/usr/sbin/
+
+endef
+
+$(eval $(call BuildPackage,hnsd))

+ 199 - 0
package/network/services/unbound/Makefile

@@ -0,0 +1,199 @@
+#
+# Copyright (C) 2010-2016 OpenWrt.org
+#
+# This is free software, licensed under the GNU General Public License v2.
+# See /LICENSE for more information.
+#
+
+include $(TOPDIR)/rules.mk
+
+PKG_NAME:=unbound
+PKG_VERSION:=1.7.3
+PKG_RELEASE:=6
+
+PKG_LICENSE:=BSD-3-Clause
+PKG_LICENSE_FILES:=LICENSE
+PKG_MAINTAINER:=Eric Luehrsen <ericluehrsen@gmail.com>
+
+PKG_SOURCE:=$(PKG_NAME)-$(PKG_VERSION).tar.gz
+PKG_SOURCE_URL:=http://www.unbound.net/downloads
+PKG_HASH:=c11de115d928a6b48b2165e0214402a7a7da313cd479203a7ce7a8b62cba602d
+
+PKG_BUILD_PARALLEL:=1
+PKG_FIXUP:=autoreconf
+PKG_INSTALL:=1
+
+include $(INCLUDE_DIR)/package.mk
+
+define Package/unbound/Default
+  TITLE:=Validating Recursive DNS Server
+  URL:=http://www.unbound.net/
+  DEPENDS:=+libopenssl
+endef
+
+define Package/unbound
+  $(call Package/unbound/Default)
+  SECTION:=net
+  CATEGORY:=Network
+  SUBMENU:=IP Addresses and Names
+  USERID:=unbound:unbound
+  TITLE+= (daemon)
+  DEPENDS+= +libunbound
+endef
+
+define Package/unbound/description
+  This package contains the Unbound daemon.
+endef
+
+define Package/unbound-anchor
+  $(call Package/unbound/Default)
+  SECTION:=net
+  CATEGORY:=Network
+  SUBMENU:=IP Addresses and Names
+  TITLE+= (DSKEY utility)
+  DEPENDS+= +unbound +libexpat
+endef
+
+define Package/unbound-anchor/description
+  This package contains the Unbound anchor utility.
+endef
+
+define Package/unbound-control
+  $(call Package/unbound/Default)
+  SECTION:=net
+  CATEGORY:=Network
+  SUBMENU:=IP Addresses and Names
+  TITLE+= (control utility)
+  DEPENDS+= +unbound
+endef
+
+define Package/unbound-control/description
+  This package contains the Unbound control utility.
+endef
+
+define Package/unbound-control-setup
+  $(call Package/unbound/Default)
+  SECTION:=net
+  CATEGORY:=Network
+  SUBMENU:=IP Addresses and Names
+  TITLE+= (control setup)
+  DEPENDS+= +unbound-control +openssl-util
+endef
+
+define Package/unbound-control-setup/description
+  This package contains the Unbound control setup utility.
+endef
+
+define Package/unbound-host
+  $(call Package/unbound/Default)
+  SECTION:=net
+  CATEGORY:=Network
+  SUBMENU:=IP Addresses and Names
+  TITLE+= (lookup utility)
+  DEPENDS+= +libunbound
+endef
+
+define Package/unbound-host/description
+  This package contains the Unbound DNS lookup utility.
+endef
+
+define Package/libunbound
+  $(call Package/unbound/Default)
+  SECTION:=libs
+  CATEGORY:=Libraries
+  TITLE+= (library)
+  DEPENDS+= +libpthread
+endef
+
+define Package/libunbound/description
+  This package contains the Unbound shared library.
+endef
+
+CONFIGURE_ARGS += \
+	--disable-dsa \
+	--disable-gost \
+	--enable-allsymbols \
+	--enable-tfo-client \
+	--enable-tfo-server \
+	--with-libexpat="$(STAGING_DIR)/usr" \
+	--with-ssl="$(STAGING_DIR)/usr" \
+	--with-user=unbound \
+	--with-run-dir=/var/lib/unbound \
+	--with-conf-file=/var/lib/unbound/unbound.conf \
+	--with-pidfile=/var/run/unbound.pid
+
+define Package/unbound/conffiles
+/etc/config/unbound
+/etc/unbound/unbound.conf
+/etc/unbound/unbound_ext.conf
+/etc/unbound/unbound_srv.conf
+endef
+
+define Build/InstallDev
+	$(INSTALL_DIR) $(1)/usr/include
+	$(INSTALL_DATA) $(PKG_INSTALL_DIR)/usr/include/unbound.h $(1)/usr/include/
+	$(INSTALL_DIR) $(1)/usr/lib
+	$(INSTALL_DATA) $(PKG_INSTALL_DIR)/usr/lib/libunbound.{so*,a,la} $(1)/usr/lib/
+endef
+
+define Package/unbound/install
+	$(INSTALL_DIR) $(1)/usr/sbin
+	$(INSTALL_BIN) \
+		$(PKG_INSTALL_DIR)/usr/sbin/unbound \
+		$(PKG_INSTALL_DIR)/usr/sbin/unbound-checkconf \
+		$(1)/usr/sbin/
+	$(INSTALL_DIR) $(1)/etc/unbound
+	$(INSTALL_DATA) \
+		$(PKG_INSTALL_DIR)/var/lib/unbound/unbound.conf \
+		$(1)/etc/unbound/unbound.conf
+	$(INSTALL_DATA) ./files/root.key $(1)/etc/unbound/root.key
+	$(INSTALL_DATA) ./files/unbound_ext.conf $(1)/etc/unbound/unbound_ext.conf
+	$(INSTALL_DATA) ./files/unbound_srv.conf $(1)/etc/unbound/unbound_srv.conf
+	$(INSTALL_DIR) $(1)/etc/config
+	$(INSTALL_DATA) ./files/unbound.uci $(1)/etc/config/unbound
+	$(INSTALL_DIR) $(1)/etc/hotplug.d/ntp
+	$(INSTALL_BIN)  ./files/unbound.ntpd $(1)/etc/hotplug.d/ntp/25-unbound
+	$(INSTALL_DIR) $(1)/etc/init.d
+	$(INSTALL_BIN)  ./files/unbound.init $(1)/etc/init.d/unbound
+	$(INSTALL_DIR) $(1)/usr/lib/unbound
+	$(INSTALL_DATA) ./files/defaults.sh $(1)/usr/lib/unbound/defaults.sh
+	$(INSTALL_DATA) ./files/dnsmasq.sh $(1)/usr/lib/unbound/dnsmasq.sh
+	$(INSTALL_DATA) ./files/iptools.sh $(1)/usr/lib/unbound/iptools.sh
+	$(INSTALL_BIN)  ./files/odhcpd.sh $(1)/usr/lib/unbound/odhcpd.sh
+	$(INSTALL_DATA) ./files/odhcpd.awk $(1)/usr/lib/unbound/odhcpd.awk
+	$(INSTALL_DATA) ./files/stopping.sh $(1)/usr/lib/unbound/stopping.sh
+	$(INSTALL_DATA) ./files/unbound.sh $(1)/usr/lib/unbound/unbound.sh
+endef
+
+define Package/unbound-anchor/install
+	$(INSTALL_DIR) $(1)/usr/sbin
+	$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/sbin/unbound-anchor $(1)/usr/sbin/
+endef
+
+define Package/unbound-control/install
+	$(INSTALL_DIR) $(1)/usr/sbin
+	$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/sbin/unbound-control $(1)/usr/sbin/
+endef
+
+define Package/unbound-control-setup/install
+	$(INSTALL_DIR) $(1)/usr/sbin
+	$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/sbin/unbound-control-setup $(1)/usr/sbin/
+endef
+
+define Package/unbound-host/install
+	$(INSTALL_DIR) $(1)/usr/sbin
+	$(INSTALL_BIN) $(PKG_INSTALL_DIR)/usr/sbin/unbound-host $(1)/usr/sbin/
+endef
+
+define Package/libunbound/install
+	$(INSTALL_DIR) $(1)/usr/lib
+	$(INSTALL_DATA) $(PKG_INSTALL_DIR)/usr/lib/libunbound.so.* $(1)/usr/lib/
+endef
+
+$(eval $(call BuildPackage,unbound))
+$(eval $(call BuildPackage,unbound-anchor))
+$(eval $(call BuildPackage,unbound-control))
+$(eval $(call BuildPackage,unbound-control-setup))
+$(eval $(call BuildPackage,unbound-host))
+$(eval $(call BuildPackage,libunbound))
+

+ 428 - 0
package/network/services/unbound/files/README.md

@@ -0,0 +1,428 @@
+# Unbound Recursive DNS Server with UCI
+
+## Unbound Description
+[Unbound](https://www.unbound.net/) is a validating, recursive, and caching DNS resolver. The C implementation of Unbound is developed and maintained by [NLnet Labs](https://www.nlnetlabs.nl/). It is based on ideas and algorithms taken from a java prototype developed by Verisign labs, Nominet, Kirei and ep.net. Unbound is designed as a set of modular components, so that also DNSSEC (secure DNS) validation and stub-resolvers (that do not run as a server, but are linked into an application) are easily possible.
+
+## Package Overview
+OpenWrt default build uses [dnsmasq](http://www.thekelleys.org.uk/dnsmasq/docs/dnsmasq-man.html) for DNS forwarding and DHCP. With a forward only resolver, dependence on the upstream recursors may be cause for concern. They are often provided by the ISP, and some users have switched to public DNS providers. Either way may result in problems due to performance, "snoop-vertising", hijacking (MiM), and other causes. Running a recursive resolver or resolver capable of TLS may be a solution.
+
+Unbound may be useful on consumer grade embedded hardware. It is fully DNSSEC and TLS capable. It is _intended_ to be a recursive resolver only. NLnet Labs [NSD](https://www.nlnetlabs.nl/projects/nsd/) is _intended_ for the authoritative task. This is different than [ISC Bind](https://www.isc.org/downloads/bind/) and its inclusive functions. Unbound configuration effort and memory consumption may be easier to control. A consumer could have their own recursive resolver with 8/64 MB router, and remove potential issues from forwarding resolvers outside of their control.
+
+This package builds on Unbounds capabilities with OpenWrt UCI. Not every Unbound option is in UCI, but rather, UCI simplifies the combination of related options. Unbounds native options are bundled and balanced within a smaller set of choices. Options include resources, DNSSEC, access control, and some TTL tweaking. The UCI also provides an escape option and works at the raw "unbound.conf" level.
+
+## HOW TO: Ad Blocking
+The UCI scripts will work with [net/adblock](https://github.com/openwrt/packages/blob/master/net/adblock/files/README.md), if it is installed and enabled. Its all detected and integrated automatically. In brief, the adblock scripts create distinct local-zone files that are simply included in the unbound conf file during UCI generation. If you don't want this, then disable adblock or reconfigure adblock to not send these files to Unbound.
+
+A few tweaks may be needed to enhance the realiability and effectiveness. Ad Block option for delay time may need to be set for upto one minute (adb_triggerdelay), because of boot up race conditions with interfaces calling Unbound restarts. Also many smart devices (TV, microwave, or refigerator) will also use public DNS servers either as a bypass or for certain connections in general. If you wish to force exclusive DNS to your router, then you will need a firewall rule for example:
+
+**/etc/config/firewall**:
+```
+config rule
+  option name 'Block-Public-DNS'
+  option enabled '1'
+  option src 'lan'
+  option dest 'wan'
+  option dest_port '53 853 5353'
+  option proto 'tcpudp'
+  option family 'any'
+  option target 'REJECT'
+```
+
+## HOW TO: Integrate with DHCP
+Some UCI options and scripts help Unbound to work with DHCP servers to load the local DNS. The examples provided here are serial dnsmasq-unbound, parallel dnsmasq-unbound, and unbound scripted with odhcpd.
+
+### Serial dnsmasq
+In this case, dnsmasq is not changed *much* with respect to the default [OpenWrt](https://openwrt.org/docs/guide-user/base-system/dns_configuration) configuration. Here dnsmasq is forced to use the local Unbound instance as the lone upstream DNS server, instead of your ISP. This may be the easiest implementation, but performance degradation can occur in high volume networks. Unbound and dnsmasq effectively have the same information in memory, and all transfers are double handled.
+
+**/etc/config/unbound**:
+```
+config unbound
+  option add_local_fqdn '0'
+  option add_wan_fqdn '0'
+  option dhcp_link 'none'
+  # dnsmasq should not forward your domain to unbound, but if...
+  option domain 'yourdomain'
+  option domain_type 'refuse'
+  option listen_port '1053'
+  ...
+```
+
+**/etc/config/dhcp**:
+```
+config dnsmasq
+  option domain 'yourdomain'
+  option noresolv '1'
+  option resolvfile '/tmp/resolv.conf.auto'
+  option port '53'
+  list server '127.0.0.1#1053'
+  list server '::1#1053'
+  ...
+```
+
+### Parallel dnsmasq
+In this case, Unbound serves your local network directly for all purposes. It will look over to dnsmasq for DHCP-DNS resolution. Unbound is generally accessible on port 53, and dnsmasq is only accessed at 127.0.0.1:1053 by Unbound. Although you can dig/drill/nslookup remotely with the proper directives.
+
+**/etc/config/unbound**:
+```
+config unbound
+  option dhcp_link 'dnsmasq'
+  option listen_port '53'
+  ...
+```
+
+**/etc/config/dhcp**:
+```
+config dnsmasq
+  option domain 'yourdomain'
+  option noresolv '1'
+  option resolvfile '/tmp/resolv.conf.auto'
+  option port '1053'
+  ...
+
+config dhcp 'lan'
+  # dnsmasq may not issue DNS option if not std. configuration
+  list dhcp_option 'option:dns-server,0.0.0.0'
+  ...
+```
+
+### Unbound and odhcpd
+You may ask, "can Unbound replace dnsmasq?" You can have DHCP-DNS records with Unbound and [odhcpd](https://github.com/openwrt/odhcpd/blob/master/README) only. The UCI scripts will allow Unbound to act like dnsmasq. When odhcpd configures each DHCP lease, it will call a script. The script provided with Unbound will read the lease file for DHCP-DNS records. The unbound-control application is required, because simply rewriting conf-files and restarting unbound is too much overhead.
+- Default OpenWrt has dnsmasq+odhcpd with `odhcpd-ipv6only` limited to DHCPv6.
+- If you use dnsmasq+odhcpd together, then use dnsmasq serial or parallel methods above.
+- You must install package `odhcpd` (full) to use odhcpd alone.
+- You must install package `unbound-control` to load and unload leases.
+- Remember to uninstall (or disable) dnsmasq when you won't use it.
+
+**/etc/config/unbound**:
+```
+config unbound
+  # name your router in DNS
+  option add_local_fqdn '1'
+  option add_wan_fqdn '1'
+  option dhcp_link 'odhcpd'
+  # add SLAAC inferred from DHCPv4
+  option dhcp4_slaac6 '1'
+  option domain 'lan'
+  option domain_type 'static'
+  option listen_port '53'
+  option rebind_protection '1'
+  # install unbound-control and set this
+  option unbound_control '1'
+  ...
+```
+
+**/etc/config/dhcp**:
+```
+config dhcp 'lan'
+  option dhcpv4 'server'
+  option dhcpv6 'server'
+  option interface 'lan'
+  option leasetime '12h'
+  option ra 'server'
+  option ra_management '1'
+  ...
+
+config odhcpd 'odhcpd'
+  option maindhcp '1'
+  option leasefile '/var/lib/odhcpd/dhcp.leases'
+  # this is where the magic happens
+  option leasetrigger '/usr/lib/unbound/odhcpd.sh'
+```
+
+## HOW TO: Manual Override
+Yes, there is a UCI to disable the rest of Unbound UCI. However, OpenWrt or LEDE are targeted at embedded machines with flash ROM. The initialization scripts do a few things to protect flash ROM.
+
+### Completely Manual (almost)
+All of `/etc/unbound` (persistent, ROM) is copied to `/var/lib/unbound` (tmpfs, RAM). Edit your manual `/etc/unbound/unbound.conf` to reference this `/var/lib/unbound` location for included files. Note in preparation for a jail, `/var/lib/unbound` is `chown unbound`. Configure for security in`/etc/unbound/unbound.conf` with options `username:unbound` and `chroot:/var/lib/unbound`.
+
+Keep the DNSKEY updated with your choice of flash activity. `root.key` maintenance for DNSKEY RFC5011 would be hard on flash. Unbound natively updates frequently. It also creates and destroys working files in the process. In `/var/lib/unbound` this is no problem, but it would be gone at the next reboot. If you have DNSSEC (validator) active, then you should consider the age UCI option. Choose how many days to copy from `/var/lib/unbound/root.key` (tmpfs) to `/etc/unbound/root.key` (flash).
+
+**/etc/config/unbound**:
+```
+config unbound
+  option manual_conf '1'
+  option root_age '9'
+  # end
+```
+
+### Hybrid Manual/UCI
+You like the UCI. Yet, you need to add some difficult to standardize options, or just are not ready to make a UCI request yet. The files `/etc/unbound/unbound_srv.conf` and `/etc/unbound/unbound_ext.conf` will be copied to Unbounds chroot directory and included during auto generation.
+
+The file `unbound_srv.conf` will be added into the `server:` clause. The file `unbound_ext.conf` will be added to the end of all configuration. It is for extended `forward-zone:`, `stub-zone:`, `auth-zone:`, and `view:` clauses. You can also disable unbound-control in the UCI which only allows "localhost" connections unencrypted, and then add an encrypted remote `control:` clause.
+
+## HOW TO: Cache Zone Files
+Unbound has the ability to AXFR a whole zone from an authoritative server to prefetch the zone. This can speed up access to common zones. Some may have special bandwidth concerns for DNSSEC overhead. The following is a generic example. UCI defaults include the [root](https://www.internic.net/domain/) zone, but it is disabled as a ready to go example.
+
+**/etc/config/unbound**:
+```
+config zone
+  option enabled '1'
+  option fallback '1'
+  option url_dir 'https://asset-management.it.example.com/zones/'
+  option zone_type 'auth_zone'
+  list server 'ns1.it.example.com'
+  list server 'ns2.it.example.com'
+  list zone_name 'example.com'
+```
+
+## HOW TO: TLS Over DNS
+Unbound can use TLS as a client or server. UCI supports Unbound as a forwarding client with TLS. Servers are more complex and need manual configuration. This may be desired for privacy against stealth tracking. Some public DNS servers seem to advertise help in this quest. If your looking for a better understanding, then some information can be found at [Cloudflare](https://www.cloudflare.com/) DNS [1.1.1.1](https://1.1.1.1/). The following is a generic example. You can mix providers by using complete server specificaiton to override the zones common port and certificate domain index.
+
+**NOTICE:** Unbound requires openssl-1.1.0 to verify host certificates. OpenWrt at present is configured with openssl-1.0.2. Connections will be over TLS, but theoretically, certificates may not be from a trusted source. See report [Unbound #658](https://www.nlnetlabs.nl/bugs-script/show_bug.cgi?id=658). When this is resolved, it will be recommended again to install `ca-bundle`, maintain it, and be sure to include the TLS certificate domain index with the host addresses.
+
+**/etc/config/unbound**:
+```
+config zone
+  option enabled '1'
+  # question: do you want to recurse when TLS fails or not?
+  option fallback '0'
+  option tls_index 'dns.example.net'
+  option tls_port '853'
+  option tls_upstream '1'
+  option zone_type 'forward_zone'
+  # these servers assume a common TLS port/index
+  list server '192.0.2.53'
+  list server '2001:db8::53'
+  # this alternate server is fully specified inline
+  list server '192.0.2.153@443#dns.alternate.example.org'
+  list zone_name '.'
+```
+
+## Complete List of UCI Options
+**/etc/config/unbound**:
+```
+config unbound
+  Currently only one instance is supported.
+
+  option add_extra_dns '0'
+    Level. Execute traditional DNS overrides found in `/etc/config/dhcp`.
+    Optional so you may use other Unbound conf or redirect to NSD instance.
+    0 - Ignore `/etc/config/dhcp`
+    1 - Use only 'domain' clause (host records)
+    2 - Use 'domain', 'mxhost', and 'srvhost' clauses
+    3 - Use all of 'domain', 'mxhost', 'srvhost', and 'cname' clauses
+
+  option add_local_fqdn '0'
+    Level. This puts your routers host name in the LAN (local) DNS.
+    Each level is more detailed and comprehensive.
+    0 - Disabled
+    1 - Host Name on only the primary address
+    2 - Host Name on all addresses found (except link)
+    3 - FQDN and host name on all addresses (except link)
+    4 - Above and interfaces named <iface>.<hostname>.<domain>
+
+  option add_wan_fqdn '0'
+    Level. Same as previous option only this applies to the WAN. WAN
+    are inferred by a UCI `config dhcp` entry that contains the line
+    option ignore '1'.
+
+  option dns64 '0'
+    Boolean. Enable DNS64 through Unbound in order to bridge networks
+    that are IPV6 only and IPV4 only (see RFC6052).
+
+  option dns64_prefix '64:ff9b::/96'
+    IPV6 Prefix. The IPV6 prefix wrapped on the IPV4 address for DNS64.
+    You should use RFC6052 "well known" address, unless you also
+    redirect to a proxy or gateway for your NAT64.
+
+  option dhcp_link 'none'
+    Program Name. Link to one of the supported programs we have scripts
+    for. You may also need to install a trigger script in the DHCP
+    servers configuration. See HOW TO above.
+
+  option dhcp4_slaac6 '0'
+    Boolean. Some DHCP servers do this natively (dnsmasq). Otherwise
+    the script provided with this package will try to fabricate SLAAC
+    IP6 addresses from DHCPv4 MAC records.
+
+  option domain 'lan'
+    Unbound local-zone: <domain> <type>. This is used to suffix all
+    host records, and maintain a local zone. When dnsmasq is dhcp_link
+    however, then this option is ignored (dnsmasq does it all).
+
+  option domain_type 'static'
+    Unbound local-zone: <domain> <type>. This allows you to lock
+    down or allow forwarding of the local zone. Notable types:
+    static - typical single router setup much like OpenWrt dnsmasq default
+    refuse - to answer overtly with DNS code REFUSED
+    deny - to drop queries for the local zone
+    transparent - to use your manually added forward-zone: or stub-zone: clause
+
+  option edns_size '1280'
+    Bytes. Extended DNS is necessary for DNSSEC. However, it can run
+    into MTU issues. Use this size in bytes to manage drop outs.
+
+  option extended_stats '0'
+    Boolean. extended statistics are printed from unbound-control.
+    Keeping track of more statistics takes time.
+
+  option hide_binddata '1'
+    Boolean. If enabled version.server, version.bind, id.server, and
+    hostname.bind queries are refused.
+
+  option listen_port '53'
+    Port. Incoming. Where Unbound will listen for queries.
+
+  option localservice '1'
+    Boolean. Prevent DNS amplification attacks. Only provide access to
+    Unbound from subnets this machine has interfaces on.
+
+  option manual_conf '0'
+    Boolean. Skip all this UCI nonsense. Manually edit the
+    configuration. Make changes to /etc/unbound/unbound.conf.
+
+  option protocol 'mixed'
+    Unbound can limit its protocol used for recursive queries.
+    ip4_only - limit issues if you do not have native IPv6
+    ip6_only - test environment only; could cauase problems
+    ip6_prefer - both IPv4 and IPv6 but try IPv6 first
+    mixed - both IPv4 and IPv6
+    default - Unbound built-in defaults
+
+  option query_minimize '0'
+    Boolean. Enable a minor privacy option. Don't let each server know
+    the next recursion. Query one piece at a time.
+
+  option query_min_strict '0'
+    Boolean. Query minimize is best effort and will fall back to normal
+    when it must. This option prevents the fall back, but less than
+    standard name servers will fail to resolve their domains.
+
+  option rebind_localhost '0'
+    Boolean. Prevent loopback "127.0.0.0/8" or "::1/128" responses.
+    These may used by black hole servers for good purposes like
+    ad-blocking or parental access control. Obviously these responses
+    also can be used to for bad purposes.
+
+  option rebind_protection '1'
+    Level. Block your local address responses from global DNS. A poisoned
+    reponse within "192.168.0.0/24" or "fd00::/8" could turn a local browser
+    into an external attack proxy server. IP6 GLA may be vulnerable also.
+    0 - Off
+    1 - Only RFC 1918 and 4193 responses blocked
+    2 - Plus GLA /64 on designated interface(s)
+    3 - Plus DHCP-PD range passed down interfaces (not implemented)
+
+  option recursion 'passive'
+    Unbound has many options for recrusion but UCI is bundled for simplicity.
+    passive - slower until cache fills but kind on CPU load
+    default - Unbound built-in defaults
+    aggressive - uses prefetching to handle more requests quickly
+
+  option resource 'small'
+    Unbound has many options for resources but UCI is bundled for simplicity.
+    tiny - similar to published memory restricted configuration
+    small - about half of medium
+    medium - similar to default, but fixed for consistency
+    default - Unbound built-in defaults
+    large - about double of medium
+
+  option root_age '9'
+    Days. >90 Disables. Age limit for Unbound root data like root
+    DNSSEC key. Unbound uses RFC 5011 to manage root key. This could
+    harm flash ROM. This activity is mapped to "tmpfs," but every so
+    often it needs to be copied back to flash for the next reboot.
+
+  option ttl_min '120'
+    Seconds. Minimum TTL in cache. Recursion can be expensive without
+    cache. A low TTL is normal for server migration. A low TTL can be
+    abused for snoop-vertising (DNS hit counts; recording query IP).
+    Typical to configure maybe 0~300, but 1800 is the maximum accepted.
+
+  option unbound_control '0'
+    Level. Enables unbound-control application access ports.
+    0 - No unbound-control Access, or add your own in 'unbound_ext.conf'
+    1 - Unencrypted Local Host Access
+    2 - SSL Local Host Access; auto unbound-control-setup if available
+    3 - SSL Network Access; auto unbound-control-setup if available
+    4 - SSL Network Access; static key/pem files must already exist
+
+  option validator '0'
+    Boolean. Enable DNSSEC. Unbound names this the "validator" module.
+
+  option validator_ntp '1'
+    Boolean. Disable DNSSEC time checks at boot. Once NTP confirms
+    global real time, then DNSSEC is restarted at full strength. Many
+    embedded devices don't have a real time power off clock. NTP needs
+    DNS to resolve servers. This works around the chicken-and-egg.
+
+  option verbosity '1'
+    Level. Sets Unbounds logging intensity.
+
+  list domain_insecure 'ntp.somewhere.org'
+    Domain. Domains that you wish to skip DNSSEC. It is one way around NTP
+    chicken and egg. Your DHCP servered domains are automatically included.
+
+  list trigger_interface 'lan' 'wan'
+    Interface (logical). This option is a work around for netifd/procd
+    interaction with WAN DHCPv6. Minor RA or DHCP changes in IP6 can
+    cause netifd to execute procd interface reload. Limit Unbound procd
+    triggers to LAN and WAN (IP4 only) to prevent restart @2-3 minutes.
+
+
+config zone
+  Create Unbounds forward-zone:, stub-zone:, or auth-zone: clauses
+
+  option enabled 1
+    Boolean. Enable the zone clause.
+
+  option fallback 1
+    Boolean. Permit normal recursion when the narrowly selected servers
+    in this zone are unresponsive or return empty responses. Disable, if
+    there are security concerns (forward only internal to organization).
+
+  option port 53
+    Port. Servers are contact on this port for plain DNS operations.
+
+  option resolv_conf 0
+    Boolean. Use "resolv.conf" as it was filled by the DHCP client. This
+    can be used to forward zones within your ISP (mail.example.net) or that
+    have co-located services (streamed-movies.example.com). Recursion may
+    not yield the most local result, but forwarding may instead.
+
+  option tls_index (n/a)
+    Domain. Name TLS certificates are signed for (dns.example.net). If this
+    option is ommitted, then Unbound will make the connection but not
+    validate it.
+
+  option tls_port 853
+    Port. Servers are contact on this port for DNS over TLS operations.
+
+  option tls_upstream 0
+    Boolean. Use TLS to contact the zone server.
+
+  option url_dir
+    String. http or https path, directory part only, to the zone file for
+    auth_zone type only. Files "${zone_name}.zone" are expect in this path.
+
+  option zone_type (n/a)
+    State. Required field or the clause is effectively disabled. Check
+    Unbound documentation for clarity (unbound-conf).
+    auth_zone     - prefetch whole zones from authoritative server (ICANN)
+    forward_zone  - forward queries in these domains to the listed servers
+    stub_zone     - force recursion of these domains to the listed servers
+
+  list server (n/a)
+    IP. Every zone must have one server. Stub and forward require IP to
+    prevent chicken and egg (due to UCI simplicity). Authoritative prefetch
+    may use a server name.
+
+  list zone_name
+    Domain. Every zone must represent some part of the DNS tree. It can be
+    all of it "." or you internal organization domain "example.com." Within
+    each zone clause all zone names will be matched to all servers.
+```
+
+## Replaced Options
+  config unbound / option prefetch_root
+    List the domains in a zone with type auth_zone and fill in the server
+    or url fields. Root zones are ready but disabled in default install UCI.
+
+  config unbound / list domain_forward
+    List the domains in a zone with type forward_zone and enable the
+    resolv_conf option.
+
+  config unbound / list rebind_interface
+    Enable rebind_protection at 2 and all DHCP interfaces are also
+    protected for IPV6 GLA (parallel to subnets in add_local_fqdn).
+

+ 66 - 0
package/network/services/unbound/files/defaults.sh

@@ -0,0 +1,66 @@
+#!/bin/sh
+##############################################################################
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# 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.
+#
+# Copyright (C) 2016 Eric Luehrsen
+#
+##############################################################################
+
+# where are we?
+UB_LIBDIR=/usr/lib/unbound
+UB_VARDIR=/var/lib/unbound
+UB_PIDFILE=/var/run/unbound.pid
+
+# conf deconstructed
+UB_TOTAL_CONF=$UB_VARDIR/unbound.conf
+UB_CORE_CONF=$UB_VARDIR/server.conf.tmp
+UB_HOST_CONF=$UB_VARDIR/host.conf.tmp
+UB_DHCP_CONF=$UB_VARDIR/dhcp.conf
+UB_ZONE_CONF=$UB_VARDIR/zone.conf.tmp
+UB_CTRL_CONF=$UB_VARDIR/ctrl.conf.tmp
+UB_SRVMASQ_CONF=$UB_VARDIR/dnsmasq_srv.conf.tmp
+UB_EXTMASQ_CONF=$UB_VARDIR/dnsmasq_ext.conf.tmp
+UB_SRV_CONF=$UB_VARDIR/unbound_srv.conf
+UB_EXT_CONF=$UB_VARDIR/unbound_ext.conf
+
+# TLS keys
+UB_TLS_KEY_FILE="TLS server UCI not implemented"
+UB_TLS_PEM_FILE="TLS server UCI not implemented"
+UB_TLS_FWD_FILE=$UB_VARDIR/ca-certificates.crt
+UB_TLS_ETC_FILE=/etc/ssl/certs/ca-certificates.crt
+
+# start files
+UB_RKEY_FILE=$UB_VARDIR/root.key
+UB_RHINT_FILE=$UB_VARDIR/root.hints
+UB_TIME_FILE=$UB_VARDIR/hotplug.time
+UB_SKIP_FILE=$UB_VARDIR/skip.time
+
+# control app keys
+UB_CTLKEY_FILE=$UB_VARDIR/unbound_control.key
+UB_CTLPEM_FILE=$UB_VARDIR/unbound_control.pem
+UB_SRVKEY_FILE=$UB_VARDIR/unbound_server.key
+UB_SRVPEM_FILE=$UB_VARDIR/unbound_server.pem
+
+# similar default SOA / NS RR as Unbound uses for private ARPA zones
+UB_XSER=$(( $( date +%s ) / 60 ))
+UB_XSOA="7200 IN SOA localhost. nobody.invalid. $UB_XSER 3600 1200 9600 300"
+UB_XNS="7200 IN NS localhost."
+UB_XTXT="7200 IN TXT \"comment=local intranet dns zone\""
+UB_MTXT="7200 IN TXT \"comment=masked internet dns zone\""
+UB_LTXT="7200 IN TXT \"comment=rfc6762 multicast dns zone\""
+
+# helper apps
+UB_ANCHOR=/usr/sbin/unbound-anchor
+UB_CONTROL=/usr/sbin/unbound-control
+UB_CONTROL_CFG="$UB_CONTROL -c $UB_TOTAL_CONF"
+
+##############################################################################
+

+ 309 - 0
package/network/services/unbound/files/dnsmasq.sh

@@ -0,0 +1,309 @@
+#!/bin/sh
+##############################################################################
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# 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.
+#
+# Copyright (C) 2016 Eric Luehrsen
+#
+##############################################################################
+#
+# This crosses over to the dnsmasq UCI file "dhcp" and parses it for fields
+# that will allow Unbound to request local host DNS of dnsmasq. We need to look
+# at the interfaces in "dhcp" and get their subnets. The Unbound conf syntax
+# makes this a little difficult. First in "server:" we need to create private
+# zones for the domain and PTR records. Then we need to create numerous
+# "forward:" clauses to forward those zones to dnsmasq.
+#
+##############################################################################
+
+DM_D_WAN_FQDN=0
+
+DM_LIST_KNOWN_ZONES="invalid"
+DM_LIST_TRN_ZONES=""
+DM_LIST_LOCAL_DATA=""
+DM_LIST_LOCAL_PTR=""
+DM_LIST_FWD_PORTS=""
+DM_LIST_FWD_ZONES=""
+
+##############################################################################
+
+create_local_zone() {
+  local target="$1"
+  local partial domain found
+
+  case $DM_LIST_TRN_ZONES in
+    *"${target}"*)
+      found=1
+      ;;
+
+    *)
+      case $target in
+        [A-Za-z0-9]*.[A-Za-z0-9]*)
+          found=0
+          ;;
+
+        *) # no dots
+          found=1
+          ;;
+      esac
+  esac
+
+
+  if [ $found -eq 0 ] ; then
+    # New Zone! Bundle local-zones: by first two name tiers "abcd.tld."
+    partial=$( echo "$target" | awk -F. '{ j=NF ; i=j-1; print $i"."$j }' )
+    DM_LIST_TRN_ZONES="$DM_LIST_TRN_ZONES $partial"
+    DM_LIST_KNOWN_ZONES="$DM_LIST_KNOWN_ZONES $partial"
+  fi
+}
+
+##############################################################################
+
+create_host_record() {
+  local cfg="$1"
+  local ip name debug_ip
+
+  # basefiles dhcp "domain" clause which means host A, AAAA, and PRT record
+  config_get ip   "$cfg" ip
+  config_get name "$cfg" name
+
+
+  if [ -n "$name" -a -n "$ip" ] ; then
+    create_local_zone "$name"
+
+
+    case $ip in
+      fe[89ab][0-9a-f]:*|169.254.*)
+        debug_ip="$ip@$host"
+        ;;
+
+      [1-9a-f]*:*[0-9a-f])
+        DM_LIST_LOCAL_DATA="$DM_LIST_LOCAL_DATA $name.@@300@@IN@@AAAA@@$ip"
+        DM_LIST_LOCAL_PTR="$DM_LIST_LOCAL_PTR $ip@@300@@$name"
+        ;;
+
+      [1-9]*.*[0-9])
+        DM_LIST_LOCAL_DATA="$DM_LIST_LOCAL_DATA $name.@@300@@IN@@A@@$ip"
+        DM_LIST_LOCAL_PTR="$DM_LIST_LOCAL_PTR $ip@@300@@$name"
+        ;;
+    esac
+  fi
+}
+
+##############################################################################
+
+create_mx_record() {
+  local cfg="$1"
+  local domain relay pref record
+
+  # Insert a static MX record
+  config_get domain "$cfg" domain
+  config_get relay  "$cfg" relay
+  config_get pref   "$cfg" pref 10
+
+
+  if [ -n "$domain" -a -n "$relay" ] ; then
+    create_local_zone "$domain"
+    record="$domain.@@300@@IN@@MX@@$pref@@$relay."
+    DM_LIST_LOCAL_DATA="$DM_LIST_LOCAL_DATA $record"
+  fi
+}
+
+##############################################################################
+
+create_srv_record() {
+  local cfg="$1"
+  local srv target port class weight record
+
+  # Insert a static SRV record such as SIP server
+  config_get srv    "$cfg" srv
+  config_get target "$cfg" target
+  config_get port   "$cfg" port
+  config_get class  "$cfg" class 10
+  config_get weight "$cfg" weight 10
+
+
+  if [ -n "$srv" -a -n "$target" -a -n "$port" ] ; then
+    create_local_zone "$srv"
+    record="$srv.@@300@@IN@@SRV@@$class@@$weight@@$port@@$target."
+    DM_LIST_LOCAL_DATA="$DM_LIST_LOCAL_DATA $record"
+  fi
+}
+
+##############################################################################
+
+create_cname_record() {
+  local cfg="$1"
+  local cname target record
+
+  # Insert static CNAME record
+  config_get cname  "$cfg" cname
+  config_get target "$cfg" target
+
+
+  if [ -n "$cname" -a -n "$target" ] ; then
+    create_local_zone "$cname"
+    record="$cname.@@300@@IN@@CNAME@@$target."
+    DM_LIST_LOCAL_DATA="$DM_LIST_LOCAL_DATA $record"
+  fi
+}
+
+##############################################################################
+
+dnsmasq_local_zone() {
+  local cfg="$1"
+  local fwd_port fwd_domain wan_fqdn
+
+  # dnsmasq domain and interface assignment settings will control config
+  config_get fwd_domain "$cfg" domain
+  config_get fwd_port "$cfg" port
+  config_get wan_fqdn "$cfg" add_wan_fqdn
+
+
+  if [ -n "$wan_fqdn" ] ; then
+    DM_D_WAN_FQDN=$wan_fqdn
+  fi
+
+
+  if [ -n "$fwd_domain" -a -n "$fwd_port" -a ! "${fwd_port:-53}" -eq 53 ] ; then
+    # dnsmasq localhost listening ports (possible multiple instances)
+    DM_LIST_FWD_PORTS="$DM_LIST_FWD_PORTS $fwd_port"
+    DM_LIST_FWD_ZONES="$DM_LIST_FWD_ZONES $fwd_domain"
+  fi
+}
+
+##############################################################################
+
+dnsmasq_local_arpa() {
+  local ifarpa ifsubnet
+
+
+  if [ -n "$UB_LIST_NETW_LAN" ] ; then
+    for ifsubnet in $UB_LIST_NETW_LAN ; do
+      ifarpa=$( domain_ptr_any "${ifsubnet#*@}" )
+      DM_LIST_FWD_ZONES="$DM_LIST_FWD_ZONES $ifarpa"
+    done
+  fi
+
+
+  if [ -n "$UB_LIST_NETW_WAN" -a "$DM_D_WAN_FQDN" -gt 0 ] ; then
+    for ifsubnet in $UB_LIST_NETW_WAN ; do
+      ifarpa=$( domain_ptr_any "${ifsubnet#*@}" )
+      DM_LIST_FWD_ZONES="$DM_LIST_FWD_ZONES $ifarpa"
+    done
+  fi
+}
+
+##############################################################################
+
+dnsmasq_inactive() {
+  local record
+
+
+  if [ "$UB_D_EXTRA_DNS" -gt 0 ] ; then
+    # Parasite from the uci.dhcp.domain clauses
+    DM_LIST_KNOWN_ZONES="$DM_LIST_KNOWN_ZONES $UB_TXT_DOMAIN"
+    config_load dhcp
+    config_foreach create_host_record domain
+
+
+    if [ "$UB_D_EXTRA_DNS" -gt 1 ] ; then
+      config_foreach create_srv_record srvhost
+      config_foreach create_mx_record mxhost
+    fi
+
+
+    if [ "$UB_D_EXTRA_DNS" -gt 2 ] ; then
+      config_foreach create_cname_record cname
+    fi
+
+
+    {
+      echo "# $UB_SRVMASQ_CONF generated by UCI $( date -Is )"
+      if [ -n "$DM_LIST_TRN_ZONES" ] ; then
+        for record in $DM_LIST_TRN_ZONES ; do
+          echo "  local-zone: $record transparent"
+        done
+        echo
+      fi
+      if [ -n "$DM_LIST_LOCAL_DATA" ] ; then
+        for record in $DM_LIST_LOCAL_DATA ; do
+          echo "  local-data: \"${record//@@/ }\""
+        done
+        echo
+      fi
+      if [ -n "$DM_LIST_LOCAL_PTR" ] ; then
+        for record in $DM_LIST_LOCAL_PTR ; do
+          echo "  local-data-ptr: \"${record//@@/ }\""
+        done
+        echo
+      fi
+    } > $UB_SRVMASQ_CONF
+  fi
+}
+
+##############################################################################
+
+dnsmasq_active() {
+  # Look at dnsmasq settings
+  config_load dhcp
+  # Zone for DHCP / SLAAC-PING DOMAIN
+  config_foreach dnsmasq_local_zone dnsmasq
+  # Zone for DHCP / SLAAC-PING ARPA
+  dnsmasq_local_arpa
+
+
+  if [ -n "$DM_LIST_FWD_PORTS" -a -n "$DM_LIST_FWD_ZONES" ] ; then
+    {
+      # Forward to dnsmasq on same host for DHCP lease hosts
+      echo "# $UB_SRVMASQ_CONF generated by UCI $( date -Is )"
+      echo "  do-not-query-localhost: no"
+      echo
+    } > $UB_SRVMASQ_CONF
+
+    echo "# $UB_EXTMASQ_CONF generated by UCI $( date -Is )" > $UB_EXTMASQ_CONF
+
+
+    for fwd_domain in $DM_LIST_FWD_ZONES ; do
+      {
+        # This creates a domain with local privledges
+        echo "  domain-insecure: $fwd_domain"
+        echo "  private-domain: $fwd_domain"
+        echo "  local-zone: $fwd_domain transparent"
+        echo
+      } >> $UB_SRVMASQ_CONF
+
+      {
+        # This is derived from dnsmasq local domain and dhcp service subnets
+        echo "forward-zone:"
+        echo "  name: $fwd_domain"
+        echo "  forward-first: no"
+        for port in $DM_LIST_FWD_PORTS ; do
+          echo "  forward-addr: 127.0.0.1@$port"
+        done
+        echo
+      } >> $UB_EXTMASQ_CONF
+    done
+  fi
+}
+
+##############################################################################
+
+dnsmasq_link() {
+  if [ "$UB_D_DHCP_LINK" = "dnsmasq" ] ; then
+    dnsmasq_active
+
+  else
+    dnsmasq_inactive
+  fi
+}
+
+##############################################################################
+

+ 198 - 0
package/network/services/unbound/files/iptools.sh

@@ -0,0 +1,198 @@
+#!/bin/sh
+##############################################################################
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# 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.
+#
+# Copyright (C) 2016 Eric Luehrsen
+#
+##############################################################################
+#
+# These are iptools that might be useful in a larger package, if provided
+# elsewhere for common use. One example that many may find useful is turning
+# flexible IPV6 colon dividers into PTR. Otherwise these are incomplete and
+# would need robustness improvements for more generic applications.
+#
+##############################################################################
+
+domain_ptr_ip6() {
+  # Get the nibble rounded /CIDR ...ip6.arpa.
+  echo "$1" | awk -F: \
+  'BEGIN { OFS = "" ; }
+  { CIDR = $0 ;
+  sub(/.*\//,"",CIDR) ;
+  CIDR = (CIDR / 4) ;
+  sub(/\/[0-9]+/,"",$0) ;
+  ct_stop = 9 - NF ;
+  for(i=1; i<=NF; i++) {
+    if(length($i) == 0) {
+      for(j=1; j<=ct_stop; j++) { $i = ($i "0000") ; } }
+    else { $i = substr(("0000" $i), length($i)+5-4) ; } } ;
+  y = $0 ;
+  ct_start = length(y) - 32 + CIDR ;
+  for(i=ct_start; i>0; i--) { x = (x substr(y,i,1)) ; } ;
+  gsub(/./,"&\.",x) ;
+  x = (x "ip6.arpa") ;
+  print x }'
+}
+
+##############################################################################
+
+host_ptr_ip6() {
+  # Get complete host ...ip6.arpa.
+  echo "$1" | awk -F: \
+  'BEGIN { OFS = "" ; }
+  { sub(/\/[0-9]+/,"",$0) ;
+  ct_stop = 9 - NF ;
+  for(i=1; i<=NF; i++) {
+    if(length($i) == 0) {
+      for(j=1; j<=ct_stop; j++) { $i = ($i "0000") ; } }
+    else { $i = substr(("0000" $i), length($i)+5-4) ; } } ;
+  y = $0 ;
+  ct_start = length(y);
+  for(i=ct_start; i>0; i--) { x = (x substr(y,i,1)) ; } ;
+  sub(/[0-9]+\//,"",x) ;
+  gsub(/./,"&\.",x) ;
+  x = (x "ip6.arpa") ;
+  print x }'
+}
+
+##############################################################################
+
+domain_ptr_ip4() {
+  # Get the byte rounded /CIDR ...in-addr.arpa.
+  echo "$1" | awk \
+  '{ CIDR = $0 ;
+  sub(/.*\//,"",CIDR) ;
+  CIDR = (CIDR / 8) ;
+  dtxt = $0 ;
+  sub(/\/.*/,"",dtxt) ;
+  split(dtxt, dtxt, ".") ;
+  for(i=1; i<=CIDR; i++) { x = (dtxt[i] "." x) ; }
+  x = (x "in-addr.arpa") ;
+  print x }'
+}
+
+##############################################################################
+
+host_ptr_ip4() {
+  # Get omplete host ...in-addr.arpa.
+  echo "$1" | awk -F. \
+  '{ x = ( $4"."$3"."$2"."$1".in-addr.arpa" ) ;
+  sub(/\/[0-9]+/,"",x) ;
+  print x }'
+}
+
+##############################################################################
+
+valid_subnet6() {
+  case "$1" in
+    # GA
+    [1-9][0-9a-f][0-9a-f][0-9a-f]":"*) echo "ok" ;;
+    # ULA
+    f[cd][0-9a-f][0-9a-f]":"*) echo "ok" ;;
+    # fe80::, ::1, and such
+    *) echo "not" ;;
+  esac
+}
+
+##############################################################################
+
+valid_subnet4() {
+  case "$1" in
+    # Link, Local, and Such
+    169"."254"."*) echo "not" ;;
+    127"."*) echo "not" ;;
+    0"."*) echo "not" ;;
+    255"."*) echo "not" ;;
+    # Other Normal
+    25[0-4]"."[0-9]*) echo "ok" ;;
+    2[0-4][0-9]"."[0-9]*) echo "ok" ;;
+    1[0-9][0-9]"."[0-9]*) echo "ok" ;;
+    [0-9][0-9]"."[0-9]*) echo "ok" ;;
+    [0-9]"."[0-9]*) echo "ok" ;;
+    # Not Right
+    *) echo "not";;
+  esac
+}
+
+##############################################################################
+
+valid_subnet_any() {
+  local subnet=$1
+  local validip4=$( valid_subnet4 $subnet )
+  local validip6=$( valid_subnet6 $subnet )
+
+
+  if [ "$validip4" = "ok" -o "$validip6" = "ok" ] ; then
+    echo "ok"
+  else
+    echo "not"
+  fi
+}
+##############################################################################
+
+private_subnet() {
+  case "$1" in
+    10"."*) echo "ok" ;;
+    172"."1[6-9]"."*) echo "ok" ;;
+    172"."2[0-9]"."*) echo "ok" ;;
+    172"."3[0-1]"."*) echo "ok" ;;
+    192"."168"."*) echo "ok" ;;
+    f[cd][0-9a-f][0-9a-f]":"*) echo "ok" ;;
+    *) echo "not" ;;
+  esac
+}
+
+##############################################################################
+
+domain_ptr_any() {
+  local subnet=$1
+  local arpa validip4 validip6
+
+  validip4=$( valid_subnet4 $subnet )
+  validip6=$( valid_subnet6 $subnet )
+
+
+  if [ "$validip4" = "ok" ] ; then
+    arpa=$( domain_ptr_ip4 "$subnet" )
+  elif [ "$validip6" = "ok" ] ; then
+    arpa=$( domain_ptr_ip6 "$subnet" )
+  fi
+
+
+  if [ -n "$arpa" ] ; then
+    echo $arpa
+  fi
+}
+
+##############################################################################
+
+host_ptr_any() {
+  local subnet=$1
+  local arpa validip4 validip6
+
+  validip4=$( valid_subnet4 $subnet )
+  validip6=$( valid_subnet6 $subnet )
+
+
+  if [ "$validip4" = "ok" ] ; then
+    arpa=$( host_ptr_ip4 "$subnet" )
+  elif [ "$validip6" = "ok" ] ; then
+    arpa=$( host_ptr_ip6 "$subnet" )
+  fi
+
+
+  if [ -n "$arpa" ] ; then
+    echo $arpa
+  fi
+}
+
+##############################################################################
+

+ 209 - 0
package/network/services/unbound/files/odhcpd.awk

@@ -0,0 +1,209 @@
+#!/usr/bin/awk
+##############################################################################
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# 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.
+#
+# Copyright (C) 2016 Eric Luehrsen
+#
+##############################################################################
+#
+# Turn DHCP records into meaningful A, AAAA, and PTR records. Also lift a
+# function from dnsmasq and use DHCPv4 MAC to find IPV6 SLAAC hosts.
+#
+# External Parameters
+#   "hostfile" = where this script will cache host DNS data
+#   "domain" = text domain suffix
+#   "bslaac" = boolean, use DHCPv4 MAC to find GA and ULA IPV6 SLAAC
+#   "bisolt" = boolean, format <host>.<network>.<domain>. so you can isolate
+#   "bconf"  = boolean, write conf file format rather than pipe records
+#
+##############################################################################
+
+/^#/ {
+  # We need to pick out DHCP v4 or v6 records
+  net = $2 ; id = $3 ; cls = $4 ; hst = $5 ; adr = $9 ; adr2 = $10
+  cdr = adr ;
+  cdr2 = adr2 ;
+  sub( /\/.*/, "", adr ) ;
+  sub( /.*\//, "", cdr ) ;
+  sub( /\/.*/, "", adr2 ) ;
+  sub( /.*\//, "", cdr2 ) ;
+
+
+  if ( hst !~ /^[[:alnum:]]([-[:alnum:]]*[[:alnum:]])?$/ ) {
+    # that is not a valid host name (RFC1123)
+    hst = "-" ;
+  }
+
+
+  if ( bisolt == 1 ) {
+    # TODO: this might be better with a substituion option,
+    # or per DHCP pool do-not-DNS option, but its getting busy here.
+    fqdn = net
+    fqdn = sub( /\./, "-", fqdn ) ;
+    fqdn = tolower( hst "." fqdn "." domain ) ;
+  }
+
+  else {
+    fqdn = tolower( hst "." domain ) ;
+  }
+
+
+  if ((cls == "ipv4") && (hst != "-") && (cdr == 32) && (NF == 9)) {
+    # IPV4 ; only for provided hostnames and full /32 assignments
+    # NF=9 ; odhcpd errata in field format without host name
+    ptr = adr ; qpr = "" ; split( ptr, ptr, "." ) ;
+    slaac = slaac_eui64( id ) ;
+
+
+    if ( bconf == 1 ) {
+      x = ( "local-data: \"" fqdn ". 300 IN A " adr "\"" ) ;
+      y = ( "local-data-ptr: \"" adr " 300 " fqdn "\"" ) ;
+      print ( x "\n" y "\n" ) > hostfile ;
+    }
+
+    else {
+      for( i=1; i<=4; i++ ) { qpr = ( ptr[i] "." qpr) ; }
+      x = ( fqdn ". 300 IN A " adr ) ;
+      y = ( qpr "in-addr.arpa. 300 IN PTR " fqdn ) ;
+      print ( x "\n" y ) > hostfile ;
+    }
+
+
+    if (( bslaac == 1 ) && ( slaac != 0 )) {
+      # UCI option to discover IPV6 routed SLAAC addresses
+      # NOT TODO - ping probe take too long when added in awk-rule loop
+      cmd = ( "ip -6 --oneline route show dev " net ) ;
+
+
+      while ( ( cmd | getline adr ) > 0 ) {
+        if (( substr( adr, 1, 5 ) <= "fdff:" ) \
+        && ( index( adr, "anycast" ) == 0 ) \
+        && ( index( adr, "via" ) == 0 )) {
+          # GA or ULA routed addresses only (not LL or MC)
+          sub( /\/.*/, "", adr ) ;
+          adr = ( adr slaac ) ;
+
+
+          if ( split( adr, tmp0, ":" ) > 8 ) {
+            sub( "::", ":", adr ) ;
+          }
+
+
+          if ( bconf == 1 ) {
+            x = ( "local-data: \"" fqdn ". 300 IN AAAA " adr "\"" ) ;
+            y = ( "local-data-ptr: \"" adr " 300 " fqdn "\"" ) ;
+            print ( x "\n" y "\n" ) > hostfile ;
+          }
+
+          else {
+            qpr = ipv6_ptr( adr ) ;
+            x = ( fqdn ". 300 IN AAAA " adr ) ;
+            y = ( qpr ". 300 IN PTR " fqdn ) ;
+            print ( x "\n" y ) > hostfile ;
+          }
+        }
+      }
+
+
+      close( cmd ) ;
+    }
+  }
+
+  else if ((cls != "ipv4") && (hst != "-") && (9 <= NF) && (NF <= 10)) {
+    if (cdr == 128) {
+      if ( bconf == 1 ) {
+        x = ( "local-data: \"" fqdn ". 300 IN AAAA " adr "\"" ) ;
+        y = ( "local-data-ptr: \"" adr " 300 " fqdn "\"" ) ;
+        print ( x "\n" y "\n" ) > hostfile ;
+      }
+
+      else {
+        # only for provided hostnames and full /128 assignments
+        qpr = ipv6_ptr( adr ) ;
+        x = ( fqdn ". 300 IN AAAA " adr ) ;
+        y = ( qpr ". 300 IN PTR " fqdn ) ;
+        print ( x "\n" y ) > hostfile ;
+      }
+    }
+
+    if (cdr2 == 128) {
+      if ( bconf == 1 ) {
+        x = ( "local-data: \"" fqdn ". 300 IN AAAA " adr2 "\"" ) ;
+        y = ( "local-data-ptr: \"" adr2 " 300 " fqdn "\"" ) ;
+        print ( x "\n" y "\n" ) > hostfile ;
+      }
+
+      else {
+        # odhcp puts GA and ULA on the same line (position 9 and 10)
+        qpr2 = ipv6_ptr( adr2 ) ;
+        x = ( fqdn ". 300 IN AAAA " adr2 ) ;
+        y = ( qpr2 ". 300 IN PTR " fqdn ) ;
+        print ( x "\n" y ) > hostfile ;
+      }
+    }
+  }
+
+  else {
+    # dump non-conforming lease records
+  }
+}
+
+##############################################################################
+
+function ipv6_ptr( ipv6,    arpa, ary, end, i, j, new6, sz, start ) {
+  # IPV6 colon flexibility is a challenge when creating [ptr].ip6.arpa.
+  sz = split( ipv6, ary, ":" ) ; end = 9 - sz ;
+
+
+  for( i=1; i<=sz; i++ ) {
+    if( length(ary[i]) == 0 ) {
+      for( j=1; j<=end; j++ ) { ary[i] = ( ary[i] "0000" ) ; }
+    }
+
+    else {
+      ary[i] = substr( ( "0000" ary[i] ), length( ary[i] )+5-4 ) ;
+    }
+  }
+
+
+  new6 = ary[1] ;
+  for( i = 2; i <= sz; i++ ) { new6 = ( new6 ary[i] ) ; }
+  start = length( new6 ) ;
+  for( i=start; i>0; i-- ) { arpa = ( arpa substr( new6, i, 1 ) ) ; } ;
+  gsub( /./, "&\.", arpa ) ; arpa = ( arpa "ip6.arpa" ) ;
+
+  return arpa ;
+}
+
+##############################################################################
+
+function slaac_eui64( mac,    ary, glbit, eui64 ) {
+  if ( length(mac) >= 12 ) {
+    # RFC2373 and use DHCPv4 registered MAC to find SLAAC addresses
+    split( mac , ary , "" ) ;
+    glbit = ( "0x" ary[2] ) ;
+    glbit = sprintf( "%d", glbit ) ;
+    glbit = or( glbit, 2 ) ;
+    ary[2] = sprintf( "%x", glbit ) ;
+    eui64 = ( ary[1] ary[2] ary[3] ary[4] ":" ary[5] ary[6] "ff:fe" ) ;
+    eui64 = ( eui64 ary[7] ary[8] ":" ary[9] ary[10]  ary[11] ary[12] ) ;
+  }
+
+  else {
+    eui64 = 0 ;
+  }
+
+
+  return eui64 ;
+}
+
+##############################################################################
+

+ 117 - 0
package/network/services/unbound/files/odhcpd.sh

@@ -0,0 +1,117 @@
+#!/bin/sh
+##############################################################################
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# 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.
+#
+# Copyright (C) 2016 Eric Luehrsen
+#
+##############################################################################
+#
+# This script facilitates alternate installation of Unbound+odhcpd and no
+# need for dnsmasq. There are some limitations, but it works and is small.
+# The lease file is parsed to make "zone-data:" and "local-data:" entries.
+#
+# config odhcpd 'odhcpd'
+#   option leasetrigger '/usr/lib/unbound/odhcpd.sh'
+#
+##############################################################################
+
+. /lib/functions.sh
+. /usr/lib/unbound/defaults.sh
+
+##############################################################################
+
+odhcpd_zonedata() {
+  local longconf dateconf
+  local dns_ls_add=$UB_VARDIR/dhcp_dns.add
+  local dns_ls_del=$UB_VARDIR/dhcp_dns.del
+  local dhcp_ls_new=$UB_VARDIR/dhcp_lease.new
+  local dhcp_ls_old=$UB_VARDIR/dhcp_lease.old
+  local dhcp_ls_add=$UB_VARDIR/dhcp_lease.add
+  local dhcp_ls_del=$UB_VARDIR/dhcp_lease.del
+
+  local dhcp_link=$( uci_get unbound.@unbound[0].dhcp_link )
+  local dhcp4_slaac6=$( uci_get unbound.@unbound[0].dhcp4_slaac6 )
+  local dhcp_domain=$( uci_get unbound.@unbound[0].domain )
+  local dhcp_origin=$( uci_get dhcp.@odhcpd[0].leasefile )
+
+
+  if [ -f "$UB_TOTAL_CONF" -a -f "$dhcp_origin" \
+       -a "$dhcp_link" = "odhcpd" -a -n "$dhcp_domain" ] ; then
+    # Capture the lease file which could be changing often
+    sort $dhcp_origin > $dhcp_ls_new
+
+
+    if [ ! -f $UB_DHCP_CONF -o ! -f $dhcp_ls_old ] ; then
+      longconf=2
+
+    else
+      dateconf=$(( $( date +%s ) - $( date -r $UB_DHCP_CONF +%s ) ))
+
+
+      if [ $dateconf > 150 ] ; then
+        longconf=1
+      else
+        longconf=0
+      fi
+    fi
+
+
+    if [ $longconf -gt 0 ] ; then
+      # Go through the messy business of coding up A, AAAA, and PTR records
+      # This static conf will be available if Unbound restarts asynchronously
+      awk -v hostfile=$UB_DHCP_CONF -v domain=$dhcp_domain \
+          -v bslaac=$dhcp4_slaac6 -v bisolt=0 -v bconf=1 \
+          -f /usr/lib/unbound/odhcpd.awk $dhcp_ls_new
+    fi
+
+
+    if [ $longconf -lt 2 ] ; then
+      # Deleting and adding all records into Unbound can be a burden in a
+      # high density environment. Use unbound-control incrementally.
+      sort $dhcp_ls_old $dhcp_ls_new $dhcp_ls_new | uniq -u > $dhcp_ls_del
+      awk -v hostfile=$dns_ls_del -v domain=$dhcp_domain \
+          -v bslaac=$dhcp4_slaac6 -v bisolt=0 -v bconf=0 \
+          -f /usr/lib/unbound/odhcpd.awk $dhcp_ls_del
+
+      sort $dhcp_ls_new $dhcp_ls_old $dhcp_ls_old | uniq -u > $dhcp_ls_add
+      awk -v hostfile=$dns_ls_add -v domain=$dhcp_domain \
+          -v bslaac=$dhcp4_slaac6 -v bisolt=0 -v bconf=0 \
+          -f /usr/lib/unbound/odhcpd.awk $dhcp_ls_add
+
+    else
+      awk -v hostfile=$dns_ls_add -v domain=$dhcp_domain \
+          -v bslaac=$dhcp4_slaac6 -v bisolt=0 -v bconf=0 \
+          -f /usr/lib/unbound/odhcpd.awk $dhcp_ls_new
+    fi
+
+
+    if [ -f "$dns_ls_del" ] ; then
+      cat $dns_ls_del | $UB_CONTROL_CFG local_datas_remove
+    fi
+
+
+    if [ -f "$dns_ls_add" ] ; then
+      cat $dns_ls_add | $UB_CONTROL_CFG local_datas
+    fi
+
+
+    # prepare next round
+    mv $dhcp_ls_new $dhcp_ls_old
+    rm -f $dns_ls_del $dns_ls_add $dhcp_ls_del $dhcp_ls_add
+  fi
+}
+
+##############################################################################
+
+odhcpd_zonedata
+
+##############################################################################
+

+ 3 - 0
package/network/services/unbound/files/root.key

@@ -0,0 +1,3 @@
+. IN DS 19036 8 2 49AAC11D7B6F6446702E54A1607371607A1A41855200FD2CE1CDDE32F24E8FB5
+. IN DS 20326 8 2 E06D44B80B8F1D39A95C0B0D7C65D08458E880409BBC683457104237C7F8EC8D
+

+ 127 - 0
package/network/services/unbound/files/stopping.sh

@@ -0,0 +1,127 @@
+#!/bin/sh
+##############################################################################
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# 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.
+#
+# Copyright (C) 2016 Eric Luehrsen
+#
+##############################################################################
+#
+# This component will copy root.key back to /etc/unbound/ periodically, but
+# avoid ROM flash abuse (UCI option).
+#
+##############################################################################
+
+. /usr/lib/unbound/defaults.sh
+
+##############################################################################
+
+roothints_update() {
+  # TODO: Might not be implemented. Unbound doesn't natively update hints.
+  # Unbound philosophy is built in root hints are good for machine life.
+  return 0
+}
+
+##############################################################################
+
+rootkey_update() {
+  local basekey_date rootkey_date rootkey_age filestuff
+  local dnssec=$( uci_get unbound.@unbound[0].validator )
+  local dnssec_ntp=$( uci_get unbound.@unbound[0].validator_ntp )
+  local dnssec_age=$( uci_get unbound.@unbound[0].root_age )
+
+  # fix empty
+  [ -z "$dnssec"     ] && dnssec=0
+  [ -z "$dnssec_ntp" ] && dnssec_ntp=1
+  [ -z "$dnssec_age" ] && dnssec_age=9
+
+
+  if [ "$dnssec_age" -gt 90 -o "$dnssec" -lt 1 ] ; then
+    # Feature disabled
+    return 0
+
+  elif [ "$dnssec_ntp" -gt 0 -a ! -f "$UB_TIME_FILE" ] ; then
+    # We don't have time yet
+    return 0
+  fi
+
+
+  if [ -f /etc/unbound/root.key ] ; then
+    basekey_date=$( date -r /etc/unbound/root.key +%s )
+
+  else
+    # No persistent storage key
+    basekey_date=$( date -d 2000-01-01 +%s )
+  fi
+
+
+  if [ -f "$UB_RKEY_FILE" ] ; then
+    # Unbound maintains it itself
+    rootkey_date=$( date -r $UB_RKEY_FILE +%s )
+    rootkey_age=$(( (rootkey_date - basekey_date) / 86440 ))
+
+  elif [ -x "$UB_ANCHOR" ] ; then
+    # No tmpfs key - use unbound-anchor
+    rootkey_date=$( date -I +%s )
+    rootkey_age=$(( (rootkey_date - basekey_date) / 86440 ))
+    $UB_ANCHOR -a $UB_RKEY_FILE
+
+  else
+    # give up
+    rootkey_age=0
+  fi
+
+
+  if [ "$rootkey_age" -gt "$dnssec_age" ] ; then
+    filestuff=$( cat $UB_RKEY_FILE )
+
+
+    case "$filestuff" in
+      *NOERROR*)
+        # Header comment for drill and dig
+        logger -t unbound -s "root.key updated after $rootkey_age days"
+        cp -p $UB_RKEY_FILE /etc/unbound/root.key
+        ;;
+
+      *"state=2 [  VALID  ]"*)
+        # Comment inline to key for unbound-anchor
+        logger -t unbound -s "root.key updated after $rootkey_age days"
+        cp -p $UB_RKEY_FILE /etc/unbound/root.key
+        ;;
+
+      *)
+        logger -t unbound -s "root.key still $rootkey_age days old"
+        ;;
+    esac
+  fi
+}
+
+##############################################################################
+
+resolv_teardown() {
+  case $( cat /tmp/resolv.conf ) in
+    *"generated by Unbound UCI"*)
+      # our resolver file, reset to auto resolver file.
+      rm -f /tmp/resolv.conf
+      ln -s /tmp/resolv.conf.auto /tmp/resolv.conf
+      ;;
+  esac
+}
+
+##############################################################################
+
+unbound_stop() {
+  resolv_teardown
+  roothints_update
+  rootkey_update
+}
+
+##############################################################################
+

+ 84 - 0
package/network/services/unbound/files/unbound.init

@@ -0,0 +1,84 @@
+#!/bin/sh /etc/rc.common
+##############################################################################
+#
+# Copyright (C) 2016 Michael Hanselmann, Eric Luehrsen
+#
+##############################################################################
+#
+# This init script is just the entry point for Unbound UCI.
+#
+##############################################################################
+
+START=19
+STOP=50
+USE_PROCD=1
+PROG=/usr/sbin/unbound
+
+##############################################################################
+
+boot() {
+  UB_BOOT=1
+  start "$@"
+}
+
+##############################################################################
+
+start_service() {
+  if [ -n "$UB_BOOT" ] ; then
+    # Load procd triggers (rc) and use event IFUP to really start
+    return 0
+  fi
+
+  # complex UCI work
+  . /usr/lib/unbound/unbound.sh
+  unbound_start
+
+  # standard procd clause
+  procd_open_instance "unbound"
+  procd_set_param command $PROG -d -c $UB_TOTAL_CONF
+  procd_set_param respawn
+  procd_close_instance
+}
+
+##############################################################################
+
+stop_service() {
+  # clean up
+  . /usr/lib/unbound/stopping.sh
+  unbound_stop
+
+  # Wait! on restart Unbound may take time writing closure stats to syslog
+  pidof $PROG && sleep 1
+}
+
+##############################################################################
+
+service_triggers() {
+  local legacy=$( uci_get unbound.@unbound[0].trigger )
+  local triggers=$( uci_get unbound.@unbound[0].trigger_interface )
+  local trigger="$triggers $legacy"
+
+  . /usr/lib/unbound/defaults.sh
+
+
+  if [ ! -f "$UB_TOTAL_CONF" -o -n "$UB_BOOT" ] ; then
+    # Unbound is can be a bit heavy, so wait some on first start but any
+    # interface coming up affects the trigger and delay so guarantee start
+    procd_add_raw_trigger "interface.*.up" 3000 /etc/init.d/unbound restart
+
+  elif [ -n "$triggers" ] ; then
+    procd_add_reload_trigger "unbound" "dhcp"
+
+
+    for trigger in $triggers ; do
+      # User selected triggers to restart at any other time
+      procd_add_reload_interface_trigger "$trigger"
+    done
+
+  else
+    procd_add_reload_trigger "unbound" "dhcp"
+  fi
+}
+
+##############################################################################
+

+ 27 - 0
package/network/services/unbound/files/unbound.ntpd

@@ -0,0 +1,27 @@
+#!/bin/sh
+##############################################################################
+#
+# Copyright (C) 2016 Eric Luehrsen
+#
+##############################################################################
+#
+# "Restart" Unbound on hotplug NTP ready:
+# - Only do this the first time when no file exists
+# - Some of Unbound conf options to not reload run time
+# - Change the enable flag for DNSSEC date-time checking
+#
+##############################################################################
+
+# Common file location definitions
+. /usr/lib/unbound/defaults.sh
+
+##############################################################################
+
+if [ ! -f "$UB_TIME_FILE" -a "$ACTION" = stratum ] ; then
+  date -Is > $UB_TIME_FILE
+  /etc/init.d/unbound enabled && /etc/init.d/unbound restart
+  # Yes, hard RESTART. We need to be absolutely sure to enable DNSSEC.
+fi
+
+##############################################################################
+

+ 1443 - 0
package/network/services/unbound/files/unbound.sh

@@ -0,0 +1,1443 @@
+#!/bin/sh
+##############################################################################
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# 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.
+#
+# Copyright (C) 2016 Eric Luehrsen
+#
+##############################################################################
+#
+# Unbound is a full featured recursive server with many options. The UCI
+# provided tries to simplify and bundle options. This should make Unbound
+# easier to deploy. Even light duty routers may resolve recursively instead of
+# depending on a stub with the ISP. The UCI also attempts to replicate dnsmasq
+# features as used in base LEDE/OpenWrt. If there is a desire for more
+# detailed tuning, then manual conf file overrides are also made available.
+#
+##############################################################################
+
+UB_B_SLAAC6_MAC=0
+UB_B_DNSSEC=0
+UB_B_DNS64=0
+UB_B_EXT_STATS=0
+UB_B_GATE_NAME=0
+UB_B_HIDE_BIND=1
+UB_B_LOCL_BLCK=0
+UB_B_LOCL_SERV=1
+UB_B_MAN_CONF=0
+UB_B_NTP_BOOT=1
+UB_B_QUERY_MIN=0
+UB_B_QRY_MINST=0
+UB_B_AUTH_ROOT=0
+
+UB_D_CONTROL=0
+UB_D_DOMAIN_TYPE=static
+UB_D_DHCP_LINK=none
+UB_D_EXTRA_DNS=0
+UB_D_LAN_FQDN=0
+UB_D_PRIV_BLCK=1
+UB_D_PROTOCOL=mixed
+UB_D_RESOURCE=small
+UB_D_RECURSION=passive
+UB_D_VERBOSE=1
+UB_D_WAN_FQDN=0
+
+UB_IP_DNS64="64:ff9b::/96"
+
+UB_N_EDNS_SIZE=1280
+UB_N_RX_PORT=53
+UB_N_ROOT_AGE=9
+
+UB_TTL_MIN=120
+UB_TXT_DOMAIN=lan
+UB_TXT_HOSTNAME=thisrouter
+
+##############################################################################
+
+# reset as a combo with UB_B_NTP_BOOT and some time stamp files
+UB_B_READY=1
+
+# keep track of assignments during inserted resource records
+UB_LIST_NETW_ALL=""
+UB_LIST_NETW_LAN=""
+UB_LIST_NETW_WAN=""
+UB_LIST_INSECURE=""
+UB_LIST_ZONE_SERVERS=""
+UB_LIST_ZONE_NAMES=""
+
+##############################################################################
+
+. /lib/functions.sh
+. /lib/functions/network.sh
+
+. /usr/lib/unbound/defaults.sh
+. /usr/lib/unbound/dnsmasq.sh
+. /usr/lib/unbound/iptools.sh
+
+##############################################################################
+
+bundle_all_networks() {
+  local cfg="$1"
+  local ifname ifdashname validip
+  local subnet subnets subnets4 subnets6
+
+  network_get_subnets  subnets4 "$cfg"
+  network_get_subnets6 subnets6 "$cfg"
+  network_get_device   ifname   "$cfg"
+
+  ifdashname="${ifname//./-}"
+  subnets="$subnets4 $subnets6"
+
+
+  if [ -n "$subnets" ] ; then
+    for subnet in $subnets ; do
+      validip=$( valid_subnet_any $subnet )
+
+
+      if [ "$validip" = "ok" ] ; then
+        UB_LIST_NETW_ALL="$UB_LIST_NETW_ALL $ifdashname@$subnet"
+      fi
+    done
+  fi
+}
+
+##############################################################################
+
+bundle_lan_networks() {
+  local cfg="$1"
+  local ifsubnet ifname ifdashname ignore
+
+  config_get_bool    ignore "$cfg" ignore 0
+  network_get_device ifname "$cfg"
+  ifdashname="${ifname//./-}"
+
+
+  if [ "$ignore" -eq 0 -a -n "$ifdashname" -a -n "$UB_LIST_NETW_ALL" ] ; then
+    for ifsubnet in $UB_LIST_NETW_ALL ; do
+      case $ifsubnet in
+        "${ifdashname}"@*)
+          # Special GLA protection for local block; ULA protected as a catagory
+          UB_LIST_NETW_LAN="$UB_LIST_NETW_LAN $ifsubnet"
+          ;;
+      esac
+    done
+  fi
+}
+
+##############################################################################
+
+bundle_wan_networks() {
+  local ifsubnet
+
+
+  if [ -n "$UB_LIST_NETW_ALL" ] ; then
+    for ifsubnet in $UB_LIST_NETW_ALL ; do
+      case $UB_LIST_NETW_LAN in
+        *"${ifsubnet}"*)
+          # If LAN, then not WAN ...
+          ;;
+
+        *)
+          UB_LIST_NETW_WAN="$UB_LIST_NETW_WAN $ifsubnet"
+          ;;
+      esac
+    done
+  fi
+}
+
+##############################################################################
+
+bundle_resolv_conf_servers() {
+  local resolvers=$( awk '/nameserver/ { print $2 }' /tmp/resolv.conf.auto )
+  UB_LIST_ZONE_SERVERS="$UB_LIST_ZONE_SERVERS $resolvers"
+}
+
+##############################################################################
+
+bundle_zone_names() {
+  UB_LIST_ZONE_NAMES="$UB_LIST_ZONE_NAMES $1"
+}
+
+##############################################################################
+
+bundle_zone_servers() {
+  UB_LIST_ZONE_SERVERS="$UB_LIST_ZONE_SERVERS $1"
+}
+
+##############################################################################
+
+bundle_domain_insecure() {
+  UB_LIST_INSECURE="$UB_LIST_INSECURE $1"
+}
+
+##############################################################################
+
+unbound_mkdir() {
+  local filestuff
+
+
+  if [ "$UB_D_DHCP_LINK" = "odhcpd" ] ; then
+    local dhcp_origin=$( uci_get dhcp.@odhcpd[0].leasefile )
+    local dhcp_dir=$( dirname $dhcp_origin )
+
+
+    if [ ! -d "$dhcp_dir" ] ; then
+      # make sure odhcpd has a directory to write (not done itself, yet)
+      mkdir -p "$dhcp_dir"
+    fi
+  fi
+
+
+  if [ -f $UB_RKEY_FILE ] ; then
+    filestuff=$( cat $UB_RKEY_FILE )
+
+
+    case "$filestuff" in
+      *"state=2 [  VALID  ]"*)
+        # Lets not lose RFC 5011 tracking if we don't have to
+        cp -p $UB_RKEY_FILE $UB_RKEY_FILE.keep
+        ;;
+    esac
+  fi
+
+
+  # Blind copy /etc/unbound to /var/lib/unbound
+  mkdir -p $UB_VARDIR
+  rm -f $UB_VARDIR/dhcp_*
+  touch $UB_TOTAL_CONF
+  cp -p /etc/unbound/* $UB_VARDIR/
+
+
+  if [ ! -f $UB_RHINT_FILE ] ; then
+    if [ -f /usr/share/dns/root.hints ] ; then
+      # Debian-like package dns-root-data
+      cp -p /usr/share/dns/root.hints $UB_RHINT_FILE
+
+    elif [ "$UB_B_READY" -eq 0 ] ; then
+      logger -t unbound -s "default root hints (built in root-servers.net)"
+    fi
+  fi
+
+
+  if [ ! -f $UB_RKEY_FILE ] ; then
+    if [ -f /usr/share/dns/root.key ] ; then
+      # Debian-like package dns-root-data
+      cp -p /usr/share/dns/root.key $UB_RKEY_FILE
+
+    elif [ -x $UB_ANCHOR ] ; then
+      $UB_ANCHOR -a $UB_RKEY_FILE
+
+    elif [ "$UB_B_READY" -eq 0 ] ; then
+      logger -t unbound -s "default trust anchor (built in root DS record)"
+    fi
+  fi
+
+
+  if [ -f $UB_RKEY_FILE.keep ] ; then
+    # root.key.keep is reused if newest
+    cp -u $UB_RKEY_FILE.keep $UB_RKEY_FILE
+    rm -f $UB_RKEY_FILE.keep
+  fi
+
+
+  if [ -f $UB_TLS_ETC_FILE ] ; then
+    # copy the cert bundle into jail
+    cp -p $UB_TLS_ETC_FILE $UB_TLS_FWD_FILE
+  fi
+
+
+  # Ensure access and prepare to jail
+  chown -R unbound:unbound $UB_VARDIR
+  chmod 755 $UB_VARDIR
+  chmod 644 $UB_VARDIR/*
+
+
+  if [ -f $UB_CTLKEY_FILE -o -f $UB_CTLPEM_FILE \
+    -o -f $UB_SRVKEY_FILE -o -f $UB_SRVPEM_FILE ] ; then
+    # Keys (some) exist already; do not create new ones
+    chmod 640 $UB_CTLKEY_FILE $UB_CTLPEM_FILE \
+              $UB_SRVKEY_FILE $UB_SRVPEM_FILE
+
+  elif [ -x /usr/sbin/unbound-control-setup ] ; then
+    case "$UB_D_CONTROL" in
+      [2-3])
+        # unbound-control-setup for encrypt opt. 2 and 3, but not 4 "static"
+        /usr/sbin/unbound-control-setup -d $UB_VARDIR
+
+        chown -R unbound:unbound  $UB_CTLKEY_FILE $UB_CTLPEM_FILE \
+                                  $UB_SRVKEY_FILE $UB_SRVPEM_FILE
+
+        chmod 640 $UB_CTLKEY_FILE $UB_CTLPEM_FILE \
+                  $UB_SRVKEY_FILE $UB_SRVPEM_FILE
+
+        cp -p $UB_CTLKEY_FILE /etc/unbound/unbound_control.key
+        cp -p $UB_CTLPEM_FILE /etc/unbound/unbound_control.pem
+        cp -p $UB_SRVKEY_FILE /etc/unbound/unbound_server.key
+        cp -p $UB_SRVPEM_FILE /etc/unbound/unbound_server.pem
+        ;;
+    esac
+  fi
+
+
+  if [ -f "$UB_TIME_FILE" ] ; then
+    # NTP is done so its like you actually had an RTC
+    UB_B_READY=1
+    UB_B_NTP_BOOT=0
+
+  elif [ "$UB_B_NTP_BOOT" -eq 0 ] ; then
+    # time is considered okay on this device (ignore /etc/hotplug/ntpd/unbound)
+    date -Is > $UB_TIME_FILE
+    UB_B_READY=0
+    UB_B_NTP_BOOT=0
+
+  else
+    # DNSSEC-TIME will not reconcile
+    UB_B_READY=0
+    UB_B_NTP_BOOT=1
+  fi
+}
+
+##############################################################################
+
+unbound_control() {
+  echo "# $UB_CTRL_CONF generated by UCI $( date -Is )" > $UB_CTRL_CONF
+
+
+  if [ "$UB_D_CONTROL" -gt 1 ] ; then
+    if [ ! -f $UB_CTLKEY_FILE -o ! -f $UB_CTLPEM_FILE \
+      -o ! -f $UB_SRVKEY_FILE -o ! -f $UB_SRVPEM_FILE ] ; then
+      # Key files need to be present; if unbound-control-setup was found, then
+      # they might have been made during unbound_makedir() above.
+      UB_D_CONTROL=0
+    fi
+  fi
+
+
+  case "$UB_D_CONTROL" in
+    1)
+      {
+        # Local Host Only Unencrypted Remote Control
+        echo "remote-control:"
+        echo "  control-enable: yes"
+        echo "  control-use-cert: no"
+        echo "  control-interface: 127.0.0.1"
+        echo "  control-interface: ::1"
+        echo
+      } >> $UB_CTRL_CONF
+      ;;
+
+    2)
+      {
+        # Local Host Only Encrypted Remote Control
+        echo "remote-control:"
+        echo "  control-enable: yes"
+        echo "  control-use-cert: yes"
+        echo "  control-interface: 127.0.0.1"
+        echo "  control-interface: ::1"
+        echo "  server-key-file: $UB_SRVKEY_FILE"
+        echo "  server-cert-file: $UB_SRVPEM_FILE"
+        echo "  control-key-file: $UB_CTLKEY_FILE"
+        echo "  control-cert-file: $UB_CTLPEM_FILE"
+        echo
+      } >> $UB_CTRL_CONF
+      ;;
+
+    [3-4])
+      {
+        # Network Encrypted Remote Control
+        # (3) may auto setup and (4) must have static key/pem files
+        # TODO: add UCI list for interfaces to bind
+        echo "remote-control:"
+        echo "  control-enable: yes"
+        echo "  control-use-cert: yes"
+        echo "  control-interface: 0.0.0.0"
+        echo "  control-interface: ::0"
+        echo "  server-key-file: $UB_SRVKEY_FILE"
+        echo "  server-cert-file: $UB_SRVPEM_FILE"
+        echo "  control-key-file: $UB_CTLKEY_FILE"
+        echo "  control-cert-file: $UB_CTLPEM_FILE"
+        echo
+      } >> $UB_CTRL_CONF
+      ;;
+  esac
+}
+
+##############################################################################
+
+unbound_zone() {
+  local cfg=$1
+  local servers_ip=""
+  local servers_host=""
+  local zone_sym zone_name zone_type zone_enabled zone_file
+  local tls_upstream fallback
+  local server port tls_port tls_index tls_suffix url_dir
+
+  if [ ! -f "$UB_ZONE_CONF" ] ; then
+    echo "# $UB_ZONE_CONF generated by UCI $( date -Is )" > $UB_ZONE_CONF
+  fi
+
+
+  config_get_bool zone_enabled  "$cfg" enabled 0
+
+
+  if [ "$zone_enabled" -eq 1 ] ; then
+    # these lists are built for each zone; empty to start
+    UB_LIST_ZONE_NAMES=""
+    UB_LIST_ZONE_SERVERS=""
+
+    config_get  zone_type "$cfg" zone_type ""
+    config_get  port      "$cfg" port ""
+    config_get  tls_index "$cfg" tls_index ""
+    config_get  tls_port  "$cfg" tls_port 853
+    config_get  url_dir   "$cfg" url_dir ""
+
+    config_get_bool resolv_conf   "$cfg" resolv_conf 0
+    config_get_bool fallback      "$cfg" fallback 1
+    config_get_bool tls_upstream  "$cfg" tls_upstream 0
+
+    config_list_foreach "$cfg" zone_name  bundle_zone_names
+    config_list_foreach "$cfg" server     bundle_zone_servers
+
+    # string formating for Unbound syntax
+    tls_suffix="${tls_port:+@${tls_port}${tls_index:+#${tls_index}}}"
+    [ "$fallback" -eq 0 ]     && fallback=no     || fallback=yes
+    [ "$tls_upstream" -eq 0 ] && tls_upstream=no || tls_upstream=yes
+
+
+    if [ $resolv_conf -eq 1 ] ; then
+      bundle_resolv_conf_servers
+    fi
+
+  else
+    zone_type=skip
+  fi
+
+
+  case $zone_type in
+    auth_zone)
+      if [ -n "$UB_LIST_ZONE_NAMES" \
+           -a \( -n "$url_dir" -o -n "$UB_LIST_ZONE_SERVERS" \) ] ; then
+        for zone_name in $UB_LIST_ZONE_NAMES ; do
+          if [ "$zone_name" = "." ] ; then
+            zone_sym=.
+            zone_name=root
+            zone_file=root.zone
+          else
+            zone_sym=$zone_name
+            zone_file=$zone_name.zone
+            zone_file=${zone_file//../.}
+          fi
+
+
+          {
+            # generate an auth-zone: with switches for prefetch cache
+            echo "auth-zone:"
+            echo "  name: $zone_sym"
+            for server in $UB_LIST_ZONE_SERVERS ; do
+              echo "  master: $server${port:+@${port}}"
+            done
+            if [ -n "$url_dir" ] ; then
+              echo "  url: $url_dir$zone_file"
+            fi
+            echo "  fallback-enabled: $fallback"
+            echo "  for-downstream: no"
+            echo "  for-upstream: yes"
+            echo "  zonefile: $zone_file"
+            echo
+          } >> $UB_ZONE_CONF
+        done
+      fi
+      ;;
+
+    forward_zone)
+      if [ ! -f $UB_TLS_FWD_FILE -a "$tls_upstream" = "yes" ] ; then
+        logger -p 4 -t unbound -s \
+          "Forward-zone TLS benefits from authentication in package 'ca-bundle'"
+      fi
+
+
+      if [ -n "$UB_LIST_ZONE_NAMES" -a -n "$UB_LIST_ZONE_SERVERS" ] ; then
+        for server in $UB_LIST_ZONE_SERVERS ; do
+          if [ "$( valid_subnet_any $server )" = "not" ] ; then
+            case $server in
+              *@[0-9]*)
+                # unique Unbound option for server host name
+                servers_host="$servers_host $server"
+                ;;
+
+              *)
+                if [ "$tls_upstream" = "yes" ] ; then
+                  servers_host="$servers_host $server${tls_port:+@${tls_port}}"
+                else
+                  servers_host="$servers_host $server${port:+@${port}}"
+                fi
+            esac
+
+          else
+            case $server in
+              *[0-9]@[0-9]*)
+                # unique Unbound option for server address
+                servers_ip="$servers_ip $server"
+                ;;
+
+              *)
+                if [ "$tls_upstream" = "yes" ] ; then
+                  servers_ip="$servers_ip $server$tls_suffix"
+                else
+                  servers_ip="$servers_ip $server${port:+@${port}}"
+                fi
+            esac
+          fi
+        done
+
+
+        for zonename in $UB_LIST_ZONE_NAMES ; do
+          {
+            # generate a forward-zone with or without tls
+            echo "forward-zone:"
+            echo "  name: $zonename"
+            for server in $servers_host ; do
+              echo "  forward-host: $server"
+            done
+            for server in $servers_ip ; do
+              echo "  forward-addr: $server"
+            done
+            echo "  forward-first: $fallback"
+            echo "  forward-tls-upstream: $tls_upstream"
+            echo
+          } >> $UB_ZONE_CONF
+        done
+      fi
+      ;;
+
+    stub_zone)
+      if [ -n "$UB_LIST_ZONE_NAMES" -a -n "$UB_LIST_ZONE_SERVERS" ] ; then
+        for zonename in $UB_LIST_ZONE_NAMES ; do
+          {
+            # generate a stub-zone: or ensure short cut to authority NS
+            echo "stub-zone:"
+            echo "  name: $zonename"
+            for server in $UB_LIST_ZONE_SERVERS ; do
+              echo "  stub-addr: $server${port:+@${port}}"
+            done
+            echo "  stub-first: $fallback"
+            echo
+          } >> $UB_ZONE_CONF
+        done
+      fi
+      ;;
+  esac
+}
+
+##############################################################################
+
+unbound_conf() {
+  local rt_mem rt_conn rt_buff modulestring domain ifsubnet nsubnet
+
+  {
+    # server: for this whole function
+    echo "# $UB_CORE_CONF generated by UCI $( date -Is )"
+    echo "server:"
+    echo "  username: unbound"
+    echo "  chroot: $UB_VARDIR"
+    echo "  directory: $UB_VARDIR"
+    echo "  pidfile: $UB_PIDFILE"
+  } > $UB_CORE_CONF
+
+
+  if [ -f "$UB_TLS_FWD_FILE" ] ; then
+    # TLS cert bundle for upstream forwarder and https zone files
+    # This is loaded before drop to root, so pull from /etc/ssl
+    echo "  tls-cert-bundle: $UB_TLS_FWD_FILE" >> $UB_CORE_CONF
+  fi
+
+
+  if [ -f "$UB_RHINT_FILE" ] ; then
+    # Optional hints if found
+    echo "  root-hints: $UB_RHINT_FILE" >> $UB_CORE_CONF
+  fi
+
+
+  if [ "$UB_B_DNSSEC" -gt 0 -a -f "$UB_RKEY_FILE" ] ; then
+    {
+      echo "  auto-trust-anchor-file: $UB_RKEY_FILE"
+      echo
+    } >> $UB_CORE_CONF
+
+  else
+    echo >> $UB_CORE_CONF
+  fi
+
+
+  {
+    # No threading
+    echo "  num-threads: 1"
+    echo "  msg-cache-slabs: 1"
+    echo "  rrset-cache-slabs: 1"
+    echo "  infra-cache-slabs: 1"
+    echo "  key-cache-slabs: 1"
+    echo
+    # Logging
+    echo "  use-syslog: yes"
+    echo "  statistics-interval: 0"
+    echo "  statistics-cumulative: no"
+  } >> $UB_CORE_CONF
+
+
+  if [ "$UB_D_VERBOSE" -ge 0 -a "$UB_D_VERBOSE" -le 5 ] ; then
+    echo "  verbosity: $UB_D_VERBOSE" >> $UB_CORE_CONF
+  fi
+
+
+  if [ "$UB_B_EXT_STATS" -gt 0 ] ; then
+    {
+      # Log More
+      echo "  extended-statistics: yes"
+      echo
+    } >> $UB_CORE_CONF
+
+  else
+    {
+      # Log Less
+      echo "  extended-statistics: no"
+      echo
+    } >> $UB_CORE_CONF
+  fi
+
+
+  case "$UB_D_PROTOCOL" in
+    ip4_only)
+      {
+        echo "  edns-buffer-size: $UB_N_EDNS_SIZE"
+        echo "  port: $UB_N_RX_PORT"
+        echo "  outgoing-port-permit: 10240-65535"
+        echo "  interface: 0.0.0.0"
+        echo "  interface: ::0"
+        echo "  outgoing-interface: 0.0.0.0"
+        echo "  do-ip4: yes"
+        echo "  do-ip6: no"
+        echo
+      } >> $UB_CORE_CONF
+      ;;
+
+    ip6_only)
+      {
+        echo "  edns-buffer-size: $UB_N_EDNS_SIZE"
+        echo "  port: $UB_N_RX_PORT"
+        echo "  outgoing-port-permit: 10240-65535"
+        echo "  interface: 0.0.0.0"
+        echo "  interface: ::0"
+        echo "  outgoing-interface: ::0"
+        echo "  do-ip4: no"
+        echo "  do-ip6: yes"
+        echo
+      } >> $UB_CORE_CONF
+      ;;
+
+    ip6_prefer)
+      {
+        echo "  edns-buffer-size: $UB_N_EDNS_SIZE"
+        echo "  port: $UB_N_RX_PORT"
+        echo "  outgoing-port-permit: 10240-65535"
+        echo "  interface: 0.0.0.0"
+        echo "  interface: ::0"
+        echo "  outgoing-interface: 0.0.0.0"
+        echo "  outgoing-interface: ::0"
+        echo "  do-ip4: yes"
+        echo "  do-ip6: yes"
+        echo "  prefer-ip6: yes"
+        echo
+      } >> $UB_CORE_CONF
+      ;;
+
+    mixed)
+      {
+        # Interface Wildcard (access contol handled by "option local_service")
+        echo "  edns-buffer-size: $UB_N_EDNS_SIZE"
+        echo "  port: $UB_N_RX_PORT"
+        echo "  outgoing-port-permit: 10240-65535"
+        echo "  interface: 0.0.0.0"
+        echo "  interface: ::0"
+        echo "  outgoing-interface: 0.0.0.0"
+        echo "  outgoing-interface: ::0"
+        echo "  do-ip4: yes"
+        echo "  do-ip6: yes"
+        echo
+      } >> $UB_CORE_CONF
+      ;;
+
+    *)
+      if [ "$UB_B_READY" -eq 0 ] ; then
+        logger -t unbound -s "default protocol configuration"
+      fi
+
+
+      {
+        # outgoing-interface has useful defaults; incoming is localhost though
+        echo "  edns-buffer-size: $UB_N_EDNS_SIZE"
+        echo "  port: $UB_N_RX_PORT"
+        echo "  outgoing-port-permit: 10240-65535"
+        echo "  interface: 0.0.0.0"
+        echo "  interface: ::0"
+        echo
+      } >> $UB_CORE_CONF
+      ;;
+  esac
+
+
+  {
+    # Other harding and options for an embedded router
+    echo "  harden-short-bufsize: yes"
+    echo "  harden-large-queries: yes"
+    echo "  harden-glue: yes"
+    echo "  harden-below-nxdomain: no"
+    echo "  harden-referral-path: no"
+    echo "  use-caps-for-id: no"
+    echo
+  } >> $UB_CORE_CONF
+
+
+  case "$UB_D_RESOURCE" in
+    # Tiny - Unbound's recommended cheap hardware config
+    tiny)   rt_mem=1  ; rt_conn=2  ; rt_buff=1 ;;
+    # Small - Half RRCACHE and open ports
+    small)  rt_mem=8  ; rt_conn=10 ; rt_buff=2 ;;
+    # Medium - Nearly default but with some added balancintg
+    medium) rt_mem=16 ; rt_conn=20 ; rt_buff=4 ;;
+    # Large - Double medium
+    large)  rt_mem=32 ; rt_conn=40 ; rt_buff=4 ;;
+    # Whatever unbound does
+    *) rt_mem=0 ; rt_conn=0 ;;
+  esac
+
+
+  if [ "$rt_mem" -gt 0 ] ; then
+    {
+      # Set memory sizing parameters
+      echo "  msg-buffer-size: $(($rt_buff*8192))"
+      echo "  outgoing-range: $(($rt_conn*64))"
+      echo "  num-queries-per-thread: $(($rt_conn*32))"
+      echo "  outgoing-num-tcp: $(($rt_conn))"
+      echo "  incoming-num-tcp: $(($rt_conn))"
+      echo "  rrset-cache-size: $(($rt_mem*256))k"
+      echo "  msg-cache-size: $(($rt_mem*128))k"
+      echo "  key-cache-size: $(($rt_mem*128))k"
+      echo "  neg-cache-size: $(($rt_mem*64))k"
+      echo "  infra-cache-numhosts: $(($rt_mem*256))"
+      echo
+    } >> $UB_CORE_CONF
+
+  elif [ "$UB_B_READY" -eq 0 ] ; then
+    logger -t unbound -s "default memory configuration"
+  fi
+
+
+  # Assembly of module-config: options is tricky; order matters
+  modulestring="iterator"
+
+
+  if [ "$UB_B_DNSSEC" -gt 0 ] ; then
+    if [ "$UB_B_NTP_BOOT" -gt 0 ] ; then
+      # DNSSEC chicken and egg with getting NTP time
+      echo "  val-override-date: -1" >> $UB_CORE_CONF
+    fi
+
+
+    {
+      echo "  harden-dnssec-stripped: yes"
+      echo "  val-clean-additional: yes"
+      echo "  ignore-cd-flag: yes"
+    } >> $UB_CORE_CONF
+
+
+    modulestring="validator $modulestring"
+  fi
+
+
+  if [ "$UB_B_DNS64" -gt 0 ] ; then
+    echo "  dns64-prefix: $UB_IP_DNS64" >> $UB_CORE_CONF
+
+    modulestring="dns64 $modulestring"
+  fi
+
+
+  {
+    # Print final module string
+    echo "  module-config: \"$modulestring\""
+    echo
+  }  >> $UB_CORE_CONF
+
+
+  case "$UB_D_RECURSION" in
+    passive)
+      {
+        # Some query privacy but "strict" will break some servers
+        if [ "$UB_B_QRY_MINST" -gt 0 \
+          -a "$UB_B_QUERY_MIN" -gt 0 ] ; then
+          echo "  qname-minimisation: yes"
+          echo "  qname-minimisation-strict: yes"
+        elif [ "$UB_B_QUERY_MIN" -gt 0 ] ; then
+          echo "  qname-minimisation: yes"
+        else
+          echo "  qname-minimisation: no"
+        fi
+        # Use DNSSEC to quickly understand NXDOMAIN ranges
+        if [ "$UB_B_DNSSEC" -gt 0 ] ; then
+          echo "  aggressive-nsec: yes"
+          echo "  prefetch-key: no"
+        fi
+        # On demand fetching
+        echo "  prefetch: no"
+        echo "  target-fetch-policy: \"0 0 0 0 0\""
+        echo
+      } >> $UB_CORE_CONF
+      ;;
+
+    aggressive)
+      {
+        # Some query privacy but "strict" will break some servers
+        if [ "$UB_B_QRY_MINST" -gt 0 \
+          -a "$UB_B_QUERY_MIN" -gt 0 ] ; then
+          echo "  qname-minimisation: yes"
+          echo "  qname-minimisation-strict: yes"
+        elif [ "$UB_B_QUERY_MIN" -gt 0 ] ; then
+          echo "  qname-minimisation: yes"
+        else
+          echo "  qname-minimisation: no"
+        fi
+        # Use DNSSEC to quickly understand NXDOMAIN ranges
+        if [ "$UB_B_DNSSEC" -gt 0 ] ; then
+          echo "  aggressive-nsec: yes"
+          echo "  prefetch-key: yes"
+        fi
+        # Prefetch what can be
+        echo "  prefetch: yes"
+        echo "  target-fetch-policy: \"3 2 1 0 0\""
+        echo
+      } >> $UB_CORE_CONF
+      ;;
+
+    *)
+      if [ "$UB_B_READY" -eq 0 ] ; then
+        logger -t unbound -s "default recursion configuration"
+      fi
+      ;;
+  esac
+
+
+  {
+    # Reload records more than 20 hours old
+    # DNSSEC 5 minute bogus cool down before retry
+    # Adaptive infrastructure info kept for 15 minutes
+    echo "  cache-min-ttl: $UB_TTL_MIN"
+    echo "  cache-max-ttl: 72000"
+    echo "  val-bogus-ttl: 300"
+    echo "  infra-host-ttl: 900"
+    echo
+  } >> $UB_CORE_CONF
+
+
+  if [ "$UB_B_HIDE_BIND" -gt 0 ] ; then
+    {
+      # Block server id and version DNS TXT records
+      echo "  hide-identity: yes"
+      echo "  hide-version: yes"
+      echo
+    } >> $UB_CORE_CONF
+  fi
+
+
+  if [ "$UB_D_PRIV_BLCK" -gt 0 ] ; then
+    {
+      # Remove _upstream_ or global reponses with private addresses.
+      # Unbounds own "local zone" and "forward zone" may still use these.
+      # RFC1918, RFC3927, RFC4291, RFC6598, RFC6890
+      echo "  private-address: 10.0.0.0/8"
+      echo "  private-address: 100.64.0.0/10"
+      echo "  private-address: 169.254.0.0/16"
+      echo "  private-address: 172.16.0.0/12"
+      echo "  private-address: 192.168.0.0/16"
+      echo "  private-address: fc00::/7"
+      echo "  private-address: fe80::/10"
+      echo
+    } >> $UB_CORE_CONF
+  fi
+
+
+  if [ -n "$UB_LIST_NETW_LAN" -a "$UB_D_PRIV_BLCK" -gt 1 ] ; then
+    {
+      for ifsubnet in $UB_LIST_NETW_LAN ; do
+        case $ifsubnet in
+          *@[1-9][0-9a-f][0-9a-f][0-9a-f]:*:[0-9a-f]*)
+            # Remove global DNS responses with your local network IP6 GLA
+            echo "  private-address: ${ifsubnet#*@}"
+            ;;
+        esac
+      done
+      echo
+    } >> $UB_CORE_CONF
+  fi
+
+
+  if [ "$UB_B_LOCL_BLCK" -gt 0 ] ; then
+    {
+      # Remove DNS reponses from upstream with loopback IP
+      # Black hole DNS method for ad blocking, so consider...
+      echo "  private-address: 127.0.0.0/8"
+      echo "  private-address: ::1/128"
+      echo
+    } >> $UB_CORE_CONF
+  fi
+
+
+  if  [ -n "$UB_LIST_INSECURE" ] ; then
+    {
+      for domain in $UB_LIST_INSECURE ; do
+        # Except and accept domains without (DNSSEC); work around broken domains
+        echo "  domain-insecure: $domain"
+      done
+      echo
+    } >> $UB_CORE_CONF
+  fi
+
+
+  if [ "$UB_B_LOCL_SERV" -gt 0 -a -n "$UB_LIST_NETW_ALL" ] ; then
+    {
+      for ifsubnet in $UB_LIST_NETW_ALL ; do
+        # Only respond to queries from subnets which have an interface.
+        # Prevent DNS amplification attacks by not responding to the universe.
+        echo "  access-control: ${ifsubnet#*@} allow"
+      done
+      echo "  access-control: 127.0.0.0/8 allow"
+      echo "  access-control: ::1/128 allow"
+      echo "  access-control: fe80::/10 allow"
+      echo
+    } >> $UB_CORE_CONF
+
+  else
+    {
+      echo "  access-control: 0.0.0.0/0 allow"
+      echo "  access-control: ::0/0 allow"
+      echo
+    } >> $UB_CORE_CONF
+  fi
+}
+
+##############################################################################
+
+unbound_hostname() {
+  local ifsubnet ifarpa ifaddr ifname iffqdn
+  local ulaprefix hostfqdn name names namerec ptrrec
+  local zonetype=0
+
+  echo "# $UB_HOST_CONF generated by UCI $( date -Is )" > $UB_HOST_CONF
+
+
+  if [ "$UB_D_DHCP_LINK" = "dnsmasq" ] ; then
+    {
+      echo "# Local zone is handled by dnsmasq"
+      echo
+    } >> $UB_HOST_CONF
+
+  elif [ -n "$UB_TXT_DOMAIN" \
+         -a \( "$UB_D_WAN_FQDN" -gt 0 -o "$UB_D_LAN_FQDN" -gt 0 \) ] ; then
+    case "$UB_D_DOMAIN_TYPE" in
+      deny|inform_deny|refuse|static)
+        {
+          # type static means only this router has your domain
+          echo "  domain-insecure: $UB_TXT_DOMAIN"
+          echo "  private-domain: $UB_TXT_DOMAIN"
+          echo "  local-zone: $UB_TXT_DOMAIN $UB_D_DOMAIN_TYPE"
+          echo "  local-data: \"$UB_TXT_DOMAIN. $UB_XSOA\""
+          echo "  local-data: \"$UB_TXT_DOMAIN. $UB_XNS\""
+          echo "  local-data: '$UB_TXT_DOMAIN. $UB_XTXT'"
+          echo
+          # avoid upstream involvement in RFC6762
+          echo "  domain-insecure: local"
+          echo "  private-domain: local"
+          echo "  local-zone: local $UB_D_DOMAIN_TYPE"
+          echo "  local-data: \"local. $UB_XSOA\""
+          echo "  local-data: \"local. $UB_XNS\""
+          echo "  local-data: 'local. $UB_LTXT'"
+          echo
+        } >> $UB_HOST_CONF
+        zonetype=2
+        ;;
+
+      transparent|typetransparent)
+        {
+          # transparent will permit forward-zone: or stub-zone: clauses
+          echo "  private-domain: $UB_TXT_DOMAIN"
+          echo "  local-zone: $UB_TXT_DOMAIN $UB_D_DOMAIN_TYPE"
+          echo
+        } >> $UB_HOST_CONF
+        zonetype=1
+        ;;
+    esac
+
+
+    {
+      # Hostname as TLD works, but not transparent through recursion (singular)
+      echo "  domain-insecure: $UB_TXT_HOSTNAME"
+      echo "  private-domain: $UB_TXT_HOSTNAME"
+      echo "  local-zone: $UB_TXT_HOSTNAME static"
+      echo "  local-data: \"$UB_TXT_HOSTNAME. $UB_XSOA\""
+      echo "  local-data: \"$UB_TXT_HOSTNAME. $UB_XNS\""
+      echo "  local-data: '$UB_TXT_HOSTNAME. $UB_XTXT'"
+      echo
+    } >> $UB_HOST_CONF
+
+
+    if [ -n "$UB_LIST_NETW_WAN" ] ; then
+      for ifsubnet in $UB_LIST_NETW_WAN ; do
+        ifaddr=${ifsubnet#*@}
+        ifaddr=${ifaddr%/*}
+        ifarpa=$( host_ptr_any "$ifaddr" )
+
+
+        if [ -n "$ifarpa" ] ; then
+          if [ "$UB_D_WAN_FQDN" -gt 0 ] ; then
+            {
+              # Create a static zone for WAN host record only (singular)
+              echo "  domain-insecure: $ifarpa"
+              echo "  private-address: $ifaddr"
+              echo "  local-zone: $ifarpa static"
+              echo "  local-data: \"$ifarpa. $UB_XSOA\""
+              echo "  local-data: \"$ifarpa. $UB_XNS\""
+              echo "  local-data: '$ifarpa. $UB_MTXT'"
+              echo
+            } >> $UB_HOST_CONF
+
+          elif [ "$zonetype" -gt 0 ] ; then
+            {
+              echo "  local-zone: $ifarpa transparent"
+              echo
+            } >> $UB_HOST_CONF
+          fi
+        fi
+      done
+    fi
+
+
+    if  [ -n "$UB_LIST_NETW_LAN" ] ; then
+      for ifsubnet in $UB_LIST_NETW_LAN ; do
+        ifarpa=$( domain_ptr_any "${ifsubnet#*@}" )
+
+
+        if [ -n "$ifarpa" ] ; then
+          if [ "$zonetype" -eq 2 ] ; then
+            {
+              # Do NOT forward queries with your ip6.arpa or in-addr.arpa
+              echo "  domain-insecure: $ifarpa"
+              echo "  local-zone: $ifarpa static"
+              echo "  local-data: \"$ifarpa. $UB_XSOA\""
+              echo "  local-data: \"$ifarpa. $UB_XNS\""
+              echo "  local-data: '$ifarpa. $UB_XTXT'"
+              echo
+            } >> $UB_HOST_CONF
+
+          elif [ "$zonetype" -eq 1 -a "$UB_D_PRIV_BLCK" -eq 0 ] ; then
+            {
+              echo "  local-zone: $ifarpa transparent"
+              echo
+            } >> $UB_HOST_CONF
+          fi
+        fi
+      done
+    fi
+
+
+    ulaprefix=$( uci_get network.@globals[0].ula_prefix )
+    ulaprefix=${ulaprefix%%:/*}
+    hostfqdn="$UB_TXT_HOSTNAME.$UB_TXT_DOMAIN"
+
+
+    if [ -z "$ulaprefix" ] ; then
+      # Nonsense so this option isn't globbed below
+      ulaprefix="fdno:such:addr::"
+    fi
+
+
+    if [ "$UB_LIST_NETW_LAN" -a "$UB_D_LAN_FQDN" -gt 0 ] ; then
+      for ifsubnet in $UB_LIST_NETW_LAN ; do
+        ifaddr=${ifsubnet#*@}
+        ifaddr=${ifaddr%/*}
+        ifname=${ifsubnet%@*}
+        iffqdn="$ifname.$hostfqdn"
+
+
+        if [ "$UB_D_LAN_FQDN" -eq 4 ] ; then
+          names="$iffqdn $hostfqdn $UB_TXT_HOSTNAME"
+          ptrrec="  local-data-ptr: \"$ifaddr 300 $iffqdn\""
+          echo "$ptrrec" >> $UB_HOST_CONF
+
+        elif [ "$UB_D_LAN_FQDN" -eq 3 ] ; then
+          names="$hostfqdn $UB_TXT_HOSTNAME"
+          ptrrec="  local-data-ptr: \"$ifaddr 300 $hostfqdn\""
+          echo "$ptrrec" >> $UB_HOST_CONF
+
+        else
+          names="$UB_TXT_HOSTNAME"
+          ptrrec="  local-data-ptr: \"$ifaddr 300 $UB_TXT_HOSTNAME\""
+          echo "$ptrrec" >> $UB_HOST_CONF
+        fi
+
+
+        for name in $names ; do
+          case $ifaddr in
+            "${ulaprefix}"*)
+              # IP6 ULA only is assigned for OPTION 1
+              namerec="  local-data: \"$name. 300 IN AAAA $ifaddr\""
+              echo "$namerec" >> $UB_HOST_CONF
+              ;;
+
+            [1-9]*.*[0-9])
+              namerec="  local-data: \"$name. 300 IN A $ifaddr\""
+              echo "$namerec" >> $UB_HOST_CONF
+              ;;
+
+            *)
+              if [ "$UB_D_LAN_FQDN" -gt 1 ] ; then
+                # IP6 GLA is assigned for higher options
+                namerec="  local-data: \"$name. 300 IN AAAA $ifaddr\""
+                echo "$namerec" >> $UB_HOST_CONF
+              fi
+              ;;
+          esac
+        done
+        echo >> $UB_HOST_CONF
+      done
+    fi
+
+
+    if [ -n "$UB_LIST_NETW_WAN" -a "$UB_D_WAN_FQDN" -gt 0 ] ; then
+      for ifsubnet in $UB_LIST_NETW_WAN ; do
+        ifaddr=${ifsubnet#*@}
+        ifaddr=${ifaddr%/*}
+        ifname=${ifsubnet%@*}
+        iffqdn="$ifname.$hostfqdn"
+
+
+        if [ "$UB_D_WAN_FQDN" -eq 4 ] ; then
+          names="$iffqdn $hostfqdn $UB_TXT_HOSTNAME"
+          ptrrec="  local-data-ptr: \"$ifaddr 300 $iffqdn\""
+          echo "$ptrrec" >> $UB_HOST_CONF
+
+        elif [ "$UB_D_WAN_FQDN" -eq 3 ] ; then
+          names="$hostfqdn $UB_TXT_HOSTNAME"
+          ptrrec="  local-data-ptr: \"$ifaddr 300 $hostfqdn\""
+          echo "$ptrrec" >> $UB_HOST_CONF
+
+        else
+          names="$UB_TXT_HOSTNAME"
+          ptrrec="  local-data-ptr: \"$ifaddr 300 $UB_TXT_HOSTNAME\""
+          echo "$ptrrec" >> $UB_HOST_CONF
+        fi
+
+
+        for name in $names ; do
+          case $ifaddr in
+            "${ulaprefix}"*)
+              # IP6 ULA only is assigned for OPTION 1
+              namerec="  local-data: \"$name. 300 IN AAAA $ifaddr\""
+              echo "$namerec" >> $UB_HOST_CONF
+              ;;
+
+            [1-9]*.*[0-9])
+              namerec="  local-data: \"$name. 300 IN A $ifaddr\""
+              echo "$namerec" >> $UB_HOST_CONF
+              ;;
+
+            *)
+              if [ "$UB_D_WAN_FQDN" -gt 1 ] ; then
+                # IP6 GLA is assigned for higher options
+                namerec="  local-data: \"$name. 300 IN AAAA $ifaddr\""
+                echo "$namerec" >> $UB_HOST_CONF
+              fi
+            ;;
+          esac
+        done
+        echo >> $UB_HOST_CONF
+      done
+    fi
+  fi # end if uci valid
+}
+
+##############################################################################
+
+unbound_uci() {
+  local cfg="$1"
+  local dnsmasqpath hostnm
+
+  hostnm=$( uci_get system.@system[0].hostname | awk '{print tolower($0)}' )
+  UB_TXT_HOSTNAME=${hostnm:-thisrouter}
+
+  config_get_bool UB_B_SLAAC6_MAC "$cfg" dhcp4_slaac6 0
+  config_get_bool UB_B_DNS64      "$cfg" dns64 0
+  config_get_bool UB_B_EXT_STATS  "$cfg" extended_stats 0
+  config_get_bool UB_B_HIDE_BIND  "$cfg" hide_binddata 1
+  config_get_bool UB_B_LOCL_SERV  "$cfg" localservice 1
+  config_get_bool UB_B_MAN_CONF   "$cfg" manual_conf 0
+  config_get_bool UB_B_QUERY_MIN  "$cfg" query_minimize 0
+  config_get_bool UB_B_QRY_MINST  "$cfg" query_min_strict 0
+  config_get_bool UB_B_AUTH_ROOT  "$cfg" prefetch_root 0
+  config_get_bool UB_B_LOCL_BLCK  "$cfg" rebind_localhost 0
+  config_get_bool UB_B_DNSSEC     "$cfg" validator 0
+  config_get_bool UB_B_NTP_BOOT   "$cfg" validator_ntp 1
+
+  config_get UB_IP_DNS64    "$cfg" dns64_prefix "64:ff9b::/96"
+
+  config_get UB_N_EDNS_SIZE "$cfg" edns_size 1280
+  config_get UB_N_RX_PORT   "$cfg" listen_port 53
+  config_get UB_N_ROOT_AGE  "$cfg" root_age 9
+
+  config_get UB_D_CONTROL     "$cfg" unbound_control 0
+  config_get UB_D_DOMAIN_TYPE "$cfg" domain_type static
+  config_get UB_D_DHCP_LINK   "$cfg" dhcp_link none
+  config_get UB_D_EXTRA_DNS   "$cfg" add_extra_dns 0
+  config_get UB_D_LAN_FQDN    "$cfg" add_local_fqdn 0
+  config_get UB_D_PRIV_BLCK   "$cfg" rebind_protection 1
+  config_get UB_D_PROTOCOL    "$cfg" protocol mixed
+  config_get UB_D_RECURSION   "$cfg" recursion passive
+  config_get UB_D_RESOURCE    "$cfg" resource small
+  config_get UB_D_VERBOSE     "$cfg" verbosity 1
+  config_get UB_D_WAN_FQDN    "$cfg" add_wan_fqdn 0
+
+  config_get UB_TTL_MIN     "$cfg" ttl_min 120
+  config_get UB_TXT_DOMAIN  "$cfg" domain lan
+
+  config_list_foreach "$cfg" domain_insecure  bundle_domain_insecure
+
+
+  if [ "$UB_D_DHCP_LINK" = "none" ] ; then
+    config_get_bool UB_B_DNSMASQ   "$cfg" dnsmasq_link_dns 0
+
+
+    if [ "$UB_B_DNSMASQ" -gt 0 ] ; then
+      UB_D_DHCP_LINK=dnsmasq
+
+
+      if [ "$UB_B_READY" -eq 0 ] ; then
+        logger -t unbound -s "Please use 'dhcp_link' selector instead"
+      fi
+    fi
+  fi
+
+
+  if [ "$UB_D_DHCP_LINK" = "dnsmasq" ] ; then
+    if [ ! -x /usr/sbin/dnsmasq -o ! -x /etc/init.d/dnsmasq ] ; then
+      UB_D_DHCP_LINK=none
+    else
+      /etc/init.d/dnsmasq enabled || UB_D_DHCP_LINK=none
+    fi
+
+
+    if [ "$UB_B_READY" -eq 0 -a "$UB_D_DHCP_LINK" = "none" ] ; then
+      logger -t unbound -s "cannot forward to dnsmasq"
+    fi
+  fi
+
+
+  if [ "$UB_D_DHCP_LINK" = "odhcpd" ] ; then
+    if [ ! -x /usr/sbin/odhcpd -o ! -x /etc/init.d/odhcpd ] ; then
+      UB_D_DHCP_LINK=none
+    else
+      /etc/init.d/odhcpd enabled || UB_D_DHCP_LINK=none
+    fi
+
+
+    if [ "$UB_B_READY" -eq 0 -a "$UB_D_DHCP_LINK" = "none" ] ; then
+      logger -t unbound -s "cannot receive records from odhcpd"
+    fi
+  fi
+
+
+  if [ "$UB_N_EDNS_SIZE" -lt 512 \
+    -o 4096 -lt "$UB_N_EDNS_SIZE" ] ; then
+    logger -t unbound -s "edns_size exceeds range, using default"
+    UB_N_EDNS_SIZE=1280
+  fi
+
+
+  if [ "$UB_N_RX_PORT" -ne 53 \
+      -a \( "$UB_N_RX_PORT" -lt 1024 -o 10240 -lt "$UB_N_RX_PORT" \) ] ; then
+    logger -t unbound -s "privileged port or in 5 digits, using default"
+    UB_N_RX_PORT=53
+  fi
+
+
+  if [ "$UB_TTL_MIN" -gt 1800 ] ; then
+    logger -t unbound -s "ttl_min could have had awful side effects, using 300"
+    UB_TTL_MIN=300
+  fi
+}
+
+##############################################################################
+
+unbound_include() {
+  local adb_enabled
+  local adb_files=$( ls $UB_VARDIR/adb_list.* 2>/dev/null )
+
+  echo "# $UB_TOTAL_CONF generated by UCI $( date -Is )" > $UB_TOTAL_CONF
+
+
+  if [ -f "$UB_CORE_CONF" ] ; then
+    # Yes this all looks busy, but it is in TMPFS. Working on separate files
+    # and piecing together is easier. UCI order is less constrained.
+    cat $UB_CORE_CONF >> $UB_TOTAL_CONF
+    rm  $UB_CORE_CONF
+  fi
+
+
+  if [ -f "$UB_HOST_CONF" ] ; then
+    # UCI definitions of local host or local subnet
+    cat $UB_HOST_CONF >> $UB_TOTAL_CONF
+    rm  $UB_HOST_CONF
+  fi
+
+
+  if [ -f $UB_SRVMASQ_CONF ] ; then
+    # UCI found link to dnsmasq
+    cat $UB_SRVMASQ_CONF >> $UB_TOTAL_CONF
+    rm  $UB_SRVMASQ_CONF
+  fi
+
+
+  if [ -f "$UB_DHCP_CONF" ] ; then
+    {
+      # Seed DHCP records because dhcp scripts trigger externally
+      # Incremental Unbound restarts may drop unbound-control records
+      echo "include: $UB_DHCP_CONF"
+      echo
+    }>> $UB_TOTAL_CONF
+  fi
+
+
+  if [ -z "$adb_files" \
+       -o  ! -x /usr/bin/adblock.sh -o ! -x /etc/init.d/adblock ] ; then
+    adb_enabled=0
+
+  elif /etc/init.d/adblock enabled ; then
+    adb_enabled=1
+    {
+      # Pull in your selected openwrt/pacakges/net/adblock generated lists
+      echo "include: $UB_VARDIR/adb_list.*"
+      echo
+    } >> $UB_TOTAL_CONF
+
+  else
+    adb_enabled=0
+  fi
+
+
+  if [ -f $UB_SRV_CONF ] ; then
+    {
+      # Pull your own "server:" options here
+      echo "include: $UB_SRV_CONF"
+      echo
+    }>> $UB_TOTAL_CONF
+  fi
+
+
+  if [ -f "$UB_ZONE_CONF" ] ; then
+    # UCI defined forward, stub, and auth zones
+    cat $UB_ZONE_CONF >> $UB_TOTAL_CONF
+    rm  $UB_ZONE_CONF
+  fi
+
+
+  if [ -f "$UB_CTRL_CONF" ] ; then
+    # UCI defined control application connection
+    cat $UB_CTRL_CONF >> $UB_TOTAL_CONF
+    rm  $UB_CTRL_CONF
+  fi
+
+
+  if [ -f "$UB_EXTMASQ_CONF" ] ; then
+    # UCI found link to dnsmasq
+    cat $UB_EXTMASQ_CONF >> $UB_TOTAL_CONF
+    rm  $UB_EXTMASQ_CONF
+  fi
+
+
+  if [ -f "$UB_EXT_CONF" ] ; then
+    {
+      # Pull your own extend feature clauses here
+      echo "include: $UB_EXT_CONF"
+      echo
+    } >> $UB_TOTAL_CONF
+  fi
+}
+
+##############################################################################
+
+resolv_setup() {
+  if [ "$UB_N_RX_PORT" != "53" ] ; then
+    return
+
+  elif [ -x /etc/init.d/dnsmasq ] \
+    && /etc/init.d/dnsmasq enabled \
+    && nslookup localhost 127.0.0.1#53 >/dev/null 2>&1 ; then
+    # unbound is configured for port 53, but dnsmasq is enabled and a resolver
+    #   listens on localhost:53, lets assume dnsmasq manages the resolver file.
+    # TODO:
+    #   really check if dnsmasq runs a local (main) resolver in stead of using
+    #   nslookup that times out when no resolver listens on localhost:53.
+    return
+  fi
+
+
+  # unbound is designated to listen on 127.0.0.1#53,
+  #   set resolver file to local.
+  rm -f /tmp/resolv.conf
+
+  {
+    echo "# /tmp/resolv.conf generated by Unbound UCI $( date -Is )"
+    echo "nameserver 127.0.0.1"
+    echo "nameserver ::1"
+    echo "search $UB_TXT_DOMAIN."
+  } > /tmp/resolv.conf
+}
+
+##############################################################################
+
+unbound_start() {
+  config_load unbound
+  config_foreach unbound_uci unbound
+  unbound_mkdir
+
+
+  if [ "$UB_B_MAN_CONF" -eq 0 ] ; then
+    # iterate zones before we load other UCI
+    # forward-zone: auth-zone: and stub-zone:
+    config_foreach unbound_zone zone
+    # associate potential DNS RR with interfaces
+    config_load network
+    config_foreach bundle_all_networks interface
+    config_load dhcp
+    config_foreach bundle_lan_networks dhcp
+    bundle_wan_networks
+    # server:
+    unbound_conf
+    unbound_hostname
+    # control:
+    unbound_control
+    # dnsmasq
+    dnsmasq_link
+    # merge
+    unbound_include
+  fi
+
+
+  resolv_setup
+}
+
+##############################################################################
+

+ 53 - 0
package/network/services/unbound/files/unbound.uci

@@ -0,0 +1,53 @@
+config unbound
+	option add_extra_dns '0'
+	option add_local_fqdn '1'
+	option add_wan_fqdn '0'
+	option dhcp_link 'none'
+	option dhcp4_slaac6 '0'
+	option dns64 '0'
+	option dns64_prefix '64:ff9b::/96'
+	option domain 'lan'
+	option domain_type 'static'
+	option edns_size '1280'
+	option extended_stats '0'
+	option hide_binddata '1'
+	option listen_port '53'
+	option localservice '1'
+	option manual_conf '0'
+	option protocol 'default'
+	option query_minimize '0'
+	option query_min_strict '0'
+	option rebind_localhost '0'
+	option rebind_protection '1'
+	option recursion 'default'
+	option resource 'default'
+	option root_age '9'
+	option ttl_min '120'
+	option unbound_control '0'
+	option validator '0'
+	option validator_ntp '1'
+	option verbosity '1'
+	list trigger_interface 'lan'
+	list trigger_interface 'wan'
+	#list domain_insecure 'ntp.example.com'
+
+config zone
+	option enabled '0'
+	option fallback '1'
+	option url_dir 'https://www.internic.net/domain/'
+	option zone_type 'auth_zone'
+	list server 'lax.xfr.dns.icann.org'
+	list server 'iad.xfr.dns.icann.org'
+	list zone_name '.'
+	list zone_name 'arpa.'
+	list zone_name 'in-addr.arpa.'
+	list zone_name 'ip6.arpa.'
+
+config zone
+	option enabled '0'
+	option fallback '1'
+	option resolv_conf '1'
+	option zone_type 'forward_zone'
+	list zone_name 'isp-bill.example.com.'
+	list zone_name 'isp-mail.example.net.'
+

+ 9 - 0
package/network/services/unbound/files/unbound_ext.conf

@@ -0,0 +1,9 @@
+##############################################################################
+# Extended user clauses added to the end of the UCI generated 'unbound.conf'
+#
+# Put your own forward:, view:, stub:, or remote-control: clauses here. This
+# file is appended to the end of 'unbound.conf' with an include: statement.
+# Notice that it is not part of the server: clause. Use 'unbound_srv.conf' to
+# place custom option statements in the server: clause.
+##############################################################################
+

+ 9 - 0
package/network/services/unbound/files/unbound_srv.conf

@@ -0,0 +1,9 @@
+##############################################################################
+# User custom options added in the server: clause part of UCI 'unbound.conf'
+#
+# Add your own option statements here when they are not covered by UCI. This
+# file is placed _inside_ the server: clause with an include: statement. Do
+# not start other clauses here, because that would brake the server: clause.
+# Use 'unbound_ext.conf' to start new clauses at the end of 'unbound.conf'.
+##############################################################################
+

+ 81 - 0
package/network/services/unbound/patches/100-example-conf-in.patch

@@ -0,0 +1,81 @@
+Index: doc/example.conf.in
+===================================================================
+--- a/doc/example.conf.in
++++ b/doc/example.conf.in
+@@ -15,6 +15,76 @@ server:
+ 	# verbosity number, 0 is least verbose. 1 is default.
+ 	verbosity: 1
+
++	############################################################################
++	# MEMORY CONTROL EXAMPLE
++	# In the example config settings below memory usage is reduced. Some ser-
++	# vice levels are lower, notable very large data and a high TCP load are
++	# no longer supported ... are exceptional for the DNS.
++	# (http://unbound.net/documentation/unbound.conf.html)
++	############################################################################
++
++	# Self jail Unbound with user "unbound" to /var/lib/unbound
++	# The script /etc/init.d/unbound will setup the location
++	username: "unbound"
++	directory: "/var/lib/unbound"
++	chroot: "/var/lib/unbound"
++
++	# The pid file is created before privleges drop so no concern
++	pidfile: "/var/run/unbound.pid"
++
++	# no threads and no memory slabs for threads
++	num-threads: 1
++	msg-cache-slabs: 1
++	rrset-cache-slabs: 1
++	infra-cache-slabs: 1
++	key-cache-slabs: 1
++
++	# don't be picky about interfaces but consider your firewall
++	interface: 0.0.0.0
++	interface: ::0
++	access-control: 0.0.0.0/0 allow
++	access-control: ::0/0 allow
++
++	# this limits TCP service but uses less buffers
++	outgoing-num-tcp: 1
++	incoming-num-tcp: 1
++
++	# use somewhat higher port numbers versus possible NAT issue
++	outgoing-port-permit: "10240-65335"
++
++	# uses less memory but less performance
++	outgoing-range: 60
++	num-queries-per-thread: 30
++
++	# exclude large responses
++	msg-buffer-size: 8192
++
++	# tiny memory cache
++	infra-cache-numhosts: 200
++	msg-cache-size: 100k
++	rrset-cache-size: 100k
++	key-cache-size: 100k
++	neg-cache-size: 10k
++
++	# gentle on recursion
++	target-fetch-policy: "2 1 0 0 0 0"
++	harden-large-queries: yes
++	harden-short-bufsize: yes
++
++	# DNSSEC enable by removing comments on "module-config:" and "auto-trust-
++	# -anchor-file:" The init script will copy root key to /var/lib/unbound.
++	# See package documentation for crontab entry to copy RFC5011 results back.
++	#module-config: "validator iterator"
++	#auto-trust-anchor-file: "/var/lib/unbound/root.key"
++
++	# DNSSEC needs real time to validate signatures. If your device does not
++	# have power off clock (reboot), then you may need this work around.
++	#domain-insecure: "pool.ntp.org"
++
++	############################################################################
++	# Resume Stock example.conf.in
++	############################################################################
++
+ 	# print statistics to the log (for every thread) every N seconds.
+ 	# Set to "" or 0 to disable. Default is disabled.
+ 	# statistics-interval: 0

+ 48 - 0
package/network/services/unbound/patches/200-openssl-log-err.patch

@@ -0,0 +1,48 @@
+Index: daemon/remote.c
+===================================================================
+--- a/daemon/remote.c
++++ b/daemon/remote.c
+@@ -1950,6 +1950,11 @@
+ 				return NULL;
+ 			}
+ 		} else {
++#ifndef HAVE_SSL_SET1_HOST
++			if(auth_name)
++			  log_err("no name verification functionality in "
++				"ssl library, ignored name for %s", todo);
++#endif
+ 			/* add address */
+ 			if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0,
+ 				auth_name)) {
+Index: iterator/iter_fwd.c
+===================================================================
+--- a/iterator/iter_fwd.c
++++ b/iterator/iter_fwd.c
+@@ -239,6 +239,11 @@
+ 				s->name, p->str);
+ 			return 0;
+ 		}
++#ifndef HAVE_SSL_SET1_HOST
++		if(tls_auth_name)
++			log_err("no name verification functionality in "
++				"ssl library, ignored name for %s", p->str);
++#endif
+ 		if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0,
+ 			tls_auth_name)) {
+ 			log_err("out of memory");
+Index: iterator/iter_hints.c
+===================================================================
+--- a/iterator/iter_hints.c
++++ b/iterator/iter_hints.c
+@@ -252,6 +252,11 @@
+ 				s->name, p->str);
+ 			return 0;
+ 		}
++#ifndef HAVE_SSL_SET1_HOST
++		if(auth_name)
++			log_err("no name verification functionality in "
++				"ssl library, ignored name for %s", p->str);
++#endif
+ 		if(!delegpt_add_addr_mlc(dp, &addr, addrlen, 0, 0,
+ 			auth_name)) {
+ 			log_err("out of memory");