3e161f81ac7699599782ab3f53254df99e7959b5
[metze/samba/wip.git] / source4 / dns_server / dnsserver_common.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    DNS server utils
5
6    Copyright (C) 2010 Kai Blin
7    Copyright (C) 2014 Stefan Metzmacher
8    Copyright (C) 2015 Andrew Bartlett
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24 #include "includes.h"
25 #include "libcli/util/ntstatus.h"
26 #include "libcli/util/werror.h"
27 #include "librpc/ndr/libndr.h"
28 #include "librpc/gen_ndr/ndr_dns.h"
29 #include "librpc/gen_ndr/ndr_dnsp.h"
30 #include <ldb.h>
31 #include "dsdb/samdb/samdb.h"
32 #include "dsdb/common/util.h"
33 #include "dns_server/dnsserver_common.h"
34 #include "lib/util/dlinklist.h"
35
36 #undef DBGC_CLASS
37 #define DBGC_CLASS DBGC_DNS
38
39 uint8_t werr_to_dns_err(WERROR werr)
40 {
41         if (W_ERROR_EQUAL(WERR_OK, werr)) {
42                 return DNS_RCODE_OK;
43         } else if (W_ERROR_EQUAL(DNS_ERR(FORMAT_ERROR), werr)) {
44                 return DNS_RCODE_FORMERR;
45         } else if (W_ERROR_EQUAL(DNS_ERR(SERVER_FAILURE), werr)) {
46                 return DNS_RCODE_SERVFAIL;
47         } else if (W_ERROR_EQUAL(DNS_ERR(NAME_ERROR), werr)) {
48                 return DNS_RCODE_NXDOMAIN;
49         } else if (W_ERROR_EQUAL(WERR_DNS_ERROR_NAME_DOES_NOT_EXIST, werr)) {
50                 return DNS_RCODE_NXDOMAIN;
51         } else if (W_ERROR_EQUAL(DNS_ERR(NOT_IMPLEMENTED), werr)) {
52                 return DNS_RCODE_NOTIMP;
53         } else if (W_ERROR_EQUAL(DNS_ERR(REFUSED), werr)) {
54                 return DNS_RCODE_REFUSED;
55         } else if (W_ERROR_EQUAL(DNS_ERR(YXDOMAIN), werr)) {
56                 return DNS_RCODE_YXDOMAIN;
57         } else if (W_ERROR_EQUAL(DNS_ERR(YXRRSET), werr)) {
58                 return DNS_RCODE_YXRRSET;
59         } else if (W_ERROR_EQUAL(DNS_ERR(NXRRSET), werr)) {
60                 return DNS_RCODE_NXRRSET;
61         } else if (W_ERROR_EQUAL(DNS_ERR(NOTAUTH), werr)) {
62                 return DNS_RCODE_NOTAUTH;
63         } else if (W_ERROR_EQUAL(DNS_ERR(NOTZONE), werr)) {
64                 return DNS_RCODE_NOTZONE;
65         } else if (W_ERROR_EQUAL(DNS_ERR(BADKEY), werr)) {
66                 return DNS_RCODE_BADKEY;
67         }
68         DEBUG(5, ("No mapping exists for %s\n", win_errstr(werr)));
69         return DNS_RCODE_SERVFAIL;
70 }
71
72 WERROR dns_common_extract(struct ldb_context *samdb,
73                           const struct ldb_message_element *el,
74                           TALLOC_CTX *mem_ctx,
75                           struct dnsp_DnssrvRpcRecord **records,
76                           uint16_t *num_records)
77 {
78         uint16_t ri;
79         struct dnsp_DnssrvRpcRecord *recs;
80
81         *records = NULL;
82         *num_records = 0;
83
84         recs = talloc_zero_array(mem_ctx, struct dnsp_DnssrvRpcRecord,
85                                  el->num_values);
86         if (recs == NULL) {
87                 return WERR_NOT_ENOUGH_MEMORY;
88         }
89         for (ri = 0; ri < el->num_values; ri++) {
90                 bool am_rodc;
91                 int ret;
92                 const char *dnsHostName = NULL;
93                 struct ldb_val *v = &el->values[ri];
94                 enum ndr_err_code ndr_err;
95                 ndr_err = ndr_pull_struct_blob(v, recs, &recs[ri],
96                                 (ndr_pull_flags_fn_t)ndr_pull_dnsp_DnssrvRpcRecord);
97                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
98                         TALLOC_FREE(recs);
99                         DEBUG(0, ("Failed to grab dnsp_DnssrvRpcRecord\n"));
100                         return DNS_ERR(SERVER_FAILURE);
101                 }
102
103                 /*
104                  * In AD, except on an RODC (where we should list a random RWDC,
105                  * we should over-stamp the MNAME with our own hostname
106                  */
107                 if (recs[ri].wType != DNS_TYPE_SOA) {
108                         continue;
109                 }
110
111                 ret = samdb_rodc(samdb, &am_rodc);
112                 if (ret != LDB_SUCCESS) {
113                         DEBUG(0, ("Failed to confirm we are not an RODC: %s\n",
114                                   ldb_errstring(samdb)));
115                         return DNS_ERR(SERVER_FAILURE);
116                 }
117
118                 if (am_rodc) {
119                         continue;
120                 }
121
122                 ret = samdb_dns_host_name(samdb, &dnsHostName);
123                 if (ret != LDB_SUCCESS || dnsHostName == NULL) {
124                         DEBUG(0, ("Failed to get dnsHostName from rootDSE"));
125                         return DNS_ERR(SERVER_FAILURE);
126                 }
127
128                 recs[ri].data.soa.mname = talloc_strdup(recs, dnsHostName);
129         }
130
131         *records = recs;
132         *num_records = el->num_values;
133         return WERR_OK;
134 }
135
136 /*
137  * Lookup a DNS record, performing an exact match.
138  * i.e. DNS wild card records are not considered.
139  */
140 WERROR dns_common_lookup(struct ldb_context *samdb,
141                          TALLOC_CTX *mem_ctx,
142                          struct ldb_dn *dn,
143                          struct dnsp_DnssrvRpcRecord **records,
144                          uint16_t *num_records,
145                          bool *tombstoned)
146 {
147         static const char * const attrs[] = {
148                 "dnsRecord",
149                 "dNSTombstoned",
150                 NULL
151         };
152         int ret;
153         WERROR werr;
154         struct ldb_message *msg = NULL;
155         struct ldb_message_element *el;
156
157         *records = NULL;
158         *num_records = 0;
159
160         if (tombstoned != NULL) {
161                 *tombstoned = false;
162                 ret = dsdb_search_one(samdb, mem_ctx, &msg, dn,
163                         LDB_SCOPE_BASE, attrs, 0,
164                         "(objectClass=dnsNode)");
165         } else {
166                 ret = dsdb_search_one(samdb, mem_ctx, &msg, dn,
167                         LDB_SCOPE_BASE, attrs, 0,
168                         "(&(objectClass=dnsNode)(!(dNSTombstoned=TRUE)))");
169         }
170         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
171                 return WERR_DNS_ERROR_NAME_DOES_NOT_EXIST;
172         }
173         if (ret != LDB_SUCCESS) {
174                 /* TODO: we need to check if there's a glue record we need to
175                  * create a referral to */
176                 return DNS_ERR(NAME_ERROR);
177         }
178
179         if (tombstoned != NULL) {
180                 *tombstoned = ldb_msg_find_attr_as_bool(msg,
181                                         "dNSTombstoned", false);
182         }
183
184         el = ldb_msg_find_element(msg, "dnsRecord");
185         if (el == NULL) {
186                 TALLOC_FREE(msg);
187                 /*
188                  * records produced by older Samba releases
189                  * keep dnsNode objects without dnsRecord and
190                  * without setting dNSTombstoned=TRUE.
191                  *
192                  * We just pretend they're tombstones.
193                  */
194                 if (tombstoned != NULL) {
195                         struct dnsp_DnssrvRpcRecord *recs;
196                         recs = talloc_array(mem_ctx,
197                                             struct dnsp_DnssrvRpcRecord,
198                                             1);
199                         if (recs == NULL) {
200                                 return WERR_NOT_ENOUGH_MEMORY;
201                         }
202                         recs[0] = (struct dnsp_DnssrvRpcRecord) {
203                                 .wType = DNS_TYPE_TOMBSTONE,
204                                 /*
205                                  * A value of timestamp != 0
206                                  * indicated that the object was already
207                                  * a tombstone, this will be used
208                                  * in dns_common_replace()
209                                  */
210                                 .data.timestamp = 1,
211                         };
212
213                         *tombstoned = true;
214                         *records = recs;
215                         *num_records = 1;
216                         return WERR_OK;
217                 } else {
218                         /*
219                          * Because we are not looking for a tombstone
220                          * in this codepath, we just pretend it does
221                          * not exist at all.
222                          */
223                         return WERR_DNS_ERROR_NAME_DOES_NOT_EXIST;
224                 }
225         }
226
227         werr = dns_common_extract(samdb, el, mem_ctx, records, num_records);
228         TALLOC_FREE(msg);
229         if (!W_ERROR_IS_OK(werr)) {
230                 return werr;
231         }
232
233         return WERR_OK;
234 }
235
236 /*
237  * Build an ldb_parse_tree node for an equality check
238  *
239  * Note: name is assumed to have been validated by dns_name_check
240  *       so will be zero terminated and of a reasonable size.
241  */
242 static struct ldb_parse_tree *build_equality_operation(
243         TALLOC_CTX *mem_ctx,
244         bool add_asterix,     /* prepend an '*' to the name          */
245         const uint8_t *name,  /* the value being matched             */
246         const char *attr,     /* the attribute to check name against */
247         size_t size)          /* length of name                      */
248 {
249
250         struct ldb_parse_tree *el = NULL;  /* Equality node being built */
251         struct ldb_val *value = NULL;      /* Value the attr will be compared
252                                               with */
253         size_t length = 0;                 /* calculated length of the value
254                                               including option '*' prefix and
255                                               '\0' string terminator */
256
257         el = talloc(mem_ctx, struct ldb_parse_tree);
258         if (el == NULL) {
259                 DBG_ERR("Unable to allocate ldb_parse_tree\n");
260                 return NULL;
261         }
262
263         el->operation = LDB_OP_EQUALITY;
264         el->u.equality.attr = talloc_strdup(mem_ctx, attr);
265         value = &el->u.equality.value;
266         length = (add_asterix) ? size + 2 : size + 1;
267         value->data = talloc_zero_array(el, uint8_t, length);
268         if (el == NULL) {
269                 DBG_ERR("Unable to allocate value->data\n");
270                 TALLOC_FREE(el);
271                 return NULL;
272         }
273
274         value->length = length;
275         if (add_asterix) {
276                 value->data[0] = '*';
277                 memcpy(&value->data[1], name, size);
278         } else {
279                 memcpy(value->data, name, size);
280         }
281         return el;
282 }
283
284 /*
285  * Determine the number of levels in name
286  * essentially the number of '.'s in the name + 1
287  *
288  * name is assumed to have been validated by dns_name_check
289  */
290 static unsigned int number_of_labels(const struct ldb_val *name) {
291         int x  = 0;
292         unsigned int labels = 1;
293         for (x = 0; x < name->length; x++) {
294                 if (name->data[x] == '.') {
295                         labels++;
296                 }
297         }
298         return labels;
299 }
300 /*
301  * Build a query that matches the target name, and any possible
302  * DNS wild card entries
303  *
304  * Builds a parse tree equivalent to the example query.
305  *
306  * x.y.z -> (|(name=x.y.z)(name=\2a.y.z)(name=\2a.z)(name=\2a))
307  *
308  * The attribute 'name' is used as this is what the LDB index is on
309  * (the RDN, being 'dc' in this use case, does not have an index in
310  * the AD schema).
311  *
312  * Returns NULL if unable to build the query.
313  *
314  * The first component of the DN is assumed to be the name being looked up
315  * and also that it has been validated by dns_name_check
316  *
317  */
318 #define BASE "(&(objectClass=dnsNode)(!(dNSTombstoned=TRUE))(|(a=b)(c=d)))"
319 static struct ldb_parse_tree *build_wildcard_query(
320         TALLOC_CTX *mem_ctx,
321         struct ldb_dn *dn)
322 {
323         const struct ldb_val *name = NULL;            /* The DNS name being
324                                                          queried */
325         const char *attr = "name";                    /* The attribute name */
326         struct ldb_parse_tree *query = NULL;          /* The constructed query
327                                                          parse tree*/
328         struct ldb_parse_tree *wildcard_query = NULL; /* The parse tree for the
329                                                          name and wild card
330                                                          entries */
331         int labels = 0;         /* The number of labels in the name */
332
333         name = ldb_dn_get_rdn_val(dn);
334         if (name == NULL) {
335                 DBG_ERR("Unable to get domain name value\n");
336                 return NULL;
337         }
338         labels = number_of_labels(name);
339
340         query = ldb_parse_tree(mem_ctx, BASE);
341         if (query == NULL) {
342                 DBG_ERR("Unable to parse query %s\n", BASE);
343                 return NULL;
344         }
345
346         /*
347          * The 3rd element of BASE is a place holder which is replaced with
348          * the actual wild card query
349          */
350         wildcard_query = query->u.list.elements[2];
351         TALLOC_FREE(wildcard_query->u.list.elements);
352
353         wildcard_query->u.list.num_elements = labels + 1;
354         wildcard_query->u.list.elements = talloc_array(
355                 wildcard_query,
356                 struct ldb_parse_tree *,
357                 labels + 1);
358         /*
359          * Build the wild card query
360          */
361         {
362                 int x = 0;   /* current character in the name               */
363                 int l = 0;   /* current equality operator index in elements */
364                 struct ldb_parse_tree *el = NULL; /* Equality operator being
365                                                      built */
366                 bool add_asterix = true;  /* prepend an '*' to the value    */
367                 for (l = 0, x = 0; l < labels && x < name->length; l++) {
368                         unsigned int size = name->length - x;
369                         add_asterix = (name->data[x] == '.');
370                         el = build_equality_operation(
371                                 mem_ctx,
372                                 add_asterix,
373                                 &name->data[x],
374                                 attr,
375                                 size);
376                         if (el == NULL) {
377                                 return NULL;  /* Reason will have been logged */
378                         }
379                         wildcard_query->u.list.elements[l] = el;
380
381                         /* skip to the start of the next label */
382                         for (;x < name->length && name->data[x] != '.'; x++);
383                 }
384
385                 /* Add the base level "*" only query */
386                 el = build_equality_operation(mem_ctx, true, NULL, attr, 0);
387                 if (el == NULL) {
388                         TALLOC_FREE(query);
389                         return NULL;  /* Reason will have been logged */
390                 }
391                 wildcard_query->u.list.elements[l] = el;
392         }
393         return query;
394 }
395
396 /*
397  * Scan the list of records matching a dns wildcard query and return the
398  * best match.
399  *
400  * The best match is either an exact name match, or the longest wild card
401  * entry returned
402  *
403  * i.e. name = a.b.c candidates *.b.c, *.c,        - *.b.c would be selected
404  *      name = a.b.c candidates a.b.c, *.b.c, *.c  - a.b.c would be selected
405  */
406 static struct ldb_message *get_best_match(struct ldb_dn *dn,
407                                           struct ldb_result *result)
408 {
409         int matched = 0;    /* Index of the current best match in result */
410         size_t length = 0;  /* The length of the current candidate       */
411         const struct ldb_val *target = NULL;    /* value we're looking for */
412         const struct ldb_val *candidate = NULL; /* current candidate value */
413         int x = 0;
414
415         target = ldb_dn_get_rdn_val(dn);
416         for(x = 0; x < result->count; x++) {
417                 candidate = ldb_dn_get_rdn_val(result->msgs[x]->dn);
418                 if (strncasecmp((char *) target->data,
419                                 (char *) candidate->data,
420                                 target->length) == 0) {
421                         /* Exact match stop searching and return */
422                         return result->msgs[x];
423                 }
424                 if (candidate->length > length) {
425                         matched = x;
426                         length  = candidate->length;
427                 }
428         }
429         return result->msgs[matched];
430 }
431
432 /*
433  * Look up a DNS entry, if an exact match does not exist, return the
434  * closest matching DNS wildcard entry if available
435  *
436  * Returns: LDB_ERR_NO_SUCH_OBJECT     If no matching record exists
437  *          LDB_ERR_OPERATIONS_ERROR   If the query fails
438  *          LDB_SUCCESS                If a matching record was retrieved
439  *
440  */
441 static int dns_wildcard_lookup(struct ldb_context *samdb,
442                                TALLOC_CTX *mem_ctx,
443                                struct ldb_dn *dn,
444                                struct ldb_message **msg)
445 {
446         static const char * const attrs[] = {
447                 "dnsRecord",
448                 "dNSTombstoned",
449                 NULL
450         };
451         struct ldb_dn *parent = NULL;     /* The parent dn                    */
452         struct ldb_result *result = NULL; /* Results of the search            */
453         int ret;                          /* Return code                      */
454         struct ldb_parse_tree *query = NULL; /* The query to run              */
455         struct ldb_request *request = NULL;  /* LDB request for the query op  */
456         struct ldb_message *match = NULL;    /* the best matching DNS record  */
457         TALLOC_CTX *frame = talloc_stackframe();
458
459         parent = ldb_dn_get_parent(frame, dn);
460         if (parent == NULL) {
461                 DBG_ERR("Unable to extract parent from dn\n");
462                 TALLOC_FREE(frame);
463                 return LDB_ERR_OPERATIONS_ERROR;
464         }
465
466         query = build_wildcard_query(frame, dn);
467         if (query == NULL) {
468                 TALLOC_FREE(frame);
469                 return LDB_ERR_OPERATIONS_ERROR;
470         }
471
472         result = talloc_zero(mem_ctx, struct ldb_result);
473         if (result == NULL) {
474                 TALLOC_FREE(frame);
475                 DBG_ERR("Unable to allocate ldb_result\n");
476                 return LDB_ERR_OPERATIONS_ERROR;
477         }
478
479         ret = ldb_build_search_req_ex(&request,
480                                       samdb,
481                                       frame,
482                                       parent,
483                                       LDB_SCOPE_ONELEVEL,
484                                       query,
485                                       attrs,
486                                       NULL,
487                                       result,
488                                       ldb_search_default_callback,
489                                       NULL);
490         if (ret != LDB_SUCCESS) {
491                 TALLOC_FREE(frame);
492                 DBG_ERR("ldb_build_search_req_ex returned %d\n", ret);
493                 return ret;
494         }
495
496         ret = ldb_request(samdb, request);
497         if (ret != LDB_SUCCESS) {
498                 TALLOC_FREE(frame);
499                 return ret;
500         }
501
502         ret = ldb_wait(request->handle, LDB_WAIT_ALL);
503         if (ret != LDB_SUCCESS) {
504                 TALLOC_FREE(frame);
505                 return ret;
506         }
507
508         if (result->count == 0) {
509                 TALLOC_FREE(frame);
510                 return LDB_ERR_NO_SUCH_OBJECT;
511         }
512
513         match = get_best_match(dn, result);
514         if (match == NULL) {
515                 TALLOC_FREE(frame);
516                 return LDB_ERR_OPERATIONS_ERROR;
517         }
518
519         *msg = talloc_move(mem_ctx, &match);
520         TALLOC_FREE(frame);
521         return LDB_SUCCESS;
522 }
523
524 /*
525  * Lookup a DNS record, will match DNS wild card records if an exact match
526  * is not found.
527  */
528 WERROR dns_common_wildcard_lookup(struct ldb_context *samdb,
529                                   TALLOC_CTX *mem_ctx,
530                                   struct ldb_dn *dn,
531                                   struct dnsp_DnssrvRpcRecord **records,
532                                   uint16_t *num_records)
533 {
534         int ret;
535         WERROR werr;
536         struct ldb_message *msg = NULL;
537         struct ldb_message_element *el = NULL;
538         const struct ldb_val *name = NULL;
539
540         *records = NULL;
541         *num_records = 0;
542
543         name = ldb_dn_get_rdn_val(dn);
544         if (name == NULL) {
545                 return DNS_ERR(NAME_ERROR);
546         }
547
548         /* Don't look for a wildcard for @ */
549         if (name->length == 1 && name->data[0] == '@') {
550                 return dns_common_lookup(samdb,
551                                          mem_ctx,
552                                          dn,
553                                          records,
554                                          num_records,
555                                          NULL);
556         }
557
558         werr =  dns_name_check(
559                         mem_ctx,
560                         strlen((const char*)name->data),
561                         (const char*) name->data);
562         if (!W_ERROR_IS_OK(werr)) {
563                 return werr;
564         }
565
566         ret = dns_wildcard_lookup(samdb, mem_ctx, dn, &msg);
567         if (ret == LDB_ERR_OPERATIONS_ERROR) {
568                 return DNS_ERR(SERVER_FAILURE);
569         }
570         if (ret != LDB_SUCCESS) {
571                 return DNS_ERR(NAME_ERROR);
572         }
573
574         el = ldb_msg_find_element(msg, "dnsRecord");
575         if (el == NULL) {
576                 return WERR_DNS_ERROR_NAME_DOES_NOT_EXIST;
577         }
578
579         werr = dns_common_extract(samdb, el, mem_ctx, records, num_records);
580         TALLOC_FREE(msg);
581         if (!W_ERROR_IS_OK(werr)) {
582                 return werr;
583         }
584
585         return WERR_OK;
586 }
587
588 static int rec_cmp(const struct dnsp_DnssrvRpcRecord *r1,
589                    const struct dnsp_DnssrvRpcRecord *r2)
590 {
591         if (r1->wType != r2->wType) {
592                 /*
593                  * The records are sorted with higher types first
594                  */
595                 return r2->wType - r1->wType;
596         }
597
598         /*
599          * Then we need to sort from the oldest to newest timestamp
600          */
601         return r1->dwTimeStamp - r2->dwTimeStamp;
602 }
603
604 /*
605  * Check for valid DNS names. These are names which:
606  *   - are non-empty
607  *   - do not start with a dot
608  *   - do not have any empty labels
609  *   - have no more than 127 labels
610  *   - are no longer than 253 characters
611  *   - none of the labels exceed 63 characters
612  */
613 WERROR dns_name_check(TALLOC_CTX *mem_ctx, size_t len, const char *name)
614 {
615         size_t i;
616         unsigned int labels    = 0;
617         unsigned int label_len = 0;
618
619         if (len == 0) {
620                 return WERR_DS_INVALID_DN_SYNTAX;
621         }
622
623         if (len > 1 && name[0] == '.') {
624                 return WERR_DS_INVALID_DN_SYNTAX;
625         }
626
627         if ((len - 1) > DNS_MAX_DOMAIN_LENGTH) {
628                 return WERR_DS_INVALID_DN_SYNTAX;
629         }
630
631         for (i = 0; i < len - 1; i++) {
632                 if (name[i] == '.' && name[i+1] == '.') {
633                         return WERR_DS_INVALID_DN_SYNTAX;
634                 }
635                 if (name[i] == '.') {
636                         labels++;
637                         if (labels > DNS_MAX_LABELS) {
638                                 return WERR_DS_INVALID_DN_SYNTAX;
639                         }
640                         label_len = 0;
641                 } else {
642                         label_len++;
643                         if (label_len > DNS_MAX_LABEL_LENGTH) {
644                                 return WERR_DS_INVALID_DN_SYNTAX;
645                         }
646                 }
647         }
648
649         return WERR_OK;
650 }
651
652 static WERROR check_name_list(TALLOC_CTX *mem_ctx, uint16_t rec_count,
653                               struct dnsp_DnssrvRpcRecord *records)
654 {
655         WERROR werr;
656         uint16_t i;
657         size_t len;
658         struct dnsp_DnssrvRpcRecord record;
659
660         werr = WERR_OK;
661         for (i = 0; i < rec_count; i++) {
662                 record = records[i];
663
664                 switch (record.wType) {
665
666                 case DNS_TYPE_NS:
667                         len = strlen(record.data.ns);
668                         werr = dns_name_check(mem_ctx, len, record.data.ns);
669                         break;
670                 case DNS_TYPE_CNAME:
671                         len = strlen(record.data.cname);
672                         werr = dns_name_check(mem_ctx, len, record.data.cname);
673                         break;
674                 case DNS_TYPE_SOA:
675                         len = strlen(record.data.soa.mname);
676                         werr = dns_name_check(mem_ctx, len, record.data.soa.mname);
677                         if (!W_ERROR_IS_OK(werr)) {
678                                 break;
679                         }
680                         len = strlen(record.data.soa.rname);
681                         werr = dns_name_check(mem_ctx, len, record.data.soa.rname);
682                         break;
683                 case DNS_TYPE_PTR:
684                         len = strlen(record.data.ptr);
685                         werr = dns_name_check(mem_ctx, len, record.data.ptr);
686                         break;
687                 case DNS_TYPE_MX:
688                         len = strlen(record.data.mx.nameTarget);
689                         werr = dns_name_check(mem_ctx, len, record.data.mx.nameTarget);
690                         break;
691                 case DNS_TYPE_SRV:
692                         len = strlen(record.data.srv.nameTarget);
693                         werr = dns_name_check(mem_ctx, len,
694                                               record.data.srv.nameTarget);
695                         break;
696                 /*
697                  * In the default case, the record doesn't have a DN, so it
698                  * must be ok.
699                  */
700                 default:
701                         break;
702                 }
703
704                 if (!W_ERROR_IS_OK(werr)) {
705                         return werr;
706                 }
707         }
708
709         return WERR_OK;
710 }
711
712 WERROR dns_common_replace(struct ldb_context *samdb,
713                           TALLOC_CTX *mem_ctx,
714                           struct ldb_dn *dn,
715                           bool needs_add,
716                           uint32_t serial,
717                           struct dnsp_DnssrvRpcRecord *records,
718                           uint16_t rec_count)
719 {
720         struct ldb_message_element *el;
721         uint16_t i;
722         int ret;
723         WERROR werr;
724         struct ldb_message *msg = NULL;
725         bool was_tombstoned = false;
726         bool become_tombstoned = false;
727
728         msg = ldb_msg_new(mem_ctx);
729         W_ERROR_HAVE_NO_MEMORY(msg);
730
731         msg->dn = dn;
732
733         werr = check_name_list(mem_ctx, rec_count, records);
734         if (!W_ERROR_IS_OK(werr)) {
735                 return werr;
736         }
737
738         ret = ldb_msg_add_empty(msg, "dnsRecord", LDB_FLAG_MOD_REPLACE, &el);
739         if (ret != LDB_SUCCESS) {
740                 return DNS_ERR(SERVER_FAILURE);
741         }
742
743         /*
744          * we have at least one value,
745          * which might be used for the tombstone marker
746          */
747         el->values = talloc_zero_array(el, struct ldb_val, MAX(1, rec_count));
748         if (rec_count > 0) {
749                 W_ERROR_HAVE_NO_MEMORY(el->values);
750
751                 /*
752                  * We store a sorted list with the high wType values first
753                  * that's what windows does. It also simplifies the
754                  * filtering of DNS_TYPE_TOMBSTONE records
755                  */
756                 TYPESAFE_QSORT(records, rec_count, rec_cmp);
757         }
758
759         for (i = 0; i < rec_count; i++) {
760                 struct ldb_val *v = &el->values[el->num_values];
761                 enum ndr_err_code ndr_err;
762
763                 if (records[i].wType == DNS_TYPE_TOMBSTONE) {
764                         if (records[i].data.timestamp != 0) {
765                                 was_tombstoned = true;
766                         }
767                         continue;
768                 }
769
770                 records[i].dwSerial = serial;
771                 ndr_err = ndr_push_struct_blob(v, el->values, &records[i],
772                                 (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
773                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
774                         DEBUG(0, ("Failed to push dnsp_DnssrvRpcRecord\n"));
775                         return DNS_ERR(SERVER_FAILURE);
776                 }
777                 el->num_values++;
778         }
779
780         if (needs_add) {
781                 if (el->num_values == 0) {
782                         return WERR_OK;
783                 }
784
785                 ret = ldb_msg_add_string(msg, "objectClass", "dnsNode");
786                 if (ret != LDB_SUCCESS) {
787                         return DNS_ERR(SERVER_FAILURE);
788                 }
789
790                 ret = ldb_add(samdb, msg);
791                 if (ret != LDB_SUCCESS) {
792                         return DNS_ERR(SERVER_FAILURE);
793                 }
794
795                 return WERR_OK;
796         }
797
798         if (el->num_values == 0) {
799                 struct dnsp_DnssrvRpcRecord tbs;
800                 struct ldb_val *v = &el->values[el->num_values];
801                 enum ndr_err_code ndr_err;
802                 struct timeval tv;
803
804                 if (was_tombstoned) {
805                         /*
806                          * This is already a tombstoned object.
807                          * Just leave it instead of updating the time stamp.
808                          */
809                         return WERR_OK;
810                 }
811
812                 tv = timeval_current();
813                 tbs = (struct dnsp_DnssrvRpcRecord) {
814                         .wType = DNS_TYPE_TOMBSTONE,
815                         .dwSerial = serial,
816                         .data.timestamp = timeval_to_nttime(&tv),
817                 };
818
819                 ndr_err = ndr_push_struct_blob(v, el->values, &tbs,
820                                 (ndr_push_flags_fn_t)ndr_push_dnsp_DnssrvRpcRecord);
821                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
822                         DEBUG(0, ("Failed to push dnsp_DnssrvRpcRecord\n"));
823                         return DNS_ERR(SERVER_FAILURE);
824                 }
825                 el->num_values++;
826
827                 become_tombstoned = true;
828         }
829
830         if (was_tombstoned || become_tombstoned) {
831                 ret = ldb_msg_add_empty(msg, "dNSTombstoned",
832                                         LDB_FLAG_MOD_REPLACE, NULL);
833                 if (ret != LDB_SUCCESS) {
834                         return DNS_ERR(SERVER_FAILURE);
835                 }
836
837                 ret = ldb_msg_add_fmt(msg, "dNSTombstoned", "%s",
838                                       become_tombstoned ? "TRUE" : "FALSE");
839                 if (ret != LDB_SUCCESS) {
840                         return DNS_ERR(SERVER_FAILURE);
841                 }
842         }
843
844         ret = ldb_modify(samdb, msg);
845         if (ret != LDB_SUCCESS) {
846                 NTSTATUS nt = dsdb_ldb_err_to_ntstatus(ret);
847                 return ntstatus_to_werror(nt);
848         }
849
850         return WERR_OK;
851 }
852
853 bool dns_name_match(const char *zone, const char *name, size_t *host_part_len)
854 {
855         size_t zl = strlen(zone);
856         size_t nl = strlen(name);
857         ssize_t zi, ni;
858         static const size_t fixup = 'a' - 'A';
859
860         if (zl > nl) {
861                 return false;
862         }
863
864         for (zi = zl, ni = nl; zi >= 0; zi--, ni--) {
865                 char zc = zone[zi];
866                 char nc = name[ni];
867
868                 /* convert to lower case */
869                 if (zc >= 'A' && zc <= 'Z') {
870                         zc += fixup;
871                 }
872                 if (nc >= 'A' && nc <= 'Z') {
873                         nc += fixup;
874                 }
875
876                 if (zc != nc) {
877                         return false;
878                 }
879         }
880
881         if (ni >= 0) {
882                 if (name[ni] != '.') {
883                         return false;
884                 }
885
886                 ni--;
887         }
888
889         *host_part_len = ni+1;
890
891         return true;
892 }
893
894 WERROR dns_common_name2dn(struct ldb_context *samdb,
895                           struct dns_server_zone *zones,
896                           TALLOC_CTX *mem_ctx,
897                           const char *name,
898                           struct ldb_dn **_dn)
899 {
900         struct ldb_dn *base;
901         struct ldb_dn *dn;
902         const struct dns_server_zone *z;
903         size_t host_part_len = 0;
904         WERROR werr;
905
906         if (name == NULL) {
907                 return DNS_ERR(FORMAT_ERROR);
908         }
909
910         if (strcmp(name, "") == 0) {
911                 base = ldb_get_default_basedn(samdb);
912                 dn = ldb_dn_copy(mem_ctx, base);
913                 ldb_dn_add_child_fmt(dn, "DC=@,DC=RootDNSServers,CN=MicrosoftDNS,CN=System");
914                 *_dn = dn;
915                 return WERR_OK;
916         }
917
918         /* Check non-empty names */
919         werr = dns_name_check(mem_ctx, strlen(name), name);
920         if (!W_ERROR_IS_OK(werr)) {
921                 return werr;
922         }
923
924         for (z = zones; z != NULL; z = z->next) {
925                 bool match;
926
927                 match = dns_name_match(z->name, name, &host_part_len);
928                 if (match) {
929                         break;
930                 }
931         }
932
933         if (z == NULL) {
934                 return DNS_ERR(NAME_ERROR);
935         }
936
937         if (host_part_len == 0) {
938                 dn = ldb_dn_copy(mem_ctx, z->dn);
939                 ldb_dn_add_child_fmt(dn, "DC=@");
940                 *_dn = dn;
941                 return WERR_OK;
942         }
943
944         dn = ldb_dn_copy(mem_ctx, z->dn);
945         ldb_dn_add_child_fmt(dn, "DC=%*.*s", (int)host_part_len, (int)host_part_len, name);
946         *_dn = dn;
947         return WERR_OK;
948 }
949
950 static int dns_common_sort_zones(struct ldb_message **m1, struct ldb_message **m2)
951 {
952         const char *n1, *n2;
953         size_t l1, l2;
954
955         n1 = ldb_msg_find_attr_as_string(*m1, "name", NULL);
956         n2 = ldb_msg_find_attr_as_string(*m2, "name", NULL);
957
958         l1 = strlen(n1);
959         l2 = strlen(n2);
960
961         /* If the string lengths are not equal just sort by length */
962         if (l1 != l2) {
963                 /* If m1 is the larger zone name, return it first */
964                 return l2 - l1;
965         }
966
967         /*TODO: We need to compare DNs here, we want the DomainDNSZones first */
968         return 0;
969 }
970
971 NTSTATUS dns_common_zones(struct ldb_context *samdb,
972                           TALLOC_CTX *mem_ctx,
973                           struct ldb_dn *base_dn,
974                           struct dns_server_zone **zones_ret)
975 {
976         int ret;
977         static const char * const attrs[] = { "name", NULL};
978         struct ldb_result *res;
979         int i;
980         struct dns_server_zone *new_list = NULL;
981         TALLOC_CTX *frame = talloc_stackframe();
982
983         if (base_dn) {
984                 /* This search will work against windows */
985                 ret = dsdb_search(samdb, frame, &res,
986                                   base_dn, LDB_SCOPE_SUBTREE,
987                                   attrs, 0, "(objectClass=dnsZone)");
988         } else {
989                 /* TODO: this search does not work against windows */
990                 ret = dsdb_search(samdb, frame, &res, NULL,
991                                   LDB_SCOPE_SUBTREE,
992                                   attrs,
993                                   DSDB_SEARCH_SEARCH_ALL_PARTITIONS,
994                                   "(objectClass=dnsZone)");
995         }
996         if (ret != LDB_SUCCESS) {
997                 TALLOC_FREE(frame);
998                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
999         }
1000
1001         TYPESAFE_QSORT(res->msgs, res->count, dns_common_sort_zones);
1002
1003         for (i=0; i < res->count; i++) {
1004                 struct dns_server_zone *z;
1005
1006                 z = talloc_zero(mem_ctx, struct dns_server_zone);
1007                 if (z == NULL) {
1008                         TALLOC_FREE(frame);
1009                         return NT_STATUS_NO_MEMORY;
1010                 }
1011
1012                 z->name = ldb_msg_find_attr_as_string(res->msgs[i], "name", NULL);
1013                 talloc_steal(z, z->name);
1014                 z->dn = talloc_move(z, &res->msgs[i]->dn);
1015                 /*
1016                  * Ignore the RootDNSServers zone and zones that we don't support yet
1017                  * RootDNSServers should never be returned (Windows DNS server don't)
1018                  * ..TrustAnchors should never be returned as is, (Windows returns
1019                  * TrustAnchors) and for the moment we don't support DNSSEC so we'd better
1020                  * not return this zone.
1021                  */
1022                 if ((strcmp(z->name, "RootDNSServers") == 0) ||
1023                     (strcmp(z->name, "..TrustAnchors") == 0))
1024                 {
1025                         DEBUG(10, ("Ignoring zone %s\n", z->name));
1026                         talloc_free(z);
1027                         continue;
1028                 }
1029                 DLIST_ADD_END(new_list, z);
1030         }
1031
1032         *zones_ret = new_list;
1033         TALLOC_FREE(frame);
1034         return NT_STATUS_OK;
1035 }