reglib.c 36.5 KB
Newer Older
1
#include <errno.h>
2
#include <stdio.h>
3
#include <arpa/inet.h>
4 5
#include <sys/types.h>
#include <dirent.h>
6 7 8 9
#include <sys/stat.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
10 11
#include <stdbool.h>
#include <unistd.h>
12
#include <string.h>
13
#include <limits.h>
14 15 16

#include <arpa/inet.h> /* ntohl */

17
#include "reglib.h"
18
#include "regdb.h"
19 20

#ifdef USE_OPENSSL
21 22 23
#include <openssl/objects.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>
24
#include <openssl/pem.h>
25 26 27 28 29 30
#endif

#ifdef USE_GCRYPT
#include <gcrypt.h>
#endif

31
#include "reglib.h"
32 33 34 35 36 37 38 39 40

#ifdef USE_OPENSSL
#include "keys-ssl.c"
#endif

#ifdef USE_GCRYPT
#include "keys-gcrypt.c"
#endif

41 42 43 44 45 46 47 48 49 50 51 52 53
int debug = 0;

struct reglib_rule_parse_list {
	int n_parsers;
	int (*rule_parsers[])(char *line, struct ieee80211_reg_rule *reg_rule);
};

struct reglib_country_parse_list {
	int n_parsers;
	int (*country_parsers[])(char *line, struct ieee80211_regdomain *rd);
};


54 55
void *
reglib_get_file_ptr(uint8_t *db, size_t dblen, size_t structlen, uint32_t ptr)
56
{
57
	uint32_t p = ntohl(ptr);
58

59 60 61 62 63
	if (structlen > dblen) {
		fprintf(stderr, "Invalid database file, too short!\n");
		exit(3);
	}

64 65 66 67 68 69 70 71
	if (p > dblen - structlen) {
		fprintf(stderr, "Invalid database file, bad pointer!\n");
		exit(3);
	}

	return (void *)(db + p);
}

72 73 74 75 76 77 78 79 80 81 82
static size_t
reglib_array_len(size_t baselen, unsigned int elemcount, size_t elemlen)
{
	if (elemcount > (SIZE_MAX - baselen) / elemlen) {
		fprintf(stderr, "Invalid database file, count too large!\n");
		exit(3);
	}

	return baselen + elemcount * elemlen;
}

83
/*
84
 * reglib_verify_db_signature():
85
 *
86 87 88 89 90
 * Checks the validity of the signature found on the regulatory
 * database against the array 'keys'. Returns 1 if there exists
 * at least one key in the array such that the signature is valid
 * against that key; 0 otherwise.
 */
91 92

#ifdef USE_OPENSSL
93
int reglib_verify_db_signature(uint8_t *db, size_t dblen, size_t siglen)
94 95
{
	RSA *rsa;
96
	uint8_t hash[SHA_DIGEST_LENGTH];
97 98
	unsigned int i;
	int ok = 0;
99 100 101 102
	DIR *pubkey_dir;
	struct dirent *nextfile;
	FILE *keyfile;
	char filename[PATH_MAX];
103 104 105 106 107 108 109

	if (SHA1(db, dblen, hash) != hash) {
		fprintf(stderr, "Failed to calculate SHA1 sum.\n");
		goto out;
	}

	for (i = 0; (i < sizeof(keys)/sizeof(keys[0])) && (!ok); i++) {
110 111 112 113 114 115
		rsa = RSA_new();
		if (!rsa) {
			fprintf(stderr, "Failed to create RSA key.\n");
			goto out;
		}

116 117 118 119 120 121
		rsa->e = &keys[i].e;
		rsa->n = &keys[i].n;

		ok = RSA_verify(NID_sha1, hash, SHA_DIGEST_LENGTH,
				db + dblen, siglen, rsa) == 1;

122 123 124 125
		rsa->e = NULL;
		rsa->n = NULL;
		RSA_free(rsa);
	}
126 127 128 129 130 131 132
	if (!ok && (pubkey_dir = opendir(PUBKEY_DIR))) {
		while (!ok && (nextfile = readdir(pubkey_dir))) {
			snprintf(filename, PATH_MAX, "%s/%s", PUBKEY_DIR,
				nextfile->d_name);
			if ((keyfile = fopen(filename, "rb"))) {
				rsa = PEM_read_RSA_PUBKEY(keyfile,
					NULL, NULL, NULL);
Luis R. Rodriguez's avatar
Luis R. Rodriguez committed
133
				if (rsa)
134 135 136 137 138 139 140 141
					ok = RSA_verify(NID_sha1, hash, SHA_DIGEST_LENGTH,
						db + dblen, siglen, rsa) == 1;
				RSA_free(rsa);
				fclose(keyfile);
			}
		}
		closedir(pubkey_dir);
	}
142 143 144 145 146 147 148 149

	if (!ok)
		fprintf(stderr, "Database signature verification failed.\n");

out:
	return ok;
}
#endif /* USE_OPENSSL */
150 151

#ifdef USE_GCRYPT
152
int reglib_verify_db_signature(uint8_t *db, size_t dblen, size_t siglen)
153
{
154 155
	gcry_mpi_t mpi_e, mpi_n;
	gcry_sexp_t rsa, signature, data;
156
	uint8_t hash[20];
157 158 159 160 161 162 163 164 165 166 167 168
	unsigned int i;
	int ok = 0;

	/* initialise */
	gcry_check_version(NULL);

	/* hash the db */
	gcry_md_hash_buffer(GCRY_MD_SHA1, hash, db, dblen);

	if (gcry_sexp_build(&data, NULL, "(data (flags pkcs1) (hash sha1 %b))",
			    20, hash)) {
		fprintf(stderr, "Failed to build data S-expression.\n");
169
		return ok;
170 171 172 173 174
	}

	if (gcry_sexp_build(&signature, NULL, "(sig-val (rsa (s %b)))",
			    siglen, db + dblen)) {
		fprintf(stderr, "Failed to build signature S-expression.\n");
175 176
		gcry_sexp_release(data);
		return ok;
177 178 179 180
	}

	for (i = 0; (i < sizeof(keys)/sizeof(keys[0])) && (!ok); i++) {
		if (gcry_mpi_scan(&mpi_e, GCRYMPI_FMT_USG,
181
				keys[i].e, keys[i].len_e, NULL) ||
182
		    gcry_mpi_scan(&mpi_n, GCRYMPI_FMT_USG,
183
				keys[i].n, keys[i].len_n, NULL)) {
184 185 186 187 188 189 190 191
			fprintf(stderr, "Failed to convert numbers.\n");
			goto out;
		}

		if (gcry_sexp_build(&rsa, NULL,
				    "(public-key (rsa (n %m) (e %m)))",
				    mpi_n, mpi_e)) {
			fprintf(stderr, "Failed to build RSA S-expression.\n");
192 193
			gcry_mpi_release(mpi_e);
			gcry_mpi_release(mpi_n);
194 195 196 197
			goto out;
		}

		ok = gcry_pk_verify(signature, data, rsa) == 0;
198 199
		gcry_mpi_release(mpi_e);
		gcry_mpi_release(mpi_n);
200
		gcry_sexp_release(rsa);
201 202 203 204 205 206
	}

	if (!ok)
		fprintf(stderr, "Database signature verification failed.\n");

out:
207 208
	gcry_sexp_release(data);
	gcry_sexp_release(signature);
209
	return ok;
210 211 212 213
}
#endif /* USE_GCRYPT */

