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