dlz_mysqldyn_mod.c 38.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
 * Copyright (C) 2014 Maui Systems Ltd, Scotland, contact@maui-systems.co.uk.
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the
 * above copyright notice and this permission notice appear in all
 * copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND MAUI SYSTEMS LTD DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL MAUI SYSTEMS LTD  BE
 * LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR
 * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 * SOFTWARE.
 */

/*
 * Copyright (C) 2011,2014  Internet Systems Consortium, Inc. ("ISC")
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * BIND 9 DLZ MySQL module with support for dynamic DNS (DDNS)
 *
 * Adapted from code contributed by Marty Lee, Maui Systems Ltd.
 *
 * See README for database schema and usage details.
 */

43
#include <stdbool.h>
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <inttypes.h>
#include <pthread.h>
#include <netdb.h>
#include <ifaddrs.h>

#include <mysql/mysql.h>
#include <mysql/errmsg.h>

#include <dlz_minimal.h>
#include <dlz_list.h>
#include <dlz_pthread.h>

/*
 * The SQL queries that will be used for lookups and updates are defined
 * here.  They will be processed into queries by the build_query()
 * function.
 *
 * NOTE: Despite appearances, these do NOT use printf-style formatting.
 * "%s", with no modifiers, is the only supported directive.
 */

/*
 * Get the NS RRset for a zone
 * Arguments: zone-name
 */
#define Q_GETNS \
	"SELECT d.data FROM ZoneData d, Zones z " \
	"WHERE UPPER(d.type) = 'NS' AND LOWER(z.domain) = LOWER('%s') " \
	"AND z.id = d.zone_id"

/*
 * Get a list of zones (ignoring writable or not)
 * Arguments: (none)
 */
#define Q_GETZONES "SELECT LOWER(domain), serial FROM Zones"

/*
 * Find a specific zone
 * Arguments: zone-name
 */
#define Q_FINDZONE \
	"SELECT id FROM Zones WHERE LOWER(domain) = LOWER('%s')"

/*
 * Get SOA data from zone apex
 * Arguments: zone-name
 */
#define Q_GETSOA \
	"SELECT host, admin, serial, refresh, retry, expire, minimum, ttl " \
	"FROM Zones WHERE LOWER(domain) = LOWER('%s')"

/*
 * Get other data from zone apex
 * Arguments: zone-name, zone-name (repeated)
 */
#define Q_GETAPEX \
	"SELECT d.type, d.data, d.ttl FROM ZoneData d, Zones z " \
	"WHERE LOWER(z.domain) = LOWER('%s') AND z.id = d.zone_id " \
	"AND LOWER(d.name) IN (LOWER('%s'), '', '@') "\
	"ORDER BY UPPER(d.type) ASC"

/*
 * Get data from non-apex nodes
 * Arguments: zone-name, node-name (relative to zone name)
 */
#define Q_GETNODE \
	"SELECT d.type, d.data, d.ttl FROM ZoneData d, Zones z " \
	"WHERE LOWER(z.domain) = LOWER('%s') AND z.id = d.zone_id " \
	"AND LOWER(d.name) = LOWER('%s') " \
	"ORDER BY UPPER(d.type) ASC"

/*
 * Get all data from a zone, for AXFR
 * Arguments: zone-name
 */
#define Q_GETALL \
	"SELECT d.name, d.type, d.data, d.ttl FROM ZoneData d, Zones z " \
	"WHERE LOWER(z.domain) = LOWER('%s') AND z.id = d.zone_id"

/*
 * Get SOA serial number for a zone.
 * Arguments: zone-name
 */
#define Q_GETSERIAL \
	"SELECT serial FROM Zones WHERE domain = '%s'"

/*
 * Determine whether a zone is writeable, and if so, retrieve zone_id
 * Arguments: zone-name
 */
#define Q_WRITEABLE \
	"SELECT id FROM Zones WHERE " \
	"LOWER(domain) = LOWER('%s') AND writeable = 1"

/*
 * Insert data into zone (other than SOA)
 * Arguments: zone-id (from Q_WRITEABLE), node-name (relative to zone-name),
 * 	      rrtype, rdata text, TTL (in text format)
 */
#define I_DATA \
	"INSERT INTO ZoneData (zone_id, name, type, data, ttl) " \
	"VALUES (%s, LOWER('%s'), UPPER('%s'), '%s', %s)"

/*
 * Update SOA serial number for a zone
 * Arguments: new serial number (in text format), zone-id (from Q_WRITEABLE)
 */
#define U_SERIAL \
	"UPDATE Zones SET serial = %s WHERE id = %s"

/*
 * Delete a specific record (non-SOA) from a zone
 *
 * Arguments: node-name (relative to zone-name), zone-id (from Q_WRITEABLE),
 * 	      rrtype, rdata text, TTL (in text format).
 */
#define D_RECORD \
	"DELETE FROM ZoneData WHERE zone_id = %s AND " \
	"LOWER(name) = LOWER('%s') AND UPPER(type) = UPPER('%s') AND " \
	"data = '%s' AND ttl = %s"

/*
 * Delete an entire rrset from a zone
 * Arguments: node-name (relative to zone-name), zone-id (from Q_WRITEABLE),
 * 	      rrtype.
 */
#define D_RRSET \
	"DELETE FROM ZoneData WHERE zone_id = %s AND " \
	"LOWER(name) = LOWER('%s') AND UPPER(type) = UPPER('%s')"

/*
 * Number of concurrent database connections we support
 * - equivalent to maxmium number of concurrent transactions
 *   that can be 'in-flight' + 1
 */
#define MAX_DBI 16

typedef struct mysql_record {
	char zone[255];
	char name[100];
	char type[10];
	char data[200];
	char ttl[10];
} mysql_record_t;

typedef struct mysql_instance {
	int id;
	MYSQL *sock;
	int connected;
	dlz_mutex_t mutex;
} mysql_instance_t;

typedef struct mysql_transaction mysql_transaction_t;
struct mysql_transaction {
	char *zone;
	char *zone_id;
	mysql_instance_t *dbi;
	mysql_transaction_t *next;
};

