xref: /openbsd-src/usr.sbin/nsd/xfrd-disk.c (revision 50b7afb2c2c0993b0894d4e34bf857cb13ed9c80)
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 
151 	tempregion = region_create(xalloc, free);
152 	if(!tempregion)
153 		return;
154 
155 	in = fopen(statefile, "r");
156 	if(!in) {
157 		if(errno != ENOENT) {
158 			log_msg(LOG_ERR, "xfrd: Could not open file %s for reading: %s",
159 				statefile, strerror(errno));
160 		} else {
161 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: no file %s. refreshing all zones.",
162 				statefile));
163 		}
164 		region_destroy(tempregion);
165 		return;
166 	}
167 	if(!xfrd_read_check_str(in, XFRD_FILE_MAGIC) ||
168 	   !xfrd_read_check_str(in, "filetime:") ||
169 	   !xfrd_read_i32(in, &filetime) ||
170 	   (time_t)filetime > xfrd_time()+15 ||
171 	   !xfrd_read_check_str(in, "numzones:") ||
172 	   !xfrd_read_i32(in, &numzones))
173 	{
174 		log_msg(LOG_ERR, "xfrd: corrupt state file %s dated %d (now=%lld)",
175 			statefile, (int)filetime, (long long)xfrd_time());
176 		fclose(in);
177 		region_destroy(tempregion);
178 		return;
179 	}
180 
181 	for(i=0; i<numzones; i++) {
182 		char *p;
183 		xfrd_zone_t* zone;
184 		const dname_type* dname;
185 		uint32_t state, masnum, nextmas, round_num, timeout;
186 		xfrd_soa_t soa_nsd_read, soa_disk_read, soa_notified_read;
187 		time_t soa_nsd_acquired_read,
188 			soa_disk_acquired_read, soa_notified_acquired_read;
189 		xfrd_soa_t incoming_soa;
190 		time_t incoming_acquired;
191 
192 		memset(&soa_nsd_read, 0, sizeof(soa_nsd_read));
193 		memset(&soa_disk_read, 0, sizeof(soa_disk_read));
194 		memset(&soa_notified_read, 0, sizeof(soa_notified_read));
195 
196 		if(!xfrd_read_check_str(in, "zone:") ||
197 		   !xfrd_read_check_str(in, "name:")  ||
198 		   !(p=xfrd_read_token(in)) ||
199 		   !(dname = dname_parse(tempregion, p)) ||
200 		   !xfrd_read_check_str(in, "state:") ||
201 		   !xfrd_read_i32(in, &state) || (state>2) ||
202 		   !xfrd_read_check_str(in, "master:") ||
203 		   !xfrd_read_i32(in, &masnum) ||
204 		   !xfrd_read_check_str(in, "next_master:") ||
205 		   !xfrd_read_i32(in, &nextmas) ||
206 		   !xfrd_read_check_str(in, "round_num:") ||
207 		   !xfrd_read_i32(in, &round_num) ||
208 		   !xfrd_read_check_str(in, "next_timeout:") ||
209 		   !xfrd_read_i32(in, &timeout) ||
210 		   !xfrd_read_state_soa(in, "soa_nsd_acquired:", "soa_nsd:",
211 			&soa_nsd_read, &soa_nsd_acquired_read) ||
212 		   !xfrd_read_state_soa(in, "soa_disk_acquired:", "soa_disk:",
213 			&soa_disk_read, &soa_disk_acquired_read) ||
214 		   !xfrd_read_state_soa(in, "soa_notify_acquired:", "soa_notify:",
215 			&soa_notified_read, &soa_notified_acquired_read))
216 		{
217 			log_msg(LOG_ERR, "xfrd: corrupt state file %s dated %d (now=%lld)",
218 				statefile, (int)filetime, (long long)xfrd_time());
219 			fclose(in);
220 			region_destroy(tempregion);
221 			return;
222 		}
223 
224 		zone = (xfrd_zone_t*)rbtree_search(xfrd->zones, dname);
225 		if(!zone) {
226 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: state file has info for not configured zone %s", p));
227 			continue;
228 		}
229 
230 		if(soa_nsd_acquired_read>xfrd_time()+15 ||
231 			soa_disk_acquired_read>xfrd_time()+15 ||
232 			soa_notified_acquired_read>xfrd_time()+15)
233 		{
234 			log_msg(LOG_ERR, "xfrd: statefile %s contains"
235 				" times in the future for zone %s. Ignoring.",
236 				statefile, zone->apex_str);
237 			continue;
238 		}
239 		zone->state = state;
240 		zone->master_num = masnum;
241 		zone->next_master = nextmas;
242 		zone->round_num = round_num;
243 		zone->timeout.tv_sec = timeout;
244 		zone->timeout.tv_usec = 0;
245 
246 		/* read the zone OK, now set the master properly */
247 		zone->master = acl_find_num(zone->zone_options->pattern->
248 			request_xfr, zone->master_num);
249 		if(!zone->master) {
250 			DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: masters changed for zone %s",
251 				zone->apex_str));
252 			zone->master = zone->zone_options->pattern->request_xfr;
253 			zone->master_num = 0;
254 			zone->round_num = 0;
255 		}
256 
257 		/*
258 		 * There is no timeout,
259 		 * or there is a notification,
260 		 * or there is a soa && current time is past refresh point
261 		 */
262 		if(timeout == 0 || soa_notified_acquired_read != 0 ||
263 			(soa_disk_acquired_read != 0 &&
264 			(uint32_t)xfrd_time() - soa_disk_acquired_read
265 				> ntohl(soa_disk_read.refresh)))
266 		{
267 			zone->state = xfrd_zone_refreshing;
268 			xfrd_set_refresh_now(zone);
269 		}
270 
271 		/* There is a soa && current time is past expiry point */
272 		if(soa_disk_acquired_read!=0 &&
273 			(uint32_t)xfrd_time() - soa_disk_acquired_read
274 				> ntohl(soa_disk_read.expire))
275 		{
276 			zone->state = xfrd_zone_expired;
277 			xfrd_set_refresh_now(zone);
278 		}
279 
280 		/* handle as an incoming SOA. */
281 		incoming_soa = zone->soa_nsd;
282 		incoming_acquired = zone->soa_nsd_acquired;
283 		zone->soa_nsd = soa_nsd_read;
284 		zone->soa_disk = soa_disk_read;
285 		zone->soa_notified = soa_notified_read;
286 		zone->soa_nsd_acquired = soa_nsd_acquired_read;
287 		/* we had better use what we got from starting NSD, not
288 		 * what we store in this file, because the actual zone
289 		 * contents trumps the contents of this cache */
290 		/* zone->soa_disk_acquired = soa_disk_acquired_read; */
291 		zone->soa_notified_acquired = soa_notified_acquired_read;
292 		xfrd_handle_incoming_soa(zone, &incoming_soa, incoming_acquired);
293 	}
294 
295 	if(!xfrd_read_check_str(in, XFRD_FILE_MAGIC)) {
296 		log_msg(LOG_ERR, "xfrd: corrupt state file %s dated %d (now=%lld)",
297 			statefile, (int)filetime, (long long)xfrd_time());
298 		region_destroy(tempregion);
299 		fclose(in);
300 		return;
301 	}
302 
303 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: read %d zones from state file", (int)numzones));
304 	fclose(in);
305 	region_destroy(tempregion);
306 }
307 
308 /* prints neato days hours and minutes. */
309 static void
310 neato_timeout(FILE* out, const char* str, time_t secs)
311 {
312 	fprintf(out, "%s", str);
313 	if(secs <= 0) {
314 		fprintf(out, " %llds", (long long)secs);
315 		return;
316 	}
317 	if(secs >= 3600*24) {
318 		fprintf(out, " %lldd", (long long)(secs/(3600*24)));
319 		secs = secs % (3600*24);
320 	}
321 	if(secs >= 3600) {
322 		fprintf(out, " %lldh", (long long)(secs/3600));
323 		secs = secs%3600;
324 	}
325 	if(secs >= 60) {
326 		fprintf(out, " %lldm", (long long)(secs/60));
327 		secs = secs%60;
328 	}
329 	if(secs > 0) {
330 		fprintf(out, " %llds", (long long)secs);
331 	}
332 }
333 
334 static void xfrd_write_dname(FILE* out, uint8_t* dname)
335 {
336 	uint8_t* d= dname+1;
337 	uint8_t len = *d++;
338 	uint8_t i;
339 
340 	if(dname[0]<=1) {
341 		fprintf(out, ".");
342 		return;
343 	}
344 
345 	while(len)
346 	{
347 		assert(d - (dname+1) <= dname[0]);
348 		for(i=0; i<len; i++)
349 		{
350 			uint8_t ch = *d++;
351 			if (isalnum(ch) || ch == '-' || ch == '_') {
352 				fprintf(out, "%c", ch);
353 			} else if (ch == '.' || ch == '\\') {
354 				fprintf(out, "\\%c", ch);
355 			} else {
356 				fprintf(out, "\\%03u", (unsigned int)ch);
357 			}
358 		}
359 		fprintf(out, ".");
360 		len = *d++;
361 	}
362 }
363 
364 static void
365 xfrd_write_state_soa(FILE* out, const char* id,
366 	xfrd_soa_t* soa, time_t soatime, const dname_type* ATTR_UNUSED(apex))
367 {
368 	fprintf(out, "\t%s_acquired: %d", id, (int)soatime);
369 	if(!soatime) {
370 		fprintf(out, "\n");
371 		return;
372 	}
373 	neato_timeout(out, "\t# was", xfrd_time()-soatime);
374 	fprintf(out, " ago\n");
375 
376 	fprintf(out, "\t%s: %u %u %u %u", id,
377 		(unsigned)ntohs(soa->type), (unsigned)ntohs(soa->klass),
378 		(unsigned)ntohl(soa->ttl), (unsigned)ntohs(soa->rdata_count));
379 	fprintf(out, " ");
380 	xfrd_write_dname(out, soa->prim_ns);
381 	fprintf(out, " ");
382 	xfrd_write_dname(out, soa->email);
383 	fprintf(out, " %u", (unsigned)ntohl(soa->serial));
384 	fprintf(out, " %u", (unsigned)ntohl(soa->refresh));
385 	fprintf(out, " %u", (unsigned)ntohl(soa->retry));
386 	fprintf(out, " %u", (unsigned)ntohl(soa->expire));
387 	fprintf(out, " %u\n", (unsigned)ntohl(soa->minimum));
388 	fprintf(out, "\t#");
389 	neato_timeout(out, " refresh =", ntohl(soa->refresh));
390 	neato_timeout(out, " retry =", ntohl(soa->retry));
391 	neato_timeout(out, " expire =", ntohl(soa->expire));
392 	neato_timeout(out, " minimum =", ntohl(soa->minimum));
393 	fprintf(out, "\n");
394 }
395 
396 void
397 xfrd_write_state(struct xfrd_state* xfrd)
398 {
399 	rbnode_t* p;
400 	const char* statefile = xfrd->nsd->options->xfrdfile;
401 	FILE *out;
402 	time_t now = xfrd_time();
403 
404 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: write file %s", statefile));
405 	out = fopen(statefile, "w");
406 	if(!out) {
407 		log_msg(LOG_ERR, "xfrd: Could not open file %s for writing: %s",
408 				statefile, strerror(errno));
409 		return;
410 	}
411 
412 	fprintf(out, "%s\n", XFRD_FILE_MAGIC);
413 	fprintf(out, "# This file is written on exit by nsd xfr daemon.\n");
414 	fprintf(out, "# This file contains slave zone information:\n");
415 	fprintf(out, "# 	* timeouts (when was zone data acquired)\n");
416 	fprintf(out, "# 	* state (OK, refreshing, expired)\n");
417 	fprintf(out, "# 	* which master transfer to attempt next\n");
418 	fprintf(out, "# The file is read on start (but not on reload) by nsd xfr daemon.\n");
419 	fprintf(out, "# You can edit; but do not change statement order\n");
420 	fprintf(out, "# and no fancy stuff (like quoted \"strings\").\n");
421 	fprintf(out, "#\n");
422 	fprintf(out, "# If you remove a zone entry, it will be refreshed.\n");
423 	fprintf(out, "# This can be useful for an expired zone; it revives\n");
424 	fprintf(out, "# the zone temporarily, from refresh-expiry time.\n");
425 	fprintf(out, "# If you delete the file all slave zones are updated.\n");
426 	fprintf(out, "#\n");
427 	fprintf(out, "# Note: if you edit this file while nsd is running,\n");
428 	fprintf(out, "#       it will be overwritten on exit by nsd.\n");
429 	fprintf(out, "\n");
430 	fprintf(out, "filetime: %lld\t# %s\n", (long long)now, ctime(&now));
431 	fprintf(out, "# The number of zone entries in this file\n");
432 	fprintf(out, "numzones: %d\n", (int)xfrd->zones->count);
433 	fprintf(out, "\n");
434 	for(p = rbtree_first(xfrd->zones); p && p!=RBTREE_NULL; p=rbtree_next(p))
435 	{
436 		xfrd_zone_t* zone = (xfrd_zone_t*)p;
437 		fprintf(out, "zone: \tname: %s\n", zone->apex_str);
438 		fprintf(out, "\tstate: %d", (int)zone->state);
439 		fprintf(out, " # %s", zone->state==xfrd_zone_ok?"OK":(
440 			zone->state==xfrd_zone_refreshing?"refreshing":"expired"));
441 		fprintf(out, "\n");
442 		fprintf(out, "\tmaster: %d\n", zone->master_num);
443 		fprintf(out, "\tnext_master: %d\n", zone->next_master);
444 		fprintf(out, "\tround_num: %d\n", zone->round_num);
445 		fprintf(out, "\tnext_timeout: %d",
446 			(zone->zone_handler_flags&EV_TIMEOUT)?(int)zone->timeout.tv_sec:0);
447 		if((zone->zone_handler_flags&EV_TIMEOUT)) {
448 			neato_timeout(out, "\t# =", zone->timeout.tv_sec);
449 		}
450 		fprintf(out, "\n");
451 		xfrd_write_state_soa(out, "soa_nsd", &zone->soa_nsd,
452 			zone->soa_nsd_acquired, zone->apex);
453 		xfrd_write_state_soa(out, "soa_disk", &zone->soa_disk,
454 			zone->soa_disk_acquired, zone->apex);
455 		xfrd_write_state_soa(out, "soa_notify", &zone->soa_notified,
456 			zone->soa_notified_acquired, zone->apex);
457 		fprintf(out, "\n");
458 	}
459 
460 	fprintf(out, "%s\n", XFRD_FILE_MAGIC);
461 	DEBUG(DEBUG_XFRD,1, (LOG_INFO, "xfrd: written %d zones to state file",
462 		(int)xfrd->zones->count));
463 	fclose(out);
464 }
465 
466 /* return tempdirname */
467 static void
468 tempdirname(char* buf, size_t sz, struct nsd* nsd)
469 {
470 	snprintf(buf, sz, "%snsd-xfr-%d",
471 		nsd->options->xfrdir, (int)nsd->pid);
472 }
473 
474 void
475 xfrd_make_tempdir(struct nsd* nsd)
476 {
477 	char tnm[1024];
478 	tempdirname(tnm, sizeof(tnm), nsd);
479 	/* create parent directories if needed (0750 permissions) */
480 	if(!create_dirs(tnm)) {
481 		log_msg(LOG_ERR, "parentdirs of %s failed", tnm);
482 	}
483 	/* restrictive permissions here, because this may be in /tmp */
484 	if(mkdir(tnm, 0700)==-1) {
485 		if(errno != EEXIST) {
486 			log_msg(LOG_ERR, "mkdir %s failed: %s",
487 				tnm, strerror(errno));
488 		}
489 	}
490 }
491 
492 void
493 xfrd_del_tempdir(struct nsd* nsd)
494 {
495 	char tnm[1024];
496 	tempdirname(tnm, sizeof(tnm), nsd);
497 	/* ignore parent directories, they are likely /var/tmp, /tmp or
498 	 * /var/cache/nsd and do not have to be deleted */
499 	if(rmdir(tnm)==-1 && errno != ENOENT) {
500 		log_msg(LOG_WARNING, "rmdir %s failed: %s", tnm,
501 			strerror(errno));
502 	}
503 }
504 
505 /* return name of xfrfile in tempdir */
506 static void
507 tempxfrname(char* buf, size_t sz, struct nsd* nsd, uint64_t number)
508 {
509 	char tnm[1024];
510 	tempdirname(tnm, sizeof(tnm), nsd);
511 	snprintf(buf, sz, "%s/xfr.%lld", tnm, (long long)number);
512 }
513 
514 FILE*
515 xfrd_open_xfrfile(struct nsd* nsd, uint64_t number, char* mode)
516 {
517 	char fname[1024];
518 	FILE* xfr;
519 	tempxfrname(fname, sizeof(fname), nsd, number);
520 	xfr = fopen(fname, mode);
521 	if(!xfr && errno == ENOENT) {
522 		/* directory may not exist */
523 		xfrd_make_tempdir(nsd);
524 		xfr = fopen(fname, mode);
525 	}
526 	if(!xfr) {
527 		log_msg(LOG_ERR, "open %s for %s failed: %s", fname, mode,
528 			strerror(errno));
529 		return NULL;
530 	}
531 	return xfr;
532 }
533 
534 void
535 xfrd_unlink_xfrfile(struct nsd* nsd, uint64_t number)
536 {
537 	char fname[1024];
538 	tempxfrname(fname, sizeof(fname), nsd, number);
539 	if(unlink(fname) == -1) {
540 		log_msg(LOG_WARNING, "could not unlink %s: %s", fname,
541 			strerror(errno));
542 	}
543 }
544