xref: /aosp_15_r20/external/iptables/libiptc/libiptc.c (revision a71a954618bbadd4a345637e5edcf36eec826889)
1 /* Library which manipulates firewall rules.  Version $Revision$ */
2 
3 /* Architecture of firewall rules is as follows:
4  *
5  * Chains go INPUT, FORWARD, OUTPUT then user chains.
6  * Each user chain starts with an ERROR node.
7  * Every chain ends with an unconditional jump: a RETURN for user chains,
8  * and a POLICY for built-ins.
9  */
10 
11 /* (C) 1999 Paul ``Rusty'' Russell - Placed under the GNU GPL (See
12  * COPYING for details).
13  * (C) 2000-2004 by the Netfilter Core Team <[email protected]>
14  *
15  * 2003-Jun-20: Harald Welte <[email protected]>:
16  *	- Reimplementation of chain cache to use offsets instead of entries
17  * 2003-Jun-23: Harald Welte <[email protected]>:
18  * 	- performance optimization, sponsored by Astaro AG (http://www.astaro.com/)
19  * 	  don't rebuild the chain cache after every operation, instead fix it
20  * 	  up after a ruleset change.
21  * 2004-Aug-18: Harald Welte <[email protected]>:
22  * 	- further performance work: total reimplementation of libiptc.
23  * 	- libiptc now has a real internal (linked-list) represntation of the
24  * 	  ruleset and a parser/compiler from/to this internal representation
25  * 	- again sponsored by Astaro AG (http://www.astaro.com/)
26  *
27  * 2008-Jan+Jul: Jesper Dangaard Brouer <[email protected]>
28  * 	- performance work: speedup chain list "name" searching.
29  * 	- performance work: speedup initial ruleset parsing.
30  * 	- sponsored by ComX Networks A/S (http://www.comx.dk/)
31  */
32 #include <unistd.h>
33 #include <fcntl.h>
34 #include <sys/types.h>
35 #include <sys/socket.h>
36 #include <stdbool.h>
37 #include <xtables.h>
38 #include <libiptc/xtcshared.h>
39 
40 #include "linux_list.h"
41 
42 //#define IPTC_DEBUG2 1
43 
44 #ifdef IPTC_DEBUG2
45 #include <fcntl.h>
46 #define DEBUGP(x, args...)	fprintf(stderr, "%s: " x, __FUNCTION__, ## args)
47 #define DEBUGP_C(x, args...)	fprintf(stderr, x, ## args)
48 #else
49 #define DEBUGP(x, args...)
50 #define DEBUGP_C(x, args...)
51 #endif
52 
53 #ifdef DEBUG
54 #define debug(x, args...)	fprintf(stderr, x, ## args)
55 #else
56 #define debug(x, args...)
57 #endif
58 
59 static void *iptc_fn = NULL;
60 
61 static const char *hooknames[] = {
62 	[HOOK_PRE_ROUTING]	= "PREROUTING",
63 	[HOOK_LOCAL_IN]		= "INPUT",
64 	[HOOK_FORWARD]		= "FORWARD",
65 	[HOOK_LOCAL_OUT]	= "OUTPUT",
66 	[HOOK_POST_ROUTING]	= "POSTROUTING",
67 };
68 
69 /* Convenience structures */
70 struct chain_head;
71 struct rule_head;
72 
73 struct counter_map
74 {
75 	enum {
76 		COUNTER_MAP_NOMAP,
77 		COUNTER_MAP_NORMAL_MAP,
78 		COUNTER_MAP_ZEROED,
79 		COUNTER_MAP_SET
80 	} maptype;
81 	unsigned int mappos;
82 };
83 
84 enum iptcc_rule_type {
85 	IPTCC_R_STANDARD,		/* standard target (ACCEPT, ...) */
86 	IPTCC_R_MODULE,			/* extension module (SNAT, ...) */
87 	IPTCC_R_FALLTHROUGH,		/* fallthrough rule */
88 	IPTCC_R_JUMP,			/* jump to other chain */
89 };
90 
91 struct rule_head
92 {
93 	struct list_head list;
94 	struct chain_head *chain;
95 	struct counter_map counter_map;
96 
97 	unsigned int index;		/* index (needed for counter_map) */
98 	unsigned int offset;		/* offset in rule blob */
99 
100 	enum iptcc_rule_type type;
101 	struct chain_head *jump;	/* jump target, if IPTCC_R_JUMP */
102 
103 	unsigned int size;		/* size of entry data */
104 	STRUCT_ENTRY entry[0];
105 };
106 
107 struct chain_head
108 {
109 	struct list_head list;
110 	char name[TABLE_MAXNAMELEN];
111 	unsigned int hooknum;		/* hook number+1 if builtin */
112 	unsigned int references;	/* how many jumps reference us */
113 	int verdict;			/* verdict if builtin */
114 
115 	STRUCT_COUNTERS counters;	/* per-chain counters */
116 	struct counter_map counter_map;
117 
118 	unsigned int num_rules;		/* number of rules in list */
119 	struct list_head rules;		/* list of rules */
120 
121 	unsigned int index;		/* index (needed for jump resolval) */
122 	unsigned int head_offset;	/* offset in rule blob */
123 	unsigned int foot_index;	/* index (needed for counter_map) */
124 	unsigned int foot_offset;	/* offset in rule blob */
125 };
126 
127 struct xtc_handle {
128 	int sockfd;
129 	int changed;			 /* Have changes been made? */
130 
131 	struct list_head chains;
132 
133 	struct chain_head *chain_iterator_cur;
134 	struct rule_head *rule_iterator_cur;
135 
136 	unsigned int num_chains;         /* number of user defined chains */
137 
138 	struct chain_head **chain_index;   /* array for fast chain list access*/
139 	unsigned int        chain_index_sz;/* size of chain index array */
140 
141 	int sorted_offsets; /* if chains are received sorted from kernel,
142 			     * then the offsets are also sorted. Says if its
143 			     * possible to bsearch offsets using chain_index.
144 			     */
145 
146 	STRUCT_GETINFO info;
147 	STRUCT_GET_ENTRIES *entries;
148 };
149 
150 enum bsearch_type {
151 	BSEARCH_NAME,	/* Binary search after chain name */
152 	BSEARCH_OFFSET,	/* Binary search based on offset */
153 };
154 
155 /* allocate a new chain head for the cache */
iptcc_alloc_chain_head(const char * name,int hooknum)156 static struct chain_head *iptcc_alloc_chain_head(const char *name, int hooknum)
157 {
158 	struct chain_head *c = malloc(sizeof(*c));
159 	if (!c)
160 		return NULL;
161 	memset(c, 0, sizeof(*c));
162 
163 	strncpy(c->name, name, TABLE_MAXNAMELEN - 1);
164 	c->hooknum = hooknum;
165 	INIT_LIST_HEAD(&c->rules);
166 
167 	return c;
168 }
169 
170 /* allocate and initialize a new rule for the cache */
iptcc_alloc_rule(struct chain_head * c,unsigned int size)171 static struct rule_head *iptcc_alloc_rule(struct chain_head *c, unsigned int size)
172 {
173 	struct rule_head *r = malloc(sizeof(*r)+size);
174 	if (!r)
175 		return NULL;
176 	memset(r, 0, sizeof(*r));
177 
178 	r->chain = c;
179 	r->size = size;
180 
181 	return r;
182 }
183 
184 /* notify us that the ruleset has been modified by the user */
185 static inline void
set_changed(struct xtc_handle * h)186 set_changed(struct xtc_handle *h)
187 {
188 	h->changed = 1;
189 }
190 
191 /**********************************************************************
192  * iptc blob utility functions (iptcb_*)
193  **********************************************************************/
194 
195 static inline int
iptcb_get_number(const STRUCT_ENTRY * i,const STRUCT_ENTRY * seek,unsigned int * pos)196 iptcb_get_number(const STRUCT_ENTRY *i,
197 	   const STRUCT_ENTRY *seek,
198 	   unsigned int *pos)
199 {
200 	if (i == seek)
201 		return 1;
202 	(*pos)++;
203 	return 0;
204 }
205 
206 static inline int
iptcb_get_entry_n(STRUCT_ENTRY * i,unsigned int number,unsigned int * pos,STRUCT_ENTRY ** pe)207 iptcb_get_entry_n(STRUCT_ENTRY *i,
208 	    unsigned int number,
209 	    unsigned int *pos,
210 	    STRUCT_ENTRY **pe)
211 {
212 	if (*pos == number) {
213 		*pe = i;
214 		return 1;
215 	}
216 	(*pos)++;
217 	return 0;
218 }
219 
220 static inline STRUCT_ENTRY *
iptcb_get_entry(struct xtc_handle * h,unsigned int offset)221 iptcb_get_entry(struct xtc_handle *h, unsigned int offset)
222 {
223 	return (STRUCT_ENTRY *)((char *)h->entries->entrytable + offset);
224 }
225 
226 static unsigned int
iptcb_entry2index(struct xtc_handle * const h,const STRUCT_ENTRY * seek)227 iptcb_entry2index(struct xtc_handle *const h, const STRUCT_ENTRY *seek)
228 {
229 	unsigned int pos = 0;
230 
231 	if (ENTRY_ITERATE(h->entries->entrytable, h->entries->size,
232 			  iptcb_get_number, seek, &pos) == 0) {
233 		fprintf(stderr, "ERROR: offset %u not an entry!\n",
234 			(unsigned int)((char *)seek - (char *)h->entries->entrytable));
235 		abort();
236 	}
237 	return pos;
238 }
239 
240 static inline STRUCT_ENTRY *
iptcb_offset2entry(struct xtc_handle * h,unsigned int offset)241 iptcb_offset2entry(struct xtc_handle *h, unsigned int offset)
242 {
243 	return (STRUCT_ENTRY *) ((void *)h->entries->entrytable+offset);
244 }
245 
246 
247 static inline unsigned long
iptcb_entry2offset(struct xtc_handle * const h,const STRUCT_ENTRY * e)248 iptcb_entry2offset(struct xtc_handle *const h, const STRUCT_ENTRY *e)
249 {
250 	return (void *)e - (void *)h->entries->entrytable;
251 }
252 
253 static inline unsigned int
iptcb_offset2index(struct xtc_handle * const h,unsigned int offset)254 iptcb_offset2index(struct xtc_handle *const h, unsigned int offset)
255 {
256 	return iptcb_entry2index(h, iptcb_offset2entry(h, offset));
257 }
258 
259 /* Returns 0 if not hook entry, else hooknumber + 1 */
260 static inline unsigned int
iptcb_ent_is_hook_entry(STRUCT_ENTRY * e,struct xtc_handle * h)261 iptcb_ent_is_hook_entry(STRUCT_ENTRY *e, struct xtc_handle *h)
262 {
263 	unsigned int i;
264 
265 	for (i = 0; i < NUMHOOKS; i++) {
266 		if ((h->info.valid_hooks & (1 << i))
267 		    && iptcb_get_entry(h, h->info.hook_entry[i]) == e)
268 			return i+1;
269 	}
270 	return 0;
271 }
272 
273 
274 /**********************************************************************
275  * Chain index (cache utility) functions
276  **********************************************************************
277  * The chain index is an array with pointers into the chain list, with
278  * CHAIN_INDEX_BUCKET_LEN spacing.  This facilitates the ability to
279  * speedup chain list searching, by find a more optimal starting
280  * points when searching the linked list.
281  *
282  * The starting point can be found fast by using a binary search of
283  * the chain index. Thus, reducing the previous search complexity of
284  * O(n) to O(log(n/k) + k) where k is CHAIN_INDEX_BUCKET_LEN.
285  *
286  * A nice property of the chain index, is that the "bucket" list
287  * length is max CHAIN_INDEX_BUCKET_LEN (when just build, inserts will
288  * change this). Oppose to hashing, where the "bucket" list length can
289  * vary a lot.
290  */
291 #ifndef CHAIN_INDEX_BUCKET_LEN
292 #define CHAIN_INDEX_BUCKET_LEN 40
293 #endif
294 
295 /* Another nice property of the chain index is that inserting/creating
296  * chains in chain list don't change the correctness of the chain
297  * index, it only causes longer lists in the buckets.
298  *
299  * To mitigate the performance penalty of longer bucket lists and the
300  * penalty of rebuilding, the chain index is rebuild only when
301  * CHAIN_INDEX_INSERT_MAX chains has been added.
302  */
303 #ifndef CHAIN_INDEX_INSERT_MAX
304 #define CHAIN_INDEX_INSERT_MAX 355
305 #endif
306 
307 static inline unsigned int iptcc_is_builtin(struct chain_head *c);
308 
309 /* Use binary search in the chain index array, to find a chain_head
310  * pointer closest to the place of the searched name element.
311  *
312  * Notes that, binary search (obviously) requires that the chain list
313  * is sorted by name.
314  *
315  * The not so obvious: The chain index array, is actually both sorted
316  * by name and offset, at the same time!.  This is only true because,
317  * chain are stored sorted in the kernel (as we pushed it in sorted).
318  *
319  */
320 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)321 __iptcc_bsearch_chain_index(const char *name, unsigned int offset,
322 			    unsigned int *idx, struct xtc_handle *handle,
323 			    enum bsearch_type type)
324 {
325 	unsigned int pos, end;
326 	int res;
327 
328 	struct list_head *list_pos;
329 	list_pos=&handle->chains;
330 
331 	/* Check for empty array, e.g. no user defined chains */
332 	if (handle->chain_index_sz == 0) {
333 		debug("WARNING: handle->chain_index_sz == 0\n");
334 		return list_pos;
335 	}
336 
337 	/* Init */
338 	end = handle->chain_index_sz;
339 	pos = end / 2;
340 
341 	debug("bsearch Find chain:%s (pos:%d end:%d) (offset:%d)\n",
342 	      name, pos, end, offset);
343 
344 	/* Loop */
345  loop:
346 	if (!handle->chain_index[pos]) {
347 		fprintf(stderr, "ERROR: NULL pointer chain_index[%d]\n", pos);
348 		return &handle->chains; /* Be safe, return orig start pos */
349 	}
350 
351 	debug("bsearch Index[%d] name:%s ",
352 	      pos, handle->chain_index[pos]->name);
353 
354 	/* Support for different compare functions */
355 	switch (type) {
356 	case BSEARCH_NAME:
357 		res = strcmp(name, handle->chain_index[pos]->name);
358 		break;
359 	case BSEARCH_OFFSET:
360 		debug("head_offset:[%d] foot_offset:[%d] ",
361 		      handle->chain_index[pos]->head_offset,
362 		      handle->chain_index[pos]->foot_offset);
363 		res = offset - handle->chain_index[pos]->head_offset;
364 		break;
365 	default:
366 		fprintf(stderr, "ERROR: %d not a valid bsearch type\n",
367 			type);
368 		abort();
369 		break;
370 	}
371 	debug("res:%d ", res);
372 
373 
374 	list_pos = &handle->chain_index[pos]->list;
375 	*idx = pos;
376 
377 	if (res == 0) { /* Found element, by direct hit */
378 		debug("[found] Direct hit pos:%d end:%d\n", pos, end);
379 		return list_pos;
380 	} else if (res < 0) { /* Too far, jump back */
381 		end = pos;
382 		pos = pos / 2;
383 
384 		/* Exit case: First element of array */
385 		if (end == 0) {
386 			debug("[found] Reached first array elem (end%d)\n",end);
387 			return list_pos;
388 		}
389 		debug("jump back to pos:%d (end:%d)\n", pos, end);
390 		goto loop;
391 	} else { /* res > 0; Not far enough, jump forward */
392 
393 		/* Exit case: Last element of array */
394 		if (pos == handle->chain_index_sz-1) {
395 			debug("[found] Last array elem (end:%d)\n", end);
396 			return list_pos;
397 		}
398 
399 		/* Exit case: Next index less, thus elem in this list section */
400 		switch (type) {
401 		case BSEARCH_NAME:
402 			res = strcmp(name, handle->chain_index[pos+1]->name);
403 			break;
404 		case BSEARCH_OFFSET:
405 			res = offset - handle->chain_index[pos+1]->head_offset;
406 			break;
407 		}
408 
409 		if (res < 0) {
410 			debug("[found] closest list (end:%d)\n", end);
411 			return list_pos;
412 		}
413 
414 		pos = (pos+end)/2;
415 		debug("jump forward to pos:%d (end:%d)\n", pos, end);
416 		goto loop;
417 	}
418 }
419 
420 /* Wrapper for string chain name based bsearch */
421 static struct list_head *
iptcc_bsearch_chain_index(const char * name,unsigned int * idx,struct xtc_handle * handle)422 iptcc_bsearch_chain_index(const char *name, unsigned int *idx,
423 			  struct xtc_handle *handle)
424 {
425 	return __iptcc_bsearch_chain_index(name, 0, idx, handle, BSEARCH_NAME);
426 }
427 
428 
429 /* Wrapper for offset chain based bsearch */
430 static struct list_head *
iptcc_bsearch_chain_offset(unsigned int offset,unsigned int * idx,struct xtc_handle * handle)431 iptcc_bsearch_chain_offset(unsigned int offset, unsigned int *idx,
432 			  struct xtc_handle *handle)
433 {
434 	struct list_head *pos;
435 
436 	/* If chains were not received sorted from kernel, then the
437 	 * offset bsearch is not possible.
438 	 */
439 	if (!handle->sorted_offsets)
440 		pos = handle->chains.next;
441 	else
442 		pos = __iptcc_bsearch_chain_index(NULL, offset, idx, handle,
443 						  BSEARCH_OFFSET);
444 	return pos;
445 }
446 
447 
448 #ifdef DEBUG
449 /* Trivial linear search of chain index. Function used for verifying
450    the output of bsearch function */
451 static struct list_head *
iptcc_linearly_search_chain_index(const char * name,struct xtc_handle * handle)452 iptcc_linearly_search_chain_index(const char *name, struct xtc_handle *handle)
453 {
454 	unsigned int i=0;
455 	int res=0;
456 
457 	struct list_head *list_pos;
458 	list_pos = &handle->chains;
459 
460 	if (handle->chain_index_sz)
461 		list_pos = &handle->chain_index[0]->list;
462 
463 	/* Linearly walk of chain index array */
464 
465 	for (i=0; i < handle->chain_index_sz; i++) {
466 		if (handle->chain_index[i]) {
467 			res = strcmp(handle->chain_index[i]->name, name);
468 			if (res > 0)
469 				break; // One step too far
470 			list_pos = &handle->chain_index[i]->list;
471 			if (res == 0)
472 				break; // Direct hit
473 		}
474 	}
475 
476 	return list_pos;
477 }
478 #endif
479 
iptcc_chain_index_alloc(struct xtc_handle * h)480 static int iptcc_chain_index_alloc(struct xtc_handle *h)
481 {
482 	unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
483 	unsigned int array_elems;
484 	unsigned int array_mem;
485 
486 	/* Allocate memory for the chain index array */
487 	array_elems = (h->num_chains / list_length) +
488                       (h->num_chains % list_length ? 1 : 0);
489 	array_mem   = sizeof(h->chain_index) * array_elems;
490 
491 	debug("Alloc Chain index, elems:%d mem:%d bytes\n",
492 	      array_elems, array_mem);
493 
494 	h->chain_index = malloc(array_mem);
495 	if (h->chain_index == NULL && array_mem > 0) {
496 		h->chain_index_sz = 0;
497 		return -ENOMEM;
498 	}
499 	memset(h->chain_index, 0, array_mem);
500 	h->chain_index_sz = array_elems;
501 
502 	return 1;
503 }
504 
iptcc_chain_index_free(struct xtc_handle * h)505 static void iptcc_chain_index_free(struct xtc_handle *h)
506 {
507 	h->chain_index_sz = 0;
508 	free(h->chain_index);
509 }
510 
511 
512 #ifdef DEBUG
iptcc_chain_index_dump(struct xtc_handle * h)513 static void iptcc_chain_index_dump(struct xtc_handle *h)
514 {
515 	unsigned int i = 0;
516 
517 	/* Dump: contents of chain index array */
518 	for (i=0; i < h->chain_index_sz; i++) {
519 		if (h->chain_index[i]) {
520 			fprintf(stderr, "Chain index[%d].name: %s\n",
521 				i, h->chain_index[i]->name);
522 		}
523 	}
524 }
525 #endif
526 
527 /* Build the chain index */
iptcc_chain_index_build(struct xtc_handle * h)528 static int iptcc_chain_index_build(struct xtc_handle *h)
529 {
530 	unsigned int list_length = CHAIN_INDEX_BUCKET_LEN;
531 	unsigned int chains = 0;
532 	unsigned int cindex = 0;
533 	struct chain_head *c;
534 
535 	/* Build up the chain index array here */
536 	debug("Building chain index\n");
537 
538 	debug("Number of user defined chains:%d bucket_sz:%d array_sz:%d\n",
539 		h->num_chains, list_length, h->chain_index_sz);
540 
541 	if (h->chain_index_sz == 0)
542 		return 0;
543 
544 	list_for_each_entry(c, &h->chains, list) {
545 
546 		/* Issue: The index array needs to start after the
547 		 * builtin chains, as they are not sorted */
548 		if (!iptcc_is_builtin(c)) {
549 			cindex=chains / list_length;
550 
551 			/* Safe guard, break out on array limit, this
552 			 * is useful if chains are added and array is
553 			 * rebuild, without realloc of memory. */
554 			if (cindex >= h->chain_index_sz)
555 				break;
556 
557 			if ((chains % list_length)== 0) {
558 				debug("\nIndex[%d] Chains:", cindex);
559 				h->chain_index[cindex] = c;
560 			}
561 			chains++;
562 		}
563 		debug("%s, ", c->name);
564 	}
565 	debug("\n");
566 
567 	return 1;
568 }
569 
iptcc_chain_index_rebuild(struct xtc_handle * h)570 static int iptcc_chain_index_rebuild(struct xtc_handle *h)
571 {
572 	debug("REBUILD chain index array\n");
573 	iptcc_chain_index_free(h);
574 	if ((iptcc_chain_index_alloc(h)) < 0)
575 		return -ENOMEM;
576 	iptcc_chain_index_build(h);
577 	return 1;
578 }
579 
580 /* Delete chain (pointer) from index array.  Removing an element from
581  * the chain list only affects the chain index array, if the chain
582  * index points-to/uses that list pointer.
583  *
584  * There are different strategies, the simple and safe is to rebuild
585  * the chain index every time.  The more advanced is to update the
586  * array index to point to the next element, but that requires some
587  * house keeping and boundary checks.  The advanced is implemented, as
588  * the simple approach behaves badly when all chains are deleted
589  * because list_for_each processing will always hit the first chain
590  * index, thus causing a rebuild for every chain.
591  */
iptcc_chain_index_delete_chain(struct chain_head * c,struct xtc_handle * h)592 static int iptcc_chain_index_delete_chain(struct chain_head *c, struct xtc_handle *h)
593 {
594 	struct list_head *index_ptr, *next;
595 	struct chain_head *c2;
596 	unsigned int idx, idx2;
597 
598 	index_ptr = iptcc_bsearch_chain_index(c->name, &idx, h);
599 
600 	debug("Del chain[%s] c->list:%p index_ptr:%p\n",
601 	      c->name, &c->list, index_ptr);
602 
603 	/* Save the next pointer */
604 	next = c->list.next;
605 	list_del(&c->list);
606 
607 	if (index_ptr == &c->list) { /* Chain used as index ptr */
608 
609 		/* If this is the last chain in the list, its index bucket just
610 		 * became empty. Adjust the size to avoid a NULL-pointer deref
611 		 * later.
612 		 */
613 		if (next == &h->chains) {
614 			h->chain_index_sz--;
615 			return 0;
616 		}
617 
618 		/* See if its possible to avoid a rebuild, by shifting
619 		 * to next pointer.  Its possible if the next pointer
620 		 * is located in the same index bucket.
621 		 */
622 		c2         = list_entry(next, struct chain_head, list);
623 		iptcc_bsearch_chain_index(c2->name, &idx2, h);
624 		if (idx != idx2) {
625 			/* Rebuild needed */
626 			return iptcc_chain_index_rebuild(h);
627 		} else {
628 			/* Avoiding rebuild */
629 			debug("Update cindex[%d] with next ptr name:[%s]\n",
630 			      idx, c2->name);
631 			h->chain_index[idx]=c2;
632 			return 0;
633 		}
634 	}
635 	return 0;
636 }
637 
638 
639 /**********************************************************************
640  * iptc cache utility functions (iptcc_*)
641  **********************************************************************/
642 
643 /* Is the given chain builtin (1) or user-defined (0) */
iptcc_is_builtin(struct chain_head * c)644 static inline unsigned int iptcc_is_builtin(struct chain_head *c)
645 {
646 	return (c->hooknum ? 1 : 0);
647 }
648 
649 /* Get a specific rule within a chain */
iptcc_get_rule_num(struct chain_head * c,unsigned int rulenum)650 static struct rule_head *iptcc_get_rule_num(struct chain_head *c,
651 					    unsigned int rulenum)
652 {
653 	struct rule_head *r;
654 	unsigned int num = 0;
655 
656 	list_for_each_entry(r, &c->rules, list) {
657 		num++;
658 		if (num == rulenum)
659 			return r;
660 	}
661 	return NULL;
662 }
663 
664 /* Get a specific rule within a chain backwards */
iptcc_get_rule_num_reverse(struct chain_head * c,unsigned int rulenum)665 static struct rule_head *iptcc_get_rule_num_reverse(struct chain_head *c,
666 					    unsigned int rulenum)
667 {
668 	struct rule_head *r;
669 	unsigned int num = 0;
670 
671 	list_for_each_entry_reverse(r, &c->rules, list) {
672 		num++;
673 		if (num == rulenum)
674 			return r;
675 	}
676 	return NULL;
677 }
678 
679 /* Returns chain head if found, otherwise NULL. */
680 static struct chain_head *
iptcc_find_chain_by_offset(struct xtc_handle * handle,unsigned int offset)681 iptcc_find_chain_by_offset(struct xtc_handle *handle, unsigned int offset)
682 {
683 	struct list_head *pos;
684 	struct list_head *list_start_pos;
685 	unsigned int i;
686 
687 	if (list_empty(&handle->chains))
688 		return NULL;
689 
690 	/* Find a smart place to start the search */
691   	list_start_pos = iptcc_bsearch_chain_offset(offset, &i, handle);
692 
693 	/* Note that iptcc_bsearch_chain_offset() skips builtin
694 	 * chains, but this function is only used for finding jump
695 	 * targets, and a buildin chain is not a valid jump target */
696 
697 	debug("Offset:[%u] starting search at index:[%u]\n", offset, i);
698 //	list_for_each(pos, &handle->chains) {
699 	list_for_each(pos, list_start_pos->prev) {
700 		struct chain_head *c = list_entry(pos, struct chain_head, list);
701 		debug(".");
702 		if (offset >= c->head_offset && offset <= c->foot_offset) {
703 			debug("Offset search found chain:[%s]\n", c->name);
704 			return c;
705 		}
706 	}
707 
708 	return NULL;
709 }
710 
711 /* Returns chain head if found, otherwise NULL. */
712 static struct chain_head *
iptcc_find_label(const char * name,struct xtc_handle * handle)713 iptcc_find_label(const char *name, struct xtc_handle *handle)
714 {
715 	struct list_head *pos;
716 	struct list_head *list_start_pos;
717 	unsigned int i=0;
718 	int res;
719 
720 	if (list_empty(&handle->chains))
721 		return NULL;
722 
723 	/* First look at builtin chains */
724 	list_for_each(pos, &handle->chains) {
725 		struct chain_head *c = list_entry(pos, struct chain_head, list);
726 		if (!iptcc_is_builtin(c))
727 			break;
728 		if (!strcmp(c->name, name))
729 			return c;
730 	}
731 
732 	/* Find a smart place to start the search via chain index */
733   	//list_start_pos = iptcc_linearly_search_chain_index(name, handle);
734   	list_start_pos = iptcc_bsearch_chain_index(name, &i, handle);
735 
736 	/* Handel if bsearch bails out early */
737 	if (list_start_pos == &handle->chains) {
738 		list_start_pos = pos;
739 	}
740 #ifdef DEBUG
741 	else {
742 		/* Verify result of bsearch against linearly index search */
743 		struct list_head *test_pos;
744 		struct chain_head *test_c, *tmp_c;
745 		test_pos = iptcc_linearly_search_chain_index(name, handle);
746 		if (list_start_pos != test_pos) {
747 			debug("BUG in chain_index search\n");
748 			test_c=list_entry(test_pos,      struct chain_head,list);
749 			tmp_c =list_entry(list_start_pos,struct chain_head,list);
750 			debug("Verify search found:\n");
751 			debug(" Chain:%s\n", test_c->name);
752 			debug("BSearch found:\n");
753 			debug(" Chain:%s\n", tmp_c->name);
754 			exit(42);
755 		}
756 	}
757 #endif
758 
759 	/* Initial/special case, no user defined chains */
760 	if (handle->num_chains == 0)
761 		return NULL;
762 
763 	/* Start searching through the chain list */
764 	list_for_each(pos, list_start_pos->prev) {
765 		struct chain_head *c = list_entry(pos, struct chain_head, list);
766 		res = strcmp(c->name, name);
767 		debug("List search name:%s == %s res:%d\n", name, c->name, res);
768 		if (res==0)
769 			return c;
770 
771 		/* We can stop earlier as we know list is sorted */
772 		if (res>0 && !iptcc_is_builtin(c)) { /* Walked too far*/
773 			debug(" Not in list, walked too far, sorted list\n");
774 			return NULL;
775 		}
776 
777 		/* Stop on wrap around, if list head is reached */
778 		if (pos == &handle->chains) {
779 			debug("Stop, list head reached\n");
780 			return NULL;
781 		}
782 	}
783 
784 	debug("List search NOT found name:%s\n", name);
785 	return NULL;
786 }
787 
788 /* called when rule is to be removed from cache */
iptcc_delete_rule(struct rule_head * r)789 static void iptcc_delete_rule(struct rule_head *r)
790 {
791 	DEBUGP("deleting rule %p (offset %u)\n", r, r->offset);
792 	/* clean up reference count of called chain */
793 	if (r->type == IPTCC_R_JUMP
794 	    && r->jump)
795 		r->jump->references--;
796 
797 	list_del(&r->list);
798 	free(r);
799 }
800 
801 
802 /**********************************************************************
803  * RULESET PARSER (blob -> cache)
804  **********************************************************************/
805 
806 /* Delete policy rule of previous chain, since cache doesn't contain
807  * chain policy rules.
808  * WARNING: This function has ugly design and relies on a lot of context, only
809  * to be called from specific places within the parser */
__iptcc_p_del_policy(struct xtc_handle * h,unsigned int num)810 static int __iptcc_p_del_policy(struct xtc_handle *h, unsigned int num)
811 {
812 	const unsigned char *data;
813 
814 	if (h->chain_iterator_cur) {
815 		/* policy rule is last rule */
816 		struct rule_head *pr = (struct rule_head *)
817 			h->chain_iterator_cur->rules.prev;
818 
819 		/* save verdict */
820 		data = GET_TARGET(pr->entry)->data;
821 		h->chain_iterator_cur->verdict = *(const int *)data;
822 
823 		/* save counter and counter_map information */
824 		h->chain_iterator_cur->counter_map.maptype =
825 						COUNTER_MAP_NORMAL_MAP;
826 		h->chain_iterator_cur->counter_map.mappos = num-1;
827 		memcpy(&h->chain_iterator_cur->counters, &pr->entry->counters,
828 			sizeof(h->chain_iterator_cur->counters));
829 
830 		/* foot_offset points to verdict rule */
831 		h->chain_iterator_cur->foot_index = num;
832 		h->chain_iterator_cur->foot_offset = pr->offset;
833 
834 		/* delete rule from cache */
835 		iptcc_delete_rule(pr);
836 		h->chain_iterator_cur->num_rules--;
837 
838 		return 1;
839 	}
840 	return 0;
841 }
842 
843 /* alphabetically insert a chain into the list */
iptc_insert_chain(struct xtc_handle * h,struct chain_head * c)844 static void iptc_insert_chain(struct xtc_handle *h, struct chain_head *c)
845 {
846 	struct chain_head *tmp;
847 	struct list_head  *list_start_pos;
848 	unsigned int i=1;
849 
850 	/* Find a smart place to start the insert search */
851   	list_start_pos = iptcc_bsearch_chain_index(c->name, &i, h);
852 
853 	/* Handle the case, where chain.name is smaller than index[0] */
854 	if (i==0 && strcmp(c->name, h->chain_index[0]->name) <= 0) {
855 		h->chain_index[0] = c; /* Update chain index head */
856 		list_start_pos = h->chains.next;
857 		debug("Update chain_index[0] with %s\n", c->name);
858 	}
859 
860 	/* Handel if bsearch bails out early */
861 	if (list_start_pos == &h->chains) {
862 		list_start_pos = h->chains.next;
863 	}
864 
865 	/* sort only user defined chains */
866 	if (!c->hooknum) {
867 		list_for_each_entry(tmp, list_start_pos->prev, list) {
868 			if (!tmp->hooknum && strcmp(c->name, tmp->name) <= 0) {
869 				list_add(&c->list, tmp->list.prev);
870 				return;
871 			}
872 
873 			/* Stop if list head is reached */
874 			if (&tmp->list == &h->chains) {
875 				debug("Insert, list head reached add to tail\n");
876 				break;
877 			}
878 		}
879 	}
880 
881 	/* survived till end of list: add at tail */
882 	list_add_tail(&c->list, &h->chains);
883 }
884 
885 /* Another ugly helper function split out of cache_add_entry to make it less
886  * spaghetti code */
__iptcc_p_add_chain(struct xtc_handle * h,struct chain_head * c,unsigned int offset,unsigned int * num)887 static void __iptcc_p_add_chain(struct xtc_handle *h, struct chain_head *c,
888 				unsigned int offset, unsigned int *num)
889 {
890 	struct list_head  *tail = h->chains.prev;
891 	struct chain_head *ctail;
892 
893 	__iptcc_p_del_policy(h, *num);
894 
895 	c->head_offset = offset;
896 	c->index = *num;
897 
898 	/* Chains from kernel are already sorted, as they are inserted
899 	 * sorted. But there exists an issue when shifting to 1.4.0
900 	 * from an older version, as old versions allow last created
901 	 * chain to be unsorted.
902 	 */
903 	if (iptcc_is_builtin(c)) /* Only user defined chains are sorted*/
904 		list_add_tail(&c->list, &h->chains);
905 	else {
906 		ctail = list_entry(tail, struct chain_head, list);
907 
908 		if (strcmp(c->name, ctail->name) > 0 ||
909 		    iptcc_is_builtin(ctail))
910 			list_add_tail(&c->list, &h->chains);/* Already sorted*/
911 		else {
912 			iptc_insert_chain(h, c);/* Was not sorted */
913 
914 			/* Notice, if chains were not received sorted
915 			 * from kernel, then an offset bsearch is no
916 			 * longer valid.
917 			 */
918 			h->sorted_offsets = 0;
919 
920 			debug("NOTICE: chain:[%s] was NOT sorted(ctail:%s)\n",
921 			      c->name, ctail->name);
922 		}
923 	}
924 
925 	h->chain_iterator_cur = c;
926 }
927 
928 /* main parser function: add an entry from the blob to the cache */
cache_add_entry(STRUCT_ENTRY * e,struct xtc_handle * h,STRUCT_ENTRY ** prev,unsigned int * num)929 static int cache_add_entry(STRUCT_ENTRY *e,
930 			   struct xtc_handle *h,
931 			   STRUCT_ENTRY **prev,
932 			   unsigned int *num)
933 {
934 	unsigned int builtin;
935 	unsigned int offset = (char *)e - (char *)h->entries->entrytable;
936 
937 	DEBUGP("entering...");
938 
939 	/* Last entry ("policy rule"). End it.*/
940 	if (iptcb_entry2offset(h,e) + e->next_offset == h->entries->size) {
941 		/* This is the ERROR node at the end of the chain */
942 		DEBUGP_C("%u:%u: end of table:\n", *num, offset);
943 
944 		__iptcc_p_del_policy(h, *num);
945 
946 		h->chain_iterator_cur = NULL;
947 		goto out_inc;
948 	}
949 
950 	/* We know this is the start of a new chain if it's an ERROR
951 	 * target, or a hook entry point */
952 
953 	if (strcmp(GET_TARGET(e)->u.user.name, ERROR_TARGET) == 0) {
954 		struct chain_head *c =
955 			iptcc_alloc_chain_head((const char *)GET_TARGET(e)->data, 0);
956 		DEBUGP_C("%u:%u:new userdefined chain %s: %p\n", *num, offset,
957 			(char *)c->name, c);
958 		if (!c) {
959 			errno = -ENOMEM;
960 			return -1;
961 		}
962 		h->num_chains++; /* New user defined chain */
963 
964 		__iptcc_p_add_chain(h, c, offset, num);
965 
966 	} else if ((builtin = iptcb_ent_is_hook_entry(e, h)) != 0) {
967 		struct chain_head *c =
968 			iptcc_alloc_chain_head((char *)hooknames[builtin-1],
969 						builtin);
970 		DEBUGP_C("%u:%u new builtin chain: %p (rules=%p)\n",
971 			*num, offset, c, &c->rules);
972 		if (!c) {
973 			errno = -ENOMEM;
974 			return -1;
975 		}
976 
977 		c->hooknum = builtin;
978 
979 		__iptcc_p_add_chain(h, c, offset, num);
980 
981 		/* FIXME: this is ugly. */
982 		goto new_rule;
983 	} else {
984 		/* has to be normal rule */
985 		struct rule_head *r;
986 new_rule:
987 
988 		if (!(r = iptcc_alloc_rule(h->chain_iterator_cur,
989 					   e->next_offset))) {
990 			errno = ENOMEM;
991 			return -1;
992 		}
993 		DEBUGP_C("%u:%u normal rule: %p: ", *num, offset, r);
994 
995 		r->index = *num;
996 		r->offset = offset;
997 		memcpy(r->entry, e, e->next_offset);
998 		r->counter_map.maptype = COUNTER_MAP_NORMAL_MAP;
999 		r->counter_map.mappos = r->index;
1000 
1001 		/* handling of jumps, etc. */
1002 		if (!strcmp(GET_TARGET(e)->u.user.name, STANDARD_TARGET)) {
1003 			STRUCT_STANDARD_TARGET *t;
1004 
1005 			t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
1006 			if (t->target.u.target_size
1007 			    != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
1008 				errno = EINVAL;
1009 				free(r);
1010 				return -1;
1011 			}
1012 
1013 			if (t->verdict < 0) {
1014 				DEBUGP_C("standard, verdict=%d\n", t->verdict);
1015 				r->type = IPTCC_R_STANDARD;
1016 			} else if (t->verdict == r->offset+e->next_offset) {
1017 				DEBUGP_C("fallthrough\n");
1018 				r->type = IPTCC_R_FALLTHROUGH;
1019 			} else {
1020 				DEBUGP_C("jump, target=%u\n", t->verdict);
1021 				r->type = IPTCC_R_JUMP;
1022 				/* Jump target fixup has to be deferred
1023 				 * until second pass, since we migh not
1024 				 * yet have parsed the target */
1025 			}
1026 		} else {
1027 			DEBUGP_C("module, target=%s\n", GET_TARGET(e)->u.user.name);
1028 			r->type = IPTCC_R_MODULE;
1029 		}
1030 
1031 		list_add_tail(&r->list, &h->chain_iterator_cur->rules);
1032 		h->chain_iterator_cur->num_rules++;
1033 	}
1034 out_inc:
1035 	(*num)++;
1036 	return 0;
1037 }
1038 
1039 
1040 /* parse an iptables blob into it's pieces */
parse_table(struct xtc_handle * h)1041 static int parse_table(struct xtc_handle *h)
1042 {
1043 	STRUCT_ENTRY *prev;
1044 	unsigned int num = 0;
1045 	struct chain_head *c;
1046 
1047 	/* Assume that chains offsets are sorted, this verified during
1048 	   parsing of ruleset (in __iptcc_p_add_chain())*/
1049 	h->sorted_offsets = 1;
1050 
1051 	/* First pass: over ruleset blob */
1052 	ENTRY_ITERATE(h->entries->entrytable, h->entries->size,
1053 			cache_add_entry, h, &prev, &num);
1054 
1055 	/* Build the chain index, used for chain list search speedup */
1056 	if ((iptcc_chain_index_alloc(h)) < 0)
1057 		return -ENOMEM;
1058 	iptcc_chain_index_build(h);
1059 
1060 	/* Second pass: fixup parsed data from first pass */
1061 	list_for_each_entry(c, &h->chains, list) {
1062 		struct rule_head *r;
1063 		list_for_each_entry(r, &c->rules, list) {
1064 			struct chain_head *lc;
1065 			STRUCT_STANDARD_TARGET *t;
1066 
1067 			if (r->type != IPTCC_R_JUMP)
1068 				continue;
1069 
1070 			t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
1071 			lc = iptcc_find_chain_by_offset(h, t->verdict);
1072 			if (!lc)
1073 				return -1;
1074 			r->jump = lc;
1075 			lc->references++;
1076 		}
1077 	}
1078 
1079 	return 1;
1080 }
1081 
1082 
1083 /**********************************************************************
1084  * RULESET COMPILATION (cache -> blob)
1085  **********************************************************************/
1086 
1087 /* Convenience structures */
1088 struct iptcb_chain_start{
1089 	STRUCT_ENTRY e;
1090 	struct xt_error_target name;
1091 };
1092 #define IPTCB_CHAIN_START_SIZE	(sizeof(STRUCT_ENTRY) +			\
1093 				 ALIGN(sizeof(struct xt_error_target)))
1094 
1095 struct iptcb_chain_foot {
1096 	STRUCT_ENTRY e;
1097 	STRUCT_STANDARD_TARGET target;
1098 };
1099 #define IPTCB_CHAIN_FOOT_SIZE	(sizeof(STRUCT_ENTRY) +			\
1100 				 ALIGN(sizeof(STRUCT_STANDARD_TARGET)))
1101 
1102 struct iptcb_chain_error {
1103 	STRUCT_ENTRY entry;
1104 	struct xt_error_target target;
1105 };
1106 #define IPTCB_CHAIN_ERROR_SIZE	(sizeof(STRUCT_ENTRY) +			\
1107 				 ALIGN(sizeof(struct xt_error_target)))
1108 
1109 
1110 
1111 /* compile rule from cache into blob */
iptcc_compile_rule(struct xtc_handle * h,STRUCT_REPLACE * repl,struct rule_head * r)1112 static inline int iptcc_compile_rule (struct xtc_handle *h, STRUCT_REPLACE *repl, struct rule_head *r)
1113 {
1114 	/* handle jumps */
1115 	if (r->type == IPTCC_R_JUMP) {
1116 		STRUCT_STANDARD_TARGET *t;
1117 		t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
1118 		/* memset for memcmp convenience on delete/replace */
1119 		memset(t->target.u.user.name, 0, XT_EXTENSION_MAXNAMELEN);
1120 		strcpy(t->target.u.user.name, STANDARD_TARGET);
1121 		t->target.u.user.revision = 0;
1122 		/* Jumps can only happen to builtin chains, so we
1123 		 * can safely assume that they always have a header */
1124 		t->verdict = r->jump->head_offset + IPTCB_CHAIN_START_SIZE;
1125 	} else if (r->type == IPTCC_R_FALLTHROUGH) {
1126 		STRUCT_STANDARD_TARGET *t;
1127 		t = (STRUCT_STANDARD_TARGET *)GET_TARGET(r->entry);
1128 		t->verdict = r->offset + r->size;
1129 	}
1130 
1131 	/* copy entry from cache to blob */
1132 	memcpy((char *)repl->entries+r->offset, r->entry, r->size);
1133 
1134 	return 1;
1135 }
1136 
1137 /* compile chain from cache into blob */
iptcc_compile_chain(struct xtc_handle * h,STRUCT_REPLACE * repl,struct chain_head * c)1138 static int iptcc_compile_chain(struct xtc_handle *h, STRUCT_REPLACE *repl, struct chain_head *c)
1139 {
1140 	int ret;
1141 	struct rule_head *r;
1142 	struct iptcb_chain_start *head;
1143 	struct iptcb_chain_foot *foot;
1144 
1145 	/* only user-defined chains have heaer */
1146 	if (!iptcc_is_builtin(c)) {
1147 		/* put chain header in place */
1148 		head = (void *)repl->entries + c->head_offset;
1149 		head->e.target_offset = sizeof(STRUCT_ENTRY);
1150 		head->e.next_offset = IPTCB_CHAIN_START_SIZE;
1151 		strcpy(head->name.target.u.user.name, ERROR_TARGET);
1152 		head->name.target.u.target_size =
1153 				ALIGN(sizeof(struct xt_error_target));
1154 		strncpy(head->name.errorname, c->name, XT_FUNCTION_MAXNAMELEN);
1155 		head->name.errorname[XT_FUNCTION_MAXNAMELEN - 1] = '\0';
1156 	} else {
1157 		repl->hook_entry[c->hooknum-1] = c->head_offset;
1158 		repl->underflow[c->hooknum-1] = c->foot_offset;
1159 	}
1160 
1161 	/* iterate over rules */
1162 	list_for_each_entry(r, &c->rules, list) {
1163 		ret = iptcc_compile_rule(h, repl, r);
1164 		if (ret < 0)
1165 			return ret;
1166 	}
1167 
1168 	/* put chain footer in place */
1169 	foot = (void *)repl->entries + c->foot_offset;
1170 	foot->e.target_offset = sizeof(STRUCT_ENTRY);
1171 	foot->e.next_offset = IPTCB_CHAIN_FOOT_SIZE;
1172 	strcpy(foot->target.target.u.user.name, STANDARD_TARGET);
1173 	foot->target.target.u.target_size =
1174 				ALIGN(sizeof(STRUCT_STANDARD_TARGET));
1175 	/* builtin targets have verdict, others return */
1176 	if (iptcc_is_builtin(c))
1177 		foot->target.verdict = c->verdict;
1178 	else
1179 		foot->target.verdict = RETURN;
1180 	/* set policy-counters */
1181 	foot->e.counters = c->counters;
1182 
1183 	return 0;
1184 }
1185 
1186 /* calculate offset and number for every rule in the cache */
iptcc_compile_chain_offsets(struct xtc_handle * h,struct chain_head * c,unsigned int * offset,unsigned int * num)1187 static int iptcc_compile_chain_offsets(struct xtc_handle *h, struct chain_head *c,
1188 				       unsigned int *offset, unsigned int *num)
1189 {
1190 	struct rule_head *r;
1191 
1192 	c->head_offset = *offset;
1193 	DEBUGP("%s: chain_head %u, offset=%u\n", c->name, *num, *offset);
1194 
1195 	if (!iptcc_is_builtin(c))  {
1196 		/* Chain has header */
1197 		*offset += sizeof(STRUCT_ENTRY)
1198 			     + ALIGN(sizeof(struct xt_error_target));
1199 		(*num)++;
1200 	}
1201 
1202 	list_for_each_entry(r, &c->rules, list) {
1203 		DEBUGP("rule %u, offset=%u, index=%u\n", *num, *offset, *num);
1204 		r->offset = *offset;
1205 		r->index = *num;
1206 		*offset += r->size;
1207 		(*num)++;
1208 	}
1209 
1210 	DEBUGP("%s; chain_foot %u, offset=%u, index=%u\n", c->name, *num,
1211 		*offset, *num);
1212 	c->foot_offset = *offset;
1213 	c->foot_index = *num;
1214 	*offset += sizeof(STRUCT_ENTRY)
1215 		   + ALIGN(sizeof(STRUCT_STANDARD_TARGET));
1216 	(*num)++;
1217 
1218 	return 1;
1219 }
1220 
1221 /* put the pieces back together again */
iptcc_compile_table_prep(struct xtc_handle * h,unsigned int * size)1222 static int iptcc_compile_table_prep(struct xtc_handle *h, unsigned int *size)
1223 {
1224 	struct chain_head *c;
1225 	unsigned int offset = 0, num = 0;
1226 	int ret = 0;
1227 
1228 	/* First pass: calculate offset for every rule */
1229 	list_for_each_entry(c, &h->chains, list) {
1230 		ret = iptcc_compile_chain_offsets(h, c, &offset, &num);
1231 		if (ret < 0)
1232 			return ret;
1233 	}
1234 
1235 	/* Append one error rule at end of chain */
1236 	num++;
1237 	offset += sizeof(STRUCT_ENTRY)
1238 		  + ALIGN(sizeof(struct xt_error_target));
1239 
1240 	/* ruleset size is now in offset */
1241 	*size = offset;
1242 	return num;
1243 }
1244 
iptcc_compile_table(struct xtc_handle * h,STRUCT_REPLACE * repl)1245 static int iptcc_compile_table(struct xtc_handle *h, STRUCT_REPLACE *repl)
1246 {
1247 	struct chain_head *c;
1248 	struct iptcb_chain_error *error;
1249 
1250 	/* Second pass: copy from cache to offsets, fill in jumps */
1251 	list_for_each_entry(c, &h->chains, list) {
1252 		int ret = iptcc_compile_chain(h, repl, c);
1253 		if (ret < 0)
1254 			return ret;
1255 	}
1256 
1257 	/* Append error rule at end of chain */
1258 	error = (void *)repl->entries + repl->size - IPTCB_CHAIN_ERROR_SIZE;
1259 	error->entry.target_offset = sizeof(STRUCT_ENTRY);
1260 	error->entry.next_offset = IPTCB_CHAIN_ERROR_SIZE;
1261 	error->target.target.u.user.target_size =
1262 		ALIGN(sizeof(struct xt_error_target));
1263 	strcpy((char *)&error->target.target.u.user.name, ERROR_TARGET);
1264 	strcpy((char *)&error->target.errorname, "ERROR");
1265 
1266 	return 1;
1267 }
1268 
1269 /**********************************************************************
1270  * EXTERNAL API (operates on cache only)
1271  **********************************************************************/
1272 
1273 /* Allocate handle of given size */
1274 static struct xtc_handle *
alloc_handle(STRUCT_GETINFO * infop)1275 alloc_handle(STRUCT_GETINFO *infop)
1276 {
1277 	struct xtc_handle *h;
1278 
1279 	h = malloc(sizeof(*h));
1280 	if (!h) {
1281 		errno = ENOMEM;
1282 		return NULL;
1283 	}
1284 	memset(h, 0, sizeof(*h));
1285 	INIT_LIST_HEAD(&h->chains);
1286 	strcpy(h->info.name, infop->name);
1287 
1288 	h->entries = malloc(sizeof(STRUCT_GET_ENTRIES) + infop->size);
1289 	if (!h->entries)
1290 		goto out_free_handle;
1291 
1292 	strcpy(h->entries->name, infop->name);
1293 	h->entries->size = infop->size;
1294 
1295 	return h;
1296 
1297 out_free_handle:
1298 	free(h);
1299 
1300 	return NULL;
1301 }
1302 
1303 
1304 struct xtc_handle *
TC_INIT(const char * tablename)1305 TC_INIT(const char *tablename)
1306 {
1307 	struct xtc_handle *h;
1308 	STRUCT_GETINFO info;
1309 	unsigned int tmp;
1310 	socklen_t s;
1311 	int sockfd;
1312 
1313 retry:
1314 	iptc_fn = TC_INIT;
1315 
1316 	if (strlen(tablename) >= TABLE_MAXNAMELEN) {
1317 		errno = EINVAL;
1318 		return NULL;
1319 	}
1320 
1321 	sockfd = socket(TC_AF, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_RAW);
1322 	if (sockfd < 0)
1323 		return NULL;
1324 
1325 	s = sizeof(info);
1326 
1327 	strcpy(info.name, tablename);
1328 	if (getsockopt(sockfd, TC_IPPROTO, SO_GET_INFO, &info, &s) < 0) {
1329 		close(sockfd);
1330 		return NULL;
1331 	}
1332 
1333 	DEBUGP("valid_hooks=0x%08x, num_entries=%u, size=%u\n",
1334 		info.valid_hooks, info.num_entries, info.size);
1335 
1336 	h = alloc_handle(&info);
1337 	if (h == NULL) {
1338 		close(sockfd);
1339 		return NULL;
1340 	}
1341 
1342 	/* Initialize current state */
1343 	h->sockfd = sockfd;
1344 	h->info = info;
1345 
1346 	h->entries->size = h->info.size;
1347 
1348 	tmp = sizeof(STRUCT_GET_ENTRIES) + h->info.size;
1349 
1350 	if (getsockopt(h->sockfd, TC_IPPROTO, SO_GET_ENTRIES, h->entries,
1351 		       &tmp) < 0)
1352 		goto error;
1353 
1354 #ifdef IPTC_DEBUG2
1355 	{
1356 		int fd = open("/tmp/libiptc-so_get_entries.blob",
1357 				O_CREAT|O_WRONLY, 0644);
1358 		if (fd >= 0) {
1359 			write(fd, h->entries, tmp);
1360 			close(fd);
1361 		}
1362 	}
1363 #endif
1364 
1365 	if (parse_table(h) < 0)
1366 		goto error;
1367 
1368 	return h;
1369 error:
1370 	TC_FREE(h);
1371 	/* A different process changed the ruleset size, retry */
1372 	if (errno == EAGAIN)
1373 		goto retry;
1374 	return NULL;
1375 }
1376 
1377 void
TC_FREE(struct xtc_handle * h)1378 TC_FREE(struct xtc_handle *h)
1379 {
1380 	struct chain_head *c, *tmp;
1381 
1382 	iptc_fn = TC_FREE;
1383 	close(h->sockfd);
1384 
1385 	list_for_each_entry_safe(c, tmp, &h->chains, list) {
1386 		struct rule_head *r, *rtmp;
1387 
1388 		list_for_each_entry_safe(r, rtmp, &c->rules, list) {
1389 			free(r);
1390 		}
1391 
1392 		free(c);
1393 	}
1394 
1395 	iptcc_chain_index_free(h);
1396 
1397 	free(h->entries);
1398 	free(h);
1399 }
1400 
1401 static inline int
print_match(const STRUCT_ENTRY_MATCH * m)1402 print_match(const STRUCT_ENTRY_MATCH *m)
1403 {
1404 	printf("Match name: `%s'\n", m->u.user.name);
1405 	return 0;
1406 }
1407 
1408 static int dump_entry(STRUCT_ENTRY *e, struct xtc_handle *const handle);
1409 
1410 void
TC_DUMP_ENTRIES(struct xtc_handle * const handle)1411 TC_DUMP_ENTRIES(struct xtc_handle *const handle)
1412 {
1413 	iptc_fn = TC_DUMP_ENTRIES;
1414 
1415 	printf("libiptc v%s. %u bytes.\n",
1416 	       XTABLES_VERSION, handle->entries->size);
1417 	printf("Table `%s'\n", handle->info.name);
1418 	printf("Hooks: pre/in/fwd/out/post = %x/%x/%x/%x/%x\n",
1419 	       handle->info.hook_entry[HOOK_PRE_ROUTING],
1420 	       handle->info.hook_entry[HOOK_LOCAL_IN],
1421 	       handle->info.hook_entry[HOOK_FORWARD],
1422 	       handle->info.hook_entry[HOOK_LOCAL_OUT],
1423 	       handle->info.hook_entry[HOOK_POST_ROUTING]);
1424 	printf("Underflows: pre/in/fwd/out/post = %x/%x/%x/%x/%x\n",
1425 	       handle->info.underflow[HOOK_PRE_ROUTING],
1426 	       handle->info.underflow[HOOK_LOCAL_IN],
1427 	       handle->info.underflow[HOOK_FORWARD],
1428 	       handle->info.underflow[HOOK_LOCAL_OUT],
1429 	       handle->info.underflow[HOOK_POST_ROUTING]);
1430 
1431 	ENTRY_ITERATE(handle->entries->entrytable, handle->entries->size,
1432 		      dump_entry, handle);
1433 }
1434 
1435 /* Does this chain exist? */
TC_IS_CHAIN(const char * chain,struct xtc_handle * const handle)1436 int TC_IS_CHAIN(const char *chain, struct xtc_handle *const handle)
1437 {
1438 	iptc_fn = TC_IS_CHAIN;
1439 	return iptcc_find_label(chain, handle) != NULL;
1440 }
1441 
iptcc_chain_iterator_advance(struct xtc_handle * handle)1442 static void iptcc_chain_iterator_advance(struct xtc_handle *handle)
1443 {
1444 	struct chain_head *c = handle->chain_iterator_cur;
1445 
1446 	if (c->list.next == &handle->chains)
1447 		handle->chain_iterator_cur = NULL;
1448 	else
1449 		handle->chain_iterator_cur =
1450 			list_entry(c->list.next, struct chain_head, list);
1451 }
1452 
1453 /* Iterator functions to run through the chains. */
1454 const char *
TC_FIRST_CHAIN(struct xtc_handle * handle)1455 TC_FIRST_CHAIN(struct xtc_handle *handle)
1456 {
1457 	struct chain_head *c = list_entry(handle->chains.next,
1458 					  struct chain_head, list);
1459 
1460 	iptc_fn = TC_FIRST_CHAIN;
1461 
1462 
1463 	if (list_empty(&handle->chains)) {
1464 		DEBUGP(": no chains\n");
1465 		return NULL;
1466 	}
1467 
1468 	handle->chain_iterator_cur = c;
1469 	iptcc_chain_iterator_advance(handle);
1470 
1471 	DEBUGP(": returning `%s'\n", c->name);
1472 	return c->name;
1473 }
1474 
1475 /* Iterator functions to run through the chains.  Returns NULL at end. */
1476 const char *
TC_NEXT_CHAIN(struct xtc_handle * handle)1477 TC_NEXT_CHAIN(struct xtc_handle *handle)
1478 {
1479 	struct chain_head *c = handle->chain_iterator_cur;
1480 
1481 	iptc_fn = TC_NEXT_CHAIN;
1482 
1483 	if (!c) {
1484 		DEBUGP(": no more chains\n");
1485 		return NULL;
1486 	}
1487 
1488 	iptcc_chain_iterator_advance(handle);
1489 
1490 	DEBUGP(": returning `%s'\n", c->name);
1491 	return c->name;
1492 }
1493 
1494 /* Get first rule in the given chain: NULL for empty chain. */
1495 const STRUCT_ENTRY *
TC_FIRST_RULE(const char * chain,struct xtc_handle * handle)1496 TC_FIRST_RULE(const char *chain, struct xtc_handle *handle)
1497 {
1498 	struct chain_head *c;
1499 	struct rule_head *r;
1500 
1501 	iptc_fn = TC_FIRST_RULE;
1502 
1503 	DEBUGP("first rule(%s): ", chain);
1504 
1505 	c = iptcc_find_label(chain, handle);
1506 	if (!c) {
1507 		errno = ENOENT;
1508 		return NULL;
1509 	}
1510 
1511 	/* Empty chain: single return/policy rule */
1512 	if (list_empty(&c->rules)) {
1513 		DEBUGP_C("no rules, returning NULL\n");
1514 		return NULL;
1515 	}
1516 
1517 	r = list_entry(c->rules.next, struct rule_head, list);
1518 	handle->rule_iterator_cur = r;
1519 	DEBUGP_C("%p\n", r);
1520 
1521 	return r->entry;
1522 }
1523 
1524 /* Returns NULL when rules run out. */
1525 const STRUCT_ENTRY *
TC_NEXT_RULE(const STRUCT_ENTRY * prev,struct xtc_handle * handle)1526 TC_NEXT_RULE(const STRUCT_ENTRY *prev, struct xtc_handle *handle)
1527 {
1528 	struct rule_head *r;
1529 
1530 	iptc_fn = TC_NEXT_RULE;
1531 	DEBUGP("rule_iterator_cur=%p...", handle->rule_iterator_cur);
1532 
1533 	if (handle->rule_iterator_cur == NULL) {
1534 		DEBUGP_C("returning NULL\n");
1535 		return NULL;
1536 	}
1537 
1538 	r = list_entry(handle->rule_iterator_cur->list.next,
1539 			struct rule_head, list);
1540 
1541 	iptc_fn = TC_NEXT_RULE;
1542 
1543 	DEBUGP_C("next=%p, head=%p...", &r->list,
1544 		&handle->rule_iterator_cur->chain->rules);
1545 
1546 	if (&r->list == &handle->rule_iterator_cur->chain->rules) {
1547 		handle->rule_iterator_cur = NULL;
1548 		DEBUGP_C("finished, returning NULL\n");
1549 		return NULL;
1550 	}
1551 
1552 	handle->rule_iterator_cur = r;
1553 
1554 	/* NOTE: prev is without any influence ! */
1555 	DEBUGP_C("returning rule %p\n", r);
1556 	return r->entry;
1557 }
1558 
1559 /* Returns a pointer to the target name of this position. */
standard_target_map(int verdict)1560 static const char *standard_target_map(int verdict)
1561 {
1562 	switch (verdict) {
1563 		case RETURN:
1564 			return LABEL_RETURN;
1565 			break;
1566 		case -NF_ACCEPT-1:
1567 			return LABEL_ACCEPT;
1568 			break;
1569 		case -NF_DROP-1:
1570 			return LABEL_DROP;
1571 			break;
1572 		case -NF_QUEUE-1:
1573 			return LABEL_QUEUE;
1574 			break;
1575 		default:
1576 			fprintf(stderr, "ERROR: %d not a valid target)\n",
1577 				verdict);
1578 			abort();
1579 			break;
1580 	}
1581 	/* not reached */
1582 	return NULL;
1583 }
1584 
1585 /* Returns a pointer to the target name of this position. */
TC_GET_TARGET(const STRUCT_ENTRY * ce,struct xtc_handle * handle)1586 const char *TC_GET_TARGET(const STRUCT_ENTRY *ce,
1587 			  struct xtc_handle *handle)
1588 {
1589 	STRUCT_ENTRY *e = (STRUCT_ENTRY *)ce;
1590 	struct rule_head *r = container_of(e, struct rule_head, entry[0]);
1591 	const unsigned char *data;
1592 
1593 	iptc_fn = TC_GET_TARGET;
1594 
1595 	switch(r->type) {
1596 		int spos;
1597 		case IPTCC_R_FALLTHROUGH:
1598 			return "";
1599 			break;
1600 		case IPTCC_R_JUMP:
1601 			DEBUGP("r=%p, jump=%p, name=`%s'\n", r, r->jump, r->jump->name);
1602 			return r->jump->name;
1603 			break;
1604 		case IPTCC_R_STANDARD:
1605 			data = GET_TARGET(e)->data;
1606 			spos = *(const int *)data;
1607 			DEBUGP("r=%p, spos=%d'\n", r, spos);
1608 			return standard_target_map(spos);
1609 			break;
1610 		case IPTCC_R_MODULE:
1611 			return GET_TARGET(e)->u.user.name;
1612 			break;
1613 	}
1614 	return NULL;
1615 }
1616 /* Is this a built-in chain?  Actually returns hook + 1. */
1617 int
TC_BUILTIN(const char * chain,struct xtc_handle * const handle)1618 TC_BUILTIN(const char *chain, struct xtc_handle *const handle)
1619 {
1620 	struct chain_head *c;
1621 
1622 	iptc_fn = TC_BUILTIN;
1623 
1624 	c = iptcc_find_label(chain, handle);
1625 	if (!c) {
1626 		errno = ENOENT;
1627 		return 0;
1628 	}
1629 
1630 	return iptcc_is_builtin(c);
1631 }
1632 
1633 /* Get the policy of a given built-in chain */
1634 const char *
TC_GET_POLICY(const char * chain,STRUCT_COUNTERS * counters,struct xtc_handle * handle)1635 TC_GET_POLICY(const char *chain,
1636 	      STRUCT_COUNTERS *counters,
1637 	      struct xtc_handle *handle)
1638 {
1639 	struct chain_head *c;
1640 
1641 	iptc_fn = TC_GET_POLICY;
1642 
1643 	DEBUGP("called for chain %s\n", chain);
1644 
1645 	c = iptcc_find_label(chain, handle);
1646 	if (!c) {
1647 		errno = ENOENT;
1648 		return NULL;
1649 	}
1650 
1651 	if (!iptcc_is_builtin(c))
1652 		return NULL;
1653 
1654 	*counters = c->counters;
1655 
1656 	return standard_target_map(c->verdict);
1657 }
1658 
1659 static int
iptcc_standard_map(struct rule_head * r,int verdict)1660 iptcc_standard_map(struct rule_head *r, int verdict)
1661 {
1662 	STRUCT_ENTRY *e = r->entry;
1663 	STRUCT_STANDARD_TARGET *t;
1664 
1665 	t = (STRUCT_STANDARD_TARGET *)GET_TARGET(e);
1666 
1667 	if (t->target.u.target_size
1668 	    != ALIGN(sizeof(STRUCT_STANDARD_TARGET))) {
1669 		errno = EINVAL;
1670 		return 0;
1671 	}
1672 	/* memset for memcmp convenience on delete/replace */
1673 	memset(t->target.u.user.name, 0, XT_EXTENSION_MAXNAMELEN);
1674 	strcpy(t->target.u.user.name, STANDARD_TARGET);
1675 	t->target.u.user.revision = 0;
1676 	t->verdict = verdict;
1677 
1678 	r->type = IPTCC_R_STANDARD;
1679 
1680 	return 1;
1681 }
1682 
1683 static int
iptcc_map_target(struct xtc_handle * const handle,struct rule_head * r,bool dry_run)1684 iptcc_map_target(struct xtc_handle *const handle,
1685 	   struct rule_head *r,
1686 	   bool dry_run)
1687 {
1688 	STRUCT_ENTRY *e = r->entry;
1689 	STRUCT_ENTRY_TARGET *t = GET_TARGET(e);
1690 
1691 	/* Maybe it's empty (=> fall through) */
1692 	if (strcmp(t->u.user.name, "") == 0) {
1693 		r->type = IPTCC_R_FALLTHROUGH;
1694 		return 1;
1695 	}
1696 	/* Maybe it's a standard target name... */
1697 	else if (strcmp(t->u.user.name, LABEL_ACCEPT) == 0)
1698 		return iptcc_standard_map(r, -NF_ACCEPT - 1);
1699 	else if (strcmp(t->u.user.name, LABEL_DROP) == 0)
1700 		return iptcc_standard_map(r, -NF_DROP - 1);
1701 	else if (strcmp(t->u.user.name, LABEL_QUEUE) == 0)
1702 		return iptcc_standard_map(r, -NF_QUEUE - 1);
1703 	else if (strcmp(t->u.user.name, LABEL_RETURN) == 0)
1704 		return iptcc_standard_map(r, RETURN);
1705 	else if (TC_BUILTIN(t->u.user.name, handle)) {
1706 		/* Can't jump to builtins. */
1707 		errno = EINVAL;
1708 		return 0;
1709 	} else {
1710 		/* Maybe it's an existing chain name. */
1711 		struct chain_head *c;
1712 		DEBUGP("trying to find chain `%s': ", t->u.user.name);
1713 
1714 		c = iptcc_find_label(t->u.user.name, handle);
1715 		if (c) {
1716 			DEBUGP_C("found!\n");
1717 			r->type = IPTCC_R_JUMP;
1718 			r->jump = c;
1719 			c->references++;
1720 			return 1;
1721 		}
1722 		DEBUGP_C("not found :(\n");
1723 	}
1724 
1725 	/* Must be a module?  If not, kernel will reject... */
1726 	/* memset to all 0 for your memcmp convenience: don't clear version */
1727 	memset(t->u.user.name + strlen(t->u.user.name),
1728 	       0,
1729 	       FUNCTION_MAXNAMELEN - 1 - strlen(t->u.user.name));
1730 	r->type = IPTCC_R_MODULE;
1731 	if (!dry_run)
1732 		set_changed(handle);
1733 	return 1;
1734 }
1735 
1736 /* Insert the entry `fw' in chain `chain' into position `rulenum'. */
1737 int
TC_INSERT_ENTRY(const IPT_CHAINLABEL chain,const STRUCT_ENTRY * e,unsigned int rulenum,struct xtc_handle * handle)1738 TC_INSERT_ENTRY(const IPT_CHAINLABEL chain,
1739 		const STRUCT_ENTRY *e,
1740 		unsigned int rulenum,
1741 		struct xtc_handle *handle)
1742 {
1743 	struct chain_head *c;
1744 	struct rule_head *r;
1745 	struct list_head *prev;
1746 
1747 	iptc_fn = TC_INSERT_ENTRY;
1748 
1749 	if (!(c = iptcc_find_label(chain, handle))) {
1750 		errno = ENOENT;
1751 		return 0;
1752 	}
1753 
1754 	/* first rulenum index = 0
1755 	   first c->num_rules index = 1 */
1756 	if (rulenum > c->num_rules) {
1757 		errno = E2BIG;
1758 		return 0;
1759 	}
1760 
1761 	/* If we are inserting at the end just take advantage of the
1762 	   double linked list, insert will happen before the entry
1763 	   prev points to. */
1764 	if (rulenum == c->num_rules) {
1765 		prev = &c->rules;
1766 	} else if (rulenum + 1 <= c->num_rules/2) {
1767 		r = iptcc_get_rule_num(c, rulenum + 1);
1768 		prev = &r->list;
1769 	} else {
1770 		r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
1771 		prev = &r->list;
1772 	}
1773 
1774 	if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1775 		errno = ENOMEM;
1776 		return 0;
1777 	}
1778 
1779 	memcpy(r->entry, e, e->next_offset);
1780 	r->counter_map.maptype = COUNTER_MAP_SET;
1781 
1782 	if (!iptcc_map_target(handle, r, false)) {
1783 		free(r);
1784 		return 0;
1785 	}
1786 
1787 	list_add_tail(&r->list, prev);
1788 	c->num_rules++;
1789 
1790 	set_changed(handle);
1791 
1792 	return 1;
1793 }
1794 
1795 /* Atomically replace rule `rulenum' in `chain' with `fw'. */
1796 int
TC_REPLACE_ENTRY(const IPT_CHAINLABEL chain,const STRUCT_ENTRY * e,unsigned int rulenum,struct xtc_handle * handle)1797 TC_REPLACE_ENTRY(const IPT_CHAINLABEL chain,
1798 		 const STRUCT_ENTRY *e,
1799 		 unsigned int rulenum,
1800 		 struct xtc_handle *handle)
1801 {
1802 	struct chain_head *c;
1803 	struct rule_head *r, *old;
1804 
1805 	iptc_fn = TC_REPLACE_ENTRY;
1806 
1807 	if (!(c = iptcc_find_label(chain, handle))) {
1808 		errno = ENOENT;
1809 		return 0;
1810 	}
1811 
1812 	if (rulenum >= c->num_rules) {
1813 		errno = E2BIG;
1814 		return 0;
1815 	}
1816 
1817 	/* Take advantage of the double linked list if possible. */
1818 	if (rulenum + 1 <= c->num_rules/2) {
1819 		old = iptcc_get_rule_num(c, rulenum + 1);
1820 	} else {
1821 		old = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
1822 	}
1823 
1824 	if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1825 		errno = ENOMEM;
1826 		return 0;
1827 	}
1828 
1829 	memcpy(r->entry, e, e->next_offset);
1830 	r->counter_map.maptype = COUNTER_MAP_SET;
1831 
1832 	if (!iptcc_map_target(handle, r, false)) {
1833 		free(r);
1834 		return 0;
1835 	}
1836 
1837 	list_add(&r->list, &old->list);
1838 	iptcc_delete_rule(old);
1839 
1840 	set_changed(handle);
1841 
1842 	return 1;
1843 }
1844 
1845 /* Append entry `fw' to chain `chain'.  Equivalent to insert with
1846    rulenum = length of chain. */
1847 int
TC_APPEND_ENTRY(const IPT_CHAINLABEL chain,const STRUCT_ENTRY * e,struct xtc_handle * handle)1848 TC_APPEND_ENTRY(const IPT_CHAINLABEL chain,
1849 		const STRUCT_ENTRY *e,
1850 		struct xtc_handle *handle)
1851 {
1852 	struct chain_head *c;
1853 	struct rule_head *r;
1854 
1855 	iptc_fn = TC_APPEND_ENTRY;
1856 	if (!(c = iptcc_find_label(chain, handle))) {
1857 		DEBUGP("unable to find chain `%s'\n", chain);
1858 		errno = ENOENT;
1859 		return 0;
1860 	}
1861 
1862 	if (!(r = iptcc_alloc_rule(c, e->next_offset))) {
1863 		DEBUGP("unable to allocate rule for chain `%s'\n", chain);
1864 		errno = ENOMEM;
1865 		return 0;
1866 	}
1867 
1868 	memcpy(r->entry, e, e->next_offset);
1869 	r->counter_map.maptype = COUNTER_MAP_SET;
1870 
1871 	if (!iptcc_map_target(handle, r, false)) {
1872 		DEBUGP("unable to map target of rule for chain `%s'\n", chain);
1873 		free(r);
1874 		return 0;
1875 	}
1876 
1877 	list_add_tail(&r->list, &c->rules);
1878 	c->num_rules++;
1879 
1880 	set_changed(handle);
1881 
1882 	return 1;
1883 }
1884 
1885 static inline int
match_different(const STRUCT_ENTRY_MATCH * a,const unsigned char * a_elems,const unsigned char * b_elems,unsigned char ** maskptr)1886 match_different(const STRUCT_ENTRY_MATCH *a,
1887 		const unsigned char *a_elems,
1888 		const unsigned char *b_elems,
1889 		unsigned char **maskptr)
1890 {
1891 	const STRUCT_ENTRY_MATCH *b;
1892 	unsigned int i;
1893 
1894 	/* Offset of b is the same as a. */
1895 	b = (void *)b_elems + ((unsigned char *)a - a_elems);
1896 
1897 	if (a->u.match_size != b->u.match_size)
1898 		return 1;
1899 
1900 	if (strcmp(a->u.user.name, b->u.user.name) != 0)
1901 		return 1;
1902 
1903 	*maskptr += ALIGN(sizeof(*a));
1904 
1905 	for (i = 0; i < a->u.match_size - ALIGN(sizeof(*a)); i++)
1906 		if (((a->data[i] ^ b->data[i]) & (*maskptr)[i]) != 0)
1907 			return 1;
1908 	*maskptr += i;
1909 	return 0;
1910 }
1911 
1912 static inline int
target_same(struct rule_head * a,struct rule_head * b,const unsigned char * mask)1913 target_same(struct rule_head *a, struct rule_head *b,const unsigned char *mask)
1914 {
1915 	unsigned int i;
1916 	STRUCT_ENTRY_TARGET *ta, *tb;
1917 
1918 	if (a->type != b->type)
1919 		return 0;
1920 
1921 	ta = GET_TARGET(a->entry);
1922 	tb = GET_TARGET(b->entry);
1923 
1924 	switch (a->type) {
1925 	case IPTCC_R_FALLTHROUGH:
1926 		return 1;
1927 	case IPTCC_R_JUMP:
1928 		return a->jump == b->jump;
1929 	case IPTCC_R_STANDARD:
1930 		return ((STRUCT_STANDARD_TARGET *)ta)->verdict
1931 			== ((STRUCT_STANDARD_TARGET *)tb)->verdict;
1932 	case IPTCC_R_MODULE:
1933 		if (ta->u.target_size != tb->u.target_size)
1934 			return 0;
1935 		if (strcmp(ta->u.user.name, tb->u.user.name) != 0)
1936 			return 0;
1937 
1938 		for (i = 0; i < ta->u.target_size - sizeof(*ta); i++)
1939 			if (((ta->data[i] ^ tb->data[i]) & mask[i]) != 0)
1940 				return 0;
1941 		return 1;
1942 	default:
1943 		fprintf(stderr, "ERROR: bad type %i\n", a->type);
1944 		abort();
1945 	}
1946 }
1947 
1948 static unsigned char *
1949 is_same(const STRUCT_ENTRY *a,
1950 	const STRUCT_ENTRY *b,
1951 	unsigned char *matchmask);
1952 
1953 
1954 /* find the first rule in `chain' which matches `fw' and remove it unless dry_run is set */
delete_entry(const IPT_CHAINLABEL chain,const STRUCT_ENTRY * origfw,unsigned char * matchmask,struct xtc_handle * handle,bool dry_run)1955 static int delete_entry(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *origfw,
1956 			unsigned char *matchmask, struct xtc_handle *handle,
1957 			bool dry_run)
1958 {
1959 	struct chain_head *c;
1960 	struct rule_head *r, *i;
1961 
1962 	iptc_fn = TC_DELETE_ENTRY;
1963 	if (!(c = iptcc_find_label(chain, handle))) {
1964 		errno = ENOENT;
1965 		return 0;
1966 	}
1967 
1968 	/* Create a rule_head from origfw. */
1969 	r = iptcc_alloc_rule(c, origfw->next_offset);
1970 	if (!r) {
1971 		errno = ENOMEM;
1972 		return 0;
1973 	}
1974 
1975 	memcpy(r->entry, origfw, origfw->next_offset);
1976 	r->counter_map.maptype = COUNTER_MAP_NOMAP;
1977 	if (!iptcc_map_target(handle, r, dry_run)) {
1978 		DEBUGP("unable to map target of rule for chain `%s'\n", chain);
1979 		free(r);
1980 		return 0;
1981 	} else {
1982 		/* iptcc_map_target increment target chain references
1983 		 * since this is a fake rule only used for matching
1984 		 * the chain references count is decremented again.
1985 		 */
1986 		if (r->type == IPTCC_R_JUMP
1987 		    && r->jump)
1988 			r->jump->references--;
1989 	}
1990 
1991 	list_for_each_entry(i, &c->rules, list) {
1992 		unsigned char *mask;
1993 
1994 		mask = is_same(r->entry, i->entry, matchmask);
1995 		if (!mask)
1996 			continue;
1997 
1998 		if (!target_same(r, i, mask))
1999 			continue;
2000 
2001 		/* if we are just doing a dry run, we simply skip the rest */
2002 		if (dry_run){
2003 			free(r);
2004 			return 1;
2005 		}
2006 
2007 		/* If we are about to delete the rule that is the
2008 		 * current iterator, move rule iterator back.  next
2009 		 * pointer will then point to real next node */
2010 		if (i == handle->rule_iterator_cur) {
2011 			handle->rule_iterator_cur =
2012 				list_entry(handle->rule_iterator_cur->list.prev,
2013 					   struct rule_head, list);
2014 		}
2015 
2016 		c->num_rules--;
2017 		iptcc_delete_rule(i);
2018 
2019 		set_changed(handle);
2020 		free(r);
2021 		return 1;
2022 	}
2023 
2024 	free(r);
2025 	errno = ENOENT;
2026 	return 0;
2027 }
2028 
2029 /* check whether a specified rule is present */
TC_CHECK_ENTRY(const IPT_CHAINLABEL chain,const STRUCT_ENTRY * origfw,unsigned char * matchmask,struct xtc_handle * handle)2030 int TC_CHECK_ENTRY(const IPT_CHAINLABEL chain, const STRUCT_ENTRY *origfw,
2031 		   unsigned char *matchmask, struct xtc_handle *handle)
2032 {
2033 	/* do a dry-run delete to find out whether a matching rule exists */
2034 	return delete_entry(chain, origfw, matchmask, handle, true);
2035 }
2036 
2037 /* Delete the first rule in `chain' which matches `fw'. */
TC_DELETE_ENTRY(const IPT_CHAINLABEL chain,const STRUCT_ENTRY * origfw,unsigned char * matchmask,struct xtc_handle * handle)2038 int TC_DELETE_ENTRY(const IPT_CHAINLABEL chain,	const STRUCT_ENTRY *origfw,
2039 		    unsigned char *matchmask, struct xtc_handle *handle)
2040 {
2041 	return delete_entry(chain, origfw, matchmask, handle, false);
2042 }
2043 
2044 /* Delete the rule in position `rulenum' in `chain'. */
2045 int
TC_DELETE_NUM_ENTRY(const IPT_CHAINLABEL chain,unsigned int rulenum,struct xtc_handle * handle)2046 TC_DELETE_NUM_ENTRY(const IPT_CHAINLABEL chain,
2047 		    unsigned int rulenum,
2048 		    struct xtc_handle *handle)
2049 {
2050 	struct chain_head *c;
2051 	struct rule_head *r;
2052 
2053 	iptc_fn = TC_DELETE_NUM_ENTRY;
2054 
2055 	if (!(c = iptcc_find_label(chain, handle))) {
2056 		errno = ENOENT;
2057 		return 0;
2058 	}
2059 
2060 	if (rulenum >= c->num_rules) {
2061 		errno = E2BIG;
2062 		return 0;
2063 	}
2064 
2065 	/* Take advantage of the double linked list if possible. */
2066 	if (rulenum + 1 <= c->num_rules/2) {
2067 		r = iptcc_get_rule_num(c, rulenum + 1);
2068 	} else {
2069 		r = iptcc_get_rule_num_reverse(c, c->num_rules - rulenum);
2070 	}
2071 
2072 	/* If we are about to delete the rule that is the current
2073 	 * iterator, move rule iterator back.  next pointer will then
2074 	 * point to real next node */
2075 	if (r == handle->rule_iterator_cur) {
2076 		handle->rule_iterator_cur =
2077 			list_entry(handle->rule_iterator_cur->list.prev,
2078 				   struct rule_head, list);
2079 	}
2080 
2081 	c->num_rules--;
2082 	iptcc_delete_rule(r);
2083 
2084 	set_changed(handle);
2085 
2086 	return 1;
2087 }
2088 
2089 /* Flushes the entries in the given chain (ie. empties chain). */
2090 int
TC_FLUSH_ENTRIES(const IPT_CHAINLABEL chain,struct xtc_handle * handle)2091 TC_FLUSH_ENTRIES(const IPT_CHAINLABEL chain, struct xtc_handle *handle)
2092 {
2093 	struct chain_head *c;
2094 	struct rule_head *r, *tmp;
2095 
2096 	iptc_fn = TC_FLUSH_ENTRIES;
2097 	if (!(c = iptcc_find_label(chain, handle))) {
2098 		errno = ENOENT;
2099 		return 0;
2100 	}
2101 
2102 	list_for_each_entry_safe(r, tmp, &c->rules, list) {
2103 		iptcc_delete_rule(r);
2104 	}
2105 
2106 	c->num_rules = 0;
2107 
2108 	set_changed(handle);
2109 
2110 	return 1;
2111 }
2112 
2113 /* Zeroes the counters in a chain. */
2114 int
TC_ZERO_ENTRIES(const IPT_CHAINLABEL chain,struct xtc_handle * handle)2115 TC_ZERO_ENTRIES(const IPT_CHAINLABEL chain, struct xtc_handle *handle)
2116 {
2117 	struct chain_head *c;
2118 	struct rule_head *r;
2119 
2120 	iptc_fn = TC_ZERO_ENTRIES;
2121 	if (!(c = iptcc_find_label(chain, handle))) {
2122 		errno = ENOENT;
2123 		return 0;
2124 	}
2125 
2126 	if (c->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2127 		c->counter_map.maptype = COUNTER_MAP_ZEROED;
2128 
2129 	list_for_each_entry(r, &c->rules, list) {
2130 		if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2131 			r->counter_map.maptype = COUNTER_MAP_ZEROED;
2132 	}
2133 
2134 	set_changed(handle);
2135 
2136 	return 1;
2137 }
2138 
2139 STRUCT_COUNTERS *
TC_READ_COUNTER(const IPT_CHAINLABEL chain,unsigned int rulenum,struct xtc_handle * handle)2140 TC_READ_COUNTER(const IPT_CHAINLABEL chain,
2141 		unsigned int rulenum,
2142 		struct xtc_handle *handle)
2143 {
2144 	struct chain_head *c;
2145 	struct rule_head *r;
2146 
2147 	iptc_fn = TC_READ_COUNTER;
2148 
2149 	if (!(c = iptcc_find_label(chain, handle))) {
2150 		errno = ENOENT;
2151 		return NULL;
2152 	}
2153 
2154 	if (!(r = iptcc_get_rule_num(c, rulenum))) {
2155 		errno = E2BIG;
2156 		return NULL;
2157 	}
2158 
2159 	return &r->entry[0].counters;
2160 }
2161 
2162 int
TC_ZERO_COUNTER(const IPT_CHAINLABEL chain,unsigned int rulenum,struct xtc_handle * handle)2163 TC_ZERO_COUNTER(const IPT_CHAINLABEL chain,
2164 		unsigned int rulenum,
2165 		struct xtc_handle *handle)
2166 {
2167 	struct chain_head *c;
2168 	struct rule_head *r;
2169 
2170 	iptc_fn = TC_ZERO_COUNTER;
2171 
2172 	if (!(c = iptcc_find_label(chain, handle))) {
2173 		errno = ENOENT;
2174 		return 0;
2175 	}
2176 
2177 	if (!(r = iptcc_get_rule_num(c, rulenum))) {
2178 		errno = E2BIG;
2179 		return 0;
2180 	}
2181 
2182 	if (r->counter_map.maptype == COUNTER_MAP_NORMAL_MAP)
2183 		r->counter_map.maptype = COUNTER_MAP_ZEROED;
2184 
2185 	set_changed(handle);
2186 
2187 	return 1;
2188 }
2189 
2190 int
TC_SET_COUNTER(const IPT_CHAINLABEL chain,unsigned int rulenum,STRUCT_COUNTERS * counters,struct xtc_handle * handle)2191 TC_SET_COUNTER(const IPT_CHAINLABEL chain,
2192 	       unsigned int rulenum,
2193 	       STRUCT_COUNTERS *counters,
2194 	       struct xtc_handle *handle)
2195 {
2196 	struct chain_head *c;
2197 	struct rule_head *r;
2198 	STRUCT_ENTRY *e;
2199 
2200 	iptc_fn = TC_SET_COUNTER;
2201 
2202 	if (!(c = iptcc_find_label(chain, handle))) {
2203 		errno = ENOENT;
2204 		return 0;
2205 	}
2206 
2207 	if (!(r = iptcc_get_rule_num(c, rulenum))) {
2208 		errno = E2BIG;
2209 		return 0;
2210 	}
2211 
2212 	e = r->entry;
2213 	r->counter_map.maptype = COUNTER_MAP_SET;
2214 
2215 	memcpy(&e->counters, counters, sizeof(STRUCT_COUNTERS));
2216 
2217 	set_changed(handle);
2218 
2219 	return 1;
2220 }
2221 
2222 /* Creates a new chain. */
2223 /* To create a chain, create two rules: error node and unconditional
2224  * return. */
2225 int
TC_CREATE_CHAIN(const IPT_CHAINLABEL chain,struct xtc_handle * handle)2226 TC_CREATE_CHAIN(const IPT_CHAINLABEL chain, struct xtc_handle *handle)
2227 {
2228 	static struct chain_head *c;
2229 	int capacity;
2230 	int exceeded;
2231 
2232 	iptc_fn = TC_CREATE_CHAIN;
2233 
2234 	/* find_label doesn't cover built-in targets: DROP, ACCEPT,
2235            QUEUE, RETURN. */
2236 	if (iptcc_find_label(chain, handle)
2237 	    || strcmp(chain, LABEL_DROP) == 0
2238 	    || strcmp(chain, LABEL_ACCEPT) == 0
2239 	    || strcmp(chain, LABEL_QUEUE) == 0
2240 	    || strcmp(chain, LABEL_RETURN) == 0) {
2241 		DEBUGP("Chain `%s' already exists\n", chain);
2242 		errno = EEXIST;
2243 		return 0;
2244 	}
2245 
2246 	if (strlen(chain)+1 > sizeof(IPT_CHAINLABEL)) {
2247 		DEBUGP("Chain name `%s' too long\n", chain);
2248 		errno = EINVAL;
2249 		return 0;
2250 	}
2251 
2252 	c = iptcc_alloc_chain_head(chain, 0);
2253 	if (!c) {
2254 		DEBUGP("Cannot allocate memory for chain `%s'\n", chain);
2255 		errno = ENOMEM;
2256 		return 0;
2257 
2258 	}
2259 	handle->num_chains++; /* New user defined chain */
2260 
2261 	DEBUGP("Creating chain `%s'\n", chain);
2262 	iptc_insert_chain(handle, c); /* Insert sorted */
2263 
2264 	/* Inserting chains don't change the correctness of the chain
2265 	 * index (except if its smaller than index[0], but that
2266 	 * handled by iptc_insert_chain).  It only causes longer lists
2267 	 * in the buckets. Thus, only rebuild chain index when the
2268 	 * capacity is exceed with CHAIN_INDEX_INSERT_MAX chains.
2269 	 */
2270 	capacity = handle->chain_index_sz * CHAIN_INDEX_BUCKET_LEN;
2271 	exceeded = handle->num_chains - capacity;
2272 	if (exceeded > CHAIN_INDEX_INSERT_MAX) {
2273 		debug("Capacity(%d) exceeded(%d) rebuild (chains:%d)\n",
2274 		      capacity, exceeded, handle->num_chains);
2275 		iptcc_chain_index_rebuild(handle);
2276 	}
2277 
2278 	set_changed(handle);
2279 
2280 	return 1;
2281 }
2282 
2283 /* Get the number of references to this chain. */
2284 int
TC_GET_REFERENCES(unsigned int * ref,const IPT_CHAINLABEL chain,struct xtc_handle * handle)2285 TC_GET_REFERENCES(unsigned int *ref, const IPT_CHAINLABEL chain,
2286 		  struct xtc_handle *handle)
2287 {
2288 	struct chain_head *c;
2289 
2290 	iptc_fn = TC_GET_REFERENCES;
2291 	if (!(c = iptcc_find_label(chain, handle))) {
2292 		errno = ENOENT;
2293 		return 0;
2294 	}
2295 
2296 	*ref = c->references;
2297 
2298 	return 1;
2299 }
2300 
2301 /* Deletes a chain. */
2302 int
TC_DELETE_CHAIN(const IPT_CHAINLABEL chain,struct xtc_handle * handle)2303 TC_DELETE_CHAIN(const IPT_CHAINLABEL chain, struct xtc_handle *handle)
2304 {
2305 	unsigned int references;
2306 	struct chain_head *c;
2307 
2308 	iptc_fn = TC_DELETE_CHAIN;
2309 
2310 	if (!(c = iptcc_find_label(chain, handle))) {
2311 		DEBUGP("cannot find chain `%s'\n", chain);
2312 		errno = ENOENT;
2313 		return 0;
2314 	}
2315 
2316 	if (TC_BUILTIN(chain, handle)) {
2317 		DEBUGP("cannot remove builtin chain `%s'\n", chain);
2318 		errno = EINVAL;
2319 		return 0;
2320 	}
2321 
2322 	if (!TC_GET_REFERENCES(&references, chain, handle)) {
2323 		DEBUGP("cannot get references on chain `%s'\n", chain);
2324 		return 0;
2325 	}
2326 
2327 	if (references > 0) {
2328 		DEBUGP("chain `%s' still has references\n", chain);
2329 		errno = EMLINK;
2330 		return 0;
2331 	}
2332 
2333 	if (c->num_rules) {
2334 		DEBUGP("chain `%s' is not empty\n", chain);
2335 		errno = ENOTEMPTY;
2336 		return 0;
2337 	}
2338 
2339 	/* If we are about to delete the chain that is the current
2340 	 * iterator, move chain iterator forward. */
2341 	if (c == handle->chain_iterator_cur)
2342 		iptcc_chain_iterator_advance(handle);
2343 
2344 	handle->num_chains--; /* One user defined chain deleted */
2345 
2346 	//list_del(&c->list); /* Done in iptcc_chain_index_delete_chain() */
2347 	iptcc_chain_index_delete_chain(c, handle);
2348 	free(c);
2349 
2350 	DEBUGP("chain `%s' deleted\n", chain);
2351 
2352 	set_changed(handle);
2353 
2354 	return 1;
2355 }
2356 
2357 /* Renames a chain. */
TC_RENAME_CHAIN(const IPT_CHAINLABEL oldname,const IPT_CHAINLABEL newname,struct xtc_handle * handle)2358 int TC_RENAME_CHAIN(const IPT_CHAINLABEL oldname,
2359 		    const IPT_CHAINLABEL newname,
2360 		    struct xtc_handle *handle)
2361 {
2362 	struct chain_head *c;
2363 	iptc_fn = TC_RENAME_CHAIN;
2364 
2365 	/* find_label doesn't cover built-in targets: DROP, ACCEPT,
2366            QUEUE, RETURN. */
2367 	if (iptcc_find_label(newname, handle)
2368 	    || strcmp(newname, LABEL_DROP) == 0
2369 	    || strcmp(newname, LABEL_ACCEPT) == 0
2370 	    || strcmp(newname, LABEL_QUEUE) == 0
2371 	    || strcmp(newname, LABEL_RETURN) == 0) {
2372 		errno = EEXIST;
2373 		return 0;
2374 	}
2375 
2376 	if (!(c = iptcc_find_label(oldname, handle))
2377 	    || TC_BUILTIN(oldname, handle)) {
2378 		errno = ENOENT;
2379 		return 0;
2380 	}
2381 
2382 	if (strlen(newname)+1 > sizeof(IPT_CHAINLABEL)) {
2383 		errno = EINVAL;
2384 		return 0;
2385 	}
2386 
2387 	handle->num_chains--;
2388 
2389 	/* This only unlinks "c" from the list, thus no free(c) */
2390 	iptcc_chain_index_delete_chain(c, handle);
2391 
2392 	/* Change the name of the chain */
2393 	strncpy(c->name, newname, sizeof(IPT_CHAINLABEL) - 1);
2394 
2395 	handle->num_chains++;
2396 
2397 	/* Insert sorted into to list again */
2398 	iptc_insert_chain(handle, c);
2399 
2400 	set_changed(handle);
2401 
2402 	return 1;
2403 }
2404 
2405 /* Sets the policy on a built-in chain. */
2406 int
TC_SET_POLICY(const IPT_CHAINLABEL chain,const IPT_CHAINLABEL policy,STRUCT_COUNTERS * counters,struct xtc_handle * handle)2407 TC_SET_POLICY(const IPT_CHAINLABEL chain,
2408 	      const IPT_CHAINLABEL policy,
2409 	      STRUCT_COUNTERS *counters,
2410 	      struct xtc_handle *handle)
2411 {
2412 	struct chain_head *c;
2413 
2414 	iptc_fn = TC_SET_POLICY;
2415 
2416 	if (!(c = iptcc_find_label(chain, handle))) {
2417 		DEBUGP("cannot find chain `%s'\n", chain);
2418 		errno = ENOENT;
2419 		return 0;
2420 	}
2421 
2422 	if (!iptcc_is_builtin(c)) {
2423 		DEBUGP("cannot set policy of userdefinedchain `%s'\n", chain);
2424 		errno = ENOENT;
2425 		return 0;
2426 	}
2427 
2428 	if (strcmp(policy, LABEL_ACCEPT) == 0)
2429 		c->verdict = -NF_ACCEPT - 1;
2430 	else if (strcmp(policy, LABEL_DROP) == 0)
2431 		c->verdict = -NF_DROP - 1;
2432 	else {
2433 		errno = EINVAL;
2434 		return 0;
2435 	}
2436 
2437 	if (counters) {
2438 		/* set byte and packet counters */
2439 		memcpy(&c->counters, counters, sizeof(STRUCT_COUNTERS));
2440 		c->counter_map.maptype = COUNTER_MAP_SET;
2441 	} else {
2442 		c->counter_map.maptype = COUNTER_MAP_NOMAP;
2443 	}
2444 
2445 	set_changed(handle);
2446 
2447 	return 1;
2448 }
2449 
2450 /* Without this, on gcc 2.7.2.3, we get:
2451    libiptc.c: In function `TC_COMMIT':
2452    libiptc.c:833: fixed or forbidden register was spilled.
2453    This may be due to a compiler bug or to impossible asm
2454    statements or clauses.
2455 */
2456 static void
subtract_counters(STRUCT_COUNTERS * answer,const STRUCT_COUNTERS * a,const STRUCT_COUNTERS * b)2457 subtract_counters(STRUCT_COUNTERS *answer,
2458 		  const STRUCT_COUNTERS *a,
2459 		  const STRUCT_COUNTERS *b)
2460 {
2461 	answer->pcnt = a->pcnt - b->pcnt;
2462 	answer->bcnt = a->bcnt - b->bcnt;
2463 }
2464 
2465 
counters_nomap(STRUCT_COUNTERS_INFO * newcounters,unsigned int idx)2466 static void counters_nomap(STRUCT_COUNTERS_INFO *newcounters, unsigned int idx)
2467 {
2468 	newcounters->counters[idx] = ((STRUCT_COUNTERS) { 0, 0});
2469 	DEBUGP_C("NOMAP => zero\n");
2470 }
2471 
counters_normal_map(STRUCT_COUNTERS_INFO * newcounters,STRUCT_REPLACE * repl,unsigned int idx,unsigned int mappos)2472 static void counters_normal_map(STRUCT_COUNTERS_INFO *newcounters,
2473 				STRUCT_REPLACE *repl, unsigned int idx,
2474 				unsigned int mappos)
2475 {
2476 	/* Original read: X.
2477 	 * Atomic read on replacement: X + Y.
2478 	 * Currently in kernel: Z.
2479 	 * Want in kernel: X + Y + Z.
2480 	 * => Add in X + Y
2481 	 * => Add in replacement read.
2482 	 */
2483 	newcounters->counters[idx] = repl->counters[mappos];
2484 	DEBUGP_C("NORMAL_MAP => mappos %u \n", mappos);
2485 }
2486 
counters_map_zeroed(STRUCT_COUNTERS_INFO * newcounters,STRUCT_REPLACE * repl,unsigned int idx,unsigned int mappos,STRUCT_COUNTERS * counters)2487 static void counters_map_zeroed(STRUCT_COUNTERS_INFO *newcounters,
2488 				STRUCT_REPLACE *repl, unsigned int idx,
2489 				unsigned int mappos, STRUCT_COUNTERS *counters)
2490 {
2491 	/* Original read: X.
2492 	 * Atomic read on replacement: X + Y.
2493 	 * Currently in kernel: Z.
2494 	 * Want in kernel: Y + Z.
2495 	 * => Add in Y.
2496 	 * => Add in (replacement read - original read).
2497 	 */
2498 	subtract_counters(&newcounters->counters[idx],
2499 			  &repl->counters[mappos],
2500 			  counters);
2501 	DEBUGP_C("ZEROED => mappos %u\n", mappos);
2502 }
2503 
counters_map_set(STRUCT_COUNTERS_INFO * newcounters,unsigned int idx,STRUCT_COUNTERS * counters)2504 static void counters_map_set(STRUCT_COUNTERS_INFO *newcounters,
2505                              unsigned int idx, STRUCT_COUNTERS *counters)
2506 {
2507 	/* Want to set counter (iptables-restore) */
2508 
2509 	memcpy(&newcounters->counters[idx], counters,
2510 		sizeof(STRUCT_COUNTERS));
2511 
2512 	DEBUGP_C("SET\n");
2513 }
2514 
2515 
2516 int
TC_COMMIT(struct xtc_handle * handle)2517 TC_COMMIT(struct xtc_handle *handle)
2518 {
2519 	/* Replace, then map back the counters. */
2520 	STRUCT_REPLACE *repl;
2521 	STRUCT_COUNTERS_INFO *newcounters;
2522 	struct chain_head *c;
2523 	int ret;
2524 	size_t counterlen;
2525 	int new_number;
2526 	unsigned int new_size;
2527 
2528 	iptc_fn = TC_COMMIT;
2529 
2530 	/* Don't commit if nothing changed. */
2531 	if (!handle->changed)
2532 		goto finished;
2533 
2534 	new_number = iptcc_compile_table_prep(handle, &new_size);
2535 	if (new_number < 0) {
2536 		errno = ENOMEM;
2537 		goto out_zero;
2538 	}
2539 
2540 	repl = malloc(sizeof(*repl) + new_size);
2541 	if (!repl) {
2542 		errno = ENOMEM;
2543 		goto out_zero;
2544 	}
2545 	memset(repl, 0, sizeof(*repl) + new_size);
2546 
2547 #if 0
2548 	TC_DUMP_ENTRIES(*handle);
2549 #endif
2550 
2551 	counterlen = sizeof(STRUCT_COUNTERS_INFO)
2552 			+ sizeof(STRUCT_COUNTERS) * new_number;
2553 
2554 	/* These are the old counters we will get from kernel */
2555 	repl->counters = calloc(handle->info.num_entries,
2556 				sizeof(STRUCT_COUNTERS));
2557 	if (!repl->counters) {
2558 		errno = ENOMEM;
2559 		goto out_free_repl;
2560 	}
2561 	/* These are the counters we're going to put back, later. */
2562 	newcounters = malloc(counterlen);
2563 	if (!newcounters) {
2564 		errno = ENOMEM;
2565 		goto out_free_repl_counters;
2566 	}
2567 	memset(newcounters, 0, counterlen);
2568 
2569 	strcpy(repl->name, handle->info.name);
2570 	repl->num_entries = new_number;
2571 	repl->size = new_size;
2572 
2573 	repl->num_counters = handle->info.num_entries;
2574 	repl->valid_hooks  = handle->info.valid_hooks;
2575 
2576 	DEBUGP("num_entries=%u, size=%u, num_counters=%u\n",
2577 		repl->num_entries, repl->size, repl->num_counters);
2578 
2579 	ret = iptcc_compile_table(handle, repl);
2580 	if (ret < 0) {
2581 		errno = ret;
2582 		goto out_free_newcounters;
2583 	}
2584 
2585 
2586 #ifdef IPTC_DEBUG2
2587 	{
2588 		int fd = open("/tmp/libiptc-so_set_replace.blob",
2589 				O_CREAT|O_WRONLY, 0644);
2590 		if (fd >= 0) {
2591 			write(fd, repl, sizeof(*repl) + repl->size);
2592 			close(fd);
2593 		}
2594 	}
2595 #endif
2596 
2597 	ret = setsockopt(handle->sockfd, TC_IPPROTO, SO_SET_REPLACE, repl,
2598 			 sizeof(*repl) + repl->size);
2599 	if (ret < 0)
2600 		goto out_free_newcounters;
2601 
2602 	/* Put counters back. */
2603 	strcpy(newcounters->name, handle->info.name);
2604 	newcounters->num_counters = new_number;
2605 
2606 	list_for_each_entry(c, &handle->chains, list) {
2607 		struct rule_head *r;
2608 
2609 		/* Builtin chains have their own counters */
2610 		if (iptcc_is_builtin(c)) {
2611 			DEBUGP("counter for chain-index %u: ", c->foot_index);
2612 			switch(c->counter_map.maptype) {
2613 			case COUNTER_MAP_NOMAP:
2614 				counters_nomap(newcounters, c->foot_index);
2615 				break;
2616 			case COUNTER_MAP_NORMAL_MAP:
2617 				counters_normal_map(newcounters, repl,
2618 						    c->foot_index,
2619 						    c->counter_map.mappos);
2620 				break;
2621 			case COUNTER_MAP_ZEROED:
2622 				counters_map_zeroed(newcounters, repl,
2623 						    c->foot_index,
2624 						    c->counter_map.mappos,
2625 						    &c->counters);
2626 				break;
2627 			case COUNTER_MAP_SET:
2628 				counters_map_set(newcounters, c->foot_index,
2629 						 &c->counters);
2630 				break;
2631 			}
2632 		}
2633 
2634 		list_for_each_entry(r, &c->rules, list) {
2635 			DEBUGP("counter for index %u: ", r->index);
2636 			switch (r->counter_map.maptype) {
2637 			case COUNTER_MAP_NOMAP:
2638 				counters_nomap(newcounters, r->index);
2639 				break;
2640 
2641 			case COUNTER_MAP_NORMAL_MAP:
2642 				counters_normal_map(newcounters, repl,
2643 						    r->index,
2644 						    r->counter_map.mappos);
2645 				break;
2646 
2647 			case COUNTER_MAP_ZEROED:
2648 				counters_map_zeroed(newcounters, repl,
2649 						    r->index,
2650 						    r->counter_map.mappos,
2651 						    &r->entry->counters);
2652 				break;
2653 
2654 			case COUNTER_MAP_SET:
2655 				counters_map_set(newcounters, r->index,
2656 						 &r->entry->counters);
2657 				break;
2658 			}
2659 		}
2660 	}
2661 
2662 #ifdef IPTC_DEBUG2
2663 	{
2664 		int fd = open("/tmp/libiptc-so_set_add_counters.blob",
2665 				O_CREAT|O_WRONLY, 0644);
2666 		if (fd >= 0) {
2667 			write(fd, newcounters, counterlen);
2668 			close(fd);
2669 		}
2670 	}
2671 #endif
2672 
2673 	ret = setsockopt(handle->sockfd, TC_IPPROTO, SO_SET_ADD_COUNTERS,
2674 			 newcounters, counterlen);
2675 	if (ret < 0)
2676 		goto out_free_newcounters;
2677 
2678 	free(repl->counters);
2679 	free(repl);
2680 	free(newcounters);
2681 
2682 finished:
2683 	return 1;
2684 
2685 out_free_newcounters:
2686 	free(newcounters);
2687 out_free_repl_counters:
2688 	free(repl->counters);
2689 out_free_repl:
2690 	free(repl);
2691 out_zero:
2692 	return 0;
2693 }
2694 
2695 /* Translates errno numbers into more human-readable form than strerror. */
2696 const char *
TC_STRERROR(int err)2697 TC_STRERROR(int err)
2698 {
2699 	unsigned int i;
2700 	struct table_struct {
2701 		void *fn;
2702 		int err;
2703 		const char *message;
2704 	} table [] =
2705 	  { { TC_INIT, EPERM, "Permission denied (you must be root)" },
2706 	    { TC_INIT, EINVAL, "Module is wrong version" },
2707 	    { TC_INIT, ENOENT,
2708 		    "Table does not exist (do you need to insmod?)" },
2709 	    { TC_DELETE_CHAIN, ENOTEMPTY, "Chain is not empty" },
2710 	    { TC_DELETE_CHAIN, EINVAL, "Can't delete built-in chain" },
2711 	    { TC_DELETE_CHAIN, EMLINK,
2712 	      "Can't delete chain with references left" },
2713 	    { TC_CREATE_CHAIN, EEXIST, "Chain already exists" },
2714 	    { TC_INSERT_ENTRY, E2BIG, "Index of insertion too big" },
2715 	    { TC_REPLACE_ENTRY, E2BIG, "Index of replacement too big" },
2716 	    { TC_DELETE_NUM_ENTRY, E2BIG, "Index of deletion too big" },
2717 	    { TC_READ_COUNTER, E2BIG, "Index of counter too big" },
2718 	    { TC_ZERO_COUNTER, E2BIG, "Index of counter too big" },
2719 	    { TC_INSERT_ENTRY, ELOOP, "Loop found in table" },
2720 	    { TC_INSERT_ENTRY, EINVAL, "Target problem" },
2721 	    /* ENOENT for DELETE probably means no matching rule */
2722 	    { TC_DELETE_ENTRY, ENOENT,
2723 	      "Bad rule (does a matching rule exist in that chain?)" },
2724 	    { TC_SET_POLICY, ENOENT,
2725 	      "Bad built-in chain name" },
2726 	    { TC_SET_POLICY, EINVAL,
2727 	      "Bad policy name" },
2728 
2729 	    { NULL, 0, "Incompatible with this kernel" },
2730 	    { NULL, ENOPROTOOPT, "iptables who? (do you need to insmod?)" },
2731 	    { NULL, ENOSYS, "Will be implemented real soon.  I promise ;)" },
2732 	    { NULL, ENOMEM, "Memory allocation problem" },
2733 	    { NULL, ENOENT, "No chain/target/match by that name" },
2734 	  };
2735 
2736 	for (i = 0; i < sizeof(table)/sizeof(struct table_struct); i++) {
2737 		if ((!table[i].fn || table[i].fn == iptc_fn)
2738 		    && table[i].err == err)
2739 			return table[i].message;
2740 	}
2741 
2742 	return strerror(err);
2743 }
2744 
2745 const struct xtc_ops TC_OPS = {
2746 	.commit        = TC_COMMIT,
2747 	.init          = TC_INIT,
2748 	.free          = TC_FREE,
2749 	.builtin       = TC_BUILTIN,
2750 	.is_chain      = TC_IS_CHAIN,
2751 	.flush_entries = TC_FLUSH_ENTRIES,
2752 	.create_chain  = TC_CREATE_CHAIN,
2753 	.first_chain   = TC_FIRST_CHAIN,
2754 	.next_chain    = TC_NEXT_CHAIN,
2755 	.get_policy    = TC_GET_POLICY,
2756 	.set_policy    = TC_SET_POLICY,
2757 	.strerror      = TC_STRERROR,
2758 };
2759