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