sailfish_iptables_ext.c 37.7 KB
Newer Older
1 2 3
/*
 *
 *  Connection Manager wrapper implementation of the exposed iptables
Slava Monich's avatar
Slava Monich committed
4 5
 *  functions for SailfishOS MDM. Contains save, restore and clear
 *  functionality.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
 *
 *  Copyright (C) 2017-2018 Jolla Ltd. All rights reserved.
 *  Contact: Jussi Laakkonen <jussi.laakkonen@jolla.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 */
 
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#define CONNMAN_API_SUBJECT_TO_CHANGE
#include "src/connman.h"

#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <limits.h>

#include <netdb.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <libgen.h>
#include <endian.h>

#include <netinet/ip.h>
#include <xtables.h>
#include <libiptc/libiptc.h>

#include <linux/netfilter/xt_connmark.h>

#include <iptables_ext.h>

#define INFO(fmt,arg...)			connman_info(fmt, ## arg)
#define ERR(fmt,arg...)				connman_error(fmt, ## arg)

#define IPTABLES_NAMES_FILE			"/proc/net/ip_tables_names"

gint check_save_directory(const char* fpath)
{
	gchar* path = NULL;
	gint mode = S_IRWXU;
	gint access_mode = R_OK|W_OK|X_OK;
	gint rval = 0;
	
	if (!fpath || !(*fpath))
		return 1;
		
	path = g_path_get_dirname(fpath);
	
	// If given path has no proper prefix or is is ending with / or
	// is the same as the STORAGEDIR path
	if (!g_str_has_prefix(path, STORAGEDIR) || g_str_has_suffix(path,"/") ||
		g_strcmp0(path,STORAGEDIR) == 0) {
		rval = 1;
		goto out;
	}

	if (g_file_test(path,G_FILE_TEST_EXISTS)) {
		// Try to remove regular file or symlink 
		if (g_file_test(path,G_FILE_TEST_IS_REGULAR) ||
			g_file_test(path, G_FILE_TEST_IS_SYMLINK)) {
85
			DBG("Removing %s",path);
86
			if (g_remove(path)) {
87 88
				ERR("check_save_directory() Remove of %s "
					"failed (%s)", path, strerror(errno));
89 90 91 92 93 94 95 96 97
				rval = -1;
				goto out;
			}
		}
		
		// exists and is a dir
		if (g_file_test(path, G_FILE_TEST_IS_DIR)) {
			// Check that this dir can be accessed
			if (access(path, access_mode) == -1) {
98 99 100
				ERR("check_save_directory() Dir %s "
					"cannot be accessed (%s).", path,
					strerror(errno));
101 102 103 104
				rval = -1;
				goto out;
			}
			
105
			DBG("Dir %s exists, nothing done.", path);
106 107 108 109
			goto out;
		}
	}
	
110
	DBG("Creating new dir for saving %s", path);
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
	rval = g_mkdir_with_parents(path,mode);

out:
	g_free(path);
	return rval;
}

/*
	Set content to given file, calls check_save_directory() to check the
	save location.
	
	@returns: 0 on success, 1 on access/content and -1 on parameter error.
*/
gint iptables_set_file_contents(const gchar *fpath, GString *str,
	gboolean free_str)
{
	gint rval = 1;
	
	if (!fpath || !(*fpath) || !str || !str->len)
		return -1;
		
	if (!check_save_directory(fpath)) {
		GError *err = NULL;
		
135 136
		rval = g_file_set_contents(fpath, str->str, str->len, &err) ?
				0 : 1;
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
			
		if (rval || err) {
			ERR("iptables_set_file_contents() %s",
				err ? err->message : "noerror");
			g_error_free(err);
		}
	}
	
	if (free_str && str)
		g_string_free(str, true);
	
	return rval;
}

/*
	Get content from a file specified in path.
*/
GString* iptables_get_file_contents(const gchar* fpath)
{
	GString *contents = NULL;
	
	if (fpath && *fpath && g_str_has_prefix(fpath, STORAGEDIR)) {
		gchar *content = NULL;
		gsize len = -1;
		GError *err = NULL;
		
		if (g_file_get_contents(fpath, &content, &len, &err))
			contents = g_string_new_len(content, len);
		else {
			ERR("iptables_get_file_contents() %s", err->message);
			g_error_free(err);
		}
		
		g_free(content);
	}
	return contents;
}

static gboolean str_has_connman_prefix(const gchar* str)
{
	if(!str)
		return false;

	return g_str_has_prefix(str,"connman-");
}

static gboolean str_contains_connman(const gchar* str)
{
	if(!str)
		return false;
	
	return g_strrstr(str, "connman-") ? true : false;
}

typedef struct output_capture_data {
	gint stdout_pipes[2];
	gint stdout_saved;
	gint stdout_read_limit;
	gint stdout_bytes_read;
	gchar *stdout_data;
} output_capture_data;

199
gint stdout_capture_end(output_capture_data *data)
200
{
201 202 203 204 205
	gint rval = 0;

	if(!data)
		return 1;

206
	if (fflush(stdout))
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
		DBG("fflushing stdout failed: %s", strerror(errno));

	if (data->stdout_saved != -1) {
		if (dup2(data->stdout_saved,fileno(stdout)) == -1) {
			DBG("Cannot restore stdout: %s", strerror(errno));
			rval = -1;
		}

		if (close(data->stdout_saved) == -1) {
			DBG("Cannot close saved stdout: %s", strerror(errno));
			rval = -1;
		} else {
			data->stdout_saved = -1;
		}
	}

	if (data->stdout_pipes[0] != -1) {
		if (close(data->stdout_pipes[0]) == -1) {
			DBG("Cannot close stdout_pipes[0]: %s",
				strerror(errno));
			rval = -1;
		}

		data->stdout_pipes[0] = -1;
	}

	if (data->stdout_pipes[1] != -1 ) {
		if (close(data->stdout_pipes[1])) {
			DBG("Cannot close stdout_pipes[1]: %s",
				strerror(errno));
			rval = -1;
		}
	}

	return rval != -1 ? 0 : 1;
}

