commands.c 40.3 KB
Newer Older
1
/*  Copyright (C) 2017 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
Daniel Salzman's avatar
Daniel Salzman committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    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, see <http://www.gnu.org/licenses/>.
 */

Daniel Salzman's avatar
Daniel Salzman committed
17
#include <string.h>
18
#include <unistd.h>
19
#include <sys/time.h>
Daniel Salzman's avatar
Daniel Salzman committed
20 21

#include "knot/common/log.h"
22
#include "knot/common/stats.h"
Daniel Salzman's avatar
Daniel Salzman committed
23 24
#include "knot/conf/confio.h"
#include "knot/ctl/commands.h"
Libor Peltan's avatar
Libor Peltan committed
25
#include "knot/dnssec/key-events.h"
26
#include "knot/events/handlers.h"
27
#include "knot/events/log.h"
28
#include "knot/nameserver/query_module.h"
29
#include "knot/updates/zone-update.h"
30
#include "knot/zone/timers.h"
31
#include "knot/zone/zonefile.h"
Daniel Salzman's avatar
Daniel Salzman committed
32
#include "libknot/libknot.h"
33
#include "libknot/yparser/yptrafo.h"
Daniel Salzman's avatar
Daniel Salzman committed
34
#include "contrib/macros.h"
35
#include "contrib/mempattern.h"
Daniel Salzman's avatar
Daniel Salzman committed
36
#include "contrib/string.h"
37
#include "zscanner/scanner.h"
38
#include "contrib/strtonum.h"
Daniel Salzman's avatar
Daniel Salzman committed
39

40 41 42
#define MATCH_FILTER(args, code) ((args)->data[KNOT_CTL_IDX_FILTER] == NULL || \
                                  strchr((args)->data[KNOT_CTL_IDX_FILTER], (code)) != NULL)

43 44 45 46 47 48 49 50 51 52 53
void ctl_log_data(knot_ctl_data_t *data)
{
	if (data == NULL) {
		return;
	}

	const char *zone = (*data)[KNOT_CTL_IDX_ZONE];
	const char *section = (*data)[KNOT_CTL_IDX_SECTION];
	const char *item = (*data)[KNOT_CTL_IDX_ITEM];
	const char *id = (*data)[KNOT_CTL_IDX_ID];

54 55 56 57
	if (section == NULL) {
		return;
	}

58
	if (zone != NULL) {
59 60 61 62 63 64 65 66 67 68 69 70 71 72
		log_ctl_zone_str_debug(zone,
		              "control, item '%s%s%s%s%s%s'", section,
		              (id   != NULL ? "["  : ""),
		              (id   != NULL ? id   : ""),
		              (id   != NULL ? "]"  : ""),
		              (item != NULL ? "."  : ""),
		              (item != NULL ? item : ""));
	} else {
		log_ctl_debug("control, item '%s%s%s%s%s%s'", section,
		              (id   != NULL ? "["  : ""),
		              (id   != NULL ? id   : ""),
		              (id   != NULL ? "]"  : ""),
		              (item != NULL ? "."  : ""),
		              (item != NULL ? item : ""));
73 74 75
	}
}

76
static void send_error(ctl_args_t *args, const char *msg)
Daniel Salzman's avatar
Daniel Salzman committed
77
{
78 79
	knot_ctl_data_t data;
	memcpy(&data, args->data, sizeof(data));
Daniel Salzman's avatar
Daniel Salzman committed
80

81
	data[KNOT_CTL_IDX_ERROR] = msg;
Daniel Salzman's avatar
Daniel Salzman committed
82

83 84
	int ret = knot_ctl_send(args->ctl, KNOT_CTL_TYPE_DATA, &data);
	if (ret != KNOT_EOK) {
85
		log_ctl_debug("control, failed to send error (%s)", knot_strerror(ret));
86
	}
Daniel Salzman's avatar
Daniel Salzman committed
87 88
}

89
static int get_zone(ctl_args_t *args, zone_t **zone)
Daniel Salzman's avatar
Daniel Salzman committed
90
{
91 92 93 94
	const char *name = args->data[KNOT_CTL_IDX_ZONE];
	assert(name != NULL);

	uint8_t buff[KNOT_DNAME_MAXLEN];
Daniel Salzman's avatar
Daniel Salzman committed
95

96 97 98
	knot_dname_t *dname = knot_dname_from_str(buff, name, sizeof(buff));
	if (dname == NULL) {
		return KNOT_EINVAL;
Daniel Salzman's avatar
Daniel Salzman committed
99 100
	}

101
	int ret = knot_dname_to_lower(dname);
Daniel Salzman's avatar
Daniel Salzman committed
102
	if (ret != KNOT_EOK) {
103 104
		return ret;
	}
Daniel Salzman's avatar
Daniel Salzman committed
105

106 107 108
	*zone = knot_zonedb_find(args->server->zone_db, dname);
	if (*zone == NULL) {
		return KNOT_ENOZONE;
Daniel Salzman's avatar
Daniel Salzman committed
109
	}
110 111

	return KNOT_EOK;
Daniel Salzman's avatar
Daniel Salzman committed
112 113
}

114
static int zones_apply(ctl_args_t *args, int (*fcn)(zone_t *, ctl_args_t *))
Daniel Salzman's avatar
Daniel Salzman committed
115
{
116 117 118 119 120 121 122
	// Process all configured zones if none is specified.
	if (args->data[KNOT_CTL_IDX_ZONE] == NULL) {
		knot_zonedb_foreach(args->server->zone_db, fcn, args);
		return KNOT_EOK;
	}

	int ret = KNOT_EOK;
Daniel Salzman's avatar
Daniel Salzman committed
123

124 125
	while (true) {
		zone_t *zone;
126
		ret = get_zone(args, &zone);
127 128 129 130
		if (ret == KNOT_EOK) {
			ret = fcn(zone, args);
		}
		if (ret != KNOT_EOK) {
131 132
			log_ctl_zone_str_error(args->data[KNOT_CTL_IDX_ZONE],
			                       "control, error (%s)", knot_strerror(ret));
133 134
			send_error(args, knot_strerror(ret));
		}
Daniel Salzman's avatar
Daniel Salzman committed
135

136 137 138 139
		// Get next zone name.
		ret = knot_ctl_receive(args->ctl, &args->type, &args->data);
		if (ret != KNOT_EOK || args->type != KNOT_CTL_TYPE_DATA) {
			break;
Daniel Salzman's avatar
Daniel Salzman committed
140
		}
141
		ctl_log_data(&args->data);
Daniel Salzman's avatar
Daniel Salzman committed
142 143
	}

144
	return ret;
Daniel Salzman's avatar
Daniel Salzman committed
145 146
}