#if !defined(USE_OPENSSL) && !defined(USE_GCRYPT)
214
int reglib_verify_db_signature(uint8_t *db, size_t dblen, size_t siglen)
215
{
216 217
	return 1;
}
218
#endif
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
const struct reglib_regdb_ctx *reglib_malloc_regdb_ctx(const char *regdb_file)
{
	struct regdb_file_header *header;
	struct reglib_regdb_ctx *ctx;

	ctx = malloc(sizeof(struct reglib_regdb_ctx));
	if (!ctx)
		return NULL;

	memset(ctx, 0, sizeof(struct reglib_regdb_ctx));

	ctx->fd = open(regdb_file, O_RDONLY);

	if (ctx->fd < 0) {
		free(ctx);
		return NULL;
	}

	if (fstat(ctx->fd, &ctx->stat)) {
		close(ctx->fd);
		free(ctx);
		return NULL;
	}

	ctx->real_dblen = ctx->stat.st_size;

	ctx->db = mmap(NULL, ctx->real_dblen, PROT_READ,
		       MAP_PRIVATE, ctx->fd, 0);
	if (ctx->db == MAP_FAILED) {
		close(ctx->fd);
		free(ctx);
		return NULL;
	}

254
	ctx->header = reglib_get_file_ptr(ctx->db, ctx->real_dblen,
255 256 257 258 259 260 261 262 263 264 265 266
					  sizeof(struct regdb_file_header),
					  0);
	header = ctx->header;

	if (ntohl(header->magic) != REGDB_MAGIC)
		goto err_out;

	if (ntohl(header->version) != REGDB_VERSION)
		goto err_out;

	ctx->siglen = ntohl(header->signature_length);

267
	if (ctx->siglen > ctx->real_dblen - sizeof(*header))
268 269
		goto err_out;

270 271 272
	/* The actual dblen does not take into account the signature */
	ctx->dblen = ctx->real_dblen - ctx->siglen;

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	/* verify signature */
	if (!reglib_verify_db_signature(ctx->db, ctx->dblen, ctx->siglen))
		goto err_out;

	ctx->verified = true;
	ctx->num_countries = ntohl(header->reg_country_num);
	ctx->countries = reglib_get_file_ptr(ctx->db,
					     ctx->dblen,
					     sizeof(struct regdb_file_reg_country) * ctx->num_countries,
					     header->reg_country_ptr);
	return ctx;

err_out:
	close(ctx->fd);
	munmap(ctx->db, ctx->real_dblen);
	free(ctx);
	return NULL;
}

void reglib_free_regdb_ctx(const struct reglib_regdb_ctx *regdb_ctx)
{
	struct reglib_regdb_ctx *ctx;

	if (!regdb_ctx)
		return;

	ctx = (struct reglib_regdb_ctx *) regdb_ctx;

	memset(ctx, 0, sizeof(struct reglib_regdb_ctx));
	close(ctx->fd);
	munmap(ctx->db, ctx->real_dblen);
	free(ctx);
}

307
static void reg_rule2rd(uint8_t *db, size_t dblen,
308 309 310 311 312 313 314 315 316
	uint32_t ruleptr, struct ieee80211_reg_rule *rd_reg_rule)
{
	struct regdb_file_reg_rule *rule;
	struct regdb_file_freq_range *freq;
	struct regdb_file_power_rule *power;

	struct ieee80211_freq_range *rd_freq_range = &rd_reg_rule->freq_range;
	struct ieee80211_power_rule *rd_power_rule = &rd_reg_rule->power_rule;

317 318 319
	rule  = reglib_get_file_ptr(db, dblen, sizeof(*rule), ruleptr);
	freq  = reglib_get_file_ptr(db, dblen, sizeof(*freq), rule->freq_range_ptr);
	power = reglib_get_file_ptr(db, dblen, sizeof(*power), rule->power_rule_ptr);
320 321 322 323 324 325 326 327 328

	rd_freq_range->start_freq_khz = ntohl(freq->start_freq);
	rd_freq_range->end_freq_khz = ntohl(freq->end_freq);
	rd_freq_range->max_bandwidth_khz = ntohl(freq->max_bandwidth);

	rd_power_rule->max_antenna_gain = ntohl(power->max_antenna_gain);
	rd_power_rule->max_eirp = ntohl(power->max_eirp);

	rd_reg_rule->flags = ntohl(rule->flags);
329 330 331

	if (rd_reg_rule->flags & RRF_NO_IR_ALL)
		rd_reg_rule->flags |= RRF_NO_IR_ALL;
332 333 334
}

/* Converts a file regdomain to ieee80211_regdomain, easier to manage */
335
const static struct ieee80211_regdomain *
336
country2rd(const struct reglib_regdb_ctx *ctx,
337
	   struct regdb_file_reg_country *country)
338 339 340
{
	struct regdb_file_reg_rules_collection *rcoll;
	struct ieee80211_regdomain *rd;
341 342
	unsigned int i, num_rules;
	size_t size_of_rd;
343

344 345
	rcoll = reglib_get_file_ptr(ctx->db, ctx->dblen, sizeof(*rcoll),
				    country->reg_collection_ptr);
346 347
	num_rules = ntohl(rcoll->reg_rule_num);
	/* re-get pointer with sanity checking for num_rules */
348
	rcoll = reglib_get_file_ptr(ctx->db, ctx->dblen,
349 350 351
				    reglib_array_len(sizeof(*rcoll), num_rules,
						     sizeof(uint32_t)),
				    country->reg_collection_ptr);
352

353 354 355
	size_of_rd = reglib_array_len(sizeof(struct ieee80211_regdomain),
				      num_rules,
				      sizeof(struct ieee80211_reg_rule));
356 357 358 359 360 361 362 363 364

	rd = malloc(size_of_rd);
	if (!rd)
		return NULL;

	memset(rd, 0, size_of_rd);

	rd->alpha2[0] = country->alpha2[0];
	rd->alpha2[1] = country->alpha2[1];
365
	rd->dfs_region = country->creqs & 0x3;
366 367 368
	rd->n_reg_rules = num_rules;

	for (i = 0; i < num_rules; i++) {
369
		reg_rule2rd(ctx->db, ctx->dblen, rcoll->reg_rule_ptrs[i],
370 371 372 373 374
			&rd->reg_rules[i]);
	}

	return rd;
}
375