gint stdout_capture_start(output_capture_data *data)
{
	if(!data)
		return -1;

	if (fflush(stdout)) {
		DBG("fflushing stdout failed: %s", strerror(errno));
		goto error;
	}

254
	data->stdout_saved = dup(fileno(stdout));
255 256 257 258

	if (data->stdout_saved == -1) {
		DBG("Cannot copy stdout: %s", strerror(errno));
		goto error;
259
	}
260 261 262 263 264 265

	if (pipe(data->stdout_pipes) == -1) {
		DBG("cannot create pipe: %s", strerror(errno));
		goto error;
	}

266
	if (dup2(data->stdout_pipes[1], fileno(stdout)) == -1) {
267 268
		DBG("cannot duplicate fp with dup2: %s", strerror(errno));
		goto error;
269 270 271
	}
	
	if (close(data->stdout_pipes[1])) {
272 273
		DBG("cannot close existing fp: %s", strerror(errno));
		goto error;
274 275 276 277 278
	}
	
	data->stdout_pipes[1] = -1;
	
	return 0;
279 280 281 282

error:
	stdout_capture_end(data);
	return -1;
283 284 285 286 287 288 289
}

void stdout_capture_data(output_capture_data *data)
{
	data->stdout_data = g_try_malloc0(data->stdout_read_limit);
	ssize_t bytes_read = 0;

290 291 292 293 294
	if (fflush(stdout)) {
		DBG("fflushing stdout failed: %s", strerror(errno));
		return;
	}

295 296 297 298 299 300 301 302 303 304 305
	do {
		bytes_read = read(data->stdout_pipes[0],
			&(data->stdout_data[data->stdout_bytes_read]),
			data->stdout_read_limit);

		data->stdout_bytes_read += bytes_read;
		
		// Read full amount
		if (bytes_read == data->stdout_read_limit) {
			// Increase size of the data by the amount of read limit
			data->stdout_data = g_try_realloc(data->stdout_data, 
306 307
				data->stdout_bytes_read +
					data->stdout_read_limit);
308
			
309 310 311
			// g_try_realloc() does not zero content, use memset
			memset(&(data->stdout_data[data->stdout_bytes_read]),
				'\0', data->stdout_read_limit);
312 313 314 315 316 317 318 319 320 321 322
		}
		// Read less than limit, stop
		else
			break;
			
	} while (bytes_read > 0);
	
	if (bytes_read == -1)
		ERR("stdout_capture_data() error while reading stdout: %s",
			strerror(errno));
	
323 324
	if (fflush(stdout))
		DBG("flushing stdout failed");
325 326 327 328 329 330 331
}

/*
	Calls the save() function of iptables entry. Captures the stdout
	of the save() method and appends it to given GString.
*/
static void print_target_or_match(GString *line, const void *ip,
332 333
	const struct xtables_target *target,
	const struct xt_entry_target *t_entry,
334 335 336
	const struct xtables_match *match, const struct xt_entry_match *m_entry)
{
	output_capture_data data = {
337 338
		.stdout_pipes = {-1},
		.stdout_saved = -1,
339 340 341 342 343 344 345 346 347
		.stdout_read_limit = 1024,
		.stdout_bytes_read = 0,
		.stdout_data = NULL
	};
	
	if (!(line && ip && ((target && t_entry) || (match && m_entry))))
		return;


348 349 350 351
	if (stdout_capture_start(&data)) {
		ERR("Starting stdout capture failed.");
		goto out;
	}
352 353 354 355 356 357 358 359
	
	// t_entry/m_entry->u.user.revision from iptables 1.6.1 iptables.c:1139
	if (target && t_entry && target->save &&
		t_entry->u.user.revision == target->revision)
		target->save(ip,t_entry);
	else if (match && m_entry && match->save && 
		m_entry->u.user.revision == match->revision)
		match->save(ip,m_entry);
360

361 362 363 364 365 366
	stdout_capture_data(&data);
	
	if (data.stdout_bytes_read > 0) {
		g_string_append(line,data.stdout_data);
		g_free(data.stdout_data);
	}
367 368

out:
369 370 371 372 373
	if (stdout_capture_end(&data))
		ERR("Ending stdout capture failed.");
}

static void print_target(GString *line, const void *ip,
374 375
	const struct xtables_target *target,
	const struct xt_entry_target *entry)
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
{
	if (line && ip && target && entry)
		print_target_or_match(line,ip,target,entry,NULL,NULL);
}

static void print_match(GString *line, const void *ip,
	const struct xtables_match *match, const struct xt_entry_match *entry)
{
	if (line && ip && match && entry)
		print_target_or_match(line,ip,NULL,NULL,match,entry);
}

/* 	Adapted from GPLv2 iptables source file (v.1.4.15) iptables.c:987
	function print_proto().
*/
static void print_proto(GString* line, uint16_t proto, int invert)
{
	if (proto) {
		unsigned int i;
		const char *invertstr = invert ? " !" : "";

		const struct protoent *pent = getprotobynumber(proto);
		if (pent) {
399 400
			g_string_append_printf(line,"%s -p %s", invertstr,
						pent->p_name);
401 402 403 404 405 406
			return;
		}

		for (i = 0; xtables_chain_protos[i].name != NULL; ++i) {
			if (xtables_chain_protos[i].num == proto) {
				g_string_append_printf(line,"%s -p %s",
407 408
						invertstr,
						xtables_chain_protos[i].name);
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
				return;
			}
		}
		g_string_append_printf(line,"%s -p %u", invertstr, proto);
	}
}

/* 	From GPLv2 iptables source file (v.1.4.15) iptables.c:1010 */
#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))