147
static int zone_status(zone_t *zone, ctl_args_t *args)
Daniel Salzman's avatar
Daniel Salzman committed
148
{
149 150 151 152
	char name[KNOT_DNAME_TXT_MAXLEN + 1];
	if (knot_dname_to_str(name, zone->name, sizeof(name)) == NULL) {
		return KNOT_EINVAL;
	}
Daniel Salzman's avatar
Daniel Salzman committed
153

154
	knot_ctl_data_t data = {
155
		[KNOT_CTL_IDX_ZONE] = name
156
	};
Daniel Salzman's avatar
Daniel Salzman committed
157

158
	int ret;
Daniel Salzman's avatar
Daniel Salzman committed
159
	char buff[128];
160
	knot_ctl_type_t type = KNOT_CTL_TYPE_DATA;
161 162 163

	if (MATCH_FILTER(args, CTL_FILTER_STATUS_ROLE)) {
		data[KNOT_CTL_IDX_TYPE] = "role";
164

165 166 167 168 169
		if (zone_is_slave(conf(), zone)) {
			data[KNOT_CTL_IDX_DATA] = "slave";
		} else {
			data[KNOT_CTL_IDX_DATA] = "master";
		}
170

171 172 173 174 175 176
		ret = knot_ctl_send(args->ctl, type, &data);
		if (ret != KNOT_EOK) {
			return ret;
		} else {
			type = KNOT_CTL_TYPE_EXTRA;
		}
177
	}
178 179

	if (MATCH_FILTER(args, CTL_FILTER_STATUS_SERIAL)) {
180
		data[KNOT_CTL_IDX_TYPE] = "serial";
181

182 183
		if (zone->contents != NULL) {
			knot_rdataset_t *soa = node_rdataset(zone->contents->apex,
184
			                                     KNOT_RRTYPE_SOA);
185
			ret = snprintf(buff, sizeof(buff), "%u", knot_soa_serial(soa));
186
		} else {
187
			ret = snprintf(buff, sizeof(buff), "none");
188 189
		}
		if (ret < 0 || ret >= sizeof(buff)) {
Daniel Salzman's avatar
Daniel Salzman committed
190 191
			return KNOT_ESPACE;
		}
192 193 194

		data[KNOT_CTL_IDX_DATA] = buff;

195 196 197 198 199 200
		ret = knot_ctl_send(args->ctl, type, &data);
		if (ret != KNOT_EOK) {
			return ret;
		} else {
			type = KNOT_CTL_TYPE_EXTRA;
		}
Daniel Salzman's avatar
Daniel Salzman committed
201
	}
202 203

	if (MATCH_FILTER(args, CTL_FILTER_STATUS_TRANSACTION)) {
204 205
		data[KNOT_CTL_IDX_TYPE] = "transaction";
		data[KNOT_CTL_IDX_DATA] = (zone->control_update != NULL) ? "open" : "none";
206 207 208
		ret = knot_ctl_send(args->ctl, type, &data);
		if (ret != KNOT_EOK) {
			return ret;
209 210
		} else {
			type = KNOT_CTL_TYPE_EXTRA;
211
		}
Daniel Salzman's avatar
Daniel Salzman committed
212
	}
213

214
	bool ufrozen = zone->events.ufrozen;
215
	if (MATCH_FILTER(args, CTL_FILTER_STATUS_FREEZE)) {
216 217
		data[KNOT_CTL_IDX_TYPE] = "freeze";
		if (ufrozen) {
218
			if (zone_events_get_time(zone, ZONE_EVENT_UTHAW) < time(NULL)) {
219 220
				data[KNOT_CTL_IDX_DATA] = "yes";
			} else {
221
				data[KNOT_CTL_IDX_DATA] = "thawing";
222
			}
223
		} else {
224
			if (zone_events_get_time(zone, ZONE_EVENT_UFREEZE) < time(NULL)) {
225 226
				data[KNOT_CTL_IDX_DATA] = "no";
			} else {
227 228
				data[KNOT_CTL_IDX_DATA] = "freezing";

229
			}
230
		}
231
		ret = knot_ctl_send(args->ctl, type, &data);
232 233 234 235
		if (ret != KNOT_EOK) {
			return ret;
		}
	}
236 237

	if (MATCH_FILTER(args, CTL_FILTER_STATUS_EVENTS)) {
238
		for (zone_event_type_t i = 0; i < ZONE_EVENT_COUNT; i++) {
239 240 241 242 243 244 245 246 247 248 249 250 251
			// Events not worth showing or used elsewhere.
			if (i == ZONE_EVENT_LOAD || i == ZONE_EVENT_UFREEZE ||
			    i == ZONE_EVENT_UTHAW) {
				continue;
			}

			// Skip events affected by freeze.
			if (ufrozen && ufreeze_applies(i)) {
				continue;
			}

			data[KNOT_CTL_IDX_TYPE] = zone_events_get_name(i);
			time_t ev_time = zone_events_get_time(zone, i);
252
			if (ev_time <= 0) {
253
				ret = snprintf(buff, sizeof(buff), "not scheduled");
254 255
			} else if (ev_time <= time(NULL)) {
				ret = snprintf(buff, sizeof(buff), "pending");
256
			} else {
257 258
				ret = knot_time_print(TIME_PRINT_HUMAN_MIXED,
				                      ev_time, buff, sizeof(buff));
259 260 261 262 263 264 265 266 267
			}
			if (ret < 0 || ret >= sizeof(buff)) {
				return KNOT_ESPACE;
			}
			data[KNOT_CTL_IDX_DATA] = buff;

			ret = knot_ctl_send(args->ctl, type, &data);
			if (ret != KNOT_EOK) {
				return ret;
268
			}
269
			type = KNOT_CTL_TYPE_EXTRA;
270
		}
271 272
	}

273
	return KNOT_EOK;
Daniel Salzman's avatar
Daniel Salzman committed
274 275
}

276
static int zone_reload(zone_t *zone, ctl_args_t *args)
Daniel Salzman's avatar
Daniel Salzman committed
277
{
278
	UNUSED(args);
Daniel Salzman's avatar
Daniel Salzman committed
279

280
	if (zone_expired(zone)) {
Daniel Salzman's avatar
Daniel Salzman committed
281 282 283
		return KNOT_ENOTSUP;
	}

284
	zone_events_schedule_user(zone, ZONE_EVENT_LOAD);
Daniel Salzman's avatar
Daniel Salzman committed
285 286 287 288

	return KNOT_EOK;
}

289
static int zone_refresh(zone_t *zone, ctl_args_t *args)
Daniel Salzman's avatar
Daniel Salzman committed
290
{
291
	UNUSED(args);
Daniel Salzman's avatar
Daniel Salzman committed
292

293
	if (!zone_is_slave(conf(), zone)) {
Daniel Salzman's avatar
Daniel Salzman committed
294 295 296
		return KNOT_ENOTSUP;
	}

297
	zone_events_schedule_user(zone, ZONE_EVENT_REFRESH);
Daniel Salzman's avatar
Daniel Salzman committed
298 299 300 301

	return KNOT_EOK;
}

302
static int zone_retransfer(zone_t *zone, ctl_args_t *args)
Daniel Salzman's avatar
Daniel Salzman committed
303
{
304
	UNUSED(args);
Daniel Salzman's avatar
Daniel Salzman committed
305

306
	if (!zone_is_slave(conf(), zone)) {
Daniel Salzman's avatar
Daniel Salzman committed
307 308 309 310
		return KNOT_ENOTSUP;
	}

	zone->flags |= ZONE_FORCE_AXFR;
311
	zone_events_schedule_user(zone, ZONE_EVENT_REFRESH);
Daniel Salzman's avatar
Daniel Salzman committed
312 313 314 315

	return KNOT_EOK;
}

316
static int zone_flush(zone_t *zone, ctl_args_t *args)
Daniel Salzman's avatar
Daniel Salzman committed
317
{
318 319 320
	if (args->data[KNOT_CTL_IDX_FILTER] != NULL &&
	    strchr(args->data[KNOT_CTL_IDX_FILTER], CTL_FILTER_FLUSH_OUTDIR) != NULL) {
		// ^^ this is different than macro MATCH_FILTER
321 322
		return zone_dump_to_dir(conf(), zone, args->data[KNOT_CTL_IDX_DATA]);
	}
Daniel Salzman's avatar
Daniel Salzman committed
323

324 325 326 327
	if (ctl_has_flag(args->data[KNOT_CTL_IDX_FLAGS], CTL_FLAG_FORCE)) {
		zone->flags |= ZONE_FORCE_FLUSH;
	}

328
	zone_events_schedule_user(zone, ZONE_EVENT_FLUSH);
Daniel Salzman's avatar
Daniel Salzman committed
329 330 331 332

	return KNOT_EOK;
}

333
static int zone_sign(zone_t *zone, ctl_args_t *args)
Daniel Salzman's avatar
Daniel Salzman committed
334
{
335
	UNUSED(args);
Daniel Salzman's avatar
Daniel Salzman committed
336 337 338 339 340 341 342

	conf_val_t val = conf_zone_get(conf(), C_DNSSEC_SIGNING, zone->name);
	if (!conf_bool(&val)) {
		return KNOT_ENOTSUP;
	}

	zone->flags |= ZONE_FORCE_RESIGN;
343 344 345 346 347
	zone_events_schedule_user(zone, ZONE_EVENT_DNSSEC);

	return KNOT_EOK;
}

348
static int zone_ksk_sbm_confirm(zone_t *zone, ctl_args_t *args)
Libor Peltan's avatar
Libor Peltan committed
349 350 351
{
	kdnssec_ctx_t ctx = { 0 };

352
	int ret = kdnssec_ctx_init(conf(), &ctx, zone->name, NULL);
Libor Peltan's avatar
Libor Peltan committed
353 354 355 356
	if (ret != KNOT_EOK) {
		return ret;
	}

357
	ret = knot_dnssec_ksk_sbm_confirm(&ctx);
Libor Peltan's avatar
Libor Peltan committed
358 359 360 361 362 363 364 365 366

	kdnssec_ctx_deinit(&ctx);

	zone_events_schedule_now(zone, ZONE_EVENT_DNSSEC);
	// NOT zone_events_schedule_user(), intentionally

	return ret;
}