typedef struct mysql_data {
	int debug;

	/*
	 * Database connection details
	 */
	char *db_name;
	char *db_host;
	char *db_user;
	char *db_pass;

	/*
	 * Database structures
	 */
	mysql_instance_t db[MAX_DBI];

	/*
	 * Transactions
	 */
	mysql_transaction_t *transactions;

	/*
	 * Mutex for transactions
	 */
	dlz_mutex_t tx_mutex;

	/* Helper functions from the dlz_dlopen driver */
	log_t *log;
	dns_sdlz_putrr_t *putrr;
	dns_sdlz_putnamedrr_t *putnamedrr;
	dns_dlz_writeablezone_t *writeable_zone;
} mysql_data_t;

typedef struct mysql_arg mysql_arg_t;
typedef DLZ_LIST(mysql_arg_t) mysql_arglist_t;
struct mysql_arg {
	char *arg;
	DLZ_LINK(mysql_arg_t) link;
};

static const char *modname = "dlz_mysqldyn";

/*
 * Local functions
 */
257
static bool
258
259
260
261
262
263
264
265
db_connect(mysql_data_t *state, mysql_instance_t *dbi) {
	MYSQL *conn;
	/*
	 * Make sure this thread has been through 'init'
	 */
	mysql_thread_init();

	if (dbi->connected)
266
		return (true);
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282

	if (state->log != NULL)
		state->log(ISC_LOG_INFO, "%s: init connection %d ",
			   modname, dbi->id);

	conn = mysql_real_connect(dbi->sock, state->db_host,
				  state->db_user, state->db_pass,
				  state->db_name, 0, NULL,
				  CLIENT_REMEMBER_OPTIONS);
	if (conn == NULL) {
		if (state->log != NULL)
			state->log(ISC_LOG_ERROR,
				   "%s: database connection failed: %s",
				   modname, mysql_error(dbi->sock));

		dlz_mutex_unlock(&dbi->mutex);
283
		return (false);
284
285
286
	}

	dbi->connected = 1;
287
	return (true);
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
}

static mysql_instance_t *
get_dbi(mysql_data_t *state) {
	int i;

	/*
	 * Find an available dbi
	 */
	for (i = 0; i < MAX_DBI; i++) {
		if (dlz_mutex_trylock(&state->db[i].mutex) == 0)
			break;
	}

	if (i == MAX_DBI) {
		if (state->debug && state->log != NULL)
			state->log(ISC_LOG_ERROR,
				   "%s: No available connections", modname);
		return (NULL);
	}
	return (&state->db[i]);
}

/*
 * Allocate memory and store an escaped, sanitized version
 * of string 'original'
 */
static char *
sanitize(mysql_instance_t *dbi, const char *original) {
	char *s;

	if (original == NULL)
		return (NULL);

	s = (char *) malloc((strlen(original) * 2) + 1);
	if (s != NULL) {
		memset(s, 0, (strlen(original) * 2) + 1);

		mysql_real_escape_string(dbi->sock, s, original,
					 strlen(original));
	}

	return (s);
}

/*
 * Append the string pointed to by 's' to the argument list 'arglist',
 * and add the string length to the running total pointed to by 'len'.
 */
static isc_result_t
338
additem(mysql_arglist_t *arglist, char **s, size_t *len) {
339
340
341
342
343
344
345
	mysql_arg_t *item;

	item = malloc(sizeof(*item));
	if (item == NULL)
		return (ISC_R_NOMEMORY);

	DLZ_LINK_INIT(item, link);
346
	item->arg = *s;
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
	*len += strlen(*s);
	DLZ_LIST_APPEND(*arglist, item, link);
	*s = NULL;

	return (ISC_R_SUCCESS);
}

/*
 * Construct a query string using a variable number of arguments, and
 * save it into newly allocated memory.
 *
 * NOTE: 'command' resembles a printf-style format string, but ONLY
 * supports the "%s" directive with no modifiers of any kind.
 *
 * If 'dbi' is NULL, we attempt to get a temporary database connection;
 * otherwise we use the existing one.
 */
static char *
build_query(mysql_data_t *state, mysql_instance_t *dbi,
	    const char *command, ...)
{
	isc_result_t result;
369
	bool localdbi = false;
370
371
	mysql_arglist_t arglist;
	mysql_arg_t *item;
372
	char *p, *q, *tmp = NULL, *querystr = NULL;
373
374
375
376
377
378
379
380
381
	char *query = NULL;
	size_t len = 0;
	va_list ap1;

	/* Get a DB instance if needed */
	if (dbi == NULL) {
		dbi = get_dbi(state);
		if (dbi == NULL)
			return (NULL);
382
		localdbi = true;
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
	}

	/* Make sure this instance is connected */
	if (!db_connect(state, dbi))
		goto fail;

	va_start(ap1, command);
	DLZ_LIST_INIT(arglist);
	q = querystr = strdup(command);
	if (querystr == NULL)
		goto fail;

	for (;;) {
		if (*q == '\0')
			break;

		p = strstr(q, "%s");
		if (p != NULL) {
			*p = '\0';
			tmp = strdup(q);
			if (tmp == NULL)
				goto fail;

406
			result = additem(&arglist, &tmp, &len);
407
408
409
410
411
412
413
			if (result != ISC_R_SUCCESS)
				goto fail;

			tmp = sanitize(dbi, va_arg(ap1, const char *));
			if (tmp == NULL)
				goto fail;

414
			result = additem(&arglist, &tmp, &len);
415
416
417
418
419
420
421
422
423
			if (result != ISC_R_SUCCESS)
				goto fail;

			q = p + 2;
		} else {
			tmp = strdup(q);
			if (tmp == NULL)
				goto fail;

424
			result = additem(&arglist, &tmp, &len);
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
			if (result != ISC_R_SUCCESS)
				goto fail;

			break;
		}
	}

	if (len == 0)
		goto fail;

	query = malloc(len + 1);
	if (query == NULL)
		goto fail;

	*query = '\0';
	for (item = DLZ_LIST_HEAD(arglist);
	     item != NULL;
	     item = DLZ_LIST_NEXT(item, link))
		if (item->arg != NULL)
			strcat(query, item->arg);

 fail:
	va_end(ap1);

	for (item = DLZ_LIST_HEAD(arglist);
	     item != NULL;
	     item = DLZ_LIST_NEXT(item, link))
	{
		if (item->arg != NULL)
			free(item->arg);
		free(item);
	}

	if (tmp != NULL)
		free(tmp);
	if (querystr != NULL)
		free (querystr);

	if (dbi != NULL && localdbi)
		dlz_mutex_unlock(&dbi->mutex);

	return (query);
}