376
const struct ieee80211_regdomain *
377
reglib_get_rd_idx(unsigned int idx, const struct reglib_regdb_ctx *ctx)
378 379 380
{
	struct regdb_file_reg_country *country;

381
	if (!ctx)
382 383
		return NULL;

384
	if (idx >= ctx->num_countries)
385
		return NULL;
386

387
	country = ctx->countries + idx;
388

389
	return country2rd(ctx, country);
390
}
391

392
const struct ieee80211_regdomain *
393
reglib_get_rd_alpha2(const char *alpha2, const char *file)
394
{
395
	const struct reglib_regdb_ctx *ctx;
396
	const struct ieee80211_regdomain *rd = NULL;
397 398
	struct regdb_file_reg_country *country;
	bool found_country = false;
399
	unsigned int i;
400

401 402
	ctx = reglib_malloc_regdb_ctx(file);
	if (!ctx)
403 404
		return NULL;

405 406
	for (i = 0; i < ctx->num_countries; i++) {
		country = ctx->countries + i;
407 408 409 410 411 412 413 414 415
		if (memcmp(country->alpha2, alpha2, 2) == 0) {
			found_country = 1;
			break;
		}
	}

	if (!found_country)
		goto out;

416
	rd = country2rd(ctx, country);
417 418 419 420
	if (!rd)
		goto out;

out:
421
	reglib_free_regdb_ctx(ctx);
422 423
	return rd;
}
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445

/* Sanity check on a regulatory rule */
static int is_valid_reg_rule(const struct ieee80211_reg_rule *rule)
{
	const struct ieee80211_freq_range *freq_range = &rule->freq_range;
	uint32_t freq_diff;

	if (freq_range->start_freq_khz == 0 || freq_range->end_freq_khz == 0)
		return 0;

	if (freq_range->start_freq_khz > freq_range->end_freq_khz)
		return 0;

	freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;

	if (freq_range->end_freq_khz <= freq_range->start_freq_khz ||
	    freq_range->max_bandwidth_khz > freq_diff)
		return 0;

	return 1;
}

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
int reglib_is_valid_rd(const struct ieee80211_regdomain *rd)
{
	const struct ieee80211_reg_rule *reg_rule = NULL;
	unsigned int i;

	if (!rd->n_reg_rules)
		return 0;

	for (i = 0; i < rd->n_reg_rules; i++) {
		reg_rule = &rd->reg_rules[i];
		if (!is_valid_reg_rule(reg_rule))
		return 0;
	}
	return 1;
}

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 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
static int reg_rules_union(const struct ieee80211_reg_rule *rule1,
			   const struct ieee80211_reg_rule *rule2,
			   struct ieee80211_reg_rule *union_rule)
{
	const struct ieee80211_freq_range *freq_range1, *freq_range2;
	struct ieee80211_freq_range *freq_range;
	const struct ieee80211_power_rule *power_rule1, *power_rule2;
	struct ieee80211_power_rule *power_rule;

	freq_range1 = &rule1->freq_range;
	freq_range2 = &rule2->freq_range;
	freq_range = &union_rule->freq_range;

	power_rule1 = &rule1->power_rule;
	power_rule2 = &rule2->power_rule;
	power_rule = &union_rule->power_rule;


	if (freq_range1->end_freq_khz < freq_range2->start_freq_khz)
		return -EINVAL;
	if (freq_range2->end_freq_khz < freq_range1->start_freq_khz)
		return -EINVAL;

	freq_range->start_freq_khz = reglib_min(freq_range1->start_freq_khz,
					 freq_range2->start_freq_khz);
	freq_range->end_freq_khz = reglib_max(freq_range1->end_freq_khz,
				       freq_range2->end_freq_khz);
	freq_range->max_bandwidth_khz = reglib_max(freq_range1->max_bandwidth_khz,
					    freq_range2->max_bandwidth_khz);

	power_rule->max_eirp = reglib_max(power_rule1->max_eirp,
		power_rule2->max_eirp);
	power_rule->max_antenna_gain = reglib_max(power_rule1->max_antenna_gain,
		power_rule2->max_antenna_gain);

	union_rule->flags = rule1->flags | rule2->flags;

	if (!is_valid_reg_rule(union_rule))
		return -EINVAL;

	return 0;
}

505
/*
506
 * Helper for reglib_intersect_rds(), this does the real
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
 * mathematical intersection fun
 */
static int reg_rules_intersect(const struct ieee80211_reg_rule *rule1,
			       const struct ieee80211_reg_rule *rule2,
			       struct ieee80211_reg_rule *intersected_rule)
{
	const struct ieee80211_freq_range *freq_range1, *freq_range2;
	struct ieee80211_freq_range *freq_range;
	const struct ieee80211_power_rule *power_rule1, *power_rule2;
	struct ieee80211_power_rule *power_rule;
	uint32_t freq_diff;

	freq_range1 = &rule1->freq_range;
	freq_range2 = &rule2->freq_range;
	freq_range = &intersected_rule->freq_range;

	power_rule1 = &rule1->power_rule;
	power_rule2 = &rule2->power_rule;
	power_rule = &intersected_rule->power_rule;

527
	freq_range->start_freq_khz = reglib_max(freq_range1->start_freq_khz,
528
					 freq_range2->start_freq_khz);
529
	freq_range->end_freq_khz = reglib_min(freq_range1->end_freq_khz,
530
				       freq_range2->end_freq_khz);
531
	freq_range->max_bandwidth_khz = reglib_min(freq_range1->max_bandwidth_khz,
532 533 534 535 536 537
					    freq_range2->max_bandwidth_khz);