/* 	Adapted from GPLv2 iptables source file (v.1.4.15) iptables.c:1068
	function print_ip().
*/
static void print_ip(GString* line, const char *prefix, uint32_t ip,
			uint32_t mask, int invert)
{
	uint32_t bits, hmask = ntohl(mask);
	int i;
	
	if (!mask && !ip && !invert)
		return;
	
	g_string_append_printf(line, "%s %s %u.%u.%u.%u",
		invert ? " !" : "",
		prefix,
		IP_PARTS(ip));

	if (mask == 0xFFFFFFFFU)
		g_string_append(line,"/32");
	else {
		i    = 32;
		bits = 0xFFFFFFFEU;
		while (--i >= 0 && hmask != bits)
			bits <<= 1;
		if (i >= 0)
			g_string_append_printf(line,"/%u", i);
		else
452 453
			g_string_append_printf(line,"/%u.%u.%u.%u",
					IP_PARTS(mask));
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487
	}
}

/* 	Adapted from GPLv2 iptables source file (v.1.4.15) iptables.c:1020
	function print_iface().
*/
static void print_iface(GString* line, char letter, const char *iface,
	const unsigned char *mask, int invert)
{
	unsigned int i;

	if (mask[0] == 0)
		return;

	g_string_append_printf(line,"%s -%c ", invert ? " !" : "", letter);

	for (i = 0; i < IFNAMSIZ; i++) {
		if (mask[i] != 0) {
			if (iface[i] != '\0')
				g_string_append_printf(line,"%c", iface[i]);
		} else {
			/* we can access iface[i-1] here, because
			 * a few lines above we make sure that mask[0] != 0 */
			if (iface[i-1] != '\0')
				g_string_append(line,"+");
			break;
		}
	}
}

/* Re-implemented XT_MATCH_ITERATE preprocessor macro in C from GPLv2 iptables
	source header include/linux/netfilter/x_tables.h
*/
static int match_iterate(
488
	GString *line, const struct ipt_entry *entry, const struct ipt_ip *ip,
489
	int (*fn) (
490 491 492 493
		GString *fn_line,
		const struct xt_entry_match *fn_entry, 
		const struct ipt_ip *fn_ip)
	 )
494
{
495
	guint i = 0;
496
	gint rval = 0;
497 498 499 500
	struct xt_entry_match *match = NULL;
	
	if(!line || !entry || !ip || !fn)
		return 1;
501 502
	
	for (i = sizeof(struct ipt_entry);
503 504 505 506
		i < (entry)->target_offset;
		i += match ? match->u.match_size : 0) {
		match = (void *)entry + i;
		rval = fn(line, match, ip);
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
		if (rval != 0)
			break;
	}
	return rval;
}

/* 	Adapted from GPLv2 iptables source file (v.1.6.1) iptables.c:1025
	function print_match_save().
*/
static int print_match_save(GString *line, const struct xt_entry_match *e,
			const struct ipt_ip *ip)
{
	struct xtables_match *match =
		xtables_find_match(e->u.user.name, XTF_TRY_LOAD, NULL);

	if (match) {
		g_string_append_printf(line, " -m %s",
			match->alias ? match->alias(e) : e->u.user.name);
		print_match(line, ip, match, e);
526 527 528 529 530 531 532 533 534

		/*
		 * xtables_find_match allocates a clone in case the found
		 * match has struct xt_entry_match* set (match->m). Otherwise
		 * an entry from the internal list is returned that must not
		 * be free'd. (iptables v.1.6.1 libxtables/xtables.c:653)
		 */
		if (match->m)
			free(match);
535 536
	} else {
		if (e->u.match_size) {
537 538
			ERR("print_match_save() Can't find library for match "
				"`%s'", e->u.user.name);
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
			return 1;
		}
	}
	return 0;
}

/* 	Adapted from GPLv2 iptables source file (v.1.4.15) iptables.c:1099
	function print_rule4().
*/
void print_iptables_rule(GString* line, const struct ipt_entry *e,
		struct xtc_handle *h, const char *chain, int counters)
{
	const struct xt_entry_target *t = NULL;
	const char *target_name = NULL;

	/* print counters for iptables-save */
	if (counters > 0)
		g_string_append_printf(line,"[%llu:%llu] ", 
				(unsigned long long)e->counters.pcnt,
				(unsigned long long)e->counters.bcnt);
	
	/* print chain name */
	g_string_append_printf(line,"-A %s", chain);

	/* Print IP part. */
	print_ip(line,"-s", e->ip.src.s_addr,e->ip.smsk.s_addr,
			e->ip.invflags & IPT_INV_SRCIP);	

	print_ip(line,"-d", e->ip.dst.s_addr, e->ip.dmsk.s_addr,
			e->ip.invflags & IPT_INV_DSTIP);

	print_iface(line,'i', e->ip.iniface, e->ip.iniface_mask,
			e->ip.invflags & IPT_INV_VIA_IN);

	print_iface(line,'o', e->ip.outiface, e->ip.outiface_mask,
			e->ip.invflags & IPT_INV_VIA_OUT);

	print_proto(line,e->ip.proto, e->ip.invflags & XT_INV_PROTO);

	if (e->ip.flags & IPT_F_FRAG)
		g_string_append_printf(line,"%s -f",
			e->ip.invflags & IPT_INV_FRAG ? " !" : "");
	
	/* Print matchinfo part */
	if (e->target_offset)
584
		match_iterate(line, e, &e->ip, print_match_save);
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601

	/* print counters for iptables -R */
	if (counters < 0)
		g_string_append_printf(line," -c %llu %llu",
			(unsigned long long)e->counters.pcnt,
			(unsigned long long)e->counters.bcnt);
	
	/* Print target name and targinfo part */
	// iptc_get_target() returns an empty string if target does not exist
	target_name = iptc_get_target(e, h);
	t = ipt_get_target((struct ipt_entry *)e);
	
	if (t->u.user.name[0]) {
		const struct xtables_target *target =
			xtables_find_target(t->u.user.name, XTF_TRY_LOAD);
		
		if (!target) {
602 603
			ERR("print_iptables_rule() can't find library for "
				"target `%s'\n", t->u.user.name);
604 605 606 607 608
			return;
		}

		// Make sure that alias exists or target_name has content
		if (target->alias || *target_name) {
609 610 611 612
			/*
			 * Iptables v1.6.1 iptables.c:1138 print target info
			 * before checks
			 */
613 614 615 616 617 618 619 620 621 622 623 624
			g_string_append_printf(line, " -j %s",
				target->alias ? target->alias(t) : target_name);
		}
			
		print_target(line, &e->ip, target, t);
	} else if (target_name && (*target_name != '\0'))
		g_string_append_printf(line," -%c %s",
			e->ip.flags & IPT_F_GOTO ? 'g' : 'j', target_name);

