├── tests ├── integration │ ├── fixtures │ │ ├── __init__.py │ │ └── setup.py │ ├── tools │ │ ├── __init__.py │ │ ├── verify.py │ │ └── sniffer.py │ ├── conf │ │ └── basic.json │ └── test_basic.py ├── ci │ ├── requirements.txt │ ├── install.sh │ └── run.sh ├── Makefile.am └── check.sh ├── autogen.sh ├── AUTHORS ├── examples ├── simple.json └── bridged.json ├── src ├── Makefile.am ├── logging.h ├── misc.h ├── options.h ├── logging.c ├── packet.h ├── conf.h ├── packet.c ├── misc.c ├── conf.c ├── options.c ├── dhcp-helper.c └── queue.h ├── Makefile.am ├── ChangeLog.md ├── .gitignore ├── dhcp-helper.8 ├── .travis.yml ├── configure.ac ├── README.md └── COPYING /tests/integration/fixtures/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/integration/tools/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/ci/requirements.txt: -------------------------------------------------------------------------------- 1 | pytest>=2.9.0 2 | scapy>=2.2.0 3 | -------------------------------------------------------------------------------- /tests/Makefile.am: -------------------------------------------------------------------------------- 1 | CLEANFILES = *.trs *.log 2 | 3 | TESTS = check.sh 4 | -------------------------------------------------------------------------------- /autogen.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | 3 | autoreconf --force --install --verbose 4 | -------------------------------------------------------------------------------- /tests/ci/install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | pip install -r tests/ci/requirements.txt 4 | -------------------------------------------------------------------------------- /tests/check.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cd .. 4 | tests/ci/run.sh 5 | status=$? 6 | 7 | exit $status 8 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Jonas Johansson 2 | Mattias Walström 3 | Thomas Eliassson 4 | 5 | Original Author: 6 | Simon Kelley 7 | -------------------------------------------------------------------------------- /tests/integration/conf/basic.json: -------------------------------------------------------------------------------- 1 | { 2 | "server": [ 3 | { 4 | "address": "127.0.0.1" 5 | }], 6 | "group": [ 7 | { 8 | "ifname" : "lo", 9 | "giaddr": "198.10.1.1" 10 | } 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /examples/simple.json: -------------------------------------------------------------------------------- 1 | { 2 | "server": [ 3 | { 4 | "address": "198.19.10.2" 5 | }], 6 | "group": [ 7 | { 8 | "giaddr": "198.19.20.1" 9 | } 10 | ] 11 | } 12 | 13 | -------------------------------------------------------------------------------- /tests/ci/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | ip netns add dhcp-helper-ns1 4 | ip netns exec dhcp-helper-ns1 bash -c "ip link set lo up" 5 | 6 | ip netns exec dhcp-helper-ns1 bash -c "(cd tests/integration; pytest)" 7 | status=$? 8 | 9 | ip netns del dhcp-helper-ns1 10 | 11 | exit $status 12 | -------------------------------------------------------------------------------- /src/Makefile.am: -------------------------------------------------------------------------------- 1 | bin_PROGRAMS = dhcp-helper 2 | 3 | dhcp_helper_CFLAGS = -W -Wall -Wextra -fno-strict-aliasing 4 | dhcp_helper_CFLAGS += $(JANSSON_CFLAGS) $(LIBNL_CFLAGS) 5 | dhcp_helper_LDADD = $(JANSSON_LIBS) $(LIBNL_LIBS) 6 | dhcp_helper_SOURCES = dhcp-helper.c options.h queue.h conf.c conf.h \ 7 | packet.c packet.h options.c logging.c logging.h \ 8 | misc.c misc.h 9 | -------------------------------------------------------------------------------- /tests/integration/fixtures/setup.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import subprocess 3 | 4 | @pytest.fixture() 5 | def setup(): 6 | print "[!] Start DHCP Relay Agent" 7 | args = ["../../dhcp-helper", "-d", "-f", "conf/basic.json"] 8 | proc = subprocess.Popen(args=args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 9 | 10 | yield setup 11 | 12 | proc.kill() 13 | print "[!] Kill DHCP Relay Agent" 14 | -------------------------------------------------------------------------------- /tests/integration/tools/verify.py: -------------------------------------------------------------------------------- 1 | from scapy.all import * 2 | 3 | class Verify(): 4 | 5 | @staticmethod 6 | def giaddr(pkt, giaddr): 7 | """ Verify DHCP packet""" 8 | for packet in pkt: 9 | 10 | if not packet.haslayer(DHCP): 11 | continue 12 | 13 | if packet[BOOTP].giaddr == giaddr: 14 | return True 15 | else: 16 | print("\nfailed: wrong giaddr: " + packet[BOOTP].giaddr) 17 | return False 18 | 19 | return False 20 | -------------------------------------------------------------------------------- /tests/integration/test_basic.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import time 3 | from scapy.all import * 4 | from fixtures.setup import * 5 | from tools.sniffer import Sniffer 6 | from tools.verify import Verify 7 | 8 | interface = "lo" 9 | giaddr = "198.10.1.1" 10 | 11 | def test_basic(setup): 12 | 13 | print "[!] Starting sniffer" 14 | sniffer = Sniffer(interface, "dst host 127.0.0.1 and udp port 67") 15 | sniffer.capture() 16 | time.sleep(1) 17 | 18 | print "[!] Send DHCP request" 19 | dhcp_request(iface=interface, timeout=1) 20 | 21 | print "[!] Verify data from sniffer" 22 | pkt = sniffer.report() 23 | 24 | assert Verify.giaddr(pkt, giaddr) 25 | -------------------------------------------------------------------------------- /Makefile.am: -------------------------------------------------------------------------------- 1 | SUBDIRS = src tests 2 | AUTOMAKE_OPTIONS = subdir-objects 3 | ACLOCAL_AMFLAGS = ${ACLOCAL_FLAGS} 4 | 5 | doc_DATA = README.md ChangeLog.md 6 | EXTRA_DIST = README.md ChangeLog.md 7 | dist_man8_MANS = dhcp-helper.8 8 | dist_noinst_SCRIPTS = autogen.sh 9 | 10 | # Generate MD5 checksum file 11 | MD5 = md5sum 12 | md5-dist: 13 | @for file in $(DIST_ARCHIVES); do \ 14 | $(MD5) $$file > $$file.md5; \ 15 | done 16 | 17 | # Target to run when building a release 18 | release: dist md5-dist 19 | @for file in $(DIST_ARCHIVES); do \ 20 | printf "$$file \tDistribution tarball\n"; \ 21 | printf "$$file.md5\t"; cat $$file.md5 | cut -f1 -d' '; \ 22 | done 23 | -------------------------------------------------------------------------------- /ChangeLog.md: -------------------------------------------------------------------------------- 1 | Change Log 2 | ========== 3 | 4 | All notable changes to the project are documented in this file. 5 | 6 | - Versions >= v2.0, Westermo Teleindustri AB 7 | - Versions <= v1.2, Simon Kelley 8 | 9 | [v2.1][] - 2018-06-11 10 | --------------------- 11 | ### Changes 12 | - Add unittest 13 | - Add ARP entry to be able to send unicast answer to clients 14 | - Add FDB entry in bridge to fix issue with some switches 15 | - Minor bugfixes 16 | 17 | v2.0 - 2018-05-31 18 | --------------------- 19 | ### Changes 20 | - Add support to run agent to run with bridges 21 | - Add support for configuration via configuration file 22 | - Add DHCP Option 82 support 23 | 24 | [v2.1]: https://github.com/westermo/dhcp-helper/compare/v2.0...v2.1 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # http://www.gnu.org/software/automake 2 | 3 | *.o 4 | .deps 5 | .dirstamp 6 | 7 | Makefile 8 | Makefile.in 9 | compile 10 | configure 11 | depcomp 12 | install-sh 13 | missing 14 | INSTALL 15 | 16 | /ar-lib 17 | /mdate-sh 18 | /py-compile 19 | /test-driver 20 | /ylwrap 21 | 22 | # http://www.gnu.org/software/autoconf 23 | 24 | /autom4te.cache 25 | /autoscan.log 26 | /autoscan-*.log 27 | /aclocal.m4 28 | /config.guess 29 | /config.sub 30 | /configure.scan 31 | stamp-h1 32 | config.* 33 | !src/include/config.* 34 | src/include/config.h 35 | src/include/config.h.in 36 | 37 | # https://www.gnu.org/software/global/ 38 | GPATH 39 | GRTAGS 40 | GSYMS 41 | GTAGS 42 | ID 43 | 44 | # https://www.gnu.org/software/libtool/ 45 | 46 | /ltmain.sh 47 | 48 | # http://www.gnu.org/software/texinfo 49 | 50 | /texinfo.tex 51 | 52 | dhcp-helper 53 | 54 | *~ 55 | -------------------------------------------------------------------------------- /src/logging.h: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2018 Westermo Teleindustri AB 4 | 5 | This program is free software; you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation; version 2 dated June, 1991, or 8 | (at your option) version 3 dated 29 June, 2007. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #ifndef __LOGGING_H__ 20 | #define __LOGGING_H__ 21 | 22 | #include 23 | 24 | void syslog2 (int level, const char *format, ...); 25 | void log_console(int enable); 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /src/misc.h: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2004,2008 Simon Kelley 4 | Copyright (c) 2018 Westermo Teleindustri AB 5 | 6 | This program is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; version 2 dated June, 1991, or 9 | (at your option) version 3 dated 29 June, 2007. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | #ifndef __MISC_H__ 20 | #define __MISC_H__ 21 | #include "conf.h" 22 | 23 | int setup_nftables(cfg_t *cfg); 24 | int cleanup_nftables(cfg_t *cfg); 25 | int add_arp_entry(int ifindex, unsigned char *mac, struct sockaddr_in saddr); 26 | int add_fdb_entry(int ifindex, unsigned char *mac); 27 | #endif 28 | -------------------------------------------------------------------------------- /src/options.h: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2004,2008 Simon Kelley 4 | Copyright (c) 2018 Westermo Teleindustri AB 5 | 6 | This program is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; version 2 dated June, 1991, or 9 | (at your option) version 3 dated 29 June, 2007. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #ifndef __OPTIONS_H__ 21 | #define __OPTIONS_H__ 22 | #include "packet.h" 23 | 24 | size_t add_options (struct dhcp_packet_with_opts *mess, size_t sz, int iface_index, struct in_addr iface_addr, cfg_group_t *group, cfg_t *cfg); 25 | size_t remove_options(struct dhcp_packet_with_opts *mess, size_t sz); 26 | 27 | #endif 28 | -------------------------------------------------------------------------------- /dhcp-helper.8: -------------------------------------------------------------------------------- 1 | .TH DHCP-HELPER 8 2 | .SH NAME 3 | dhcp-helper \- A DHCP/BOOTP relay agent. 4 | .SH SYNOPSIS 5 | .B dhcp-helper 6 | .I [OPTION]... 7 | .SH "DESCRIPTION" 8 | .BR dhcp-helper 9 | is a DHCP and BOOTP relay agent. It listens for DHCP and BOOTP broadcasts on directly connected 10 | subnets and relays them to DHCP or BOOTP servers elsewhere. It also relays replies from the remote 11 | servers back to partially configured hosts. Once hosts are fully configured they can communicate 12 | directly with their servers and no longer need the services of a relay. 13 | 14 | .SH OPTIONS 15 | dhcp-helper requires a configuration file to operate correctly. The 16 | .B \-f 17 | option is used to specify a configuration file. 18 | .TP 19 | .B \-f 20 | Specify the configuration file to be used. 21 | .TP 22 | .B \-d 23 | Log all levels to stdout, used for debugging. 24 | .TP 25 | .B \-v 26 | Report the software release version. 27 | .TP 28 | .B \-h 29 | Show usage. 30 | .SH NOTES 31 | When running with a bridge, nftables is required. 32 | .SH AUTHOR 33 | Written by Jonas Johansson, Mattias Walström and Thomas Eliassson 34 | .br 35 | Original written by: Simon Kelley 36 | 37 | 38 | -------------------------------------------------------------------------------- /examples/bridged.json: -------------------------------------------------------------------------------- 1 | { 2 | "option82": { 3 | "remote-id": { 4 | "type": "hostname" 5 | } 6 | }, 7 | "server": [ 8 | { 9 | "address": "192.168.2.1", 10 | "port": 1067 11 | }, 12 | { 13 | "address": "192.168.3.1", 14 | "port": 67 15 | } 16 | ], 17 | "group": [ 18 | { 19 | "ifname": "vlan1", 20 | "giaddr": "192.168.1.6", 21 | "iface": [ 22 | { 23 | "ifname": "eth0" 24 | }, 25 | { 26 | "ifname": "eth6", 27 | "circuit-id": "switch10" 28 | } 29 | ], 30 | "server": [ 31 | { 32 | "address": "192.168.100.2", 33 | "port": 67 34 | } 35 | ] 36 | }, 37 | { 38 | "ifname": "vlan2", 39 | "giaddr": "192.168.100.1", 40 | "iface": [ 41 | { 42 | "ifname": "eth3" 43 | }, 44 | { 45 | "ifname": "eth8" 46 | } 47 | ] 48 | } 49 | ] 50 | } 51 | -------------------------------------------------------------------------------- /src/logging.c: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2018 Westermo Teleindustri AB 4 | 5 | This program is free software; you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation; version 2 dated June, 1991, or 8 | (at your option) version 3 dated 29 June, 2007. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include "logging.h" 22 | 23 | static int console = 0; 24 | 25 | /* 26 | * Makes it possible to log to console only for debugging. 27 | */ 28 | void syslog2 (int level, const char *format, ...) 29 | { 30 | va_list args; 31 | va_start(args, format); 32 | 33 | if (console) 34 | { 35 | vprintf(format, args); 36 | printf("\n"); 37 | } 38 | else 39 | vsyslog(level, format, args); 40 | va_end(args); 41 | } 42 | 43 | void log_console(int enable) 44 | { 45 | console = enable; 46 | } 47 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | # Travis CI integration 2 | # Defaults to GNU GCC and autotools: ./configure && make && make test 3 | language: c 4 | 5 | sudo: required 6 | 7 | # It is not really needed, other than for showing correct language tag in Travis CI build log. 8 | language: c 9 | compiler: 10 | - gcc 11 | - clang 12 | 13 | addons: 14 | apt: 15 | packages: 16 | - tree 17 | - libnl-3-dev 18 | - libnl-3-200 19 | - libnl-route-3-200 20 | - libnl-genl-3-200 21 | - libnl-route-3-dev 22 | - libnl-genl-3-dev 23 | - libjansson-dev 24 | - libev-dev 25 | - tcpdump 26 | - python-pip 27 | 28 | # before_install: 29 | # - docker run --privileged -d --name travis-ci -v $(pwd):/travis ubuntu:xenial tail -f /dev/null 30 | # - docker ps 31 | 32 | # install: 33 | # - docker exec -t travis-ci bash -c "apt-get update; 34 | # apt-get install -y libnl-3-dev libnl-3-200 libnl-route-3-200 libnl-genl-3-200 libnl-route-3-dev libnl-genl-3-dev libjansson-dev libev-dev build-essential autoconf automake pkg-config clang tcpdump iproute2 python-pip; 35 | # mv /usr/sbin/tcpdump /usr/local/bin/; ln -s /usr/local/bin/tcpdump /usr/sbin/" 36 | 37 | # script: 38 | # - docker exec -t travis-ci bash -c "cd /travis; ./autogen.sh && ./configure && make && tests/ci/install.sh && tests/ci/run.sh" 39 | 40 | # We don't store generated files (configure and Makefile) in GIT, 41 | # so we must customize the default build script to run ./autogen.sh 42 | script: 43 | - ./autogen.sh 44 | - ./configure --prefix= 45 | - make V=1 all 46 | - make V=1 install-strip DESTDIR=~/tmp 47 | - tree -h ~/tmp 48 | - ldd ~/tmp/bin/dhcp-helper 49 | - size ~/tmp/bin/dhcp-helper 50 | - ~/tmp/bin/dhcp-helper -h 51 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | AC_INIT([dhcp-helper], [2.2-pre], [], [dhcp-helper]) 2 | AC_PREREQ([2.59]) 3 | AC_CONFIG_HEADERS([src/config.h]) 4 | 5 | AC_CONFIG_SRCDIR([src/dhcp-helper.c]) 6 | AC_CONFIG_FILES([Makefile src/Makefile tests/Makefile]) 7 | 8 | AC_PROG_CPP 9 | AC_PROG_CC 10 | 11 | # Lax strictness, don't define PACKAGE and VERSION in config.h 12 | AM_INIT_AUTOMAKE([1.10 foreign no-define]) 13 | 14 | # Checks for header files. 15 | AC_HEADER_STDC 16 | AC_CHECK_HEADERS([sys/socket.h]) 17 | AC_CHECK_HEADERS([sys/ioctl.h]) 18 | AC_CHECK_HEADERS([sys/select.h]) 19 | AC_CHECK_HEADERS([sys/time.h]) 20 | AC_CHECK_HEADERS([sys/stat.h]) 21 | AC_CHECK_HEADERS([limits.h]) 22 | AC_CHECK_HEADERS([net/if.h]) 23 | AC_CHECK_HEADERS([unistd.h]) 24 | AC_CHECK_HEADERS([fcntl.h]) 25 | AC_CHECK_HEADERS([stdio.h]) 26 | AC_CHECK_HEADERS([string.h]) 27 | AC_CHECK_HEADERS([stdlib.h]) 28 | AC_CHECK_HEADERS([time.h]) 29 | AC_CHECK_HEADERS([errno.h]) 30 | AC_CHECK_HEADERS([pwd.h]) 31 | AC_CHECK_HEADERS([grp.h]) 32 | AC_CHECK_HEADERS([netdb.h]) 33 | AC_CHECK_HEADERS([linux/types.h]) 34 | AC_CHECK_HEADERS([linux/capability.h]) 35 | 36 | AC_CHECK_HEADERS([sys/prctl.h]) 37 | AC_CHECK_HEADERS([net/if_arp.h]) 38 | 39 | AC_CHECK_HEADERS([linux/netlink.h]) 40 | 41 | # Check for pkg-config first, warn if it's not installed 42 | PKG_PROG_PKG_CONFIG 43 | 44 | PKG_CHECK_MODULES([LIBNL], [libnl-3.0 libnl-genl-3.0 libnl-route-3.0]) 45 | PKG_CHECK_MODULES([JANSSON], [jansson]) 46 | 47 | AC_CHECK_HEADER([ev.h], 48 | [AC_CHECK_LIB([ev], [ev_loop_new], 49 | [], 50 | [AC_MSG_ERROR("libev not found")] )], 51 | [AC_MSG_ERROR("ev.h not found")] 52 | ) 53 | 54 | # Checks for typedefs, structures, and compiler characteristics. 55 | AC_TYPE_SIZE_T 56 | 57 | # distribute additional compiler and linker flags among Makefiles 58 | # --> set and change these variables instead of CXXFLAGS or LDFLAGS (for user only) 59 | AC_SUBST([AM_CFLAGS]) 60 | AC_SUBST([AM_LDFLAGS]) 61 | 62 | AC_SUBST([CFLAGS]) 63 | 64 | AC_OUTPUT 65 | -------------------------------------------------------------------------------- /src/packet.h: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2004,2008 Simon Kelley 4 | Copyright (c) 2018 Westermo Teleindustri AB 5 | 6 | This program is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; version 2 dated June, 1991, or 9 | (at your option) version 3 dated 29 June, 2007. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #ifndef __PACKET_H__ 21 | #define __PACKET_H__ 22 | #include "conf.h" 23 | 24 | #define DHCP_COOKIE 0x63825363 25 | 26 | #define MIN_PACKETSZ 300 27 | #define DHCP_PACKET_MAX 16384 /* hard limit on DHCP packet size */ 28 | 29 | #define INADDRSZ 4 30 | 31 | #define DHCP_CHADDR_MAX 16 32 | #define DHCP_SERVER_PORT 67 33 | #define DHCP_CLIENT_PORT 68 34 | #define DHCP_SERVER_ALTPORT 1067 35 | #define DHCP_CLIENT_ALTPORT 1068 36 | #define BOOTREQUEST 1 37 | #define BOOTREPLY 2 38 | 39 | #define DHCP_SERVER_PORT 67 40 | #define DHCP_CLIENT_PORT 68 41 | #define DHCP_SERVER_ALTPORT 1067 42 | #define DHCP_CLIENT_ALTPORT 1068 43 | 44 | #define BOOTREQUEST 1 45 | #define BOOTREPLY 2 46 | 47 | struct dhcp_packet_with_opts { 48 | struct dhcp_packet { 49 | unsigned char op, htype, hlen, hops; 50 | unsigned int xid; 51 | unsigned short secs, flags; 52 | struct in_addr ciaddr, yiaddr, siaddr, giaddr; 53 | unsigned char chaddr[DHCP_CHADDR_MAX], sname[64], file[128]; 54 | } header; 55 | unsigned char options[312]; 56 | }; 57 | 58 | typedef struct client_cache_t { 59 | TAILQ_ENTRY(client_cache_t) link; 60 | unsigned char hwaddr[DHCP_CHADDR_MAX]; 61 | struct in_addr giaddr; 62 | int ifindex; 63 | } client_cache_t; 64 | 65 | int handle_packet(cfg_t *cfg, struct dhcp_packet *packet, ssize_t sz, int ifindex, int sd_out); 66 | 67 | #endif 68 | -------------------------------------------------------------------------------- /src/conf.h: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2018 Westermo Teleindustri AB 4 | 5 | This program is free software; you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation; version 2 dated June, 1991, or 8 | (at your option) version 3 dated 29 June, 2007. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #ifndef __CONF_H__ 20 | #define __CONF_H__ 21 | 22 | #include "queue.h" 23 | #include 24 | 25 | #define SCRIPT_LEN 100 26 | #define CIRCUIT_ID_LEN 50 27 | #define REMOTE_ID_LEN 50 28 | 29 | typedef enum option82_rid_type_t { 30 | RID_TYPE_HOSTNAME, 31 | RID_TYPE_GIADDR, 32 | RID_TYPE_MANUAL, 33 | } opt82_rid_type_t; 34 | 35 | typedef enum option82_cid_type_t { 36 | CID_TYPE_IFNAME, 37 | CID_TYPE_MANUAL, 38 | } opt82_cid_type_t; 39 | 40 | typedef struct cfg_iface_t { 41 | TAILQ_ENTRY(cfg_iface_t) link; 42 | int ifindex; 43 | 44 | opt82_cid_type_t type; 45 | char circuit_id[CIRCUIT_ID_LEN]; 46 | int circuit_id_len; 47 | ev_io io; 48 | int sd; /* sd in io, for clean-up access */ 49 | } cfg_iface_t; 50 | 51 | typedef struct cfg_group_t { 52 | TAILQ_ENTRY(cfg_group_t) link; 53 | TAILQ_HEAD(, cfg_iface_t) iface_list; 54 | TAILQ_HEAD(, cfg_server_t) server_list; 55 | unsigned int ifindex; 56 | int giaddr; 57 | } cfg_group_t; 58 | 59 | typedef struct cfg_server_t { 60 | TAILQ_ENTRY(cfg_server_t) link; 61 | int addr; 62 | int port; 63 | } cfg_server_t; 64 | 65 | typedef struct cfg_opt82 { 66 | int enabled; 67 | opt82_rid_type_t rid_type; 68 | 69 | char remote_id[REMOTE_ID_LEN]; 70 | int remote_id_len; 71 | } cfg_opt82_t; 72 | 73 | typedef struct cfg_t { 74 | TAILQ_HEAD(, cfg_server_t) server_list; 75 | TAILQ_HEAD(, cfg_group_t) group_list; 76 | cfg_opt82_t opt82; 77 | int force_server_id; 78 | int udp_listen_port; 79 | } cfg_t; 80 | 81 | int conf_read(cfg_t *cfg, char *file); 82 | void conf_free(cfg_t *cfg); 83 | #endif 84 | -------------------------------------------------------------------------------- /tests/integration/tools/sniffer.py: -------------------------------------------------------------------------------- 1 | import signal 2 | import subprocess 3 | import tempfile 4 | import threading 5 | import time 6 | from scapy.all import * 7 | 8 | class Sniffer(): 9 | popenlock = threading.Lock() 10 | 11 | def __init__(self, iface, my_filter=None): 12 | self.iface = iface 13 | self.filter = my_filter 14 | self.proc = None 15 | tmpnam = "pcap_" + iface + "_" 16 | self.fnamefd, self.fname = tempfile.mkstemp(prefix=tmpnam) 17 | return 18 | 19 | def capture(self): 20 | """Starts the sniffer as a separate process""" 21 | if self.proc: 22 | self.proc.kill() 23 | self.proc = None 24 | 25 | args = [] 26 | args += ["/usr/sbin/tcpdump", "-l", "-nN", 27 | "-i", self.iface, 28 | "-w", self.fname, 29 | "-s", str(3000), 30 | "-U"] 31 | 32 | if self.filter: 33 | if not isinstance(self.filter, list): 34 | self.filter = [self.filter] 35 | args += self.filter 36 | 37 | # Lock thread, popen might not be thread safe 38 | Sniffer.popenlock.acquire() 39 | try: 40 | print('Starting tcpdump cmd: %s' % ' '.join(args)) 41 | self.proc = subprocess.Popen(args=args, stderr=subprocess.PIPE) 42 | finally: 43 | Sniffer.popenlock.release() 44 | 45 | self.proc.stderr.readline() 46 | 47 | return 48 | 49 | def kill_and_wait(self): 50 | """Stop the running process if any and wait for it to finish""" 51 | if not self.proc: 52 | return False 53 | 54 | self.proc.send_signal(signal.SIGINT) 55 | time.sleep(0.5) 56 | if not self.proc.poll(): 57 | # Process is still alive 58 | time.sleep(1) 59 | try: 60 | self.proc.kill() 61 | except OSError: 62 | pass 63 | 64 | self.proc.wait() 65 | self.proc = None 66 | 67 | return True 68 | 69 | def report(self): 70 | """Terminate the sniffer and return the gathered data""" 71 | if not self.kill_and_wait(): 72 | return None 73 | 74 | if not os.path.exists(self.fname): 75 | return [] 76 | if os.path.getsize(self.fname) == 0: 77 | return [] 78 | try: 79 | cap = rdpcap(self.fname) 80 | except Scapy_Exception: # No packets received 81 | return [] 82 | 83 | os.remove(self.fname) 84 | 85 | return cap 86 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | dhcp-helper - DHCP relay agent w/ Option 82 support 2 | =================================================== 3 | [![License Badge][]][License] [![Travis Status][]][Travis] 4 | 5 | A DHCP relay agent is commonly used in routed networks with centralized 6 | DHCP services. The relay agent is a service typically configured on a 7 | router where it converts all DHCP broadcast messages from clients into 8 | unicast messages which it forwards to the central DHCP server(s). 9 | 10 | dhcp-helper listens for DHCP and BOOTP broadcasts on all its configured 11 | interfaces and relays them to DHCP or BOOTP servers elsewhere. It also 12 | relays replies from the remote servers back to the hosts. Once hosts 13 | are fully configured they can communicate directly with their servers 14 | and no longer need the services of a relay. 15 | 16 | In some setups it is preferred to always enforce communication via the 17 | DHCP relay. This usually coincides with requirements for DHCP Option 18 | 82, i.e., where the relay tucks on extra information for the server 19 | regarding which port a host is connected to and from which relay the 20 | request is forwarded from. In Option 82 terms these are called the 21 | circuit id and remote id, respectively. For more information, see IETF 22 | [RFC 3046](https://tools.ietf.org/html/rfc3046). 23 | 24 | dhcp-helper is optimized to run on a VLAN aware bridge, but work as well 25 | for a much simpler use case (see simple.json). If running with a bridge 26 | nftables is required (kernel support and userspace binary). This to stop 27 | DHCP packets that's already processed by the relay agent to be forwarded 28 | by the bridge. 29 | 30 | dhcp-helper requires a configuration file to operate correctly (default 31 | read from `/etc/dhcphelper.json` or specified via the `-f` 32 | option). The simplest configuration look like this: 33 | 34 | ``` 35 | { 36 | "server": [ 37 | { 38 | "address": "198.19.10.2" 39 | }], 40 | "group": [ 41 | { 42 | "giaddr": "198.19.20.1" 43 | } 44 | ] 45 | } 46 | ``` 47 | 48 | This configuration will listen for DHCP request on the local interface 49 | which has the IP address 198.19.20.1. An incoming DHCP request will 50 | then be relayed to a DHCP server at IP address 198.19.10.2. 51 | 52 | 53 | Building 54 | -------- 55 | 56 | Requirements on an Ubuntu 16.04 system: 57 | ``` 58 | apt-get install libnl-3-dev libnl-route-3-dev libnl-genl-3-dev libjansson-dev libev-dev 59 | ``` 60 | Build dhcp-helper: 61 | ``` 62 | ./configure && make && make install 63 | ``` 64 | 65 | 66 | Configuration 67 | ------------- 68 | 69 | simple.json - A very simple case where you only run the relay agent on one interface and no bridge. 70 | bridged.json - More advanced case with multiple servers and running on a VLAN aware bridge. 71 | 72 | ### Configuration file 73 | **option82** - Should option 82 be enabled, optional 74 | * **remote-id** - remote ID settings, optional 75 | * **type** - remote id type can either be manual [string or hex values](#string-or-hex-values), hostname or giaddr 76 | * **data** - only applicable when using manual 77 | 78 | **server** - array of servers, optional 79 | * **address** - IPv4 address of server, required 80 | * **port** - TCP port for the server, optional (default port 67) 81 | 82 | **group** - array of objects, required 83 | * **giaddr** - Local address to use when communicate with server, required 84 | * **ifname** - interface to broadcast answers to, if not specified it is the interface with giaddr, optional 85 | * **iface** - array of objects, optional 86 | * **ifname** - the name of the interface, required 87 | * **circuit-id** - value to send to the server, see [String or hex values](#string-or-hex-values) 88 | * **server** - object of objects, optional if specified globally, override global configured servers 89 | * **address** - Where to send, required 90 | * **port** - TCP port for the server, optional (default port 67) 91 | 92 | ### String or hex values 93 | Circuit-id and remote-id can be entered as hex values as well as string. 94 | 95 | As raw hex values: 96 | ``` 97 | "option82": { 98 | "remote-id": { 99 | "type": "manual", 100 | "data": [ 101 | "0x5a", 102 | "0x5a", 103 | "0x5a", 104 | "0x5a" 105 | ] 106 | } 107 | }, 108 | ``` 109 | as a string: 110 | ``` 111 | "option82": { 112 | "remote-id": { 113 | "type": "manual", 114 | "data": "test" 115 | } 116 | }, 117 | ``` 118 | 119 | 120 | Origin & References 121 | ------------------- 122 | 123 | dhcp-helper was originally written by Simon Kelley 124 | 125 | 126 | [License]: https://en.wikipedia.org/wiki/GPL_license 127 | [License Badge]: https://img.shields.io/badge/License-GPL%20v2-blue.svg 128 | [Travis]: https://travis-ci.org/westermo/dhcp-helper 129 | [Travis Status]: https://travis-ci.org/westermo/dhcp-helper.svg?branch=master 130 | -------------------------------------------------------------------------------- /src/packet.c: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2004,2008 Simon Kelley 4 | Copyright (c) 2018 Westermo Teleindustri AB 5 | 6 | This program is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; version 2 dated June, 1991, or 9 | (at your option) version 3 dated 29 June, 2007. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #include "config.h" 21 | 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | 30 | #include "logging.h" 31 | #include "packet.h" 32 | #include "options.h" 33 | #include "conf.h" 34 | #include 35 | #include "queue.h" 36 | #include "misc.h" 37 | 38 | int send_sd; 39 | 40 | union { 41 | struct cmsghdr align; /* this ensures alignment */ 42 | char control[CMSG_SPACE(sizeof(struct in_pktinfo))]; 43 | } control_u; 44 | 45 | /* Search for group by iface index. 46 | * @Return NULL if not found. */ 47 | cfg_group_t *find_group(cfg_t *cfg, int ifindex) 48 | { 49 | cfg_group_t *entry; 50 | cfg_iface_t *entry2; 51 | 52 | TAILQ_FOREACH(entry, &cfg->group_list, link) { 53 | TAILQ_FOREACH(entry2, &entry->iface_list, link) { 54 | int index = entry2->ifindex; 55 | 56 | if (index == ifindex) 57 | return entry; 58 | } 59 | } 60 | return NULL; 61 | } 62 | 63 | /* Search for group by giaddr. 64 | * @Return NULL if not found. */ 65 | cfg_group_t *find_group_by_giaddr(cfg_t *cfg, struct in_addr giaddr) 66 | { 67 | cfg_group_t *entry; 68 | cfg_iface_t *entry2; 69 | 70 | TAILQ_FOREACH(entry, &cfg->group_list, link) { 71 | TAILQ_FOREACH(entry2, &entry->iface_list, link) { 72 | if ((in_addr_t)entry->giaddr == giaddr.s_addr) 73 | return entry; 74 | } 75 | } 76 | return NULL; 77 | } 78 | 79 | /* Is already gatewayed by us? 80 | * TODO: Is this needed? Inherited from original dhcp-helper */ 81 | static int is_local_gw(cfg_t *cfg, in_addr_t s_addr) 82 | { 83 | cfg_group_t *entry; 84 | 85 | TAILQ_FOREACH(entry, &cfg->group_list, link) { 86 | if (s_addr == (in_addr_t)entry->giaddr) 87 | return 1; 88 | } 89 | return 0; 90 | } 91 | 92 | static int handle_request(cfg_t *cfg, struct dhcp_packet *packet, int ifindex, ssize_t sz) 93 | { 94 | struct sockaddr_in saddr; 95 | cfg_group_t *group; 96 | cfg_server_t *server; 97 | 98 | memset(&saddr, 0, sizeof(saddr)); 99 | 100 | syslog2(LOG_DEBUG, "Received a request"); 101 | 102 | group = find_group(cfg, ifindex); 103 | if (!group) { 104 | syslog2(LOG_ERR, "Received packet on wrong interface (ifindex: %d), discarding it.", ifindex); 105 | return 1; 106 | } 107 | /* already relayed ? */ 108 | if (packet->giaddr.s_addr) { 109 | syslog2(LOG_DEBUG, "Already relayed by %s", inet_ntoa(packet->giaddr)); 110 | 111 | if (is_local_gw(cfg, packet->giaddr.s_addr)) { 112 | /* RFC3046, 2.1.1, discard if spoofed */ 113 | syslog2(LOG_NOTICE, "Already relayed by this relay agent or spoofed!"); 114 | return 0; 115 | } 116 | 117 | /* RFC3046, 2.1.1, simply forward if giaddr set, 118 | * without changing giaddr or adding option82.*/ 119 | } else { 120 | struct in_addr addr; 121 | 122 | syslog2(LOG_DEBUG, "Will relay"); 123 | /* plug in our address */ 124 | 125 | addr.s_addr = packet->giaddr.s_addr = group->giaddr; 126 | if (cfg->opt82.enabled) 127 | sz = add_options((struct dhcp_packet_with_opts *)packet, sz, ifindex, addr, group, cfg); 128 | } 129 | 130 | if (!TAILQ_EMPTY(&group->server_list)) { 131 | TAILQ_FOREACH(server, &group->server_list, link) { 132 | //saddr.sin_family = AF_INET; 133 | saddr.sin_addr.s_addr = server->addr; 134 | saddr.sin_port = htons(server->port); 135 | syslog2(LOG_DEBUG, "Forward request to %s!", inet_ntoa(saddr.sin_addr)); 136 | while (sendto(send_sd, packet, sz, 0, (struct sockaddr *)&saddr, sizeof(saddr)) == -1 && errno == EINTR) ; 137 | } 138 | } else { 139 | TAILQ_FOREACH(server, &cfg->server_list, link) { 140 | //saddr.sin_family = AF_INET; 141 | saddr.sin_addr.s_addr = server->addr; 142 | saddr.sin_port = htons(server->port); 143 | syslog2(LOG_DEBUG, "Forward request to %s!", inet_ntoa(saddr.sin_addr)); 144 | while (sendto(send_sd, packet, sz, 0, (struct sockaddr *)&saddr, sizeof(saddr)) == -1 && errno == EINTR) ; 145 | } 146 | } 147 | if (add_fdb_entry(ifindex, packet->chaddr)) { 148 | syslog2(LOG_ERR, "Failed adding FDB entry to bridge"); 149 | return 1; 150 | } 151 | 152 | return 0; 153 | } 154 | 155 | int handle_reply(cfg_t *cfg, struct dhcp_packet *packet, int ifindex, ssize_t sz) 156 | { 157 | struct msghdr msg; 158 | struct iovec iov; 159 | struct sockaddr_in saddr; 160 | struct in_pktinfo *pkt; 161 | cfg_group_t *group; 162 | struct cmsghdr *cmptr; 163 | int result = 0; 164 | 165 | syslog2(LOG_DEBUG, "Received a reply on ifindex %d", ifindex); 166 | /* packet from server send back to client */ 167 | 168 | group = find_group_by_giaddr(cfg, packet->giaddr); 169 | 170 | memset(&saddr, 0, sizeof(saddr)); 171 | 172 | memset(&msg, 0, sizeof(msg)); 173 | msg.msg_control = control_u.control; 174 | msg.msg_controllen = sizeof(control_u); 175 | msg.msg_name = &saddr; 176 | msg.msg_namelen = 0; 177 | msg.msg_iov = &iov; 178 | msg.msg_iovlen = 1; 179 | 180 | saddr.sin_port = htons(DHCP_CLIENT_PORT); 181 | msg.msg_control = NULL; 182 | msg.msg_controllen = 0; 183 | msg.msg_namelen = sizeof(saddr); 184 | 185 | iov.iov_base = packet; 186 | iov.iov_len = sz; 187 | 188 | /* I'm the gateway, remove options (option 82) and reset giaddr */ 189 | if (group) { 190 | sz = remove_options((struct dhcp_packet_with_opts *)packet, sz); 191 | packet->giaddr.s_addr = 0; 192 | } 193 | if (packet->ciaddr.s_addr) 194 | saddr.sin_addr = packet->ciaddr; 195 | else if (ntohs(packet->flags) & 0x8000 || !packet->yiaddr.s_addr || packet->hlen > 14) { 196 | syslog2(LOG_DEBUG, "Send broadcast reply."); 197 | /* broadcast to 255.255.255.255 */ 198 | msg.msg_controllen = sizeof(control_u); 199 | msg.msg_control = control_u.control; 200 | cmptr = CMSG_FIRSTHDR(&msg); 201 | saddr.sin_addr.s_addr = INADDR_BROADCAST; 202 | pkt = (struct in_pktinfo *)CMSG_DATA(cmptr); 203 | if (!pkt) 204 | return 1; 205 | pkt->ipi_ifindex = group->ifindex; 206 | pkt->ipi_spec_dst.s_addr = 0; 207 | msg.msg_controllen = cmptr->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); 208 | cmptr->cmsg_level = SOL_IP; 209 | cmptr->cmsg_type = IP_PKTINFO; 210 | } else if (group) { 211 | /* client not configured and cannot reply to ARP. 212 | Insert arp entry direct. */ 213 | saddr.sin_addr = packet->yiaddr; 214 | 215 | msg.msg_name = &saddr; 216 | syslog2(LOG_DEBUG, "Send unicast reply to %s.", inet_ntoa(saddr.sin_addr)); 217 | add_arp_entry(group->ifindex, packet->chaddr, saddr); 218 | } else 219 | return 1; 220 | 221 | do { 222 | result = sendmsg(send_sd, &msg, 0); 223 | if (result < 0) 224 | syslog2(LOG_WARNING, "Sending error: %m"); 225 | } while (result == -1 && errno == EINTR); 226 | 227 | return 0; 228 | } 229 | 230 | int handle_packet(cfg_t *cfg, struct dhcp_packet *packet, ssize_t sz, int ifindex, int sd_out) 231 | { 232 | send_sd = sd_out; 233 | /* rfc1542 says discard if > 16 */ 234 | if ((packet->hops++) > 16) 235 | return 1; 236 | 237 | if (packet->hlen > DHCP_CHADDR_MAX) 238 | return 1; 239 | 240 | if (packet->op == BOOTREQUEST) 241 | handle_request(cfg, packet, ifindex, sz); 242 | else if (packet->op == BOOTREPLY) 243 | handle_reply(cfg, packet, ifindex, sz); 244 | 245 | return 0; 246 | } 247 | -------------------------------------------------------------------------------- /src/misc.c: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2004,2008 Simon Kelley 4 | Copyright (c) 2018 Westermo Teleindustri AB 5 | 6 | This program is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; version 2 dated June, 1991, or 9 | (at your option) version 3 dated 29 June, 2007. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | #include 29 | #include 30 | #include 31 | #include 32 | 33 | #include "conf.h" 34 | #include "logging.h" 35 | 36 | #define NFT_IN_CHAIN "dhcpr-input" 37 | #define NFT_FWD_CHAIN "dhcpr-forward " 38 | 39 | static char *mac_ntoa(unsigned char *ptr) 40 | { 41 | static char address[30]; 42 | 43 | sprintf(address, "%02X:%02X:%02X:%02X:%02X:%02X", ptr[0], ptr[1], ptr[2], ptr[3], ptr[4], ptr[5]); 44 | 45 | return (address); 46 | } 47 | 48 | static int iface_is_bridged(struct nl_sock *sk, int ifindex) 49 | { 50 | struct rtnl_link *link, *master; 51 | 52 | rtnl_link_get_kernel(sk, ifindex, NULL, &link); 53 | /* Only add nftables rules if interface is bridged. */ 54 | if (link) { 55 | if (rtnl_link_get_master(link)) { 56 | rtnl_link_get_kernel(sk, rtnl_link_get_master(link), NULL, &master); 57 | if (rtnl_link_is_bridge(master)) { 58 | rtnl_link_put(master); 59 | rtnl_link_put(link); 60 | return 1; 61 | } 62 | } 63 | rtnl_link_put(link); 64 | } 65 | 66 | return 0; 67 | } 68 | 69 | int setup_nftables(cfg_t *cfg) 70 | { 71 | cfg_group_t *group; 72 | cfg_iface_t *iface; 73 | char file[128] = "/tmp/dhcp-helper.XXXXXX"; 74 | char cmd[256], ifname[IFNAMSIZ]; 75 | FILE *fp; 76 | struct nl_sock *sk; 77 | int err = 0, fd, anybridged = 0; 78 | mode_t cur_umask; 79 | 80 | cur_umask = umask(0600); 81 | fd = mkstemp(file); 82 | umask(cur_umask); 83 | if (fd == -1) { 84 | syslog2(LOG_ERR, "Could not generate tempfile"); 85 | return 1; 86 | } 87 | 88 | fp = fdopen(fd, "w+"); 89 | if (!fp) { 90 | close(fd); 91 | syslog2(LOG_ERR, "Could not open tempfile"); 92 | err = 1; 93 | goto err_unlink; 94 | } 95 | 96 | sk = nl_socket_alloc(); 97 | if (!sk) { 98 | err = -NLE_NOMEM; 99 | goto err_close_fp; 100 | } 101 | 102 | err = nl_connect(sk, NETLINK_ROUTE); 103 | if (err) 104 | goto err_free_sk; 105 | 106 | fprintf(fp, "table bridge filter {\n"); 107 | fprintf(fp, "chain " NFT_IN_CHAIN " {\n type filter hook input priority -200\n"); 108 | TAILQ_FOREACH(group, &cfg->group_list, link) { 109 | TAILQ_FOREACH(iface, &group->iface_list, link) { 110 | if (iface_is_bridged(sk, iface->ifindex)) { 111 | anybridged = 1; 112 | if_indextoname(iface->ifindex, ifname); 113 | syslog2(LOG_DEBUG, "Interface %s is bridged, setting up nftables", ifname); 114 | fprintf(fp, "iif %s ip protocol udp udp dport 67 drop\n", ifname); 115 | } 116 | } 117 | } 118 | fprintf(fp, "}\n"); 119 | 120 | fprintf(fp, "chain " NFT_FWD_CHAIN " {\n type filter hook forward priority -200\n"); 121 | TAILQ_FOREACH(group, &cfg->group_list, link) { 122 | TAILQ_FOREACH(iface, &group->iface_list, link) { 123 | /* Only add nftables rules if interface is bridged. */ 124 | if (iface_is_bridged(sk, iface->ifindex)) { 125 | anybridged = 1; 126 | if_indextoname(iface->ifindex, ifname); 127 | syslog2(LOG_DEBUG, "Interface %s is bridged, setting up nftables", ifname); 128 | fprintf(fp, "pkttype broadcast iif %s ip protocol udp udp dport 67 drop\n", ifname); 129 | } 130 | } 131 | } 132 | fprintf(fp, "}\n}"); 133 | 134 | fprintf(fp, "\n"); 135 | err_free_sk: 136 | nl_socket_free(sk); 137 | err_close_fp: 138 | fclose(fp); 139 | if (anybridged) { 140 | snprintf(cmd, sizeof(cmd), "nft -f %s", file); 141 | if (system(cmd)) 142 | syslog2(LOG_ERR, "Failed applying nftables rules"); 143 | } 144 | err_unlink: 145 | unlink(file); 146 | 147 | return err; 148 | } 149 | 150 | int cleanup_nftables(cfg_t *cfg) 151 | { 152 | cfg_group_t *group; 153 | int anybridged = 0; 154 | struct nl_sock *sk; 155 | 156 | sk = nl_socket_alloc(); 157 | if (!sk) { 158 | return 1; 159 | } 160 | 161 | if (nl_connect(sk, NETLINK_ROUTE)) 162 | goto err_free_sk; 163 | 164 | TAILQ_FOREACH(group, &cfg->group_list, link) { 165 | cfg_iface_t *iface; 166 | TAILQ_FOREACH(iface, &group->iface_list, link) { 167 | if (iface_is_bridged(sk, iface->ifindex)) 168 | anybridged = 1; 169 | } 170 | } 171 | 172 | if (anybridged) { 173 | syslog2(LOG_DEBUG, "Some interfaces is bridged, remove nftables rules"); 174 | if (system("nft delete chain bridge filter " NFT_IN_CHAIN)) 175 | syslog2(LOG_ERR, "Failed deleting nftables input rules"); 176 | if (system("nft delete chain bridge filter " NFT_FWD_CHAIN)) 177 | syslog2(LOG_ERR, "Failed deleting nftables forward rules"); 178 | } 179 | err_free_sk: 180 | nl_socket_free(sk); 181 | return 0; 182 | } 183 | 184 | /** 185 | If there is an underlaying switchcore, it may implement 'DHCP-snooping', 186 | in this case it will most likely not learn the MAC-address correctly. 187 | 188 | To fix this, add a FDB entry in the bridge, if there are a switch under 189 | the FDB entry will be accelerated. 190 | */ 191 | int add_fdb_entry(int ifindex, unsigned char *mac) 192 | { 193 | int err = 0; 194 | struct nl_addr *addr; 195 | struct rtnl_neigh *neigh; 196 | struct nl_sock *sk; 197 | sk = nl_socket_alloc(); 198 | 199 | if (!sk) 200 | return 1; 201 | 202 | err = nl_connect(sk, NETLINK_ROUTE); 203 | if (err) { 204 | syslog(LOG_ERR, "Failed setting connecting to NETLINK_ROUTE: %s", nl_geterror(err)); 205 | goto free_sk; 206 | } 207 | 208 | if (!iface_is_bridged(sk, ifindex)) { 209 | syslog2(LOG_DEBUG, "Interface %d is not bridged, skipping FDB entry", ifindex); 210 | nl_socket_free(sk); 211 | return 0; /* No fail, just exit. */ 212 | } 213 | 214 | addr = nl_addr_alloc(ETH_ALEN); 215 | if (!addr) { 216 | syslog2(LOG_ERR, "Could not allocate netlink address"); 217 | err = -NLE_NOMEM; 218 | goto free_sk; 219 | } 220 | 221 | syslog2(LOG_DEBUG, "Interface %d is bridged, adding FDB entry", ifindex); 222 | nl_addr_set_family(addr, AF_LLC); 223 | err = nl_addr_set_binary_addr(addr, mac, ETH_ALEN); 224 | if (err) { 225 | syslog(LOG_ERR, "Failed creating netlink binary address: %s", nl_geterror(err)); 226 | goto free_addr; 227 | return err; 228 | } 229 | 230 | neigh = rtnl_neigh_alloc(); 231 | if (!neigh) { 232 | err = -NLE_NOMEM; 233 | goto free_addr; 234 | } 235 | rtnl_neigh_set_family(neigh, PF_BRIDGE); 236 | rtnl_neigh_set_lladdr(neigh, addr); 237 | nl_addr_set_prefixlen(addr, 48); 238 | rtnl_neigh_set_flags(neigh, NTF_MASTER); 239 | rtnl_neigh_set_state(neigh, NUD_REACHABLE); 240 | rtnl_neigh_set_ifindex(neigh, ifindex); 241 | 242 | syslog(LOG_DEBUG, "Adding MAC %02x:%02x:%02x:%02x:%02x:%02x ifindex %d in bridge FDB", mac[0],mac[1],mac[2],mac[3],mac[4],mac[5], ifindex); 243 | err = rtnl_neigh_add(sk, neigh, NLM_F_CREATE); //NLM_F_CREATE); 244 | 245 | rtnl_neigh_put(neigh); 246 | free_addr: 247 | nl_addr_put(addr); 248 | free_sk: 249 | nl_socket_free(sk); 250 | 251 | return err; 252 | } 253 | 254 | int add_arp_entry(int ifindex, unsigned char *mac, struct sockaddr_in saddr) 255 | { 256 | struct arpreq req; 257 | struct sockaddr_in *sin; 258 | char ifname[IFNAMSIZ]; 259 | int fd; 260 | 261 | if_indextoname(ifindex, ifname); 262 | 263 | syslog2(LOG_DEBUG, "Add arp entry for address %s, iface %s mac %s", inet_ntoa(saddr.sin_addr), ifname, mac_ntoa(mac)); 264 | 265 | bzero(&req, sizeof(req)); 266 | sin = (struct sockaddr_in *)&req.arp_pa; 267 | sin->sin_family = AF_INET; 268 | sin->sin_addr.s_addr = saddr.sin_addr.s_addr; 269 | 270 | memcpy(req.arp_ha.sa_data, mac, ETHER_ADDR_LEN); 271 | req.arp_flags = ATF_COM; 272 | strncpy(req.arp_dev, ifname, sizeof(req.arp_dev)); 273 | 274 | fd = socket(AF_INET, SOCK_DGRAM, 0); 275 | if (fd < 1) { 276 | syslog2(LOG_WARNING, "Failed opening socket to add arp entry"); 277 | return -1; 278 | } 279 | if (ioctl(fd, SIOCSARP, &req) < 0) { 280 | syslog2(LOG_WARNING, "Failed adding arp entry for address %s, iface %s mac %s", inet_ntoa(saddr.sin_addr), ifname, mac_ntoa(mac)); 281 | close(fd); 282 | return -1; 283 | } 284 | close(fd); 285 | 286 | syslog2(LOG_DEBUG, "ARP cache entry successfully added."); 287 | 288 | return 0; 289 | } 290 | -------------------------------------------------------------------------------- /src/conf.c: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2018 Westermo Teleindustri AB 4 | 5 | This program is free software; you can redistribute it and/or modify 6 | it under the terms of the GNU General Public License as published by 7 | the Free Software Foundation; version 2 dated June, 1991, or 8 | (at your option) version 3 dated 29 June, 2007. 9 | 10 | This program is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | GNU General Public License for more details. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | */ 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | #include 30 | #include "logging.h" 31 | 32 | /* 33 | jansson does not support to parse integers as hex, therefore we must 34 | store/read them as strings, e.g [ "0x1", "0x2" ], and convert them. 35 | */ 36 | static int _parse_hex_arr(json_t *arr, char *dst, int len) 37 | { 38 | json_t *obj; 39 | int num = 0; 40 | size_t i; 41 | 42 | json_array_foreach(arr, i, obj) { 43 | if (num >= len) { 44 | errno = ENOMEM; 45 | return 1; 46 | } 47 | if (json_is_string(obj)) 48 | dst[num++] = (char)strtoul(json_string_value(obj), NULL, 16); 49 | } 50 | 51 | return num; 52 | } 53 | 54 | static int read_int(json_t *json, int *dst, char *key, int defvalue) 55 | { 56 | json_t *obj; 57 | 58 | obj = json_object_get(json, key); 59 | if (!obj) { 60 | *dst = defvalue; 61 | return 0; 62 | } 63 | 64 | if (!json_is_integer(obj)) { 65 | *dst = defvalue; 66 | return 0; 67 | } 68 | 69 | *dst = json_integer_value(obj); 70 | 71 | return 0; 72 | } 73 | 74 | static void option82_parse_manual(json_t *obj, char *buf, int len, int *res) 75 | { 76 | if (json_is_string(obj)) { 77 | strncpy(buf, json_string_value(obj), len); 78 | *res = strlen(buf); 79 | } else if (json_is_array(obj)) { 80 | *res = _parse_hex_arr(obj, buf, len); 81 | } 82 | } 83 | 84 | static int read_option82(json_t *json, cfg_t *cfg) 85 | { 86 | json_t *obj; 87 | 88 | obj = json_object_get(json, "option82"); 89 | if (json_is_object(obj)) { 90 | json_t *remote; 91 | const char *str; 92 | 93 | cfg->opt82.enabled = 1; 94 | 95 | remote = json_object_get(obj, "remote-id"); 96 | if (json_is_object(remote)) { 97 | json_t *type, *data; 98 | 99 | type = json_object_get(remote, "type"); 100 | if (json_is_string(type)) { 101 | str = json_string_value(type); 102 | if (!strcmp(str, "giaddr")) 103 | cfg->opt82.rid_type = RID_TYPE_GIADDR; 104 | else if (!strcmp(str, "hostname")) 105 | cfg->opt82.rid_type = RID_TYPE_HOSTNAME; 106 | else if (!strcmp(str, "manual")) { 107 | cfg->opt82.rid_type = RID_TYPE_MANUAL; 108 | data = json_object_get(remote, "data"); 109 | option82_parse_manual(data, cfg->opt82.remote_id, sizeof(cfg->opt82.remote_id), 110 | &cfg->opt82.remote_id_len); 111 | } 112 | } 113 | } 114 | } 115 | return 0; 116 | } 117 | 118 | static int read_ifaces(json_t *json, cfg_group_t *group) 119 | { 120 | json_t *arr, *obj; 121 | size_t i; 122 | 123 | TAILQ_INIT(&group->iface_list); 124 | 125 | arr = json_object_get(json, "iface"); 126 | if (!json_is_array(arr)) { 127 | cfg_iface_t *iface; 128 | 129 | syslog2(LOG_DEBUG, "No ifaces node, use same as in group"); 130 | iface = malloc(sizeof(*iface)); 131 | if (!iface) { 132 | syslog2(LOG_ERR, "Failed allocate memory: %s", strerror(errno)); 133 | return 1; 134 | } 135 | 136 | memset(iface, 0, sizeof(*iface)); 137 | iface->ifindex = group->ifindex; 138 | TAILQ_INSERT_TAIL(&group->iface_list, iface, link); 139 | return 0; 140 | } 141 | 142 | json_array_foreach(arr, i, obj) { 143 | cfg_iface_t *iface; 144 | json_t *ifname; 145 | 146 | if (!json_is_object(obj)) 147 | return 1; 148 | 149 | ifname = json_object_get(obj, "ifname"); 150 | if (!json_is_string(ifname)) 151 | return 1; 152 | 153 | iface = malloc(sizeof(*iface)); 154 | if (!iface) { 155 | syslog2(LOG_ERR, "Failed allocate memory: %s", strerror(errno)); 156 | return 1; 157 | } 158 | 159 | memset(iface, 0, sizeof(*iface)); 160 | iface->ifindex = if_nametoindex(json_string_value(ifname)); 161 | 162 | /* Iface specific option82-settings */ 163 | json_t *circuit = json_object_get(obj, "circuit-id"); 164 | option82_parse_manual(circuit, iface->circuit_id, sizeof(iface->circuit_id), &iface->circuit_id_len); 165 | 166 | TAILQ_INSERT_TAIL(&group->iface_list, iface, link); 167 | } 168 | 169 | return 0; 170 | } 171 | 172 | static int read_servers(json_t *json, cfg_t *cfg, cfg_group_t *group) 173 | { 174 | json_t *arr, *obj, *address; 175 | size_t i; 176 | 177 | if (group) 178 | TAILQ_INIT(&group->server_list); 179 | else 180 | TAILQ_INIT(&cfg->server_list); 181 | 182 | arr = json_object_get(json, "server"); 183 | if (!json_is_array(arr)) 184 | return 0; 185 | 186 | json_array_foreach(arr, i, obj) { 187 | cfg_server_t *server; 188 | 189 | if (!json_is_object(obj)) 190 | return 1; 191 | 192 | address = json_object_get(obj, "address"); 193 | if (!json_is_string(address)) 194 | return 1; 195 | 196 | server = malloc(sizeof(*server)); 197 | if (!server) { 198 | syslog2(LOG_ERR, "Failed allocate memory: %s", strerror(errno)); 199 | return 1; 200 | } 201 | inet_pton(AF_INET, json_string_value(address), &server->addr); 202 | if (read_int(obj, &server->port, "port", 67)) { 203 | free(server); 204 | return 1; 205 | } 206 | if (group) 207 | TAILQ_INSERT_TAIL(&group->server_list, server, link); 208 | else 209 | TAILQ_INSERT_TAIL(&cfg->server_list, server, link); 210 | } 211 | 212 | return 0; 213 | } 214 | 215 | static int read_group(json_t *json, cfg_t *cfg) 216 | { 217 | json_t *obj, *arr; 218 | int i; 219 | struct ifaddrs *ifap, *ifa; 220 | cfg_group_t *group = NULL; 221 | 222 | arr = json_object_get(json, "group"); 223 | if (!json_is_array(arr)) 224 | return 1; 225 | 226 | getifaddrs(&ifap); 227 | if (!ifap) 228 | return 1; 229 | 230 | TAILQ_INIT(&cfg->group_list); 231 | json_array_foreach(arr, i, obj) { 232 | json_t *ifname, *giaddr; 233 | struct sockaddr_in *sa; 234 | 235 | if (!json_is_object(obj)) 236 | goto err; 237 | 238 | group = malloc(sizeof(*group)); 239 | if (!group) { 240 | syslog2(LOG_ERR, "Failed allocate memory: %s", strerror(errno)); 241 | goto err; 242 | } 243 | memset(group, 0, sizeof(*group)); 244 | 245 | /* Parse giaddr */ 246 | giaddr = json_object_get(obj, "giaddr"); 247 | if (!json_is_string(giaddr)) 248 | goto err; 249 | 250 | if (!inet_pton(AF_INET, json_string_value(giaddr), &group->giaddr)) 251 | goto err; 252 | 253 | /* Parse/find interface for giaddr */ 254 | ifname = json_object_get(obj, "ifname"); 255 | if (json_is_string(ifname)) { 256 | group->ifindex = if_nametoindex(json_string_value(ifname)); 257 | } else { 258 | for (ifa = ifap; ifa; ifa = ifa->ifa_next) { 259 | if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) { 260 | sa = (struct sockaddr_in *)ifa->ifa_addr; 261 | if (sa->sin_addr.s_addr == (in_addr_t)group->giaddr) { 262 | syslog2(LOG_DEBUG, "Found interface %s", ifa->ifa_name); 263 | group->ifindex = if_nametoindex(ifa->ifa_name); 264 | break; 265 | } 266 | } 267 | } 268 | } 269 | if (!group->ifindex) 270 | goto err; 271 | 272 | /* Parse all interfaces in this group */ 273 | read_ifaces(obj, group); 274 | 275 | /* Parse all group specific servers. */ 276 | read_servers(obj, NULL, group); 277 | TAILQ_INSERT_TAIL(&cfg->group_list, group, link); 278 | } 279 | 280 | freeifaddrs(ifap); 281 | return 0; 282 | err: 283 | if (group) 284 | free(group); 285 | freeifaddrs(ifap); 286 | return 1; 287 | } 288 | 289 | /** 290 | Read option 11 (force server ID) 291 | */ 292 | static int read_force_sid(json_t *json, cfg_t *cfg) 293 | { 294 | json_t *obj; 295 | 296 | obj = json_object_get(json, "force-server-id"); 297 | 298 | 299 | if (obj && json_is_boolean(obj)) 300 | cfg->force_server_id = json_is_true(obj); 301 | 302 | return 0; 303 | } 304 | 305 | static int read_udp_listen_port(json_t *json, cfg_t *cfg) 306 | { 307 | if (read_int(json, &cfg->udp_listen_port, "udp-listen-port", 67)) 308 | return 1; 309 | 310 | return 0; 311 | } 312 | 313 | /* Check that config is consistent, return 0 if not ok. */ 314 | static int conf_validate(cfg_t *cfg) 315 | { 316 | cfg_group_t *group; 317 | 318 | TAILQ_FOREACH(group, &cfg->group_list, link) { 319 | if (TAILQ_EMPTY(&group->server_list) && TAILQ_EMPTY(&cfg->server_list)) { 320 | syslog2(LOG_ERR, "No servers found for group."); 321 | return 0; 322 | } 323 | } 324 | 325 | return 1; 326 | } 327 | 328 | int conf_read(cfg_t *cfg, char *file) 329 | { 330 | json_t *json; 331 | json_error_t error; 332 | 333 | memset(cfg, 0, sizeof(*cfg)); 334 | 335 | if (!file) 336 | return 1; 337 | 338 | json = json_load_file(file, 0, &error); 339 | if (!json) { 340 | syslog2(LOG_ERR, "Could not open %s, %d:%s", file, error.line, error.text); 341 | return 1; 342 | } 343 | 344 | if (read_servers(json, cfg, NULL)) 345 | goto err; 346 | 347 | if (read_force_sid(json, cfg)) 348 | goto err; 349 | 350 | if (read_udp_listen_port(json, cfg)) 351 | goto err; 352 | 353 | if (read_option82(json, cfg)) 354 | goto err; 355 | 356 | if (read_group(json, cfg)) 357 | goto err; 358 | 359 | if (!conf_validate(cfg)) 360 | goto err; 361 | 362 | json_decref(json); 363 | return 0; 364 | err: 365 | json_decref(json); 366 | conf_free(cfg); 367 | 368 | return 1; 369 | } 370 | 371 | void conf_free(cfg_t *cfg) 372 | { 373 | cfg_group_t *group, *itemp; 374 | cfg_server_t *server, *stemp; 375 | 376 | TAILQ_FOREACH_SAFE(group, &cfg->group_list, link, itemp) { 377 | cfg_iface_t *iface, *ptemp; 378 | 379 | TAILQ_FOREACH_SAFE(server, &group->server_list, link, stemp) { 380 | TAILQ_REMOVE(&group->server_list, server, link); 381 | free(server); 382 | } 383 | TAILQ_FOREACH_SAFE(iface, &group->iface_list, link, ptemp) { 384 | TAILQ_REMOVE(&group->iface_list, iface, link); 385 | free(iface); 386 | } 387 | TAILQ_REMOVE(&cfg->group_list, group, link); 388 | free(group); 389 | } 390 | 391 | TAILQ_FOREACH_SAFE(server, &cfg->server_list, link, stemp) { 392 | TAILQ_REMOVE(&cfg->server_list, server, link); 393 | free(server); 394 | } 395 | } 396 | -------------------------------------------------------------------------------- /src/options.c: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2004,2008 Simon Kelley 4 | Copyright (c) 2018 Westermo Teleindustri AB 5 | 6 | This program is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; version 2 dated June, 1991, or 9 | (at your option) version 3 dated 29 June, 2007. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | 32 | #include "packet.h" 33 | #include "logging.h" 34 | 35 | #define option_bool(x) (0) 36 | 37 | #define OPTION_PAD 0 38 | #define OPTION_OVERLOAD 52 39 | #define OPTION_MESSAGE_TYPE 53 40 | #define OPTION_AGENT_ID 82 41 | #define OPTION_END 255 42 | 43 | #define SUBOPT_CIRCUIT_ID 1 44 | #define SUBOPT_REMOTE_ID 2 45 | #define SUBOPT_SERVER_OR 11 /* RFC 5107 */ 46 | 47 | #define DHOPT_ADDR 1 48 | #define DHOPT_STRING 2 49 | 50 | #define MAX_OPTION_SIZE 255 51 | 52 | #define option_len(opt) ((int)(((unsigned char *)(opt))[1])) 53 | 54 | typedef unsigned int u32; 55 | 56 | struct dhcp_opt { 57 | int opt, len, flags; 58 | unsigned char *val; 59 | struct dhcp_opt *next; 60 | }; 61 | 62 | /* return length, note this only does the data part */ 63 | static int do_opt(struct dhcp_opt *opt, unsigned char *p) 64 | { 65 | int len = opt->len; 66 | 67 | if (p && len != 0) { 68 | if (opt->flags & DHOPT_ADDR) { 69 | int j; 70 | struct in_addr *a = (struct in_addr *)opt->val; 71 | 72 | for (j = 0; j < opt->len; j += INADDRSZ, a++) { 73 | memcpy(p, a, INADDRSZ); 74 | p += INADDRSZ; 75 | } 76 | } else 77 | memcpy(p, opt->val ? opt->val : (unsigned char *)"", len); 78 | } 79 | return len; 80 | } 81 | 82 | static unsigned char *dhcp_skip_opts(unsigned char *start) 83 | { 84 | while (*start != 0) 85 | start += start[1] + 2; 86 | return start; 87 | } 88 | 89 | static unsigned char *free_space(struct dhcp_packet_with_opts *mess, unsigned char *end, int opt, int len) 90 | { 91 | unsigned char *p = dhcp_skip_opts(&mess->options[0] + sizeof(u32)); 92 | 93 | if (p + len + 3 >= end) { 94 | p = NULL; 95 | syslog2(LOG_WARNING, "Cannot send DHCP/BOOTP option %d: no space left in packet", opt); 96 | } 97 | 98 | if (p) { 99 | *(p++) = opt; 100 | *(p++) = len; 101 | } 102 | 103 | return p; 104 | } 105 | 106 | static unsigned char *option_find1(unsigned char *p, unsigned char *end, int opt, int minsize) 107 | { 108 | while (1) { 109 | if (p >= end) 110 | return NULL; 111 | else if (*p == OPTION_END) 112 | return opt == OPTION_END ? p : NULL; 113 | else if (*p == OPTION_PAD) 114 | p++; 115 | else { 116 | int opt_len; 117 | 118 | if (p > end - 2) 119 | return NULL; /* malformed packet */ 120 | opt_len = option_len(p); 121 | if (p > end - (2 + opt_len)) 122 | return NULL; /* malformed packet */ 123 | if (*p == opt && opt_len >= minsize) 124 | return p; 125 | p += opt_len + 2; 126 | } 127 | } 128 | } 129 | 130 | static unsigned char *option_find(struct dhcp_packet_with_opts *mess, size_t size, int opt_type, int minsize) 131 | { 132 | unsigned char *ret, *overload; 133 | 134 | /* skip over DHCP cookie; */ 135 | if ((ret = option_find1(&mess->options[0] + sizeof(u32), ((unsigned char *)mess) + size, opt_type, minsize))) 136 | return ret; 137 | /* look for overload option. */ 138 | if (!(overload = option_find1(&mess->options[0] + sizeof(u32), ((unsigned char *)mess) + size, OPTION_OVERLOAD, 1))) 139 | return NULL; 140 | /* Can we look in filename area ? */ 141 | if ((overload[2] & 1) && (ret = option_find1(&mess->header.file[0], &mess->header.file[128], opt_type, minsize))) 142 | return ret; 143 | /* finally try sname area */ 144 | if ((overload[2] & 2) && (ret = option_find1(&mess->header.sname[0], &mess->header.sname[64], opt_type, minsize))) 145 | return ret; 146 | return NULL; 147 | } 148 | 149 | 150 | static size_t dhcp_packet_size(struct dhcp_packet_with_opts *mess, unsigned char *real_end) 151 | { 152 | unsigned char *p = dhcp_skip_opts(&mess->options[0] + sizeof(u32)); 153 | size_t ret; 154 | 155 | (void)real_end; /* unused */ 156 | *p++ = OPTION_END; 157 | 158 | if (option_bool(OPT_LOG_OPTS)) { 159 | if (mess->header.siaddr.s_addr != 0) 160 | syslog2(LOG_DEBUG, "%u next server: %s", ntohl(mess->header.xid), inet_ntoa(mess->header.siaddr)); 161 | if ((mess->header.flags & htons(0x8000)) && mess->header.ciaddr.s_addr == 0) 162 | syslog2(LOG_DEBUG, "%u broadcast response.", ntohl(mess->header.xid)); 163 | } 164 | 165 | ret = (size_t)(p - (unsigned char *)mess); 166 | 167 | if (ret < MIN_PACKETSZ) 168 | ret = MIN_PACKETSZ; 169 | 170 | return ret; 171 | } 172 | 173 | static void encap_opts(struct dhcp_opt *opt, int encap, struct dhcp_packet_with_opts *mess, unsigned char *end) 174 | { 175 | int len, enc_len; 176 | struct dhcp_opt *start; 177 | unsigned char *p; 178 | size_t tot_len; 179 | 180 | /* find size in advance */ 181 | for (enc_len = 0, start = opt; opt; opt = opt->next) { 182 | int new = do_opt(opt, NULL) + 2; 183 | if (enc_len + new <= MAX_OPTION_SIZE) 184 | enc_len += new; 185 | else { 186 | syslog2(LOG_WARNING, "Cannot add DHCP/BOOTP option %d: option to large (%d).", opt, new); 187 | return; 188 | } 189 | } 190 | 191 | tot_len = enc_len; 192 | if (enc_len != 0 && (p = free_space(mess, end, encap, tot_len))) { 193 | for (; start; start = start->next) { 194 | len = do_opt(start, p + 2); 195 | *(p++) = start->opt; 196 | *(p++) = len; 197 | p += len; 198 | } 199 | } 200 | } 201 | 202 | static void add_option82(struct dhcp_packet_with_opts *mess, unsigned char *end, int ifindex, cfg_t *cfg, 203 | cfg_iface_t *iface, struct in_addr addr) 204 | { 205 | unsigned char ifname[IF_NAMESIZE]; 206 | char *giaddr; 207 | struct dhcp_opt opt_cid; 208 | struct dhcp_opt opt_rid; 209 | struct dhcp_opt opt_sor; 210 | struct dhcp_opt *opt_root; 211 | char host[HOST_NAME_MAX]; 212 | 213 | memset(ifname, 0, IF_NAMESIZE); 214 | 215 | syslog2(LOG_DEBUG, "Adding option 82."); 216 | 217 | if (!if_indextoname(ifindex, (char *)&ifname[0])) 218 | return; /* Report error? */ 219 | 220 | opt_rid.opt = SUBOPT_REMOTE_ID; 221 | 222 | switch (cfg->opt82.rid_type) { 223 | case RID_TYPE_MANUAL: 224 | opt_rid.val = (unsigned char *)cfg->opt82.remote_id; 225 | opt_rid.len = cfg->opt82.remote_id_len; 226 | break; 227 | case RID_TYPE_GIADDR: 228 | giaddr = inet_ntoa(addr); 229 | opt_rid.val = (unsigned char *)giaddr; 230 | opt_rid.len = strlen(giaddr); 231 | break; 232 | 233 | case RID_TYPE_HOSTNAME: 234 | gethostname(host, sizeof(host)); 235 | opt_rid.val = (unsigned char *)host; 236 | opt_rid.len = strlen(host); 237 | break; 238 | } 239 | opt_rid.flags = 0; 240 | opt_rid.next = NULL; 241 | 242 | opt_cid.opt = SUBOPT_CIRCUIT_ID; 243 | syslog2(LOG_DEBUG, "circuit_id: %p, len: %d\n", iface->circuit_id, iface->circuit_id_len); 244 | if (iface->circuit_id_len > 0) { 245 | opt_cid.val = (unsigned char *)iface->circuit_id; 246 | opt_cid.len = iface->circuit_id_len; 247 | } else { 248 | opt_cid.val = &ifname[0]; 249 | opt_cid.len = strlen((char *)ifname); 250 | } 251 | opt_cid.flags = 0; 252 | opt_cid.next = &opt_rid; 253 | 254 | if (addr.s_addr) { 255 | opt_sor.opt = SUBOPT_SERVER_OR; 256 | opt_sor.val = (unsigned char *)&addr; 257 | opt_sor.len = 4; 258 | opt_sor.flags = DHOPT_ADDR; 259 | opt_sor.next = &opt_cid; 260 | opt_root = &opt_sor; 261 | } else 262 | opt_root = &opt_cid; 263 | 264 | encap_opts(opt_root, OPTION_AGENT_ID, mess, end); 265 | } 266 | 267 | /* Is request from @iface_index allowed? */ 268 | static cfg_iface_t *find_iface_cfg(cfg_group_t *group, int ifindex) 269 | { 270 | cfg_iface_t *entry; 271 | 272 | TAILQ_FOREACH(entry, &group->iface_list, link) { 273 | int index = entry->ifindex; 274 | 275 | if (index == ifindex) 276 | return entry; 277 | } 278 | return NULL; 279 | } 280 | 281 | size_t add_options(struct dhcp_packet_with_opts *mess, size_t sz, int ifindex, struct in_addr addr, cfg_group_t *group, cfg_t *cfg) 282 | { 283 | unsigned char *tmp, *opt, *end = (unsigned char *)(mess + 1); 284 | unsigned char *real_end = (unsigned char *)(mess + 1); 285 | cfg_iface_t *iface; 286 | int nbytes; 287 | 288 | syslog2(LOG_DEBUG, "Adding options"); 289 | 290 | if (!cfg->opt82.enabled) 291 | return 0; 292 | 293 | iface = find_iface_cfg(group, ifindex); 294 | if (!iface) { 295 | syslog2(LOG_ERR, "Could not find iface configuration for index %d", ifindex); 296 | return 1; 297 | } 298 | if (mess->header.op != BOOTREQUEST) //|| mess->hlen > DHCP_CHADDR_MAX) 299 | return 0; 300 | 301 | /* Why this? From dnsmasq. Don't add options if hardware type is 0. */ 302 | if (mess->header.htype == 0 && mess->header.hlen != 0) 303 | return 0; 304 | 305 | /* check for DHCP rather than BOOTP */ 306 | if ((opt = option_find(mess, sz, OPTION_MESSAGE_TYPE, 1))) { 307 | u32 cookie = htonl(DHCP_COOKIE); 308 | 309 | /* only insist on a cookie for DHCP. */ 310 | if (memcmp(mess->options, &cookie, sizeof(u32)) != 0) 311 | return 0; 312 | } 313 | /* Find end of options, set rest of mess to 0 to prepare for additional options. */ 314 | tmp = option_find(mess, sz, OPTION_END, 0); 315 | nbytes = end - tmp; 316 | memset(tmp, 0, nbytes); 317 | 318 | /* If not forcing server id, reset address */ 319 | if (!cfg->force_server_id) 320 | memset(&addr, 0, sizeof(addr)); 321 | 322 | /* Option 82 should always be added last */ 323 | add_option82(mess, end, ifindex, cfg, iface, addr); 324 | 325 | return dhcp_packet_size(mess, real_end); 326 | } 327 | 328 | /* Remove option 82 before returning to client */ 329 | size_t remove_options(struct dhcp_packet_with_opts *mess, size_t sz) 330 | { 331 | unsigned char *tmp; 332 | unsigned char *end = (unsigned char *)(mess + 1); 333 | 334 | tmp = option_find(mess, sz, OPTION_AGENT_ID, 0); 335 | if (tmp) { 336 | /* number of bytes from option 82 to end option */ 337 | int nbytes = end - tmp; 338 | /* number of bytes for whole option 82 including option and length field */ 339 | int opt82_len = option_len(tmp) + 2; 340 | 341 | /* move rest of options after option 82 to where option 82 starts */ 342 | memmove(tmp, tmp + opt82_len, nbytes - opt82_len); 343 | return dhcp_packet_size((struct dhcp_packet_with_opts *)(tmp + nbytes - opt82_len), end); 344 | } 345 | 346 | return sz; 347 | } 348 | -------------------------------------------------------------------------------- /src/dhcp-helper.c: -------------------------------------------------------------------------------- 1 | /* dhcp-helper 2 | 3 | Copyright (c) 2004,2008 Simon Kelley 4 | Copyright (c) 2018 Westermo Teleindustri AB 5 | 6 | This program is free software; you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation; version 2 dated June, 1991, or 9 | (at your option) version 3 dated 29 June, 2007. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | 34 | #include "conf.h" 35 | #include "packet.h" 36 | #include "logging.h" 37 | #include "config.h" 38 | #include "misc.h" 39 | 40 | static int sd_out = 0; 41 | static int sd_separate_in = 0; 42 | 43 | static ev_signal sighup_watcher; 44 | static ev_signal sigint_watcher; 45 | static ev_signal sigquit_watcher; 46 | static ev_signal sigterm_watcher; 47 | 48 | static ev_io io_upstreams; 49 | static ev_io io_upstreams_separate_listen; 50 | 51 | static char config_file[128] = "/etc/dhcphelper.json"; 52 | 53 | static int get_ifindex(struct msghdr *msg) 54 | { 55 | struct cmsghdr *cmptr; 56 | int ifindex = 0; 57 | 58 | for (cmptr = CMSG_FIRSTHDR(msg); cmptr; cmptr = CMSG_NXTHDR(msg, cmptr)) { 59 | if (cmptr->cmsg_level == SOL_IP && cmptr->cmsg_type == IP_PKTINFO) { 60 | union { 61 | unsigned char *c; 62 | struct in_pktinfo *p; 63 | } p; 64 | 65 | p.c = CMSG_DATA(cmptr); 66 | ifindex = p.p->ipi_ifindex; 67 | } 68 | } 69 | 70 | return ifindex; 71 | } 72 | 73 | static struct dhcp_packet_with_opts *packet_rcv_udp(int sd, unsigned char *buf, int sz, int *len, int *ifindex) 74 | { 75 | union { 76 | struct cmsghdr align; /* this ensures alignment */ 77 | char control[CMSG_SPACE(sizeof(struct in_pktinfo))]; 78 | } control_u; 79 | struct msghdr msg; 80 | struct iovec iov; 81 | struct sockaddr_in saddr; 82 | 83 | memset(&msg, 0, sizeof(msg)); 84 | msg.msg_control = control_u.control; 85 | msg.msg_controllen = sizeof(control_u); 86 | msg.msg_name = &saddr; 87 | msg.msg_namelen = 0; 88 | msg.msg_iov = &iov; 89 | msg.msg_iovlen = 1; 90 | iov.iov_base = buf; // packet; 91 | iov.iov_len = sz; 92 | *len = recvmsg(sd, &msg, 0); 93 | 94 | *ifindex = get_ifindex(&msg); 95 | 96 | if (*len < 1) { 97 | syslog2(LOG_WARNING, "Received udp packet size %d.", *len); 98 | return NULL; 99 | } 100 | 101 | if (!*ifindex) { 102 | syslog2(LOG_WARNING, "Invalid ifindex for received udp packet (%d).", *ifindex); 103 | return NULL; 104 | } 105 | 106 | return (struct dhcp_packet_with_opts *)buf; 107 | } 108 | 109 | static struct dhcp_packet_with_opts *packet_rcv_raw(int sd, unsigned char *buf, int sz, int *len, int *ifindex) 110 | { 111 | struct sockaddr_ll sl; 112 | struct ethhdr *eth_hdr = (struct ethhdr *)buf; 113 | struct iphdr *ip_hdr = (struct iphdr *)((char *)eth_hdr + (sizeof(struct ethhdr))); 114 | struct udphdr *udp; 115 | int dport; 116 | 117 | socklen_t salen = sizeof sl; 118 | 119 | *len = recvfrom(sd, buf, sz, 0, (struct sockaddr *)&sl, &salen); 120 | if (*len < 1) { 121 | syslog2(LOG_WARNING, "Received raw packet size %d.", *len); 122 | return NULL; 123 | } 124 | 125 | /* Not interested in outgoing packets. */ 126 | if (sl.sll_pkttype & PACKET_OUTGOING) 127 | return NULL; 128 | 129 | *ifindex = sl.sll_ifindex; 130 | if (!*ifindex) { 131 | syslog2(LOG_WARNING, "Invalid ifindex for received raw packet (%d).", *ifindex); 132 | return NULL; 133 | } 134 | 135 | udp = (struct udphdr *)((char *)ip_hdr + (4 * ip_hdr->ihl)); 136 | dport = ntohs(udp->dest); 137 | 138 | if (dport != 67 && dport != 68) { 139 | syslog2(LOG_NOTICE, "Received raw packet with invalid destination port (%d).", dport); 140 | return NULL; 141 | } 142 | 143 | return (struct dhcp_packet_with_opts *)((char *)(udp) + sizeof(struct udphdr)); 144 | } 145 | 146 | static void packet_cb_raw(struct ev_loop *loop __attribute__ ((unused)), ev_io *w, int revents __attribute__ ((unused))) 147 | { 148 | static unsigned char buf[2048]; /* MAXIMUM_PACKET_SIZE */ 149 | cfg_t *cfg = ev_userdata(loop); 150 | struct dhcp_packet_with_opts *packet; 151 | int ifindex; 152 | int len; 153 | 154 | ev_io_stop(loop, w); 155 | 156 | packet = packet_rcv_raw(w->fd, buf, sizeof(buf), &len, &ifindex); 157 | if (packet) 158 | handle_packet(cfg, &packet->header, len, ifindex, sd_out); 159 | 160 | ev_io_start(loop, w); 161 | } 162 | 163 | static void packet_cb_udp(struct ev_loop *loop __attribute__ ((unused)), ev_io *w, int revents __attribute__ ((unused))) 164 | { 165 | static unsigned char buf[2048]; /* MAXIMUM_PACKET_SIZE */ 166 | cfg_t *cfg = ev_userdata(loop); 167 | struct dhcp_packet_with_opts *packet; 168 | int ifindex; 169 | int len; 170 | 171 | ev_io_stop(loop, w); 172 | 173 | packet = packet_rcv_udp(w->fd, buf, sizeof(buf), &len, &ifindex); 174 | if (packet) 175 | handle_packet(cfg, &packet->header, len, ifindex, sd_out); 176 | ev_io_start(loop, w); 177 | } 178 | 179 | /* 180 | sudo tcpdump -dd -s0 -i enx0080c83bb148 "ether[12] == 0x08 && ether[13] == 0x00 181 | && ether[23]==17 && ether[36] == 00 && ether[37] == 67" 182 | */ 183 | int add_filter(int sd) 184 | { 185 | struct sock_fprog fprog; 186 | 187 | static struct sock_filter filter[] = { 188 | {0x30, 0, 0, 0x0000000c}, 189 | {0x15, 0, 9, 0x00000008}, 190 | {0x30, 0, 0, 0x0000000d}, 191 | {0x15, 0, 7, 0x00000000}, 192 | {0x30, 0, 0, 0x00000017}, 193 | {0x15, 0, 5, 0x00000011}, 194 | {0x30, 0, 0, 0x00000024}, 195 | {0x15, 0, 3, 0x00000000}, 196 | {0x30, 0, 0, 0x00000025}, 197 | {0x15, 0, 1, 0x00000043}, 198 | {0x6, 0, 0, 0x00040000}, 199 | {0x6, 0, 0, 0x00000000}, 200 | }; 201 | fprog.len = sizeof filter / sizeof(filter[0]); 202 | fprog.filter = filter; 203 | 204 | if ((setsockopt(sd, SOL_SOCKET, SO_ATTACH_FILTER, &fprog, sizeof(fprog))) < 0) { 205 | syslog2(LOG_WARNING, "Failed to set socket filter."); 206 | return 1; 207 | } 208 | return 0; 209 | } 210 | 211 | static int bind_to_interface(int sd, int ifindex) 212 | { 213 | struct sockaddr_ll sll; 214 | 215 | bzero(&sll, sizeof(sll)); 216 | sll.sll_family = AF_PACKET; 217 | sll.sll_ifindex = ifindex; 218 | sll.sll_pkttype = PACKET_BROADCAST; 219 | if ((bind(sd, (struct sockaddr *)&sll, sizeof(sll))) == -1) { 220 | syslog2(LOG_WARNING, "Failed to bind socket to interface."); 221 | return 1; 222 | } 223 | return 0; 224 | } 225 | 226 | static int setup_sockets_raw(struct ev_loop *loop, cfg_t *cfg) 227 | { 228 | cfg_group_t *group; 229 | cfg_iface_t *iface; 230 | 231 | TAILQ_FOREACH(group, &cfg->group_list, link) { 232 | TAILQ_FOREACH(iface, &group->iface_list, link) { 233 | int index = iface->ifindex; 234 | 235 | iface->sd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)); 236 | if (iface->sd == -1) { 237 | perror("Unable to create in socket"); 238 | return 1; 239 | } 240 | add_filter(iface->sd); 241 | bind_to_interface(iface->sd, index); 242 | ev_io_init(&iface->io, packet_cb_raw, iface->sd, EV_READ); 243 | ev_io_start(loop, &iface->io); 244 | } 245 | } 246 | return 0; 247 | } 248 | 249 | 250 | static int setup_socket_udp_separate_listen(struct ev_loop *loop, cfg_t *cfg) 251 | { 252 | int udp_listen_port = cfg->udp_listen_port; 253 | int oneopt = 1; 254 | 255 | if (sd_separate_in > 0) 256 | return 0; 257 | 258 | /* If default port we only need to use one socket for send and receive, 259 | * at this point that has already been created (sd_out), so we just 260 | * return */ 261 | if (udp_listen_port == DHCP_SERVER_PORT) 262 | return 0; 263 | 264 | sd_separate_in = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP); 265 | if (sd_separate_in == -1) { 266 | perror("Unable to create in socket"); 267 | return 1; 268 | } 269 | if (setsockopt(sd_separate_in, SOL_IP, IP_PKTINFO, &oneopt, sizeof(oneopt)) == -1 || 270 | setsockopt(sd_separate_in, SOL_SOCKET, SO_BROADCAST, &oneopt, sizeof(oneopt)) == -1) { 271 | perror("Unable to set socket option, SO_BROADCAST"); 272 | close(sd_separate_in); 273 | return 1; 274 | } 275 | 276 | if (setsockopt(sd_separate_in, SOL_SOCKET, SO_REUSEPORT, &oneopt, sizeof(oneopt)) == -1) { 277 | perror("Unable to set socket option, SO_REUSEPORT"); 278 | close(sd_separate_in); 279 | return 1; 280 | } 281 | 282 | struct sockaddr_in saddr; 283 | 284 | memset(&saddr, 0, sizeof(saddr)); 285 | 286 | saddr.sin_family = AF_INET; 287 | saddr.sin_port = htons(udp_listen_port); 288 | saddr.sin_addr.s_addr = INADDR_ANY; 289 | if (bind(sd_separate_in, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in))) { 290 | perror("dhcp-helper: cannot bind DHCP high level socket"); 291 | return -1; 292 | } 293 | 294 | ev_io_init(&io_upstreams_separate_listen, packet_cb_udp, sd_separate_in, EV_READ); 295 | ev_io_start(loop, &io_upstreams_separate_listen); 296 | 297 | return 0; 298 | } 299 | 300 | /* 301 | * Setup socket for listening to packets form server and to be used 302 | * for sending replies to clients. 303 | */ 304 | static int setup_socket_udp(struct ev_loop *loop) 305 | { 306 | int oneopt = 1; 307 | 308 | if (sd_out > 0) 309 | return 0; 310 | 311 | sd_out = socket(AF_INET, SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP); 312 | if (sd_out == -1) { 313 | perror("Unable to create out socket"); 314 | return 1; 315 | } 316 | if (setsockopt(sd_out, SOL_IP, IP_PKTINFO, &oneopt, sizeof(oneopt)) == -1 || 317 | setsockopt(sd_out, SOL_SOCKET, SO_BROADCAST, &oneopt, sizeof(oneopt)) == -1) { 318 | perror("Unable to set socket option, SO_BROADCAST"); 319 | close(sd_out); 320 | return 1; 321 | } 322 | 323 | struct sockaddr_in saddr; 324 | 325 | memset(&saddr, 0, sizeof(saddr)); 326 | 327 | saddr.sin_family = AF_INET; 328 | saddr.sin_port = htons(DHCP_SERVER_PORT); 329 | saddr.sin_addr.s_addr = INADDR_ANY; 330 | if (bind(sd_out, (struct sockaddr *)&saddr, sizeof(struct sockaddr_in))) { 331 | perror("dhcp-helper: cannot bind DHCP high level socket"); 332 | return -1; 333 | } 334 | 335 | ev_io_init(&io_upstreams, packet_cb_udp, sd_out, EV_READ); 336 | ev_io_start(loop, &io_upstreams); 337 | 338 | 339 | return 0; 340 | } 341 | 342 | static void cleanup(struct ev_loop *loop) 343 | { 344 | static int first = 1; 345 | cfg_group_t *group; 346 | cfg_t *cfg = ev_userdata(loop); 347 | 348 | if (first) { 349 | first = 0; 350 | return; 351 | } 352 | 353 | TAILQ_FOREACH(group, &cfg->group_list, link) { 354 | cfg_iface_t *iface; 355 | 356 | TAILQ_FOREACH(iface, &group->iface_list, link) { 357 | char ifname[IFNAMSIZ]; 358 | 359 | if_indextoname(iface->ifindex, ifname); 360 | ev_io_stop(loop, &iface->io); 361 | syslog2(LOG_DEBUG, "clean-up interface %s\n", ifname); 362 | if (iface->sd > 0) { 363 | close(iface->sd); 364 | iface->sd = 0; 365 | } 366 | } 367 | } 368 | /* If we have a non standard listen port, we need to "restart" that UDP 369 | * socket if the value have possibly been reconfigured. */ 370 | if (sd_separate_in > 0) { 371 | ev_io_stop(loop, &io_upstreams_separate_listen); 372 | close(sd_separate_in); 373 | sd_separate_in = 0; 374 | } 375 | 376 | cleanup_nftables(cfg); 377 | conf_free(cfg); 378 | } 379 | 380 | static struct ev_loop *init(struct ev_loop *loop, char *fname) 381 | { 382 | cfg_t *cfg = ev_userdata(loop); 383 | 384 | /* Clear all old settings. */ 385 | cleanup(loop); 386 | if (!cfg || conf_read(cfg, fname)) { 387 | syslog2(LOG_ERR, "Failed reading configuration file, %s: %m", fname); 388 | ev_break(loop, EVBREAK_ALL); 389 | return NULL; 390 | } 391 | 392 | if (setup_sockets_raw(loop, cfg) || setup_socket_udp(loop) || 393 | setup_socket_udp_separate_listen(loop, cfg)) { 394 | syslog2(LOG_ERR, "Failed setting up required sockets."); 395 | ev_break(loop, EVBREAK_ALL); 396 | return NULL; 397 | } 398 | 399 | if (setup_nftables(cfg)) { 400 | syslog2(LOG_ERR, "Failed setting up nftables."); 401 | ev_break(loop, EVBREAK_ALL); 402 | return NULL; 403 | } 404 | return loop; 405 | } 406 | 407 | static void sigcb(struct ev_loop *loop, ev_signal *w, int rev __attribute__ ((unused))) 408 | { 409 | switch (w->signum) { 410 | case SIGHUP: 411 | init(loop, config_file); 412 | break; 413 | 414 | default: 415 | /* Currently graceful shutdown on all other signals */ 416 | cleanup(loop); 417 | ev_break(loop, EVBREAK_ALL); 418 | break; 419 | } 420 | } 421 | 422 | static struct ev_loop *init_signals(struct ev_loop *loop) 423 | { 424 | ev_signal_init(&sigterm_watcher, sigcb, SIGTERM); 425 | ev_signal_start(loop, &sigterm_watcher); 426 | ev_signal_init(&sigint_watcher, sigcb, SIGINT); 427 | ev_signal_start(loop, &sigint_watcher); 428 | ev_signal_init(&sigquit_watcher, sigcb, SIGQUIT); 429 | ev_signal_start(loop, &sigquit_watcher); 430 | ev_signal_init(&sighup_watcher, sigcb, SIGHUP); 431 | ev_signal_start(loop, &sighup_watcher); 432 | 433 | return loop; 434 | } 435 | 436 | static int version(void) 437 | { 438 | printf("%s v%s\n", PACKAGE_NAME, PACKAGE_VERSION); 439 | 440 | return 0; 441 | } 442 | 443 | static int usage(void) 444 | { 445 | printf("Usage: %s [-hvd] -f \n\n" 446 | " -f Read config file\n" 447 | " -d Log all levels to stdout, for debugging.\n" 448 | " -v Show program version\n" 449 | " -h Show this help text\n" 450 | "\n", PACKAGE_NAME); 451 | 452 | return 0; 453 | } 454 | 455 | int main(int argc, char **argv) 456 | { 457 | struct ev_loop *loop; 458 | cfg_t cfg; 459 | int c; 460 | 461 | while ((c = getopt(argc, argv, "f:vdh")) != EOF) { 462 | switch (c) { 463 | case 'f': 464 | strncpy(config_file, optarg, sizeof(config_file)); 465 | config_file[sizeof(config_file)-1] = '\0'; 466 | break; 467 | 468 | case 'v': 469 | return version(); 470 | 471 | case 'd': 472 | log_console(1); 473 | break; 474 | 475 | case 'h': 476 | default: 477 | return usage(); 478 | } 479 | } 480 | 481 | if (access(config_file, F_OK)) { 482 | fprintf(stderr, "Configuration file (%s) not found!\n", config_file); 483 | 484 | return 1; 485 | } 486 | 487 | setlogmask(LOG_UPTO(LOG_INFO)); 488 | syslog2(LOG_INFO, "Starting dhcp-helper"); 489 | 490 | loop = ev_default_loop(0); 491 | 492 | ev_set_userdata(loop, &cfg); 493 | init_signals(loop); 494 | loop = init(loop, config_file); 495 | 496 | if (loop) 497 | ev_run(loop, 0); 498 | 499 | conf_free(&cfg); 500 | close(sd_out); 501 | close(sd_separate_in); 502 | 503 | return 0; 504 | } 505 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /src/queue.h: -------------------------------------------------------------------------------- 1 | /* $OpenBSD: queue.h,v 1.43 2015/12/28 19:38:40 millert Exp $ */ 2 | /* $NetBSD: queue.h,v 1.11 1996/05/16 05:17:14 mycroft Exp $ */ 3 | 4 | /* 5 | * Copyright (c) 1991, 1993 6 | * The Regents of the University of California. All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without 9 | * modification, are permitted provided that the following conditions 10 | * are met: 11 | * 1. Redistributions of source code must retain the above copyright 12 | * notice, this list of conditions and the following disclaimer. 13 | * 2. Redistributions in binary form must reproduce the above copyright 14 | * notice, this list of conditions and the following disclaimer in the 15 | * documentation and/or other materials provided with the distribution. 16 | * 3. Neither the name of the University nor the names of its contributors 17 | * may be used to endorse or promote products derived from this software 18 | * without specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 21 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 24 | * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 26 | * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 27 | * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 28 | * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 29 | * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 30 | * SUCH DAMAGE. 31 | * 32 | * @(#)queue.h 8.5 (Berkeley) 8/20/94 33 | */ 34 | 35 | #ifndef _SYS_QUEUE_H_ 36 | #define _SYS_QUEUE_H_ 37 | 38 | /* 39 | * This file defines five types of data structures: singly-linked lists, 40 | * lists, simple queues, tail queues and XOR simple queues. 41 | * 42 | * 43 | * A singly-linked list is headed by a single forward pointer. The elements 44 | * are singly linked for minimum space and pointer manipulation overhead at 45 | * the expense of O(n) removal for arbitrary elements. New elements can be 46 | * added to the list after an existing element or at the head of the list. 47 | * Elements being removed from the head of the list should use the explicit 48 | * macro for this purpose for optimum efficiency. A singly-linked list may 49 | * only be traversed in the forward direction. Singly-linked lists are ideal 50 | * for applications with large datasets and few or no removals or for 51 | * implementing a LIFO queue. 52 | * 53 | * A list is headed by a single forward pointer (or an array of forward 54 | * pointers for a hash table header). The elements are doubly linked 55 | * so that an arbitrary element can be removed without a need to 56 | * traverse the list. New elements can be added to the list before 57 | * or after an existing element or at the head of the list. A list 58 | * may only be traversed in the forward direction. 59 | * 60 | * A simple queue is headed by a pair of pointers, one to the head of the 61 | * list and the other to the tail of the list. The elements are singly 62 | * linked to save space, so elements can only be removed from the 63 | * head of the list. New elements can be added to the list before or after 64 | * an existing element, at the head of the list, or at the end of the 65 | * list. A simple queue may only be traversed in the forward direction. 66 | * 67 | * A tail queue is headed by a pair of pointers, one to the head of the 68 | * list and the other to the tail of the list. The elements are doubly 69 | * linked so that an arbitrary element can be removed without a need to 70 | * traverse the list. New elements can be added to the list before or 71 | * after an existing element, at the head of the list, or at the end of 72 | * the list. A tail queue may be traversed in either direction. 73 | * 74 | * An XOR simple queue is used in the same way as a regular simple queue. 75 | * The difference is that the head structure also includes a "cookie" that 76 | * is XOR'd with the queue pointer (first, last or next) to generate the 77 | * real pointer value. 78 | * 79 | * For details on the use of these macros, see the queue(3) manual page. 80 | */ 81 | 82 | #if defined(QUEUE_MACRO_DEBUG) || (defined(_KERNEL) && defined(DIAGNOSTIC)) 83 | #define _Q_INVALIDATE(a) (a) = ((void *)-1) 84 | #else 85 | #define _Q_INVALIDATE(a) 86 | #endif 87 | 88 | /* 89 | * Singly-linked List definitions. 90 | */ 91 | #define SLIST_HEAD(name, type) \ 92 | struct name { \ 93 | struct type *slh_first; /* first element */ \ 94 | } 95 | 96 | #define SLIST_HEAD_INITIALIZER(head) \ 97 | { NULL } 98 | 99 | #define SLIST_ENTRY(type) \ 100 | struct { \ 101 | struct type *sle_next; /* next element */ \ 102 | } 103 | 104 | /* 105 | * Singly-linked List access methods. 106 | */ 107 | #define SLIST_FIRST(head) ((head)->slh_first) 108 | #define SLIST_END(head) NULL 109 | #define SLIST_EMPTY(head) (SLIST_FIRST(head) == SLIST_END(head)) 110 | #define SLIST_NEXT(elm, field) ((elm)->field.sle_next) 111 | 112 | #define SLIST_FOREACH(var, head, field) \ 113 | for((var) = SLIST_FIRST(head); \ 114 | (var) != SLIST_END(head); \ 115 | (var) = SLIST_NEXT(var, field)) 116 | 117 | #define SLIST_FOREACH_SAFE(var, head, field, tvar) \ 118 | for ((var) = SLIST_FIRST(head); \ 119 | (var) && ((tvar) = SLIST_NEXT(var, field), 1); \ 120 | (var) = (tvar)) 121 | 122 | /* 123 | * Singly-linked List functions. 124 | */ 125 | #define SLIST_INIT(head) { \ 126 | SLIST_FIRST(head) = SLIST_END(head); \ 127 | } 128 | 129 | #define SLIST_INSERT_AFTER(slistelm, elm, field) do { \ 130 | (elm)->field.sle_next = (slistelm)->field.sle_next; \ 131 | (slistelm)->field.sle_next = (elm); \ 132 | } while (0) 133 | 134 | #define SLIST_INSERT_HEAD(head, elm, field) do { \ 135 | (elm)->field.sle_next = (head)->slh_first; \ 136 | (head)->slh_first = (elm); \ 137 | } while (0) 138 | 139 | #define SLIST_REMOVE_AFTER(elm, field) do { \ 140 | (elm)->field.sle_next = (elm)->field.sle_next->field.sle_next; \ 141 | } while (0) 142 | 143 | #define SLIST_REMOVE_HEAD(head, field) do { \ 144 | (head)->slh_first = (head)->slh_first->field.sle_next; \ 145 | } while (0) 146 | 147 | #define SLIST_REMOVE(head, elm, type, field) do { \ 148 | if ((head)->slh_first == (elm)) { \ 149 | SLIST_REMOVE_HEAD((head), field); \ 150 | } else { \ 151 | struct type *curelm = (head)->slh_first; \ 152 | \ 153 | while (curelm->field.sle_next != (elm)) \ 154 | curelm = curelm->field.sle_next; \ 155 | curelm->field.sle_next = \ 156 | curelm->field.sle_next->field.sle_next; \ 157 | } \ 158 | _Q_INVALIDATE((elm)->field.sle_next); \ 159 | } while (0) 160 | 161 | /* 162 | * List definitions. 163 | */ 164 | #define LIST_HEAD(name, type) \ 165 | struct name { \ 166 | struct type *lh_first; /* first element */ \ 167 | } 168 | 169 | #define LIST_HEAD_INITIALIZER(head) \ 170 | { NULL } 171 | 172 | #define LIST_ENTRY(type) \ 173 | struct { \ 174 | struct type *le_next; /* next element */ \ 175 | struct type **le_prev; /* address of previous next element */ \ 176 | } 177 | 178 | /* 179 | * List access methods. 180 | */ 181 | #define LIST_FIRST(head) ((head)->lh_first) 182 | #define LIST_END(head) NULL 183 | #define LIST_EMPTY(head) (LIST_FIRST(head) == LIST_END(head)) 184 | #define LIST_NEXT(elm, field) ((elm)->field.le_next) 185 | 186 | #define LIST_FOREACH(var, head, field) \ 187 | for((var) = LIST_FIRST(head); \ 188 | (var)!= LIST_END(head); \ 189 | (var) = LIST_NEXT(var, field)) 190 | 191 | #define LIST_FOREACH_SAFE(var, head, field, tvar) \ 192 | for ((var) = LIST_FIRST(head); \ 193 | (var) && ((tvar) = LIST_NEXT(var, field), 1); \ 194 | (var) = (tvar)) 195 | 196 | /* 197 | * List functions. 198 | */ 199 | #define LIST_INIT(head) do { \ 200 | LIST_FIRST(head) = LIST_END(head); \ 201 | } while (0) 202 | 203 | #define LIST_INSERT_AFTER(listelm, elm, field) do { \ 204 | if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \ 205 | (listelm)->field.le_next->field.le_prev = \ 206 | &(elm)->field.le_next; \ 207 | (listelm)->field.le_next = (elm); \ 208 | (elm)->field.le_prev = &(listelm)->field.le_next; \ 209 | } while (0) 210 | 211 | #define LIST_INSERT_BEFORE(listelm, elm, field) do { \ 212 | (elm)->field.le_prev = (listelm)->field.le_prev; \ 213 | (elm)->field.le_next = (listelm); \ 214 | *(listelm)->field.le_prev = (elm); \ 215 | (listelm)->field.le_prev = &(elm)->field.le_next; \ 216 | } while (0) 217 | 218 | #define LIST_INSERT_HEAD(head, elm, field) do { \ 219 | if (((elm)->field.le_next = (head)->lh_first) != NULL) \ 220 | (head)->lh_first->field.le_prev = &(elm)->field.le_next;\ 221 | (head)->lh_first = (elm); \ 222 | (elm)->field.le_prev = &(head)->lh_first; \ 223 | } while (0) 224 | 225 | #define LIST_REMOVE(elm, field) do { \ 226 | if ((elm)->field.le_next != NULL) \ 227 | (elm)->field.le_next->field.le_prev = \ 228 | (elm)->field.le_prev; \ 229 | *(elm)->field.le_prev = (elm)->field.le_next; \ 230 | _Q_INVALIDATE((elm)->field.le_prev); \ 231 | _Q_INVALIDATE((elm)->field.le_next); \ 232 | } while (0) 233 | 234 | #define LIST_REPLACE(elm, elm2, field) do { \ 235 | if (((elm2)->field.le_next = (elm)->field.le_next) != NULL) \ 236 | (elm2)->field.le_next->field.le_prev = \ 237 | &(elm2)->field.le_next; \ 238 | (elm2)->field.le_prev = (elm)->field.le_prev; \ 239 | *(elm2)->field.le_prev = (elm2); \ 240 | _Q_INVALIDATE((elm)->field.le_prev); \ 241 | _Q_INVALIDATE((elm)->field.le_next); \ 242 | } while (0) 243 | 244 | /* 245 | * Simple queue definitions. 246 | */ 247 | #define SIMPLEQ_HEAD(name, type) \ 248 | struct name { \ 249 | struct type *sqh_first; /* first element */ \ 250 | struct type **sqh_last; /* addr of last next element */ \ 251 | } 252 | 253 | #define SIMPLEQ_HEAD_INITIALIZER(head) \ 254 | { NULL, &(head).sqh_first } 255 | 256 | #define SIMPLEQ_ENTRY(type) \ 257 | struct { \ 258 | struct type *sqe_next; /* next element */ \ 259 | } 260 | 261 | /* 262 | * Simple queue access methods. 263 | */ 264 | #define SIMPLEQ_FIRST(head) ((head)->sqh_first) 265 | #define SIMPLEQ_END(head) NULL 266 | #define SIMPLEQ_EMPTY(head) (SIMPLEQ_FIRST(head) == SIMPLEQ_END(head)) 267 | #define SIMPLEQ_NEXT(elm, field) ((elm)->field.sqe_next) 268 | 269 | #define SIMPLEQ_FOREACH(var, head, field) \ 270 | for((var) = SIMPLEQ_FIRST(head); \ 271 | (var) != SIMPLEQ_END(head); \ 272 | (var) = SIMPLEQ_NEXT(var, field)) 273 | 274 | #define SIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \ 275 | for ((var) = SIMPLEQ_FIRST(head); \ 276 | (var) && ((tvar) = SIMPLEQ_NEXT(var, field), 1); \ 277 | (var) = (tvar)) 278 | 279 | /* 280 | * Simple queue functions. 281 | */ 282 | #define SIMPLEQ_INIT(head) do { \ 283 | (head)->sqh_first = NULL; \ 284 | (head)->sqh_last = &(head)->sqh_first; \ 285 | } while (0) 286 | 287 | #define SIMPLEQ_INSERT_HEAD(head, elm, field) do { \ 288 | if (((elm)->field.sqe_next = (head)->sqh_first) == NULL) \ 289 | (head)->sqh_last = &(elm)->field.sqe_next; \ 290 | (head)->sqh_first = (elm); \ 291 | } while (0) 292 | 293 | #define SIMPLEQ_INSERT_TAIL(head, elm, field) do { \ 294 | (elm)->field.sqe_next = NULL; \ 295 | *(head)->sqh_last = (elm); \ 296 | (head)->sqh_last = &(elm)->field.sqe_next; \ 297 | } while (0) 298 | 299 | #define SIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ 300 | if (((elm)->field.sqe_next = (listelm)->field.sqe_next) == NULL)\ 301 | (head)->sqh_last = &(elm)->field.sqe_next; \ 302 | (listelm)->field.sqe_next = (elm); \ 303 | } while (0) 304 | 305 | #define SIMPLEQ_REMOVE_HEAD(head, field) do { \ 306 | if (((head)->sqh_first = (head)->sqh_first->field.sqe_next) == NULL) \ 307 | (head)->sqh_last = &(head)->sqh_first; \ 308 | } while (0) 309 | 310 | #define SIMPLEQ_REMOVE_AFTER(head, elm, field) do { \ 311 | if (((elm)->field.sqe_next = (elm)->field.sqe_next->field.sqe_next) \ 312 | == NULL) \ 313 | (head)->sqh_last = &(elm)->field.sqe_next; \ 314 | } while (0) 315 | 316 | #define SIMPLEQ_CONCAT(head1, head2) do { \ 317 | if (!SIMPLEQ_EMPTY((head2))) { \ 318 | *(head1)->sqh_last = (head2)->sqh_first; \ 319 | (head1)->sqh_last = (head2)->sqh_last; \ 320 | SIMPLEQ_INIT((head2)); \ 321 | } \ 322 | } while (0) 323 | 324 | /* 325 | * XOR Simple queue definitions. 326 | */ 327 | #define XSIMPLEQ_HEAD(name, type) \ 328 | struct name { \ 329 | struct type *sqx_first; /* first element */ \ 330 | struct type **sqx_last; /* addr of last next element */ \ 331 | unsigned long sqx_cookie; \ 332 | } 333 | 334 | #define XSIMPLEQ_ENTRY(type) \ 335 | struct { \ 336 | struct type *sqx_next; /* next element */ \ 337 | } 338 | 339 | /* 340 | * XOR Simple queue access methods. 341 | */ 342 | #define XSIMPLEQ_XOR(head, ptr) ((__typeof(ptr))((head)->sqx_cookie ^ \ 343 | (unsigned long)(ptr))) 344 | #define XSIMPLEQ_FIRST(head) XSIMPLEQ_XOR(head, ((head)->sqx_first)) 345 | #define XSIMPLEQ_END(head) NULL 346 | #define XSIMPLEQ_EMPTY(head) (XSIMPLEQ_FIRST(head) == XSIMPLEQ_END(head)) 347 | #define XSIMPLEQ_NEXT(head, elm, field) XSIMPLEQ_XOR(head, ((elm)->field.sqx_next)) 348 | 349 | 350 | #define XSIMPLEQ_FOREACH(var, head, field) \ 351 | for ((var) = XSIMPLEQ_FIRST(head); \ 352 | (var) != XSIMPLEQ_END(head); \ 353 | (var) = XSIMPLEQ_NEXT(head, var, field)) 354 | 355 | #define XSIMPLEQ_FOREACH_SAFE(var, head, field, tvar) \ 356 | for ((var) = XSIMPLEQ_FIRST(head); \ 357 | (var) && ((tvar) = XSIMPLEQ_NEXT(head, var, field), 1); \ 358 | (var) = (tvar)) 359 | 360 | /* 361 | * XOR Simple queue functions. 362 | */ 363 | #define XSIMPLEQ_INIT(head) do { \ 364 | arc4random_buf(&(head)->sqx_cookie, sizeof((head)->sqx_cookie)); \ 365 | (head)->sqx_first = XSIMPLEQ_XOR(head, NULL); \ 366 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \ 367 | } while (0) 368 | 369 | #define XSIMPLEQ_INSERT_HEAD(head, elm, field) do { \ 370 | if (((elm)->field.sqx_next = (head)->sqx_first) == \ 371 | XSIMPLEQ_XOR(head, NULL)) \ 372 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ 373 | (head)->sqx_first = XSIMPLEQ_XOR(head, (elm)); \ 374 | } while (0) 375 | 376 | #define XSIMPLEQ_INSERT_TAIL(head, elm, field) do { \ 377 | (elm)->field.sqx_next = XSIMPLEQ_XOR(head, NULL); \ 378 | *(XSIMPLEQ_XOR(head, (head)->sqx_last)) = XSIMPLEQ_XOR(head, (elm)); \ 379 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ 380 | } while (0) 381 | 382 | #define XSIMPLEQ_INSERT_AFTER(head, listelm, elm, field) do { \ 383 | if (((elm)->field.sqx_next = (listelm)->field.sqx_next) == \ 384 | XSIMPLEQ_XOR(head, NULL)) \ 385 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ 386 | (listelm)->field.sqx_next = XSIMPLEQ_XOR(head, (elm)); \ 387 | } while (0) 388 | 389 | #define XSIMPLEQ_REMOVE_HEAD(head, field) do { \ 390 | if (((head)->sqx_first = XSIMPLEQ_XOR(head, \ 391 | (head)->sqx_first)->field.sqx_next) == XSIMPLEQ_XOR(head, NULL)) \ 392 | (head)->sqx_last = XSIMPLEQ_XOR(head, &(head)->sqx_first); \ 393 | } while (0) 394 | 395 | #define XSIMPLEQ_REMOVE_AFTER(head, elm, field) do { \ 396 | if (((elm)->field.sqx_next = XSIMPLEQ_XOR(head, \ 397 | (elm)->field.sqx_next)->field.sqx_next) \ 398 | == XSIMPLEQ_XOR(head, NULL)) \ 399 | (head)->sqx_last = \ 400 | XSIMPLEQ_XOR(head, &(elm)->field.sqx_next); \ 401 | } while (0) 402 | 403 | 404 | /* 405 | * Tail queue definitions. 406 | */ 407 | #define TAILQ_HEAD(name, type) \ 408 | struct name { \ 409 | struct type *tqh_first; /* first element */ \ 410 | struct type **tqh_last; /* addr of last next element */ \ 411 | } 412 | 413 | #define TAILQ_HEAD_INITIALIZER(head) \ 414 | { NULL, &(head).tqh_first } 415 | 416 | #define TAILQ_ENTRY(type) \ 417 | struct { \ 418 | struct type *tqe_next; /* next element */ \ 419 | struct type **tqe_prev; /* address of previous next element */ \ 420 | } 421 | 422 | /* 423 | * Tail queue access methods. 424 | */ 425 | #define TAILQ_FIRST(head) ((head)->tqh_first) 426 | #define TAILQ_END(head) NULL 427 | #define TAILQ_NEXT(elm, field) ((elm)->field.tqe_next) 428 | #define TAILQ_LAST(head, headname) \ 429 | (*(((struct headname *)((head)->tqh_last))->tqh_last)) 430 | /* XXX */ 431 | #define TAILQ_PREV(elm, headname, field) \ 432 | (*(((struct headname *)((elm)->field.tqe_prev))->tqh_last)) 433 | #define TAILQ_EMPTY(head) \ 434 | (TAILQ_FIRST(head) == TAILQ_END(head)) 435 | 436 | #define TAILQ_FOREACH(var, head, field) \ 437 | for((var) = TAILQ_FIRST(head); \ 438 | (var) != TAILQ_END(head); \ 439 | (var) = TAILQ_NEXT(var, field)) 440 | 441 | #define TAILQ_FOREACH_SAFE(var, head, field, tvar) \ 442 | for ((var) = TAILQ_FIRST(head); \ 443 | (var) != TAILQ_END(head) && \ 444 | ((tvar) = TAILQ_NEXT(var, field), 1); \ 445 | (var) = (tvar)) 446 | 447 | 448 | #define TAILQ_FOREACH_REVERSE(var, head, headname, field) \ 449 | for((var) = TAILQ_LAST(head, headname); \ 450 | (var) != TAILQ_END(head); \ 451 | (var) = TAILQ_PREV(var, headname, field)) 452 | 453 | #define TAILQ_FOREACH_REVERSE_SAFE(var, head, headname, field, tvar) \ 454 | for ((var) = TAILQ_LAST(head, headname); \ 455 | (var) != TAILQ_END(head) && \ 456 | ((tvar) = TAILQ_PREV(var, headname, field), 1); \ 457 | (var) = (tvar)) 458 | 459 | /* 460 | * Tail queue functions. 461 | */ 462 | #define TAILQ_INIT(head) do { \ 463 | (head)->tqh_first = NULL; \ 464 | (head)->tqh_last = &(head)->tqh_first; \ 465 | } while (0) 466 | 467 | #define TAILQ_INSERT_HEAD(head, elm, field) do { \ 468 | if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \ 469 | (head)->tqh_first->field.tqe_prev = \ 470 | &(elm)->field.tqe_next; \ 471 | else \ 472 | (head)->tqh_last = &(elm)->field.tqe_next; \ 473 | (head)->tqh_first = (elm); \ 474 | (elm)->field.tqe_prev = &(head)->tqh_first; \ 475 | } while (0) 476 | 477 | #define TAILQ_INSERT_TAIL(head, elm, field) do { \ 478 | (elm)->field.tqe_next = NULL; \ 479 | (elm)->field.tqe_prev = (head)->tqh_last; \ 480 | *(head)->tqh_last = (elm); \ 481 | (head)->tqh_last = &(elm)->field.tqe_next; \ 482 | } while (0) 483 | 484 | #define TAILQ_INSERT_AFTER(head, listelm, elm, field) do { \ 485 | if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\ 486 | (elm)->field.tqe_next->field.tqe_prev = \ 487 | &(elm)->field.tqe_next; \ 488 | else \ 489 | (head)->tqh_last = &(elm)->field.tqe_next; \ 490 | (listelm)->field.tqe_next = (elm); \ 491 | (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \ 492 | } while (0) 493 | 494 | #define TAILQ_INSERT_BEFORE(listelm, elm, field) do { \ 495 | (elm)->field.tqe_prev = (listelm)->field.tqe_prev; \ 496 | (elm)->field.tqe_next = (listelm); \ 497 | *(listelm)->field.tqe_prev = (elm); \ 498 | (listelm)->field.tqe_prev = &(elm)->field.tqe_next; \ 499 | } while (0) 500 | 501 | #define TAILQ_REMOVE(head, elm, field) do { \ 502 | if (((elm)->field.tqe_next) != NULL) \ 503 | (elm)->field.tqe_next->field.tqe_prev = \ 504 | (elm)->field.tqe_prev; \ 505 | else \ 506 | (head)->tqh_last = (elm)->field.tqe_prev; \ 507 | *(elm)->field.tqe_prev = (elm)->field.tqe_next; \ 508 | _Q_INVALIDATE((elm)->field.tqe_prev); \ 509 | _Q_INVALIDATE((elm)->field.tqe_next); \ 510 | } while (0) 511 | 512 | #define TAILQ_REPLACE(head, elm, elm2, field) do { \ 513 | if (((elm2)->field.tqe_next = (elm)->field.tqe_next) != NULL) \ 514 | (elm2)->field.tqe_next->field.tqe_prev = \ 515 | &(elm2)->field.tqe_next; \ 516 | else \ 517 | (head)->tqh_last = &(elm2)->field.tqe_next; \ 518 | (elm2)->field.tqe_prev = (elm)->field.tqe_prev; \ 519 | *(elm2)->field.tqe_prev = (elm2); \ 520 | _Q_INVALIDATE((elm)->field.tqe_prev); \ 521 | _Q_INVALIDATE((elm)->field.tqe_next); \ 522 | } while (0) 523 | 524 | #define TAILQ_CONCAT(head1, head2, field) do { \ 525 | if (!TAILQ_EMPTY(head2)) { \ 526 | *(head1)->tqh_last = (head2)->tqh_first; \ 527 | (head2)->tqh_first->field.tqe_prev = (head1)->tqh_last; \ 528 | (head1)->tqh_last = (head2)->tqh_last; \ 529 | TAILQ_INIT((head2)); \ 530 | } \ 531 | } while (0) 532 | 533 | #endif /* !_SYS_QUEUE_H_ */ 534 | --------------------------------------------------------------------------------