367 368 369 370 371 372 373 374 375 376 377 378 379 380
static int zone_freeze(zone_t *zone, ctl_args_t *args)
{
	UNUSED(args);

	zone_events_schedule_now(zone, ZONE_EVENT_UFREEZE);

	return KNOT_EOK;
}

static int zone_thaw(zone_t *zone, ctl_args_t *args)
{
	UNUSED(args);

	zone_events_schedule_now(zone, ZONE_EVENT_UTHAW);
Daniel Salzman's avatar
Daniel Salzman committed
381 382 383 384

	return KNOT_EOK;
}

385 386 387 388 389 390 391 392 393 394 395 396 397 398
static int zone_txn_begin(zone_t *zone, ctl_args_t *args)
{
	UNUSED(args);

	if (zone->control_update != NULL) {
		return KNOT_TXN_EEXISTS;
	}

	zone->control_update = malloc(sizeof(zone_update_t));
	if (zone->control_update == NULL) {
		return KNOT_ENOMEM;
	}

	zone_update_flags_t type = (zone->contents == NULL) ? UPDATE_FULL : UPDATE_INCREMENTAL;
399
	int ret = zone_update_init(zone->control_update, zone, type | UPDATE_SIGN | UPDATE_STRICT);
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
	if (ret != KNOT_EOK) {
		free(zone->control_update);
		zone->control_update = NULL;
		return ret;
	}

	return KNOT_EOK;
}

static int zone_txn_commit(zone_t *zone, ctl_args_t *args)
{
	UNUSED(args);

	if (zone->control_update == NULL) {
		return KNOT_TXN_ENOTEXISTS;
	}

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
	// Sign update.
	conf_val_t val = conf_zone_get(conf(), C_DNSSEC_SIGNING, zone->name);
	bool dnssec_enable = (zone->control_update->flags & UPDATE_SIGN) && conf_bool(&val);
	if (dnssec_enable) {
		zone_sign_reschedule_t resch = { 0 };
		int ret = knot_dnssec_sign_update(zone->control_update, &resch);
		if (ret != KNOT_EOK) {
			zone_update_clear(zone->control_update);
			free(zone->control_update);
			zone->control_update = NULL;
			return ret;
		}
		log_dnssec_next(zone->name, (time_t)resch.next_sign);
		zone_events_schedule_at(zone, ZONE_EVENT_DNSSEC, (time_t)resch.next_sign);
	}

433 434
	int ret = zone_update_commit(conf(), zone->control_update);
	if (ret != KNOT_EOK) {
435 436 437 438 439
		/* Invalidate the transaction if aborted. */
		if (zone->control_update->zone == NULL) {
			free(zone->control_update);
			zone->control_update = NULL;
		}
440 441 442 443 444 445 446
		return ret;
	}

	zone_update_clear(zone->control_update);
	free(zone->control_update);
	zone->control_update = NULL;

447
	/* Sync zonefile immediately if configured. */
448
	val = conf_zone_get(conf(), C_ZONEFILE_SYNC, zone->name);
449
	if (conf_int(&val) == 0) {
450
		zone_events_schedule_now(zone, ZONE_EVENT_FLUSH);
451 452
	}

453
	zone_events_schedule_now(zone, ZONE_EVENT_NOTIFY);
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 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 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 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 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 644 645 646 647 648 649
	return KNOT_EOK;
}

static int zone_txn_abort(zone_t *zone, ctl_args_t *args)
{
	UNUSED(args);

	if (zone->control_update == NULL) {
		return KNOT_TXN_ENOTEXISTS;
	}

	zone_update_clear(zone->control_update);
	free(zone->control_update);
	zone->control_update = NULL;

	return KNOT_EOK;
}

typedef struct {
	ctl_args_t *args;
	int type_filter; // -1: no specific type, [0, 2^16]: specific type.
	knot_dump_style_t style;
	knot_ctl_data_t data;
	char zone[KNOT_DNAME_TXT_MAXLEN + 1];
	char owner[KNOT_DNAME_TXT_MAXLEN + 1];
	char ttl[16];
	char type[32];
	char rdata[2 * 65536];
} send_ctx_t;

static send_ctx_t *create_send_ctx(const knot_dname_t *zone_name, ctl_args_t *args)
{
	send_ctx_t *ctx = mm_alloc(&args->mm, sizeof(*ctx));
	if (ctx == NULL) {
		return NULL;
	}
	memset(ctx, 0, sizeof(*ctx));

	ctx->args = args;

	// Set the dump style.
	ctx->style.show_ttl = true;
	ctx->style.human_tmstamp = true;

	// Set the output data buffers.
	ctx->data[KNOT_CTL_IDX_ZONE]  = ctx->zone;
	ctx->data[KNOT_CTL_IDX_OWNER] = ctx->owner;
	ctx->data[KNOT_CTL_IDX_TTL]   = ctx->ttl;
	ctx->data[KNOT_CTL_IDX_TYPE]  = ctx->type;
	ctx->data[KNOT_CTL_IDX_DATA]  = ctx->rdata;

	// Set the ZONE.
	if (knot_dname_to_str(ctx->zone, zone_name, sizeof(ctx->zone)) == NULL) {
		mm_free(&args->mm, ctx);
		return NULL;
	}

	// Set the TYPE filter.
	if (args->data[KNOT_CTL_IDX_TYPE] != NULL) {
		uint16_t type;
		if (knot_rrtype_from_string(args->data[KNOT_CTL_IDX_TYPE], &type) != 0) {
			mm_free(&args->mm, ctx);
			return NULL;
		}
		ctx->type_filter = type;
	} else {
		ctx->type_filter = -1;
	}

	return ctx;
}

static int send_rrset(knot_rrset_t *rrset, send_ctx_t *ctx)
{
	int ret = snprintf(ctx->ttl, sizeof(ctx->ttl), "%u", knot_rrset_ttl(rrset));
	if (ret <= 0 || ret >= sizeof(ctx->ttl)) {
		return KNOT_ESPACE;
	}

	if (knot_rrtype_to_string(rrset->type, ctx->type, sizeof(ctx->type)) < 0) {
		return KNOT_ESPACE;
	}

	for (size_t i = 0; i < rrset->rrs.rr_count; ++i) {
		ret = knot_rrset_txt_dump_data(rrset, i, ctx->rdata,
		                               sizeof(ctx->rdata), &ctx->style);
		if (ret < 0) {
			return ret;
		}

		ret = knot_ctl_send(ctx->args->ctl, KNOT_CTL_TYPE_DATA, &ctx->data);
		if (ret != KNOT_EOK) {
			return ret;
		}
	}

	return KNOT_EOK;
}

static int send_node(zone_node_t *node, void *ctx_void)
{
	send_ctx_t *ctx = ctx_void;
	if (knot_dname_to_str(ctx->owner, node->owner, sizeof(ctx->owner)) == NULL) {
		return KNOT_EINVAL;
	}

	for (size_t i = 0; i < node->rrset_count; ++i) {
		knot_rrset_t rrset = node_rrset_at(node, i);

		// Check for requested TYPE.
		if (ctx->type_filter != -1 && rrset.type != ctx->type_filter) {
			continue;
		}

		int ret = send_rrset(&rrset, ctx);
		if (ret != KNOT_EOK) {
			return ret;
		}
	}

	return KNOT_EOK;
}