	g_string_append(line, "\n");
}

625 626 627 628 629 630 631 632 633 634 635 636
static struct xtc_handle* get_iptc_handle(const char *table_name)
{
	struct xtc_handle *h = NULL;

	if (table_name && *table_name) {
		h = iptc_init(table_name);

		if (!h) {
			xtables_load_ko(xtables_modprobe_program, false);
			h = iptc_init(table_name);
		}
		if (!h)
637 638 639
			ERR("get_iptc_handle() Cannot initialize iptc: %s "
				"for table %s\n", iptc_strerror(errno),
				table_name);
640 641 642 643 644 645
	}

	return h;
}


646 647 648 649 650 651 652 653
/* 	Adapted from GPLv2 iptables source file (v.1.4.15) iptables-save.c:35
	function for_each_table().
*/
int iptables_check_table(const char *table_name)
{
	int ret = 1;
	FILE *procfile = NULL;
	char read_table_name[XT_TABLE_MAXNAMELEN+1];
654
	struct xtc_handle *handle = NULL;
655 656 657 658
	
	if (!table_name || !(*table_name))
		return ret;
	
659 660 661 662 663 664 665
	/* Try to get iptc handle for the table first,
	 * otherwise read from file */
	if ((handle = get_iptc_handle(table_name))) {
		iptc_free(handle);
		return 0;
	}

666 667 668 669 670 671 672
	memset(&read_table_name,0,sizeof(read_table_name));

	procfile = fopen(IPTABLES_NAMES_FILE, "re");
	
	if (!procfile) {
		switch (errno) {
		case ENOENT:
673 674
			ERR("iptables_check_table() names file %s "
				"does not exist", IPTABLES_NAMES_FILE);
675 676
			return -ENOENT;
		case EACCES:
677 678
			ERR("iptables_check_table() names file %s "
				"cannot be accessed", IPTABLES_NAMES_FILE);
679 680
			return -EACCES;
		default:
681 682
			ERR("iptables_check_table() cannot open names file "
				"%s, %s", IPTABLES_NAMES_FILE, strerror(errno));
683 684 685 686 687 688
			return -1;
		}
	}
	
	while (fgets(read_table_name, sizeof(read_table_name), procfile)) {
		if (read_table_name[strlen(read_table_name) - 1] != '\n')
689 690
			ERR("iptables_check_table() Badly formed table_name "
				"`%s'", read_table_name);
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820
		else {
			read_table_name[strlen(read_table_name) - 1] = '\0';
		
			ret = g_ascii_strcasecmp(read_table_name,table_name);
		
			if (!ret) // 0, match
				break;
		}
		
		memset(&read_table_name,0,sizeof(read_table_name));
	}

	fclose(procfile);
	return ret;
}

/* 	Adapted from GPLv2 iptables source file (v.1.4.15) iptables-save.c:59
	function do_output().
*/
static int iptables_save_table(const char *fpath, GString** output,
	const char *table_name, gboolean save_to_file)
{
	struct xtc_handle *h = NULL;
	const char *chain = NULL;
	GString *line = NULL;
	time_t now = {0};
	gint table_result = iptables_check_table(table_name);
	
	switch (table_result) {
	case 0:
		break;
	case 1:
		ERR("iptables_save_table() called with invalid table name");
	default:
		return 1; // Error accessing iptables names file
	}
	
	if (!save_to_file && (!output || !(*output) || (*output)->len)) {
		ERR("iptables_save_table() invalid GString pointer given");
		return 1;
	}
	
	DBG("%s %s", "iptables_save_table() saving table: ", table_name);
	
	if (!(h = get_iptc_handle(table_name)))
		return 1;
	
	// Create new Gstring only if saving to file
	if (fpath) {
		line = g_string_new("");
		now = time(NULL);
	
		g_string_append_printf(line,"# Generated by connman on %s",
			ctime(&now));
		g_string_append_printf(line,"*%s\n", table_name);
	} else
		line = *output; // Use given GString

	/* Dump out chain names first,
	 * thereby preventing dependency conflicts */
	for (chain = iptc_first_chain(h); chain; chain = iptc_next_chain(h)) {
	
		// Skip chains with connman prefix
		if(str_has_connman_prefix(chain))
			continue;
	
		g_string_append_printf(line,":%s ", chain);
		if (iptc_builtin(chain, h)) {
			struct xt_counters count = {0};
			
			g_string_append_printf(line,"%s ",
					iptc_get_policy(chain, &count, h));
					
			g_string_append_printf(line,"[%llu:%llu]\n", 
					(unsigned long long)count.pcnt,
					(unsigned long long)count.bcnt);
		} else
			g_string_append_printf(line,"- [0:0]\n");
	}

	for (chain = iptc_first_chain(h); chain; chain = iptc_next_chain(h)) {
		const struct ipt_entry *e = NULL;
		
		// Skip chains with connman prefix
		if(str_has_connman_prefix(chain))
			continue;

		/* Dump out rules */
		e = iptc_first_rule(chain, h);
		while (e) {
			print_iptables_rule(line, e, h, chain, 0);
			e = iptc_next_rule(e, h);
		}
	}

	now = time(NULL);
	
	if (fpath) {
		g_string_append_printf(line,"COMMIT\n");
		g_string_append_printf(line,"# Completed on %s", ctime(&now));
	}
	
	iptc_free(h);
	
	if (fpath)
		return iptables_set_file_contents(fpath, line, true);
	else
		return 0;
}