	freq_diff = freq_range->end_freq_khz - freq_range->start_freq_khz;
	if (freq_range->max_bandwidth_khz > freq_diff)
		freq_range->max_bandwidth_khz = freq_diff;

538
	power_rule->max_eirp = reglib_min(power_rule1->max_eirp,
539
		power_rule2->max_eirp);
540
	power_rule->max_antenna_gain = reglib_min(power_rule1->max_antenna_gain,
541 542 543 544 545 546 547 548 549 550 551
		power_rule2->max_antenna_gain);

	intersected_rule->flags = rule1->flags | rule2->flags;

	if (!is_valid_reg_rule(intersected_rule))
		return -EINVAL;

	return 0;
}

/**
552
 * reglib_intersect_rds - do the intersection between two regulatory domains
553 554 555 556 557 558 559 560 561 562 563 564
 * @rd1: first regulatory domain
 * @rd2: second regulatory domain
 *
 * Use this function to get the intersection between two regulatory domains.
 * Once completed we will mark the alpha2 for the rd as intersected, "98",
 * as no one single alpha2 can represent this regulatory domain.
 *
 * Returns a pointer to the regulatory domain structure which will hold the
 * resulting intersection of rules between rd1 and rd2. We will
 * malloc() this structure for you.
 */
struct ieee80211_regdomain *
565 566
reglib_intersect_rds(const struct ieee80211_regdomain *rd1,
		     const struct ieee80211_regdomain *rd2)
567
{
568 569
	int r;
	size_t size_of_regd;
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
	unsigned int x, y;
	unsigned int num_rules = 0, rule_idx = 0;
	const struct ieee80211_reg_rule *rule1, *rule2;
	struct ieee80211_reg_rule *intersected_rule;
	struct ieee80211_regdomain *rd;
	/* This is just a dummy holder to help us count */
	struct ieee80211_reg_rule irule;

	/* Uses the stack temporarily for counter arithmetic */
	intersected_rule = &irule;

	memset(intersected_rule, 0, sizeof(struct ieee80211_reg_rule));

	if (!rd1 || !rd2)
		return NULL;

	/* First we get a count of the rules we'll need, then we actually
	 * build them. This is to so we can malloc() and free() a
	 * regdomain once. The reason we use reg_rules_intersect() here
	 * is it will return -EINVAL if the rule computed makes no sense.
	 * All rules that do check out OK are valid. */

	for (x = 0; x < rd1->n_reg_rules; x++) {
		rule1 = &rd1->reg_rules[x];
		for (y = 0; y < rd2->n_reg_rules; y++) {
			rule2 = &rd2->reg_rules[y];
			if (!reg_rules_intersect(rule1, rule2,
					intersected_rule))
				num_rules++;
			memset(intersected_rule, 0,
					sizeof(struct ieee80211_reg_rule));
		}
	}

	if (!num_rules)
		return NULL;

607 608 609
	size_of_regd = reglib_array_len(sizeof(struct ieee80211_regdomain),
					num_rules + 1,
					sizeof(struct ieee80211_reg_rule));
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643

	rd = malloc(size_of_regd);
	if (!rd)
		return NULL;

	memset(rd, 0, size_of_regd);

	for (x = 0; x < rd1->n_reg_rules; x++) {
		rule1 = &rd1->reg_rules[x];
		for (y = 0; y < rd2->n_reg_rules; y++) {
			rule2 = &rd2->reg_rules[y];
			/* This time around instead of using the stack lets
			 * write to the target rule directly saving ourselves
			 * a memcpy() */
			intersected_rule = &rd->reg_rules[rule_idx];
			r = reg_rules_intersect(rule1, rule2,
				intersected_rule);
			if (r)
				continue;
			rule_idx++;
		}
	}

	if (rule_idx != num_rules) {
		free(rd);
		return NULL;
	}

	rd->n_reg_rules = num_rules;
	rd->alpha2[0] = '9';
	rd->alpha2[1] = '9';

	return rd;
}
644

645 646
const struct ieee80211_regdomain *
reglib_intersect_regdb(const struct reglib_regdb_ctx *ctx)
647 648 649 650 651 652
{
	const struct ieee80211_regdomain *rd;
	struct ieee80211_regdomain *prev_rd_intsct = NULL, *rd_intsct = NULL;
	int intersected = 0;
	unsigned int idx = 0;

653 654 655 656
	if (!ctx)
		return NULL;

	reglib_for_each_country(rd, idx, ctx) {
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
		if (reglib_is_world_regdom((const char *) rd->alpha2)) {
			free((struct ieee80211_regdomain *) rd);
			continue;
		}

		if (!prev_rd_intsct) {
			prev_rd_intsct = (struct ieee80211_regdomain *) rd;
			continue;
		}

		if (rd_intsct) {
			free(prev_rd_intsct);
			prev_rd_intsct = (struct ieee80211_regdomain *) rd_intsct;
		}

		rd_intsct = reglib_intersect_rds(prev_rd_intsct, rd);
		if (!rd_intsct) {
			free(prev_rd_intsct);
			free((struct ieee80211_regdomain *) rd);
			return NULL;
		}

		intersected++;
		free((struct ieee80211_regdomain *) rd);
	}

	if (!idx)
		return NULL;

	if (intersected <= 0) {
		rd_intsct = prev_rd_intsct;
		prev_rd_intsct = NULL;
		if (idx > 1) {
			free(rd_intsct);
			return NULL;
		}
	}

	if (prev_rd_intsct)
		free(prev_rd_intsct);

	return rd_intsct;
}

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
static const char *dfs_domain_name(enum regdb_dfs_regions region)
{
	switch (region) {
	case REGDB_DFS_UNSET:
		return "DFS-UNSET";
	case REGDB_DFS_FCC:
		return "DFS-FCC";
	case REGDB_DFS_ETSI:
		return "DFS-ETSI";
	case REGDB_DFS_JP:
		return "DFS-JP";
	default:
		return "DFS-invalid";
	}
}