static int get_owner(uint8_t *out, size_t out_len, knot_dname_t *origin,
                     ctl_args_t *args)
{
	const char *owner = args->data[KNOT_CTL_IDX_OWNER];
	assert(owner != NULL);

	bool fqdn = false;
	int prefix_len = 0;

	size_t owner_len = strlen(owner);
	if (owner_len > 0 && (owner_len != 1 || owner[0] != '@')) {
		// Check if the owner is FQDN.
		if (owner[owner_len - 1] == '.') {
			fqdn = true;
		}

		knot_dname_t *dname = knot_dname_from_str(out, owner, out_len);
		if (dname == NULL) {
			return KNOT_EINVAL;
		}

		int ret = knot_dname_to_lower(dname);
		if (ret != KNOT_EOK) {
			return ret;
		}

		prefix_len = knot_dname_size(out);
		if (prefix_len <= 0) {
			return KNOT_EINVAL;
		}

		// Ignore trailing dot.
		prefix_len--;
	}

	// Append the origin.
	if (!fqdn) {
		int origin_len = knot_dname_size(origin);
		if (origin_len <= 0 || origin_len > out_len - prefix_len) {
			return KNOT_EINVAL;
		}
		memcpy(out + prefix_len, origin, origin_len);
	}

	return KNOT_EOK;
}

static int zone_read(zone_t *zone, ctl_args_t *args)
{
	send_ctx_t *ctx = create_send_ctx(zone->name, args);
	if (ctx == NULL) {
		return KNOT_ENOMEM;
	}

	int ret = KNOT_EOK;

	if (args->data[KNOT_CTL_IDX_OWNER] != NULL) {
		uint8_t owner[KNOT_DNAME_MAXLEN];

		ret = get_owner(owner, sizeof(owner), zone->name, args);
		if (ret != KNOT_EOK) {
			goto zone_read_failed;
		}

		const zone_node_t *node = zone_contents_find_node(zone->contents, owner);
		if (node == NULL) {
			ret = KNOT_ENONODE;
			goto zone_read_failed;
		}

		ret = send_node((zone_node_t *)node, ctx);
	} else if (zone->contents != NULL) {
650
		ret = zone_contents_apply(zone->contents, send_node, ctx);
651 652 653 654 655 656 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 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
	}

zone_read_failed:
	mm_free(&args->mm, ctx);

	return ret;
}

static int zone_flag_txn_get(zone_t *zone, ctl_args_t *args, const char *flag)
{
	if (zone->control_update == NULL) {
		return KNOT_TXN_ENOTEXISTS;
	}

	send_ctx_t *ctx = create_send_ctx(zone->name, args);
	if (ctx == NULL) {
		return KNOT_ENOMEM;
	}
	ctx->data[KNOT_CTL_IDX_FLAGS] = flag;

	int ret = KNOT_EOK;

	if (args->data[KNOT_CTL_IDX_OWNER] != NULL) {
		uint8_t owner[KNOT_DNAME_MAXLEN];

		ret = get_owner(owner, sizeof(owner), zone->name, args);
		if (ret != KNOT_EOK) {
			goto zone_txn_get_failed;
		}

		const zone_node_t *node = zone_update_get_node(zone->control_update, owner);
		if (node == NULL) {
			ret = KNOT_ENONODE;
			goto zone_txn_get_failed;
		}

		ret = send_node((zone_node_t *)node, ctx);
	} else {
		zone_update_iter_t it;
		ret = zone_update_iter(&it, zone->control_update);
		if (ret != KNOT_EOK) {
			goto zone_txn_get_failed;
		}

		const zone_node_t *iter_node = zone_update_iter_val(&it);
		while (iter_node != NULL) {
			ret = send_node((zone_node_t *)iter_node, ctx);
			if (ret != KNOT_EOK) {
				zone_update_iter_finish(&it);
				goto zone_txn_get_failed;
			}

			ret = zone_update_iter_next(&it);
			if (ret != KNOT_EOK) {
				zone_update_iter_finish(&it);
				goto zone_txn_get_failed;
			}

			iter_node = zone_update_iter_val(&it);
		}
		zone_update_iter_finish(&it);
	}

zone_txn_get_failed:
	mm_free(&args->mm, ctx);

	return ret;
}

static int zone_txn_get(zone_t *zone, ctl_args_t *args)
{
	return zone_flag_txn_get(zone, args, NULL);
}

static int send_changeset_part(changeset_t *ch, send_ctx_t *ctx, bool from)
{
	ctx->data[KNOT_CTL_IDX_FLAGS] = from ? CTL_FLAG_REM : CTL_FLAG_ADD;

	// Send SOA only if explicitly changed.
	if (ch->soa_to != NULL) {
		knot_rrset_t *soa = from ? ch->soa_from : ch->soa_to;
		assert(soa);

		char *owner = knot_dname_to_str(ctx->owner, soa->owner, sizeof(ctx->owner));
		if (owner == NULL) {
			return KNOT_EINVAL;
		}

		int ret = send_rrset(soa, ctx);
		if (ret != KNOT_EOK) {
			return ret;
		}
	}

	// Send other records.
	changeset_iter_t it;
747
	int ret = from ? changeset_iter_rem(&it, ch) : changeset_iter_add(&it, ch);
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 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
	if (ret != KNOT_EOK) {
		return ret;
	}

	knot_rrset_t rrset = changeset_iter_next(&it);
	while (!knot_rrset_empty(&rrset)) {
		char *owner = knot_dname_to_str(ctx->owner, rrset.owner, sizeof(ctx->owner));
		if (owner == NULL) {
			changeset_iter_clear(&it);
			return KNOT_EINVAL;
		}

		ret = send_rrset(&rrset, ctx);
		if (ret != KNOT_EOK) {
			changeset_iter_clear(&it);
			return ret;
		}

		rrset = changeset_iter_next(&it);
	}
	changeset_iter_clear(&it);

	return KNOT_EOK;
}

static int send_changeset(changeset_t *ch, send_ctx_t *ctx)
{
	// First send 'from' changeset part.
	int ret = send_changeset_part(ch, ctx, true);
	if (ret != KNOT_EOK) {
		return ret;
	}

	// Second send 'to' changeset part.
	ret = send_changeset_part(ch, ctx, false);
	if (ret != KNOT_EOK) {
		return ret;
	}

	return KNOT_EOK;
}

static int zone_txn_diff(zone_t *zone, ctl_args_t *args)
{
	if (zone->control_update == NULL) {
		return KNOT_TXN_ENOTEXISTS;
	}

	// FULL update has no changeset to print, do a 'get' instead.
	if (zone->control_update->flags & UPDATE_FULL) {
		return zone_flag_txn_get(zone, args, CTL_FLAG_ADD);
	}

	send_ctx_t *ctx = create_send_ctx(zone->name, args);
	if (ctx == NULL) {
		return KNOT_ENOMEM;
	}

	int ret = send_changeset(&zone->control_update->change, ctx);
	mm_free(&args->mm, ctx);
	return ret;
}

static int get_ttl(zone_t *zone, ctl_args_t *args, uint32_t *ttl)
{
	uint8_t owner[KNOT_DNAME_MAXLEN];

	int ret = get_owner(owner, sizeof(owner), zone->name, args);
	if (ret != KNOT_EOK) {
		return ret;
	}

	const zone_node_t *node = zone_update_get_node(zone->control_update, owner);
	if (node == NULL) {
		return KNOT_ETTL;
	}

	uint16_t type;
	if (knot_rrtype_from_string(args->data[KNOT_CTL_IDX_TYPE], &type) != 0) {
		return KNOT_EINVAL;
	}

	knot_rdataset_t *rdataset = node_rdataset(node, type);
	if (rdataset == NULL) {
		return KNOT_ETTL;
	}

	*ttl = knot_rdataset_ttl(rdataset);

	return KNOT_EOK;
}