/* Does this name end in a dot? */
470
static bool
471
472
isrelative(const char *s) {
	if (s == NULL || s[strlen(s) - 1] == '.')
473
474
		return (false);
	return (true);
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
}

/* Return a dot if 's' doesn't already end with one */
static inline const char *
dot(const char *s) {
	return (isrelative(s) ? "." : "");
}

/*
 * Generate a full hostname from a (presumably relative) name 'name'
 * and a zone name 'zone'; store the result in 'dest' (which must have
 * enough space).
 */
static void
fqhn(const char *name, const char *zone, char *dest) {
	if (dest == NULL)
		return;

	if (strlen(name) == 0 || strcmp(name, "@") == 0)
		sprintf(dest, "%s%s", zone, dot(zone));
	else {
		if (isrelative(name))
			sprintf(dest, "%s.%s%s", name, zone, dot(zone));
		else
			strcpy(dest, name);
	}
}

/*
 * Names are stored in relative form in ZoneData; this function
 * removes labels matching 'zone' from the end of 'name'.
 */
static char *
relname(const char *name, const char *zone) {
	size_t nlen, zlen;
	const char *p;
	char *new;

	new = (char *) malloc(strlen(name) + 1);
	if (new == NULL)
		return (NULL);

	nlen = strlen(name);
	zlen = strlen(zone);

	if (nlen < zlen) {
		strcpy(new, name);
		return (new);
	} else if (nlen == zlen || strcasecmp(name, zone) == 0) {
		strcpy(new, "@");
		return (new);
	}

	p = name + nlen - zlen;
	if (strcasecmp(p, zone) != 0 &&
	    (zone[zlen - 1] != '.' ||
	     strncasecmp(p, zone, zlen - 1) != 0))
	{
		strcpy(new, name);
		return (new);
	}

	strncpy(new, name, nlen - zlen);
	new[nlen - zlen - 1] = '\0';
	return (new);
}

static isc_result_t
validate_txn(mysql_data_t *state, mysql_transaction_t *txn) {
	isc_result_t result = ISC_R_FAILURE;
	mysql_transaction_t *txp;

	dlz_mutex_lock(&state->tx_mutex);
	for (txp = state->transactions; txp != NULL; txp = txp->next) {
		if (txn == txp) {
			result = ISC_R_SUCCESS;
			break;
		}
	}
	dlz_mutex_unlock(&state->tx_mutex);

	if (result != ISC_R_SUCCESS && state->log != NULL)
		state->log(ISC_LOG_ERROR, "%s: invalid txn %x", modname, txn);

	return (result);
}

static isc_result_t
563
db_execute(mysql_data_t *state, mysql_instance_t *dbi, const char *query) {
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
	int ret;

	/* Make sure this instance is connected.  */
	if (!db_connect(state, dbi))
		return (ISC_R_FAILURE);

	ret = mysql_real_query(dbi->sock, query, strlen(query));
	if (ret != 0) {
		if (state->debug && state->log != NULL)
			state->log(ISC_LOG_ERROR,
				   "%s: query '%s' failed: %s",
				   modname, query, mysql_error(dbi->sock));
		return (ISC_R_FAILURE);
	}

	if (state->debug && state->log != NULL)
		state->log(ISC_LOG_INFO, "%s: execute(%d) %s",
			   modname, dbi->id, query);

	return (ISC_R_SUCCESS);
}

static MYSQL_RES *
587
db_query(mysql_data_t *state, mysql_instance_t *dbi, const char *query) {
588
	isc_result_t result;
589
	bool localdbi = false;
590
591
592
593
594
595
596
597
598
599
	MYSQL_RES *res = NULL;

	if (query == NULL)
		return (NULL);

	/* Get a DB instance if needed */
	if (dbi == NULL) {
		dbi = get_dbi(state);
		if (dbi == NULL)
			return (NULL);
600
		localdbi = true;
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
650
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
	}

	/* Make sure this instance is connected */
	if (!db_connect(state, dbi))
		goto fail;

	result = db_execute(state, dbi, query);
	if (result != ISC_R_SUCCESS)
		goto fail;

	res = mysql_store_result(dbi->sock);
	if (res == NULL) {
		if (state->log != NULL)
			state->log(ISC_LOG_ERROR,
				   "%s: unable to store result: %s",
				   modname, mysql_error(dbi->sock));
		goto fail;
	}

	if (state->debug && state->log != NULL)
		state->log(ISC_LOG_INFO,
			   "%s: query(%d) returned %d rows",
			   modname, dbi->id, mysql_num_rows(res));

 fail:
	if (dbi != NULL && localdbi)
		dlz_mutex_unlock(&dbi->mutex);
	return (res);
}

/*
 * Generate a DNS NOTIFY packet:
 * 12 bytes header
 * Question (1)
 * 	strlen(zone) +2
 *  2 bytes qtype
 *  2 bytes qclass
 *
 * -> 18 bytes + strlen(zone)
 *
 * N.B. Need to be mindful of byte ordering; using htons to map 16bit
 * values to the 'on the wire' packet values.
 */