static void print_reg_rule(const struct ieee80211_reg_rule *rule)
{
	const struct ieee80211_freq_range *freq;
	const struct ieee80211_power_rule *power;

	freq  = &rule->freq_range;
	power = &rule->power_rule;

	printf("\t(%.3f - %.3f @ %.3f), ",
	       ((float)(freq->start_freq_khz))/1000.0,
	       ((float)(freq->end_freq_khz))/1000.0,
	       ((float)(freq->max_bandwidth_khz))/1000.0);

	printf("(");

	if (power->max_eirp)
		printf("%.2f)", ((float)(power->max_eirp)/100.0));
	else
		printf("N/A)");

	if (rule->flags & RRF_NO_OFDM)
		printf(", NO-OFDM");
	if (rule->flags & RRF_NO_CCK)
		printf(", NO-CCK");
	if (rule->flags & RRF_NO_INDOOR)
		printf(", NO-INDOOR");
	if (rule->flags & RRF_NO_OUTDOOR)
		printf(", NO-OUTDOOR");
	if (rule->flags & RRF_DFS)
		printf(", DFS");
	if (rule->flags & RRF_PTP_ONLY)
		printf(", PTP-ONLY");
	if (rule->flags & RRF_PTMP_ONLY)
		printf(", PTMP-ONLY");
751 752
	if (rule->flags & RRF_NO_IR_ALL)
		printf(", NO-IR");
753 754
	if (rule->flags & RRF_AUTO_BW)
		printf(", AUTO-BW");
755 756 757 758 759 760 761 762 763 764 765 766 767

	printf("\n");
}

void reglib_print_regdom(const struct ieee80211_regdomain *rd)
{
	unsigned int i;
	printf("country %.2s: %s\n", rd->alpha2,
	       dfs_domain_name(rd->dfs_region));
	for (i = 0; i < rd->n_reg_rules; i++)
		print_reg_rule(&rd->reg_rules[i]);
	printf("\n");
}
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

static unsigned int reglib_parse_dfs_region(char *dfs_region)
{
	if (strncmp(dfs_region, "DFS-FCC", 7) == 0)
		return REGDB_DFS_FCC;
	if (strncmp(dfs_region, "DFS-ETSI", 8) == 0)
		return REGDB_DFS_ETSI;
	if (strncmp(dfs_region, "DFS-JP", 6) == 0)
		return REGDB_DFS_JP;
	return REGDB_DFS_UNSET;
}

static uint32_t reglib_parse_rule_flag(char *flag_s)
{
	if (strncmp(flag_s, "NO-OFDM", 7) == 0)
		return RRF_NO_OFDM;
	if (strncmp(flag_s, "NO-CCK", 6) == 0)
		return RRF_NO_CCK;
	if (strncmp(flag_s, "NO-INDOOR", 9) == 0)
		return RRF_NO_INDOOR;
	if (strncmp(flag_s, "NO-OUTDOOR", 10) == 0)
		return RRF_NO_OUTDOOR;
	if (strncmp(flag_s, "DFS", 3) == 0)
		return RRF_DFS;
	if (strncmp(flag_s, "PTP-ONLY", 8) == 0)
		return RRF_PTP_ONLY;
	if (strncmp(flag_s, "PTMP-ONLY", 9) == 0)
		return RRF_PTMP_ONLY;
	if (strncmp(flag_s, "NO-IR", 5) == 0)
		return RRF_NO_IR;
798 799
	if (strncmp(flag_s, "AUTO-BW", 7) == 0)
		return RRF_AUTO_BW;
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 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 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 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

	return 0;
}

static int
reglib_parse_rule_simple(char *line, struct ieee80211_reg_rule *reg_rule)
{
	int hits;
	float start_freq_khz, end_freq_khz, max_bandwidth_khz, max_eirp;

	hits = sscanf(line, "\t(%f - %f @ %f), (%f)\n",
		      &start_freq_khz,
		      &end_freq_khz,
		      &max_bandwidth_khz,
		      &max_eirp);

	if (hits != 4)
		return -EINVAL;

	reg_rule->freq_range.start_freq_khz =
		REGLIB_MHZ_TO_KHZ(start_freq_khz);
	reg_rule->freq_range.end_freq_khz =
		REGLIB_MHZ_TO_KHZ(end_freq_khz);
	reg_rule->freq_range.max_bandwidth_khz =
		REGLIB_MHZ_TO_KHZ(max_bandwidth_khz);
	reg_rule->power_rule.max_eirp =
		REGLIB_DBM_TO_MBM(max_eirp);

	reg_rule->flags = 0;

	if (debug)
		printf("reglib_parse_rule_simple(): %d line: %s", hits, line);


	return 0;
}

static int
reglib_parse_rule_simple_mw(char *line, struct ieee80211_reg_rule *reg_rule)
{
	int hits;
	float start_freq_khz, end_freq_khz, max_bandwidth_khz, max_eirp;
	char mw[3];

	hits = sscanf(line, "\t(%f - %f @ %f), (%f %2[mW])\n",
		      &start_freq_khz,
		      &end_freq_khz,
		      &max_bandwidth_khz,
		      &max_eirp, mw);

	if (hits != 4)
		return -EINVAL;


	reg_rule->freq_range.start_freq_khz =
		REGLIB_MHZ_TO_KHZ(start_freq_khz);
	reg_rule->freq_range.end_freq_khz =
		REGLIB_MHZ_TO_KHZ(end_freq_khz);
	reg_rule->freq_range.max_bandwidth_khz =
		REGLIB_MHZ_TO_KHZ(max_bandwidth_khz);
	reg_rule->power_rule.max_eirp =
		REGLIB_MW_TO_MBM(max_eirp);

	reg_rule->flags = 0;

	if (debug)
		printf("reglib_parse_rule_simple_mw(): %d line: %s",
		       hits, line);

	return 0;
}

static int
reglib_parse_rule_args(char *line, struct ieee80211_reg_rule *reg_rule)
{
#define IGNORE_COMMA_OR_SPACE "%*[ ,]"
	int hits;
	char flag_list[9][100];
	unsigned int i = 0;
	float start_freq_khz, end_freq_khz, max_bandwidth_khz, max_eirp;

	for (i = 0; i < 9; i++)
		memset(flag_list[i], 0, sizeof(flag_list[i]));

	hits = sscanf(line, "\t(%f - %f @ %f), (%f)"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s",
		      &start_freq_khz,
		      &end_freq_khz,
		      &max_bandwidth_khz,
		      &max_eirp,
		      flag_list[0],
		      flag_list[1],
		      flag_list[2],
		      flag_list[3],
		      flag_list[4],
		      flag_list[5],
		      flag_list[6],
		      flag_list[7],
		      flag_list[8]);

	if (hits < 5)
		return -EINVAL;

	reg_rule->freq_range.start_freq_khz =
		REGLIB_MHZ_TO_KHZ(start_freq_khz);
	reg_rule->freq_range.end_freq_khz =
		REGLIB_MHZ_TO_KHZ(end_freq_khz);
	reg_rule->freq_range.max_bandwidth_khz =
		REGLIB_MHZ_TO_KHZ(max_bandwidth_khz);
	reg_rule->power_rule.max_eirp =
		REGLIB_DBM_TO_MBM(max_eirp);

	for (i = 0; i < 8; i++)
		reg_rule->flags |= reglib_parse_rule_flag(flag_list[i]);

	if (debug)
		printf("reglib_parse_rule_args(): %d flags: %d, line: %s",
		       hits, reg_rule->flags, line);

	return 0;
#undef IGNORE_COMMA_OR_SPACE
}


