s4-dns Use match-by-key in GSSAPI server if principal is not specified
[kai/samba.git] / source4 / dns_server / dlz_bind9.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    bind9 dlz driver for Samba
5
6    Copyright (C) 2010 Andrew Tridgell
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "talloc.h"
24 #include "param/param.h"
25 #include "lib/events/events.h"
26 #include "dsdb/samdb/samdb.h"
27 #include "dsdb/common/util.h"
28 #include "auth/auth.h"
29 #include "auth/session.h"
30 #include "auth/gensec/gensec.h"
31 #include "librpc/gen_ndr/security.h"
32 #include "auth/credentials/credentials.h"
33 #include "system/kerberos.h"
34 #include "auth/kerberos/kerberos.h"
35 #include "gen_ndr/ndr_dnsp.h"
36 #include "gen_ndr/server_id.h"
37 #include "messaging/messaging.h"
38 #include "lib/cmdline/popt_common.h"
39 #include "dlz_minimal.h"
40
41
42 struct b9_options {
43         const char *url;
44         const char *debug;
45 };
46
47 struct dlz_bind9_data {
48         struct b9_options options;
49         struct ldb_context *samdb;
50         struct tevent_context *ev_ctx;
51         struct loadparm_context *lp;
52         int *transaction_token;
53         uint32_t soa_serial;
54
55         /* Used for dynamic update */
56         struct smb_krb5_context *smb_krb5_ctx;
57         struct auth_session_info *session_info;
58         char *update_name;
59
60         /* helper functions from the dlz_dlopen driver */
61         void (*log)(int level, const char *fmt, ...);
62         isc_result_t (*putrr)(dns_sdlzlookup_t *handle, const char *type,
63                               dns_ttl_t ttl, const char *data);
64         isc_result_t (*putnamedrr)(dns_sdlzlookup_t *handle, const char *name,
65                                    const char *type, dns_ttl_t ttl, const char *data);
66         isc_result_t (*writeable_zone)(dns_view_t *view, const char *zone_name);
67 };
68
69
70 static const char *zone_prefixes[] = {
71         "CN=MicrosoftDNS,DC=DomainDnsZones",
72         "CN=MicrosoftDNS,DC=ForestDnsZones",
73         "CN=MicrosoftDNS,CN=System",
74         NULL
75 };
76
77 /*
78   return the version of the API
79  */
80 _PUBLIC_ int dlz_version(unsigned int *flags)
81 {
82         return DLZ_DLOPEN_VERSION;
83 }
84
85 /*
86    remember a helper function from the bind9 dlz_dlopen driver
87  */
88 static void b9_add_helper(struct dlz_bind9_data *state, const char *helper_name, void *ptr)
89 {
90         if (strcmp(helper_name, "log") == 0) {
91                 state->log = ptr;
92         }
93         if (strcmp(helper_name, "putrr") == 0) {
94                 state->putrr = ptr;
95         }
96         if (strcmp(helper_name, "putnamedrr") == 0) {
97                 state->putnamedrr = ptr;
98         }
99         if (strcmp(helper_name, "writeable_zone") == 0) {
100                 state->writeable_zone = ptr;
101         }
102 }
103
104 /*
105   format a record for bind9
106  */
107 static bool b9_format(struct dlz_bind9_data *state,
108                       TALLOC_CTX *mem_ctx,
109                       struct dnsp_DnssrvRpcRecord *rec,
110                       const char **type, const char **data)
111 {
112         switch (rec->wType) {
113         case DNS_TYPE_A:
114                 *type = "a";
115                 *data = rec->data.ipv4;
116                 break;
117
118         case DNS_TYPE_AAAA:
119                 *type = "aaaa";
120                 *data = rec->data.ipv6;
121                 break;
122
123         case DNS_TYPE_CNAME:
124                 *type = "cname";
125                 *data = rec->data.cname;
126                 break;
127
128         case DNS_TYPE_TXT:
129                 *type = "txt";
130                 *data = rec->data.txt;
131                 break;
132
133         case DNS_TYPE_PTR:
134                 *type = "ptr";
135                 *data = rec->data.ptr;
136                 break;
137
138         case DNS_TYPE_SRV:
139                 *type = "srv";
140                 *data = talloc_asprintf(mem_ctx, "%u %u %u %s",
141                                         rec->data.srv.wPriority,
142                                         rec->data.srv.wWeight,
143                                         rec->data.srv.wPort,
144                                         rec->data.srv.nameTarget);
145                 break;
146
147         case DNS_TYPE_MX:
148                 *type = "mx";
149                 *data = talloc_asprintf(mem_ctx, "%u %s",
150                                         rec->data.mx.wPriority,
151                                         rec->data.mx.nameTarget);
152                 break;
153
154         case DNS_TYPE_HINFO:
155                 *type = "hinfo";
156                 *data = talloc_asprintf(mem_ctx, "%s %s",
157                                         rec->data.hinfo.cpu,
158                                         rec->data.hinfo.os);
159                 break;
160
161         case DNS_TYPE_NS:
162                 *type = "ns";
163                 *data = rec->data.ns;
164                 break;
165
166         case DNS_TYPE_SOA: {
167                 const char *mname;
168                 *type = "soa";
169
170                 /* we need to fake the authoritative nameserver to
171                  * point at ourselves. This is how AD DNS servers
172                  * force clients to send updates to the right local DC
173                  */
174                 mname = talloc_asprintf(mem_ctx, "%s.%s",
175                                         lpcfg_netbios_name(state->lp), lpcfg_dnsdomain(state->lp));
176                 if (mname == NULL) {
177                         return false;
178                 }
179                 mname = strlower_talloc(mem_ctx, mname);
180                 if (mname == NULL) {
181                         return false;
182                 }
183
184                 state->soa_serial = rec->data.soa.serial;
185
186                 *data = talloc_asprintf(mem_ctx, "%s %s %u %u %u %u %u",
187                                         mname,
188                                         rec->data.soa.rname,
189                                         rec->data.soa.serial,
190                                         rec->data.soa.refresh,
191                                         rec->data.soa.retry,
192                                         rec->data.soa.expire,
193                                         rec->data.soa.minimum);
194                 break;
195         }
196
197         default:
198                 state->log(ISC_LOG_ERROR, "samba b9_putrr: unhandled record type %u",
199                            rec->wType);
200                 return false;
201         }
202
203         return true;
204 }
205
206 static const struct {
207         enum dns_record_type dns_type;
208         const char *typestr;
209         bool single_valued;
210 } dns_typemap[] = {
211         { DNS_TYPE_A,     "A"     , false},
212         { DNS_TYPE_AAAA,  "AAAA"  , false},
213         { DNS_TYPE_CNAME, "CNAME" , true},
214         { DNS_TYPE_TXT,   "TXT"   , false},
215         { DNS_TYPE_PTR,   "PTR"   , false},
216         { DNS_TYPE_SRV,   "SRV"   , false},
217         { DNS_TYPE_MX,    "MX"    , false},
218         { DNS_TYPE_HINFO, "HINFO" , false},
219         { DNS_TYPE_NS,    "NS"    , false},
220         { DNS_TYPE_SOA,   "SOA"   , true},
221 };
222
223
224 /*
225   see if a DNS type is single valued
226  */
227 static bool b9_single_valued(enum dns_record_type dns_type)
228 {
229         int i;
230         for (i=0; i<ARRAY_SIZE(dns_typemap); i++) {
231                 if (dns_typemap[i].dns_type == dns_type) {
232                         return dns_typemap[i].single_valued;
233                 }
234         }
235         return false;
236 }
237
238 /*
239   see if a DNS type is single valued
240  */
241 static bool b9_dns_type(const char *type, enum dns_record_type *dtype)
242 {
243         int i;
244         for (i=0; i<ARRAY_SIZE(dns_typemap); i++) {
245                 if (strcasecmp(dns_typemap[i].typestr, type) == 0) {
246                         *dtype = dns_typemap[i].dns_type;
247                         return true;
248                 }
249         }
250         return false;
251 }
252
253
254 #define DNS_PARSE_STR(ret, str, sep, saveptr) do {      \
255         (ret) = strtok_r(str, sep, &saveptr); \
256         if ((ret) == NULL) return false; \
257         } while (0)
258
259 #define DNS_PARSE_UINT(ret, str, sep, saveptr) do {  \
260         char *istr = strtok_r(str, sep, &saveptr); \
261         if ((istr) == NULL) return false; \
262         (ret) = strtoul(istr, NULL, 10); \
263         } while (0)
264
265 /*
266   parse a record from bind9
267  */
268 static bool b9_parse(struct dlz_bind9_data *state,
269                      const char *rdatastr,
270                      struct dnsp_DnssrvRpcRecord *rec)
271 {
272         char *full_name, *dclass, *type;
273         char *str, *saveptr=NULL;
274         int i;
275
276         str = talloc_strdup(rec, rdatastr);
277         if (str == NULL) {
278                 return false;
279         }
280
281         /* parse the SDLZ string form */
282         DNS_PARSE_STR(full_name, str, "\t", saveptr);
283         DNS_PARSE_UINT(rec->dwTtlSeconds, NULL, "\t", saveptr);
284         DNS_PARSE_STR(dclass, NULL, "\t", saveptr);
285         DNS_PARSE_STR(type, NULL, "\t", saveptr);
286
287         /* construct the record */
288         for (i=0; i<ARRAY_SIZE(dns_typemap); i++) {
289                 if (strcasecmp(type, dns_typemap[i].typestr) == 0) {
290                         rec->wType = dns_typemap[i].dns_type;
291                         break;
292                 }
293         }
294         if (i == ARRAY_SIZE(dns_typemap)) {
295                 state->log(ISC_LOG_ERROR, "samba_dlz: unsupported record type '%s' for '%s'",
296                            type, full_name);
297                 return false;
298         }
299
300         switch (rec->wType) {
301         case DNS_TYPE_A:
302                 DNS_PARSE_STR(rec->data.ipv4, NULL, " ", saveptr);
303                 break;
304
305         case DNS_TYPE_AAAA:
306                 DNS_PARSE_STR(rec->data.ipv6, NULL, " ", saveptr);
307                 break;
308
309         case DNS_TYPE_CNAME:
310                 DNS_PARSE_STR(rec->data.cname, NULL, " ", saveptr);
311                 break;
312
313         case DNS_TYPE_TXT:
314                 DNS_PARSE_STR(rec->data.txt, NULL, "\t", saveptr);
315                 break;
316
317         case DNS_TYPE_PTR:
318                 DNS_PARSE_STR(rec->data.ptr, NULL, " ", saveptr);
319                 break;
320
321         case DNS_TYPE_SRV:
322                 DNS_PARSE_UINT(rec->data.srv.wPriority, NULL, " ", saveptr);
323                 DNS_PARSE_UINT(rec->data.srv.wWeight, NULL, " ", saveptr);
324                 DNS_PARSE_UINT(rec->data.srv.wPort, NULL, " ", saveptr);
325                 DNS_PARSE_STR(rec->data.srv.nameTarget, NULL, " ", saveptr);
326                 break;
327
328         case DNS_TYPE_MX:
329                 DNS_PARSE_UINT(rec->data.mx.wPriority, NULL, " ", saveptr);
330                 DNS_PARSE_STR(rec->data.mx.nameTarget, NULL, " ", saveptr);
331                 break;
332
333         case DNS_TYPE_HINFO:
334                 DNS_PARSE_STR(rec->data.hinfo.cpu, NULL, " ", saveptr);
335                 DNS_PARSE_STR(rec->data.hinfo.os, NULL, " ", saveptr);
336                 break;
337
338         case DNS_TYPE_NS:
339                 DNS_PARSE_STR(rec->data.ns, NULL, " ", saveptr);
340                 break;
341
342         case DNS_TYPE_SOA:
343                 DNS_PARSE_STR(rec->data.soa.mname, NULL, " ", saveptr);
344                 DNS_PARSE_STR(rec->data.soa.rname, NULL, " ", saveptr);
345                 DNS_PARSE_UINT(rec->data.soa.serial, NULL, " ", saveptr);
346                 DNS_PARSE_UINT(rec->data.soa.refresh, NULL, " ", saveptr);
347                 DNS_PARSE_UINT(rec->data.soa.retry, NULL, " ", saveptr);
348                 DNS_PARSE_UINT(rec->data.soa.expire, NULL, " ", saveptr);
349                 DNS_PARSE_UINT(rec->data.soa.minimum, NULL, " ", saveptr);
350                 break;
351
352         default:
353                 state->log(ISC_LOG_ERROR, "samba b9_parse: unhandled record type %u",
354                            rec->wType);
355                 return false;
356         }
357
358         /* we should be at the end of the buffer now */
359         if (strtok_r(NULL, "\t ", &saveptr) != NULL) {
360                 state->log(ISC_LOG_ERROR, "samba b9_parse: expected data at end of string for '%s'");
361                 return false;
362         }
363
364         return true;
365 }
366
367 /*
368   send a resource recond to bind9
369  */
370 static isc_result_t b9_putrr(struct dlz_bind9_data *state,
371                              void *handle, struct dnsp_DnssrvRpcRecord *rec,
372                              const char **types)
373 {
374         isc_result_t result;
375         const char *type, *data;
376         TALLOC_CTX *tmp_ctx = talloc_new(state);
377
378         if (!b9_format(state, tmp_ctx, rec, &type, &data)) {
379                 return ISC_R_FAILURE;
380         }
381
382         if (data == NULL) {
383                 talloc_free(tmp_ctx);
384                 return ISC_R_NOMEMORY;
385         }
386
387         if (types) {
388                 int i;
389                 for (i=0; types[i]; i++) {
390                         if (strcmp(types[i], type) == 0) break;
391                 }
392                 if (types[i] == NULL) {
393                         /* skip it */
394                         return ISC_R_SUCCESS;
395                 }
396         }
397
398         result = state->putrr(handle, type, rec->dwTtlSeconds, data);
399         if (result != ISC_R_SUCCESS) {
400                 state->log(ISC_LOG_ERROR, "Failed to put rr");
401         }
402         talloc_free(tmp_ctx);
403         return result;
404 }
405
406
407 /*
408   send a named resource recond to bind9
409  */
410 static isc_result_t b9_putnamedrr(struct dlz_bind9_data *state,
411                                   void *handle, const char *name,
412                                   struct dnsp_DnssrvRpcRecord *rec)
413 {
414         isc_result_t result;
415         const char *type, *data;
416         TALLOC_CTX *tmp_ctx = talloc_new(state);
417
418         if (!b9_format(state, tmp_ctx, rec, &type, &data)) {
419                 return ISC_R_FAILURE;
420         }
421
422         if (data == NULL) {
423                 talloc_free(tmp_ctx);
424                 return ISC_R_NOMEMORY;
425         }
426
427         result = state->putnamedrr(handle, name, type, rec->dwTtlSeconds, data);
428         if (result != ISC_R_SUCCESS) {
429                 state->log(ISC_LOG_ERROR, "Failed to put named rr '%s'", name);
430         }
431         talloc_free(tmp_ctx);
432         return result;
433 }
434
435 /*
436    parse options
437  */
438 static isc_result_t parse_options(struct dlz_bind9_data *state,
439                                   unsigned int argc, char *argv[],
440                                   struct b9_options *options)
441 {
442         int opt;
443         poptContext pc;
444         struct poptOption long_options[] = {
445                 { "url", 'H', POPT_ARG_STRING, &options->url, 0, "database URL", "URL" },
446                 { "debug", 'd', POPT_ARG_STRING, &options->debug, 0, "debug level", "DEBUG" },
447                 { NULL }
448         };
449
450         pc = poptGetContext("dlz_bind9", argc, (const char **)argv, long_options,
451                         POPT_CONTEXT_KEEP_FIRST);
452         while ((opt = poptGetNextOpt(pc)) != -1) {
453                 switch (opt) {
454                 default:
455                         state->log(ISC_LOG_ERROR, "dlz_bind9: Invalid option %s: %s",
456                                    poptBadOption(pc, 0), poptStrerror(opt));
457                         return ISC_R_FAILURE;
458                 }
459         }
460
461         return ISC_R_SUCCESS;
462 }
463
464
465 /*
466   called to initialise the driver
467  */
468 _PUBLIC_ isc_result_t dlz_create(const char *dlzname,
469                                  unsigned int argc, char *argv[],
470                                  void **dbdata, ...)
471 {
472         struct dlz_bind9_data *state;
473         const char *helper_name;
474         va_list ap;
475         isc_result_t result;
476         TALLOC_CTX *tmp_ctx;
477         struct ldb_dn *dn;
478         NTSTATUS nt_status;
479
480         state = talloc_zero(NULL, struct dlz_bind9_data);
481         if (state == NULL) {
482                 return ISC_R_NOMEMORY;
483         }
484
485         tmp_ctx = talloc_new(state);
486
487         /* fill in the helper functions */
488         va_start(ap, dbdata);
489         while ((helper_name = va_arg(ap, const char *)) != NULL) {
490                 b9_add_helper(state, helper_name, va_arg(ap, void*));
491         }
492         va_end(ap);
493
494         /* Do not install samba signal handlers */
495         fault_setup_disable();
496
497         /* Start logging */
498         setup_logging("samba_dlz", DEBUG_DEFAULT_STDERR);
499
500         state->ev_ctx = s4_event_context_init(state);
501         if (state->ev_ctx == NULL) {
502                 result = ISC_R_NOMEMORY;
503                 goto failed;
504         }
505
506         result = parse_options(state, argc, argv, &state->options);
507         if (result != ISC_R_SUCCESS) {
508                 goto failed;
509         }
510
511         state->lp = loadparm_init_global(true);
512         if (state->lp == NULL) {
513                 result = ISC_R_NOMEMORY;
514                 goto failed;
515         }
516
517         if (state->options.debug) {
518                 lpcfg_do_global_parameter(state->lp, "log level", state->options.debug);
519         } else {
520                 lpcfg_do_global_parameter(state->lp, "log level", "0");
521         }
522
523         if (smb_krb5_init_context(state, state->ev_ctx, state->lp, &state->smb_krb5_ctx) != 0) {
524                 result = ISC_R_NOMEMORY;
525                 goto failed;
526         }
527
528         nt_status = gensec_init();
529         if (!NT_STATUS_IS_OK(nt_status)) {
530                 talloc_free(tmp_ctx);
531                 return false;
532         }
533
534         if (state->options.url == NULL) {
535                 state->options.url = lpcfg_private_path(state, state->lp, "dns/sam.ldb");
536                 if (state->options.url == NULL) {
537                         result = ISC_R_NOMEMORY;
538                         goto failed;
539                 }
540         }
541
542         state->samdb = samdb_connect_url(state, state->ev_ctx, state->lp,
543                                         system_session(state->lp), 0, state->options.url);
544         if (state->samdb == NULL) {
545                 state->log(ISC_LOG_ERROR, "samba_dlz: Failed to connect to %s",
546                         state->options.url);
547                 result = ISC_R_FAILURE;
548                 goto failed;
549         }
550
551         dn = ldb_get_default_basedn(state->samdb);
552         if (dn == NULL) {
553                 state->log(ISC_LOG_ERROR, "samba_dlz: Unable to get basedn for %s - %s",
554                            state->options.url, ldb_errstring(state->samdb));
555                 result = ISC_R_FAILURE;
556                 goto failed;
557         }
558
559         state->log(ISC_LOG_INFO, "samba_dlz: started for DN %s",
560                    ldb_dn_get_linearized(dn));
561
562         *dbdata = state;
563
564         talloc_free(tmp_ctx);
565         return ISC_R_SUCCESS;
566
567 failed:
568         talloc_free(state);
569         return result;
570 }
571
572 /*
573   shutdown the backend
574  */
575 _PUBLIC_ void dlz_destroy(void *dbdata)
576 {
577         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
578         state->log(ISC_LOG_INFO, "samba_dlz: shutting down");
579         talloc_free(state);
580 }
581
582
583 /*
584   return the base DN for a zone
585  */
586 static isc_result_t b9_find_zone_dn(struct dlz_bind9_data *state, const char *zone_name,
587                                     TALLOC_CTX *mem_ctx, struct ldb_dn **zone_dn)
588 {
589         int ret;
590         TALLOC_CTX *tmp_ctx = talloc_new(state);
591         const char *attrs[] = { NULL };
592         int i;
593
594         for (i=0; zone_prefixes[i]; i++) {
595                 struct ldb_dn *dn;
596                 struct ldb_result *res;
597
598                 dn = ldb_dn_copy(tmp_ctx, ldb_get_default_basedn(state->samdb));
599                 if (dn == NULL) {
600                         talloc_free(tmp_ctx);
601                         return ISC_R_NOMEMORY;
602                 }
603
604                 if (!ldb_dn_add_child_fmt(dn, "DC=%s,%s", zone_name, zone_prefixes[i])) {
605                         talloc_free(tmp_ctx);
606                         return ISC_R_NOMEMORY;
607                 }
608
609                 ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, "objectClass=dnsZone");
610                 if (ret == LDB_SUCCESS) {
611                         if (zone_dn != NULL) {
612                                 *zone_dn = talloc_steal(mem_ctx, dn);
613                         }
614                         talloc_free(tmp_ctx);
615                         return ISC_R_SUCCESS;
616                 }
617                 talloc_free(dn);
618         }
619
620         talloc_free(tmp_ctx);
621         return ISC_R_NOTFOUND;
622 }
623
624
625 /*
626   return the DN for a name. The record does not need to exist, but the
627   zone must exist
628  */
629 static isc_result_t b9_find_name_dn(struct dlz_bind9_data *state, const char *name,
630                                     TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
631 {
632         const char *p;
633
634         /* work through the name piece by piece, until we find a zone */
635         for (p=name; p; ) {
636                 isc_result_t result;
637                 result = b9_find_zone_dn(state, p, mem_ctx, dn);
638                 if (result == ISC_R_SUCCESS) {
639                         /* we found a zone, now extend the DN to get
640                          * the full DN
641                          */
642                         bool ret;
643                         if (p == name) {
644                                 ret = ldb_dn_add_child_fmt(*dn, "DC=@");
645                         } else {
646                                 ret = ldb_dn_add_child_fmt(*dn, "DC=%.*s", (int)(p-name)-1, name);
647                         }
648                         if (!ret) {
649                                 talloc_free(*dn);
650                                 return ISC_R_NOMEMORY;
651                         }
652                         return ISC_R_SUCCESS;
653                 }
654                 p = strchr(p, '.');
655                 if (p == NULL) {
656                         break;
657                 }
658                 p++;
659         }
660         return ISC_R_NOTFOUND;
661 }
662
663
664 /*
665   see if we handle a given zone
666  */
667 _PUBLIC_ isc_result_t dlz_findzonedb(void *dbdata, const char *name)
668 {
669         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
670         return b9_find_zone_dn(state, name, NULL, NULL);
671 }
672
673
674 /*
675   lookup one record
676  */
677 static isc_result_t dlz_lookup_types(struct dlz_bind9_data *state,
678                                      const char *zone, const char *name,
679                                      dns_sdlzlookup_t *lookup,
680                                      const char **types)
681 {
682         TALLOC_CTX *tmp_ctx = talloc_new(state);
683         const char *attrs[] = { "dnsRecord", NULL };
684         int ret = LDB_SUCCESS, i;
685         struct ldb_result *res;
686         struct ldb_message_element *el;
687         struct ldb_dn *dn;
688
689         for (i=0; zone_prefixes[i]; i++) {
690                 dn = ldb_dn_copy(tmp_ctx, ldb_get_default_basedn(state->samdb));
691                 if (dn == NULL) {
692                         talloc_free(tmp_ctx);
693                         return ISC_R_NOMEMORY;
694                 }
695
696                 if (!ldb_dn_add_child_fmt(dn, "DC=%s,DC=%s,%s", name, zone, zone_prefixes[i])) {
697                         talloc_free(tmp_ctx);
698                         return ISC_R_NOMEMORY;
699                 }
700
701                 ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_BASE,
702                                  attrs, "objectClass=dnsNode");
703                 if (ret == LDB_SUCCESS) {
704                         break;
705                 }
706         }
707         if (ret != LDB_SUCCESS) {
708                 talloc_free(tmp_ctx);
709                 return ISC_R_NOTFOUND;
710         }
711
712         el = ldb_msg_find_element(res->msgs[0], "dnsRecord");
713         if (el == NULL || el->num_values == 0) {
714                 talloc_free(tmp_ctx);
715                 return ISC_R_NOTFOUND;
716         }
717
718         for (i=0; i<el->num_values; i++) {
719                 struct dnsp_DnssrvRpcRecord rec;
720                 enum ndr_err_code ndr_err;
721                 isc_result_t result;
722
723                 ndr_err = ndr_pull_struct_blob(&el->values[i], tmp_ctx, &rec,
724                                                (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
725                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
726                         state->log(ISC_LOG_ERROR, "samba_dlz: failed to parse dnsRecord for %s",
727                                    ldb_dn_get_linearized(dn));
728                         talloc_free(tmp_ctx);
729                         return ISC_R_FAILURE;
730                 }
731
732                 result = b9_putrr(state, lookup, &rec, types);
733                 if (result != ISC_R_SUCCESS) {
734                         talloc_free(tmp_ctx);
735                         return result;
736                 }
737         }
738
739         talloc_free(tmp_ctx);
740         return ISC_R_SUCCESS;
741 }
742
743 /*
744   lookup one record
745  */
746 _PUBLIC_ isc_result_t dlz_lookup(const char *zone, const char *name,
747                                  void *dbdata, dns_sdlzlookup_t *lookup)
748 {
749         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
750         return dlz_lookup_types(state, zone, name, lookup, NULL);
751 }
752
753
754 /*
755   see if a zone transfer is allowed
756  */
757 _PUBLIC_ isc_result_t dlz_allowzonexfr(void *dbdata, const char *name, const char *client)
758 {
759         /* just say yes for all our zones for now */
760         return dlz_findzonedb(dbdata, name);
761 }
762
763 /*
764   perform a zone transfer
765  */
766 _PUBLIC_ isc_result_t dlz_allnodes(const char *zone, void *dbdata,
767                                    dns_sdlzallnodes_t *allnodes)
768 {
769         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
770         const char *attrs[] = { "dnsRecord", NULL };
771         int ret = LDB_SUCCESS, i, j;
772         struct ldb_dn *dn;
773         struct ldb_result *res;
774         TALLOC_CTX *tmp_ctx = talloc_new(state);
775
776         for (i=0; zone_prefixes[i]; i++) {
777                 dn = ldb_dn_copy(tmp_ctx, ldb_get_default_basedn(state->samdb));
778                 if (dn == NULL) {
779                         talloc_free(tmp_ctx);
780                         return ISC_R_NOMEMORY;
781                 }
782
783                 if (!ldb_dn_add_child_fmt(dn, "DC=%s,%s", zone, zone_prefixes[i])) {
784                         talloc_free(tmp_ctx);
785                         return ISC_R_NOMEMORY;
786                 }
787
788                 ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_SUBTREE,
789                                  attrs, "objectClass=dnsNode");
790                 if (ret == LDB_SUCCESS) {
791                         break;
792                 }
793         }
794         if (ret != LDB_SUCCESS) {
795                 talloc_free(tmp_ctx);
796                 return ISC_R_NOTFOUND;
797         }
798
799         for (i=0; i<res->count; i++) {
800                 struct ldb_message_element *el;
801                 TALLOC_CTX *el_ctx = talloc_new(tmp_ctx);
802                 const char *rdn, *name;
803                 const struct ldb_val *v;
804
805                 el = ldb_msg_find_element(res->msgs[i], "dnsRecord");
806                 if (el == NULL || el->num_values == 0) {
807                         state->log(ISC_LOG_INFO, "failed to find dnsRecord for %s",
808                                    ldb_dn_get_linearized(dn));
809                         talloc_free(el_ctx);
810                         continue;
811                 }
812
813                 v = ldb_dn_get_rdn_val(res->msgs[i]->dn);
814                 if (v == NULL) {
815                         state->log(ISC_LOG_INFO, "failed to find RDN for %s",
816                                    ldb_dn_get_linearized(dn));
817                         talloc_free(el_ctx);
818                         continue;
819                 }
820
821                 rdn = talloc_strndup(el_ctx, (char *)v->data, v->length);
822                 if (rdn == NULL) {
823                         talloc_free(tmp_ctx);
824                         return ISC_R_NOMEMORY;
825                 }
826
827                 if (strcmp(rdn, "@") == 0) {
828                         name = zone;
829                 } else {
830                         name = talloc_asprintf(el_ctx, "%s.%s", rdn, zone);
831                 }
832                 if (name == NULL) {
833                         talloc_free(tmp_ctx);
834                         return ISC_R_NOMEMORY;
835                 }
836
837                 for (j=0; j<el->num_values; j++) {
838                         struct dnsp_DnssrvRpcRecord rec;
839                         enum ndr_err_code ndr_err;
840                         isc_result_t result;
841
842                         ndr_err = ndr_pull_struct_blob(&el->values[j], el_ctx, &rec,
843                                                        (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
844                         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
845                                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to parse dnsRecord for %s",
846                                            ldb_dn_get_linearized(dn));
847                                 continue;
848                         }
849
850                         result = b9_putnamedrr(state, allnodes, name, &rec);
851                         if (result != ISC_R_SUCCESS) {
852                                 continue;
853                         }
854                 }
855         }
856
857         talloc_free(tmp_ctx);
858
859         return ISC_R_SUCCESS;
860 }
861
862
863 /*
864   start a transaction
865  */
866 _PUBLIC_ isc_result_t dlz_newversion(const char *zone, void *dbdata, void **versionp)
867 {
868         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
869
870         state->log(ISC_LOG_INFO, "samba_dlz: starting transaction on zone %s", zone);
871
872         if (state->transaction_token != NULL) {
873                 state->log(ISC_LOG_INFO, "samba_dlz: transaction already started for zone %s", zone);
874                 return ISC_R_FAILURE;
875         }
876
877         state->transaction_token = talloc_zero(state, int);
878         if (state->transaction_token == NULL) {
879                 return ISC_R_NOMEMORY;
880         }
881
882         if (ldb_transaction_start(state->samdb) != LDB_SUCCESS) {
883                 state->log(ISC_LOG_INFO, "samba_dlz: failed to start a transaction for zone %s", zone);
884                 talloc_free(state->transaction_token);
885                 state->transaction_token = NULL;
886                 return ISC_R_FAILURE;
887         }
888
889         *versionp = (void *)state->transaction_token;
890
891         return ISC_R_SUCCESS;
892 }
893
894 /*
895   end a transaction
896  */
897 _PUBLIC_ void dlz_closeversion(const char *zone, isc_boolean_t commit,
898                                void *dbdata, void **versionp)
899 {
900         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
901
902         if (state->transaction_token != (int *)*versionp) {
903                 state->log(ISC_LOG_INFO, "samba_dlz: transaction not started for zone %s", zone);
904                 return;
905         }
906
907         if (commit) {
908                 if (ldb_transaction_commit(state->samdb) != LDB_SUCCESS) {
909                         state->log(ISC_LOG_INFO, "samba_dlz: failed to commit a transaction for zone %s", zone);
910                         return;
911                 }
912                 state->log(ISC_LOG_INFO, "samba_dlz: committed transaction on zone %s", zone);
913         } else {
914                 if (ldb_transaction_cancel(state->samdb) != LDB_SUCCESS) {
915                         state->log(ISC_LOG_INFO, "samba_dlz: failed to cancel a transaction for zone %s", zone);
916                         return;
917                 }
918                 state->log(ISC_LOG_INFO, "samba_dlz: cancelling transaction on zone %s", zone);
919         }
920
921         talloc_free(state->transaction_token);
922         state->transaction_token = NULL;
923         *versionp = NULL;
924 }
925
926
927 /*
928   see if there is a SOA record for a zone
929  */
930 static bool b9_has_soa(struct dlz_bind9_data *state, struct ldb_dn *dn, const char *zone)
931 {
932         const char *attrs[] = { "dnsRecord", NULL };
933         struct ldb_result *res;
934         struct ldb_message_element *el;
935         TALLOC_CTX *tmp_ctx = talloc_new(state);
936         int ret, i;
937
938         if (!ldb_dn_add_child_fmt(dn, "DC=@,DC=%s", zone)) {
939                 talloc_free(tmp_ctx);
940                 return false;
941         }
942
943         ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_BASE,
944                          attrs, "objectClass=dnsNode");
945         if (ret != LDB_SUCCESS) {
946                 talloc_free(tmp_ctx);
947                 return false;
948         }
949
950         el = ldb_msg_find_element(res->msgs[0], "dnsRecord");
951         if (el == NULL) {
952                 talloc_free(tmp_ctx);
953                 return false;
954         }
955         for (i=0; i<el->num_values; i++) {
956                 struct dnsp_DnssrvRpcRecord rec;
957                 enum ndr_err_code ndr_err;
958
959                 ndr_err = ndr_pull_struct_blob(&el->values[i], tmp_ctx, &rec,
960                                                (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
961                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
962                         continue;
963                 }
964                 if (rec.wType == DNS_TYPE_SOA) {
965                         talloc_free(tmp_ctx);
966                         return true;
967                 }
968         }
969
970         talloc_free(tmp_ctx);
971         return false;
972 }
973
974 /*
975   configure a writeable zone
976  */
977 _PUBLIC_ isc_result_t dlz_configure(dns_view_t *view, void *dbdata)
978 {
979         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
980         TALLOC_CTX *tmp_ctx;
981         struct ldb_dn *dn;
982         int i;
983
984         state->log(ISC_LOG_INFO, "samba_dlz: starting configure");
985         if (state->writeable_zone == NULL) {
986                 state->log(ISC_LOG_INFO, "samba_dlz: no writeable_zone method available");
987                 return ISC_R_FAILURE;
988         }
989
990         tmp_ctx = talloc_new(state);
991
992         for (i=0; zone_prefixes[i]; i++) {
993                 const char *attrs[] = { "name", NULL };
994                 int j, ret;
995                 struct ldb_result *res;
996
997                 dn = ldb_dn_copy(tmp_ctx, ldb_get_default_basedn(state->samdb));
998                 if (dn == NULL) {
999                         talloc_free(tmp_ctx);
1000                         return ISC_R_NOMEMORY;
1001                 }
1002
1003                 if (!ldb_dn_add_child_fmt(dn, "%s", zone_prefixes[i])) {
1004                         talloc_free(tmp_ctx);
1005                         return ISC_R_NOMEMORY;
1006                 }
1007
1008                 ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_SUBTREE,
1009                                  attrs, "objectClass=dnsZone");
1010                 if (ret != LDB_SUCCESS) {
1011                         continue;
1012                 }
1013
1014                 for (j=0; j<res->count; j++) {
1015                         isc_result_t result;
1016                         const char *zone = ldb_msg_find_attr_as_string(res->msgs[j], "name", NULL);
1017                         struct ldb_dn *zone_dn;
1018
1019                         if (zone == NULL) {
1020                                 continue;
1021                         }
1022                         zone_dn = ldb_dn_copy(tmp_ctx, dn);
1023                         if (zone_dn == NULL) {
1024                                 talloc_free(tmp_ctx);
1025                                 return ISC_R_NOMEMORY;
1026                         }
1027
1028                         if (!b9_has_soa(state, zone_dn, zone)) {
1029                                 continue;
1030                         }
1031                         result = state->writeable_zone(view, zone);
1032                         if (result != ISC_R_SUCCESS) {
1033                                 state->log(ISC_LOG_ERROR, "samba_dlz: Failed to configure zone '%s'",
1034                                            zone);
1035                                 talloc_free(tmp_ctx);
1036                                 return result;
1037                         }
1038                         state->log(ISC_LOG_INFO, "samba_dlz: configured writeable zone '%s'", zone);
1039                 }
1040         }
1041
1042         talloc_free(tmp_ctx);
1043         return ISC_R_SUCCESS;
1044 }
1045
1046 /*
1047   authorize a zone update
1048  */
1049 _PUBLIC_ isc_boolean_t dlz_ssumatch(const char *signer, const char *name, const char *tcpaddr,
1050                                     const char *type, const char *key, uint32_t keydatalen, uint8_t *keydata,
1051                                     void *dbdata)
1052 {
1053         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1054         TALLOC_CTX *tmp_ctx;
1055         DATA_BLOB ap_req;
1056         struct cli_credentials *server_credentials;
1057         char *keytab_name;
1058         int ret;
1059         int ldb_ret;
1060         NTSTATUS nt_status;
1061         struct gensec_security *gensec_ctx;
1062         struct auth_session_info *session_info;
1063         struct ldb_dn *dn;
1064         isc_result_t result;
1065         struct ldb_result *res;
1066         const char * attrs[] = { NULL };
1067         uint32_t access_mask;
1068
1069         /* Remove cached credentials, if any */
1070         if (state->session_info) {
1071                 talloc_free(state->session_info);
1072                 state->session_info = NULL;
1073         }
1074         if (state->update_name) {
1075                 talloc_free(state->update_name);
1076                 state->update_name = NULL;
1077         }
1078
1079         tmp_ctx = talloc_new(NULL);
1080         if (tmp_ctx == NULL) {
1081                 state->log(ISC_LOG_ERROR, "samba_dlz: no memory");
1082                 return false;
1083         }
1084
1085         ap_req = data_blob_const(keydata, keydatalen);
1086         server_credentials = cli_credentials_init(tmp_ctx);
1087         if (!server_credentials) {
1088                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to init server credentials");
1089                 talloc_free(tmp_ctx);
1090                 return false;
1091         }
1092
1093         cli_credentials_set_krb5_context(server_credentials, state->smb_krb5_ctx);
1094         cli_credentials_set_conf(server_credentials, state->lp);
1095
1096         keytab_name = talloc_asprintf(tmp_ctx, "file:%s/dns.keytab",
1097                                         lpcfg_private_dir(state->lp));
1098         ret = cli_credentials_set_keytab_name(server_credentials, state->lp, keytab_name,
1099                                                 CRED_SPECIFIED);
1100         if (ret != 0) {
1101                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to obtain server credentials from %s",
1102                            keytab_name);
1103                 talloc_free(tmp_ctx);
1104                 return false;
1105         }
1106         talloc_free(keytab_name);
1107
1108         nt_status = gensec_server_start(tmp_ctx,
1109                                         lpcfg_gensec_settings(tmp_ctx, state->lp),
1110                                         NULL, &gensec_ctx);
1111         if (!NT_STATUS_IS_OK(nt_status)) {
1112                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to start gensec server");
1113                 talloc_free(tmp_ctx);
1114                 return false;
1115         }
1116
1117         gensec_set_credentials(gensec_ctx, server_credentials);
1118
1119         nt_status = gensec_start_mech_by_name(gensec_ctx, "spnego");
1120         if (!NT_STATUS_IS_OK(nt_status)) {
1121                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to start spnego");
1122                 talloc_free(tmp_ctx);
1123                 return false;
1124         }
1125
1126         nt_status = gensec_update(gensec_ctx, tmp_ctx, state->ev_ctx, ap_req, &ap_req);
1127         if (!NT_STATUS_IS_OK(nt_status)) {
1128                 state->log(ISC_LOG_ERROR, "samba_dlz: spnego update failed");
1129                 talloc_free(tmp_ctx);
1130                 return false;
1131         }
1132
1133         nt_status = gensec_session_info(gensec_ctx, tmp_ctx, &session_info);
1134         if (!NT_STATUS_IS_OK(nt_status)) {
1135                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to create session info");
1136                 talloc_free(tmp_ctx);
1137                 return false;
1138         }
1139
1140         /* Get the DN from name */
1141         result = b9_find_name_dn(state, name, tmp_ctx, &dn);
1142         if (result != ISC_R_SUCCESS) {
1143                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to find name %s", name);
1144                 talloc_free(tmp_ctx);
1145                 return false;
1146         }
1147
1148         /* make sure the dn exists, or find parent dn in case new object is being added */
1149         ldb_ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_BASE,
1150                                 attrs, "objectClass=dnsNode");
1151         if (ldb_ret == LDB_ERR_NO_SUCH_OBJECT) {
1152                 ldb_dn_remove_child_components(dn, 1);
1153                 access_mask = SEC_ADS_CREATE_CHILD;
1154                 talloc_free(res);
1155         } else if (ldb_ret == LDB_SUCCESS) {
1156                 access_mask = SEC_STD_REQUIRED | SEC_ADS_SELF_WRITE;
1157                 talloc_free(res);
1158         } else {
1159                 talloc_free(tmp_ctx);
1160                 return false;
1161         }
1162
1163         /* Do ACL check */
1164         ldb_ret = dsdb_check_access_on_dn(state->samdb, tmp_ctx, dn,
1165                                                 session_info->security_token,
1166                                                 access_mask, NULL);
1167         if (ldb_ret != LDB_SUCCESS) {
1168                 state->log(ISC_LOG_INFO,
1169                         "samba_dlz: disallowing update of signer=%s name=%s type=%s error=%s",
1170                         signer, name, type, ldb_strerror(ldb_ret));
1171                 talloc_free(tmp_ctx);
1172                 return false;
1173         }
1174
1175         /* Cache session_info, so it can be used in the actual add/delete operation */
1176         state->update_name = talloc_strdup(state, name);
1177         if (state->update_name == NULL) {
1178                 state->log(ISC_LOG_ERROR, "samba_dlz: memory allocation error");
1179                 talloc_free(tmp_ctx);
1180                 return false;
1181         }
1182         state->session_info = talloc_steal(state, session_info);
1183
1184         state->log(ISC_LOG_INFO, "samba_dlz: allowing update of signer=%s name=%s tcpaddr=%s type=%s key=%s",
1185                    signer, name, tcpaddr, type, key);
1186
1187         talloc_free(tmp_ctx);
1188         return true;
1189 }
1190
1191
1192 /*
1193   add a new record
1194  */
1195 static isc_result_t b9_add_record(struct dlz_bind9_data *state, const char *name,
1196                                   struct ldb_dn *dn,
1197                                   struct dnsp_DnssrvRpcRecord *rec)
1198 {
1199         struct ldb_message *msg;
1200         enum ndr_err_code ndr_err;
1201         struct ldb_val v;
1202         int ret;
1203
1204         msg = ldb_msg_new(rec);
1205         if (msg == NULL) {
1206                 return ISC_R_NOMEMORY;
1207         }
1208         msg->dn = dn;
1209         ret = ldb_msg_add_string(msg, "objectClass", "dnsNode");
1210         if (ret != LDB_SUCCESS) {
1211                 return ISC_R_FAILURE;
1212         }
1213
1214         ndr_err = ndr_push_struct_blob(&v, rec, rec, (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
1215         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1216                 return ISC_R_FAILURE;
1217         }
1218         ret = ldb_msg_add_value(msg, "dnsRecord", &v, NULL);
1219         if (ret != LDB_SUCCESS) {
1220                 return ISC_R_FAILURE;
1221         }
1222
1223         ret = ldb_add(state->samdb, msg);
1224         if (ret != LDB_SUCCESS) {
1225                 return ISC_R_FAILURE;
1226         }
1227
1228         return ISC_R_SUCCESS;
1229 }
1230
1231 /*
1232   see if two DNS names are the same
1233  */
1234 static bool dns_name_equal(const char *name1, const char *name2)
1235 {
1236         size_t len1 = strlen(name1);
1237         size_t len2 = strlen(name2);
1238         if (name1[len1-1] == '.') len1--;
1239         if (name2[len2-1] == '.') len2--;
1240         if (len1 != len2) {
1241                 return false;
1242         }
1243         return strncasecmp_m(name1, name2, len1) == 0;
1244 }
1245
1246
1247 /*
1248   see if two dns records match
1249  */
1250 static bool b9_record_match(struct dlz_bind9_data *state,
1251                             struct dnsp_DnssrvRpcRecord *rec1, struct dnsp_DnssrvRpcRecord *rec2)
1252 {
1253         if (rec1->wType != rec2->wType) {
1254                 return false;
1255         }
1256         /* see if this type is single valued */
1257         if (b9_single_valued(rec1->wType)) {
1258                 return true;
1259         }
1260
1261         /* see if the data matches */
1262         switch (rec1->wType) {
1263         case DNS_TYPE_A:
1264                 return strcmp(rec1->data.ipv4, rec2->data.ipv4) == 0;
1265         case DNS_TYPE_AAAA:
1266                 return strcmp(rec1->data.ipv6, rec2->data.ipv6) == 0;
1267         case DNS_TYPE_CNAME:
1268                 return dns_name_equal(rec1->data.cname, rec2->data.cname);
1269         case DNS_TYPE_TXT:
1270                 return strcmp(rec1->data.txt, rec2->data.txt) == 0;
1271         case DNS_TYPE_PTR:
1272                 return strcmp(rec1->data.ptr, rec2->data.ptr) == 0;
1273         case DNS_TYPE_NS:
1274                 return dns_name_equal(rec1->data.ns, rec2->data.ns);
1275
1276         case DNS_TYPE_SRV:
1277                 return rec1->data.srv.wPriority == rec2->data.srv.wPriority &&
1278                         rec1->data.srv.wWeight  == rec2->data.srv.wWeight &&
1279                         rec1->data.srv.wPort    == rec2->data.srv.wPort &&
1280                         dns_name_equal(rec1->data.srv.nameTarget, rec2->data.srv.nameTarget);
1281
1282         case DNS_TYPE_MX:
1283                 return rec1->data.mx.wPriority == rec2->data.mx.wPriority &&
1284                         dns_name_equal(rec1->data.mx.nameTarget, rec2->data.mx.nameTarget);
1285
1286         case DNS_TYPE_HINFO:
1287                 return strcmp(rec1->data.hinfo.cpu, rec2->data.hinfo.cpu) == 0 &&
1288                         strcmp(rec1->data.hinfo.os, rec2->data.hinfo.os) == 0;
1289
1290         case DNS_TYPE_SOA:
1291                 return dns_name_equal(rec1->data.soa.mname, rec2->data.soa.mname) &&
1292                         dns_name_equal(rec1->data.soa.rname, rec2->data.soa.rname) &&
1293                         rec1->data.soa.serial == rec2->data.soa.serial &&
1294                         rec1->data.soa.refresh == rec2->data.soa.refresh &&
1295                         rec1->data.soa.retry == rec2->data.soa.retry &&
1296                         rec1->data.soa.expire == rec2->data.soa.expire &&
1297                         rec1->data.soa.minimum == rec2->data.soa.minimum;
1298         default:
1299                 state->log(ISC_LOG_ERROR, "samba b9_putrr: unhandled record type %u",
1300                            rec1->wType);
1301                 break;
1302         }
1303
1304         return false;
1305 }
1306
1307 /*
1308  * Update session_info on samdb using the cached credentials
1309  */
1310 static bool b9_set_session_info(struct dlz_bind9_data *state, const char *name)
1311 {
1312         int ret;
1313
1314         if (state->update_name == NULL || state->session_info == NULL) {
1315                 state->log(ISC_LOG_ERROR, "samba_dlz: invalid credentials");
1316                 return false;
1317         }
1318
1319         /* Do not use client credentials, if we not updating the client specified name */
1320         if (strcmp(state->update_name, name) != 0) {
1321                 return true;
1322         }
1323
1324         ret = ldb_set_opaque(state->samdb, "sessionInfo", state->session_info);
1325         if (ret != LDB_SUCCESS) {
1326                 state->log(ISC_LOG_ERROR, "samba_dlz: unable to set session info");
1327                 return false;
1328         }
1329
1330         return true;
1331 }
1332
1333 /*
1334  * Reset session_info on samdb as system session
1335  */
1336 static void b9_reset_session_info(struct dlz_bind9_data *state)
1337 {
1338         ldb_set_opaque(state->samdb, "sessionInfo", system_session(state->lp));
1339 }
1340
1341 /*
1342   add or modify a rdataset
1343  */
1344 _PUBLIC_ isc_result_t dlz_addrdataset(const char *name, const char *rdatastr, void *dbdata, void *version)
1345 {
1346         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1347         struct dnsp_DnssrvRpcRecord *rec;
1348         struct ldb_dn *dn;
1349         isc_result_t result;
1350         struct ldb_result *res;
1351         const char *attrs[] = { "dnsRecord", NULL };
1352         int ret, i;
1353         struct ldb_message_element *el;
1354         enum ndr_err_code ndr_err;
1355         NTTIME t;
1356
1357         if (state->transaction_token != (void*)version) {
1358                 state->log(ISC_LOG_INFO, "samba_dlz: bad transaction version");
1359                 return ISC_R_FAILURE;
1360         }
1361
1362         rec = talloc_zero(state, struct dnsp_DnssrvRpcRecord);
1363         if (rec == NULL) {
1364                 return ISC_R_NOMEMORY;
1365         }
1366
1367         unix_to_nt_time(&t, time(NULL));
1368         t /= 10*1000*1000; /* convert to seconds (NT time is in 100ns units) */
1369         t /= 3600;         /* convert to hours */
1370
1371         rec->rank        = DNS_RANK_ZONE;
1372         rec->dwSerial    = state->soa_serial;
1373         rec->dwTimeStamp = (uint32_t)t;
1374
1375         if (!b9_parse(state, rdatastr, rec)) {
1376                 state->log(ISC_LOG_INFO, "samba_dlz: failed to parse rdataset '%s'", rdatastr);
1377                 talloc_free(rec);
1378                 return ISC_R_FAILURE;
1379         }
1380
1381         /* find the DN of the record */
1382         result = b9_find_name_dn(state, name, rec, &dn);
1383         if (result != ISC_R_SUCCESS) {
1384                 talloc_free(rec);
1385                 return result;
1386         }
1387
1388         /* get any existing records */
1389         ret = ldb_search(state->samdb, rec, &res, dn, LDB_SCOPE_BASE, attrs, "objectClass=dnsNode");
1390         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1391                 if (!b9_set_session_info(state, name)) {
1392                         talloc_free(rec);
1393                         return ISC_R_FAILURE;
1394                 }
1395                 result = b9_add_record(state, name, dn, rec);
1396                 b9_reset_session_info(state);
1397                 talloc_free(rec);
1398                 if (result == ISC_R_SUCCESS) {
1399                         state->log(ISC_LOG_ERROR, "samba_dlz: added %s %s", name, rdatastr);
1400                 }
1401                 return result;
1402         }
1403
1404         /* there are existing records. We need to see if this will
1405          * replace a record or add to it
1406          */
1407         el = ldb_msg_find_element(res->msgs[0], "dnsRecord");
1408         if (el == NULL) {
1409                 state->log(ISC_LOG_ERROR, "samba_dlz: no dnsRecord attribute for %s",
1410                            ldb_dn_get_linearized(dn));
1411                 talloc_free(rec);
1412                 return ISC_R_FAILURE;
1413         }
1414
1415         for (i=0; i<el->num_values; i++) {
1416                 struct dnsp_DnssrvRpcRecord rec2;
1417
1418                 ndr_err = ndr_pull_struct_blob(&el->values[i], rec, &rec2,
1419                                                (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
1420                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1421                         state->log(ISC_LOG_ERROR, "samba_dlz: failed to parse dnsRecord for %s",
1422                                    ldb_dn_get_linearized(dn));
1423                         talloc_free(rec);
1424                         return ISC_R_FAILURE;
1425                 }
1426
1427                 if (b9_record_match(state, rec, &rec2)) {
1428                         break;
1429                 }
1430         }
1431         if (i == el->num_values) {
1432                 /* adding a new value */
1433                 el->values = talloc_realloc(el, el->values, struct ldb_val, el->num_values+1);
1434                 if (el->values == NULL) {
1435                         talloc_free(rec);
1436                         return ISC_R_NOMEMORY;
1437                 }
1438                 el->num_values++;
1439         }
1440
1441         ndr_err = ndr_push_struct_blob(&el->values[i], rec, rec,
1442                                        (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
1443         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1444                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to push dnsRecord for %s",
1445                            ldb_dn_get_linearized(dn));
1446                 talloc_free(rec);
1447                 return ISC_R_FAILURE;
1448         }
1449
1450
1451         if (!b9_set_session_info(state, name)) {
1452                 talloc_free(rec);
1453                 return ISC_R_FAILURE;
1454         }
1455
1456         /* modify the record */
1457         el->flags = LDB_FLAG_MOD_REPLACE;
1458         ret = ldb_modify(state->samdb, res->msgs[0]);
1459         b9_reset_session_info(state);
1460         if (ret != LDB_SUCCESS) {
1461                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to modify %s - %s",
1462                            ldb_dn_get_linearized(dn), ldb_errstring(state->samdb));
1463                 talloc_free(rec);
1464                 return ISC_R_FAILURE;
1465         }
1466
1467         state->log(ISC_LOG_INFO, "samba_dlz: added rdataset %s '%s'", name, rdatastr);
1468
1469         talloc_free(rec);
1470         return ISC_R_SUCCESS;
1471 }
1472
1473 /*
1474   remove a rdataset
1475  */
1476 _PUBLIC_ isc_result_t dlz_subrdataset(const char *name, const char *rdatastr, void *dbdata, void *version)
1477 {
1478         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1479         struct dnsp_DnssrvRpcRecord *rec;
1480         struct ldb_dn *dn;
1481         isc_result_t result;
1482         struct ldb_result *res;
1483         const char *attrs[] = { "dnsRecord", NULL };
1484         int ret, i;
1485         struct ldb_message_element *el;
1486         enum ndr_err_code ndr_err;
1487
1488         if (state->transaction_token != (void*)version) {
1489                 state->log(ISC_LOG_INFO, "samba_dlz: bad transaction version");
1490                 return ISC_R_FAILURE;
1491         }
1492
1493         rec = talloc_zero(state, struct dnsp_DnssrvRpcRecord);
1494         if (rec == NULL) {
1495                 return ISC_R_NOMEMORY;
1496         }
1497
1498         if (!b9_parse(state, rdatastr, rec)) {
1499                 state->log(ISC_LOG_INFO, "samba_dlz: failed to parse rdataset '%s'", rdatastr);
1500                 talloc_free(rec);
1501                 return ISC_R_FAILURE;
1502         }
1503
1504         /* find the DN of the record */
1505         result = b9_find_name_dn(state, name, rec, &dn);
1506         if (result != ISC_R_SUCCESS) {
1507                 talloc_free(rec);
1508                 return result;
1509         }
1510
1511         /* get the existing records */
1512         ret = ldb_search(state->samdb, rec, &res, dn, LDB_SCOPE_BASE, attrs, "objectClass=dnsNode");
1513         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1514                 talloc_free(rec);
1515                 return ISC_R_NOTFOUND;
1516         }
1517
1518         /* there are existing records. We need to see if any match
1519          */
1520         el = ldb_msg_find_element(res->msgs[0], "dnsRecord");
1521         if (el == NULL || el->num_values == 0) {
1522                 state->log(ISC_LOG_ERROR, "samba_dlz: no dnsRecord attribute for %s",
1523                            ldb_dn_get_linearized(dn));
1524                 talloc_free(rec);
1525                 return ISC_R_FAILURE;
1526         }
1527
1528         for (i=0; i<el->num_values; i++) {
1529                 struct dnsp_DnssrvRpcRecord rec2;
1530
1531                 ndr_err = ndr_pull_struct_blob(&el->values[i], rec, &rec2,
1532                                                (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
1533                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1534                         state->log(ISC_LOG_ERROR, "samba_dlz: failed to parse dnsRecord for %s",
1535                                    ldb_dn_get_linearized(dn));
1536                         talloc_free(rec);
1537                         return ISC_R_FAILURE;
1538                 }
1539
1540                 if (b9_record_match(state, rec, &rec2)) {
1541                         break;
1542                 }
1543         }
1544         if (i == el->num_values) {
1545                 talloc_free(rec);
1546                 return ISC_R_NOTFOUND;
1547         }
1548
1549         if (i < el->num_values-1) {
1550                 memmove(&el->values[i], &el->values[i+1], sizeof(el->values[0])*((el->num_values-1)-i));
1551         }
1552         el->num_values--;
1553
1554         if (!b9_set_session_info(state, name)) {
1555                 talloc_free(rec);
1556                 return ISC_R_FAILURE;
1557         }
1558
1559         if (el->num_values == 0) {
1560                 /* delete the record */
1561                 ret = ldb_delete(state->samdb, dn);
1562                 b9_reset_session_info(state);
1563         } else {
1564                 /* modify the record */
1565                 el->flags = LDB_FLAG_MOD_REPLACE;
1566                 ret = ldb_modify(state->samdb, res->msgs[0]);
1567         }
1568         b9_reset_session_info(state);
1569         if (ret != LDB_SUCCESS) {
1570                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to modify %s - %s",
1571                            ldb_dn_get_linearized(dn), ldb_errstring(state->samdb));
1572                 talloc_free(rec);
1573                 return ISC_R_FAILURE;
1574         }
1575
1576         state->log(ISC_LOG_INFO, "samba_dlz: subtracted rdataset %s '%s'", name, rdatastr);
1577
1578         talloc_free(rec);
1579         return ISC_R_SUCCESS;
1580 }
1581
1582
1583 /*
1584   delete all records of the given type
1585  */
1586 _PUBLIC_ isc_result_t dlz_delrdataset(const char *name, const char *type, void *dbdata, void *version)
1587 {
1588         struct dlz_bind9_data *state = talloc_get_type_abort(dbdata, struct dlz_bind9_data);
1589         TALLOC_CTX *tmp_ctx;
1590         struct ldb_dn *dn;
1591         isc_result_t result;
1592         struct ldb_result *res;
1593         const char *attrs[] = { "dnsRecord", NULL };
1594         int ret, i;
1595         struct ldb_message_element *el;
1596         enum ndr_err_code ndr_err;
1597         enum dns_record_type dns_type;
1598         bool found = false;
1599
1600         if (state->transaction_token != (void*)version) {
1601                 state->log(ISC_LOG_INFO, "samba_dlz: bad transaction version");
1602                 return ISC_R_FAILURE;
1603         }
1604
1605         if (!b9_dns_type(type, &dns_type)) {
1606                 state->log(ISC_LOG_INFO, "samba_dlz: bad dns type %s in delete", type);
1607                 return ISC_R_FAILURE;
1608         }
1609
1610         tmp_ctx = talloc_new(state);
1611
1612         /* find the DN of the record */
1613         result = b9_find_name_dn(state, name, tmp_ctx, &dn);
1614         if (result != ISC_R_SUCCESS) {
1615                 talloc_free(tmp_ctx);
1616                 return result;
1617         }
1618
1619         /* get the existing records */
1620         ret = ldb_search(state->samdb, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, "objectClass=dnsNode");
1621         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1622                 talloc_free(tmp_ctx);
1623                 return ISC_R_NOTFOUND;
1624         }
1625
1626         /* there are existing records. We need to see if any match the type
1627          */
1628         el = ldb_msg_find_element(res->msgs[0], "dnsRecord");
1629         if (el == NULL || el->num_values == 0) {
1630                 talloc_free(tmp_ctx);
1631                 return ISC_R_NOTFOUND;
1632         }
1633
1634         for (i=0; i<el->num_values; i++) {
1635                 struct dnsp_DnssrvRpcRecord rec2;
1636
1637                 ndr_err = ndr_pull_struct_blob(&el->values[i], tmp_ctx, &rec2,
1638                                                (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
1639                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1640                         state->log(ISC_LOG_ERROR, "samba_dlz: failed to parse dnsRecord for %s",
1641                                    ldb_dn_get_linearized(dn));
1642                         talloc_free(tmp_ctx);
1643                         return ISC_R_FAILURE;
1644                 }
1645
1646                 if (dns_type == rec2.wType) {
1647                         if (i < el->num_values-1) {
1648                                 memmove(&el->values[i], &el->values[i+1],
1649                                         sizeof(el->values[0])*((el->num_values-1)-i));
1650                         }
1651                         el->num_values--;
1652                         i--;
1653                         found = true;
1654                 }
1655         }
1656
1657         if (!found) {
1658                 talloc_free(tmp_ctx);
1659                 return ISC_R_FAILURE;
1660         }
1661
1662         if (!b9_set_session_info(state, name)) {
1663                 talloc_free(tmp_ctx);
1664                 return ISC_R_FAILURE;
1665         }
1666
1667         if (el->num_values == 0) {
1668                 /* delete the record */
1669                 ret = ldb_delete(state->samdb, dn);
1670         } else {
1671                 /* modify the record */
1672                 el->flags = LDB_FLAG_MOD_REPLACE;
1673                 ret = ldb_modify(state->samdb, res->msgs[0]);
1674         }
1675         b9_reset_session_info(state);
1676         if (ret != LDB_SUCCESS) {
1677                 state->log(ISC_LOG_ERROR, "samba_dlz: failed to delete type %s in %s - %s",
1678                            type, ldb_dn_get_linearized(dn), ldb_errstring(state->samdb));
1679                 talloc_free(tmp_ctx);
1680                 return ISC_R_FAILURE;
1681         }
1682
1683         state->log(ISC_LOG_INFO, "samba_dlz: deleted rdataset %s of type %s", name, type);
1684
1685         talloc_free(tmp_ctx);
1686         return ISC_R_SUCCESS;
1687 }