static int create_rrset(knot_rrset_t **rrset, zone_t *zone, ctl_args_t *args,
                        bool need_ttl)
{
	char origin_buff[KNOT_DNAME_TXT_MAXLEN + 1];
	char *origin = knot_dname_to_str(origin_buff, zone->name, sizeof(origin_buff));
	if (origin == NULL) {
		return KNOT_EINVAL;
	}

	const char *owner = args->data[KNOT_CTL_IDX_OWNER];
	const char *type  = args->data[KNOT_CTL_IDX_TYPE];
	const char *data  = args->data[KNOT_CTL_IDX_DATA];
	const char *ttl   = need_ttl ? args->data[KNOT_CTL_IDX_TTL] : NULL;

	// Prepare a buffer for a reconstructed record.
	const size_t buff_len = sizeof(((send_ctx_t *)0)->owner) +
	                        sizeof(((send_ctx_t *)0)->ttl) +
	                        sizeof(((send_ctx_t *)0)->type) +
	                        sizeof(((send_ctx_t *)0)->rdata);
	char *buff = mm_alloc(&args->mm, buff_len);
	if (buff == NULL) {
		return KNOT_ENOMEM;
	}

	uint32_t default_ttl = 0;
	if (ttl == NULL) {
		int ret = get_ttl(zone, args, &default_ttl);
		if (need_ttl && ret != KNOT_EOK) {
			mm_free(&args->mm, buff);
			return ret;
		}
	}

	// Reconstruct the record.
	int ret = snprintf(buff, buff_len, "%s %s %s %s\n",
	                   (owner != NULL ? owner : ""),
	                   (ttl   != NULL ? ttl   : ""),
	                   (type  != NULL ? type  : ""),
	                   (data  != NULL ? data  : ""));
	if (ret <= 0 || ret >= buff_len) {
		mm_free(&args->mm, buff);
		return KNOT_ESPACE;
	}
	size_t rdata_len = ret;

	// Initialize RR parser.
	zs_scanner_t *scanner = mm_alloc(&args->mm, sizeof(*scanner));
	if (scanner == NULL) {
		ret = KNOT_ENOMEM;
		goto parser_failed;
	}

	// Parse the record.
	if (zs_init(scanner, origin, KNOT_CLASS_IN, default_ttl) != 0 ||
	    zs_set_input_string(scanner, buff, rdata_len) != 0 ||
	    zs_parse_record(scanner) != 0 ||
	    scanner->state != ZS_STATE_DATA) {
		ret = KNOT_EPARSEFAIL;
		goto parser_failed;
	}

	// Create output rrset.
	*rrset = knot_rrset_new(scanner->r_owner, scanner->r_type,
	                        scanner->r_class, NULL);
	if (*rrset == NULL) {
		ret = KNOT_ENOMEM;
		goto parser_failed;
	}

	ret = knot_rrset_add_rdata(*rrset, scanner->r_data, scanner->r_data_length,
	                           scanner->r_ttl, NULL);
parser_failed:
	zs_deinit(scanner);
	mm_free(&args->mm, scanner);
	mm_free(&args->mm, buff);

	return ret;
}

static int zone_txn_set(zone_t *zone, ctl_args_t *args)
{
	if (zone->control_update == NULL) {
		return KNOT_TXN_ENOTEXISTS;
	}

	if (args->data[KNOT_CTL_IDX_OWNER] == NULL ||
	    args->data[KNOT_CTL_IDX_TYPE]  == NULL) {
		return KNOT_EINVAL;
	}

	knot_rrset_t *rrset;
	int ret = create_rrset(&rrset, zone, args, true);
	if (ret != KNOT_EOK) {
		return ret;
	}

	ret = zone_update_add(zone->control_update, rrset);
	knot_rrset_free(&rrset, NULL);

	// Silently update TTL.
	if (ret == KNOT_ETTL) {
		ret = KNOT_EOK;
	}

	return ret;
}

static int zone_txn_unset(zone_t *zone, ctl_args_t *args)
{
	if (zone->control_update == NULL) {
		return KNOT_TXN_ENOTEXISTS;
	}

	if (args->data[KNOT_CTL_IDX_OWNER] == NULL) {
		return KNOT_EINVAL;
	}

	// Remove specific record.
	if (args->data[KNOT_CTL_IDX_DATA] != NULL) {
		if (args->data[KNOT_CTL_IDX_TYPE] == NULL) {
			return KNOT_EINVAL;
		}

		knot_rrset_t *rrset;
		int ret = create_rrset(&rrset, zone, args, false);
		if (ret != KNOT_EOK) {
			return ret;
		}

		ret = zone_update_remove(zone->control_update, rrset);
		knot_rrset_free(&rrset, NULL);
		return ret;
	} else {
		uint8_t owner[KNOT_DNAME_MAXLEN];

		int ret = get_owner(owner, sizeof(owner), zone->name, args);
		if (ret != KNOT_EOK) {
			return ret;
		}

		// Remove whole rrset.
		if (args->data[KNOT_CTL_IDX_TYPE] != NULL) {
			uint16_t type;
			if (knot_rrtype_from_string(args->data[KNOT_CTL_IDX_TYPE],
			                            &type) != 0) {
				return KNOT_EINVAL;
			}

			return zone_update_remove_rrset(zone->control_update, owner, type);
		// Remove whole node.
		} else {
			return zone_update_remove_node(zone->control_update, owner);
		}
	}

}

997 998 999
static int zone_purge(zone_t *zone, ctl_args_t *args)
{
	// Abort possible editing transaction.
1000 1001 1002
	if (MATCH_FILTER(args, CTL_FILTER_PURGE_EXPIRE)) {
		(void)zone_txn_abort(zone, args);
	}
1003

1004
	// Purge the zone timers.
1005 1006 1007
	if (MATCH_FILTER(args, CTL_FILTER_PURGE_TIMERS)) {
		memset(&zone->timers, 0, sizeof(zone->timers));
	}
1008

1009
	// Expire the zone.
1010 1011 1012
	if (MATCH_FILTER(args, CTL_FILTER_PURGE_EXPIRE)) {
		(void)event_expire(conf(), zone);
	}
1013 1014

	// Purge the zone file.
1015 1016 1017 1018 1019
	if (MATCH_FILTER(args, CTL_FILTER_PURGE_ZONEFILE)) {
		char *zonefile = conf_zonefile(conf(), zone->name);
		(void)unlink(zonefile);
		free(zonefile);
	}
1020 1021

	// Purge the zone journal.
1022 1023 1024 1025
	if (MATCH_FILTER(args, CTL_FILTER_PURGE_JOURNAL)) {
		if (journal_open(zone->journal, zone->journal_db, zone->name) == KNOT_EOK) {
			(void)journal_scrape(zone->journal);
		}
1026
	}
1027

1028 1029 1030 1031 1032
	// Purge KASP DB.
	if (MATCH_FILTER(args, CTL_FILTER_PURGE_KASPDB)) {
		if (kasp_db_open(*kaspdb()) == KNOT_EOK) {
			(void)kasp_db_delete_all(*kaspdb(), zone->name);
		}
1033 1034
	}

1035 1036 1037
	return KNOT_EOK;
}