static int
reglib_parse_rule_args_mw(char *line, struct ieee80211_reg_rule *reg_rule)
{
#define IGNORE_COMMA_OR_SPACE "%*[ ,]"
	int hits;
	char flag_list[9][100];
	unsigned int i = 0;
	char mw[3];
	float start_freq_khz, end_freq_khz, max_bandwidth_khz, max_eirp;

	for (i = 0; i < 9; i++)
		memset(flag_list[i], 0, sizeof(flag_list[i]));

	hits = sscanf(line, "\t(%f - %f @ %f), (%f %2[mW])"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s"
		      IGNORE_COMMA_OR_SPACE "%s",
		      &start_freq_khz,
		      &end_freq_khz,
		      &max_bandwidth_khz,
		      &max_eirp,
		      mw,
		      flag_list[0],
		      flag_list[1],
		      flag_list[2],
		      flag_list[3],
		      flag_list[4],
		      flag_list[5],
		      flag_list[6],
		      flag_list[7],
		      flag_list[8]);

	if (hits < 5)
		return -EINVAL;

	reg_rule->freq_range.start_freq_khz =
		REGLIB_MHZ_TO_KHZ(start_freq_khz);
	reg_rule->freq_range.end_freq_khz =
		REGLIB_MHZ_TO_KHZ(end_freq_khz);
	reg_rule->freq_range.max_bandwidth_khz =
		REGLIB_MHZ_TO_KHZ(max_bandwidth_khz);
	reg_rule->power_rule.max_eirp =
		REGLIB_MW_TO_MBM(max_eirp);

	for (i = 0; i < 8; i++)
		reg_rule->flags |= reglib_parse_rule_flag(flag_list[i]);

	if (debug)
		printf("reglib_parse_rule_args_mw(): %d flags: %d, line: %s",
		       hits, reg_rule->flags, line);
	return 0;
#undef IGNORE_COMMA_OR_SPACE
}

static int reglib_parse_rule(FILE *fp, struct ieee80211_reg_rule *reg_rule)
{
	char line[1024];
	char *line_p;
	unsigned int i;
	int r = 0;
	struct reglib_rule_parse_list *reglib_rule_parsers;
	size_t size_parsers = sizeof(struct reglib_rule_parse_list) + 
				4 * sizeof(int (*)(char *, struct ieee80211_reg_rule *));

	reglib_rule_parsers = malloc(size_parsers);
	if (!reglib_rule_parsers)
		return -EINVAL;
	memset(reglib_rule_parsers, 0, size_parsers);

	reglib_rule_parsers->n_parsers = 4;

	/*
	 * XXX: sscanf() is a bit odd with picking up mW
	 * case over the simple one, this order however works,
	 * gotta figure out how to be more precise.
	 */
	reglib_rule_parsers->rule_parsers[0] = reglib_parse_rule_args_mw;
	reglib_rule_parsers->rule_parsers[1] = reglib_parse_rule_args;
	reglib_rule_parsers->rule_parsers[2] = reglib_parse_rule_simple;
	reglib_rule_parsers->rule_parsers[3] = reglib_parse_rule_simple_mw;

	memset(line, 0, sizeof(line));
	line_p = fgets(line, sizeof(line), fp);
1021 1022
	if (line_p != line) {
		free(reglib_rule_parsers);
1023
		return -EINVAL;
1024
	}
1025 1026 1027 1028 1029 1030 1031

	for (i = 0; i < reglib_rule_parsers->n_parsers; i++) {
		r = reglib_rule_parsers->rule_parsers[i](line, reg_rule);
		if (r == 0)
			break;
	}

1032 1033
	free(reglib_rule_parsers);

1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133
	return r;
}

static uint32_t
reglib_get_n_rules(FILE *fp, struct ieee80211_reg_rule *reg_rule)
{
	uint32_t n_rules = 0;
	int r;
	bool save_debug = false;

	save_debug = debug;
	debug = false;

	while (1) {
		r = reglib_parse_rule(fp, reg_rule);
		if (r != 0)
			break;
		n_rules++;
	}

	debug = save_debug;

	return n_rules;
}

static int reglib_parse_reg_rule(FILE *fp, struct ieee80211_reg_rule *reg_rule)
{
	int r;

	while (1) {
		r = reglib_parse_rule(fp, reg_rule);
		if (r != 0)
			continue;
		return 0;
	}
}

static struct ieee80211_regdomain *
reglib_parse_rules(FILE *fp, struct ieee80211_regdomain *trd)
{
	struct ieee80211_regdomain *rd;
	struct ieee80211_reg_rule rule;
	struct ieee80211_reg_rule *reg_rule;
	fpos_t pos;
	unsigned int i;
	uint32_t size_of_regd = 0, num_rules = 0;
	int r;

	memset(&rule, 0, sizeof(rule));
	reg_rule = &rule;

	r = fgetpos(fp, &pos);
	if (r != 0) {
		fprintf(stderr, "fgetpos() failed: %s\n",
			strerror(errno));
		return NULL;
	}

	num_rules = reglib_get_n_rules(fp, reg_rule);
	if (!num_rules)
		return NULL;

	size_of_regd = reglib_array_len(sizeof(struct ieee80211_regdomain),
					num_rules + 1,
					sizeof(struct ieee80211_reg_rule));
	rd = malloc(size_of_regd);
	if (!rd)
		return NULL;

	memset(rd, 0, size_of_regd);
	memcpy(rd, trd, sizeof(*trd));

	rd->n_reg_rules = num_rules;

	r = fsetpos(fp, &pos);
	if (r != 0) {
		fprintf(stderr, "fsetpos() failed: %s\n",
			strerror(errno));
		free(rd);
		return NULL;
	}
	for (i = 0; i < num_rules; i++) {
		struct ieee80211_reg_rule *rrule = &rd->reg_rules[i];

		if (reglib_parse_reg_rule(fp, rrule) != 0) {
			fprintf(stderr, "rule parse failed\n");
			free(rd);
			return NULL;
		}
	}
	return rd;
}