static unsigned char *
make_notify(const char *zone, int *packetlen) {
	int i, j;
	unsigned char *packet = (unsigned char *) malloc(strlen(zone) + 18);

	if (packet == NULL)
		return (NULL);

	*packetlen = strlen(zone) + 18;
	memset(packet, 0, *packetlen);

	/* Random query ID */
	i = rand();
	packet[0] = htons(i) & 0xff;
	packet[1] = htons(i) >> 8;

	/* Flags (OpCode '4' in bits 14-11), Auth Answer set in bit 10 */
	i = 0x2400;
	packet[2] = htons(i) & 0xff;
	packet[3] = htons(i) >> 8;

	/* QD Count */
	i = 0x1;
	packet[4] = htons(i) & 0xff;
	packet[5] = htons(i) >> 8;

	/* Question */
	packet[12] = '.';
	memcpy(&packet[13], zone, strlen(zone));
	packet[13 + strlen(zone)] = 0;

	/* Make the question into labels */
	j = 12;
	while (packet[j]) {
		for (i = j + 1; packet[i] != '\0' && packet[i] != '.'; i++);
		packet[j] = i - j - 1;
		j = i;
	}

	/* Question type */
	i = 6;
	packet[j + 1] = htons(i) & 0xff;
	packet[j + 2] = htons(i) >> 8;

	/* Queston class */
	i = 1;
	packet[j + 3] = htons(i) & 0xff;
	packet[j + 4] = htons(i) >> 8;

	return (packet);
}

static void
send_notify(struct sockaddr_in *addr, const unsigned char *p, const int plen) {
	int s;

	addr->sin_family = AF_INET;
	addr->sin_port = htons(53);

	if ((s = socket(PF_INET, SOCK_DGRAM, 0)) < 0)
		return;

	sendto(s, p, plen, 0, (struct sockaddr *)addr, sizeof(*addr));
	close(s);
	return;
}

/*
 * Generate and send a DNS NOTIFY packet
 */
static void
notify(mysql_data_t *state, const char *zone, int sn) {
	MYSQL_RES *res;
	MYSQL_ROW row;
	char *query;
	unsigned char *packet;
	int packetlen;
	struct ifaddrs *ifap, *ifa;
	char zaddr[INET_ADDRSTRLEN];
	void *addrp = NULL;

	/* Get the name servers from the NS rrset */
	query = build_query(state, NULL, Q_GETNS, zone);
	res = db_query(state, NULL, query);
	free (query);
	if (res == NULL)
		return;

	/* Create a DNS NOTIFY packet */
	packet = make_notify(zone, &packetlen);
	if (packet == NULL) {
		mysql_free_result(res);
		return;
	}

	/* Get a list of our own addresses */
	if (getifaddrs(&ifap) < 0)
		ifap = NULL;

	/* Tell each nameserver of the update */
	while ((row = mysql_fetch_row(res)) != NULL) {
745
		bool local = false;
746
747
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
		struct hostent *h;
		struct sockaddr_in addr, *sin;

		/*
		 * Put nameserver rdata through gethostbyname as it
		 * might be an IP address or a hostname. (XXX: switch
		 * this to inet_pton/getaddrinfo.)
		 */
		h = gethostbyname(row[0]);
		if (h == NULL)
			continue;

		memcpy(&addr.sin_addr, h->h_addr, h->h_length);
		addrp = &addr.sin_addr;

		/* Get the address for the nameserver into a string */
		inet_ntop(AF_INET, addrp, zaddr, INET_ADDRSTRLEN);
		for (ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
			char ifaddr[INET_ADDRSTRLEN];

			if (ifa->ifa_addr->sa_family != AF_INET)
				continue;

			/* Get local address into a string */
			sin = (struct sockaddr_in *) ifa->ifa_addr;
			addrp = &sin->sin_addr;
			inet_ntop(AF_INET, addrp, ifaddr, INET_ADDRSTRLEN);

			/* See if nameserver address matches this one */
			if (strcmp(ifaddr, zaddr) == 0)
776
				local = true;
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
		}

		if (!local) {
			if (state->log != NULL)
				state->log(ISC_LOG_INFO,
					   "%s: notify %s zone %s serial %d",
					   modname, row[0], zone, sn);
			send_notify(&addr, packet, packetlen);
		}
	}

	mysql_free_result(res);
	free(packet);
	if (ifap != NULL)
		freeifaddrs(ifap);
}

/*
 * Constructs a mysql_record_t structure from 'rdatastr', to be
 * used in the dlz_{add,sub,del}rdataset functions below.
 */
static mysql_record_t *
makerecord(mysql_data_t *state, const char *name, const char *rdatastr) {
	mysql_record_t *new_record;
	char *real_name, *dclass, *type, *data, *ttlstr, *buf;
	dns_ttl_t ttlvalue;

	new_record = (mysql_record_t *)
		malloc(sizeof(mysql_record_t));

	if (new_record == NULL) {
		if (state->log != NULL)
			state->log(ISC_LOG_ERROR,
				   "%s: makerecord - unable to malloc",
				   modname);
		return (NULL);
	}

	buf = strdup(rdatastr);
	if (buf == NULL) {
		if (state->log != NULL)
			state->log(ISC_LOG_ERROR,
				   "%s: makerecord - unable to malloc",
				   modname);
		free(new_record);
		return (NULL);
	}

	/*
	 * The format is:
	 * FULLNAME\tTTL\tDCLASS\tTYPE\tDATA
	 *
	 * The DATA field is space separated, and is in the data format
	 * for the type used by dig
	 */
832
	real_name = strtok_r(buf, "\t", &saveptr);
833
834
835
	if (real_name == NULL)
		goto error;

836
	ttlstr = strtok_r(NULL, "\t", &saveptr);
837
838
839
	if (ttlstr == NULL || sscanf(ttlstr, "%d", &ttlvalue) != 1)
		goto error;

840
	dclass = strtok_r(NULL, "\t", &saveptr);
841
842
843
	if (dclass == NULL)
		goto error;

844
	type = strtok_r(NULL, "\t", &saveptr);
845
846
847
	if (type == NULL)
		goto error;

848
	data = strtok_r(NULL, "\t", &saveptr);
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
	if (data == NULL)
		goto error;

	strcpy(new_record->name, name);
	strcpy(new_record->type, type);
	strcpy(new_record->data, data);
	sprintf(new_record->ttl, "%d", ttlvalue);

	free(buf);
	return (new_record);

 error:
	free(buf);
	free(new_record);
	return (NULL);
}

/*
 * Remember a helper function from the bind9 dlz_dlopen driver
 */
