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