static int
reglib_parse_country_simple(char *line, struct ieee80211_regdomain *rd)
{
	char dfs_region_alpha[9];
	char alpha2[2];
	int hits;

1134
	memset(rd, 0, sizeof(*rd));
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
	memset(alpha2, 0, sizeof(alpha2));
	memset(dfs_region_alpha, 0, sizeof(dfs_region_alpha));

	hits = sscanf(line, "country %2[a-zA-Z0-9]:",
		      alpha2);

	if (hits != 1)
		return -EINVAL;

	rd->alpha2[0] = alpha2[0];
	rd->alpha2[1] = alpha2[1];

	return 0;
}

static int reglib_parse_country_dfs(char *line, struct ieee80211_regdomain *rd)
{
	char dfs_region_alpha[9];
	char alpha2[2];
	int hits;

1156
	memset(rd, 0, sizeof(*rd));
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204
	memset(alpha2, 0, sizeof(alpha2));
	memset(dfs_region_alpha, 0, sizeof(dfs_region_alpha));

	hits = sscanf(line, "country %2[a-zA-Z0-9]:%*[ ]%s\n",
		      alpha2,
		      dfs_region_alpha);
	if (hits <= 0)
		return -EINVAL;

	if (hits != 2)
		return -EINVAL;


	rd->alpha2[0] = alpha2[0];
	rd->alpha2[1] = alpha2[1];
	rd->dfs_region = reglib_parse_dfs_region(dfs_region_alpha);

	return 0;
}

struct ieee80211_regdomain *__reglib_parse_country(FILE *fp)
{
	struct ieee80211_regdomain *rd;
	struct ieee80211_regdomain tmp_rd;
	char line[1024];
	char *line_p;
	unsigned int i;
	int r = 0;
	struct reglib_country_parse_list *reglib_country_parsers;
	size_t size_of_parsers = sizeof(struct reglib_country_parse_list) +
					2 * sizeof(int (*)(char *, struct ieee80211_regdomain *));

	reglib_country_parsers = malloc(size_of_parsers);
	if (!reglib_country_parsers)
		return NULL;
	memset(reglib_country_parsers, 0, size_of_parsers);

	reglib_country_parsers->n_parsers = 2;
	reglib_country_parsers->country_parsers[0] =
			reglib_parse_country_dfs;
	reglib_country_parsers->country_parsers[1] =
			reglib_parse_country_simple;

	memset(&tmp_rd, 0, sizeof(tmp_rd));
	memset(line, 0, sizeof(line));

	line_p = fgets(line, sizeof(line), fp);

1205 1206
	if (line_p != line) {
		free(reglib_country_parsers);
1207
		return NULL;
1208
	}
1209 1210 1211 1212 1213 1214 1215 1216 1217

	for (i = 0; i < reglib_country_parsers->n_parsers; i++) {
		r = reglib_country_parsers->country_parsers[i](line, &tmp_rd);
		if (r == 0)
			break;
	}

	if (r != 0) {
		fprintf(stderr, "Invalid country line: %s", line);
1218
		free(reglib_country_parsers);
1219 1220 1221 1222 1223
		return NULL;
	}

	rd = reglib_parse_rules(fp, &tmp_rd);

1224 1225
	free(reglib_country_parsers);

1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
	return rd;
}

static int reglib_find_next_country_stream(FILE *fp)
{
	fpos_t prev_pos;
	int r;
	unsigned int i = 0;

	while(1) {
		char line[1024];
		char *line_p;

		r = fgetpos(fp, &prev_pos);
		if (r != 0) {
			fprintf(stderr, "fgetpos() failed: %s\n",
				strerror(errno));
			return r;
		}

		memset(line, 0, sizeof(line));

		line_p = fgets(line, sizeof(line), fp);
		if (line_p == line) {
			if (strspn(line, "\n") == strlen(line)) {
				i++;
				continue;
			}
			if (strncmp(line, "country", 7) != 0)
				continue;
			r = fsetpos(fp, &prev_pos);
			if (r != 0) {
				fprintf(stderr, "fsetpos() failed: %s\n",
					strerror(errno));
				return r;
			}
			return 0;
		} else
			return EOF;
	}
}

struct ieee80211_regdomain *reglib_parse_country(FILE *fp)
{
	int r;

	r = reglib_find_next_country_stream(fp);
	if (r != 0)
		return NULL;
	return __reglib_parse_country(fp);
}

FILE *reglib_create_parse_stream(FILE *f)
{
	unsigned int lines = 0;
	FILE *fp;

	fp = tmpfile();
	if (errno) {
		fprintf(stderr, "%s\n", strerror(errno));
		return NULL;
	}

	while(1) {
		char line[1024];
		char *line_p;

		line_p = fgets(line, sizeof(line), f);
		if (line_p == line) {
			if (strchr(line, '#') == NULL) {
				fputs(line, fp);
				lines++;
			}
			continue;
		} else
			break;
	}

	rewind(fp);
	fflush(fp);

	return fp;
}
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 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

/*
 * Just whatever for now, nothing formal, but note that as bands
 * grow we'll want to make this a bit more formal somehow.
 */
static uint32_t reglib_deduce_band(uint32_t start_freq_khz)
{
	uint32_t freq_mhz = REGLIB_KHZ_TO_MHZ(start_freq_khz);

	if (freq_mhz >= 4000)
		return 5;
	if (freq_mhz > 2000 && freq_mhz < 4000)
		return 2;
	if (freq_mhz > 50000)
		return 60;
	return 1234;
}

/*
 * The idea behind a rule key is that if two rule keys share the
 * same key they can be merged together if their frequencies overlap.
 */
static uint64_t reglib_rule_key(struct ieee80211_reg_rule *reg_rule)
{
	struct ieee80211_power_rule *power_rule;
	struct ieee80211_freq_range *freq_range;
	uint32_t band;
	uint32_t key;

	freq_range = &reg_rule->freq_range;
	band = reglib_deduce_band(freq_range->start_freq_khz);

	power_rule = &reg_rule->power_rule;

	key = ((power_rule->max_eirp ^  0) <<  0) ^
	      ((reg_rule->flags      ^  8) <<  8) ^
	      ((band                 ^ 16) << 16);

	return key;
}

struct reglib_optimize_map {
	bool optimized;
	uint32_t key;
};

/* Does the provided rule suffice both of the other two */
static int reglib_opt_rule_fit(struct ieee80211_reg_rule *rule1,
			       struct ieee80211_reg_rule *rule2,
			       struct ieee80211_reg_rule *opt_rule)
{
	struct ieee80211_reg_rule interesected_rule;
	struct ieee80211_reg_rule *int_rule;
	int r;