static void
b9_add_helper(mysql_data_t *state, const char *helper_name, void *ptr) {
	if (strcmp(helper_name, "log") == 0)
		state->log = (log_t *)ptr;
	if (strcmp(helper_name, "putrr") == 0)
		state->putrr = (dns_sdlz_putrr_t *)ptr;
	if (strcmp(helper_name, "putnamedrr") == 0)
		state->putnamedrr = (dns_sdlz_putnamedrr_t *)ptr;
	if (strcmp(helper_name, "writeable_zone") == 0)
		state->writeable_zone = (dns_dlz_writeablezone_t *)ptr;
}

/*
 * DLZ API functions
 */

/*
 * Return the version of the API
 */
int
dlz_version(unsigned int *flags) {
	UNUSED(flags);
	*flags |= DNS_SDLZFLAG_THREADSAFE;
	return (DLZ_DLOPEN_VERSION);
}

/*
 * Called to initialize the driver
 */
isc_result_t
dlz_create(const char *dlzname, unsigned int argc, char *argv[],
	   void **dbdata, ...)
{
	mysql_data_t *state;
	const char *helper_name;
	va_list ap;
	int n;

	UNUSED(dlzname);

	state = calloc(1, sizeof(mysql_data_t));
	if (state == NULL)
		return (ISC_R_NOMEMORY);

913
914
915
	dlz_mutex_init(&state->tx_mutex, NULL);
	state->transactions = NULL;

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
	/* Fill in the helper functions */
	va_start(ap, dbdata);
	while ((helper_name = va_arg(ap, const char *)) != NULL)
		b9_add_helper(state, helper_name, va_arg(ap, void *));
	va_end(ap);

	if (state->log != NULL)
		state->log(ISC_LOG_INFO, "loading %s module", modname);

	if ((argc < 2) || (argc > 6)) {
		if (state->log != NULL)
			state->log(ISC_LOG_ERROR,
				   "%s: missing args <dbname> "
				   "[<dbhost> [<user> <pass>]]", modname);
		dlz_destroy(state);
		return (ISC_R_FAILURE);
	}

	state->db_name = strdup(argv[1]);
	if (argc > 2) {
		state->db_host = strdup(argv[2]);
		if (argc > 4) {
			state->db_user = strdup(argv[3]);
			state->db_pass = strdup(argv[4]);
		} else {
			state->db_user = strdup("bind");
			state->db_pass = strdup("");
		}
	} else {
		state->db_host = strdup("localhost");
		state->db_user = strdup("bind");
		state->db_pass = strdup("");
	}

	if (state->log != NULL)
		state->log(ISC_LOG_INFO,
			   "%s: DB=%s, Host=%s, User=%s",
			   modname, state->db_name,
			   state->db_host, state->db_user);

	/*
	 * Assign the 'state' to dbdata so we get it in our callbacks
	 */


	dlz_mutex_lock(&state->tx_mutex);

	/*
	 * Populate DB instances
	 */
	if (mysql_thread_safe()) {
		for (n = 0; n < MAX_DBI; n++) {
			my_bool opt = 1;
			dlz_mutex_init(&state->db[n].mutex, NULL);
			dlz_mutex_lock(&state->db[n].mutex);
			state->db[n].id = n;
			state->db[n].connected = 0;
			state->db[n].sock = mysql_init(NULL);
			mysql_options(state->db[n].sock,
				      MYSQL_READ_DEFAULT_GROUP,
				      modname);
			mysql_options(state->db[n].sock,
				      MYSQL_OPT_RECONNECT, &opt);
			dlz_mutex_unlock(&state->db[n].mutex);
		}

982
		*dbdata = state;
983
984
985
986
987
988
989
990
991
992
		dlz_mutex_unlock(&state->tx_mutex);
		return (ISC_R_SUCCESS);
	}

	free(state->db_name);
	free(state->db_host);
	free(state->db_user);
	free(state->db_pass);
	dlz_mutex_destroy(&state->tx_mutex);
	free(state);
993
	return (ISC_R_FAILURE);
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
}

/*
 * Shut down the backend
 */
void
dlz_destroy(void *dbdata) {
	mysql_data_t *state = (mysql_data_t *)dbdata;
	int i;

	if (state->debug && state->log != NULL)
		state->log(ISC_LOG_INFO, "%s: shutting down", modname);

	for (i = 0; i < MAX_DBI; i++) {
		if (state->db[i].sock) {
			mysql_close(state->db[i].sock);
			state->db[i].sock=NULL;
		}
	}
	free(state->db_name);
	free(state->db_host);
	free(state->db_user);
	free(state->db_pass);
	dlz_mutex_destroy(&state->tx_mutex);
	free(state);
}

/*
 * See if we handle a given zone
 */
isc_result_t
dlz_findzonedb(void *dbdata, const char *name,
	       dns_clientinfomethods_t *methods,
	       dns_clientinfo_t *clientinfo)
{
	isc_result_t result = ISC_R_SUCCESS;
	mysql_data_t *state = (mysql_data_t *)dbdata;
	MYSQL_RES *res;
	char *query;

	/* Query the Zones table to see if this zone is present */
	query = build_query(state, NULL, Q_FINDZONE, name);

	if (query == NULL)
		return (ISC_R_NOMEMORY);

	res = db_query(state, NULL, query);
	if (res == NULL)
		return (ISC_R_FAILURE);

	if (mysql_num_rows(res) == 0)
		result = ISC_R_NOTFOUND;

	mysql_free_result(res);
	return (result);
}

/*
 * Perform a database lookup
 */
