xref: /openbsd-src/usr.sbin/nsd/xfrd-disk.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*
2  * xfrd-disk.c - XFR (transfer) Daemon TCP system source file. Read/Write state to disk.
3  *
4  * Copyright (c) 2001-2006, NLnet Labs. All rights reserved.
5  *
6  * See LICENSE for the license.
7  *
8  */
9 
10 #include "config.h"
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <ctype.h>
14 #include <errno.h>
15 #include <sys/stat.h>
16 #include <sys/types.h>
17 #include <unistd.h>
18 #include "xfrd-disk.h"
19 #include "xfrd.h"
20 #include "buffer.h"
21 #include "nsd.h"
22 #include "options.h"
23 
24 /* quick tokenizer, reads words separated by whitespace.
25    No quoted strings. Comments are skipped (#... eol). */
26 static char*
27 xfrd_read_token(FILE* in)
28 {
29 	static char buf[4000];
30 	buf[sizeof(buf)-1]=0;
31 	while(1) {
32 		if(fscanf(in, " %3990s", buf) != 1)
33 			return 0;
34 
35 		if(buf[0] != '#')
36 			return buf;
37 
38 		if(!fgets(buf, sizeof(buf), in))
39 			return 0;
40 	}
41 }
42 
43 static int
44 xfrd_read_i16(FILE *in, uint16_t* v)
45 {
46 	char* p = xfrd_read_token(in);
47 	if(!p)
48 		return 0;
49 
50 	*v=atoi(p);
51 	return 1;
52 }
53 
54 static int
55 xfrd_read_i32(FILE *in, uint32_t* v)
56 {
57 	char* p = xfrd_read_token(in);
58 	if(!p)
59 		return 0;
60 
61 	*v=atoi(p);
62 	return 1;
63 }
64 
65 static int
66 xfrd_read_time_t(FILE *in, time_t* v)
67 {
68 	char* p = xfrd_read_token(in);
69 	if(!p)
70 		return 0;
71 
72 	*v=atol(p);
73 	return 1;
74 }
75 
76 static int
77 xfrd_read_check_str(FILE* in, const char* str)
78 {
79 	char *p = xfrd_read_token(in);
80 	if(!p)
81 		return 0;
82 
83 	if(strcmp(p, str) != 0)
84 		return 0;
85 
86 	return 1;
87 }
88 
89 static int
90 xfrd_read_state_soa(FILE* in, const char* id_acquired,
91 	const char* id, xfrd_soa_t* soa, time_t* soatime)
92 {
93 	char *p;
94 
95 	if(!xfrd_read_check_str(in, id_acquired) ||
96 	   !xfrd_read_time_t(in, soatime)) {
97 		return 0;
98 	}
99 
100 	if(*soatime == 0)
101 		return 1;
102 
103 	if(!xfrd_read_check_str(in, id) ||
104 	   !xfrd_read_i16(in, &soa->type) ||
105 	   !xfrd_read_i16(in, &soa->klass) ||
106 	   !xfrd_read_i32(in, &soa->ttl) ||
107 	   !xfrd_read_i16(in, &soa->rdata_count))
108 	{
109 		return 0;
110 	}
111 
112 	soa->type = htons(soa->type);
113 	soa->klass = htons(soa->klass);
114 	soa->ttl = htonl(soa->ttl);
115 	soa->rdata_count = htons(soa->rdata_count);
116 
117 	if(!(p=xfrd_read_token(in)) ||
118 	   !(soa->prim_ns[0] = dname_parse_wire(soa->prim_ns+1, p)))
119 		return 0;
120 
121 	if(!(p=xfrd_read_token(in)) ||
122 	   !(soa->email[0] = dname_parse_wire(soa->email+1, p)))
123 		return 0;
124 
125 	if(!xfrd_read_i32(in, &soa->serial) ||
126 	   !xfrd_read_i32(in, &soa->refresh) ||
127 	   !xfrd_read_i32(in, &soa->retry) ||
128 	   !xfrd_read_i32(in, &soa->expire) ||
129 	   !xfrd_read_i32(in, &soa->minimum))
130 	{
131 		return 0;
132 	}
133 
134 	soa->serial = htonl(soa->serial);
135 	soa->refresh = htonl(soa->refresh);
136 	soa->retry = htonl(soa->retry);
137 	soa->expire = htonl(soa->expire);
138 	soa->minimum = htonl(soa->minimum);
139 	return 1;
140 }
141 
142 void
143 xfrd_read_state(struct xfrd_state* xfrd)
144 {
145 	const char* statefile = xfrd->nsd->options->xfrdfile;
146 	FILE *in;
147 	uint32_t filetime = 0;
148 	uint32_t numzones, i;
149 	region_type *tempregion;
150 	time_t soa_refresh;
151 
152 	tempregion = region_create(xalloc, free);
153 	if(!tempregion)
154 		return;
155 
156 	in = fopen(statefile, "r");
157 	if(!in) {
158 		if(errno != ENOENT) {
159 			log_msg(LOG_ERR, "xfrd: Could not open file %s for reading: %s",
160 				statefile, strerror(errno));
161 		} else {
162 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: no file %s. refreshing all zones.",
163 				statefile));
164 		}
165 		region_destroy(tempregion);
166 		return;
167 	}
168 	if(!xfrd_read_check_str(in, XFRD_FILE_MAGIC) ||
169 	   !xfrd_read_check_str(in, "filetime:") ||
170 	   !xfrd_read_i32(in, &filetime) ||
171 	   (time_t)filetime > xfrd_time()+15 ||
172 	   !xfrd_read_check_str(in, "numzones:") ||
173 	   !xfrd_read_i32(in, &numzones))
174 	{
175 		log_msg(LOG_ERR, "xfrd: corrupt state file %s dated %d (now=%lld)",
176 			statefile, (int)filetime, (long long)xfrd_time());
177 		fclose(in);
178 		region_destroy(tempregion);
179 		return;
180 	}
181 
182 	for(i=0; i<numzones; i++) {
183 		char *p;
184 		xfrd_zone_t* zone;
185 		const dname_type* dname;
186 		uint32_t state, masnum, nextmas, round_num, timeout;
187 		xfrd_soa_t soa_nsd_read, soa_disk_read, soa_notified_read;
188 		time_t soa_nsd_acquired_read,
189 			soa_disk_acquired_read, soa_notified_acquired_read;
190 		xfrd_soa_t incoming_soa;
191 		time_t incoming_acquired;
192 
193 		if(nsd.signal_hint_shutdown) {
194 			fclose(in);
195 			region_destroy(tempregion);
196 			return;
197 		}
198 
199 		memset(&soa_nsd_read, 0, sizeof(soa_nsd_read));
200 		memset(&soa_disk_read, 0, sizeof(soa_disk_read));
201 		memset(&soa_notified_read, 0, sizeof(soa_notified_read));
202 
203 		if(!xfrd_read_check_str(in, "zone:") ||
204 		   !xfrd_read_check_str(in, "name:")  ||
205 		   !(p=xfrd_read_token(in)) ||
206 		   !(dname = dname_parse(tempregion, p)) ||
207 		   !xfrd_read_check_str(in, "state:") ||
208 		   !xfrd_read_i32(in, &state) || (state>2) ||
209 		   !xfrd_read_check_str(in, "master:") ||
210 		   !xfrd_read_i32(in, &masnum) ||
211 		   !xfrd_read_check_str(in, "next_master:") ||
212 		   !xfrd_read_i32(in, &nextmas) ||
213 		   !xfrd_read_check_str(in, "round_num:") ||
214 		   !xfrd_read_i32(in, &round_num) ||
215 		   !xfrd_read_check_str(in, "next_timeout:") ||
216 		   !xfrd_read_i32(in, &timeout) ||
217 		   !xfrd_read_state_soa(in, "soa_nsd_acquired:", "soa_nsd:",
218 			&soa_nsd_read, &soa_nsd_acquired_read) ||
219 		   !xfrd_read_state_soa(in, "soa_disk_acquired:", "soa_disk:",
220 			&soa_disk_read, &soa_disk_acquired_read) ||
221 		   !xfrd_read_state_soa(in, "soa_notify_acquired:", "soa_notify:",
222 			&soa_notified_read, &soa_notified_acquired_read))
223 		{
224 			log_msg(LOG_ERR, "xfrd: corrupt state file %s dated %d (now=%lld)",
225 				statefile, (int)filetime, (long long)xfrd_time());
226 			fclose(in);
227 			region_destroy(tempregion);
228 			return;
229 		}
230 
231 		zone = (xfrd_zone_t*)rbtree_search(xfrd->zones, dname);
232 		if(!zone) {
233 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: state file has info for not configured zone %s", p));
234 			continue;
235 		}
236 
237 		if(soa_nsd_acquired_read>xfrd_time()+15 ||
238 			soa_disk_acquired_read>xfrd_time()+15 ||
239 			soa_notified_acquired_read>xfrd_time()+15)
240 		{
241 			log_msg(LOG_ERR, "xfrd: statefile %s contains"
242 				" times in the future for zone %s. Ignoring.",
243 				statefile, zone->apex_str);
244 			continue;
245 		}
246 		zone->state = state;
247 		zone->master_num = masnum;
248 		zone->next_master = nextmas;
249 		zone->round_num = round_num;
250 		zone->timeout.tv_sec = timeout;
251 		zone->timeout.tv_usec = 0;
252 
253 		/* read the zone OK, now set the master properly */
254 		zone->master = acl_find_num(zone->zone_options->pattern->
255 			request_xfr, zone->master_num);
256 		if(!zone->master) {
257 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: masters changed for zone %s",
258 				zone->apex_str));
259 			zone->master = zone->zone_options->pattern->request_xfr;
260 			zone->master_num = 0;
261 			zone->round_num = 0;
262 		}
263 
264 		/*
265 		 * There is no timeout,
266 		 * or there is a notification,
267 		 * or there is a soa && current time is past refresh point
268 		 */
269 		soa_refresh = ntohl(soa_disk_read.refresh);
270 		if (soa_refresh > zone->zone_options->pattern->max_refresh_time)
271 			soa_refresh = zone->zone_options->pattern->max_refresh_time;
272 		else if (soa_refresh < zone->zone_options->pattern->min_refresh_time)
273 			soa_refresh = zone->zone_options->pattern->min_refresh_time;
274 		if(timeout == 0 || soa_notified_acquired_read != 0 ||
275 			(soa_disk_acquired_read != 0 &&
276 			(uint32_t)xfrd_time() - soa_disk_acquired_read
277 				> soa_refresh))
278 		{
279 			zone->state = xfrd_zone_refreshing;
280 			xfrd_set_refresh_now(zone);
281 		}
282 
283 		/* There is a soa && current time is past expiry point */
284 		if(soa_disk_acquired_read!=0 &&
285 			(uint32_t)xfrd_time() - soa_disk_acquired_read
286 				> ntohl(soa_disk_read.expire))
287 		{
288 			zone->state = xfrd_zone_expired;
289 			xfrd_set_refresh_now(zone);
290 		}
291 
292 		/* there is a zone read and it matches what we had before */
293 		if(zone->soa_nsd_acquired && zone->state != xfrd_zone_expired
294 			&& zone->soa_nsd.serial == soa_nsd_read.serial) {
295 			xfrd_deactivate_zone(zone);
296 			zone->state = state;
297 			xfrd_set_timer(zone, timeout);
298 		}
299 		if(zone->soa_nsd_acquired == 0 && soa_nsd_acquired_read == 0 &&
300 			soa_disk_acquired_read == 0) {
301 			/* continue expon backoff where we were + check now */
302 			zone->fresh_xfr_timeout = timeout;
303 		}
304 
305 		/* handle as an incoming SOA. */
306 		incoming_soa = zone->soa_nsd;
307 		incoming_acquired = zone->soa_nsd_acquired;
308 		zone->soa_nsd = soa_nsd_read;
309 		zone->soa_disk = soa_disk_read;
310 		zone->soa_notified = soa_notified_read;
311 		zone->soa_nsd_acquired = soa_nsd_acquired_read;
312 		/* we had better use what we got from starting NSD, not
313 		 * what we store in this file, because the actual zone
314 		 * contents trumps the contents of this cache */
315 		/* zone->soa_disk_acquired = soa_disk_acquired_read; */
316 		zone->soa_notified_acquired = soa_notified_acquired_read;
317 		if (zone->state == xfrd_zone_expired)
318 		{
319 			xfrd_send_expire_notification(zone);
320 		}
321 		xfrd_handle_incoming_soa(zone, &incoming_soa, incoming_acquired);
322 	}
323 
324 	if(!xfrd_read_check_str(in, XFRD_FILE_MAGIC)) {
325 		log_msg(LOG_ERR, "xfrd: corrupt state file %s dated %d (now=%lld)",
326 			statefile, (int)filetime, (long long)xfrd_time());
327 		region_destroy(tempregion);
328 		fclose(in);
329 		return;
330 	}
331 
332 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: read %d zones from state file", (int)numzones));
333 	fclose(in);
334 	region_destroy(tempregion);
335 }
336 
337 /* prints neato days hours and minutes. */
338 static void
339 neato_timeout(FILE* out, const char* str, time_t secs)
340 {
341 	fprintf(out, "%s", str);
342 	if(secs <= 0) {
343 		fprintf(out, " %llds", (long long)secs);
344 		return;
345 	}
346 	if(secs >= 3600*24) {
347 		fprintf(out, " %lldd", (long long)(secs/(3600*24)));
348 		secs = secs % (3600*24);
349 	}
350 	if(secs >= 3600) {
351 		fprintf(out, " %lldh", (long long)(secs/3600));
352 		secs = secs%3600;
353 	}
354 	if(secs >= 60) {
355 		fprintf(out, " %lldm", (long long)(secs/60));
356 		secs = secs%60;
357 	}
358 	if(secs > 0) {
359 		fprintf(out, " %llds", (long long)secs);
360 	}
361 }
362 
363 static void xfrd_write_dname(FILE* out, uint8_t* dname)
364 {
365 	uint8_t* d= dname+1;
366 	uint8_t len = *d++;
367 	uint8_t i;
368 
369 	if(dname[0]<=1) {
370 		fprintf(out, ".");
371 		return;
372 	}
373 
374 	while(len)
375 	{
376 		assert(d - (dname+1) <= dname[0]);
377 		for(i=0; i<len; i++)
378 		{
379 			uint8_t ch = *d++;
380 			if (isalnum((unsigned char)ch) || ch == '-' || ch == '_') {
381 				fprintf(out, "%c", ch);
382 			} else if (ch == '.' || ch == '\\') {
383 				fprintf(out, "\\%c", ch);
384 			} else {
385 				fprintf(out, "\\%03u", (unsigned int)ch);
386 			}
387 		}
388 		fprintf(out, ".");
389 		len = *d++;
390 	}
391 }
392 
393 static void
394 xfrd_write_state_soa(FILE* out, const char* id,
395 	xfrd_soa_t* soa, time_t soatime, const dname_type* ATTR_UNUSED(apex))
396 {
397 	fprintf(out, "\t%s_acquired: %d", id, (int)soatime);
398 	if(!soatime) {
399 		fprintf(out, "\n");
400 		return;
401 	}
402 	neato_timeout(out, "\t# was", xfrd_time()-soatime);
403 	fprintf(out, " ago\n");
404 
405 	fprintf(out, "\t%s: %u %u %u %u", id,
406 		(unsigned)ntohs(soa->type), (unsigned)ntohs(soa->klass),
407 		(unsigned)ntohl(soa->ttl), (unsigned)ntohs(soa->rdata_count));
408 	fprintf(out, " ");
409 	xfrd_write_dname(out, soa->prim_ns);
410 	fprintf(out, " ");
411 	xfrd_write_dname(out, soa->email);
412 	fprintf(out, " %u", (unsigned)ntohl(soa->serial));
413 	fprintf(out, " %u", (unsigned)ntohl(soa->refresh));
414 	fprintf(out, " %u", (unsigned)ntohl(soa->retry));
415 	fprintf(out, " %u", (unsigned)ntohl(soa->expire));
416 	fprintf(out, " %u\n", (unsigned)ntohl(soa->minimum));
417 	fprintf(out, "\t#");
418 	neato_timeout(out, " refresh =", ntohl(soa->refresh));
419 	neato_timeout(out, " retry =", ntohl(soa->retry));
420 	neato_timeout(out, " expire =", ntohl(soa->expire));
421 	neato_timeout(out, " minimum =", ntohl(soa->minimum));
422 	fprintf(out, "\n");
423 }
424 
425 void
426 xfrd_write_state(struct xfrd_state* xfrd)
427 {
428 	rbnode_t* p;
429 	const char* statefile = xfrd->nsd->options->xfrdfile;
430 	FILE *out;
431 	time_t now = xfrd_time();
432 
433 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: write file %s", statefile));
434 	out = fopen(statefile, "w");
435 	if(!out) {
436 		log_msg(LOG_ERR, "xfrd: Could not open file %s for writing: %s",
437 				statefile, strerror(errno));
438 		return;
439 	}
440 
441 	fprintf(out, "%s\n", XFRD_FILE_MAGIC);
442 	fprintf(out, "# This file is written on exit by nsd xfr daemon.\n");
443 	fprintf(out, "# This file contains slave zone information:\n");
444 	fprintf(out, "# 	* timeouts (when was zone data acquired)\n");
445 	fprintf(out, "# 	* state (OK, refreshing, expired)\n");
446 	fprintf(out, "# 	* which master transfer to attempt next\n");
447 	fprintf(out, "# The file is read on start (but not on reload) by nsd xfr daemon.\n");
448 	fprintf(out, "# You can edit; but do not change statement order\n");
449 	fprintf(out, "# and no fancy stuff (like quoted \"strings\").\n");
450 	fprintf(out, "#\n");
451 	fprintf(out, "# If you remove a zone entry, it will be refreshed.\n");
452 	fprintf(out, "# This can be useful for an expired zone; it revives\n");
453 	fprintf(out, "# the zone temporarily, from refresh-expiry time.\n");
454 	fprintf(out, "# If you delete the file all slave zones are updated.\n");
455 	fprintf(out, "#\n");
456 	fprintf(out, "# Note: if you edit this file while nsd is running,\n");
457 	fprintf(out, "#       it will be overwritten on exit by nsd.\n");
458 	fprintf(out, "\n");
459 	fprintf(out, "filetime: %lld\t# %s\n", (long long)now, ctime(&now));
460 	fprintf(out, "# The number of zone entries in this file\n");
461 	fprintf(out, "numzones: %d\n", (int)xfrd->zones->count);
462 	fprintf(out, "\n");
463 	for(p = rbtree_first(xfrd->zones); p && p!=RBTREE_NULL; p=rbtree_next(p))
464 	{
465 		xfrd_zone_t* zone = (xfrd_zone_t*)p;
466 		fprintf(out, "zone: \tname: %s\n", zone->apex_str);
467 		fprintf(out, "\tstate: %d", (int)zone->state);
468 		fprintf(out, " # %s", zone->state==xfrd_zone_ok?"OK":(
469 			zone->state==xfrd_zone_refreshing?"refreshing":"expired"));
470 		fprintf(out, "\n");
471 		fprintf(out, "\tmaster: %d\n", zone->master_num);
472 		fprintf(out, "\tnext_master: %d\n", zone->next_master);
473 		fprintf(out, "\tround_num: %d\n", zone->round_num);
474 		fprintf(out, "\tnext_timeout: %d",
475 			(zone->zone_handler_flags&EV_TIMEOUT)?(int)zone->timeout.tv_sec:0);
476 		if((zone->zone_handler_flags&EV_TIMEOUT)) {
477 			neato_timeout(out, "\t# =", zone->timeout.tv_sec);
478 		}
479 		fprintf(out, "\n");
480 		xfrd_write_state_soa(out, "soa_nsd", &zone->soa_nsd,
481 			zone->soa_nsd_acquired, zone->apex);
482 		xfrd_write_state_soa(out, "soa_disk", &zone->soa_disk,
483 			zone->soa_disk_acquired, zone->apex);
484 		xfrd_write_state_soa(out, "soa_notify", &zone->soa_notified,
485 			zone->soa_notified_acquired, zone->apex);
486 		fprintf(out, "\n");
487 	}
488 
489 	fprintf(out, "%s\n", XFRD_FILE_MAGIC);
490 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: written %d zones to state file",
491 		(int)xfrd->zones->count));
492 	fclose(out);
493 }
494 
495 /* return tempdirname */
496 static void
497 tempdirname(char* buf, size_t sz, struct nsd* nsd)
498 {
499 	snprintf(buf, sz, "%snsd-xfr-%d",
500 		nsd->options->xfrdir, (int)nsd->pid);
501 }
502 
503 void
504 xfrd_make_tempdir(struct nsd* nsd)
505 {
506 	char tnm[1024];
507 	tempdirname(tnm, sizeof(tnm), nsd);
508 	/* create parent directories if needed (0750 permissions) */
509 	if(!create_dirs(tnm)) {
510 		log_msg(LOG_ERR, "parentdirs of %s failed", tnm);
511 	}
512 	/* restrictive permissions here, because this may be in /tmp */
513 	if(mkdir(tnm, 0700)==-1) {
514 		if(errno != EEXIST) {
515 			log_msg(LOG_ERR, "mkdir %s failed: %s",
516 				tnm, strerror(errno));
517 		}
518 	}
519 }
520 
521 void
522 xfrd_del_tempdir(struct nsd* nsd)
523 {
524 	char tnm[1024];
525 	tempdirname(tnm, sizeof(tnm), nsd);
526 	/* ignore parent directories, they are likely /var/tmp, /tmp or
527 	 * /var/cache/nsd and do not have to be deleted */
528 	if(rmdir(tnm)==-1 && errno != ENOENT) {
529 		log_msg(LOG_WARNING, "rmdir %s failed: %s", tnm,
530 			strerror(errno));
531 	}
532 }
533 
534 /* return name of xfrfile in tempdir */
535 static void
536 tempxfrname(char* buf, size_t sz, struct nsd* nsd, uint64_t number)
537 {
538 	char tnm[1024];
539 	tempdirname(tnm, sizeof(tnm), nsd);
540 	snprintf(buf, sz, "%s/xfr.%lld", tnm, (long long)number);
541 }
542 
543 FILE*
544 xfrd_open_xfrfile(struct nsd* nsd, uint64_t number, char* mode)
545 {
546 	char fname[1024];
547 	FILE* xfr;
548 	tempxfrname(fname, sizeof(fname), nsd, number);
549 	xfr = fopen(fname, mode);
550 	if(!xfr && errno == ENOENT) {
551 		/* directory may not exist */
552 		xfrd_make_tempdir(nsd);
553 		xfr = fopen(fname, mode);
554 	}
555 	if(!xfr) {
556 		log_msg(LOG_ERR, "open %s for %s failed: %s", fname, mode,
557 			strerror(errno));
558 		return NULL;
559 	}
560 	return xfr;
561 }
562 
563 void
564 xfrd_unlink_xfrfile(struct nsd* nsd, uint64_t number)
565 {
566 	char fname[1024];
567 	tempxfrname(fname, sizeof(fname), nsd, number);
568 	if(unlink(fname) == -1) {
569 		log_msg(LOG_WARNING, "could not unlink %s: %s", fname,
570 			strerror(errno));
571 	}
572 }
573 
574 uint64_t
575 xfrd_get_xfrfile_size(struct nsd* nsd, uint64_t number )
576 {
577 	char fname[1024];
578 	struct stat tempxfr_stat;
579 	tempxfrname(fname, sizeof(fname), nsd, number);
580 	if( stat( fname, &tempxfr_stat ) < 0 ) {
581 	    log_msg(LOG_WARNING, "could not get file size %s: %s", fname,
582 		    strerror(errno));
583 	    return 0;
584 	}
585 	return (uint64_t)tempxfr_stat.st_size;
586 }
587