static int iptables_clear_table(const char *table_name)
{
	struct xtc_handle *h = NULL;
	const char *chain = NULL;
	gint rval = 0;
	gint table_result = iptables_check_table(table_name);
	
	switch (table_result) {
	case 0:
		break;
	case 1:
		ERR("iptables_clear_table() called with invalid table name");
	default:
		return 1; // Error accessing iptables names file
	}
			
	if (!(h = get_iptc_handle(table_name)))
		return 1;
	
	for (chain = iptc_first_chain(h); chain; chain = iptc_next_chain(h)) {
821 822 823 824 825

		// Skip chains with connman prefix
		if (str_has_connman_prefix(chain))
			continue;

826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
		if (!iptc_flush_entries(chain,h))
			rval = 1;
	}

	if (!iptc_commit(h))
		rval = 1;
	
	if (h)
		iptc_free(h);

	return rval;
}

static int iptables_iptc_set_policy(const gchar* table_name,
	const gchar* chain, const gchar* policy,
	guint64 packet_counter, guint64 byte_counter)
{
	gint rval = 0;
	struct xtc_handle *h = NULL;
	struct xt_counters counters = {0};
	
847 848
	if (!(table_name && *table_name && chain && *chain && policy &&
		*policy))
849 850 851 852 853 854
		return 1;
		
	if (!(h = get_iptc_handle(table_name)))
		return 1;

	if (!iptc_is_chain(chain,h)) {
855
		DBG("Chain \"%s\" does not exist, adding new.", chain);
856 857 858 859 860 861 862 863 864 865 866 867 868 869
		rval = connman_iptables_new_chain(table_name, chain);
		goto out; // No policy change for custom chains
	}
	
	// Do nothing for chains that are not builtin, iptc_set_policy supports
	// builtin only
	if (!iptc_builtin(chain,h))
		goto out;

	counters.pcnt = packet_counter;
	counters.bcnt = byte_counter;

	DBG("Set to table \"%s\" chain \"%s\" policy \"%s\" counters %llu %llu",
		table_name, chain, policy,
870 871
		(unsigned long long)packet_counter,
		(unsigned long long)byte_counter);
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895

	// returns 1 on success
	if (!iptc_set_policy(chain, policy, &counters, h)) {
		ERR("iptables_iptc_set_policy() policy cannot be set %s", 
			iptc_strerror(errno));
		rval = 1;
		goto out;
	}
	
	if (!iptc_commit(h)) {
		ERR("iptables_iptc_set_policy() commit error %s",
			iptc_strerror(errno));
		rval = 1;
	}

out:
	if (h)
		iptc_free(h);

	return rval;
}

static int iptables_parse_policy(const gchar* table_name, const gchar* policy)
{
Slava Monich's avatar
Slava Monich committed
896 897
	gint rval = 1;
	guint policy_tokens = 3;
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
	
	if (!table_name || !(*table_name) || !policy || !(*policy))
		return rval;
		
	// Format :CHAIN POLICY [int:int]
	gchar** tokens = g_strsplit(&(policy[1]), " ", policy_tokens);
	
	if (tokens && g_strv_length(tokens) == policy_tokens) {
	
		// Check chain for connman prefix
		if(str_has_connman_prefix(tokens[0]))
			goto out;
	
		gchar** counter_tokens = g_strsplit_set(tokens[2], "[:]", -1);

		if (counter_tokens && g_strv_length(counter_tokens) > 2) {
914 915 916 917 918 919 920 921
			/*
			 * Counters start with '[' so first token is empty so
			 * start from 1
			 */
			guint64 packet_cntr = g_ascii_strtoull(
						counter_tokens[1],NULL, 10);
			guint64 byte_cntr = g_ascii_strtoull(counter_tokens[2],
						NULL, 10);
922
			
923 924
			rval = iptables_iptc_set_policy(table_name, tokens[0],
					tokens[1], packet_cntr, byte_cntr);
925 926 927 928 929 930 931 932 933 934
		}
		g_strfreev(counter_tokens);
	
	}
out:
	g_strfreev(tokens);
	
	return rval;
}

