From b8bd3f3afec9f8960030beccfeeb37af68ec68c4 Mon Sep 17 00:00:00 2001 From: aixiao Date: Thu, 13 Oct 2022 18:01:06 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=9C=B0=E5=9F=9F=E7=99=BD?= =?UTF-8?q?=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Makefile | 10 +- conf.c | 20 + conf.h | 4 + denyhosts.sh | 2 +- libiptc/libip4tc.a | Bin 0 -> 41336 bytes libiptc/libip4tc.c | 311 +++++ libiptc/libip4tc.o | Bin 0 -> 40600 bytes libiptc/libiptc.c | 2751 +++++++++++++++++++++++++++++++++++++ libiptc/linux_list.h | 723 ++++++++++ libiptc/xtables-version.h | 2 + libiptc/xtables.h | 674 +++++++++ rhost.c | 83 +- rhost.conf | 9 +- 13 files changed, 4571 insertions(+), 18 deletions(-) create mode 100644 libiptc/libip4tc.a create mode 100644 libiptc/libip4tc.c create mode 100644 libiptc/libip4tc.o create mode 100644 libiptc/libiptc.c create mode 100644 libiptc/linux_list.h create mode 100644 libiptc/xtables-version.h create mode 100644 libiptc/xtables.h diff --git a/Makefile b/Makefile index c5d89c9..074607c 100644 --- a/Makefile +++ b/Makefile @@ -2,12 +2,20 @@ CROSS_COMPILE ?= CC := $(CROSS_COMPILE)gcc CFLAGS += -Os -g -Wall LIB += -lcurl -lip4tc + +IPTC_CFLAGS += -DHAVE_CONFIG_H -I./libiptc -D_LARGEFILE_SOURCE=1 -D_LARGE_FILES -D_FILE_OFFSET_BITS=64 -D_REENTRANT + OBG = rhost all: conf.o rhost.o libiptc.o $(CC) $(CFLAGS) $^ -o $(OBG) $(LIB) chmod +x $(OBG) - + +static: conf.o rhost.o libiptc.o + $(CC) $(IPTC_CFLAGS) -c libiptc/libip4tc.c -o libiptc/libip4tc.o + ar crs libiptc/libip4tc.a libiptc/libip4tc.o + $(CC) $(CFLAGS) $^ -o $(OBG) libiptc/libip4tc.o -lcurl + clean: rm -rf *.o rm $(OBG) diff --git a/conf.c b/conf.c index 5399e8e..daed7ac 100644 --- a/conf.c +++ b/conf.c @@ -168,6 +168,17 @@ static void parse_global_module(char *content, conf * conf) return; } + + if (strcasecmp(var, "REGION") == 0) { + val_begin_len = val_end - val_begin; + conf->REGION = atoi(val_begin); + } + + if (strcasecmp(var, "REGION_LIST") == 0) { + val_begin_len = val_end - val_begin; + if (copy_new_mem(val_begin, val_begin_len, &conf->REGION_LIST) != 0) + return; + } content = strchr(lineEnd + 1, '\n'); @@ -248,6 +259,9 @@ void free_conf(conf * conf) if (conf->IPV4_WHITE_LIST) free(conf->IPV4_WHITE_LIST); + if (conf->REGION_LIST) + free(conf->REGION_LIST); + return; } @@ -272,8 +286,14 @@ void ptintf_conf(conf * conf) printf("%s\n", conf->RECV_MAIL); if (conf->PUBLIC_IP) printf("%s\n", conf->PUBLIC_IP); + + printf("%d\n", conf->IPV4_RESTRICTION); if (conf->IPV4_WHITE_LIST) printf("%s\n", conf->IPV4_WHITE_LIST); + + printf("%d\n", conf->REGION); + if (conf->REGION_LIST) + printf("%s\n", conf->REGION_LIST); } void split_string(char string[], char delims[], char (*whitelist_ip)[WHITELIST_IP_NUM]) diff --git a/conf.h b/conf.h index 8890437..985a9fa 100644 --- a/conf.h +++ b/conf.h @@ -18,6 +18,10 @@ typedef struct CONF { // 获取公网IP Url地址 char *PUBLIC_IP; + + // 地域白名单 + int REGION; + char *REGION_LIST; // IPV4 白名单 int IPV4_RESTRICTION; diff --git a/denyhosts.sh b/denyhosts.sh index a18c66f..d8fbdfd 100644 --- a/denyhosts.sh +++ b/denyhosts.sh @@ -34,7 +34,7 @@ function run() netstat -tnulp &>> ${LOG_FILE} echo "System SSH authorization information:" &>> ${LOG_FILE} - /root/denyhosts/rhost | awk '{a[$1]+=1;} END {for(i in a){print a[i]" "i;}}' &>> ${LOG_FILE} + /root/denyhosts/rhost | grep -E "^[0-9]" | awk '{a[$1]+=1;} END {for(i in a){print a[i]" "i;}}' &>> ${LOG_FILE} $IPTABLES_SAVE > /root/ipv4tables diff --git a/libiptc/libip4tc.a b/libiptc/libip4tc.a new file mode 100644 index 0000000000000000000000000000000000000000..73b454c195c9ad4d5dda08023a5c0d1d5ae7450b GIT binary patch literal 41336 zcmeHw4|tqamG_&ZK&W8CAGOH8DYlTp(grNp@^?ZzWeWW>v<*ZkCTTJyku;M{W*}XN zmM1NCm`3X#)_%&m711rD3yd2*`SD7wyRMKPMo?%L^ooU@Ao_R+;{H0 znL&1+?|Z&ypXYmFI`{pZbI(2Z+;i_e_uluN%)X+vx2@xZ(53Z@ zl%r*)=Xqy&UgbmoFFu_;$+qUs?#`qqsg1qyxYwTA)YBaAPWE=j`wZOK*WA|8+S#p4 zoxOcY7wC@n7u|0ZhTc?H+++}X;r6z8vN_q>i!Vdokm~G8THz%2B)U4=Hfzz{eevF; zsG~@4yr-+RE$%|CJw5U6b{A=ncg2%MJZ&BEw%bdvbf-4C=*F&8UxxsG?f)#^nw>Ifi6id*d79z47igYid>8;R3aFQ&B#Oc5T#_ z*tE&EU|+H~-rJi{wGusjp4Zj6p|fXUvTc6CcxgG`ymaA0@yUhtm)0AemYE-otXNiA zQ2`eBbxg_%u#M)3It{$^c8(Y7#60Pa2lmoho4PNUan=A(;q1$gq-0$ay}R9?sqW z=9_QseAbjUjX8>v8eQ(&9B%6Ei!IU%$~X#C+ZsyYC^!=a^b!ky1mZ-OVb80m^-MBc z?Nx?6tCLzMn(?BGVWiJwYxZURx`iM*mrfmiatn-_qhX_I6fih2<)x0>&-;7}g+8_g z$tQTvQstW#7>dFgk=$cv3*nh)`k#fCX*|qK=~%reG!zpVFtGV9+;@=f+s-PJi5!j& zX2X6-L5)P}V_}pzT_b7J7`2*$7U|d`rv$acaCin?%r>xX1>+%8(aR%~s5&|Fry_GM z;|;|sm`K-(K?;tQPQ6a)(ae@z;EoQ(>N1hn3$8bKq#o8CLlcht1Ruad`dBHIHU1B1Z=!Q`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zq2KP+xK^N2XOoTPBwts_jkqvxP5;|0uV=k z`~FTy$0w`5eSaq$!0r1xEdkuVzq2KP+xK^N2XOoTPBwts_jkqvxP5;Iud2vp^|bHr zgaWvIZ(?Zxx9=&~IL^wk@B3^G@Z0wk9tz+!A*08^0DisVhXeTM6`yge$!E*8?=Q>= z;P(B6r2+gWvrYc?0B+wi+8V&^dkqf-aQj}v!2oXGYd9Rh?fXhIjw{yRzOPgl!0mew z(Ex7WgXjq0_C1L00o=a#v?qYu_nt-qxP9*_7r^a%6V*E5S^L}fEb0QdeV@XP2bSNy zPtg(Jx9?MI58(EFiai0`zE3d{!0r1Kxd3k8r>H)@*#7o?in;)9-=~NMaQi+*M*z3) zQ*005_WiFt0o=a-H4?z>`(L>LZr}f^o>{EFegCU2fZO*tq5<5#uh9{}?R$Bj3E=j9 zH*bF5=1q8F9pA}b^W9-nz45Nr`N?>H(wi^I_SR&pH-AH4AMO+8#>dGqpO0^MIm`m~ zCM=F8=lP3I-hBK@SA71ps~RuFlk9D`Yle6S-e%xK>iM$&yT{>7k*Y;$o$H%?GYs{TK&gPR;oa7;x#K&Sj6B5mu-^G{?@}?CFwqJ|p->c(+ zm1Fg{_gj%DRsY?eG#ukPkFfq+$JzYW{?sQ}HgneMf?!1B& literal 0 HcmV?d00001 diff --git a/libiptc/libip4tc.c b/libiptc/libip4tc.c new file mode 100644 index 0000000..78a896f --- /dev/null +++ b/libiptc/libip4tc.c @@ -0,0 +1,311 @@ +/* Library which manipulates firewall rules. Version 0.1. */ + +/* Architecture of firewall rules is as follows: + * + * Chains go INPUT, FORWARD, OUTPUT then user chains. + * Each user chain starts with an ERROR node. + * Every chain ends with an unconditional jump: a RETURN for user chains, + * and a POLICY for built-ins. + */ + +/* (C)1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See + COPYING for details). */ + +#include +#include +#include +#include +#include +#include + +#ifdef DEBUG_CONNTRACK +#define inline +#endif + +#if !defined(__BIONIC__) && (!defined(__GLIBC__) || (__GLIBC__ < 2)) +typedef unsigned int socklen_t; +#endif + +#include "libiptc/libiptc.h" + +#define IP_VERSION 4 +#define IP_OFFSET 0x1FFF + +#define HOOK_PRE_ROUTING NF_IP_PRE_ROUTING +#define HOOK_LOCAL_IN NF_IP_LOCAL_IN +#define HOOK_FORWARD NF_IP_FORWARD +#define HOOK_LOCAL_OUT NF_IP_LOCAL_OUT +#define HOOK_POST_ROUTING NF_IP_POST_ROUTING + +#define STRUCT_ENTRY_TARGET struct xt_entry_target +#define STRUCT_ENTRY struct ipt_entry +#define STRUCT_ENTRY_MATCH struct xt_entry_match +#define STRUCT_GETINFO struct ipt_getinfo +#define STRUCT_GET_ENTRIES struct ipt_get_entries +#define STRUCT_COUNTERS struct xt_counters +#define STRUCT_COUNTERS_INFO struct xt_counters_info +#define STRUCT_STANDARD_TARGET struct xt_standard_target +#define STRUCT_REPLACE struct ipt_replace + +#define ENTRY_ITERATE IPT_ENTRY_ITERATE +#define TABLE_MAXNAMELEN XT_TABLE_MAXNAMELEN +#define FUNCTION_MAXNAMELEN XT_FUNCTION_MAXNAMELEN + +#define GET_TARGET ipt_get_target + +#define ERROR_TARGET XT_ERROR_TARGET +#define NUMHOOKS NF_IP_NUMHOOKS + +#define IPT_CHAINLABEL xt_chainlabel + +#define TC_DUMP_ENTRIES dump_entries +#define TC_IS_CHAIN iptc_is_chain +#define TC_FIRST_CHAIN iptc_first_chain +#define TC_NEXT_CHAIN iptc_next_chain +#define TC_FIRST_RULE iptc_first_rule +#define TC_NEXT_RULE iptc_next_rule +#define TC_GET_TARGET iptc_get_target +#define TC_BUILTIN iptc_builtin +#define TC_GET_POLICY iptc_get_policy +#define TC_INSERT_ENTRY iptc_insert_entry +#define TC_REPLACE_ENTRY iptc_replace_entry +#define TC_APPEND_ENTRY iptc_append_entry +#define TC_CHECK_ENTRY iptc_check_entry +#define TC_DELETE_ENTRY iptc_delete_entry +#define TC_DELETE_NUM_ENTRY iptc_delete_num_entry +#define TC_FLUSH_ENTRIES iptc_flush_entries +#define TC_ZERO_ENTRIES iptc_zero_entries +#define TC_READ_COUNTER iptc_read_counter +#define TC_ZERO_COUNTER iptc_zero_counter +#define TC_SET_COUNTER iptc_set_counter +#define TC_CREATE_CHAIN iptc_create_chain +#define TC_GET_REFERENCES iptc_get_references +#define TC_DELETE_CHAIN iptc_delete_chain +#define TC_RENAME_CHAIN iptc_rename_chain +#define TC_SET_POLICY iptc_set_policy +#define TC_GET_RAW_SOCKET iptc_get_raw_socket +#define TC_INIT iptc_init +#define TC_FREE iptc_free +#define TC_COMMIT iptc_commit +#define TC_STRERROR iptc_strerror +#define TC_NUM_RULES iptc_num_rules +#define TC_GET_RULE iptc_get_rule +#define TC_OPS iptc_ops + +#define TC_AF AF_INET +#define TC_IPPROTO IPPROTO_IP + +#define SO_SET_REPLACE IPT_SO_SET_REPLACE +#define SO_SET_ADD_COUNTERS IPT_SO_SET_ADD_COUNTERS +#define SO_GET_INFO IPT_SO_GET_INFO +#define SO_GET_ENTRIES IPT_SO_GET_ENTRIES +#define SO_GET_VERSION IPT_SO_GET_VERSION + +#define STANDARD_TARGET XT_STANDARD_TARGET +#define LABEL_RETURN IPTC_LABEL_RETURN +#define LABEL_ACCEPT IPTC_LABEL_ACCEPT +#define LABEL_DROP IPTC_LABEL_DROP +#define LABEL_QUEUE IPTC_LABEL_QUEUE + +#define ALIGN XT_ALIGN +#define RETURN XT_RETURN + +#include "libiptc.c" + +#define IP_PARTS_NATIVE(n) \ +(unsigned int)((n)>>24)&0xFF, \ +(unsigned int)((n)>>16)&0xFF, \ +(unsigned int)((n)>>8)&0xFF, \ +(unsigned int)((n)&0xFF) + +#define IP_PARTS(n) IP_PARTS_NATIVE(ntohl(n)) + +static int +dump_entry(struct ipt_entry *e, struct xtc_handle *const handle) +{ + size_t i; + STRUCT_ENTRY_TARGET *t; + + printf("Entry %u (%lu):\n", iptcb_entry2index(handle, e), + iptcb_entry2offset(handle, e)); + printf("SRC IP: %u.%u.%u.%u/%u.%u.%u.%u\n", + IP_PARTS(e->ip.src.s_addr),IP_PARTS(e->ip.smsk.s_addr)); + printf("DST IP: %u.%u.%u.%u/%u.%u.%u.%u\n", + IP_PARTS(e->ip.dst.s_addr),IP_PARTS(e->ip.dmsk.s_addr)); + printf("Interface: `%s'/", e->ip.iniface); + for (i = 0; i < IFNAMSIZ; i++) + printf("%c", e->ip.iniface_mask[i] ? 'X' : '.'); + printf("to `%s'/", e->ip.outiface); + for (i = 0; i < IFNAMSIZ; i++) + printf("%c", e->ip.outiface_mask[i] ? 'X' : '.'); + printf("\nProtocol: %u\n", e->ip.proto); + printf("Flags: %02X\n", e->ip.flags); + printf("Invflags: %02X\n", e->ip.invflags); + printf("Counters: %llu packets, %llu bytes\n", + (unsigned long long)e->counters.pcnt, (unsigned long long)e->counters.bcnt); + printf("Cache: %08X\n", e->nfcache); + + IPT_MATCH_ITERATE(e, print_match); + + t = GET_TARGET(e); + printf("Target name: `%s' [%u]\n", t->u.user.name, t->u.target_size); + if (strcmp(t->u.user.name, STANDARD_TARGET) == 0) { + const unsigned char *data = t->data; + int pos = *(const int *)data; + if (pos < 0) + printf("verdict=%s\n", + pos == -NF_ACCEPT-1 ? "NF_ACCEPT" + : pos == -NF_DROP-1 ? "NF_DROP" + : pos == -NF_QUEUE-1 ? "NF_QUEUE" + : pos == RETURN ? "RETURN" + : "UNKNOWN"); + else + printf("verdict=%u\n", pos); + } else if (strcmp(t->u.user.name, XT_ERROR_TARGET) == 0) + printf("error=`%s'\n", t->data); + + printf("\n"); + return 0; +} + +static unsigned char * +is_same(const STRUCT_ENTRY *a, const STRUCT_ENTRY *b, unsigned char *matchmask) +{ + unsigned int i; + unsigned char *mptr; + + /* Always compare head structures: ignore mask here. */ + if (a->ip.src.s_addr != b->ip.src.s_addr + || a->ip.dst.s_addr != b->ip.dst.s_addr + || a->ip.smsk.s_addr != b->ip.smsk.s_addr + || a->ip.dmsk.s_addr != b->ip.dmsk.s_addr + || a->ip.proto != b->ip.proto + || a->ip.flags != b->ip.flags + || a->ip.invflags != b->ip.invflags) + return NULL; + + for (i = 0; i < IFNAMSIZ; i++) { + if (a->ip.iniface_mask[i] != b->ip.iniface_mask[i]) + return NULL; + if ((a->ip.iniface[i] & a->ip.iniface_mask[i]) + != (b->ip.iniface[i] & b->ip.iniface_mask[i])) + return NULL; + if (a->ip.outiface_mask[i] != b->ip.outiface_mask[i]) + return NULL; + if ((a->ip.outiface[i] & a->ip.outiface_mask[i]) + != (b->ip.outiface[i] & b->ip.outiface_mask[i])) + return NULL; + } + + if (a->target_offset != b->target_offset + || a->next_offset != b->next_offset) + return NULL; + + mptr = matchmask + sizeof(STRUCT_ENTRY); + if (IPT_MATCH_ITERATE(a, match_different, a->elems, b->elems, &mptr)) + return NULL; + mptr += XT_ALIGN(sizeof(struct xt_entry_target)); + + return mptr; +} + +#if 0 +/***************************** DEBUGGING ********************************/ +static inline int +unconditional(const struct ipt_ip *ip) +{ + unsigned int i; + + for (i = 0; i < sizeof(*ip)/sizeof(uint32_t); i++) + if (((uint32_t *)ip)[i]) + return 0; + + return 1; +} + +static inline int +check_match(const STRUCT_ENTRY_MATCH *m, unsigned int *off) +{ + assert(m->u.match_size >= sizeof(STRUCT_ENTRY_MATCH)); + assert(ALIGN(m->u.match_size) == m->u.match_size); + + (*off) += m->u.match_size; + return 0; +} + +static inline int +check_entry(const STRUCT_ENTRY *e, unsigned int *i, unsigned int *off, + unsigned int user_offset, int *was_return, + struct xtc_handle *h) +{ + unsigned int toff; + STRUCT_STANDARD_TARGET *t; + + assert(e->target_offset >= sizeof(STRUCT_ENTRY)); + assert(e->next_offset >= e->target_offset + + sizeof(STRUCT_ENTRY_TARGET)); + toff = sizeof(STRUCT_ENTRY); + IPT_MATCH_ITERATE(e, check_match, &toff); + + assert(toff == e->target_offset); + + t = (STRUCT_STANDARD_TARGET *) + GET_TARGET((STRUCT_ENTRY *)e); + /* next_offset will have to be multiple of entry alignment. */ + assert(e->next_offset == ALIGN(e->next_offset)); + assert(e->target_offset == ALIGN(e->target_offset)); + assert(t->target.u.target_size == ALIGN(t->target.u.target_size)); + assert(!TC_IS_CHAIN(t->target.u.user.name, h)); + + if (strcmp(t->target.u.user.name, STANDARD_TARGET) == 0) { + assert(t->target.u.target_size + == ALIGN(sizeof(STRUCT_STANDARD_TARGET))); + + assert(t->verdict == -NF_DROP-1 + || t->verdict == -NF_ACCEPT-1 + || t->verdict == RETURN + || t->verdict < (int)h->entries->size); + + if (t->verdict >= 0) { + STRUCT_ENTRY *te = get_entry(h, t->verdict); + int idx; + + idx = iptcb_entry2index(h, te); + assert(strcmp(GET_TARGET(te)->u.user.name, + XT_ERROR_TARGET) + != 0); + assert(te != e); + + /* Prior node must be error node, or this node. */ + assert(t->verdict == iptcb_entry2offset(h, e)+e->next_offset + || strcmp(GET_TARGET(index2entry(h, idx-1)) + ->u.user.name, XT_ERROR_TARGET) + == 0); + } + + if (t->verdict == RETURN + && unconditional(&e->ip) + && e->target_offset == sizeof(*e)) + *was_return = 1; + else + *was_return = 0; + } else if (strcmp(t->target.u.user.name, XT_ERROR_TARGET) == 0) { + assert(t->target.u.target_size + == ALIGN(sizeof(struct ipt_error_target))); + + /* If this is in user area, previous must have been return */ + if (*off > user_offset) + assert(*was_return); + + *was_return = 0; + } + else *was_return = 0; + + if (*off == user_offset) + assert(strcmp(t->target.u.user.name, XT_ERROR_TARGET) == 0); + + (*off) += e->next_offset; + (*i)++; + return 0; +} +#endif diff --git a/libiptc/libip4tc.o b/libiptc/libip4tc.o new file mode 100644 index 0000000000000000000000000000000000000000..892dbb4f822a720e867a6b4c8d1bdd1b46fbc73b GIT binary patch literal 40600 zcmdUXe|(%(mG_gRK&U{%54A{vDYlTp_6G>q@^eBvWeWWeDAsEo^$TG_nv$2^Ymkp70W6sDm;5tc-MG^CyRRCjL#R+VM&I) z)4Wr?hG_cLXu5wgnu$!-JQiMG^VkTJ(Tb6c&-i)i)I>DhkV6K34U^GytXhaNz|ysv z1c|^ChNO0vG8i~oD;1DQCW0RdtYi{=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ys8>Kt&z9e+ffsMhty$MKf83Wey;6FvJgM_3a>Fw`Z}ARrR<~(!6beb^NEmX)bcLIbdWZ! zSg`$?wER9D4=f)mzkS|@L@E9Ee9BOa={!RHxsJ2tt^Fxaux^&D)dj(r)=xjI$1hl( mHVw8NAaCM!{>8g^fsP&2|5VVFD!=uAN^$Qq=H~wmmj6GG+)Z%+ literal 0 HcmV?d00001 diff --git a/libiptc/libiptc.c b/libiptc/libiptc.c new file mode 100644 index 0000000..ceeb017 --- /dev/null +++ b/libiptc/libiptc.c @@ -0,0 +1,2751 @@ +/* Library which manipulates firewall rules. Version $Revision$ */ + +/* Architecture of firewall rules is as follows: + * + * Chains go INPUT, FORWARD, OUTPUT then user chains. + * Each user chain starts with an ERROR node. + * Every chain ends with an unconditional jump: a RETURN for user chains, + * and a POLICY for built-ins. + */ + +/* (C) 1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See + * COPYING for details). + * (C) 2000-2004 by the Netfilter Core Team + * + * 2003-Jun-20: Harald Welte : + * - Reimplementation of chain cache to use offsets instead of entries + * 2003-Jun-23: Harald Welte : + * - performance optimization, sponsored by Astaro AG (http://www.astaro.com/) + * don't rebuild the chain cache after every operation, instead fix it + * up after a ruleset change. + * 2004-Aug-18: Harald Welte : + * - further performance work: total reimplementation of libiptc. + * - libiptc now has a real internal (linked-list) represntation of the + * ruleset and a parser/compiler from/to this internal representation + * - again sponsored by Astaro AG (http://www.astaro.com/) + * + * 2008-Jan+Jul: Jesper Dangaard Brouer + * - performance work: speedup chain list "name" searching. + * - performance work: speedup initial ruleset parsing. + * - sponsored by ComX Networks A/S (http://www.comx.dk/) + */ +#include +#include +#include +#include +#include +#include +#include + +#include "linux_list.h" + +//#define IPTC_DEBUG2 1 + +#ifdef IPTC_DEBUG2 +#include +#define DEBUGP(x, args...) fprintf(stderr, "%s: " x, __FUNCTION__, ## args) +#define DEBUGP_C(x, args...) fprintf(stderr, x, ## args) +#else +#define DEBUGP(x, args...) +#define DEBUGP_C(x, args...) +#endif + +#ifdef DEBUG +#define debug(x, args...) fprintf(stderr, x, ## args) +#else +#define debug(x, args...) +#endif + +static void *iptc_fn = NULL; + +static const char *hooknames[] = { + [HOOK_PRE_ROUTING] = "PREROUTING", + [HOOK_LOCAL_IN] = "INPUT", + [HOOK_FORWARD] = "FORWARD", + [HOOK_LOCAL_OUT] = "OUTPUT", + [HOOK_POST_ROUTING] = "POSTROUTING", +}; + +/* Convenience structures */ +struct chain_head; +struct rule_head; + +struct counter_map +{ + enum { + COUNTER_MAP_NOMAP, + COUNTER_MAP_NORMAL_MAP, + COUNTER_MAP_ZEROED, + COUNTER_MAP_SET + } maptype; + unsigned int mappos; +}; + +enum iptcc_rule_type { + IPTCC_R_STANDARD, /* standard target (ACCEPT, ...) */ + IPTCC_R_MODULE, /* extension module (SNAT, ...) */ + IPTCC_R_FALLTHROUGH, /* fallthrough rule */ + IPTCC_R_JUMP, /* jump to other chain */ +}; + +struct rule_head +{ + struct list_head list; + struct chain_head *chain; + struct counter_map counter_map; + + unsigned int index; /* index (needed for counter_map) */ + unsigned int offset; /* offset in rule blob */ + + enum iptcc_rule_type type; + struct chain_head *jump; /* jump target, if IPTCC_R_JUMP */ + + unsigned int size; /* size of entry data */ + STRUCT_ENTRY entry[0]; +}; + +struct chain_head +{ + struct list_head list; + char name[TABLE_MAXNAMELEN]; + unsigned int hooknum; /* hook number+1 if builtin */ + unsigned int references; /* how many jumps reference us */ + int verdict; /* verdict if builtin */ + + STRUCT_COUNTERS counters; /* per-chain counters */ + struct counter_map counter_map; + + unsigned int num_rules; /* number of rules in list */ + struct list_head rules; /* list of rules */ + + unsigned int index; /* index (needed for jump resolval) */ + unsigned int head_offset; /* offset in rule blob */ + unsigned int foot_index; /* index (needed for counter_map) */ + unsigned int foot_offset; /* offset in rule blob */ +}; + +struct xtc_handle { + int sockfd; + int changed; /* Have changes been made? */ + + struct list_head chains; + + struct chain_head *chain_iterator_cur; + struct rule_head *rule_iterator_cur; + + unsigned int num_chains; /* number of user defined chains */ + + struct chain_head **chain_index; /* array for fast chain list access*/ + unsigned int chain_index_sz;/* size of chain index array */ + + int sorted_offsets; /* if chains are received sorted from kernel, + * then the offsets are also sorted. Says if its + * possible to bsearch offsets using chain_index. + */ + + STRUCT_GETINFO info; + STRUCT_GET_ENTRIES *entries; +}; + +enum bsearch_type { + BSEARCH_NAME, /* Binary search after chain name */ + BSEARCH_OFFSET, /* Binary search based on offset */ +}; + +/* allocate a new chain head for the cache */ +static struct chain_head *iptcc_alloc_chain_head(const char *name, int hooknum) +{ + struct chain_head *c = malloc(sizeof(*c)); + if (!c) + return NULL; + memset(c, 0, sizeof(*c)); + + strncpy(c->name, name, TABLE_MAXNAMELEN - 1); + c->hooknum = hooknum; + INIT_LIST_HEAD(&c->rules); + + return c; +} + +/* allocate and initialize a new rule for the cache */ +static struct rule_head *iptcc_alloc_rule(struct chain_head *c, unsigned int size) +{ + struct rule_head *r = malloc(sizeof(*r)+size); + if (!r) + return NULL; + memset(r, 0, sizeof(*r)); + + r->chain = c; + r->size = size; + + return r; +} + +/* notify us that the ruleset has been modified by the user */ +static inline void +set_changed(struct xtc_handle *h) +{ + h->changed = 1; +} + +/********************************************************************** + * iptc blob utility functions (iptcb_*) + **********************************************************************/ + +static inline int +iptcb_get_number(const STRUCT_ENTRY *i, + const STRUCT_ENTRY *seek, + unsigned int *pos) +{ + if (i == seek) + return 1; + (*pos)++; + return 0; +} + +static inline int +iptcb_get_entry_n(STRUCT_ENTRY *i, + unsigned int number, + unsigned int *pos, + STRUCT_ENTRY **pe) +{ + if (*pos == number) { + *pe = i; + return 1; + } + (*pos)++; + return 0; +} + +static inline STRUCT_ENTRY * +iptcb_get_entry(struct xtc_handle *h, unsigned int offset) +{ + return (STRUCT_ENTRY *)((char *)h->entries->entrytable + offset); +} + +static unsigned int +iptcb_entry2index(struct xtc_handle *const h, const STRUCT_ENTRY *seek) +{ + unsigned int pos = 0; + + if (ENTRY_ITERATE(h->entries->entrytable, h->entries->size, + iptcb_get_number, seek, &pos) == 0) { + fprintf(stderr, "ERROR: offset %u not an entry!\n", + (unsigned int)((char *)seek - (char *)h->entries->entrytable)); + abort(); + } + return pos; +} + +static inline STRUCT_ENTRY * +iptcb_offset2entry(struct xtc_handle *h, unsigned int offset) +{ + return (STRUCT_ENTRY *) ((void *)h->entries->entrytable+offset); +} + + +static inline unsigned long +iptcb_entry2offset(struct xtc_handle *const h, const STRUCT_ENTRY *e) +{ + return (void *)e - (void *)h->entries->entrytable; +} + +static inline unsigned int +iptcb_offset2index(struct xtc_handle *const h, unsigned int offset) +{ + return iptcb_entry2index(h, iptcb_offset2entry(h, offset)); +} + +/* Returns 0 if not hook entry, else hooknumber + 1 */ +static inline unsigned int +iptcb_ent_is_hook_entry(STRUCT_ENTRY *e, struct xtc_handle *h) +{ + unsigned int i; + + for (i = 0; i < NUMHOOKS; i++) { + if ((h->info.valid_hooks & (1 << i)) + && iptcb_get_entry(h, h->info.hook_entry[i]) == e) + return i+1; + } + return 0; +} + + +/********************************************************************** + * Chain index (cache utility) functions + ********************************************************************** + * The chain index is an array with pointers into the chain list, with + * CHAIN_INDEX_BUCKET_LEN spacing. This facilitates the ability to + * speedup chain list searching, by find a more optimal starting + * points when searching the linked list. + * + * The starting point can be found fast by using a binary search of + * the chain index. Thus, reducing the previous search complexity of + * O(n) to O(log(n/k) + k) where k is CHAIN_INDEX_BUCKET_LEN. + * + * A nice property of the chain index, is that the "bucket" list + * length is max CHAIN_INDEX_BUCKET_LEN (when just build, inserts will + * change this). Oppose to hashing, where the "bucket" list length can + * vary a lot. + */ +#ifndef CHAIN_INDEX_BUCKET_LEN +#define CHAIN_INDEX_BUCKET_LEN 40 +#endif + +/* Another nice property of the chain index is that inserting/creating + * chains in chain list don't change the correctness of the chain + * index, it only causes longer lists in the buckets. + * + * To mitigate the performance penalty of longer bucket lists and the + * penalty of rebuilding, the chain index is rebuild only when + * CHAIN_INDEX_INSERT_MAX chains has been added. + */ +#ifndef CHAIN_INDEX_INSERT_MAX +#define CHAIN_INDEX_INSERT_MAX 355 +#endif + +static inline unsigned int iptcc_is_builtin(struct chain_head *c); + +/* Use binary search in the chain index array, to find a chain_head + * pointer closest to the place of the searched name element. + * + * Notes that, binary search (obviously) requires that the chain list + * is sorted by name. + * + * The not so obvious: The chain index array, is actually both sorted + * by name and offset, at the same time!. This is only true because, + * chain are stored sorted in the kernel (as we pushed it in sorted). + * + */ +static struct list_head * +__iptcc_bsearch_chain_index(const char *name, unsigned int offset, + unsigned int *idx, struct xtc_handle *handle, + enum bsearch_type type) +{ + unsigned int pos, end; + int res; + + struct list_head *list_pos; + list_pos=&handle->chains; + + /* Check for empty array, e.g. no user defined chains */ + if (handle->chain_index_sz == 0) { + debug("WARNING: handle->chain_index_sz == 0\n"); + return list_pos; + } + + /* Init */ + end = handle->chain_index_sz; + pos = end / 2; + + debug("bsearch Find chain:%s (pos:%d end:%d) (offset:%d)\n", + name, pos, end, offset); + + /* Loop */ + loop: + if (!handle->chain_index[pos]) { + fprintf(stderr, "ERROR: NULL pointer chain_index[%d]\n", pos); + return &handle->chains; /* Be safe, return orig start pos */ + } + + debug("bsearch Index[%d] name:%s ", + pos, handle->chain_index[pos]->name); + + /* Support for different compare functions */ + switch (type) { + case BSEARCH_NAME: + res = strcmp(name, handle->chain_index[pos]->name); + break; + case BSEARCH_OFFSET: + debug("head_offset:[%d] foot_offset:[%d] ", + handle->chain_index[pos]->head_offset, + handle->chain_index[pos]->foot_offset); + res = offset - handle->chain_index[pos]->head_offset; + break; + default: + fprintf(stderr, "ERROR: %d not a valid bsearch type\n", + type); + abort(); + break; + } + debug("res:%d ", res); + + + list_pos = &handle->chain_index[pos]->list; + *idx = pos; + + if (res == 0) { /* Found element, by direct hit */ + debug("[found] Direct hit pos:%d end:%d\n", pos, end); + return list_pos; + } else if (res < 0) { /* Too far, jump back */ + end = pos; + pos = pos / 2; + + /* Exit case: First element of array */ + if (end == 0) { + debug("[found] Reached first array elem (end%d)\n",end); + return list_pos; + } + debug("jump back to pos:%d (end:%d)\n", pos, end); + goto loop; + } else { /* res > 0; Not far enough, jump forward */ + + /* Exit case: Last element of array */ + if (pos == handle->chain_index_sz-1) { + debug("[found] Last array elem (end:%d)\n", end); + return list_pos; + } + + /* Exit case: Next index less, thus elem in this list section */ + switch (type) { + case BSEARCH_NAME: + res = strcmp(name, handle->chain_index[pos+1]->name); + break; + case BSEARCH_OFFSET: + res = offset - handle->chain_index[pos+1]->head_offset; + break; + } + + if (res < 0) { + debug("[found] closest list (end:%d)\n", end); + return list_pos; + } + + pos = (pos+end)/2; + debug("jump forward to pos:%d (end:%d)\n", pos, end); + goto loop; + } +} + +/* Wrapper for string chain name based bsearch */ +static struct list_head * +iptcc_bsearch_chain_index(const char *name, unsigned int *idx, + struct xtc_handle *handle) +{ + return __iptcc_bsearch_chain_index(name, 0, idx, handle, BSEARCH_NAME); +} + + +/* Wrapper for offset chain based bsearch */ +static struct list_head * +iptcc_bsearch_chain_offset(unsigned int offset, unsigned int *idx, + struct xtc_handle *handle) +{ + struct list_head *pos; + + /* If chains were not received sorted from kernel, then the + * offset bsearch is not possible. + */ + if (!handle->sorted_offsets) + pos = handle->chains.next; + else + pos = __iptcc_bsearch_chain_index(NULL, offset, idx, handle, + BSEARCH_OFFSET); + return pos; +} + + +#ifdef DEBUG +/* Trivial linear search of chain index. Function used for verifying + the output of bsearch function */ +static struct list_head * +iptcc_linearly_search_chain_index(const char *name, struct xtc_handle *handle) +{ + unsigned int i=0; + int res=0; + + struct list_head *list_pos; + list_pos = &handle->chains; + + if (handle->chain_index_sz) + list_pos = &handle->chain_index[0]->list; + + /* Linearly walk of chain index array */ + + for (i=0; i < handle->chain_index_sz; i++) { + if (handle->chain_index[i]) { + res = strcmp(handle->chain_index[i]->name, name); + if (res > 0) + break; // One step too far + list_pos = &handle->chain_index[i]->list; + if (res == 0) + break; // Direct hit + } + } + + return list_pos; +} +#endif + +static int iptcc_chain_index_alloc(struct xtc_handle *h) +{ + unsigned int list_length = CHAIN_INDEX_BUCKET_LEN; + unsigned int array_elems; + unsigned int array_mem; + + /* Allocate memory for the chain index array */ + array_elems = (h->num_chains / list_length) + + (h->num_chains % list_length ? 1 : 0); + array_mem = sizeof(h->chain_index) * array_elems; + + debug("Alloc Chain index, elems:%d mem:%d bytes\n", + array_elems, array_mem); + + h->chain_index = malloc(array_mem); + if (h->chain_index == NULL && array_mem > 0) { + h->chain_index_sz = 0; + return -ENOMEM; + } + memset(h->chain_index, 0, array_mem); + h->chain_index_sz = array_elems; + + return 1; +} + +static void iptcc_chain_index_free(struct xtc_handle *h) +{ + h->chain_index_sz = 0; + free(h->chain_index); +} + + +#ifdef DEBUG +static void iptcc_chain_index_dump(struct xtc_handle *h) +{ + unsigned int i = 0; + + /* Dump: contents of chain index array */ + for (i=0; i < h->chain_index_sz; i++) { + if (h->chain_index[i]) { + fprintf(stderr, "Chain index[%d].name: %s\n", + i, h->chain_index[i]->name); + } + } +} +#endif + +/* Build the chain index */ +static int iptcc_chain_index_build(struct xtc_handle *h) +{ + unsigned int list_length = CHAIN_INDEX_BUCKET_LEN; + unsigned int chains = 0; + unsigned int cindex = 0; + struct chain_head *c; + + /* Build up the chain index array here */ + debug("Building chain index\n"); + + debug("Number of user defined chains:%d bucket_sz:%d array_sz:%d\n", + h->num_chains, list_length, h->chain_index_sz); + + if (h->chain_index_sz == 0) + return 0; + + list_for_each_entry(c, &h->chains, list) { + + /* Issue: The index array needs to start after the + * builtin chains, as they are not sorted */ + if (!iptcc_is_builtin(c)) { + cindex=chains / list_length; + + /* Safe guard, break out on array limit, this + * is useful if chains are added and array is + * rebuild, without realloc of memory. */ + if (cindex >= h->chain_index_sz) + break; + + if ((chains % list_length)== 0) { + debug("\nIndex[%d] Chains:", cindex); + h->chain_index[cindex] = c; + } + chains++; + } + debug("%s, ", c->name); + } + debug("\n"); + + return 1; +} + +static int iptcc_chain_index_rebuild(struct xtc_handle *h) +{ + debug("REBUILD chain index array\n"); + iptcc_chain_index_free(h); + if ((iptcc_chain_index_alloc(h)) < 0) + return -ENOMEM; + iptcc_chain_index_build(h); + return 1; +} + +/* Delete chain (pointer) from index array. Removing an element from + * the chain list only affects the chain index array, if the chain + * index points-to/uses that list pointer. + * + * There are different strategies, the simple and safe is to rebuild + * the chain index every time. The more advanced is to update the + * array index to point to the next element, but that requires some + * house keeping and boundary checks. The advanced is implemented, as + * the simple approach behaves badly when all chains are deleted + * because list_for_each processing will always hit the first chain + * index, thus causing a rebuild for every chain. + */ +static int iptcc_chain_index_delete_chain(struct chain_head *c, struct xtc_handle *h) +{ + struct list_head *index_ptr, *next; + struct chain_head *c2; + unsigned int idx, idx2; + + index_ptr = iptcc_bsearch_chain_index(c->name, &idx, h); + + debug("Del chain[%s] c->list:%p index_ptr:%p\n", + c->name, &c->list, index_ptr); + + /* Save the next pointer */ + next = c->list.next; + list_del(&c->list); + + if (index_ptr == &c->list) { /* Chain used as index ptr */ + + /* See if its possible to avoid a rebuild, by shifting + * to next pointer. Its possible if the next pointer + * is located in the same index bucket. + */ + c2 = list_entry(next, struct chain_head, list); + iptcc_bsearch_chain_index(c2->name, &idx2, h); + if (idx != idx2) { + /* Rebuild needed */ + return iptcc_chain_index_rebuild(h); + } else { + /* Avoiding rebuild */ + debug("Update cindex[%d] with next ptr name:[%s]\n", + idx, c2->name); + h->chain_index[idx]=c2; + return 0; + } + } + return 0; +} + + +/********************************************************************** + * iptc cache utility functions (iptcc_*) + **********************************************************************/ + +/* Is the given chain builtin (1) or user-defined (0) */ +static inline unsigned int iptcc_is_builtin(struct chain_head *c) +{ + return (c->hooknum ? 1 : 0); +} + +/* Get a specific rule within a chain */ +static struct rule_head *iptcc_get_rule_num(struct chain_head *c, + unsigned int rulenum) +{ + struct rule_head *r; + unsigned int num = 0; + + list_for_each_entry(r, &c->rules, list) { + num++; + if (num == rulenum) + return r; + } + return NULL; +} + +/* Get a specific rule within a chain backwards */ +static struct rule_head *iptcc_get_rule_num_reverse(struct chain_head *c, + unsigned int rulenum) +{ + struct rule_head *r; + unsigned int num = 0; + + list_for_each_entry_reverse(r, &c->rules, list) { + num++; + if (num == rulenum) + return r; + } + return NULL; +} + +/* Returns chain head if found, otherwise NULL. */ +static struct chain_head * +iptcc_find_chain_by_offset(struct xtc_handle *handle, unsigned int offset) +{ + struct list_head *pos; + struct list_head *list_start_pos; + unsigned int i; + + if (list_empty(&handle->chains)) + return NULL; + + /* Find a smart place to start the search */ + list_start_pos = iptcc_bsearch_chain_offset(offset, &i, handle); + + /* Note that iptcc_bsearch_chain_offset() skips builtin + * chains, but this function is only used for finding jump + * targets, and a buildin chain is not a valid jump target */ + + debug("Offset:[%u] starting search at index:[%u]\n", offset, i); +// list_for_each(pos, &handle->chains) { + list_for_each(pos, list_start_pos->prev) { + struct chain_head *c = list_entry(pos, struct chain_head, list); + debug("."); + if (offset >= c->head_offset && offset <= c->foot_offset) { + debug("Offset search found chain:[%s]\n", c->name); + return c; + } + } + + return NULL; +} + +/* Returns chain head if found, otherwise NULL. */ +static struct chain_head * +iptcc_find_label(const char *name, struct xtc_handle *handle) +{ + struct list_head *pos; + struct list_head *list_start_pos; + unsigned int i=0; + int res; + + if (list_empty(&handle->chains)) + return NULL; + + /* First look at builtin chains */ + list_for_each(pos, &handle->chains) { + struct chain_head *c = list_entry(pos, struct chain_head, list); + if (!iptcc_is_builtin(c)) + break; + if (!strcmp(c->name, name)) + return c; + } + + /* Find a smart place to start the search via chain index */ + //list_start_pos = iptcc_linearly_search_chain_index(name, handle); + list_start_pos = iptcc_bsearch_chain_index(name, &i, handle); + + /* Handel if bsearch bails out early */ + if (list_start_pos == &handle->chains) { + list_start_pos = pos; + } +#ifdef DEBUG + else { + /* Verify result of bsearch against linearly index search */ + struct list_head *test_pos; + struct chain_head *test_c, *tmp_c; + test_pos = iptcc_linearly_search_chain_index(name, handle); + if (list_start_pos != test_pos) { + debug("BUG in chain_index search\n"); + test_c=list_entry(test_pos, struct chain_head,list); + tmp_c =list_entry(list_start_pos,struct chain_head,list); + debug("Verify search found:\n"); + debug(" Chain:%s\n", test_c->name); + debug("BSearch found:\n"); + debug(" Chain:%s\n", tmp_c->name); + exit(42); + } + } +#endif + + /* Initial/special case, no user defined chains */ + if (handle->num_chains == 0) + return NULL; + + /* Start searching through the chain list */ + list_for_each(pos, list_start_pos->prev) { + struct chain_head *c = list_entry(pos, struct chain_head, list); + res = strcmp(c->name, name); + debug("List search name:%s == %s res:%d\n", name, c->name, res); + if (res==0) + return c; + + /* We can stop earlier as we know list is sorted */ + if (res>0 && !iptcc_is_builtin(c)) { /* Walked too far*/ + debug(" Not in list, walked too far, sorted list\n"); + return NULL; + } + + /* Stop on wrap around, if list head is reached */ + if (pos == &handle->chains) { + debug("Stop, list head reached\n"); + return NULL; + } + } + + debug("List search NOT found name:%s\n", name); + return NULL; +} + +/* called when rule is to be removed from cache */ +static void iptcc_delete_rule(struct rule_head *r) +{ + DEBUGP("deleting rule %p (offset %u)\n", r, r->offset); + /* clean up reference count of called chain */ + if (r->type == IPTCC_R_JUMP + && r->jump) + r->jump->references--; + + list_del(&r->list); + free(r); +} + + +/********************************************************************** + * RULESET PARSER (blob -> cache) + **********************************************************************/ + +/* Delete policy rule of previous chain, since cache doesn't contain + * chain policy rules. + * WARNING: This function has ugly design and relies on a lot of context, only + * to be called from specific places within the parser */ +static int __iptcc_p_del_policy(struct xtc_handle *h, unsigned int num) +{ + const unsigned char *data; + + if (h->chain_iterator_cur) { + /* policy rule is last rule */ + struct rule_head *pr = (struct rule_head *) + h->chain_iterator_cur->rules.prev; + + /* save verdict */ + data = GET_TARGET(pr->entry)->data; + h->chain_iterator_cur->verdict = *(const int *)data; + + /* save counter and counter_map information */ + h->chain_iterator_cur->counter_map.maptype = + COUNTER_MAP_ZEROED; + h->chain_iterator_cur->counter_map.mappos = num-1; + memcpy(&h->chain_iterator_cur->counters, &pr->entry->counters, + sizeof(h->chain_iterator_cur->counters)); + + /* foot_offset points to verdict rule */ + h->chain_iterator_cur->foot_index = num; + h->chain_iterator_cur->foot_offset = pr->offset; + + /* delete rule from cache */ + iptcc_delete_rule(pr); + h->chain_iterator_cur->num_rules--; + + return 1; + } + return 0; +} + +/* alphabetically insert a chain into the list */ +static void iptc_insert_chain(struct xtc_handle *h, struct chain_head *c) +{ + struct chain_head *tmp; + struct list_head *list_start_pos; + unsigned int i=1; + + /* Find a smart place to start the insert search */ + list_start_pos = iptcc_bsearch_chain_index(c->name, &i, h); + + /* Handle the case, where chain.name is smaller than index[0] */ + if (i==0 && strcmp(c->name, h->chain_index[0]->name) <= 0) { + h->chain_index[0] = c; /* Update chain index head */ + list_start_pos = h->chains.next; + debug("Update chain_index[0] with %s\n", c->name); + } + + /* Handel if bsearch bails out early */ + if (list_start_pos == &h->chains) { + list_start_pos = h->chains.next; + } + + /* sort only user defined chains */ + if (!c->hooknum) { + list_for_each_entry(tmp, list_start_pos->prev, list) { + if (!tmp->hooknum && strcmp(c->name, tmp->name) <= 0) { + list_add(&c->list, tmp->list.prev); + return; + } + + /* Stop if list head is reached */ + if (&tmp->list == &h->chains) { + debug("Insert, list head reached add to tail\n"); + break; + } + } + } + + /* survived till end of list: add at tail */ + list_add_tail(&c->list, &h->chains); +} + +/* Another ugly helper function split out of cache_add_entry to make it less + * spaghetti code */ +static void __iptcc_p_add_chain(struct xtc_handle *h, struct chain_head *c, + unsigned int offset, unsigned int *num) +{ + struct list_head *tail = h->chains.prev; + struct chain_head *ctail; + + __iptcc_p_del_policy(h, *num); + + c->head_offset = offset; + c->index = *num; + + /* Chains from kernel are already sorted, as they are inserted + * sorted. But there exists an issue when shifting to 1.4.0 + * from an older version, as old versions allow last created + * chain to be unsorted. + */ + if (iptcc_is_builtin(c)) /* Only user defined chains are sorted*/ + list_add_tail(&c->list, &h->chains); + else { + ctail = list_entry(tail, struct chain_head, list); + + if (strcmp(c->name, ctail->name) > 0 || + iptcc_is_builtin(ctail)) + list_add_tail(&c->list, &h->chains);/* Already sorted*/ + else { + iptc_insert_chain(h, c);/* Was not sorted */ + + /* Notice, if chains were not received sorted + * from kernel, then an offset bsearch is no + * longer valid. + */ + h->sorted_offsets = 0; + + debug("NOTICE: chain:[%s] was NOT sorted(ctail:%s)\n", + c->name, ctail->name); + } + } + + h->chain_iterator_cur = c; +} + +/* main parser function: add an entry from the blob to the cache */ +static int cache_add_entry(STRUCT_ENTRY *e, + struct xtc_handle *h, + STRUCT_ENTRY **prev, + unsigned int *num) +{ + unsigned int builtin; + unsigned int offset = (char *)e - (char *)h->entries->entrytable; + + DEBUGP("entering..."); + + /* Last entry ("policy rule"). End it.*/ + if (iptcb_entry2offset(h,e) + e->next_offset == h->entries->size) { + /* This is the ERROR node at the end of the chain */ + DEBUGP_C("%u:%u: end of table:\n", *num, offset); + + __iptcc_p_del_policy(h, *num); + + h->chain_iterator_cur = NULL; + goto out_inc; + } + + /* We know this is the start of a new chain if it's an ERROR + * target, or a hook entry point */ + + if (strcmp(GET_TARGET(e)->u.user.name, ERROR_TARGET) == 0) { + struct chain_head *c = + iptcc_alloc_chain_head((const char *)GET_TARGET(e)->data, 0); + DEBUGP_C("%u:%u:new userdefined chain %s: %p\n", *num, offset, + (char *)c->name, c); + if (!c) { + errno = -ENOMEM; + return -1; + } + h->num_chains++; /* New user defined chain */ + + __iptcc_p_add_chain(h, c, offset, num); + + } else if ((builtin = iptcb_ent_is_hook_entry(e, h)) != 0) { + struct chain_head *c = + iptcc_alloc_chain_head((char *)hooknames[builtin-1], + builtin); + DEBUGP_C("%u:%u new builtin chain: %p (rules=%p)\n", + *num, offset, c, &c->rules); + if (!c) { + errno = -ENOMEM; + return -1; + } + + c->hooknum = builtin; + + __iptcc_p_add_chain(h, c, offset, num); + + /* FIXME: this is ugly. */ + goto new_rule; + } else { + /* has to be normal rule */ + struct rule_head *r; +new_rule: + + if (!(r = iptcc_alloc_rule(h->chain_iterator_cur, + e->next_offset))) { + errno = ENOMEM; + return -1; + } + DEBUGP_C("%u:%u normal rule: %p: ", *num, offset, r); + + r->index = *num; + r->offset = offset; + memcpy(r->entry, e, e->next_offset); + r->counter_map.maptype = COUNTER_MAP_NORMAL_MAP; + r->counter_map.mappos = r->index; + + /* handling of jumps, etc. */ + if (!strcmp(GET_TARGET(e)->u.user.name, STANDARD_TARGET)) { + STRUCT_STANDARD_TARGET *t; + + t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); + if (t->target.u.target_size + != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) { + errno = EINVAL; + free(r); + return -1; + } + + if (t->verdict < 0) { + DEBUGP_C("standard, verdict=%d\n", t->verdict); + r->type = IPTCC_R_STANDARD; + } else if (t->verdict == r->offset+e->next_offset) { + DEBUGP_C("fallthrough\n"); + r->type = IPTCC_R_FALLTHROUGH; + } else { + DEBUGP_C("jump, target=%u\n", t->verdict); + r->type = IPTCC_R_JUMP; + /* Jump target fixup has to be deferred + * until second pass, since we migh not + * yet have parsed the target */ + } + } else { + DEBUGP_C("module, target=%s\n", GET_TARGET(e)->u.user.name); + r->type = IPTCC_R_MODULE; + } + + list_add_tail(&r->list, &h->chain_iterator_cur->rules); + h->chain_iterator_cur->num_rules++; + } +out_inc: + (*num)++; + return 0; +} + + +/* parse an iptables blob into it's pieces */ +static int parse_table(struct xtc_handle *h) +{ + STRUCT_ENTRY *prev; + unsigned int num = 0; + struct chain_head *c; + + /* Assume that chains offsets are sorted, this verified during + parsing of ruleset (in __iptcc_p_add_chain())*/ + h->sorted_offsets = 1; + + /* First pass: over ruleset blob */ + ENTRY_ITERATE(h->entries->entrytable, h->entries->size, + cache_add_entry, h, &prev, &num); + + /* Build the chain index, used for chain list search speedup */ + if ((iptcc_chain_index_alloc(h)) < 0) + return -ENOMEM; + iptcc_chain_index_build(h); + + /* Second pass: fixup parsed data from first pass */ + list_for_each_entry(c, &h->chains, list) { + struct rule_head *r; + list_for_each_entry(r, &c->rules, list) { + struct chain_head *lc; + STRUCT_STANDARD_TARGET *t; + + if (r->type != IPTCC_R_JUMP) + continue; + + t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry); + lc = iptcc_find_chain_by_offset(h, t->verdict); + if (!lc) + return -1; + r->jump = lc; + lc->references++; + } + } + + return 1; +} + + +/********************************************************************** + * RULESET COMPILATION (cache -> blob) + **********************************************************************/ + +/* Convenience structures */ +struct iptcb_chain_start{ + STRUCT_ENTRY e; + struct xt_error_target name; +}; +#define IPTCB_CHAIN_START_SIZE (sizeof(STRUCT_ENTRY) + \ + ALIGN(sizeof(struct xt_error_target))) + +struct iptcb_chain_foot { + STRUCT_ENTRY e; + STRUCT_STANDARD_TARGET target; +}; +#define IPTCB_CHAIN_FOOT_SIZE (sizeof(STRUCT_ENTRY) + \ + ALIGN(sizeof(STRUCT_STANDARD_TARGET))) + +struct iptcb_chain_error { + STRUCT_ENTRY entry; + struct xt_error_target target; +}; +#define IPTCB_CHAIN_ERROR_SIZE (sizeof(STRUCT_ENTRY) + \ + ALIGN(sizeof(struct xt_error_target))) + + + +/* compile rule from cache into blob */ +static inline int iptcc_compile_rule (struct xtc_handle *h, STRUCT_REPLACE *repl, struct rule_head *r) +{ + /* handle jumps */ + if (r->type == IPTCC_R_JUMP) { + STRUCT_STANDARD_TARGET *t; + t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry); + /* memset for memcmp convenience on delete/replace */ + memset(t->target.u.user.name, 0, XT_EXTENSION_MAXNAMELEN); + strcpy(t->target.u.user.name, STANDARD_TARGET); + t->target.u.user.revision = 0; + /* Jumps can only happen to builtin chains, so we + * can safely assume that they always have a header */ + t->verdict = r->jump->head_offset + IPTCB_CHAIN_START_SIZE; + } else if (r->type == IPTCC_R_FALLTHROUGH) { + STRUCT_STANDARD_TARGET *t; + t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry); + t->verdict = r->offset + r->size; + } + + /* copy entry from cache to blob */ + memcpy((char *)repl->entries+r->offset, r->entry, r->size); + + return 1; +} + +/* compile chain from cache into blob */ +static int iptcc_compile_chain(struct xtc_handle *h, STRUCT_REPLACE *repl, struct chain_head *c) +{ + int ret; + struct rule_head *r; + struct iptcb_chain_start *head; + struct iptcb_chain_foot *foot; + + /* only user-defined chains have heaer */ + if (!iptcc_is_builtin(c)) { + /* put chain header in place */ + head = (void *)repl->entries + c->head_offset; + head->e.target_offset = sizeof(STRUCT_ENTRY); + head->e.next_offset = IPTCB_CHAIN_START_SIZE; + strcpy(head->name.target.u.user.name, ERROR_TARGET); + head->name.target.u.target_size = + ALIGN(sizeof(struct xt_error_target)); + strncpy(head->name.errorname, c->name, XT_FUNCTION_MAXNAMELEN); + head->name.errorname[XT_FUNCTION_MAXNAMELEN - 1] = '\0'; + } else { + repl->hook_entry[c->hooknum-1] = c->head_offset; + repl->underflow[c->hooknum-1] = c->foot_offset; + } + + /* iterate over rules */ + list_for_each_entry(r, &c->rules, list) { + ret = iptcc_compile_rule(h, repl, r); + if (ret < 0) + return ret; + } + + /* put chain footer in place */ + foot = (void *)repl->entries + c->foot_offset; + foot->e.target_offset = sizeof(STRUCT_ENTRY); + foot->e.next_offset = IPTCB_CHAIN_FOOT_SIZE; + strcpy(foot->target.target.u.user.name, STANDARD_TARGET); + foot->target.target.u.target_size = + ALIGN(sizeof(STRUCT_STANDARD_TARGET)); + /* builtin targets have verdict, others return */ + if (iptcc_is_builtin(c)) + foot->target.verdict = c->verdict; + else + foot->target.verdict = RETURN; + /* set policy-counters */ + foot->e.counters = c->counters; + + return 0; +} + +/* calculate offset and number for every rule in the cache */ +static int iptcc_compile_chain_offsets(struct xtc_handle *h, struct chain_head *c, + unsigned int *offset, unsigned int *num) +{ + struct rule_head *r; + + c->head_offset = *offset; + DEBUGP("%s: chain_head %u, offset=%u\n", c->name, *num, *offset); + + if (!iptcc_is_builtin(c)) { + /* Chain has header */ + *offset += sizeof(STRUCT_ENTRY) + + ALIGN(sizeof(struct xt_error_target)); + (*num)++; + } + + list_for_each_entry(r, &c->rules, list) { + DEBUGP("rule %u, offset=%u, index=%u\n", *num, *offset, *num); + r->offset = *offset; + r->index = *num; + *offset += r->size; + (*num)++; + } + + DEBUGP("%s; chain_foot %u, offset=%u, index=%u\n", c->name, *num, + *offset, *num); + c->foot_offset = *offset; + c->foot_index = *num; + *offset += sizeof(STRUCT_ENTRY) + + ALIGN(sizeof(STRUCT_STANDARD_TARGET)); + (*num)++; + + return 1; +} + +/* put the pieces back together again */ +static int iptcc_compile_table_prep(struct xtc_handle *h, unsigned int *size) +{ + struct chain_head *c; + unsigned int offset = 0, num = 0; + int ret = 0; + + /* First pass: calculate offset for every rule */ + list_for_each_entry(c, &h->chains, list) { + ret = iptcc_compile_chain_offsets(h, c, &offset, &num); + if (ret < 0) + return ret; + } + + /* Append one error rule at end of chain */ + num++; + offset += sizeof(STRUCT_ENTRY) + + ALIGN(sizeof(struct xt_error_target)); + + /* ruleset size is now in offset */ + *size = offset; + return num; +} + +static int iptcc_compile_table(struct xtc_handle *h, STRUCT_REPLACE *repl) +{ + struct chain_head *c; + struct iptcb_chain_error *error; + + /* Second pass: copy from cache to offsets, fill in jumps */ + list_for_each_entry(c, &h->chains, list) { + int ret = iptcc_compile_chain(h, repl, c); + if (ret < 0) + return ret; + } + + /* Append error rule at end of chain */ + error = (void *)repl->entries + repl->size - IPTCB_CHAIN_ERROR_SIZE; + error->entry.target_offset = sizeof(STRUCT_ENTRY); + error->entry.next_offset = IPTCB_CHAIN_ERROR_SIZE; + error->target.target.u.user.target_size = + ALIGN(sizeof(struct xt_error_target)); + strcpy((char *)&error->target.target.u.user.name, ERROR_TARGET); + strcpy((char *)&error->target.errorname, "ERROR"); + + return 1; +} + +/********************************************************************** + * EXTERNAL API (operates on cache only) + **********************************************************************/ + +/* Allocate handle of given size */ +static struct xtc_handle * +alloc_handle(STRUCT_GETINFO *infop) +{ + struct xtc_handle *h; + + h = malloc(sizeof(*h)); + if (!h) { + errno = ENOMEM; + return NULL; + } + memset(h, 0, sizeof(*h)); + INIT_LIST_HEAD(&h->chains); + strcpy(h->info.name, infop->name); + + h->entries = malloc(sizeof(STRUCT_GET_ENTRIES) + infop->size); + if (!h->entries) + goto out_free_handle; + + strcpy(h->entries->name, infop->name); + h->entries->size = infop->size; + + return h; + +out_free_handle: + free(h); + + return NULL; +} + + +struct xtc_handle * +TC_INIT(const char *tablename) +{ + struct xtc_handle *h; + STRUCT_GETINFO info; + unsigned int tmp; + socklen_t s; + int sockfd; + +retry: + iptc_fn = TC_INIT; + + if (strlen(tablename) >= TABLE_MAXNAMELEN) { + errno = EINVAL; + return NULL; + } + + sockfd = socket(TC_AF, SOCK_RAW, IPPROTO_RAW); + if (sockfd < 0) + return NULL; + + if (fcntl(sockfd, F_SETFD, FD_CLOEXEC) == -1) { + fprintf(stderr, "Could not set close on exec: %s\n", + strerror(errno)); + abort(); + } + + s = sizeof(info); + + strcpy(info.name, tablename); + if (getsockopt(sockfd, TC_IPPROTO, SO_GET_INFO, &info, &s) < 0) { + close(sockfd); + return NULL; + } + + DEBUGP("valid_hooks=0x%08x, num_entries=%u, size=%u\n", + info.valid_hooks, info.num_entries, info.size); + + h = alloc_handle(&info); + if (h == NULL) { + close(sockfd); + return NULL; + } + + /* Initialize current state */ + h->sockfd = sockfd; + h->info = info; + + h->entries->size = h->info.size; + + tmp = sizeof(STRUCT_GET_ENTRIES) + h->info.size; + + if (getsockopt(h->sockfd, TC_IPPROTO, SO_GET_ENTRIES, h->entries, + &tmp) < 0) + goto error; + +#ifdef IPTC_DEBUG2 + { + int fd = open("/tmp/libiptc-so_get_entries.blob", + O_CREAT|O_WRONLY, 0644); + if (fd >= 0) { + write(fd, h->entries, tmp); + close(fd); + } + } +#endif + + if (parse_table(h) < 0) + goto error; + + return h; +error: + TC_FREE(h); + /* A different process changed the ruleset size, retry */ + if (errno == EAGAIN) + goto retry; + return NULL; +} + +void +TC_FREE(struct xtc_handle *h) +{ + struct chain_head *c, *tmp; + + iptc_fn = TC_FREE; + close(h->sockfd); + + list_for_each_entry_safe(c, tmp, &h->chains, list) { + struct rule_head *r, *rtmp; + + list_for_each_entry_safe(r, rtmp, &c->rules, list) { + free(r); + } + + free(c); + } + + iptcc_chain_index_free(h); + + free(h->entries); + free(h); +} + +static inline int +print_match(const STRUCT_ENTRY_MATCH *m) +{ + printf("Match name: `%s'\n", m->u.user.name); + return 0; +} + +static int dump_entry(STRUCT_ENTRY *e, struct xtc_handle *const handle); + +void +TC_DUMP_ENTRIES(struct xtc_handle *const handle) +{ + iptc_fn = TC_DUMP_ENTRIES; + + printf("libiptc v%s. %u bytes.\n", + XTABLES_VERSION, handle->entries->size); + printf("Table `%s'\n", handle->info.name); + printf("Hooks: pre/in/fwd/out/post = %x/%x/%x/%x/%x\n", + handle->info.hook_entry[HOOK_PRE_ROUTING], + handle->info.hook_entry[HOOK_LOCAL_IN], + handle->info.hook_entry[HOOK_FORWARD], + handle->info.hook_entry[HOOK_LOCAL_OUT], + handle->info.hook_entry[HOOK_POST_ROUTING]); + printf("Underflows: pre/in/fwd/out/post = %x/%x/%x/%x/%x\n", + handle->info.underflow[HOOK_PRE_ROUTING], + handle->info.underflow[HOOK_LOCAL_IN], + handle->info.underflow[HOOK_FORWARD], + handle->info.underflow[HOOK_LOCAL_OUT], + handle->info.underflow[HOOK_POST_ROUTING]); + + ENTRY_ITERATE(handle->entries->entrytable, handle->entries->size, + dump_entry, handle); +} + +/* Does this chain exist? */ +int TC_IS_CHAIN(const char *chain, struct xtc_handle *const handle) +{ + iptc_fn = TC_IS_CHAIN; + return iptcc_find_label(chain, handle) != NULL; +} + +static void iptcc_chain_iterator_advance(struct xtc_handle *handle) +{ + struct chain_head *c = handle->chain_iterator_cur; + + if (c->list.next == &handle->chains) + handle->chain_iterator_cur = NULL; + else + handle->chain_iterator_cur = + list_entry(c->list.next, struct chain_head, list); +} + +/* Iterator functions to run through the chains. */ +const char * +TC_FIRST_CHAIN(struct xtc_handle *handle) +{ + struct chain_head *c = list_entry(handle->chains.next, + struct chain_head, list); + + iptc_fn = TC_FIRST_CHAIN; + + + if (list_empty(&handle->chains)) { + DEBUGP(": no chains\n"); + return NULL; + } + + handle->chain_iterator_cur = c; + iptcc_chain_iterator_advance(handle); + + DEBUGP(": returning `%s'\n", c->name); + return c->name; +} + +/* Iterator functions to run through the chains. Returns NULL at end. */ +const char * +TC_NEXT_CHAIN(struct xtc_handle *handle) +{ + struct chain_head *c = handle->chain_iterator_cur; + + iptc_fn = TC_NEXT_CHAIN; + + if (!c) { + DEBUGP(": no more chains\n"); + return NULL; + } + + iptcc_chain_iterator_advance(handle); + + DEBUGP(": returning `%s'\n", c->name); + return c->name; +} + +/* Get first rule in the given chain: NULL for empty chain. */ +const STRUCT_ENTRY * +TC_FIRST_RULE(const char *chain, struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r; + + iptc_fn = TC_FIRST_RULE; + + DEBUGP("first rule(%s): ", chain); + + c = iptcc_find_label(chain, handle); + if (!c) { + errno = ENOENT; + return NULL; + } + + /* Empty chain: single return/policy rule */ + if (list_empty(&c->rules)) { + DEBUGP_C("no rules, returning NULL\n"); + return NULL; + } + + r = list_entry(c->rules.next, struct rule_head, list); + handle->rule_iterator_cur = r; + DEBUGP_C("%p\n", r); + + return r->entry; +} + +/* Returns NULL when rules run out. */ +const STRUCT_ENTRY * +TC_NEXT_RULE(const STRUCT_ENTRY *prev, struct xtc_handle *handle) +{ + struct rule_head *r; + + iptc_fn = TC_NEXT_RULE; + DEBUGP("rule_iterator_cur=%p...", handle->rule_iterator_cur); + + if (handle->rule_iterator_cur == NULL) { + DEBUGP_C("returning NULL\n"); + return NULL; + } + + r = list_entry(handle->rule_iterator_cur->list.next, + struct rule_head, list); + + iptc_fn = TC_NEXT_RULE; + + DEBUGP_C("next=%p, head=%p...", &r->list, + &handle->rule_iterator_cur->chain->rules); + + if (&r->list == &handle->rule_iterator_cur->chain->rules) { + handle->rule_iterator_cur = NULL; + DEBUGP_C("finished, returning NULL\n"); + return NULL; + } + + handle->rule_iterator_cur = r; + + /* NOTE: prev is without any influence ! */ + DEBUGP_C("returning rule %p\n", r); + return r->entry; +} + +/* Returns a pointer to the target name of this position. */ +static const char *standard_target_map(int verdict) +{ + switch (verdict) { + case RETURN: + return LABEL_RETURN; + break; + case -NF_ACCEPT-1: + return LABEL_ACCEPT; + break; + case -NF_DROP-1: + return LABEL_DROP; + break; + case -NF_QUEUE-1: + return LABEL_QUEUE; + break; + default: + fprintf(stderr, "ERROR: %d not a valid target)\n", + verdict); + abort(); + break; + } + /* not reached */ + return NULL; +} + +/* Returns a pointer to the target name of this position. */ +const char *TC_GET_TARGET(const STRUCT_ENTRY *ce, + struct xtc_handle *handle) +{ + STRUCT_ENTRY *e = (STRUCT_ENTRY *)ce; + struct rule_head *r = container_of(e, struct rule_head, entry[0]); + const unsigned char *data; + + iptc_fn = TC_GET_TARGET; + + switch(r->type) { + int spos; + case IPTCC_R_FALLTHROUGH: + return ""; + break; + case IPTCC_R_JUMP: + DEBUGP("r=%p, jump=%p, name=`%s'\n", r, r->jump, r->jump->name); + return r->jump->name; + break; + case IPTCC_R_STANDARD: + data = GET_TARGET(e)->data; + spos = *(const int *)data; + DEBUGP("r=%p, spos=%d'\n", r, spos); + return standard_target_map(spos); + break; + case IPTCC_R_MODULE: + return GET_TARGET(e)->u.user.name; + break; + } + return NULL; +} +/* Is this a built-in chain? Actually returns hook + 1. */ +int +TC_BUILTIN(const char *chain, struct xtc_handle *const handle) +{ + struct chain_head *c; + + iptc_fn = TC_BUILTIN; + + c = iptcc_find_label(chain, handle); + if (!c) { + errno = ENOENT; + return 0; + } + + return iptcc_is_builtin(c); +} + +/* Get the policy of a given built-in chain */ +const char * +TC_GET_POLICY(const char *chain, + STRUCT_COUNTERS *counters, + struct xtc_handle *handle) +{ + struct chain_head *c; + + iptc_fn = TC_GET_POLICY; + + DEBUGP("called for chain %s\n", chain); + + c = iptcc_find_label(chain, handle); + if (!c) { + errno = ENOENT; + return NULL; + } + + if (!iptcc_is_builtin(c)) + return NULL; + + *counters = c->counters; + + return standard_target_map(c->verdict); +} + +static int +iptcc_standard_map(struct rule_head *r, int verdict) +{ + STRUCT_ENTRY *e = r->entry; + STRUCT_STANDARD_TARGET *t; + + t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e); + + if (t->target.u.target_size + != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) { + errno = EINVAL; + return 0; + } + /* memset for memcmp convenience on delete/replace */ + memset(t->target.u.user.name, 0, XT_EXTENSION_MAXNAMELEN); + strcpy(t->target.u.user.name, STANDARD_TARGET); + t->target.u.user.revision = 0; + t->verdict = verdict; + + r->type = IPTCC_R_STANDARD; + + return 1; +} + +static int +iptcc_map_target(struct xtc_handle *const handle, + struct rule_head *r, + bool dry_run) +{ + STRUCT_ENTRY *e = r->entry; + STRUCT_ENTRY_TARGET *t = GET_TARGET(e); + + /* Maybe it's empty (=> fall through) */ + if (strcmp(t->u.user.name, "") == 0) { + r->type = IPTCC_R_FALLTHROUGH; + return 1; + } + /* Maybe it's a standard target name... */ + else if (strcmp(t->u.user.name, LABEL_ACCEPT) == 0) + return iptcc_standard_map(r, -NF_ACCEPT - 1); + else if (strcmp(t->u.user.name, LABEL_DROP) == 0) + return iptcc_standard_map(r, -NF_DROP - 1); + else if (strcmp(t->u.user.name, LABEL_QUEUE) == 0) + return iptcc_standard_map(r, -NF_QUEUE - 1); + else if (strcmp(t->u.user.name, LABEL_RETURN) == 0) + return iptcc_standard_map(r, RETURN); + else if (TC_BUILTIN(t->u.user.name, handle)) { + /* Can't jump to builtins. */ + errno = EINVAL; + return 0; + } else { + /* Maybe it's an existing chain name. */ + struct chain_head *c; + DEBUGP("trying to find chain `%s': ", t->u.user.name); + + c = iptcc_find_label(t->u.user.name, handle); + if (c) { + DEBUGP_C("found!\n"); + r->type = IPTCC_R_JUMP; + r->jump = c; + c->references++; + return 1; + } + DEBUGP_C("not found :(\n"); + } + + /* Must be a module? If not, kernel will reject... */ + /* memset to all 0 for your memcmp convenience: don't clear version */ + memset(t->u.user.name + strlen(t->u.user.name), + 0, + FUNCTION_MAXNAMELEN - 1 - strlen(t->u.user.name)); + r->type = IPTCC_R_MODULE; + if (!dry_run) + set_changed(handle); + return 1; +} + +/* Insert the entry `fw' in chain `chain' into position `rulenum'. */ +int +TC_INSERT_ENTRY(const IPT_CHAINLABEL chain, + const STRUCT_ENTRY *e, + unsigned int rulenum, + struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r; + struct list_head *prev; + + iptc_fn = TC_INSERT_ENTRY; + + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return 0; + } + + /* first rulenum index = 0 + first c->num_rules index = 1 */ + if (rulenum > c->num_rules) { + errno = E2BIG; + return 0; + } + + /* If we are inserting at the end just take advantage of the + double linked list, insert will happen before the entry + prev points to. */ + if (rulenum == c->num_rules) { + prev = &c->rules; + } else if (rulenum + 1 <= c->num_rules/2) { + r = iptcc_get_rule_num(c, rulenum + 1); + prev = &r->list; + } else { + r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum); + prev = &r->list; + } + + if (!(r = iptcc_alloc_rule(c, e->next_offset))) { + errno = ENOMEM; + return 0; + } + + memcpy(r->entry, e, e->next_offset); + r->counter_map.maptype = COUNTER_MAP_SET; + + if (!iptcc_map_target(handle, r, false)) { + free(r); + return 0; + } + + list_add_tail(&r->list, prev); + c->num_rules++; + + set_changed(handle); + + return 1; +} + +/* Atomically replace rule `rulenum' in `chain' with `fw'. */ +int +TC_REPLACE_ENTRY(const IPT_CHAINLABEL chain, + const STRUCT_ENTRY *e, + unsigned int rulenum, + struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r, *old; + + iptc_fn = TC_REPLACE_ENTRY; + + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return 0; + } + + if (rulenum >= c->num_rules) { + errno = E2BIG; + return 0; + } + + /* Take advantage of the double linked list if possible. */ + if (rulenum + 1 <= c->num_rules/2) { + old = iptcc_get_rule_num(c, rulenum + 1); + } else { + old = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum); + } + + if (!(r = iptcc_alloc_rule(c, e->next_offset))) { + errno = ENOMEM; + return 0; + } + + memcpy(r->entry, e, e->next_offset); + r->counter_map.maptype = COUNTER_MAP_SET; + + if (!iptcc_map_target(handle, r, false)) { + free(r); + return 0; + } + + list_add(&r->list, &old->list); + iptcc_delete_rule(old); + + set_changed(handle); + + return 1; +} + +/* Append entry `fw' to chain `chain'. Equivalent to insert with + rulenum = length of chain. */ +int +TC_APPEND_ENTRY(const IPT_CHAINLABEL chain, + const STRUCT_ENTRY *e, + struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r; + + iptc_fn = TC_APPEND_ENTRY; + if (!(c = iptcc_find_label(chain, handle))) { + DEBUGP("unable to find chain `%s'\n", chain); + errno = ENOENT; + return 0; + } + + if (!(r = iptcc_alloc_rule(c, e->next_offset))) { + DEBUGP("unable to allocate rule for chain `%s'\n", chain); + errno = ENOMEM; + return 0; + } + + memcpy(r->entry, e, e->next_offset); + r->counter_map.maptype = COUNTER_MAP_SET; + + if (!iptcc_map_target(handle, r, false)) { + DEBUGP("unable to map target of rule for chain `%s'\n", chain); + free(r); + return 0; + } + + list_add_tail(&r->list, &c->rules); + c->num_rules++; + + set_changed(handle); + + return 1; +} + +static inline int +match_different(const STRUCT_ENTRY_MATCH *a, + const unsigned char *a_elems, + const unsigned char *b_elems, + unsigned char **maskptr) +{ + const STRUCT_ENTRY_MATCH *b; + unsigned int i; + + /* Offset of b is the same as a. */ + b = (void *)b_elems + ((unsigned char *)a - a_elems); + + if (a->u.match_size != b->u.match_size) + return 1; + + if (strcmp(a->u.user.name, b->u.user.name) != 0) + return 1; + + *maskptr += ALIGN(sizeof(*a)); + + for (i = 0; i < a->u.match_size - ALIGN(sizeof(*a)); i++) + if (((a->data[i] ^ b->data[i]) & (*maskptr)[i]) != 0) + return 1; + *maskptr += i; + return 0; +} + +static inline int +target_same(struct rule_head *a, struct rule_head *b,const unsigned char *mask) +{ + unsigned int i; + STRUCT_ENTRY_TARGET *ta, *tb; + + if (a->type != b->type) + return 0; + + ta = GET_TARGET(a->entry); + tb = GET_TARGET(b->entry); + + switch (a->type) { + case IPTCC_R_FALLTHROUGH: + return 1; + case IPTCC_R_JUMP: + return a->jump == b->jump; + case IPTCC_R_STANDARD: + return ((STRUCT_STANDARD_TARGET *)ta)->verdict + == ((STRUCT_STANDARD_TARGET *)tb)->verdict; + case IPTCC_R_MODULE: + if (ta->u.target_size != tb->u.target_size) + return 0; + if (strcmp(ta->u.user.name, tb->u.user.name) != 0) + return 0; + + for (i = 0; i < ta->u.target_size - sizeof(*ta); i++) + if (((ta->data[i] ^ tb->data[i]) & mask[i]) != 0) + return 0; + return 1; + default: + fprintf(stderr, "ERROR: bad type %i\n", a->type); + abort(); + } +} + +static unsigned char * +is_same(const STRUCT_ENTRY *a, + const STRUCT_ENTRY *b, + unsigned char *matchmask); + + +/* find the first rule in `chain' which matches `fw' and remove it unless dry_run is set */ +static int delete_entry(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *origfw, + unsigned char *matchmask, struct xtc_handle *handle, + bool dry_run) +{ + struct chain_head *c; + struct rule_head *r, *i; + + iptc_fn = TC_DELETE_ENTRY; + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return 0; + } + + /* Create a rule_head from origfw. */ + r = iptcc_alloc_rule(c, origfw->next_offset); + if (!r) { + errno = ENOMEM; + return 0; + } + + memcpy(r->entry, origfw, origfw->next_offset); + r->counter_map.maptype = COUNTER_MAP_NOMAP; + if (!iptcc_map_target(handle, r, dry_run)) { + DEBUGP("unable to map target of rule for chain `%s'\n", chain); + free(r); + return 0; + } else { + /* iptcc_map_target increment target chain references + * since this is a fake rule only used for matching + * the chain references count is decremented again. + */ + if (r->type == IPTCC_R_JUMP + && r->jump) + r->jump->references--; + } + + list_for_each_entry(i, &c->rules, list) { + unsigned char *mask; + + mask = is_same(r->entry, i->entry, matchmask); + if (!mask) + continue; + + if (!target_same(r, i, mask)) + continue; + + /* if we are just doing a dry run, we simply skip the rest */ + if (dry_run){ + free(r); + return 1; + } + + /* If we are about to delete the rule that is the + * current iterator, move rule iterator back. next + * pointer will then point to real next node */ + if (i == handle->rule_iterator_cur) { + handle->rule_iterator_cur = + list_entry(handle->rule_iterator_cur->list.prev, + struct rule_head, list); + } + + c->num_rules--; + iptcc_delete_rule(i); + + set_changed(handle); + free(r); + return 1; + } + + free(r); + errno = ENOENT; + return 0; +} + +/* check whether a specified rule is present */ +int TC_CHECK_ENTRY(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *origfw, + unsigned char *matchmask, struct xtc_handle *handle) +{ + /* do a dry-run delete to find out whether a matching rule exists */ + return delete_entry(chain, origfw, matchmask, handle, true); +} + +/* Delete the first rule in `chain' which matches `fw'. */ +int TC_DELETE_ENTRY(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *origfw, + unsigned char *matchmask, struct xtc_handle *handle) +{ + return delete_entry(chain, origfw, matchmask, handle, false); +} + +/* Delete the rule in position `rulenum' in `chain'. */ +int +TC_DELETE_NUM_ENTRY(const IPT_CHAINLABEL chain, + unsigned int rulenum, + struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r; + + iptc_fn = TC_DELETE_NUM_ENTRY; + + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return 0; + } + + if (rulenum >= c->num_rules) { + errno = E2BIG; + return 0; + } + + /* Take advantage of the double linked list if possible. */ + if (rulenum + 1 <= c->num_rules/2) { + r = iptcc_get_rule_num(c, rulenum + 1); + } else { + r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum); + } + + /* If we are about to delete the rule that is the current + * iterator, move rule iterator back. next pointer will then + * point to real next node */ + if (r == handle->rule_iterator_cur) { + handle->rule_iterator_cur = + list_entry(handle->rule_iterator_cur->list.prev, + struct rule_head, list); + } + + c->num_rules--; + iptcc_delete_rule(r); + + set_changed(handle); + + return 1; +} + +/* Flushes the entries in the given chain (ie. empties chain). */ +int +TC_FLUSH_ENTRIES(const IPT_CHAINLABEL chain, struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r, *tmp; + + iptc_fn = TC_FLUSH_ENTRIES; + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return 0; + } + + list_for_each_entry_safe(r, tmp, &c->rules, list) { + iptcc_delete_rule(r); + } + + c->num_rules = 0; + + set_changed(handle); + + return 1; +} + +/* Zeroes the counters in a chain. */ +int +TC_ZERO_ENTRIES(const IPT_CHAINLABEL chain, struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r; + + iptc_fn = TC_ZERO_ENTRIES; + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return 0; + } + + if (c->counter_map.maptype == COUNTER_MAP_NORMAL_MAP) + c->counter_map.maptype = COUNTER_MAP_ZEROED; + + list_for_each_entry(r, &c->rules, list) { + if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP) + r->counter_map.maptype = COUNTER_MAP_ZEROED; + } + + set_changed(handle); + + return 1; +} + +STRUCT_COUNTERS * +TC_READ_COUNTER(const IPT_CHAINLABEL chain, + unsigned int rulenum, + struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r; + + iptc_fn = TC_READ_COUNTER; + + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return NULL; + } + + if (!(r = iptcc_get_rule_num(c, rulenum))) { + errno = E2BIG; + return NULL; + } + + return &r->entry[0].counters; +} + +int +TC_ZERO_COUNTER(const IPT_CHAINLABEL chain, + unsigned int rulenum, + struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r; + + iptc_fn = TC_ZERO_COUNTER; + + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return 0; + } + + if (!(r = iptcc_get_rule_num(c, rulenum))) { + errno = E2BIG; + return 0; + } + + if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP) + r->counter_map.maptype = COUNTER_MAP_ZEROED; + + set_changed(handle); + + return 1; +} + +int +TC_SET_COUNTER(const IPT_CHAINLABEL chain, + unsigned int rulenum, + STRUCT_COUNTERS *counters, + struct xtc_handle *handle) +{ + struct chain_head *c; + struct rule_head *r; + STRUCT_ENTRY *e; + + iptc_fn = TC_SET_COUNTER; + + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return 0; + } + + if (!(r = iptcc_get_rule_num(c, rulenum))) { + errno = E2BIG; + return 0; + } + + e = r->entry; + r->counter_map.maptype = COUNTER_MAP_SET; + + memcpy(&e->counters, counters, sizeof(STRUCT_COUNTERS)); + + set_changed(handle); + + return 1; +} + +/* Creates a new chain. */ +/* To create a chain, create two rules: error node and unconditional + * return. */ +int +TC_CREATE_CHAIN(const IPT_CHAINLABEL chain, struct xtc_handle *handle) +{ + static struct chain_head *c; + int capacity; + int exceeded; + + iptc_fn = TC_CREATE_CHAIN; + + /* find_label doesn't cover built-in targets: DROP, ACCEPT, + QUEUE, RETURN. */ + if (iptcc_find_label(chain, handle) + || strcmp(chain, LABEL_DROP) == 0 + || strcmp(chain, LABEL_ACCEPT) == 0 + || strcmp(chain, LABEL_QUEUE) == 0 + || strcmp(chain, LABEL_RETURN) == 0) { + DEBUGP("Chain `%s' already exists\n", chain); + errno = EEXIST; + return 0; + } + + if (strlen(chain)+1 > sizeof(IPT_CHAINLABEL)) { + DEBUGP("Chain name `%s' too long\n", chain); + errno = EINVAL; + return 0; + } + + c = iptcc_alloc_chain_head(chain, 0); + if (!c) { + DEBUGP("Cannot allocate memory for chain `%s'\n", chain); + errno = ENOMEM; + return 0; + + } + handle->num_chains++; /* New user defined chain */ + + DEBUGP("Creating chain `%s'\n", chain); + iptc_insert_chain(handle, c); /* Insert sorted */ + + /* Inserting chains don't change the correctness of the chain + * index (except if its smaller than index[0], but that + * handled by iptc_insert_chain). It only causes longer lists + * in the buckets. Thus, only rebuild chain index when the + * capacity is exceed with CHAIN_INDEX_INSERT_MAX chains. + */ + capacity = handle->chain_index_sz * CHAIN_INDEX_BUCKET_LEN; + exceeded = handle->num_chains - capacity; + if (exceeded > CHAIN_INDEX_INSERT_MAX) { + debug("Capacity(%d) exceeded(%d) rebuild (chains:%d)\n", + capacity, exceeded, handle->num_chains); + iptcc_chain_index_rebuild(handle); + } + + set_changed(handle); + + return 1; +} + +/* Get the number of references to this chain. */ +int +TC_GET_REFERENCES(unsigned int *ref, const IPT_CHAINLABEL chain, + struct xtc_handle *handle) +{ + struct chain_head *c; + + iptc_fn = TC_GET_REFERENCES; + if (!(c = iptcc_find_label(chain, handle))) { + errno = ENOENT; + return 0; + } + + *ref = c->references; + + return 1; +} + +/* Deletes a chain. */ +int +TC_DELETE_CHAIN(const IPT_CHAINLABEL chain, struct xtc_handle *handle) +{ + unsigned int references; + struct chain_head *c; + + iptc_fn = TC_DELETE_CHAIN; + + if (!(c = iptcc_find_label(chain, handle))) { + DEBUGP("cannot find chain `%s'\n", chain); + errno = ENOENT; + return 0; + } + + if (TC_BUILTIN(chain, handle)) { + DEBUGP("cannot remove builtin chain `%s'\n", chain); + errno = EINVAL; + return 0; + } + + if (!TC_GET_REFERENCES(&references, chain, handle)) { + DEBUGP("cannot get references on chain `%s'\n", chain); + return 0; + } + + if (references > 0) { + DEBUGP("chain `%s' still has references\n", chain); + errno = EMLINK; + return 0; + } + + if (c->num_rules) { + DEBUGP("chain `%s' is not empty\n", chain); + errno = ENOTEMPTY; + return 0; + } + + /* If we are about to delete the chain that is the current + * iterator, move chain iterator forward. */ + if (c == handle->chain_iterator_cur) + iptcc_chain_iterator_advance(handle); + + handle->num_chains--; /* One user defined chain deleted */ + + //list_del(&c->list); /* Done in iptcc_chain_index_delete_chain() */ + iptcc_chain_index_delete_chain(c, handle); + free(c); + + DEBUGP("chain `%s' deleted\n", chain); + + set_changed(handle); + + return 1; +} + +/* Renames a chain. */ +int TC_RENAME_CHAIN(const IPT_CHAINLABEL oldname, + const IPT_CHAINLABEL newname, + struct xtc_handle *handle) +{ + struct chain_head *c; + iptc_fn = TC_RENAME_CHAIN; + + /* find_label doesn't cover built-in targets: DROP, ACCEPT, + QUEUE, RETURN. */ + if (iptcc_find_label(newname, handle) + || strcmp(newname, LABEL_DROP) == 0 + || strcmp(newname, LABEL_ACCEPT) == 0 + || strcmp(newname, LABEL_QUEUE) == 0 + || strcmp(newname, LABEL_RETURN) == 0) { + errno = EEXIST; + return 0; + } + + if (!(c = iptcc_find_label(oldname, handle)) + || TC_BUILTIN(oldname, handle)) { + errno = ENOENT; + return 0; + } + + if (strlen(newname)+1 > sizeof(IPT_CHAINLABEL)) { + errno = EINVAL; + return 0; + } + + /* This only unlinks "c" from the list, thus no free(c) */ + iptcc_chain_index_delete_chain(c, handle); + + /* Change the name of the chain */ + strncpy(c->name, newname, sizeof(IPT_CHAINLABEL) - 1); + + /* Insert sorted into to list again */ + iptc_insert_chain(handle, c); + + set_changed(handle); + + return 1; +} + +/* Sets the policy on a built-in chain. */ +int +TC_SET_POLICY(const IPT_CHAINLABEL chain, + const IPT_CHAINLABEL policy, + STRUCT_COUNTERS *counters, + struct xtc_handle *handle) +{ + struct chain_head *c; + + iptc_fn = TC_SET_POLICY; + + if (!(c = iptcc_find_label(chain, handle))) { + DEBUGP("cannot find chain `%s'\n", chain); + errno = ENOENT; + return 0; + } + + if (!iptcc_is_builtin(c)) { + DEBUGP("cannot set policy of userdefinedchain `%s'\n", chain); + errno = ENOENT; + return 0; + } + + if (strcmp(policy, LABEL_ACCEPT) == 0) + c->verdict = -NF_ACCEPT - 1; + else if (strcmp(policy, LABEL_DROP) == 0) + c->verdict = -NF_DROP - 1; + else { + errno = EINVAL; + return 0; + } + + if (counters) { + /* set byte and packet counters */ + memcpy(&c->counters, counters, sizeof(STRUCT_COUNTERS)); + c->counter_map.maptype = COUNTER_MAP_SET; + } else { + c->counter_map.maptype = COUNTER_MAP_NOMAP; + } + + set_changed(handle); + + return 1; +} + +/* Without this, on gcc 2.7.2.3, we get: + libiptc.c: In function `TC_COMMIT': + libiptc.c:833: fixed or forbidden register was spilled. + This may be due to a compiler bug or to impossible asm + statements or clauses. +*/ +static void +subtract_counters(STRUCT_COUNTERS *answer, + const STRUCT_COUNTERS *a, + const STRUCT_COUNTERS *b) +{ + answer->pcnt = a->pcnt - b->pcnt; + answer->bcnt = a->bcnt - b->bcnt; +} + + +static void counters_nomap(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx) +{ + newcounters->counters[idx] = ((STRUCT_COUNTERS) { 0, 0}); + DEBUGP_C("NOMAP => zero\n"); +} + +static void counters_normal_map(STRUCT_COUNTERS_INFO *newcounters, + STRUCT_REPLACE *repl, unsigned int idx, + unsigned int mappos) +{ + /* Original read: X. + * Atomic read on replacement: X + Y. + * Currently in kernel: Z. + * Want in kernel: X + Y + Z. + * => Add in X + Y + * => Add in replacement read. + */ + newcounters->counters[idx] = repl->counters[mappos]; + DEBUGP_C("NORMAL_MAP => mappos %u \n", mappos); +} + +static void counters_map_zeroed(STRUCT_COUNTERS_INFO *newcounters, + STRUCT_REPLACE *repl, unsigned int idx, + unsigned int mappos, STRUCT_COUNTERS *counters) +{ + /* Original read: X. + * Atomic read on replacement: X + Y. + * Currently in kernel: Z. + * Want in kernel: Y + Z. + * => Add in Y. + * => Add in (replacement read - original read). + */ + subtract_counters(&newcounters->counters[idx], + &repl->counters[mappos], + counters); + DEBUGP_C("ZEROED => mappos %u\n", mappos); +} + +static void counters_map_set(STRUCT_COUNTERS_INFO *newcounters, + unsigned int idx, STRUCT_COUNTERS *counters) +{ + /* Want to set counter (iptables-restore) */ + + memcpy(&newcounters->counters[idx], counters, + sizeof(STRUCT_COUNTERS)); + + DEBUGP_C("SET\n"); +} + + +int +TC_COMMIT(struct xtc_handle *handle) +{ + /* Replace, then map back the counters. */ + STRUCT_REPLACE *repl; + STRUCT_COUNTERS_INFO *newcounters; + struct chain_head *c; + int ret; + size_t counterlen; + int new_number; + unsigned int new_size; + + iptc_fn = TC_COMMIT; + + /* Don't commit if nothing changed. */ + if (!handle->changed) + goto finished; + + new_number = iptcc_compile_table_prep(handle, &new_size); + if (new_number < 0) { + errno = ENOMEM; + goto out_zero; + } + + repl = malloc(sizeof(*repl) + new_size); + if (!repl) { + errno = ENOMEM; + goto out_zero; + } + memset(repl, 0, sizeof(*repl) + new_size); + +#if 0 + TC_DUMP_ENTRIES(*handle); +#endif + + counterlen = sizeof(STRUCT_COUNTERS_INFO) + + sizeof(STRUCT_COUNTERS) * new_number; + + /* These are the old counters we will get from kernel */ + repl->counters = malloc(sizeof(STRUCT_COUNTERS) + * handle->info.num_entries); + if (!repl->counters) { + errno = ENOMEM; + goto out_free_repl; + } + /* These are the counters we're going to put back, later. */ + newcounters = malloc(counterlen); + if (!newcounters) { + errno = ENOMEM; + goto out_free_repl_counters; + } + memset(newcounters, 0, counterlen); + + strcpy(repl->name, handle->info.name); + repl->num_entries = new_number; + repl->size = new_size; + + repl->num_counters = handle->info.num_entries; + repl->valid_hooks = handle->info.valid_hooks; + + DEBUGP("num_entries=%u, size=%u, num_counters=%u\n", + repl->num_entries, repl->size, repl->num_counters); + + ret = iptcc_compile_table(handle, repl); + if (ret < 0) { + errno = ret; + goto out_free_newcounters; + } + + +#ifdef IPTC_DEBUG2 + { + int fd = open("/tmp/libiptc-so_set_replace.blob", + O_CREAT|O_WRONLY, 0644); + if (fd >= 0) { + write(fd, repl, sizeof(*repl) + repl->size); + close(fd); + } + } +#endif + + ret = setsockopt(handle->sockfd, TC_IPPROTO, SO_SET_REPLACE, repl, + sizeof(*repl) + repl->size); + if (ret < 0) + goto out_free_newcounters; + + /* Put counters back. */ + strcpy(newcounters->name, handle->info.name); + newcounters->num_counters = new_number; + + list_for_each_entry(c, &handle->chains, list) { + struct rule_head *r; + + /* Builtin chains have their own counters */ + if (iptcc_is_builtin(c)) { + DEBUGP("counter for chain-index %u: ", c->foot_index); + switch(c->counter_map.maptype) { + case COUNTER_MAP_NOMAP: + counters_nomap(newcounters, c->foot_index); + break; + case COUNTER_MAP_NORMAL_MAP: + counters_normal_map(newcounters, repl, + c->foot_index, + c->counter_map.mappos); + break; + case COUNTER_MAP_ZEROED: + counters_map_zeroed(newcounters, repl, + c->foot_index, + c->counter_map.mappos, + &c->counters); + break; + case COUNTER_MAP_SET: + counters_map_set(newcounters, c->foot_index, + &c->counters); + break; + } + } + + list_for_each_entry(r, &c->rules, list) { + DEBUGP("counter for index %u: ", r->index); + switch (r->counter_map.maptype) { + case COUNTER_MAP_NOMAP: + counters_nomap(newcounters, r->index); + break; + + case COUNTER_MAP_NORMAL_MAP: + counters_normal_map(newcounters, repl, + r->index, + r->counter_map.mappos); + break; + + case COUNTER_MAP_ZEROED: + counters_map_zeroed(newcounters, repl, + r->index, + r->counter_map.mappos, + &r->entry->counters); + break; + + case COUNTER_MAP_SET: + counters_map_set(newcounters, r->index, + &r->entry->counters); + break; + } + } + } + +#ifdef IPTC_DEBUG2 + { + int fd = open("/tmp/libiptc-so_set_add_counters.blob", + O_CREAT|O_WRONLY, 0644); + if (fd >= 0) { + write(fd, newcounters, counterlen); + close(fd); + } + } +#endif + + ret = setsockopt(handle->sockfd, TC_IPPROTO, SO_SET_ADD_COUNTERS, + newcounters, counterlen); + if (ret < 0) + goto out_free_newcounters; + + free(repl->counters); + free(repl); + free(newcounters); + +finished: + return 1; + +out_free_newcounters: + free(newcounters); +out_free_repl_counters: + free(repl->counters); +out_free_repl: + free(repl); +out_zero: + return 0; +} + +/* Translates errno numbers into more human-readable form than strerror. */ +const char * +TC_STRERROR(int err) +{ + unsigned int i; + struct table_struct { + void *fn; + int err; + const char *message; + } table [] = + { { TC_INIT, EPERM, "Permission denied (you must be root)" }, + { TC_INIT, EINVAL, "Module is wrong version" }, + { TC_INIT, ENOENT, + "Table does not exist (do you need to insmod?)" }, + { TC_DELETE_CHAIN, ENOTEMPTY, "Chain is not empty" }, + { TC_DELETE_CHAIN, EINVAL, "Can't delete built-in chain" }, + { TC_DELETE_CHAIN, EMLINK, + "Can't delete chain with references left" }, + { TC_CREATE_CHAIN, EEXIST, "Chain already exists" }, + { TC_INSERT_ENTRY, E2BIG, "Index of insertion too big" }, + { TC_REPLACE_ENTRY, E2BIG, "Index of replacement too big" }, + { TC_DELETE_NUM_ENTRY, E2BIG, "Index of deletion too big" }, + { TC_READ_COUNTER, E2BIG, "Index of counter too big" }, + { TC_ZERO_COUNTER, E2BIG, "Index of counter too big" }, + { TC_INSERT_ENTRY, ELOOP, "Loop found in table" }, + { TC_INSERT_ENTRY, EINVAL, "Target problem" }, + /* ENOENT for DELETE probably means no matching rule */ + { TC_DELETE_ENTRY, ENOENT, + "Bad rule (does a matching rule exist in that chain?)" }, + { TC_SET_POLICY, ENOENT, + "Bad built-in chain name" }, + { TC_SET_POLICY, EINVAL, + "Bad policy name" }, + + { NULL, 0, "Incompatible with this kernel" }, + { NULL, ENOPROTOOPT, "iptables who? (do you need to insmod?)" }, + { NULL, ENOSYS, "Will be implemented real soon. I promise ;)" }, + { NULL, ENOMEM, "Memory allocation problem" }, + { NULL, ENOENT, "No chain/target/match by that name" }, + }; + + for (i = 0; i < sizeof(table)/sizeof(struct table_struct); i++) { + if ((!table[i].fn || table[i].fn == iptc_fn) + && table[i].err == err) + return table[i].message; + } + + return strerror(err); +} + +const struct xtc_ops TC_OPS = { + .commit = TC_COMMIT, + .init = TC_INIT, + .free = TC_FREE, + .builtin = TC_BUILTIN, + .is_chain = TC_IS_CHAIN, + .flush_entries = TC_FLUSH_ENTRIES, + .create_chain = TC_CREATE_CHAIN, + .first_chain = TC_FIRST_CHAIN, + .next_chain = TC_NEXT_CHAIN, + .get_policy = TC_GET_POLICY, + .set_policy = TC_SET_POLICY, + .strerror = TC_STRERROR, +}; diff --git a/libiptc/linux_list.h b/libiptc/linux_list.h new file mode 100644 index 0000000..559e33c --- /dev/null +++ b/libiptc/linux_list.h @@ -0,0 +1,723 @@ +#ifndef _LINUX_LIST_H +#define _LINUX_LIST_H + +#undef offsetof +#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER) + +/** + * container_of - cast a member of a structure out to the containing structure + * + * @ptr: the pointer to the member. + * @type: the type of the container struct this is embedded in. + * @member: the name of the member within the struct. + * + */ +#define container_of(ptr, type, member) ({ \ + const typeof( ((type *)0)->member ) *__mptr = (ptr); \ + (type *)( (char *)__mptr - offsetof(type,member) );}) + +/* + * Check at compile time that something is of a particular type. + * Always evaluates to 1 so you may use it easily in comparisons. + */ +#define typecheck(type,x) \ +({ type __dummy; \ + typeof(x) __dummy2; \ + (void)(&__dummy == &__dummy2); \ + 1; \ +}) + +#define prefetch(x) ((void)0) + +/* empty define to make this work in userspace -HW */ +#define smp_wmb() + +/* + * These are non-NULL pointers that will result in page faults + * under normal circumstances, used to verify that nobody uses + * non-initialized list entries. + */ +#define LIST_POISON1 ((void *) 0x00100100) +#define LIST_POISON2 ((void *) 0x00200200) + +/* + * Simple doubly linked list implementation. + * + * Some of the internal functions ("__xxx") are useful when + * manipulating whole lists rather than single entries, as + * sometimes we already know the next/prev entries and we can + * generate better code by using them directly rather than + * using the generic single-entry routines. + */ + +struct list_head { + struct list_head *next, *prev; +}; + +#define LIST_HEAD_INIT(name) { &(name), &(name) } + +#define LIST_HEAD(name) \ + struct list_head name = LIST_HEAD_INIT(name) + +#define INIT_LIST_HEAD(ptr) do { \ + (ptr)->next = (ptr); (ptr)->prev = (ptr); \ +} while (0) + +/* + * Insert a new entry between two known consecutive entries. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_add(struct list_head *new, + struct list_head *prev, + struct list_head *next) +{ + next->prev = new; + new->next = next; + new->prev = prev; + prev->next = new; +} + +/** + * list_add - add a new entry + * @new: new entry to be added + * @head: list head to add it after + * + * Insert a new entry after the specified head. + * This is good for implementing stacks. + */ +static inline void list_add(struct list_head *new, struct list_head *head) +{ + __list_add(new, head, head->next); +} + +/** + * list_add_tail - add a new entry + * @new: new entry to be added + * @head: list head to add it before + * + * Insert a new entry before the specified head. + * This is useful for implementing queues. + */ +static inline void list_add_tail(struct list_head *new, struct list_head *head) +{ + __list_add(new, head->prev, head); +} + +/* + * Insert a new entry between two known consecutive entries. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_add_rcu(struct list_head * new, + struct list_head * prev, struct list_head * next) +{ + new->next = next; + new->prev = prev; + smp_wmb(); + next->prev = new; + prev->next = new; +} + +/** + * list_add_rcu - add a new entry to rcu-protected list + * @new: new entry to be added + * @head: list head to add it after + * + * Insert a new entry after the specified head. + * This is good for implementing stacks. + * + * The caller must take whatever precautions are necessary + * (such as holding appropriate locks) to avoid racing + * with another list-mutation primitive, such as list_add_rcu() + * or list_del_rcu(), running on this same list. + * However, it is perfectly legal to run concurrently with + * the _rcu list-traversal primitives, such as + * list_for_each_entry_rcu(). + */ +static inline void list_add_rcu(struct list_head *new, struct list_head *head) +{ + __list_add_rcu(new, head, head->next); +} + +/** + * list_add_tail_rcu - add a new entry to rcu-protected list + * @new: new entry to be added + * @head: list head to add it before + * + * Insert a new entry before the specified head. + * This is useful for implementing queues. + * + * The caller must take whatever precautions are necessary + * (such as holding appropriate locks) to avoid racing + * with another list-mutation primitive, such as list_add_tail_rcu() + * or list_del_rcu(), running on this same list. + * However, it is perfectly legal to run concurrently with + * the _rcu list-traversal primitives, such as + * list_for_each_entry_rcu(). + */ +static inline void list_add_tail_rcu(struct list_head *new, + struct list_head *head) +{ + __list_add_rcu(new, head->prev, head); +} + +/* + * Delete a list entry by making the prev/next entries + * point to each other. + * + * This is only for internal list manipulation where we know + * the prev/next entries already! + */ +static inline void __list_del(struct list_head * prev, struct list_head * next) +{ + next->prev = prev; + prev->next = next; +} + +/** + * list_del - deletes entry from list. + * @entry: the element to delete from the list. + * Note: list_empty on entry does not return true after this, the entry is + * in an undefined state. + */ +static inline void list_del(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + entry->next = LIST_POISON1; + entry->prev = LIST_POISON2; +} + +/** + * list_del_rcu - deletes entry from list without re-initialization + * @entry: the element to delete from the list. + * + * Note: list_empty on entry does not return true after this, + * the entry is in an undefined state. It is useful for RCU based + * lockfree traversal. + * + * In particular, it means that we can not poison the forward + * pointers that may still be used for walking the list. + * + * The caller must take whatever precautions are necessary + * (such as holding appropriate locks) to avoid racing + * with another list-mutation primitive, such as list_del_rcu() + * or list_add_rcu(), running on this same list. + * However, it is perfectly legal to run concurrently with + * the _rcu list-traversal primitives, such as + * list_for_each_entry_rcu(). + * + * Note that the caller is not permitted to immediately free + * the newly deleted entry. Instead, either synchronize_kernel() + * or call_rcu() must be used to defer freeing until an RCU + * grace period has elapsed. + */ +static inline void list_del_rcu(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + entry->prev = LIST_POISON2; +} + +/** + * list_del_init - deletes entry from list and reinitialize it. + * @entry: the element to delete from the list. + */ +static inline void list_del_init(struct list_head *entry) +{ + __list_del(entry->prev, entry->next); + INIT_LIST_HEAD(entry); +} + +/** + * list_move - delete from one list and add as another's head + * @list: the entry to move + * @head: the head that will precede our entry + */ +static inline void list_move(struct list_head *list, struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add(list, head); +} + +/** + * list_move_tail - delete from one list and add as another's tail + * @list: the entry to move + * @head: the head that will follow our entry + */ +static inline void list_move_tail(struct list_head *list, + struct list_head *head) +{ + __list_del(list->prev, list->next); + list_add_tail(list, head); +} + +/** + * list_empty - tests whether a list is empty + * @head: the list to test. + */ +static inline int list_empty(const struct list_head *head) +{ + return head->next == head; +} + +/** + * list_empty_careful - tests whether a list is + * empty _and_ checks that no other CPU might be + * in the process of still modifying either member + * + * NOTE: using list_empty_careful() without synchronization + * can only be safe if the only activity that can happen + * to the list entry is list_del_init(). Eg. it cannot be used + * if another CPU could re-list_add() it. + * + * @head: the list to test. + */ +static inline int list_empty_careful(const struct list_head *head) +{ + struct list_head *next = head->next; + return (next == head) && (next == head->prev); +} + +static inline void __list_splice(struct list_head *list, + struct list_head *head) +{ + struct list_head *first = list->next; + struct list_head *last = list->prev; + struct list_head *at = head->next; + + first->prev = head; + head->next = first; + + last->next = at; + at->prev = last; +} + +/** + * list_splice - join two lists + * @list: the new list to add. + * @head: the place to add it in the first list. + */ +static inline void list_splice(struct list_head *list, struct list_head *head) +{ + if (!list_empty(list)) + __list_splice(list, head); +} + +/** + * list_splice_init - join two lists and reinitialise the emptied list. + * @list: the new list to add. + * @head: the place to add it in the first list. + * + * The list at @list is reinitialised + */ +static inline void list_splice_init(struct list_head *list, + struct list_head *head) +{ + if (!list_empty(list)) { + __list_splice(list, head); + INIT_LIST_HEAD(list); + } +} + +/** + * list_entry - get the struct for this entry + * @ptr: the &struct list_head pointer. + * @type: the type of the struct this is embedded in. + * @member: the name of the list_struct within the struct. + */ +#define list_entry(ptr, type, member) \ + container_of(ptr, type, member) + +/** + * list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each(pos, head) \ + for (pos = (head)->next, prefetch(pos->next); pos != (head); \ + pos = pos->next, prefetch(pos->next)) + +/** + * __list_for_each - iterate over a list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + * + * This variant differs from list_for_each() in that it's the + * simplest possible list iteration code, no prefetching is done. + * Use this for code that knows the list to be very short (empty + * or 1 entry) most of the time. + */ +#define __list_for_each(pos, head) \ + for (pos = (head)->next; pos != (head); pos = pos->next) + +/** + * list_for_each_prev - iterate over a list backwards + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + */ +#define list_for_each_prev(pos, head) \ + for (pos = (head)->prev, prefetch(pos->prev); pos != (head); \ + pos = pos->prev, prefetch(pos->prev)) + +/** + * list_for_each_safe - iterate over a list safe against removal of list entry + * @pos: the &struct list_head to use as a loop counter. + * @n: another &struct list_head to use as temporary storage + * @head: the head for your list. + */ +#define list_for_each_safe(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, n = pos->next) + +/** + * list_for_each_entry - iterate over list of given type + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + prefetch(pos->member.next); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member), \ + prefetch(pos->member.next)) + +/** + * list_for_each_entry_reverse - iterate backwards over list of given type. + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_reverse(pos, head, member) \ + for (pos = list_entry((head)->prev, typeof(*pos), member), \ + prefetch(pos->member.prev); \ + &pos->member != (head); \ + pos = list_entry(pos->member.prev, typeof(*pos), member), \ + prefetch(pos->member.prev)) + +/** + * list_prepare_entry - prepare a pos entry for use as a start point in + * list_for_each_entry_continue + * @pos: the type * to use as a start point + * @head: the head of the list + * @member: the name of the list_struct within the struct. + */ +#define list_prepare_entry(pos, head, member) \ + ((pos) ? : list_entry(head, typeof(*pos), member)) + +/** + * list_for_each_entry_continue - iterate over list of given type + * continuing after existing point + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_continue(pos, head, member) \ + for (pos = list_entry(pos->member.next, typeof(*pos), member), \ + prefetch(pos->member.next); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member), \ + prefetch(pos->member.next)) + +/** + * list_for_each_entry_safe - iterate over list of given type safe against removal of list entry + * @pos: the type * to use as a loop counter. + * @n: another type * to use as temporary storage + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + */ +#define list_for_each_entry_safe(pos, n, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + n = list_entry(pos->member.next, typeof(*pos), member); \ + &pos->member != (head); \ + pos = n, n = list_entry(n->member.next, typeof(*n), member)) + +/** + * list_for_each_rcu - iterate over an rcu-protected list + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + * + * This list-traversal primitive may safely run concurrently with + * the _rcu list-mutation primitives such as list_add_rcu() + * as long as the traversal is guarded by rcu_read_lock(). + */ +#define list_for_each_rcu(pos, head) \ + for (pos = (head)->next, prefetch(pos->next); pos != (head); \ + pos = pos->next, ({ smp_read_barrier_depends(); 0;}), prefetch(pos->next)) + +#define __list_for_each_rcu(pos, head) \ + for (pos = (head)->next; pos != (head); \ + pos = pos->next, ({ smp_read_barrier_depends(); 0;})) + +/** + * list_for_each_safe_rcu - iterate over an rcu-protected list safe + * against removal of list entry + * @pos: the &struct list_head to use as a loop counter. + * @n: another &struct list_head to use as temporary storage + * @head: the head for your list. + * + * This list-traversal primitive may safely run concurrently with + * the _rcu list-mutation primitives such as list_add_rcu() + * as long as the traversal is guarded by rcu_read_lock(). + */ +#define list_for_each_safe_rcu(pos, n, head) \ + for (pos = (head)->next, n = pos->next; pos != (head); \ + pos = n, ({ smp_read_barrier_depends(); 0;}), n = pos->next) + +/** + * list_for_each_entry_rcu - iterate over rcu list of given type + * @pos: the type * to use as a loop counter. + * @head: the head for your list. + * @member: the name of the list_struct within the struct. + * + * This list-traversal primitive may safely run concurrently with + * the _rcu list-mutation primitives such as list_add_rcu() + * as long as the traversal is guarded by rcu_read_lock(). + */ +#define list_for_each_entry_rcu(pos, head, member) \ + for (pos = list_entry((head)->next, typeof(*pos), member), \ + prefetch(pos->member.next); \ + &pos->member != (head); \ + pos = list_entry(pos->member.next, typeof(*pos), member), \ + ({ smp_read_barrier_depends(); 0;}), \ + prefetch(pos->member.next)) + + +/** + * list_for_each_continue_rcu - iterate over an rcu-protected list + * continuing after existing point. + * @pos: the &struct list_head to use as a loop counter. + * @head: the head for your list. + * + * This list-traversal primitive may safely run concurrently with + * the _rcu list-mutation primitives such as list_add_rcu() + * as long as the traversal is guarded by rcu_read_lock(). + */ +#define list_for_each_continue_rcu(pos, head) \ + for ((pos) = (pos)->next, prefetch((pos)->next); (pos) != (head); \ + (pos) = (pos)->next, ({ smp_read_barrier_depends(); 0;}), prefetch((pos)->next)) + +/* + * Double linked lists with a single pointer list head. + * Mostly useful for hash tables where the two pointer list head is + * too wasteful. + * You lose the ability to access the tail in O(1). + */ + +struct hlist_head { + struct hlist_node *first; +}; + +struct hlist_node { + struct hlist_node *next, **pprev; +}; + +#define HLIST_HEAD_INIT { .first = NULL } +#define HLIST_HEAD(name) struct hlist_head name = { .first = NULL } +#define INIT_HLIST_HEAD(ptr) ((ptr)->first = NULL) +#define INIT_HLIST_NODE(ptr) ((ptr)->next = NULL, (ptr)->pprev = NULL) + +static inline int hlist_unhashed(const struct hlist_node *h) +{ + return !h->pprev; +} + +static inline int hlist_empty(const struct hlist_head *h) +{ + return !h->first; +} + +static inline void __hlist_del(struct hlist_node *n) +{ + struct hlist_node *next = n->next; + struct hlist_node **pprev = n->pprev; + *pprev = next; + if (next) + next->pprev = pprev; +} + +static inline void hlist_del(struct hlist_node *n) +{ + __hlist_del(n); + n->next = LIST_POISON1; + n->pprev = LIST_POISON2; +} + +/** + * hlist_del_rcu - deletes entry from hash list without re-initialization + * @n: the element to delete from the hash list. + * + * Note: list_unhashed() on entry does not return true after this, + * the entry is in an undefined state. It is useful for RCU based + * lockfree traversal. + * + * In particular, it means that we can not poison the forward + * pointers that may still be used for walking the hash list. + * + * The caller must take whatever precautions are necessary + * (such as holding appropriate locks) to avoid racing + * with another list-mutation primitive, such as hlist_add_head_rcu() + * or hlist_del_rcu(), running on this same list. + * However, it is perfectly legal to run concurrently with + * the _rcu list-traversal primitives, such as + * hlist_for_each_entry(). + */ +static inline void hlist_del_rcu(struct hlist_node *n) +{ + __hlist_del(n); + n->pprev = LIST_POISON2; +} + +static inline void hlist_del_init(struct hlist_node *n) +{ + if (n->pprev) { + __hlist_del(n); + INIT_HLIST_NODE(n); + } +} + +#define hlist_del_rcu_init hlist_del_init + +static inline void hlist_add_head(struct hlist_node *n, struct hlist_head *h) +{ + struct hlist_node *first = h->first; + n->next = first; + if (first) + first->pprev = &n->next; + h->first = n; + n->pprev = &h->first; +} + + +/** + * hlist_add_head_rcu - adds the specified element to the specified hlist, + * while permitting racing traversals. + * @n: the element to add to the hash list. + * @h: the list to add to. + * + * The caller must take whatever precautions are necessary + * (such as holding appropriate locks) to avoid racing + * with another list-mutation primitive, such as hlist_add_head_rcu() + * or hlist_del_rcu(), running on this same list. + * However, it is perfectly legal to run concurrently with + * the _rcu list-traversal primitives, such as + * hlist_for_each_entry(), but only if smp_read_barrier_depends() + * is used to prevent memory-consistency problems on Alpha CPUs. + * Regardless of the type of CPU, the list-traversal primitive + * must be guarded by rcu_read_lock(). + * + * OK, so why don't we have an hlist_for_each_entry_rcu()??? + */ +static inline void hlist_add_head_rcu(struct hlist_node *n, + struct hlist_head *h) +{ + struct hlist_node *first = h->first; + n->next = first; + n->pprev = &h->first; + smp_wmb(); + if (first) + first->pprev = &n->next; + h->first = n; +} + +/* next must be != NULL */ +static inline void hlist_add_before(struct hlist_node *n, + struct hlist_node *next) +{ + n->pprev = next->pprev; + n->next = next; + next->pprev = &n->next; + *(n->pprev) = n; +} + +static inline void hlist_add_after(struct hlist_node *n, + struct hlist_node *next) +{ + next->next = n->next; + n->next = next; + next->pprev = &n->next; + + if(next->next) + next->next->pprev = &next->next; +} + +#define hlist_entry(ptr, type, member) container_of(ptr,type,member) + +#define hlist_for_each(pos, head) \ + for (pos = (head)->first; pos && ({ prefetch(pos->next); 1; }); \ + pos = pos->next) + +#define hlist_for_each_safe(pos, n, head) \ + for (pos = (head)->first; pos && ({ n = pos->next; 1; }); \ + pos = n) + +/** + * hlist_for_each_entry - iterate over list of given type + * @tpos: the type * to use as a loop counter. + * @pos: the &struct hlist_node to use as a loop counter. + * @head: the head for your list. + * @member: the name of the hlist_node within the struct. + */ +#define hlist_for_each_entry(tpos, pos, head, member) \ + for (pos = (head)->first; \ + pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next) + +/** + * hlist_for_each_entry_continue - iterate over a hlist continuing after existing point + * @tpos: the type * to use as a loop counter. + * @pos: the &struct hlist_node to use as a loop counter. + * @member: the name of the hlist_node within the struct. + */ +#define hlist_for_each_entry_continue(tpos, pos, member) \ + for (pos = (pos)->next; \ + pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next) + +/** + * hlist_for_each_entry_from - iterate over a hlist continuing from existing point + * @tpos: the type * to use as a loop counter. + * @pos: the &struct hlist_node to use as a loop counter. + * @member: the name of the hlist_node within the struct. + */ +#define hlist_for_each_entry_from(tpos, pos, member) \ + for (; pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next) + +/** + * hlist_for_each_entry_safe - iterate over list of given type safe against removal of list entry + * @tpos: the type * to use as a loop counter. + * @pos: the &struct hlist_node to use as a loop counter. + * @n: another &struct hlist_node to use as temporary storage + * @head: the head for your list. + * @member: the name of the hlist_node within the struct. + */ +#define hlist_for_each_entry_safe(tpos, pos, n, head, member) \ + for (pos = (head)->first; \ + pos && ({ n = pos->next; 1; }) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = n) + +/** + * hlist_for_each_entry_rcu - iterate over rcu list of given type + * @pos: the type * to use as a loop counter. + * @pos: the &struct hlist_node to use as a loop counter. + * @head: the head for your list. + * @member: the name of the hlist_node within the struct. + * + * This list-traversal primitive may safely run concurrently with + * the _rcu list-mutation primitives such as hlist_add_rcu() + * as long as the traversal is guarded by rcu_read_lock(). + */ +#define hlist_for_each_entry_rcu(tpos, pos, head, member) \ + for (pos = (head)->first; \ + pos && ({ prefetch(pos->next); 1;}) && \ + ({ tpos = hlist_entry(pos, typeof(*tpos), member); 1;}); \ + pos = pos->next, ({ smp_read_barrier_depends(); 0; }) ) + +#endif diff --git a/libiptc/xtables-version.h b/libiptc/xtables-version.h new file mode 100644 index 0000000..ed31ad8 --- /dev/null +++ b/libiptc/xtables-version.h @@ -0,0 +1,2 @@ +#define XTABLES_VERSION "libxtables.so.12" +#define XTABLES_VERSION_CODE 12 diff --git a/libiptc/xtables.h b/libiptc/xtables.h new file mode 100644 index 0000000..c2694b7 --- /dev/null +++ b/libiptc/xtables.h @@ -0,0 +1,674 @@ +#ifndef _XTABLES_H +#define _XTABLES_H + +/* + * Changing any structs/functions may incur a needed change + * in libxtables_vcurrent/vage too. + */ + +#include /* PF_* */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef IPPROTO_SCTP +#define IPPROTO_SCTP 132 +#endif +#ifndef IPPROTO_DCCP +#define IPPROTO_DCCP 33 +#endif +#ifndef IPPROTO_MH +# define IPPROTO_MH 135 +#endif +#ifndef IPPROTO_UDPLITE +#define IPPROTO_UDPLITE 136 +#endif + +#include + +struct in_addr; + +/* + * .size is here so that there is a somewhat reasonable check + * against the chosen .type. + */ +#define XTOPT_POINTER(stype, member) \ + .ptroff = offsetof(stype, member), \ + .size = sizeof(((stype *)NULL)->member) +#define XTOPT_TABLEEND {.name = NULL} + +/** + * Select the format the input has to conform to, as well as the target type + * (area pointed to with XTOPT_POINTER). Note that the storing is not always + * uniform. @cb->val will be populated with as much as there is space, i.e. + * exactly 2 items for ranges, but the target area can receive more values + * (e.g. in case of ranges), or less values (e.g. %XTTYPE_HOSTMASK). + * + * %XTTYPE_NONE: option takes no argument + * %XTTYPE_UINT*: standard integer + * %XTTYPE_UINT*RC: colon-separated range of standard integers + * %XTTYPE_DOUBLE: double-precision floating point number + * %XTTYPE_STRING: arbitrary string + * %XTTYPE_TOSMASK: 8-bit TOS value with optional mask + * %XTTYPE_MARKMASK32: 32-bit mark with optional mask + * %XTTYPE_SYSLOGLEVEL: syslog level by name or number + * %XTTYPE_HOST: one host or address (ptr: union nf_inet_addr) + * %XTTYPE_HOSTMASK: one host or address, with an optional prefix length + * (ptr: union nf_inet_addr; only host portion is stored) + * %XTTYPE_PROTOCOL: protocol number/name from /etc/protocols (ptr: uint8_t) + * %XTTYPE_PORT: 16-bit port name or number (supports %XTOPT_NBO) + * %XTTYPE_PORTRC: colon-separated port range (names acceptable), + * (supports %XTOPT_NBO) + * %XTTYPE_PLEN: prefix length + * %XTTYPE_PLENMASK: prefix length (ptr: union nf_inet_addr) + * %XTTYPE_ETHERMAC: Ethernet MAC address in hex form + */ +enum xt_option_type { + XTTYPE_NONE, + XTTYPE_UINT8, + XTTYPE_UINT16, + XTTYPE_UINT32, + XTTYPE_UINT64, + XTTYPE_UINT8RC, + XTTYPE_UINT16RC, + XTTYPE_UINT32RC, + XTTYPE_UINT64RC, + XTTYPE_DOUBLE, + XTTYPE_STRING, + XTTYPE_TOSMASK, + XTTYPE_MARKMASK32, + XTTYPE_SYSLOGLEVEL, + XTTYPE_HOST, + XTTYPE_HOSTMASK, + XTTYPE_PROTOCOL, + XTTYPE_PORT, + XTTYPE_PORTRC, + XTTYPE_PLEN, + XTTYPE_PLENMASK, + XTTYPE_ETHERMAC, +}; + +/** + * %XTOPT_INVERT: option is invertible (usable with !) + * %XTOPT_MAND: option is mandatory + * %XTOPT_MULTI: option may be specified multiple times + * %XTOPT_PUT: store value into memory at @ptroff + * %XTOPT_NBO: store value in network-byte order + * (only certain XTTYPEs recognize this) + */ +enum xt_option_flags { + XTOPT_INVERT = 1 << 0, + XTOPT_MAND = 1 << 1, + XTOPT_MULTI = 1 << 2, + XTOPT_PUT = 1 << 3, + XTOPT_NBO = 1 << 4, +}; + +/** + * @name: name of option + * @type: type of input and validation method, see %XTTYPE_* + * @id: unique number (within extension) for option, 0-31 + * @excl: bitmask of flags that cannot be used with this option + * @also: bitmask of flags that must be used with this option + * @flags: bitmask of option flags, see %XTOPT_* + * @ptroff: offset into private structure for member + * @size: size of the item pointed to by @ptroff; this is a safeguard + * @min: lowest allowed value (for singular integral types) + * @max: highest allowed value (for singular integral types) + */ +struct xt_option_entry { + const char *name; + enum xt_option_type type; + unsigned int id, excl, also, flags; + unsigned int ptroff; + size_t size; + unsigned int min, max; +}; + +/** + * @arg: input from command line + * @ext_name: name of extension currently being processed + * @entry: current option being processed + * @data: per-extension kernel data block + * @xflags: options of the extension that have been used + * @invert: whether option was used with ! + * @nvals: number of results in uXX_multi + * @val: parsed result + * @udata: per-extension private scratch area + * (cf. xtables_{match,target}->udata_size) + */ +struct xt_option_call { + const char *arg, *ext_name; + const struct xt_option_entry *entry; + void *data; + unsigned int xflags; + bool invert; + uint8_t nvals; + union { + uint8_t u8, u8_range[2], syslog_level, protocol; + uint16_t u16, u16_range[2], port, port_range[2]; + uint32_t u32, u32_range[2]; + uint64_t u64, u64_range[2]; + double dbl; + struct { + union nf_inet_addr haddr, hmask; + uint8_t hlen; + }; + struct { + uint8_t tos_value, tos_mask; + }; + struct { + uint32_t mark, mask; + }; + uint8_t ethermac[6]; + } val; + /* Wished for a world where the ones below were gone: */ + union { + struct xt_entry_match **match; + struct xt_entry_target **target; + }; + void *xt_entry; + void *udata; +}; + +/** + * @ext_name: name of extension currently being processed + * @data: per-extension (kernel) data block + * @udata: per-extension private scratch area + * (cf. xtables_{match,target}->udata_size) + * @xflags: options of the extension that have been used + */ +struct xt_fcheck_call { + const char *ext_name; + void *data, *udata; + unsigned int xflags; +}; + +/** + * A "linear"/linked-list based name<->id map, for files similar to + * /etc/iproute2/. + */ +struct xtables_lmap { + char *name; + int id; + struct xtables_lmap *next; +}; + +enum xtables_ext_flags { + XTABLES_EXT_ALIAS = 1 << 0, +}; + +struct xt_xlate; + +struct xt_xlate_mt_params { + const void *ip; + const struct xt_entry_match *match; + int numeric; + bool escape_quotes; +}; + +struct xt_xlate_tg_params { + const void *ip; + const struct xt_entry_target *target; + int numeric; + bool escape_quotes; +}; + +/* Include file for additions: new matches and targets. */ +struct xtables_match { + /* + * ABI/API version this module requires. Must be first member, + * as the rest of this struct may be subject to ABI changes. + */ + const char *version; + + struct xtables_match *next; + + const char *name; + const char *real_name; + + /* Revision of match (0 by default). */ + uint8_t revision; + + /* Extension flags */ + uint8_t ext_flags; + + uint16_t family; + + /* Size of match data. */ + size_t size; + + /* Size of match data relevant for userspace comparison purposes */ + size_t userspacesize; + + /* Function which prints out usage message. */ + void (*help)(void); + + /* Initialize the match. */ + void (*init)(struct xt_entry_match *m); + + /* Function which parses command options; returns true if it + ate an option */ + /* entry is struct ipt_entry for example */ + int (*parse)(int c, char **argv, int invert, unsigned int *flags, + const void *entry, + struct xt_entry_match **match); + + /* Final check; exit if not ok. */ + void (*final_check)(unsigned int flags); + + /* Prints out the match iff non-NULL: put space at end */ + /* ip is struct ipt_ip * for example */ + void (*print)(const void *ip, + const struct xt_entry_match *match, int numeric); + + /* Saves the match info in parsable form to stdout. */ + /* ip is struct ipt_ip * for example */ + void (*save)(const void *ip, const struct xt_entry_match *match); + + /* Print match name or alias */ + const char *(*alias)(const struct xt_entry_match *match); + + /* Pointer to list of extra command-line options */ + const struct option *extra_opts; + + /* New parser */ + void (*x6_parse)(struct xt_option_call *); + void (*x6_fcheck)(struct xt_fcheck_call *); + const struct xt_option_entry *x6_options; + + /* Translate iptables to nft */ + int (*xlate)(struct xt_xlate *xl, + const struct xt_xlate_mt_params *params); + + /* Size of per-extension instance extra "global" scratch space */ + size_t udata_size; + + /* Ignore these men behind the curtain: */ + void *udata; + unsigned int option_offset; + struct xt_entry_match *m; + unsigned int mflags; + unsigned int loaded; /* simulate loading so options are merged properly */ +}; + +struct xtables_target { + /* + * ABI/API version this module requires. Must be first member, + * as the rest of this struct may be subject to ABI changes. + */ + const char *version; + + struct xtables_target *next; + + + const char *name; + + /* Real target behind this, if any. */ + const char *real_name; + + /* Revision of target (0 by default). */ + uint8_t revision; + + /* Extension flags */ + uint8_t ext_flags; + + uint16_t family; + + + /* Size of target data. */ + size_t size; + + /* Size of target data relevant for userspace comparison purposes */ + size_t userspacesize; + + /* Function which prints out usage message. */ + void (*help)(void); + + /* Initialize the target. */ + void (*init)(struct xt_entry_target *t); + + /* Function which parses command options; returns true if it + ate an option */ + /* entry is struct ipt_entry for example */ + int (*parse)(int c, char **argv, int invert, unsigned int *flags, + const void *entry, + struct xt_entry_target **targetinfo); + + /* Final check; exit if not ok. */ + void (*final_check)(unsigned int flags); + + /* Prints out the target iff non-NULL: put space at end */ + void (*print)(const void *ip, + const struct xt_entry_target *target, int numeric); + + /* Saves the targinfo in parsable form to stdout. */ + void (*save)(const void *ip, + const struct xt_entry_target *target); + + /* Print target name or alias */ + const char *(*alias)(const struct xt_entry_target *target); + + /* Pointer to list of extra command-line options */ + const struct option *extra_opts; + + /* New parser */ + void (*x6_parse)(struct xt_option_call *); + void (*x6_fcheck)(struct xt_fcheck_call *); + const struct xt_option_entry *x6_options; + + /* Translate iptables to nft */ + int (*xlate)(struct xt_xlate *xl, + const struct xt_xlate_tg_params *params); + + size_t udata_size; + + /* Ignore these men behind the curtain: */ + void *udata; + unsigned int option_offset; + struct xt_entry_target *t; + unsigned int tflags; + unsigned int used; + unsigned int loaded; /* simulate loading so options are merged properly */ +}; + +struct xtables_rule_match { + struct xtables_rule_match *next; + struct xtables_match *match; + /* Multiple matches of the same type: the ones before + the current one are completed from parsing point of view */ + bool completed; +}; + +/** + * struct xtables_pprot - + * + * A few hardcoded protocols for 'all' and in case the user has no + * /etc/protocols. + */ +struct xtables_pprot { + const char *name; + uint8_t num; +}; + +enum xtables_tryload { + XTF_DONT_LOAD, + XTF_DURING_LOAD, + XTF_TRY_LOAD, + XTF_LOAD_MUST_SUCCEED, +}; + +enum xtables_exittype { + OTHER_PROBLEM = 1, + PARAMETER_PROBLEM, + VERSION_PROBLEM, + RESOURCE_PROBLEM, + XTF_ONLY_ONCE, + XTF_NO_INVERT, + XTF_BAD_VALUE, + XTF_ONE_ACTION, +}; + +struct xtables_globals +{ + unsigned int option_offset; + const char *program_name, *program_version; + struct option *orig_opts; + struct option *opts; + void (*exit_err)(enum xtables_exittype status, const char *msg, ...) __attribute__((noreturn, format(printf,2,3))); + int (*compat_rev)(const char *name, uint8_t rev, int opt); +}; + +#define XT_GETOPT_TABLEEND {.name = NULL, .has_arg = false} + +/* + * enum op- + * + * For writing clean nftables translations code + */ +enum xt_op { + XT_OP_EQ, + XT_OP_NEQ, + XT_OP_MAX, +}; + +#ifdef __cplusplus +extern "C" { +#endif + +extern const char *xtables_modprobe_program; +extern struct xtables_match *xtables_matches; +extern struct xtables_target *xtables_targets; + +extern void xtables_init(void); +extern void xtables_fini(void); +extern void xtables_set_nfproto(uint8_t); +extern void *xtables_calloc(size_t, size_t); +extern void *xtables_malloc(size_t); +extern void *xtables_realloc(void *, size_t); +char *xtables_strdup(const char *); + +extern int xtables_insmod(const char *, const char *, bool); +extern int xtables_load_ko(const char *, bool); +extern int xtables_set_params(struct xtables_globals *xtp); +extern void xtables_free_opts(int reset_offset); +extern struct option *xtables_merge_options(struct option *origopts, + struct option *oldopts, const struct option *newopts, + unsigned int *option_offset); + +extern int xtables_init_all(struct xtables_globals *xtp, uint8_t nfproto); +extern struct xtables_match *xtables_find_match(const char *name, + enum xtables_tryload, struct xtables_rule_match **match); +extern struct xtables_match *xtables_find_match_revision(const char *name, + enum xtables_tryload tryload, struct xtables_match *match, + int revision); +extern struct xtables_target *xtables_find_target(const char *name, + enum xtables_tryload); +struct xtables_target *xtables_find_target_revision(const char *name, + enum xtables_tryload tryload, struct xtables_target *target, + int revision); +extern int xtables_compatible_revision(const char *name, uint8_t revision, + int opt); + +extern void xtables_rule_matches_free(struct xtables_rule_match **matches); + +/* Your shared library should call one of these. */ +extern void xtables_register_match(struct xtables_match *me); +extern void xtables_register_matches(struct xtables_match *, unsigned int); +extern void xtables_register_target(struct xtables_target *me); +extern void xtables_register_targets(struct xtables_target *, unsigned int); + +extern bool xtables_strtoul(const char *, char **, uintmax_t *, + uintmax_t, uintmax_t); +extern bool xtables_strtoui(const char *, char **, unsigned int *, + unsigned int, unsigned int); +extern int xtables_service_to_port(const char *name, const char *proto); +extern uint16_t xtables_parse_port(const char *port, const char *proto); +extern void +xtables_parse_interface(const char *arg, char *vianame, unsigned char *mask); + +/* this is a special 64bit data type that is 8-byte aligned */ +#define aligned_u64 uint64_t __attribute__((aligned(8))) + +extern struct xtables_globals *xt_params; +#define xtables_error (xt_params->exit_err) + +extern void xtables_param_act(unsigned int, const char *, ...); + +extern const char *xtables_ipaddr_to_numeric(const struct in_addr *); +extern const char *xtables_ipaddr_to_anyname(const struct in_addr *); +extern const char *xtables_ipmask_to_numeric(const struct in_addr *); +extern struct in_addr *xtables_numeric_to_ipaddr(const char *); +extern struct in_addr *xtables_numeric_to_ipmask(const char *); +extern int xtables_ipmask_to_cidr(const struct in_addr *); +extern void xtables_ipparse_any(const char *, struct in_addr **, + struct in_addr *, unsigned int *); +extern void xtables_ipparse_multiple(const char *, struct in_addr **, + struct in_addr **, unsigned int *); + +extern struct in6_addr *xtables_numeric_to_ip6addr(const char *); +extern const char *xtables_ip6addr_to_numeric(const struct in6_addr *); +extern const char *xtables_ip6addr_to_anyname(const struct in6_addr *); +extern const char *xtables_ip6mask_to_numeric(const struct in6_addr *); +extern int xtables_ip6mask_to_cidr(const struct in6_addr *); +extern void xtables_ip6parse_any(const char *, struct in6_addr **, + struct in6_addr *, unsigned int *); +extern void xtables_ip6parse_multiple(const char *, struct in6_addr **, + struct in6_addr **, unsigned int *); + +/* Absolute file name for network data base files. */ +#define XT_PATH_ETHERTYPES "/etc/ethertypes" + +struct xt_ethertypeent { + char *e_name; /* Official ethernet type name. */ + char **e_aliases; /* Alias list. */ + int e_ethertype; /* Ethernet type number. */ +}; + +extern struct xt_ethertypeent *xtables_getethertypebyname(const char *name); +extern struct xt_ethertypeent *xtables_getethertypebynumber(int ethertype); + +/** + * Print the specified value to standard output, quoting dangerous + * characters if required. + */ +extern void xtables_save_string(const char *value); + +#define FMT_NUMERIC 0x0001 +#define FMT_NOCOUNTS 0x0002 +#define FMT_KILOMEGAGIGA 0x0004 +#define FMT_OPTIONS 0x0008 +#define FMT_NOTABLE 0x0010 +#define FMT_NOTARGET 0x0020 +#define FMT_VIA 0x0040 +#define FMT_NONEWLINE 0x0080 +#define FMT_LINENUMBERS 0x0100 +#define FMT_EBT_SAVE 0x0200 +#define FMT_C_COUNTS 0x0400 + +#define FMT_PRINT_RULE (FMT_NOCOUNTS | FMT_OPTIONS | FMT_VIA \ + | FMT_NUMERIC | FMT_NOTABLE) +#define FMT(tab,notab) ((format) & FMT_NOTABLE ? (notab) : (tab)) + +extern void xtables_print_num(uint64_t number, unsigned int format); +extern int xtables_parse_mac_and_mask(const char *from, void *to, void *mask); +extern int xtables_print_well_known_mac_and_mask(const void *mac, + const void *mask); +extern void xtables_print_mac(const unsigned char *macaddress); +extern void xtables_print_mac_and_mask(const unsigned char *mac, + const unsigned char *mask); + +extern void xtables_parse_val_mask(struct xt_option_call *cb, + unsigned int *val, unsigned int *mask, + const struct xtables_lmap *lmap); + +static inline void xtables_parse_mark_mask(struct xt_option_call *cb, + unsigned int *mark, + unsigned int *mask) +{ + xtables_parse_val_mask(cb, mark, mask, NULL); +} + +extern void xtables_print_val_mask(unsigned int val, unsigned int mask, + const struct xtables_lmap *lmap); + +static inline void xtables_print_mark_mask(unsigned int mark, + unsigned int mask) +{ + xtables_print_val_mask(mark, mask, NULL); +} + +#if defined(ALL_INCLUSIVE) || defined(NO_SHARED_LIBS) +# ifdef _INIT +# undef _init +# define _init _INIT +# endif + extern void init_extensions(void); + extern void init_extensions4(void); + extern void init_extensions6(void); + extern void init_extensionsa(void); + extern void init_extensionsb(void); +#else +# define _init __attribute__((constructor)) _INIT +# define EMPTY_FUNC_DEF(x) static inline void x(void) {} + EMPTY_FUNC_DEF(init_extensions) + EMPTY_FUNC_DEF(init_extensions4) + EMPTY_FUNC_DEF(init_extensions6) + EMPTY_FUNC_DEF(init_extensionsa) + EMPTY_FUNC_DEF(init_extensionsb) +# undef EMPTY_FUNC_DEF +#endif + +extern const struct xtables_pprot xtables_chain_protos[]; +extern uint16_t xtables_parse_protocol(const char *s); + +/* kernel revision handling */ +extern int kernel_version; +extern void get_kernel_version(void); +#define LINUX_VERSION(x,y,z) (0x10000*(x) + 0x100*(y) + z) +#define LINUX_VERSION_MAJOR(x) (((x)>>16) & 0xFF) +#define LINUX_VERSION_MINOR(x) (((x)>> 8) & 0xFF) +#define LINUX_VERSION_PATCH(x) ( (x) & 0xFF) + +/* xtoptions.c */ +extern void xtables_option_metavalidate(const char *, + const struct xt_option_entry *); +extern struct option *xtables_options_xfrm(struct option *, struct option *, + const struct xt_option_entry *, + unsigned int *); +extern void xtables_option_parse(struct xt_option_call *); +extern void xtables_option_tpcall(unsigned int, char **, bool, + struct xtables_target *, void *); +extern void xtables_option_mpcall(unsigned int, char **, bool, + struct xtables_match *, void *); +extern void xtables_option_tfcall(struct xtables_target *); +extern void xtables_option_mfcall(struct xtables_match *); +extern void xtables_options_fcheck(const char *, unsigned int, + const struct xt_option_entry *); + +extern struct xtables_lmap *xtables_lmap_init(const char *); +extern void xtables_lmap_free(struct xtables_lmap *); +extern int xtables_lmap_name2id(const struct xtables_lmap *, const char *); +extern const char *xtables_lmap_id2name(const struct xtables_lmap *, int); + +/* xlate infrastructure */ +struct xt_xlate *xt_xlate_alloc(int size); +void xt_xlate_free(struct xt_xlate *xl); +void xt_xlate_add(struct xt_xlate *xl, const char *fmt, ...) __attribute__((format(printf,2,3))); +#define xt_xlate_rule_add xt_xlate_add +void xt_xlate_set_add(struct xt_xlate *xl, const char *fmt, ...) __attribute__((format(printf,2,3))); +void xt_xlate_add_comment(struct xt_xlate *xl, const char *comment); +const char *xt_xlate_get_comment(struct xt_xlate *xl); +void xl_xlate_set_family(struct xt_xlate *xl, uint8_t family); +uint8_t xt_xlate_get_family(struct xt_xlate *xl); +const char *xt_xlate_get(struct xt_xlate *xl); +#define xt_xlate_rule_get xt_xlate_get +const char *xt_xlate_set_get(struct xt_xlate *xl); + +/* informed target lookups */ +void xtables_announce_chain(const char *name); + +#ifdef XTABLES_INTERNAL + +/* Shipped modules rely on this... */ + +# ifndef ARRAY_SIZE +# define ARRAY_SIZE(x) (sizeof(x) / sizeof(*(x))) +# endif + +extern void _init(void); + +#endif + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +#endif /* _XTABLES_H */ diff --git a/rhost.c b/rhost.c index 50674df..fa7e1fd 100644 --- a/rhost.c +++ b/rhost.c @@ -213,6 +213,30 @@ int whitelist(char *client_ip, char (*whitelist_ip)[WHITELIST_IP_NUM]) return 0; } +// 地域段白名单对比 +int isregion(char *str, char (*region_list)[WHITELIST_IP_NUM]) +{ + int i; + char *p; + + for (i = 1; i < WHITELIST_IP_NUM - 1; i++) { + if (strcmp(region_list[i], "\0") == 0) { // 如果字符串为空就跳出循环 + break; + } + + // 在str中查找region_list[i] + p = strstr(str, region_list[i]); + if (p != NULL) + { + return 1; + } + + } + + return 0; +} + +// 去除空格 char *remove_space(const char *str) { unsigned int uLen = strlen(str); @@ -243,6 +267,8 @@ int rule(conf * conf) { int i; char whitelist_ip[WHITELIST_IP_NUM][WHITELIST_IP_NUM] = { { 0 }, { 0 } }; + char region_list[WHITELIST_IP_NUM][WHITELIST_IP_NUM] = { { 0 }, { 0 } }; + char p[2], splice_command[LONG_BUFFER], command[LONG_BUFFER], *temp, buffer[BUFFER], awk[BUFFER]; FILE *fp, *fc; time_t timep; @@ -299,6 +325,7 @@ int rule(conf * conf) strcat(splice_command, "\n"); } } + printf("%s", splice_command); // 打印所有非法IP @@ -320,16 +347,31 @@ int rule(conf * conf) split_string(conf->IPV4_WHITE_LIST, " ", whitelist_ip); + split_string(conf->REGION_LIST, " ", region_list); + + + // 打印配置 for (i = 1; i <= WHITELIST_IP_NUM - 1; i++) { - if (*whitelist_ip[i] != '\0') ; + if (*whitelist_ip[i] != '\0') { + ; //printf("%s\n", whitelist_ip[i]); + } } - if (conf->IPV4_RESTRICTION == 1) { // 是否启用百名单 + for (i = 1; i <= WHITELIST_IP_NUM - 1; i++) { + if (*region_list[i] != '\0') { + ; + //printf("%s\n", region_list[i]); + } + } + + + + if (conf->IPV4_RESTRICTION == 1) { // 是否启用白名单 if (whitelist(buffer, whitelist_ip) == 1) { ; - //printf("白名单IPV4:%s\n", buffer); + printf("白名单IPV4:%s\n", buffer); continue; } @@ -350,22 +392,18 @@ int rule(conf * conf) if (NULL == location_json) { printf("获取IP位置错误!\n"); + + goto BLOCKED; } else { - //printf("%s\n", location_json); - char temp[BUFFER]; - memset(temp, 0, BUFFER); - char *p = strstr(location_json, "\"location\""); char *p1 = strstr(p, "\","); - - - memcpy(temp, p+12, p1-p-12); - - location = remove_space(temp); + memset(temp, 0, BUFFER); + memcpy(temp, p+12, p1-p-12); + location = remove_space(temp); } memset(iplocation, 0, BUFFER); @@ -373,7 +411,24 @@ int rule(conf * conf) strcat(iplocation, "("); strcat(iplocation, location); strcat(iplocation, ")"); - //printf("%s\n", iplocation); + + + + // 地域白名单 + if (conf->REGION == 1) + { + if (isregion(iplocation, region_list) == 1) + { + ; + printf("地域白名单: %s\n", iplocation); + + continue; + } + + } + + + if (conf->IS_DING_WEBHOOK == 1) // 钉钉告警 { @@ -393,7 +448,7 @@ int rule(conf * conf) sleep(3); } - +BLOCKED: // 是否封禁攻击IP if (conf->IS_BLOCKED == 1) { // libiptc 库插入规则 iptables -t filter -A INPUT -p tcp -m tcp -s xxxx -j DROP diff --git a/rhost.conf b/rhost.conf index b834b6d..3df175e 100644 --- a/rhost.conf +++ b/rhost.conf @@ -7,11 +7,16 @@ global { IPV4_RESTRICTION = 1; // 是否启用百名单 - IPV4_WHITE_LIST = "1.193.37.156 117.158.215.217"; // IP白名单 + IPV4_WHITE_LIST = "1.1.1.1 "; // IP白名单 + + + REGION = 1; // 是否启用地域白名单 + REGION_LIST = "河南 郑州"; // 地域列表 + IS_BLOCKED = 1; // 是否封禁攻击IP - REFUSE_NUMBER = 5; // 拒绝攻击次数 + REFUSE_NUMBER = 3; // 拒绝攻击次数 IS_MAIL = 0; // 开启邮件告警