isc_result_t
dlz_lookup(const char *zone, const char *name, void *dbdata,
	   dns_sdlzlookup_t *lookup, dns_clientinfomethods_t *methods,
	   dns_clientinfo_t *clientinfo)
{
	isc_result_t result;
	mysql_data_t *state = (mysql_data_t *)dbdata;
1061
	bool found = false;
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
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
	char *real_name;
	MYSQL_RES *res;
	MYSQL_ROW row;
	char *query;
	mysql_transaction_t *txn = NULL;
	mysql_instance_t *dbi = NULL;

	if (state->putrr == NULL) {
		if (state->log != NULL)
			state->log(ISC_LOG_ERROR,
				   "%s: dlz_lookup - no putrr", modname);
		return (ISC_R_NOTIMPLEMENTED);
	}

	/* Are we okay to try to find the txn version?  */
	if (clientinfo != NULL &&
	    clientinfo->version >= DNS_CLIENTINFO_VERSION) {
		txn = (mysql_transaction_t *) clientinfo->dbversion;
		if (txn != NULL && validate_txn(state, txn) == ISC_R_SUCCESS)
			dbi = txn->dbi;
		if (dbi != NULL) {
			state->log(ISC_LOG_DEBUG(1),
				   "%s: lookup in live transaction %p, DBI %p",
				   modname, txn, dbi);
		}
	}

	if (strcmp(name, "@") == 0) {
		real_name = (char *) malloc(strlen(zone) + 1);
		if (real_name == NULL)
			return (ISC_R_NOMEMORY);
		strcpy(real_name, zone);
	} else {
		real_name = (char *) malloc(strlen(name) + 1);
		if (real_name == NULL)
			return (ISC_R_NOMEMORY);
		strcpy(real_name, name);
	}

	if (strcmp(real_name, zone) == 0) {
		/*
		 * Get the Zones table data for use in the SOA:
		 * zone admin serial refresh retry expire min
		 */
		query = build_query(state, dbi, Q_GETSOA, zone);
		if (query == NULL) {
			free(real_name);
			return (ISC_R_NOMEMORY);
		}

		res = db_query(state, dbi, query);
		free (query);

		if (res == NULL) {
			free(real_name);
			return (ISC_R_NOTFOUND);
		}

		while ((row = mysql_fetch_row(res)) != NULL) {
			char host[1024], admin[1024], data[1024];
			int ttl;

			sscanf(row[7], "%d", &ttl);
			fqhn(row[0], zone, host);
			fqhn(row[1], zone, admin);

			/* zone admin serial refresh retry expire min */
			sprintf(data, "%s%s %s%s %s %s %s %s %s",
				host, dot(host), admin, dot(admin),
				row[2], row[3], row[4], row[5], row[6]);

			result = state->putrr(lookup, "soa", ttl, data);
			if (result != ISC_R_SUCCESS) {
				free(real_name);
				mysql_free_result(res);
				return (result);
			}
		}

		mysql_free_result(res);

		/*
		 *  Now we'll get the rest of the apex data
		 */
		query = build_query(state, dbi, Q_GETAPEX, zone, real_name);
	} else
		query = build_query(state, dbi, Q_GETNODE, zone, real_name);

	res = db_query(state, dbi, query);
	free(query);

	if (res == NULL) {
		free(real_name);
		return (ISC_R_NOTFOUND);
	}

	while ((row = mysql_fetch_row(res)) != NULL) {
		int ttl;
		sscanf(row[2], "%d", &ttl);
		result = state->putrr(lookup, row[0], ttl, row[1]);
		if (result != ISC_R_SUCCESS) {
			free(real_name);
			mysql_free_result(res);
			return (result);
		}

1168
		found = true;
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
	}

	if (state->debug && state->log != NULL)
		state->log(ISC_LOG_INFO,
			   "%s: dlz_lookup %s/%s/%s - (%d rows)",
			   modname, name, real_name, zone,
			   mysql_num_rows(res));

	mysql_free_result(res);
	free(real_name);

	if (!found)
		return (ISC_R_NOTFOUND);

	return (ISC_R_SUCCESS);
}

/*
 * See if a zone transfer is allowed
 */
isc_result_t
dlz_allowzonexfr(void *dbdata, const char *name, const char *client) {
	mysql_data_t *state = (mysql_data_t *)dbdata;

	if (state->debug && state->log != NULL)
		state->log(ISC_LOG_INFO,
			   "dlz_allowzonexfr: %s %s", name, client);

	/* Just say yes for all our zones */
	return (dlz_findzonedb(dbdata, name, NULL, NULL));
}

/*
 * Perform a zone transfer
 */
isc_result_t
dlz_allnodes(const char *zone, void *dbdata, dns_sdlzallnodes_t *allnodes) {
	isc_result_t result = ISC_R_SUCCESS;
	mysql_data_t *state = (mysql_data_t *)dbdata;
	MYSQL_RES *res;
	MYSQL_ROW row;
	char *query;

	UNUSED(zone);

	if (state->debug && (state->log != NULL))
		state->log(ISC_LOG_INFO, "dlz_allnodes: %s", zone);

	if (state->putnamedrr == NULL)
		return (ISC_R_NOTIMPLEMENTED);

	/*
	 * Get all the ZoneData for this zone
	 */
	query = build_query(state, NULL, Q_GETALL, zone);
	if (query == NULL)
		return (ISC_R_NOMEMORY);

	res = db_query(state, NULL, query);
	free(query);
	if (res == NULL)
		return (ISC_R_NOTFOUND);

	while ((row = mysql_fetch_row(res)) != NULL) {
		char hostname[1024];
		int ttl;

		sscanf(row[3], "%d", &ttl);
		fqhn(row[0], zone, hostname);
		result = state->putnamedrr(allnodes, hostname,
					   row[1], ttl, row[2]);
		if (result != ISC_R_SUCCESS)
			break;
	}

	mysql_free_result(res);
	return (result);
}

/*
 * Start a transaction
 */