935
static void iptables_append_arg(GString *string, const gchar *arg, bool quote)
936
{
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
	/* Note: Any characters with high bit set are assumed to be
	 * part of valid utf8 sequence and are passed through as-is.
	 */
	size_t i = 0;

	if (string->len) {
		/* Separate from previous arg with a space */
		g_string_append_c(string, ' ');
	}

	if (!quote) {
		/* Auto-quote if string contains spaces or control chars */
		for (i = 0; ; ) {
			int chr = (unsigned char)arg[i++];
			if (chr > 32)
				continue;
			if (chr > 0)
				quote = true;
			break;
		}
	}

	if (quote) {
		/* Note: g_shell_quote() uses single quote escaping, which
		 * basically means we can't use if if we wish to retain the
		 * original formatting with the expected inputs where no
		 * special characters are used except for the spaces within
		 * quoted comment strings.
		 */
		g_string_append_c(string, '"');
		for (i = 0; ; ) {
			int chr = (unsigned char)arg[i++];
			if (chr == 0 ) {
				break;
971
			}
972 973 974
			if (chr >= 32) {
				g_string_append_c(string, chr);
				continue;
975
			}
976 977 978 979 980 981 982 983 984
			switch (chr) {
			case '\a': chr = 'a'; break;
			case '\b': chr = 'b'; break;
			case '\t': chr = 't'; break;
			case '\n': chr = 'n'; break;
			case '\v': chr = 'v'; break;
			case '\f': chr = 'f'; break;
			case '\r': chr = 'r'; break;
			case '"': break;
985
			default:
986 987
				g_string_append_printf(string, "\\%#o", chr);
				continue;
988
			}
989 990
			g_string_append_c(string, '\\');
			g_string_append_c(string, chr);
991
		}
992 993 994 995
		g_string_append_c(string, '"');
	} else {
		/* Add as-is */
		g_string_append(string, arg);
996
	}
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
}
static int iptables_parse_rule(const gchar* table_name, gchar* rule)
{
	int rval = 1, i = 0;
	gint argc = 0;
	gchar **argv = NULL;
	GError *error = NULL;
	GString *rule_str = NULL;

	if (!table_name || !*table_name || !rule || !*rule)
		goto out;

	/* Format, e.g., -A CHAIN -p tcp -s 1.2.3.4  ... separated with spaces
	 * However a shell command line parser needs to be used to deal with
	 * arguments like: ... -m comment --comment "foo bar"
	 */
	if (!g_shell_parse_argv(rule, &argc, &argv, &error))
		goto out;

	if (argc < 4 || !argv[0][0])
		goto out;

	/* Discard all rules that have prefix "connman-" in chain name or
	 * target name. Chain = token[1], target = last token.
	 */
	if (str_has_connman_prefix(argv[1]) ||
		str_has_connman_prefix(argv[argc - 1])) {
		DBG("Skipping connman rule \"%s\"", rule);
		rval = 0; // Not an error situation
		goto out;
	}

	rule_str = g_string_new(NULL);

	/* Match "-m comment" should be checked that it is followed
	 * by a --comment content section, otherwise iptables will
	 * call exit as rule is invalid. Any words "comment" in the
	 * actual comment should not trigger this.
	 */
	for (i = 2; i < argc; ) {
		const char *arg = argv[i++];
		if (!g_strcmp0(arg, "-m")) {
			const char *match = argv[i++];
			if (!match) {
				DBG("trailing '-m' in rule \"%s\"", rule);
				goto out;
			}
			iptables_append_arg(rule_str, arg, false);
			iptables_append_arg(rule_str, match, false);
			if (!g_strcmp0(match, "comment")) {
				const char *opt = argv[i++];
				if (g_strcmp0(opt, "--comment")) {
					DBG("malformed '-m comment' "
						"in rule \"%s\"", rule);
					goto out;
				}
				const char *txt = argv[i++];
				if (!txt || g_str_has_prefix(txt, "-")) {
					DBG("malformed '--comment' "
						"in rule \"%s\"", rule);
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
					goto out;
				}
				iptables_append_arg(rule_str, opt, false);
				iptables_append_arg(rule_str, txt, true);
			}
		} else if (!g_strcmp0(arg, "-j")) {
			const char *match = argv[i++];
			if (!match) {
				DBG("trailing '-j' in rule \"%s\"", rule);
				goto out;
			}
			iptables_append_arg(rule_str, arg, false);
			iptables_append_arg(rule_str, match, false);
			if (!g_strcmp0(match, "REJECT")) {
				const char *opt = argv[i++];
				if (g_strcmp0(opt, "--reject-with")) {
					DBG("malformed '-j REJECT' "
						"in rule \"%s\"", rule);
					goto out;
				}
				const char *txt = argv[i++];
				if (!txt || g_str_has_prefix(txt, "-")) {
					DBG("malformed '--reject-with' "
						"in rule \"%s\"", rule);
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096
					goto out;
				}
				iptables_append_arg(rule_str, opt, false);
				iptables_append_arg(rule_str, txt, true);
			}
		} else {
			iptables_append_arg(rule_str, arg, false);
		}
	}

	// First token contains the mode, prefixed with '-'
	switch (argv[0][1]) {
	// Append
	case 'A':
		DBG("Append to table \"%s\" chain \"%s\" rule: %s",
			table_name, argv[1], rule_str->str);
1097
		rval = __connman_iptables_append(AF_INET, table_name, argv[1],
1098 1099 1100 1101 1102 1103
				rule_str->str);
		break;
	// Insert
	case 'I':
		DBG("Insert to table \"%s\" chain \"%s\" rule: %s",
			table_name, argv[1], rule_str->str);
1104
		rval = __connman_iptables_insert(AF_INET, table_name, argv[1],
1105 1106 1107 1108 1109 1110
				rule_str->str);
		break;
	// Delete
	case 'D':
		DBG("Delete from table \"%s\" chain \"%s\" rule: %s",
			table_name, argv[1], rule_str->str);
1111
		rval = __connman_iptables_delete(AF_INET, table_name, argv[1],
1112 1113 1114
				rule_str->str);
		break;
	default:
1115 1116 1117
		ERR("iptables_parse_rule() invalid rule prefix %c in rule %s",
			argv[0][1], rule);
		goto out;
1118 1119
	}

1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
	/*
	 * When iptables operation was a success commit rule. Commit each rule
	 * one by one to avoid problems with iptables changing in between.
	 * Only properly processed rules have set the rval. If rule parsing has
	 * failed this is not executed.
	 */
	if (!rval) {
		rval = __connman_iptables_commit(AF_INET, table_name);

		/* Commit errors are not recoverable */
		if (rval)
			ERR("iptables_parse_rule() rule %s commit failed",
						rule);
	}
1134 1135 1136 1137 1138 1139
out:
	if (rule_str)
		g_string_free(rule_str, true);
	if (error)
		g_error_free(error);
	g_strfreev(argv);
1140 1141 1142 1143 1144
	return rval;
}

static int iptables_restore_table(const char *table_name, const char *fpath)
{
1145
	gint rval = 0, i = 0, rules = 0, err = 0;
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177
	gboolean content_matches = false;
	gboolean process = true;
	gint table_result = iptables_check_table(table_name);
	
	switch (table_result) {
	case 0:
		break;
	case 1:
		ERR("iptables_restore_table() called with invalid table name");
	default:
		return 1;
	}
	
	GString *content = iptables_get_file_contents(fpath);
	
	if (!content)
		return 1;
		
	gchar** tokens = g_strsplit(content->str,"\n",0);
	
	for (i = 0; tokens[i] && process; i++) {
		switch (tokens[i][0]) {
		// Skip comment
		case '#':
			break;
		// Table name
		case '*':
			content_matches = !g_ascii_strcasecmp(&(tokens[i][1]), 
				table_name) ? true : false;
			break;
		// Chain and policy
		case ':':
1178
			if (content_matches) {
1179 1180 1181 1182
				if (iptables_parse_policy(table_name,
						tokens[i]))
					ERR("iptables_restore_table() "
						"Invalid policy %s",
1183 1184
						tokens[i]);
			}
1185 1186 1187
			break;
		// Rule
		case '-':
1188
			if (content_matches) {
1189 1190 1191 1192 1193 1194
				err = iptables_parse_rule(table_name,
							tokens[i]);

				switch (err) {
				case 0:
					/* Added and committed, fallthrough */
1195
					rules++;
1196 1197 1198 1199 1200 1201 1202 1203
				case 1:
					/* Invalid rule, ignore */
					break;
				default:
					/* Error, return error code. */
					rval = err;
					goto err;
				}
1204
			}
1205
			break;
1206 1207 1208 1209 1210
		/*
		 * If any other prefix for a line is found and we are processing
		 * 'COMMIT' is the last line in iptables saved format, stop
		 * processing
		 */
1211 1212 1213 1214 1215 1216
		default:
			if (content_matches)
				process = false;
			break;
		}
	}
1217 1218

err:
1219 1220 1221 1222
	g_strfreev(tokens);
	
	g_string_free(content,true);
	
1223
	if (content_matches) {
1224
		DBG("Added %d rules to table %s", rules, table_name);
1225
	} else {
1226
		/* TODO set rval = -1 in case of error ? */
1227 1228
		ERR("iptables_restore_table() %s",
			"requested table name does not match file table name");
1229
	}
1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246

	return rval;
}