1038 1039 1040 1041 1042 1043 1044 1045
static int send_stats_ctr(mod_ctr_t *ctr, ctl_args_t *args, knot_ctl_data_t *data)
{
	char index[128];
	char value[32];

	if (ctr->count == 1) {
		int ret = snprintf(value, sizeof(value), "%"PRIu64, ctr->counter);
		if (ret <= 0 || ret >= sizeof(value)) {
1046
			return KNOT_ESPACE;
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
		(*data)[KNOT_CTL_IDX_ID] = NULL;
		(*data)[KNOT_CTL_IDX_DATA] = value;

		ret = knot_ctl_send(args->ctl, KNOT_CTL_TYPE_DATA, data);
		if (ret != KNOT_EOK) {
			return ret;
		}
	} else {
		bool force = ctl_has_flag(args->data[KNOT_CTL_IDX_FLAGS],
		                          CTL_FLAG_FORCE);

		for (uint32_t i = 0; i < ctr->count; i++) {
			// Skip empty counters.
			if (ctr->counters[i] == 0 && !force) {
				continue;
			}

			int ret;
			if (ctr->idx_to_str) {
				char *str = ctr->idx_to_str(i, ctr->count);
				if (str == NULL) {
					continue;
				}
				ret = snprintf(index, sizeof(index), "%s", str);
				free(str);
			} else {
				ret = snprintf(index, sizeof(index), "%u", i);
			}
			if (ret <= 0 || ret >= sizeof(index)) {
1078
				return KNOT_ESPACE;
1079 1080
			}

1081
			ret = snprintf(value, sizeof(value), "%"PRIu64,
1082 1083
			               ctr->counters[i]);
			if (ret <= 0 || ret >= sizeof(value)) {
1084
				return KNOT_ESPACE;
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
			}

			(*data)[KNOT_CTL_IDX_ID] = index;
			(*data)[KNOT_CTL_IDX_DATA] = value;

			knot_ctl_type_t type = (i == 0) ? KNOT_CTL_TYPE_DATA :
			                                  KNOT_CTL_TYPE_EXTRA;
			ret = knot_ctl_send(args->ctl, type, data);
			if (ret != KNOT_EOK) {
				return ret;
			}
		}
	}
1098 1099 1100 1101

	return KNOT_EOK;
}

1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
static int modules_stats(list_t *query_modules, ctl_args_t *args, knot_dname_t *zone)
{
	if (query_modules == NULL) {
		return KNOT_EOK;
	}

	const char *section = args->data[KNOT_CTL_IDX_SECTION];
	const char *item = args->data[KNOT_CTL_IDX_ITEM];

	char name[KNOT_DNAME_TXT_MAXLEN + 1] = { 0 };
	knot_ctl_data_t data = { 0 };

	bool section_found = (section == NULL) ? true : false;
	bool item_found = (item == NULL) ? true : false;

1117
	knotd_mod_t *mod = NULL;
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 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 1178 1179 1180 1181
	WALK_LIST(mod, *query_modules) {
		// Skip modules without statistics.
		if (mod->stats_count == 0) {
			continue;
		}

		// Check for specific module.
		if (section != NULL) {
			if (section_found) {
				break;
			} else if (strcasecmp(mod->id->name + 1, section) == 0) {
				section_found = true;
			} else {
				continue;
			}
		}

		data[KNOT_CTL_IDX_SECTION] = mod->id->name + 1;

		for (int i = 0; i < mod->stats_count; i++) {
			mod_ctr_t *ctr = mod->stats + i;

			// Skip empty counter.
			if (ctr->name == NULL) {
				continue;
			}

			// Check for specific counter.
			if (item != NULL) {
				if (item_found) {
					break;
				} else if (strcasecmp(ctr->name, item) == 0) {
					item_found = true;
				} else {
					continue;
				}
			}

			// Prepare zone name if not already prepared.
			if (zone != NULL && name[0] == '\0') {
				if (knot_dname_to_str(name, zone, sizeof(name)) == NULL) {
					return KNOT_EINVAL;
				}
				data[KNOT_CTL_IDX_ZONE] = name;
			}

			data[KNOT_CTL_IDX_ITEM] = ctr->name;

			// Send the counters.
			int ret = send_stats_ctr(ctr, args, &data);
			if (ret != KNOT_EOK) {
				return ret;
			}
		}
	}

	return (section_found && item_found) ? KNOT_EOK : KNOT_ENOENT;
}

static int zone_stats(zone_t *zone, ctl_args_t *args)
{
	return modules_stats(&zone->query_modules, args, zone->name);
}

1182
static int ctl_zone(ctl_args_t *args, ctl_cmd_t cmd)
Daniel Salzman's avatar
Daniel Salzman committed
1183
{
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
	switch (cmd) {
	case CTL_ZONE_STATUS:
		return zones_apply(args, zone_status);
	case CTL_ZONE_RELOAD:
		return zones_apply(args, zone_reload);
	case CTL_ZONE_REFRESH:
		return zones_apply(args, zone_refresh);
	case CTL_ZONE_RETRANSFER:
		return zones_apply(args, zone_retransfer);
	case CTL_ZONE_FLUSH:
		return zones_apply(args, zone_flush);
	case CTL_ZONE_SIGN:
		return zones_apply(args, zone_sign);
1197
	case CTL_ZONE_KSK_SBM:
1198
		return zones_apply(args, zone_ksk_sbm_confirm);
1199 1200 1201 1202
	case CTL_ZONE_FREEZE:
		return zones_apply(args, zone_freeze);
	case CTL_ZONE_THAW:
		return zones_apply(args, zone_thaw);
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
	case CTL_ZONE_READ:
		return zones_apply(args, zone_read);
	case CTL_ZONE_BEGIN:
		return zones_apply(args, zone_txn_begin);
	case CTL_ZONE_COMMIT:
		return zones_apply(args, zone_txn_commit);
	case CTL_ZONE_ABORT:
		return zones_apply(args, zone_txn_abort);
	case CTL_ZONE_DIFF:
		return zones_apply(args, zone_txn_diff);
	case CTL_ZONE_GET:
		return zones_apply(args, zone_txn_get);
	case CTL_ZONE_SET:
		return zones_apply(args, zone_txn_set);
	case CTL_ZONE_UNSET:
		return zones_apply(args, zone_txn_unset);
1219 1220
	case CTL_ZONE_PURGE:
		return zones_apply(args, zone_purge);
1221 1222
	case CTL_ZONE_STATS:
		return zones_apply(args, zone_stats);
1223 1224
	default:
		assert(0);
1225
		return KNOT_EINVAL;
1226
	}
Daniel Salzman's avatar
Daniel Salzman committed
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
static int server_status(ctl_args_t *args)
{
	const char *type = args->data[KNOT_CTL_IDX_TYPE];

	if (type == NULL || strlen(type) == 0) {
		return KNOT_EOK;
	}

	char buff[2048] = "";

	int ret;
	if (strcasecmp(type, "version") == 0) {
		ret = snprintf(buff, sizeof(buff), "Version: %s", PACKAGE_VERSION);
	} else if (strcasecmp(type, "workers") == 0) {
		ret = snprintf(buff, sizeof(buff), "UDP workers: %zu, TCP workers %zu, "
		               "background workers: %zu", conf_udp_threads(conf()),
		               conf_tcp_threads(conf()), conf_bg_threads(conf()));
	} else if (strcasecmp(type, "configure") == 0) {
		ret = snprintf(buff, sizeof(buff), "%s", CONFIGURE_SUMMARY);
	} else {
		return KNOT_EINVAL;
	}
	if (ret <= 0 || ret >= sizeof(buff)) {
		return KNOT_ESPACE;
	}

	args->data[KNOT_CTL_IDX_DATA] = buff;

	return knot_ctl_send(args->ctl, KNOT_CTL_TYPE_DATA, &args->data);
}

1260
static int ctl_server(ctl_args_t *args, ctl_cmd_t cmd)
Daniel Salzman's avatar
Daniel Salzman committed
1261
{
1262 1263 1264 1265
	int ret = KNOT_EOK;

	switch (cmd) {
	case CTL_STATUS:
1266 1267 1268
		ret = server_status(args);
		if (ret != KNOT_EOK) {
			send_error(args, knot_strerror(ret));
1269
		}
1270 1271 1272 1273 1274
		break;
	case CTL_STOP:
		ret = KNOT_CTL_ESTOP;
		break;
	case CTL_RELOAD:
1275
		ret = server_reload(args->server);
1276 1277 1278 1279 1280 1281
		if (ret != KNOT_EOK) {
			send_error(args, knot_strerror(ret));
		}
		break;
	default:
		assert(0);
1282
		ret = KNOT_EINVAL;
1283
	}
Daniel Salzman's avatar
Daniel Salzman committed
1284

1285
	return ret;
Daniel Salzman's avatar
Daniel Salzman committed
1286 1287
}

1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
static int ctl_stats(ctl_args_t *args, ctl_cmd_t cmd)
{
	const char *section = args->data[KNOT_CTL_IDX_SECTION];
	const char *item = args->data[KNOT_CTL_IDX_ITEM];

	bool found = (section == NULL) ? true : false;

	// Process server metrics.
	if (section == NULL || strcasecmp(section, "server") == 0) {
		char value[32];
		knot_ctl_data_t data = {
			[KNOT_CTL_IDX_SECTION] = "server",
			[KNOT_CTL_IDX_DATA] = value
		};

		for (const stats_item_t *i = server_stats; i->name != NULL; i++) {
			if (item != NULL) {
				if (found) {
					break;
				} else if (strcmp(i->name, item) == 0) {
					found = true;
				} else {
					continue;
				}
			} else {
				found = true;
			}

			data[KNOT_CTL_IDX_ITEM] = i->name;
			int ret = snprintf(value, sizeof(value), "%"PRIu64,
			                   i->val(args->server));
			if (ret <= 0 || ret >= sizeof(value)) {
1320
				ret = KNOT_ESPACE;
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
				send_error(args, knot_strerror(ret));
				return ret;
			}

			ret = knot_ctl_send(args->ctl, KNOT_CTL_TYPE_DATA, &data);
			if (ret != KNOT_EOK) {
				send_error(args, knot_strerror(ret));
				return ret;
			}
		}
	}

	// Process modules metrics.
	if (section == NULL || strncasecmp(section, "mod-", strlen("mod-")) == 0) {
		int ret = modules_stats(&conf()->query_modules, args, NULL);
		if (ret != KNOT_EOK) {
			send_error(args, knot_strerror(ret));
			return ret;
		}

		found = true;
	}

	if (!found) {
		send_error(args, knot_strerror(KNOT_EINVAL));
		return KNOT_EINVAL;
	}

	return KNOT_EOK;
}

1352
static int send_block_data(conf_io_t *io, knot_ctl_data_t *data)
Daniel Salzman's avatar
Daniel Salzman committed
1353
{
1354
	knot_ctl_t *ctl = (knot_ctl_t *)io->misc;
Daniel Salzman's avatar
Daniel Salzman committed
1355

1356
	const yp_item_t *item = (io->key1 != NULL) ? io->key1 : io->key0;
Daniel Salzman's avatar
Daniel Salzman committed
1357
	assert(item != NULL);
Daniel Salzman's avatar
Daniel Salzman committed
1358

1359
	char buff[YP_MAX_TXT_DATA_LEN + 1] = "\0";
Daniel Salzman's avatar
Daniel Salzman committed
1360

1361
	(*data)[KNOT_CTL_IDX_DATA] = buff;
Daniel Salzman's avatar
Daniel Salzman committed
1362

1363 1364 1365 1366 1367 1368 1369
	// Format explicit binary data value.
	if (io->data.bin != NULL) {
		size_t buff_len = sizeof(buff);
		int ret = yp_item_to_txt(item, io->data.bin, io->data.bin_len, buff,
		                         &buff_len, YP_SNOQUOTE);
		if (ret != KNOT_EOK) {
			return ret;
Daniel Salzman's avatar
Daniel Salzman committed
1370
		}
1371
		return knot_ctl_send(ctl, KNOT_CTL_TYPE_DATA, data);
1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383
	// Format all multivalued item data if no specified index.
	} else if ((item->flags & YP_FMULTI) && io->data.index == 0) {
		size_t values = conf_val_count(io->data.val);
		for (size_t i = 0; i < values; i++) {
			conf_val(io->data.val);
			size_t buff_len = sizeof(buff);
			int ret = yp_item_to_txt(item, io->data.val->data,
			                         io->data.val->len, buff,&buff_len,
			                         YP_SNOQUOTE);
			if (ret != KNOT_EOK) {
				return ret;
			}
Daniel Salzman's avatar
Daniel Salzman committed
1384

1385 1386
			knot_ctl_type_t type = (i == 0) ? KNOT_CTL_TYPE_DATA :
			                                  KNOT_CTL_TYPE_EXTRA;
1387
			ret = knot_ctl_send(ctl, type, data);
1388 1389 1390
			if (ret != KNOT_EOK) {
				return ret;
			}
Daniel Salzman's avatar
Daniel Salzman committed
1391

1392
			conf_val_next(io->data.val);
Daniel Salzman's avatar
Daniel Salzman committed
1393
		}
1394 1395 1396 1397 1398 1399 1400 1401 1402
		return KNOT_EOK;
	// Format singlevalued item data or a specified one from multivalued.
	} else {
		conf_val(io->data.val);
		size_t buff_len = sizeof(buff);
		int ret = yp_item_to_txt(item, io->data.val->data, io->data.val->len,
		                         buff, &buff_len, YP_SNOQUOTE);
		if (ret != KNOT_EOK) {
			return ret;
Daniel Salzman's avatar
Daniel Salzman committed
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
		return knot_ctl_send(ctl, KNOT_CTL_TYPE_DATA, data);
	}
}

static int send_block(conf_io_t *io)
{
	knot_ctl_t *ctl = (knot_ctl_t *)io->misc;

	// Get possible error message.
	const char *err = io->error.str;
	if (err == NULL && io->error.code != KNOT_EOK) {
		err = knot_strerror(io->error.code);
	}

	knot_ctl_data_t data = {
		[KNOT_CTL_IDX_ERROR] = err,
	};

	if (io->key0 != NULL) {
		data[KNOT_CTL_IDX_SECTION] = io->key0->name + 1;
	}
	if (io->key1 != NULL) {
		data[KNOT_CTL_IDX_ITEM] = io->key1->name + 1;
	}

	// Get the item prefix.
	switch (io->type) {
	case NEW: data[KNOT_CTL_IDX_FLAGS] = CTL_FLAG_ADD; break;
	case OLD: data[KNOT_CTL_IDX_FLAGS] = CTL_FLAG_REM; break;
	default: break;
	}

	char id[KNOT_DNAME_TXT_MAXLEN + 1] = "\0";

	// Get the textual item id.
	if (io->id_len > 0 && io->key0 != NULL) {
		size_t id_len = sizeof(id);
		int ret = yp_item_to_txt(io->key0->var.g.id, io->id, io->id_len,
		                         id, &id_len, YP_SNOQUOTE);
		if (ret != KNOT_EOK) {
			return ret;
		}
		if (io->id_as_data) {
			data[KNOT_CTL_IDX_DATA] = id;
		} else {
			data[KNOT_CTL_IDX_ID] = id;
		}
	}

	if (io->data.val == NULL && io->data.bin == NULL) {
1454
		return knot_ctl_send(ctl, KNOT_CTL_TYPE_DATA, &data);
1455 1456
	} else {
		return send_block_data(io, &data);
Daniel Salzman's avatar
Daniel Salzman committed
1457 1458 1459
	}
}

1460
static int ctl_conf_txn(ctl_args_t *args, ctl_cmd_t cmd)
Daniel Salzman's avatar
Daniel Salzman committed
1461 1462
{
	conf_io_t io = {
1463 1464
		.fcn = send_block,
		.misc = args->ctl
Daniel Salzman's avatar
Daniel Salzman committed
1465 1466
	};

1467
	int ret = KNOT_EOK;
Daniel Salzman's avatar
Daniel Salzman committed
1468

1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
	switch (cmd) {
	case CTL_CONF_BEGIN:
		ret = conf_io_begin(false);
		break;
	case CTL_CONF_ABORT:
		conf_io_abort(false);
		ret = KNOT_EOK;
		break;
	case CTL_CONF_COMMIT:
		// First check the database.
		ret = conf_io_check(&io);
		if (ret != KNOT_EOK) {
1481 1482 1483 1484
			// A semantic error is already sent by the check function.
			if (io.error.code != KNOT_EOK) {
				return KNOT_EOK;
			}
1485
			// No transaction abort!
1486
			break;
1487
		}
Daniel Salzman's avatar
Daniel Salzman committed
1488

1489 1490 1491 1492 1493
		ret = conf_io_commit(false);
		if (ret != KNOT_EOK) {
			conf_io_abort(false);
			break;
		}
Daniel Salzman's avatar
Daniel Salzman committed
1494

1495
		ret = server_reload(args->server);
1496 1497 1498
		break;
	default:
		assert(0);
1499
		ret = KNOT_EINVAL;
Daniel Salzman's avatar
Daniel Salzman committed
1500 1501 1502
	}

	if (ret != KNOT_EOK) {
1503
		send_error(args, knot_strerror(ret));
Daniel Salzman's avatar
Daniel Salzman committed
1504 1505 1506 1507 1508
	}

	return ret;
}

1509
static int ctl_conf_read(ctl_args_t *args, ctl_cmd_t cmd)
Daniel Salzman's avatar
Daniel Salzman committed
1510 1511
{
	conf_io_t io = {
1512 1513
		.fcn = send_block,
		.misc = args->ctl
Daniel Salzman's avatar
Daniel Salzman committed
1514 1515
	};

1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
	int ret = KNOT_EOK;

	while (true) {
		const char *key0 = args->data[KNOT_CTL_IDX_SECTION];
		const char *key1 = args->data[KNOT_CTL_IDX_ITEM];
		const char *id   = args->data[KNOT_CTL_IDX_ID];

		switch (cmd) {
		case CTL_CONF_LIST:
			ret = conf_io_list(key0, &io);
			break;
		case CTL_CONF_READ:
			ret = conf_io_get(key0, key1, id, true, &io);
			break;
		case CTL_CONF_DIFF:
			ret = conf_io_diff(key0, key1, id, &io);
			break;
		case CTL_CONF_GET:
			ret = conf_io_get(key0, key1, id, false, &io);
			break;
		default:
			assert(0);
1538
			ret = KNOT_EINVAL;
1539 1540 1541 1542 1543
		}
		if (ret != KNOT_EOK) {
			send_error(args, knot_strerror(ret));
			break;
		}
Daniel Salzman's avatar
Daniel Salzman committed
1544

1545 1546 1547 1548 1549
		// Get next data unit.
		ret = knot_ctl_receive(args->ctl, &args->type, &args->data);
		if (ret != KNOT_EOK || args->type != KNOT_CTL_TYPE_DATA) {
			break;
		}
1550
		ctl_log_data(&args->data);
1551
	}
Daniel Salzman's avatar
Daniel Salzman committed
1552 1553 1554 1555

	return ret;
}

1556
static int ctl_conf_modify(ctl_args_t *args, ctl_cmd_t cmd)
Daniel Salzman's avatar
Daniel Salzman committed
1557 1558
{
	// Start child transaction.
1559
	int ret = conf_io_begin(true);
Daniel Salzman's avatar
Daniel Salzman committed
1560
	if (ret != KNOT_EOK) {
1561
		send_error(args, knot_strerror(ret));
Daniel Salzman's avatar
Daniel Salzman committed
1562 1563 1564
		return ret;
	}

1565 1566 1567 1568 1569 1570 1571 1572
	while (true) {
		const char *key0 = args->data[KNOT_CTL_IDX_SECTION];
		const char *key1 = args->data[KNOT_CTL_IDX_ITEM];
		const char *id   = args->data[KNOT_CTL_IDX_ID];
		const char *data = args->data[KNOT_CTL_IDX_DATA];

		switch (cmd) {
		case CTL_CONF_SET:
1573
			ret = conf_io_set(key0, key1, id, data);
1574 1575 1576 1577 1578 1579
			break;
		case CTL_CONF_UNSET:
			ret = conf_io_unset(key0, key1, id, data);
			break;
		default:
			assert(0);
1580
			ret = KNOT_EINVAL;
1581 1582 1583 1584
		}
		if (ret != KNOT_EOK) {
			send_error(args, knot_strerror(ret));
			break;
Daniel Salzman's avatar
Daniel Salzman committed
1585 1586
		}

1587 1588 1589 1590 1591
		// Get next data unit.
		ret = knot_ctl_receive(args->ctl, &args->type, &args->data);
		if (ret != KNOT_EOK || args->type != KNOT_CTL_TYPE_DATA) {
			break;
		}
1592
		ctl_log_data(&args->data);
1593
	}
Daniel Salzman's avatar
Daniel Salzman committed
1594 1595 1596

	// Finish child transaction.
	if (ret == KNOT_EOK) {
1597 1598 1599 1600
		ret = conf_io_commit(true);
		if (ret != KNOT_EOK) {
			send_error(args, knot_strerror(ret));
		}
Daniel Salzman's avatar
Daniel Salzman committed
1601
	} else {
1602
		conf_io_abort(true);
Daniel Salzman's avatar
Daniel Salzman committed
1603 1604
	}

1605 1606
	return ret;
}
Daniel Salzman's avatar
Daniel Salzman committed
1607

1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618
typedef struct {
	const char *name;
	int (*fcn)(ctl_args_t *, ctl_cmd_t);
} desc_t;

static const desc_t cmd_table[] = {
	[CTL_NONE]            = { "" },

	[CTL_STATUS]          = { "status",          ctl_server },
	[CTL_STOP]            = { "stop",            ctl_server },
	[CTL_RELOAD]          = { "reload",          ctl_server },
1619
	[CTL_STATS]           = { "stats",           ctl_stats },
1620 1621 1622 1623 1624 1625 1626

	[CTL_ZONE_STATUS]     = { "zone-status",     ctl_zone },
	[CTL_ZONE_RELOAD]     = { "zone-reload",     ctl_zone },
	[CTL_ZONE_REFRESH]    = { "zone-refresh",    ctl_zone },
	[CTL_ZONE_RETRANSFER] = { "zone-retransfer", ctl_zone },
	[CTL_ZONE_FLUSH]      = { "zone-flush",      ctl_zone },
	[CTL_ZONE_SIGN]       = { "zone-sign",       ctl_zone },
1627
	[CTL_ZONE_KSK_SBM]    = { "zone-ksk-submitted", ctl_zone },
1628 1629
	[CTL_ZONE_FREEZE]     = { "zone-freeze",     ctl_zone },
	[CTL_ZONE_THAW]       = { "zone-thaw",       ctl_zone },
1630

1631 1632 1633 1634 1635 1636 1637 1638
	[CTL_ZONE_READ]       = { "zone-read",       ctl_zone },
	[CTL_ZONE_BEGIN]      = { "zone-begin",      ctl_zone },
	[CTL_ZONE_COMMIT]     = { "zone-commit",     ctl_zone },
	[CTL_ZONE_ABORT]      = { "zone-abort",      ctl_zone },
	[CTL_ZONE_DIFF]       = { "zone-diff",       ctl_zone },
	[CTL_ZONE_GET]        = { "zone-get",        ctl_zone },
	[CTL_ZONE_SET]        = { "zone-set",        ctl_zone },
	[CTL_ZONE_UNSET]      = { "zone-unset",      ctl_zone },
1639
	[CTL_ZONE_PURGE]      = { "zone-purge",      ctl_zone },
1640
	[CTL_ZONE_STATS]      = { "zone-stats",	     ctl_zone },
1641

1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
	[CTL_CONF_LIST]       = { "conf-list",       ctl_conf_read },
	[CTL_CONF_READ]       = { "conf-read",       ctl_conf_read },
	[CTL_CONF_BEGIN]      = { "conf-begin",      ctl_conf_txn },
	[CTL_CONF_COMMIT]     = { "conf-commit",     ctl_conf_txn },
	[CTL_CONF_ABORT]      = { "conf-abort",      ctl_conf_txn },
	[CTL_CONF_DIFF]       = { "conf-diff",       ctl_conf_read },
	[CTL_CONF_GET]        = { "conf-get",        ctl_conf_read },
	[CTL_CONF_SET]        = { "conf-set",        ctl_conf_modify },
	[CTL_CONF_UNSET]      = { "conf-unset",      ctl_conf_modify },
};
Daniel Salzman's avatar
Daniel Salzman committed
1652

Daniel Salzman's avatar
Daniel Salzman committed
1653 1654 1655
#define MAX_CTL_CODE (sizeof(cmd_table) / sizeof(desc_t) - 1)

const char *ctl_cmd_to_str(ctl_cmd_t cmd)
1656
{
Daniel Salzman's avatar
Daniel Salzman committed
1657
	if (cmd <= CTL_NONE || cmd > MAX_CTL_CODE) {
1658
		return NULL;
Daniel Salzman's avatar
Daniel Salzman committed
1659 1660
	}

1661 1662 1663 1664 1665 1666 1667
	return cmd_table[cmd].name;
}

ctl_cmd_t ctl_str_to_cmd(const char *cmd_str)
{
	if (cmd_str == NULL) {
		return CTL_NONE;
Daniel Salzman's avatar
Daniel Salzman committed
1668 1669
	}

Daniel Salzman's avatar
Daniel Salzman committed
1670
	for (ctl_cmd_t cmd = CTL_NONE + 1; cmd <= MAX_CTL_CODE; cmd++) {
1671 1672
		if (strcmp(cmd_str, cmd_table[cmd].name) == 0) {
			return cmd;
Daniel Salzman's avatar
Daniel Salzman committed
1673 1674 1675
		}
	}

1676 1677
	return CTL_NONE;
}
Daniel Salzman's avatar
Daniel Salzman committed
1678

1679 1680 1681 1682
int ctl_exec(ctl_cmd_t cmd, ctl_args_t *args)
{
	if (args == NULL) {
		return KNOT_EINVAL;
Daniel Salzman's avatar
Daniel Salzman committed
1683 1684
	}

1685 1686
	return cmd_table[cmd].fcn(args, cmd);
}
Daniel Salzman's avatar
Daniel Salzman committed
1687 1688 1689 1690 1691 1692 1693 1694 1695

bool ctl_has_flag(const char *flags, const char *flag)
{
	if (flags == NULL || flag == NULL) {
		return false;
	}

	return strstr(flags, flag) != NULL;
}