	memset(&interesected_rule, 0, sizeof(struct ieee80211_reg_rule));
	int_rule = &interesected_rule;

	r = reg_rules_intersect(rule1, opt_rule, int_rule);
	if (r != 0)
		return r;
	r = reg_rules_intersect(rule2, opt_rule, int_rule);
	if (r != 0)
		return r;

	return 0;
}

static int reg_rule_optimize(struct ieee80211_reg_rule *rule1,
			     struct ieee80211_reg_rule *rule2,
			     struct ieee80211_reg_rule *opt_rule)
{
	int r;

	r = reg_rules_union(rule1, rule2, opt_rule);
	if (r != 0)
		return r;
	r = reglib_opt_rule_fit(rule1, rule2, opt_rule);
	if (r != 0)
		return r;

	return 0;
}

/*
 * Here's the math explanation:
 *
 * This takes each pivot frequency on the regulatory domain, computes
 * the union between it each regulatory rule on the regulatory domain
 * sequentially, and after that it tries to verify that the pivot frequency
 * fits on it by computing an intersection between it and the union, if
 * a rule exist as a possible intersection then we know the rule can be
 * subset of the combination of the two frequency ranges (union) computed.
 */
static unsigned int reg_rule_optimize_rd(struct ieee80211_regdomain *rd,
					 unsigned int rule_idx,
					 struct ieee80211_reg_rule *opt_rule,
					 struct reglib_optimize_map *opt_map)
{
	unsigned int i;
	struct ieee80211_reg_rule *rule1;
	struct ieee80211_reg_rule *rule2;

	struct ieee80211_reg_rule tmp_optimized_rule;
	struct ieee80211_reg_rule *tmp_opt_rule;

	struct ieee80211_reg_rule *target_rule;

	unsigned int optimized = 0;
	int r;

	if (rule_idx > rd->n_reg_rules)
		return 0;

	rule1 = &rd->reg_rules[rule_idx];

	memset(&tmp_optimized_rule, 0, sizeof(struct ieee80211_reg_rule));
	tmp_opt_rule = &tmp_optimized_rule;

	memset(opt_rule, 0, sizeof(*opt_rule));

	for (i = 0; i < rd->n_reg_rules; i++) {
		if (rule_idx == i)
			continue;
		rule2 = &rd->reg_rules[i];
		if (opt_map[rule_idx].key != opt_map[i].key)
			continue;

		target_rule = optimized ? opt_rule : rule1;
		r = reg_rule_optimize(target_rule, rule2, tmp_opt_rule);
		if (r != 0)
			continue;
		memcpy(opt_rule, tmp_opt_rule, sizeof(*tmp_opt_rule));

		if (!opt_map[i].optimized) {
			opt_map[i].optimized = true;
			optimized++;
		}
		if (!opt_map[rule_idx].optimized) {
			opt_map[rule_idx].optimized = true;
			optimized++;
		}
	}
	return optimized;
}

struct ieee80211_regdomain *
reglib_optimize_regdom(struct ieee80211_regdomain *rd)
{
	struct ieee80211_regdomain *opt_rd = NULL;
	struct ieee80211_reg_rule *reg_rule;
	struct ieee80211_reg_rule *reg_rule_dst;
	struct ieee80211_reg_rule optimized_reg_rule;
	struct ieee80211_reg_rule *opt_reg_rule;
	struct reglib_optimize_map *opt_map;
	unsigned int i, idx = 0, non_opt = 0, opt = 0;
	size_t num_rules, size_of_regd, size_of_opt_map;
	unsigned int num_opts = 0;

	size_of_opt_map = (rd->n_reg_rules + 2) *
		sizeof(struct reglib_optimize_map);
	opt_map = malloc(size_of_opt_map);
	if (!opt_map)
		return NULL;

	memset(opt_map, 0, size_of_opt_map);
	memset(&optimized_reg_rule, 0, sizeof(struct ieee80211_reg_rule));

	opt_reg_rule = &optimized_reg_rule;

	for (i = 0; i < rd->n_reg_rules; i++) {
		reg_rule = &rd->reg_rules[i];
		opt_map[i].key = reglib_rule_key(reg_rule);
	}
	for (i = 0; i < rd->n_reg_rules; i++) {
		reg_rule = &rd->reg_rules[i];
		if (opt_map[i].optimized)
			continue;
		num_opts = reg_rule_optimize_rd(rd, i, opt_reg_rule, opt_map);
		if (!num_opts)
			non_opt++;
		else
			opt += (num_opts ? 1 : 0);
	}

	num_rules = non_opt + opt;

	if (num_rules > rd->n_reg_rules)
		goto fail_opt_map;

	size_of_regd = reglib_array_len(sizeof(struct ieee80211_regdomain),
					num_rules + 1,
					sizeof(struct ieee80211_reg_rule));

	opt_rd = malloc(size_of_regd);
	if (!opt_rd)
		goto fail_opt_map;
	memset(opt_rd, 0, size_of_regd);

	opt_rd->n_reg_rules = num_rules;
	opt_rd->alpha2[0] = rd->alpha2[0];
	opt_rd->alpha2[1] = rd->alpha2[1];
	opt_rd->dfs_region = rd->dfs_region;

	memset(opt_map, 0, size_of_opt_map);
	memset(&optimized_reg_rule, 0, sizeof(struct ieee80211_reg_rule));

	opt_reg_rule = &optimized_reg_rule;

	for (i = 0; i < rd->n_reg_rules; i++) {
		reg_rule = &rd->reg_rules[i];
		opt_map[i].key = reglib_rule_key(reg_rule);
	}

	for (i = 0; i < rd->n_reg_rules; i++) {
		reg_rule = &rd->reg_rules[i];
		reg_rule_dst = &opt_rd->reg_rules[idx];
		if (opt_map[i].optimized)
			continue;
		num_opts = reg_rule_optimize_rd(rd, i, opt_reg_rule, opt_map);
		if (!num_opts)
			memcpy(reg_rule_dst, reg_rule, sizeof(struct ieee80211_reg_rule));
		else
			memcpy(reg_rule_dst, opt_reg_rule, sizeof(struct ieee80211_reg_rule));
		idx++;
	}

	if (idx != num_rules)
		goto fail;

	for (i = 0; i < opt_rd->n_reg_rules; i++) {
		reg_rule = &opt_rd->reg_rules[i];
		if (!is_valid_reg_rule(reg_rule))
			goto fail;
	}

	free(opt_map);
	return opt_rd;
fail:
	free(opt_rd);
fail_opt_map:
	free(opt_map);
	return NULL;
}