/*
*
* return: 0 on success, 1 error and -1 if save is already in progress
*/
int iptables_save(const char* table_name)
{
	// TODO ADD MUTEX
	gint rval = 1;
	gchar *save_file = NULL;
	
	if (!table_name || !(*table_name))
		goto out;
	
1247 1248
	save_file = g_strconcat(STORAGEDIR, "/iptables/", table_name, ".v4",
			NULL);
1249 1250 1251 1252

	if (g_file_test(save_file, G_FILE_TEST_EXISTS)) {
		// Don't allow to overwrite executables
		if (g_file_test(save_file,G_FILE_TEST_IS_EXECUTABLE)) {
1253 1254
			ERR("connman_iptables_save() cannot save firewall to "
				"%s", save_file);
1255 1256 1257 1258
			goto out;
		}
	}
		
1259
	DBG("saving iptables table %s to %s", table_name, save_file);
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277

	rval = iptables_save_table(save_file, NULL, table_name, true);
	
out:
	g_free(save_file);

	return rval;
}


int iptables_restore(const char* table_name)
{
	gint rval = 1;
	gchar *load_file = NULL;
	
	if (!table_name || !(*table_name))
		goto out;
		
1278 1279
	load_file = g_strconcat(STORAGEDIR, "/iptables/", table_name, ".v4",
			NULL);
1280 1281 1282 1283 1284 1285 1286 1287

	// Allow only regular files from connman storage
	if (!g_file_test(load_file,G_FILE_TEST_EXISTS) ||
		!g_file_test(load_file,G_FILE_TEST_IS_REGULAR)) {
			ERR("Cannot restore table %s, file %s not found",
				table_name, load_file);
			goto out;
	}
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300

	DBG("restoring iptables table %s from %s", table_name, load_file);

	if ((rval = iptables_clear_table(table_name))) {
		ERR("clearing of table %s failed, cannot restore.",
			table_name);
		goto out;
	}

	if((rval = iptables_restore_table(table_name, load_file)))
		ERR("connman_iptables_restore() cannot restore table %s",
			table_name);

1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
out:
	g_free(load_file);
	return rval;
}

static gchar** get_default_tables()
{
	gchar **tables = NULL;
	gchar *content = NULL;
	gsize length = 0;
	GError *error = NULL;
	
1313 1314
	if (g_file_get_contents(IPTABLES_NAMES_FILE, &content, &length,
		&error)) {
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
		tables = g_strsplit(content, "\n", 0);
		g_free(content);
	} else {
		if (error) {
			DBG("get_file_contents error %s", error->message);
			g_error_free(error);
		}
			
		DBG("Cannot read default iptables table names from %s",
			IPTABLES_NAMES_FILE);
	}

	return tables;
}

int __connman_iptables_save_all()
{
	gchar **tables = get_default_tables();
	
	gint i = 0;
	
	if(!tables || !g_strv_length(tables))
		return 1;
	
1339 1340 1341
	for (i = 0; tables[i] && *tables[i]; i++) {
		if (iptables_save(tables[i]))
			DBG("cannot save table \"%s\"", tables[i]);
1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356
	}
	
	g_strfreev(tables);
	
	return 0;
}

int __connman_iptables_restore_all()
{
	gchar **tables = get_default_tables();
	gint i = 0;
	
	if(!tables || !g_strv_length(tables))
		return 1;
	
1357
	for (i = 0; tables[i] && *tables[i]; i++) {
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
		if(iptables_restore(tables[i]))
			DBG("cannot restore table %s", tables[i]);
	}
	
	g_strfreev(tables);
	
	return 0;
}

int connman_iptables_clear(const char* table_name)
{
	if (!table_name || !(*table_name) ||
		g_ascii_strcasecmp(table_name,"filter"))
		return 1;

1373 1374
	DBG("%s", table_name);

1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
	return iptables_clear_table(table_name);
}

/*
	Returns: 0 Ok, -1 Parameter error, -EINVAL or -ENOMEM on Error
*/
int connman_iptables_new_chain(const char *table_name,
					const char *chain)
{
	if (!table_name || !(*table_name) || !chain || !(*chain))
		return -1;
1386 1387 1388

	DBG("%s %s", table_name, chain);

1389 1390 1391
	if (str_has_connman_prefix(chain))
		return -EINVAL;

1392
	return __connman_iptables_new_chain(AF_INET, table_name, chain);
1393 1394 1395
}

/*
1396 1397 1398 1399 1400
 * Returns:
 *   0 Ok
 *   -1 Parameter error
 *   -EINVAL or -ENOMEM on error,
 */
1401 1402 1403 1404 1405
int connman_iptables_delete_chain(const char *table_name,
					const char *chain)
{
	if (!table_name || !(*table_name) || !chain || !(*chain))
		return -1;
1406 1407 1408

	DBG("%s %s", table_name, chain);

1409 1410 1411
	if (str_has_connman_prefix(chain))
		return -EINVAL;

1412
	return __connman_iptables_delete_chain(AF_INET, table_name, chain);
1413 1414 1415 1416 1417 1418 1419
}