isc_result_t
dlz_newversion(const char *zone, void *dbdata, void **versionp) {
	isc_result_t result = ISC_R_FAILURE;
	mysql_data_t *state = (mysql_data_t *) dbdata;
	MYSQL_RES *res;
	MYSQL_ROW row;
	char *query;
	char zone_id[16];
	mysql_transaction_t *txn = NULL, *newtx = NULL;

	/*
	 * Check Zone is writable
	 */
	query = build_query(state, NULL, Q_WRITEABLE, zone);
	if (query == NULL)
		return (ISC_R_NOMEMORY);

	res = db_query(state, NULL, query);
	free(query);
	if (res == NULL)
		return (ISC_R_FAILURE);

	if ((row = mysql_fetch_row(res)) == NULL) {
		mysql_free_result(res);
		return (ISC_R_FAILURE);
	}

	strcpy(zone_id, row[0]);
	mysql_free_result(res);

	/*
	 * See if we already have a transaction for this zone
	 */
	dlz_mutex_lock(&state->tx_mutex);
	for (txn = state->transactions; txn != NULL; txn = txn->next) {
		if (strcmp(txn->zone, zone) == 0) {
			if (state->log != NULL)
				state->log(ISC_LOG_ERROR,
				   "%s: transaction already "
				   "started for zone %s", modname, zone);
			dlz_mutex_unlock(&state->tx_mutex);
			return (ISC_R_FAILURE);
		}
	}

	/*
	 * Create new transaction
	 */
	newtx = (mysql_transaction_t *)
1300
1301
1302
1303
1304
		calloc(1, sizeof(mysql_transaction_t));
	if (newtx == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}
1305
	newtx->zone = strdup(zone);
1306
1307
1308
1309
	if (newtx->zone == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}
1310
	newtx->zone_id = strdup(zone_id);
1311
1312
1313
1314
	if (newtx->zone_id == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
	newtx->dbi = get_dbi(state);
	newtx->next = NULL;

	if (newtx->dbi == NULL) {
		result = ISC_R_FAILURE;
		goto cleanup;
	}

	result = db_execute(state, newtx->dbi, "START TRANSACTION");
	if (result != ISC_R_SUCCESS) {
		dlz_mutex_unlock(&newtx->dbi->mutex);
		goto cleanup;
	}

	/*
	 * Add this tx to front of list
	 */
	newtx->next = state->transactions;
	state->transactions = newtx;

	if (state->debug && (state->log != NULL))
		state->log(ISC_LOG_INFO, "%s: New tx %x", modname, newtx);

 cleanup:
	dlz_mutex_unlock(&state->tx_mutex);
	if (result == ISC_R_SUCCESS) {
		*versionp = (void *) newtx;
	} else {
		dlz_mutex_unlock(&state->tx_mutex);
1344
1345
1346
1347
1348
1349
1350
1351
1352
		if (newtx != NULL) {
			if (newtx->zone != NULL) {
				free(newtx->zone);
			}
			if (newtx->zone != NULL) {
				free(newtx->zone_id);
			}
			free(newtx);
		}
1353
1354
1355
1356
1357
1358
1359
1360
1361
	}

	return (result);
}

/*
 * End a transaction
 */
void
1362
dlz_closeversion(const char *zone, bool commit,
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
		 void *dbdata, void **versionp)
{
	isc_result_t result;
	mysql_data_t *state = (mysql_data_t *)dbdata;
	mysql_transaction_t *txn = (mysql_transaction_t *)*versionp;
	mysql_transaction_t *txp;
	char *query;
	MYSQL_RES *res;
	MYSQL_ROW row;

	/*
	 * Find the transaction
	 */
	dlz_mutex_lock(&state->tx_mutex);
	if (state->transactions == txn) {
		/* Tx is first in list; remove it. */
		state->transactions = txn->next;
	} else {
		txp = state->transactions;
		while (txp != NULL) {
			if (txp->next != NULL) {
				if (txp->next == txn) {
					txp->next = txn->next;
					break;
				}
			}
			if (txp == txn) {
				txp = txn->next;
				break;
			}
			txp = txp->next;
		}
	}

	/*
	 * Tidy up
	 */
	dlz_mutex_unlock(&state->tx_mutex);
	*versionp = NULL;

	if (commit) {
		int oldsn = 0, newsn = 0;

		/*
		 * Find out the serial number of the zone out with the
		 * transaction so we can see if it has incremented or not
		 */
		query = build_query(state, txn->dbi, Q_GETSERIAL, zone);
		if (query == NULL && state->log != NULL) {
			state->log(ISC_LOG_ERROR,
				   "%s: unable to commit transaction %x "
				   "on zone %s: no memory",
				   modname, txn, zone);
			return;
		}

		res = db_query(state, txn->dbi, query);
		if (res != NULL) {
			while ((row = mysql_fetch_row(res)) != NULL)
				sscanf(row[0], "%d", &oldsn);
			mysql_free_result(res);
		}

		/*
		 * Commit the transaction to the database
		 */
		result = db_execute(state, txn->dbi, "COMMIT");
		if (result != ISC_R_SUCCESS && state->log != NULL) {
			state->log(ISC_LOG_INFO,
				   "%s: (%x) commit transaction on zone %s",
				   modname, txn, zone);
			return;
		}

		if (state->debug && state->log != NULL)
			state->log(ISC_LOG_INFO,
				   "%s: (%x) committing transaction "
				   "on zone %s",
				   modname, txn, zone);

		/*
		 * Now get the serial number again
		 */
		query = build_query(state, txn->dbi, Q_GETSERIAL, zone);
		res = db_query(state, txn->dbi, query);
		free(query);

		if (res != NULL) {
			while ((row = mysql_fetch_row(res)) != NULL)
				sscanf(row[0], "%d", &newsn);
			mysql_free_result(res);
		}

		/*
		 * Look to see if serial numbers have changed
		 */
		if (newsn > oldsn)
			notify(state, zone, newsn);
	} else {
		result = db_execute(state, txn->dbi, "ROLLBACK");
		if (state->debug && (state->log != NULL))
			state->log(ISC_LOG_INFO,
				   "%s: (%x) roll back transaction on zone %s",
				   modname, txn, zone);
	}

	/*
	 * Unlock the mutex for this txn
	 */
	dlz_mutex_unlock(&txn->dbi->mutex);

	/*
	 * Free up other structures
	 */
	free(txn->zone);
	free(txn->zone_id);
	free(txn);
}

/*
 * Configure a writeable zone
 */
#if DLZ_DLOPEN_VERSION < 3
isc_result_t
dlz_configure(dns_view_t *view, void *dbdata)
#else /* DLZ_DLOPEN_VERSION >= 3 */
isc_result_t
dlz_configure(dns_view_t *view, dns_dlzdb_t *dlzdb, void *dbdata)
#endif /* DLZ_DLOPEN_VERSION */
{
	mysql_data_t *state = (mysql_data_t *)dbdata;
	isc_result_t result;
	MYSQL_RES *res;
	MYSQL_ROW row;
	int count;

	/*
	 * Seed PRNG (used by Notify code)
	 */
	srand(getpid());

	if (state->debug && state->log != NULL)
		state->log(ISC_LOG_INFO, "%s: dlz_confgure", modname);

	if (state->writeable_zone == NULL) {
		if (state->log != NULL)
			state->log(ISC_LOG_ERROR,
				   "%s: no writeable_zone method available",
				   modname);
		return (ISC_R_FAILURE);
	}

	/*
	 * Get a list of Zones (ignore writeable column at this point)
	 */
	res = db_query(state, NULL, Q_GETZONES);
	if (res == NULL)
		return (ISC_R_FAILURE);

	count = 0;
	while ((row = mysql_fetch_row(res)) != NULL) {
		int sn;
		sscanf(row[1], "%d", &sn);
		notify(state, row[0], sn);
		result = state->writeable_zone(view,
#if DLZ_DLOPEN_VERSION >= 3
					       dlzdb,
#endif
					       row[0]);
		if (result != ISC_R_SUCCESS) {
			if (state->log != NULL)
				state->log(ISC_LOG_ERROR,
					   "%s: failed to configure zone %s",
					   modname, row[0]);
			mysql_free_result(res);
			return (result);
		}
		count++;
	}
	mysql_free_result(res);

	if (state->debug && state->log != NULL)
		state->log(ISC_LOG_INFO,
			   "%s: configured %d zones", modname, count);
	return (ISC_R_SUCCESS);
}

/*
 * Authorize a zone update
 */
1553
bool
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
dlz_ssumatch(const char *signer, const char *name, const char *tcpaddr,
	     const char *type, const char *key, uint32_t keydatalen,
	     unsigned char *keydata, void *dbdata)
{
	mysql_data_t *state = (mysql_data_t *)dbdata;

	UNUSED(tcpaddr);
	UNUSED(type);
	UNUSED(keydatalen);
	UNUSED(keydata);
	UNUSED(key);

	if (state->debug && state->log != NULL)
		state->log(ISC_LOG_INFO,
			   "%s: allowing update of %s by key %s",
			   modname, name, signer);
1570
	return (true);
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
}

isc_result_t
dlz_addrdataset(const char *name, const char *rdatastr,
		void *dbdata, void *version)
{
	mysql_data_t *state = (mysql_data_t *)dbdata;
	mysql_transaction_t *txn = (mysql_transaction_t *)version;
	char *new_name, *query;
	mysql_record_t *record;
	isc_result_t result;

	if (txn == NULL)
		return (ISC_R_FAILURE);

	new_name = relname(name, txn->zone);
	if (new_name == NULL)
		return (ISC_R_NOMEMORY);

	if (state->debug && (state->log != NULL))
		state->log(ISC_LOG_INFO, "%s: add (%x) %s (as %s) %s",
			   modname, version, name, new_name, rdatastr);

	record = makerecord(state, new_name, rdatastr);
	free(new_name);
	if (record == NULL)
		return (ISC_R_FAILURE);

	/* Write out data to database */
	if (strcasecmp(record->type, "SOA") != 0) {
		query = build_query(state, txn->dbi, I_DATA,
				    txn->zone_id, record->name,
				    record->type, record->data,
				    record->ttl);
		if (query == NULL) {
			result = ISC_R_FAILURE;
			goto cleanup;
		}
		result = db_execute(state, txn->dbi, query);
		free(query);
	} else {
		/*
		 * This is an SOA record, so we update: it must exist,
		 * or we wouldn't have gotten this far.
		 * SOA: zone admin serial refresh retry expire min
		 */
		char sn[32];
1618
		sscanf(record->data, "%*s %*s %31s %*s %*s %*s %*s", sn);
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
		query = build_query(state, txn->dbi, U_SERIAL, sn,
				    txn->zone_id);
		if (query == NULL) {
			result = ISC_R_FAILURE;
			goto cleanup;
		}
		result = db_execute(state, txn->dbi, query);
		free(query);
	}

 cleanup:
	free(record);
	return (result);
}

isc_result_t
dlz_subrdataset(const char *name, const char *rdatastr,
		void *dbdata, void *version)
{
	mysql_data_t *state = (mysql_data_t *)dbdata;
	mysql_transaction_t *txn = (mysql_transaction_t *)version;
	char *new_name, *query;
	mysql_record_t *record;
	isc_result_t result;

	if (txn == NULL)
		return (ISC_R_FAILURE);

	new_name = relname(name, txn->zone);
	if (new_name == NULL)
		return (ISC_R_NOMEMORY);

	if (state->debug && (state->log != NULL))
		state->log(ISC_LOG_INFO, "%s: sub (%x) %s %s",
			   modname, version, name, rdatastr);

	record = makerecord(state, new_name, rdatastr);
	free(new_name);
	if (record == NULL)
		return (ISC_R_FAILURE);
	/*
	 * If 'type' isn't 'SOA', delete the records
	 */
	if (strcasecmp(record->type, "SOA") == 0)
		result = ISC_R_SUCCESS;
	else {
		query = build_query(state, txn->dbi, D_RECORD,
				    txn->zone_id, record->name,
				    record->type, record->data,
				    record->ttl);
		if (query == NULL) {
			result = ISC_R_NOMEMORY;
			goto cleanup;
		}

		result = db_execute(state, txn->dbi, query);
		free(query);
	}

 cleanup:
	free(record);
	return (result);
}

isc_result_t
dlz_delrdataset(const char *name, const char *type,
		void *dbdata, void *version)
{
	mysql_data_t *state = (mysql_data_t *)dbdata;
	mysql_transaction_t *txn = (mysql_transaction_t *)version;
	char *new_name, *query;
	isc_result_t result;

	if (txn == NULL)
		return (ISC_R_FAILURE);

	new_name = relname(name, txn->zone);
	if (new_name == NULL)
		return (ISC_R_NOMEMORY);

	if (state->debug && (state->log != NULL))
		state->log(ISC_LOG_INFO, "%s: del (%x) %s %s",
			   modname, version, name, type);

	query = build_query(state, txn->dbi, D_RRSET,
			    txn->zone_id, new_name, type);
	if (query == NULL) {
		result = ISC_R_NOMEMORY;
		goto cleanup;
	}

	result = db_execute(state, txn->dbi, query);
	free(query);

 cleanup:
	free(new_name);
	return (result);
}