int connman_iptables_flush_chain(const char *table_name,
					const char *chain)
{
	if (!table_name || !(*table_name) || !chain || !(*chain))
		return -1;
1420 1421 1422

	DBG("%s %s", table_name, chain);

1423 1424
	if (str_has_connman_prefix(chain))
		return -EINVAL;
1425

1426
	return __connman_iptables_flush_chain(AF_INET, table_name, chain);
1427 1428 1429
}

/*
1430 1431 1432 1433
 * Returns:
 *   0 if chain found
 *   -ENOENT if not found
 *   -EINVAL on parameter error
1434 1435 1436 1437 1438
*/
int connman_iptables_find_chain(const char *table_name, const char *chain)
{
	if (!table_name || !(*table_name) || !chain || !(*chain))
		return -EINVAL;
1439 1440 1441

	DBG("%s %s", table_name, chain);

1442
	return __connman_iptables_find_chain(AF_INET, table_name, chain);
1443 1444 1445 1446 1447 1448 1449 1450 1451
}

int connman_iptables_insert(const char *table_name,
				const char *chain,
				const char *rule_spec)
{
	if (!table_name || !chain || !rule_spec || 
		!(*table_name) || !(*chain) || !(*rule_spec))
		return -EINVAL;
1452 1453 1454

	DBG("%s %s %s", table_name, chain, rule_spec);

1455 1456 1457
	if (str_has_connman_prefix(chain) || str_contains_connman(rule_spec))
		return -EINVAL;

1458
	return __connman_iptables_insert(AF_INET, table_name, chain, rule_spec);
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
}

int connman_iptables_append(const char *table_name,
				const char *chain,
				const char *rule_spec)
{
	if (!table_name || !chain || !rule_spec || 
		!(*table_name) || !(*chain) || !(*rule_spec))
		return -EINVAL;

1469 1470
	DBG("%s %s %s", table_name, chain, rule_spec);

1471 1472 1473
	if (str_has_connman_prefix(chain) || str_contains_connman(rule_spec))
		return -EINVAL;

1474
	return __connman_iptables_append(AF_INET, table_name, chain, rule_spec);
1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
}
	
int connman_iptables_delete(const char *table_name,
				const char *chain,
				const char *rule_spec)
{
	if (!table_name || !chain || !rule_spec || 
		!(*table_name) || !(*chain) || !(*rule_spec))
		return -EINVAL;

1485 1486
	DBG("%s %s %s", table_name, chain, rule_spec);

1487 1488 1489
	if (str_has_connman_prefix(chain) || str_contains_connman(rule_spec))
		return -EINVAL;

1490
	return __connman_iptables_delete(AF_INET, table_name, chain, rule_spec);
1491 1492 1493 1494 1495 1496 1497
}
	
int connman_iptables_commit(const char *table_name)
{
	if (!table_name || !(*table_name))
		return -EINVAL;

1498 1499
		DBG("%s", table_name);

1500
	return __connman_iptables_commit(AF_INET, table_name);
1501 1502 1503 1504 1505 1506 1507 1508 1509
}

int connman_iptables_change_policy(const char *table_name,
					const char *chain,
					const char *policy)
{
	if (!table_name || !chain || !policy || 
		!(*table_name) || !(*chain) || !(*policy))
		return -EINVAL;
1510 1511 1512

	DBG("%s %s %s", table_name, chain, policy);

1513 1514 1515
	if (str_has_connman_prefix(chain))
		return -EINVAL;

1516
	return __connman_iptables_change_policy(AF_INET, table_name, chain, policy);
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
}

const char* connman_iptables_default_save_path(int ip_version)
{
	if (ip_version == 4)
		return STORAGEDIR;
	
	return NULL;
}

static struct iptables_content* iptables_content_new(const gchar* table_name)
{
	struct iptables_content* content = g_new0(struct iptables_content,1);
	content->chains = NULL;
	content->rules = NULL;
	content->table = g_strdup(table_name);
	
	return content;
}

struct iptables_content* iptables_get_content(GString *output,
	const gchar* table_name)
{
	struct iptables_content *content = NULL;
	gchar **tokens = NULL, **policy_tokens = NULL;
	gboolean process = true;
	gint i = 0;
	
	if (!output || !output->len)
		return NULL;

	content = iptables_content_new(table_name);
		
	tokens = g_strsplit(output->str, "\n", -1);
	
	for (i = 0; tokens[i] && process; i++) {
		switch (tokens[i][0]) {
		// Skip comment and table name
		case '#':
		case '*':
			break;
		// Chain and policy
		case ':':
			// TODO improve this to allocate less memory
			policy_tokens = g_strsplit(&(tokens[i][1]), " ", 3);
			if (g_strv_length(policy_tokens) > 2) {
				content->chains = g_list_prepend(content->chains,
					g_strdup_printf("%s %s", 
1565 1566
						policy_tokens[0],
						policy_tokens[1]));
1567 1568 1569 1570 1571 1572 1573
			}
			g_strfreev(policy_tokens);

			break;
		// Rule
		case '-':
			content->rules = g_list_prepend(content->rules,
1574
				g_strdup(tokens[i]));
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
			break;
		// Anything else, stop processing
		default:
			process = false;
			break;
		}
	}
	
	content->chains = g_list_reverse(content->chains);
	content->rules = g_list_reverse(content->rules);
	
	g_strfreev(tokens);
	
	return content;
}

void connman_iptables_free_content(struct iptables_content *content)
{
	if (!content)
		return;
1595 1596

	DBG("");
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
	
	g_list_free_full(content->chains, g_free);
	g_list_free_full(content->rules, g_free);
	g_free(content->table);
	g_free(content);
}

struct iptables_content* connman_iptables_get_content(const char *table_name)
{
	struct iptables_content *content = NULL;
	GString *output = NULL;
	
	if(!table_name || !(*table_name))
		return NULL;
1611 1612

	DBG("%s", table_name);
1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623
	
	output = g_string_new(NULL);
	
	if (!iptables_save_table(NULL, &output, table_name, false))
		content = iptables_get_content(output, table_name);
	
	g_string_free(output, true);
	
	return content;
}