s4-lib: Remove unused samdb_msg_set_int()
[gd/samba-autobuild/.git] / source4 / dsdb / common / util.c
1 /* 
2    Unix SMB/CIFS implementation.
3    Samba utility functions
4
5    Copyright (C) Andrew Tridgell 2004
6    Copyright (C) Volker Lendecke 2004
7    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2006
8    Copyright (C) Jelmer Vernooij <jelmer@samba.org> 2007
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 "events/events.h"
26 #include "ldb.h"
27 #include "ldb_module.h"
28 #include "ldb_errors.h"
29 #include "../lib/util/util_ldb.h"
30 #include "../lib/crypto/crypto.h"
31 #include "dsdb/samdb/samdb.h"
32 #include "libcli/security/security.h"
33 #include "librpc/gen_ndr/ndr_security.h"
34 #include "librpc/gen_ndr/ndr_misc.h"
35 #include "../libds/common/flags.h"
36 #include "dsdb/common/proto.h"
37 #include "libcli/ldap/ldap_ndr.h"
38 #include "param/param.h"
39 #include "libcli/auth/libcli_auth.h"
40 #include "librpc/gen_ndr/ndr_drsblobs.h"
41 #include "system/locale.h"
42 #include "lib/util/tsort.h"
43 #include "dsdb/common/util.h"
44 #include "lib/socket/socket.h"
45 #include "librpc/gen_ndr/irpc.h"
46 #include "libds/common/flag_mapping.h"
47
48 /*
49   search the sam for the specified attributes in a specific domain, filter on
50   objectSid being in domain_sid.
51 */
52 int samdb_search_domain(struct ldb_context *sam_ldb,
53                         TALLOC_CTX *mem_ctx, 
54                         struct ldb_dn *basedn,
55                         struct ldb_message ***res,
56                         const char * const *attrs,
57                         const struct dom_sid *domain_sid,
58                         const char *format, ...)  _PRINTF_ATTRIBUTE(7,8)
59 {
60         va_list ap;
61         int i, count;
62
63         va_start(ap, format);
64         count = gendb_search_v(sam_ldb, mem_ctx, basedn,
65                                res, attrs, format, ap);
66         va_end(ap);
67
68         i=0;
69
70         while (i<count) {
71                 struct dom_sid *entry_sid;
72
73                 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
74
75                 if ((entry_sid == NULL) ||
76                     (!dom_sid_in_domain(domain_sid, entry_sid))) {
77                         /* Delete that entry from the result set */
78                         (*res)[i] = (*res)[count-1];
79                         count -= 1;
80                         talloc_free(entry_sid);
81                         continue;
82                 }
83                 talloc_free(entry_sid);
84                 i += 1;
85         }
86
87         return count;
88 }
89
90 /*
91   search the sam for a single string attribute in exactly 1 record
92 */
93 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
94                                   TALLOC_CTX *mem_ctx,
95                                   struct ldb_dn *basedn,
96                                   const char *attr_name,
97                                   const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
98 {
99         int count;
100         const char *attrs[2] = { NULL, NULL };
101         struct ldb_message **res = NULL;
102
103         attrs[0] = attr_name;
104
105         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
106         if (count > 1) {                
107                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
108                          attr_name, format, count));
109         }
110         if (count != 1) {
111                 talloc_free(res);
112                 return NULL;
113         }
114
115         return ldb_msg_find_attr_as_string(res[0], attr_name, NULL);
116 }
117
118 /*
119   search the sam for a single string attribute in exactly 1 record
120 */
121 const char *samdb_search_string(struct ldb_context *sam_ldb,
122                                 TALLOC_CTX *mem_ctx,
123                                 struct ldb_dn *basedn,
124                                 const char *attr_name,
125                                 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
126 {
127         va_list ap;
128         const char *str;
129
130         va_start(ap, format);
131         str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
132         va_end(ap);
133
134         return str;
135 }
136
137 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
138                                TALLOC_CTX *mem_ctx,
139                                struct ldb_dn *basedn,
140                                const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
141 {
142         va_list ap;
143         struct ldb_dn *ret;
144         struct ldb_message **res = NULL;
145         int count;
146
147         va_start(ap, format);
148         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
149         va_end(ap);
150
151         if (count != 1) return NULL;
152
153         ret = talloc_steal(mem_ctx, res[0]->dn);
154         talloc_free(res);
155
156         return ret;
157 }
158
159 /*
160   search the sam for a dom_sid attribute in exactly 1 record
161 */
162 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
163                                      TALLOC_CTX *mem_ctx,
164                                      struct ldb_dn *basedn,
165                                      const char *attr_name,
166                                      const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
167 {
168         va_list ap;
169         int count;
170         struct ldb_message **res;
171         const char *attrs[2] = { NULL, NULL };
172         struct dom_sid *sid;
173
174         attrs[0] = attr_name;
175
176         va_start(ap, format);
177         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
178         va_end(ap);
179         if (count > 1) {                
180                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
181                          attr_name, format, count));
182         }
183         if (count != 1) {
184                 talloc_free(res);
185                 return NULL;
186         }
187         sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
188         talloc_free(res);
189         return sid;     
190 }
191
192 /*
193   return the count of the number of records in the sam matching the query
194 */
195 int samdb_search_count(struct ldb_context *sam_ldb,
196                        TALLOC_CTX *mem_ctx,
197                        struct ldb_dn *basedn,
198                        const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
199 {
200         va_list ap;
201         const char *attrs[] = { NULL };
202         int ret;
203
204         va_start(ap, format);
205         ret = gendb_search_v(sam_ldb, mem_ctx, basedn, NULL, attrs, format, ap);
206         va_end(ap);
207
208         return ret;
209 }
210
211
212 /*
213   search the sam for a single integer attribute in exactly 1 record
214 */
215 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
216                          TALLOC_CTX *mem_ctx,
217                          unsigned int default_value,
218                          struct ldb_dn *basedn,
219                          const char *attr_name,
220                          const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
221 {
222         va_list ap;
223         int count;
224         struct ldb_message **res;
225         const char *attrs[2] = { NULL, NULL };
226
227         attrs[0] = attr_name;
228
229         va_start(ap, format);
230         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
231         va_end(ap);
232
233         if (count != 1) {
234                 return default_value;
235         }
236
237         return ldb_msg_find_attr_as_uint(res[0], attr_name, default_value);
238 }
239
240 /*
241   search the sam for a single signed 64 bit integer attribute in exactly 1 record
242 */
243 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
244                            TALLOC_CTX *mem_ctx,
245                            int64_t default_value,
246                            struct ldb_dn *basedn,
247                            const char *attr_name,
248                            const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
249 {
250         va_list ap;
251         int count;
252         struct ldb_message **res;
253         const char *attrs[2] = { NULL, NULL };
254
255         attrs[0] = attr_name;
256
257         va_start(ap, format);
258         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
259         va_end(ap);
260
261         if (count != 1) {
262                 return default_value;
263         }
264
265         return ldb_msg_find_attr_as_int64(res[0], attr_name, default_value);
266 }
267
268 /*
269   search the sam for multipe records each giving a single string attribute
270   return the number of matches, or -1 on error
271 */
272 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
273                                  TALLOC_CTX *mem_ctx,
274                                  struct ldb_dn *basedn,
275                                  const char ***strs,
276                                  const char *attr_name,
277                                  const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
278 {
279         va_list ap;
280         int count, i;
281         const char *attrs[2] = { NULL, NULL };
282         struct ldb_message **res = NULL;
283
284         attrs[0] = attr_name;
285
286         va_start(ap, format);
287         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
288         va_end(ap);
289
290         if (count <= 0) {
291                 return count;
292         }
293
294         /* make sure its single valued */
295         for (i=0;i<count;i++) {
296                 if (res[i]->num_elements != 1) {
297                         DEBUG(1,("samdb: search for %s %s not single valued\n", 
298                                  attr_name, format));
299                         talloc_free(res);
300                         return -1;
301                 }
302         }
303
304         *strs = talloc_array(mem_ctx, const char *, count+1);
305         if (! *strs) {
306                 talloc_free(res);
307                 return -1;
308         }
309
310         for (i=0;i<count;i++) {
311                 (*strs)[i] = ldb_msg_find_attr_as_string(res[i], attr_name, NULL);
312         }
313         (*strs)[count] = NULL;
314
315         return count;
316 }
317
318 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
319                                const char *attr, struct ldb_dn *default_value)
320 {
321         struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
322         if (!ret_dn) {
323                 return default_value;
324         }
325         return ret_dn;
326 }
327
328 /*
329   pull a rid from a objectSid in a result set. 
330 */
331 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
332                                    const char *attr, uint32_t default_value)
333 {
334         struct dom_sid *sid;
335         uint32_t rid;
336
337         sid = samdb_result_dom_sid(mem_ctx, msg, attr);
338         if (sid == NULL) {
339                 return default_value;
340         }
341         rid = sid->sub_auths[sid->num_auths-1];
342         talloc_free(sid);
343         return rid;
344 }
345
346 /*
347   pull a dom_sid structure from a objectSid in a result set. 
348 */
349 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
350                                      const char *attr)
351 {
352         bool ok;
353         const struct ldb_val *v;
354         struct dom_sid *sid;
355         v = ldb_msg_find_ldb_val(msg, attr);
356         if (v == NULL) {
357                 return NULL;
358         }
359         sid = talloc(mem_ctx, struct dom_sid);
360         if (sid == NULL) {
361                 return NULL;
362         }
363         ok = sid_blob_parse(*v, sid);
364         if (!ok) {
365                 talloc_free(sid);
366                 return NULL;
367         }
368         return sid;
369 }
370
371 /*
372   pull a guid structure from a objectGUID in a result set. 
373 */
374 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
375 {
376         const struct ldb_val *v;
377         struct GUID guid;
378         NTSTATUS status;
379
380         v = ldb_msg_find_ldb_val(msg, attr);
381         if (!v) return GUID_zero();
382
383         status = GUID_from_ndr_blob(v, &guid);
384         if (!NT_STATUS_IS_OK(status)) {
385                 return GUID_zero();
386         }
387
388         return guid;
389 }
390
391 /*
392   pull a sid prefix from a objectSid in a result set. 
393   this is used to find the domain sid for a user
394 */
395 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
396                                         const char *attr)
397 {
398         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
399         if (!sid || sid->num_auths < 1) return NULL;
400         sid->num_auths--;
401         return sid;
402 }
403
404 /*
405   pull a NTTIME in a result set. 
406 */
407 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
408                            NTTIME default_value)
409 {
410         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
411 }
412
413 /*
414  * Windows stores 0 for lastLogoff.
415  * But when a MS DC return the lastLogoff (as Logoff Time)
416  * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
417  * cause windows 2008 and newer version to fail for SMB requests
418  */
419 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
420 {
421         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
422
423         if (ret == 0)
424                 ret = 0x7FFFFFFFFFFFFFFFULL;
425
426         return ret;
427 }
428
429 /*
430  * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
431  * indicate an account doesn't expire.
432  *
433  * When Windows initially creates an account, it sets
434  * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF).  However,
435  * when changing from an account having a specific expiration date to
436  * that account never expiring, it sets accountExpires = 0.
437  *
438  * Consolidate that logic here to allow clearer logic for account expiry in
439  * the rest of the code.
440  */
441 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
442 {
443         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
444                                                  0);
445
446         if (ret == 0)
447                 ret = 0x7FFFFFFFFFFFFFFFULL;
448
449         return ret;
450 }
451
452 /*
453   construct the allow_password_change field from the PwdLastSet attribute and the 
454   domain password settings
455 */
456 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb, 
457                                           TALLOC_CTX *mem_ctx, 
458                                           struct ldb_dn *domain_dn, 
459                                           struct ldb_message *msg, 
460                                           const char *attr)
461 {
462         uint64_t attr_time = ldb_msg_find_attr_as_uint64(msg, attr, 0);
463         int64_t minPwdAge;
464
465         if (attr_time == 0) {
466                 return 0;
467         }
468
469         minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
470
471         /* yes, this is a -= not a += as minPwdAge is stored as the negative
472            of the number of 100-nano-seconds */
473         attr_time -= minPwdAge;
474
475         return attr_time;
476 }
477
478 /*
479   construct the force_password_change field from the PwdLastSet
480   attribute, the userAccountControl and the domain password settings
481 */
482 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb, 
483                                           TALLOC_CTX *mem_ctx, 
484                                           struct ldb_dn *domain_dn, 
485                                           struct ldb_message *msg)
486 {
487         int64_t attr_time = ldb_msg_find_attr_as_int64(msg, "pwdLastSet", 0);
488         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg,
489                                                                 "userAccountControl",
490                                                                 0);
491         int64_t maxPwdAge;
492
493         /* Machine accounts don't expire, and there is a flag for 'no expiry' */
494         if (!(userAccountControl & UF_NORMAL_ACCOUNT)
495             || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
496                 return 0x7FFFFFFFFFFFFFFFULL;
497         }
498
499         if (attr_time == 0) {
500                 return 0;
501         }
502         if (attr_time == -1) {
503                 return 0x7FFFFFFFFFFFFFFFULL;
504         }
505
506         maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
507                                        "maxPwdAge", NULL);
508         if (maxPwdAge == 0 || maxPwdAge == -0x8000000000000000ULL) {
509                 return 0x7FFFFFFFFFFFFFFFULL;
510         } else {
511                 attr_time -= maxPwdAge;
512         }
513
514         return attr_time;
515 }
516
517 /*
518   pull a samr_Password structutre from a result set. 
519 */
520 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
521 {
522         struct samr_Password *hash = NULL;
523         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
524         if (val && (val->length >= sizeof(hash->hash))) {
525                 hash = talloc(mem_ctx, struct samr_Password);
526                 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
527         }
528         return hash;
529 }
530
531 /*
532   pull an array of samr_Password structures from a result set.
533 */
534 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
535                            const char *attr, struct samr_Password **hashes)
536 {
537         unsigned int count, i;
538         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
539
540         *hashes = NULL;
541         if (!val) {
542                 return 0;
543         }
544         count = val->length / 16;
545         if (count == 0) {
546                 return 0;
547         }
548
549         *hashes = talloc_array(mem_ctx, struct samr_Password, count);
550         if (! *hashes) {
551                 return 0;
552         }
553
554         for (i=0;i<count;i++) {
555                 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
556         }
557
558         return count;
559 }
560
561 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct ldb_message *msg,
562                                 struct samr_Password **lm_pwd, struct samr_Password **nt_pwd) 
563 {
564         struct samr_Password *lmPwdHash, *ntPwdHash;
565         if (nt_pwd) {
566                 unsigned int num_nt;
567                 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
568                 if (num_nt == 0) {
569                         *nt_pwd = NULL;
570                 } else if (num_nt > 1) {
571                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
572                 } else {
573                         *nt_pwd = &ntPwdHash[0];
574                 }
575         }
576         if (lm_pwd) {
577                 /* Ensure that if we have turned off LM
578                  * authentication, that we never use the LM hash, even
579                  * if we store it */
580                 if (lpcfg_lanman_auth(lp_ctx)) {
581                         unsigned int num_lm;
582                         num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
583                         if (num_lm == 0) {
584                                 *lm_pwd = NULL;
585                         } else if (num_lm > 1) {
586                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
587                         } else {
588                                 *lm_pwd = &lmPwdHash[0];
589                         }
590                 } else {
591                         *lm_pwd = NULL;
592                 }
593         }
594         return NT_STATUS_OK;
595 }
596
597 /*
598   pull a samr_LogonHours structutre from a result set. 
599 */
600 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
601 {
602         struct samr_LogonHours hours;
603         size_t units_per_week = 168;
604         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
605
606         ZERO_STRUCT(hours);
607
608         if (val) {
609                 units_per_week = val->length * 8;
610         }
611
612         hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
613         if (!hours.bits) {
614                 return hours;
615         }
616         hours.units_per_week = units_per_week;
617         memset(hours.bits, 0xFF, units_per_week/8);
618         if (val) {
619                 memcpy(hours.bits, val->data, val->length);
620         }
621
622         return hours;
623 }
624
625 /*
626   pull a set of account_flags from a result set. 
627
628   This requires that the attributes: 
629    pwdLastSet
630    userAccountControl
631   be included in 'msg'
632 */
633 uint32_t samdb_result_acct_flags(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
634                                  struct ldb_message *msg, struct ldb_dn *domain_dn)
635 {
636         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
637         uint32_t acct_flags = ds_uf2acb(userAccountControl);
638         NTTIME must_change_time;
639         NTTIME now;
640
641         must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx, 
642                                                               domain_dn, msg);
643
644         /* Test account expire time */
645         unix_to_nt_time(&now, time(NULL));
646         /* check for expired password */
647         if (must_change_time < now) {
648                 acct_flags |= ACB_PW_EXPIRED;
649         }
650         return acct_flags;
651 }
652
653 struct lsa_BinaryString samdb_result_parameters(TALLOC_CTX *mem_ctx,
654                                                 struct ldb_message *msg,
655                                                 const char *attr)
656 {
657         struct lsa_BinaryString s;
658         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
659
660         ZERO_STRUCT(s);
661
662         if (!val) {
663                 return s;
664         }
665
666         s.array = talloc_array(mem_ctx, uint16_t, val->length/2);
667         if (!s.array) {
668                 return s;
669         }
670         s.length = s.size = val->length;
671         memcpy(s.array, val->data, val->length);
672
673         return s;
674 }
675
676 /* Find an attribute, with a particular value */
677
678 /* The current callers of this function expect a very specific
679  * behaviour: In particular, objectClass subclass equivilance is not
680  * wanted.  This means that we should not lookup the schema for the
681  * comparison function */
682 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb, 
683                                                  const struct ldb_message *msg, 
684                                                  const char *name, const char *value)
685 {
686         unsigned int i;
687         struct ldb_message_element *el = ldb_msg_find_element(msg, name);
688
689         if (!el) {
690                 return NULL;
691         }
692
693         for (i=0;i<el->num_values;i++) {
694                 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
695                         return el;
696                 }
697         }
698
699         return NULL;
700 }
701
702 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
703 {
704         struct ldb_message_element *el;
705
706         el = ldb_msg_find_element(msg, name);
707         if (el) {
708                 return LDB_SUCCESS;
709         }
710
711         return ldb_msg_add_string(msg, name, set_value);
712 }
713
714 /*
715   add a dom_sid element to a message
716 */
717 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
718                           const char *attr_name, const struct dom_sid *sid)
719 {
720         struct ldb_val v;
721         enum ndr_err_code ndr_err;
722
723         ndr_err = ndr_push_struct_blob(&v, mem_ctx, 
724                                        sid,
725                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
726         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
727                 return ldb_operr(sam_ldb);
728         }
729         return ldb_msg_add_value(msg, attr_name, &v, NULL);
730 }
731
732
733 /*
734   add a delete element operation to a message
735 */
736 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
737                          const char *attr_name)
738 {
739         /* we use an empty replace rather than a delete, as it allows for 
740            dsdb_replace() to be used everywhere */
741         return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
742 }
743
744 /*
745   add an add attribute value to a message or enhance an existing attribute
746   which has the same name and the add flag set.
747 */
748 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
749                          struct ldb_message *msg, const char *attr_name,
750                          const char *value)
751 {
752         struct ldb_message_element *el;
753         struct ldb_val val, *vals;
754         char *v;
755         unsigned int i;
756         bool found = false;
757         int ret;
758
759         v = talloc_strdup(mem_ctx, value);
760         if (v == NULL) {
761                 return ldb_oom(sam_ldb);
762         }
763
764         val.data = (uint8_t *) v;
765         val.length = strlen(v);
766
767         if (val.length == 0) {
768                 /* allow empty strings as non-existent attributes */
769                 return LDB_SUCCESS;
770         }
771
772         for (i = 0; i < msg->num_elements; i++) {
773                 el = &msg->elements[i];
774                 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
775                     (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
776                         found = true;
777                         break;
778                 }
779         }
780         if (!found) {
781                 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
782                                         &el);
783                 if (ret != LDB_SUCCESS) {
784                         return ret;
785                 }
786         }
787
788         vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
789                               el->num_values + 1);
790         if (vals == NULL) {
791                 return ldb_oom(sam_ldb);
792         }
793         el->values = vals;
794         el->values[el->num_values] = val;
795         ++(el->num_values);
796
797         return LDB_SUCCESS;
798 }
799
800 /*
801   add a delete attribute value to a message or enhance an existing attribute
802   which has the same name and the delete flag set.
803 */
804 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
805                          struct ldb_message *msg, const char *attr_name,
806                          const char *value)
807 {
808         struct ldb_message_element *el;
809         struct ldb_val val, *vals;
810         char *v;
811         unsigned int i;
812         bool found = false;
813         int ret;
814
815         v = talloc_strdup(mem_ctx, value);
816         if (v == NULL) {
817                 return ldb_oom(sam_ldb);
818         }
819
820         val.data = (uint8_t *) v;
821         val.length = strlen(v);
822
823         if (val.length == 0) {
824                 /* allow empty strings as non-existent attributes */
825                 return LDB_SUCCESS;
826         }
827
828         for (i = 0; i < msg->num_elements; i++) {
829                 el = &msg->elements[i];
830                 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
831                     (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
832                         found = true;
833                         break;
834                 }
835         }
836         if (!found) {
837                 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
838                                         &el);
839                 if (ret != LDB_SUCCESS) {
840                         return ret;
841                 }
842         }
843
844         vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
845                               el->num_values + 1);
846         if (vals == NULL) {
847                 return ldb_oom(sam_ldb);
848         }
849         el->values = vals;
850         el->values[el->num_values] = val;
851         ++(el->num_values);
852
853         return LDB_SUCCESS;
854 }
855
856 /*
857   add a int element to a message
858 */
859 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
860                        const char *attr_name, int v)
861 {
862         const char *s = talloc_asprintf(mem_ctx, "%d", v);
863         if (s == NULL) {
864                 return ldb_oom(sam_ldb);
865         }
866         return ldb_msg_add_string(msg, attr_name, s);
867 }
868
869 /*
870  * Add an unsigned int element to a message
871  *
872  * The issue here is that we have not yet first cast to int32_t explicitly,
873  * before we cast to an signed int to printf() into the %d or cast to a
874  * int64_t before we then cast to a long long to printf into a %lld.
875  *
876  * There are *no* unsigned integers in Active Directory LDAP, even the RID
877  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
878  * (See the schema, and the syntax definitions in schema_syntax.c).
879  *
880  */
881 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
882                        const char *attr_name, unsigned int v)
883 {
884         return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
885 }
886
887 /*
888   add a (signed) int64_t element to a message
889 */
890 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
891                         const char *attr_name, int64_t v)
892 {
893         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
894         if (s == NULL) {
895                 return ldb_oom(sam_ldb);
896         }
897         return ldb_msg_add_string(msg, attr_name, s);
898 }
899
900 /*
901  * Add an unsigned int64_t (uint64_t) element to a message
902  *
903  * The issue here is that we have not yet first cast to int32_t explicitly,
904  * before we cast to an signed int to printf() into the %d or cast to a
905  * int64_t before we then cast to a long long to printf into a %lld.
906  *
907  * There are *no* unsigned integers in Active Directory LDAP, even the RID
908  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
909  * (See the schema, and the syntax definitions in schema_syntax.c).
910  *
911  */
912 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
913                         const char *attr_name, uint64_t v)
914 {
915         return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
916 }
917
918 /*
919   add a samr_Password element to a message
920 */
921 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
922                        const char *attr_name, const struct samr_Password *hash)
923 {
924         struct ldb_val val;
925         val.data = talloc_memdup(mem_ctx, hash->hash, 16);
926         if (!val.data) {
927                 return ldb_oom(sam_ldb);
928         }
929         val.length = 16;
930         return ldb_msg_add_value(msg, attr_name, &val, NULL);
931 }
932
933 /*
934   add a samr_Password array to a message
935 */
936 int samdb_msg_add_hashes(struct ldb_context *ldb,
937                          TALLOC_CTX *mem_ctx, struct ldb_message *msg,
938                          const char *attr_name, struct samr_Password *hashes,
939                          unsigned int count)
940 {
941         struct ldb_val val;
942         unsigned int i;
943         val.data = talloc_array_size(mem_ctx, 16, count);
944         val.length = count*16;
945         if (!val.data) {
946                 return ldb_oom(ldb);
947         }
948         for (i=0;i<count;i++) {
949                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
950         }
951         return ldb_msg_add_value(msg, attr_name, &val, NULL);
952 }
953
954 /*
955   add a acct_flags element to a message
956 */
957 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
958                              const char *attr_name, uint32_t v)
959 {
960         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
961 }
962
963 /*
964   add a logon_hours element to a message
965 */
966 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
967                               const char *attr_name, struct samr_LogonHours *hours)
968 {
969         struct ldb_val val;
970         val.length = hours->units_per_week / 8;
971         val.data = hours->bits;
972         return ldb_msg_add_value(msg, attr_name, &val, NULL);
973 }
974
975 /*
976   add a parameters element to a message
977 */
978 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
979                              const char *attr_name, struct lsa_BinaryString *parameters)
980 {
981         struct ldb_val val;
982         val.length = parameters->length;
983         val.data = (uint8_t *)parameters->array;
984         return ldb_msg_add_value(msg, attr_name, &val, NULL);
985 }
986
987 /*
988   sets a general value element to a message
989 */
990 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
991                         const char *attr_name, const struct ldb_val *val)
992 {
993         struct ldb_message_element *el;
994
995         el = ldb_msg_find_element(msg, attr_name);
996         if (el) {
997                 el->num_values = 0;
998         }
999         return ldb_msg_add_value(msg, attr_name, val, NULL);
1000 }
1001
1002 /*
1003   set a string element in a message
1004 */
1005 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1006                          const char *attr_name, const char *str)
1007 {
1008         struct ldb_message_element *el;
1009
1010         el = ldb_msg_find_element(msg, attr_name);
1011         if (el) {
1012                 el->num_values = 0;
1013         }
1014         return ldb_msg_add_string(msg, attr_name, str);
1015 }
1016
1017 /*
1018  * Sets an unsigned int element in a message
1019  *
1020  * The issue here is that we have not yet first cast to int32_t explicitly,
1021  * before we cast to an signed int to printf() into the %d or cast to a
1022  * int64_t before we then cast to a long long to printf into a %lld.
1023  *
1024  * There are *no* unsigned integers in Active Directory LDAP, even the RID
1025  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1026  * (See the schema, and the syntax definitions in schema_syntax.c).
1027  *
1028  */
1029 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1030                        struct ldb_message *msg, const char *attr_name,
1031                        unsigned int v)
1032 {
1033         struct ldb_message_element *el;
1034
1035         el = ldb_msg_find_element(msg, attr_name);
1036         if (el) {
1037                 el->num_values = 0;
1038         }
1039         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1040 }
1041
1042 /*
1043  * Handle ldb_request in transaction
1044  */
1045 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1046                                         struct ldb_request *req)
1047 {
1048         int ret;
1049
1050         ret = ldb_transaction_start(sam_ldb);
1051         if (ret != LDB_SUCCESS) {
1052                 return ret;
1053         }
1054
1055         ret = ldb_request(sam_ldb, req);
1056         if (ret == LDB_SUCCESS) {
1057                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1058         }
1059
1060         if (ret == LDB_SUCCESS) {
1061                 return ldb_transaction_commit(sam_ldb);
1062         }
1063         ldb_transaction_cancel(sam_ldb);
1064
1065         return ret;
1066 }
1067
1068 /*
1069   return a default security descriptor
1070 */
1071 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1072 {
1073         struct security_descriptor *sd;
1074
1075         sd = security_descriptor_initialise(mem_ctx);
1076
1077         return sd;
1078 }
1079
1080 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx) 
1081 {
1082         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1083         struct ldb_dn *aggregate_dn;
1084         if (!schema_dn) {
1085                 return NULL;
1086         }
1087
1088         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1089         if (!aggregate_dn) {
1090                 return NULL;
1091         }
1092         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1093                 return NULL;
1094         }
1095         return aggregate_dn;
1096 }
1097
1098 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1099 {
1100         struct ldb_dn *new_dn;
1101
1102         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1103         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1104                 talloc_free(new_dn);
1105                 return NULL;
1106         }
1107         return new_dn;
1108 }
1109
1110 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1111 {
1112        struct ldb_dn *new_dn;
1113
1114        new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1115        if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1116                talloc_free(new_dn);
1117                return NULL;
1118        }
1119        return new_dn;
1120 }
1121
1122 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1123 {
1124         struct ldb_dn *new_dn;
1125
1126         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1127         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1128                 talloc_free(new_dn);
1129                 return NULL;
1130         }
1131         return new_dn;
1132 }
1133
1134 /*
1135   work out the domain sid for the current open ldb
1136 */
1137 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1138 {
1139         TALLOC_CTX *tmp_ctx;
1140         const struct dom_sid *domain_sid;
1141         const char *attrs[] = {
1142                 "objectSid",
1143                 NULL
1144         };
1145         struct ldb_result *res;
1146         int ret;
1147
1148         /* see if we have a cached copy */
1149         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1150         if (domain_sid) {
1151                 return domain_sid;
1152         }
1153
1154         tmp_ctx = talloc_new(ldb);
1155         if (tmp_ctx == NULL) {
1156                 goto failed;
1157         }
1158
1159         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1160
1161         if (ret != LDB_SUCCESS) {
1162                 goto failed;
1163         }
1164
1165         if (res->count != 1) {
1166                 goto failed;
1167         }
1168
1169         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1170         if (domain_sid == NULL) {
1171                 goto failed;
1172         }
1173
1174         /* cache the domain_sid in the ldb */
1175         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1176                 goto failed;
1177         }
1178
1179         talloc_steal(ldb, domain_sid);
1180         talloc_free(tmp_ctx);
1181
1182         return domain_sid;
1183
1184 failed:
1185         talloc_free(tmp_ctx);
1186         return NULL;
1187 }
1188
1189 /*
1190   get domain sid from cache
1191 */
1192 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1193 {
1194         return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1195 }
1196
1197 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1198 {
1199         TALLOC_CTX *tmp_ctx;
1200         struct dom_sid *dom_sid_new;
1201         struct dom_sid *dom_sid_old;
1202
1203         /* see if we have a cached copy */
1204         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1205                                                      "cache.domain_sid"), struct dom_sid);
1206
1207         tmp_ctx = talloc_new(ldb);
1208         if (tmp_ctx == NULL) {
1209                 goto failed;
1210         }
1211
1212         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1213         if (!dom_sid_new) {
1214                 goto failed;
1215         }
1216
1217         /* cache the domain_sid in the ldb */
1218         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1219                 goto failed;
1220         }
1221
1222         talloc_steal(ldb, dom_sid_new);
1223         talloc_free(tmp_ctx);
1224         talloc_free(dom_sid_old);
1225
1226         return true;
1227
1228 failed:
1229         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1230         talloc_free(tmp_ctx);
1231         return false;
1232 }
1233
1234 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1235 {
1236         TALLOC_CTX *tmp_ctx;
1237         struct ldb_dn *ntds_settings_dn_new;
1238         struct ldb_dn *ntds_settings_dn_old;
1239
1240         /* see if we have a forced copy from provision */
1241         ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb, 
1242                                                               "forced.ntds_settings_dn"), struct ldb_dn);
1243
1244         tmp_ctx = talloc_new(ldb);
1245         if (tmp_ctx == NULL) {
1246                 goto failed;
1247         }
1248
1249         ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1250         if (!ntds_settings_dn_new) {
1251                 goto failed;
1252         }
1253
1254         /* set the DN in the ldb to avoid lookups during provision */
1255         if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1256                 goto failed;
1257         }
1258
1259         talloc_steal(ldb, ntds_settings_dn_new);
1260         talloc_free(tmp_ctx);
1261         talloc_free(ntds_settings_dn_old);
1262
1263         return true;
1264
1265 failed:
1266         DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1267         talloc_free(tmp_ctx);
1268         return false;
1269 }
1270
1271 /*
1272   work out the ntds settings dn for the current open ldb
1273 */
1274 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1275 {
1276         TALLOC_CTX *tmp_ctx;
1277         const char *root_attrs[] = { "dsServiceName", NULL };
1278         int ret;
1279         struct ldb_result *root_res;
1280         struct ldb_dn *settings_dn;
1281
1282         /* see if we have a cached copy */
1283         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1284         if (settings_dn) {
1285                 return settings_dn;
1286         }
1287
1288         tmp_ctx = talloc_new(ldb);
1289         if (tmp_ctx == NULL) {
1290                 goto failed;
1291         }
1292
1293         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1294         if (ret != LDB_SUCCESS) {
1295                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1296                          ldb_errstring(ldb)));
1297                 goto failed;
1298         }
1299
1300         if (root_res->count != 1) {
1301                 goto failed;
1302         }
1303
1304         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1305
1306         /* note that we do not cache the DN here, as that would mean
1307          * we could not handle server renames at runtime. Only
1308          * provision sets up forced.ntds_settings_dn */
1309
1310         talloc_steal(ldb, settings_dn);
1311         talloc_free(tmp_ctx);
1312
1313         return settings_dn;
1314
1315 failed:
1316         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1317         talloc_free(tmp_ctx);
1318         return NULL;
1319 }
1320
1321 /*
1322   work out the ntds settings invocationId for the current open ldb
1323 */
1324 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1325 {
1326         TALLOC_CTX *tmp_ctx;
1327         const char *attrs[] = { "invocationId", NULL };
1328         int ret;
1329         struct ldb_result *res;
1330         struct GUID *invocation_id;
1331
1332         /* see if we have a cached copy */
1333         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1334         if (invocation_id) {
1335                 return invocation_id;
1336         }
1337
1338         tmp_ctx = talloc_new(ldb);
1339         if (tmp_ctx == NULL) {
1340                 goto failed;
1341         }
1342
1343         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1344         if (ret) {
1345                 goto failed;
1346         }
1347
1348         if (res->count != 1) {
1349                 goto failed;
1350         }
1351
1352         invocation_id = talloc(tmp_ctx, struct GUID);
1353         if (!invocation_id) {
1354                 goto failed;
1355         }
1356
1357         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1358
1359         /* cache the domain_sid in the ldb */
1360         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1361                 goto failed;
1362         }
1363
1364         talloc_steal(ldb, invocation_id);
1365         talloc_free(tmp_ctx);
1366
1367         return invocation_id;
1368
1369 failed:
1370         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1371         talloc_free(tmp_ctx);
1372         return NULL;
1373 }
1374
1375 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1376 {
1377         TALLOC_CTX *tmp_ctx;
1378         struct GUID *invocation_id_new;
1379         struct GUID *invocation_id_old;
1380
1381         /* see if we have a cached copy */
1382         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1383                                                          "cache.invocation_id");
1384
1385         tmp_ctx = talloc_new(ldb);
1386         if (tmp_ctx == NULL) {
1387                 goto failed;
1388         }
1389
1390         invocation_id_new = talloc(tmp_ctx, struct GUID);
1391         if (!invocation_id_new) {
1392                 goto failed;
1393         }
1394
1395         *invocation_id_new = *invocation_id_in;
1396
1397         /* cache the domain_sid in the ldb */
1398         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1399                 goto failed;
1400         }
1401
1402         talloc_steal(ldb, invocation_id_new);
1403         talloc_free(tmp_ctx);
1404         talloc_free(invocation_id_old);
1405
1406         return true;
1407
1408 failed:
1409         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1410         talloc_free(tmp_ctx);
1411         return false;
1412 }
1413
1414 /*
1415   work out the ntds settings objectGUID for the current open ldb
1416 */
1417 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1418 {
1419         TALLOC_CTX *tmp_ctx;
1420         const char *attrs[] = { "objectGUID", NULL };
1421         int ret;
1422         struct ldb_result *res;
1423         struct GUID *ntds_guid;
1424
1425         /* see if we have a cached copy */
1426         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1427         if (ntds_guid) {
1428                 return ntds_guid;
1429         }
1430
1431         tmp_ctx = talloc_new(ldb);
1432         if (tmp_ctx == NULL) {
1433                 goto failed;
1434         }
1435
1436         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1437         if (ret) {
1438                 goto failed;
1439         }
1440
1441         if (res->count != 1) {
1442                 goto failed;
1443         }
1444
1445         ntds_guid = talloc(tmp_ctx, struct GUID);
1446         if (!ntds_guid) {
1447                 goto failed;
1448         }
1449
1450         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1451
1452         /* cache the domain_sid in the ldb */
1453         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1454                 goto failed;
1455         }
1456
1457         talloc_steal(ldb, ntds_guid);
1458         talloc_free(tmp_ctx);
1459
1460         return ntds_guid;
1461
1462 failed:
1463         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1464         talloc_free(tmp_ctx);
1465         return NULL;
1466 }
1467
1468 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1469 {
1470         TALLOC_CTX *tmp_ctx;
1471         struct GUID *ntds_guid_new;
1472         struct GUID *ntds_guid_old;
1473
1474         /* see if we have a cached copy */
1475         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1476
1477         tmp_ctx = talloc_new(ldb);
1478         if (tmp_ctx == NULL) {
1479                 goto failed;
1480         }
1481
1482         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1483         if (!ntds_guid_new) {
1484                 goto failed;
1485         }
1486
1487         *ntds_guid_new = *ntds_guid_in;
1488
1489         /* cache the domain_sid in the ldb */
1490         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1491                 goto failed;
1492         }
1493
1494         talloc_steal(ldb, ntds_guid_new);
1495         talloc_free(tmp_ctx);
1496         talloc_free(ntds_guid_old);
1497
1498         return true;
1499
1500 failed:
1501         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1502         talloc_free(tmp_ctx);
1503         return false;
1504 }
1505
1506 /*
1507   work out the server dn for the current open ldb
1508 */
1509 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1510 {
1511         return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1512 }
1513
1514 /*
1515   work out the server dn for the current open ldb
1516 */
1517 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1518 {
1519         struct ldb_dn *server_dn;
1520         struct ldb_dn *servers_dn;
1521         struct ldb_dn *server_site_dn;
1522
1523         /* TODO: there must be a saner way to do this!! */
1524         server_dn = samdb_server_dn(ldb, mem_ctx);
1525         if (!server_dn) return NULL;
1526
1527         servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1528         talloc_free(server_dn);
1529         if (!servers_dn) return NULL;
1530
1531         server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1532         talloc_free(servers_dn);
1533
1534         return server_site_dn;
1535 }
1536
1537 /*
1538   find the site name from a computers DN record
1539  */
1540 int samdb_find_site_for_computer(struct ldb_context *ldb,
1541                                  TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1542                                  const char **site_name)
1543 {
1544         int ret;
1545         struct ldb_dn *dn;
1546         const struct ldb_val *rdn_val;
1547
1548         *site_name = NULL;
1549
1550         ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1551         if (ret != LDB_SUCCESS) {
1552                 return ret;
1553         }
1554
1555         if (!ldb_dn_remove_child_components(dn, 2)) {
1556                 talloc_free(dn);
1557                 return LDB_ERR_INVALID_DN_SYNTAX;
1558         }
1559
1560         rdn_val = ldb_dn_get_rdn_val(dn);
1561         if (rdn_val == NULL) {
1562                 return LDB_ERR_OPERATIONS_ERROR;
1563         }
1564
1565         (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1566         talloc_free(dn);
1567         if (!*site_name) {
1568                 return LDB_ERR_OPERATIONS_ERROR;
1569         }
1570         return LDB_SUCCESS;
1571 }
1572
1573 /*
1574   find the NTDS GUID from a computers DN record
1575  */
1576 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1577                                      struct GUID *ntds_guid)
1578 {
1579         int ret;
1580         struct ldb_dn *dn;
1581
1582         *ntds_guid = GUID_zero();
1583
1584         ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1585         if (ret != LDB_SUCCESS) {
1586                 return ret;
1587         }
1588
1589         if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1590                 talloc_free(dn);
1591                 return LDB_ERR_OPERATIONS_ERROR;
1592         }
1593
1594         ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1595         talloc_free(dn);
1596         return ret;
1597 }
1598
1599 /*
1600   find a 'reference' DN that points at another object
1601   (eg. serverReference, rIDManagerReference etc)
1602  */
1603 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1604                        const char *attribute, struct ldb_dn **dn)
1605 {
1606         const char *attrs[2];
1607         struct ldb_result *res;
1608         int ret;
1609
1610         attrs[0] = attribute;
1611         attrs[1] = NULL;
1612
1613         ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY, NULL);
1614         if (ret != LDB_SUCCESS) {
1615                 return ret;
1616         }
1617
1618         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1619         if (!*dn) {
1620                 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1621                         ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1622                                                ldb_dn_get_linearized(base));
1623                 } else {
1624                         ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1625                                                ldb_dn_get_linearized(base));
1626                 }
1627                 talloc_free(res);
1628                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1629         }
1630
1631         talloc_free(res);
1632         return LDB_SUCCESS;
1633 }
1634
1635 /*
1636   find our machine account via the serverReference attribute in the
1637   server DN
1638  */
1639 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1640 {
1641         struct ldb_dn *server_dn;
1642         int ret;
1643
1644         server_dn = samdb_server_dn(ldb, mem_ctx);
1645         if (server_dn == NULL) {
1646                 return LDB_ERR_NO_SUCH_OBJECT;
1647         }
1648
1649         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1650         talloc_free(server_dn);
1651
1652         return ret;
1653 }
1654
1655 /*
1656   find the RID Manager$ DN via the rIDManagerReference attribute in the
1657   base DN
1658  */
1659 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1660 {
1661         return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1662                                   "rIDManagerReference", dn);
1663 }
1664
1665 /*
1666   find the RID Set DN via the rIDSetReferences attribute in our
1667   machine account DN
1668  */
1669 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1670 {
1671         struct ldb_dn *server_ref_dn;
1672         int ret;
1673
1674         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1675         if (ret != LDB_SUCCESS) {
1676                 return ret;
1677         }
1678         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1679         talloc_free(server_ref_dn);
1680         return ret;
1681 }
1682
1683 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1684 {
1685         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1686                                                                             mem_ctx));
1687
1688         if (val == NULL) {
1689                 return NULL;
1690         }
1691
1692         return (const char *) val->data;
1693 }
1694
1695 /*
1696  * Finds the client site by using the client's IP address.
1697  * The "subnet_name" returns the name of the subnet if parameter != NULL
1698  */
1699 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1700                                    const char *ip_address, char **subnet_name)
1701 {
1702         const char *attrs[] = { "cn", "siteObject", NULL };
1703         struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1704         struct ldb_result *res;
1705         const struct ldb_val *val;
1706         const char *site_name = NULL, *l_subnet_name = NULL;
1707         const char *allow_list[2] = { NULL, NULL };
1708         unsigned int i, count;
1709         int cnt, ret;
1710
1711         /*
1712          * if we don't have a client ip e.g. ncalrpc
1713          * the server site is the client site
1714          */
1715         if (ip_address == NULL) {
1716                 return samdb_server_site_name(ldb, mem_ctx);
1717         }
1718
1719         sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1720         if (sites_container_dn == NULL) {
1721                 return NULL;
1722         }
1723
1724         subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1725         if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1726                 talloc_free(sites_container_dn);
1727                 talloc_free(subnets_dn);
1728                 return NULL;
1729         }
1730
1731         ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1732                          attrs, NULL);
1733         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1734                 count = 0;
1735         } else if (ret != LDB_SUCCESS) {
1736                 talloc_free(sites_container_dn);
1737                 talloc_free(subnets_dn);
1738                 return NULL;
1739         } else {
1740                 count = res->count;
1741         }
1742
1743         for (i = 0; i < count; i++) {
1744                 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1745                                                             NULL);
1746
1747                 allow_list[0] = l_subnet_name;
1748
1749                 if (socket_allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1750                         sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1751                                                            res->msgs[i],
1752                                                            "siteObject");
1753                         if (sites_dn == NULL) {
1754                                 /* No reference, maybe another subnet matches */
1755                                 continue;
1756                         }
1757
1758                         /* "val" cannot be NULL here since "sites_dn" != NULL */
1759                         val = ldb_dn_get_rdn_val(sites_dn);
1760                         site_name = talloc_strdup(mem_ctx,
1761                                                   (const char *) val->data);
1762
1763                         talloc_free(sites_dn);
1764
1765                         break;
1766                 }
1767         }
1768
1769         if (site_name == NULL) {
1770                 /* This is the Windows Server fallback rule: when no subnet
1771                  * exists and we have only one site available then use it (it
1772                  * is for sure the same as our server site). If more sites do
1773                  * exist then we don't know which one to use and set the site
1774                  * name to "". */
1775                 cnt = samdb_search_count(ldb, mem_ctx, sites_container_dn,
1776                                          "(objectClass=site)");
1777                 if (cnt == 1) {
1778                         site_name = samdb_server_site_name(ldb, mem_ctx);
1779                 } else {
1780                         site_name = talloc_strdup(mem_ctx, "");
1781                 }
1782                 l_subnet_name = NULL;
1783         }
1784
1785         if (subnet_name != NULL) {
1786                 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1787         }
1788
1789         talloc_free(sites_container_dn);
1790         talloc_free(subnets_dn);
1791         talloc_free(res);
1792
1793         return site_name;
1794 }
1795
1796 /*
1797   work out if we are the PDC for the domain of the current open ldb
1798 */
1799 bool samdb_is_pdc(struct ldb_context *ldb)
1800 {
1801         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1802         int ret;
1803         struct ldb_result *dom_res;
1804         TALLOC_CTX *tmp_ctx;
1805         bool is_pdc;
1806         struct ldb_dn *pdc;
1807
1808         tmp_ctx = talloc_new(ldb);
1809         if (tmp_ctx == NULL) {
1810                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1811                 return false;
1812         }
1813
1814         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1815         if (ret != LDB_SUCCESS) {
1816                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1817                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1818                          ldb_errstring(ldb)));
1819                 goto failed;
1820         }
1821         if (dom_res->count != 1) {
1822                 goto failed;
1823         }
1824
1825         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1826
1827         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1828                 is_pdc = true;
1829         } else {
1830                 is_pdc = false;
1831         }
1832
1833         talloc_free(tmp_ctx);
1834
1835         return is_pdc;
1836
1837 failed:
1838         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1839         talloc_free(tmp_ctx);
1840         return false;
1841 }
1842
1843 /*
1844   work out if we are a Global Catalog server for the domain of the current open ldb
1845 */
1846 bool samdb_is_gc(struct ldb_context *ldb)
1847 {
1848         uint32_t options;
1849         if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
1850                 return false;
1851         }
1852         return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
1853 }
1854
1855 /* Find a domain object in the parents of a particular DN.  */
1856 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1857                                    struct ldb_dn **parent_dn, const char **errstring)
1858 {
1859         TALLOC_CTX *local_ctx;
1860         struct ldb_dn *sdn = dn;
1861         struct ldb_result *res = NULL;
1862         int ret = LDB_SUCCESS;
1863         const char *attrs[] = { NULL };
1864
1865         local_ctx = talloc_new(mem_ctx);
1866         if (local_ctx == NULL) return ldb_oom(ldb);
1867
1868         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1869                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1870                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1871                 if (ret == LDB_SUCCESS) {
1872                         if (res->count == 1) {
1873                                 break;
1874                         }
1875                 } else {
1876                         break;
1877                 }
1878         }
1879
1880         if (ret != LDB_SUCCESS) {
1881                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1882                                              ldb_dn_get_linearized(dn),
1883                                              ldb_dn_get_linearized(sdn),
1884                                              ldb_errstring(ldb));
1885                 talloc_free(local_ctx);
1886                 return ret;
1887         }
1888         if (res->count != 1) {
1889                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1890                                              ldb_dn_get_linearized(dn));
1891                 DEBUG(0,(__location__ ": %s\n", *errstring));
1892                 talloc_free(local_ctx);
1893                 return LDB_ERR_CONSTRAINT_VIOLATION;
1894         }
1895
1896         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1897         talloc_free(local_ctx);
1898         return ret;
1899 }
1900
1901
1902 /*
1903  * Performs checks on a user password (plaintext UNIX format - attribute
1904  * "password"). The remaining parameters have to be extracted from the domain
1905  * object in the AD.
1906  *
1907  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1908  */
1909 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1910                                                 const uint32_t pwdProperties,
1911                                                 const uint32_t minPwdLength)
1912 {
1913         /* checks if the "minPwdLength" property is satisfied */
1914         if (minPwdLength > password->length)
1915                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1916
1917         /* checks the password complexity */
1918         if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1919                         && (password->data != NULL)
1920                         && (!check_password_quality((const char *) password->data)))
1921                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1922
1923         return SAMR_VALIDATION_STATUS_SUCCESS;
1924 }
1925
1926 /*
1927  * Callback for "samdb_set_password" password change
1928  */
1929 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
1930 {
1931         int ret;
1932
1933         if (!ares) {
1934                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1935         }
1936
1937         if (ares->error != LDB_SUCCESS) {
1938                 ret = ares->error;
1939                 req->context = talloc_steal(req,
1940                                             ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1941                 talloc_free(ares);
1942                 return ldb_request_done(req, ret);
1943         }
1944
1945         if (ares->type != LDB_REPLY_DONE) {
1946                 talloc_free(ares);
1947                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1948         }
1949
1950         req->context = talloc_steal(req,
1951                                     ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1952         talloc_free(ares);
1953         return ldb_request_done(req, LDB_SUCCESS);
1954 }
1955
1956 /*
1957  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1958  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1959  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
1960  * user change or not. The "rejectReason" gives some more information if the
1961  * change failed.
1962  *
1963  * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1964  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
1965  */
1966 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1967                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1968                             const DATA_BLOB *new_password,
1969                             const struct samr_Password *lmNewHash,
1970                             const struct samr_Password *ntNewHash,
1971                             const struct samr_Password *lmOldHash,
1972                             const struct samr_Password *ntOldHash,
1973                             enum samPwdChangeReason *reject_reason,
1974                             struct samr_DomInfo1 **_dominfo)
1975 {
1976         struct ldb_message *msg;
1977         struct ldb_message_element *el;
1978         struct ldb_request *req;
1979         struct dsdb_control_password_change_status *pwd_stat = NULL;
1980         int ret;
1981         NTSTATUS status = NT_STATUS_OK;
1982
1983 #define CHECK_RET(x) \
1984         if (x != LDB_SUCCESS) { \
1985                 talloc_free(msg); \
1986                 return NT_STATUS_NO_MEMORY; \
1987         }
1988
1989         msg = ldb_msg_new(mem_ctx);
1990         if (msg == NULL) {
1991                 return NT_STATUS_NO_MEMORY;
1992         }
1993         msg->dn = user_dn;
1994         if ((new_password != NULL)
1995                         && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
1996                 /* we have the password as plaintext UTF16 */
1997                 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
1998                                             new_password, NULL));
1999                 el = ldb_msg_find_element(msg, "clearTextPassword");
2000                 el->flags = LDB_FLAG_MOD_REPLACE;
2001         } else if ((new_password == NULL)
2002                         && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2003                 /* we have a password as LM and/or NT hash */
2004                 if (lmNewHash != NULL) {
2005                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2006                                 "dBCSPwd", lmNewHash));
2007                         el = ldb_msg_find_element(msg, "dBCSPwd");
2008                         el->flags = LDB_FLAG_MOD_REPLACE;
2009                 }
2010                 if (ntNewHash != NULL) {
2011                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2012                                 "unicodePwd", ntNewHash));
2013                         el = ldb_msg_find_element(msg, "unicodePwd");
2014                         el->flags = LDB_FLAG_MOD_REPLACE;
2015                 }
2016         } else {
2017                 /* the password wasn't specified correctly */
2018                 talloc_free(msg);
2019                 return NT_STATUS_INVALID_PARAMETER;
2020         }
2021
2022         /* build modify request */
2023         ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2024                                 samdb_set_password_callback, NULL);
2025         if (ret != LDB_SUCCESS) {
2026                 talloc_free(msg);
2027                 return NT_STATUS_NO_MEMORY;
2028         }
2029
2030         /* A password change operation */
2031         if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2032                 struct dsdb_control_password_change *change;
2033
2034                 change = talloc(req, struct dsdb_control_password_change);
2035                 if (change == NULL) {
2036                         talloc_free(req);
2037                         talloc_free(msg);
2038                         return NT_STATUS_NO_MEMORY;
2039                 }
2040
2041                 change->old_nt_pwd_hash = ntOldHash;
2042                 change->old_lm_pwd_hash = lmOldHash;
2043
2044                 ret = ldb_request_add_control(req,
2045                                               DSDB_CONTROL_PASSWORD_CHANGE_OID,
2046                                               true, change);
2047                 if (ret != LDB_SUCCESS) {
2048                         talloc_free(req);
2049                         talloc_free(msg);
2050                         return NT_STATUS_NO_MEMORY;
2051                 }
2052         }
2053         ret = ldb_request_add_control(req,
2054                                       DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2055                                       true, NULL);
2056         if (ret != LDB_SUCCESS) {
2057                 talloc_free(req);
2058                 talloc_free(msg);
2059                 return NT_STATUS_NO_MEMORY;
2060         }
2061         ret = ldb_request_add_control(req,
2062                                       DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2063                                       true, NULL);
2064         if (ret != LDB_SUCCESS) {
2065                 talloc_free(req);
2066                 talloc_free(msg);
2067                 return NT_STATUS_NO_MEMORY;
2068         }
2069
2070         ret = dsdb_autotransaction_request(ldb, req);
2071
2072         if (req->context != NULL) {
2073                 pwd_stat = talloc_steal(mem_ctx,
2074                                         ((struct ldb_control *)req->context)->data);
2075         }
2076
2077         talloc_free(req);
2078         talloc_free(msg);
2079
2080         /* Sets the domain info (if requested) */
2081         if (_dominfo != NULL) {
2082                 struct samr_DomInfo1 *dominfo;
2083
2084                 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2085                 if (dominfo == NULL) {
2086                         return NT_STATUS_NO_MEMORY;
2087                 }
2088
2089                 if (pwd_stat != NULL) {
2090                         dominfo->min_password_length     = pwd_stat->domain_data.minPwdLength;
2091                         dominfo->password_properties     = pwd_stat->domain_data.pwdProperties;
2092                         dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2093                         dominfo->max_password_age        = pwd_stat->domain_data.maxPwdAge;
2094                         dominfo->min_password_age        = pwd_stat->domain_data.minPwdAge;
2095                 }
2096
2097                 *_dominfo = dominfo;
2098         }
2099
2100         if (reject_reason != NULL) {
2101                 if (pwd_stat != NULL) {
2102                         *reject_reason = pwd_stat->reject_reason;
2103                 } else {
2104                         *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2105                 }
2106         }
2107
2108         if (pwd_stat != NULL) {
2109                 talloc_free(pwd_stat);
2110         }
2111
2112         if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2113                 const char *errmsg = ldb_errstring(ldb);
2114                 char *endptr = NULL;
2115                 WERROR werr = WERR_GENERAL_FAILURE;
2116                 status = NT_STATUS_UNSUCCESSFUL;
2117                 if (errmsg != NULL) {
2118                         werr = W_ERROR(strtol(errmsg, &endptr, 16));
2119                 }
2120                 if (endptr != errmsg) {
2121                         if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2122                                 status = NT_STATUS_WRONG_PASSWORD;
2123                         }
2124                         if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2125                                 status = NT_STATUS_PASSWORD_RESTRICTION;
2126                         }
2127                 }
2128         } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2129                 /* don't let the caller know if an account doesn't exist */
2130                 status = NT_STATUS_WRONG_PASSWORD;
2131         } else if (ret != LDB_SUCCESS) {
2132                 status = NT_STATUS_UNSUCCESSFUL;
2133         }
2134
2135         return status;
2136 }
2137
2138 /*
2139  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2140  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2141  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2142  * user change or not. The "rejectReason" gives some more information if the
2143  * change failed.
2144  *
2145  * This wrapper function for "samdb_set_password" takes a SID as input rather
2146  * than a user DN.
2147  *
2148  * This call encapsulates a new LDB transaction for changing the password;
2149  * therefore the user hasn't to start a new one.
2150  *
2151  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2152  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2153  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2154  *   NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2155  */
2156 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2157                                 const struct dom_sid *user_sid,
2158                                 const DATA_BLOB *new_password,
2159                                 const struct samr_Password *lmNewHash,
2160                                 const struct samr_Password *ntNewHash,
2161                                 const struct samr_Password *lmOldHash,
2162                                 const struct samr_Password *ntOldHash,
2163                                 enum samPwdChangeReason *reject_reason,
2164                                 struct samr_DomInfo1 **_dominfo) 
2165 {
2166         NTSTATUS nt_status;
2167         struct ldb_dn *user_dn;
2168         int ret;
2169
2170         ret = ldb_transaction_start(ldb);
2171         if (ret != LDB_SUCCESS) {
2172                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2173                 return NT_STATUS_TRANSACTION_ABORTED;
2174         }
2175
2176         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2177                                   "(&(objectSid=%s)(objectClass=user))", 
2178                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2179         if (!user_dn) {
2180                 ldb_transaction_cancel(ldb);
2181                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2182                           dom_sid_string(mem_ctx, user_sid)));
2183                 return NT_STATUS_NO_SUCH_USER;
2184         }
2185
2186         nt_status = samdb_set_password(ldb, mem_ctx,
2187                                        user_dn, NULL,
2188                                        new_password,
2189                                        lmNewHash, ntNewHash,
2190                                        lmOldHash, ntOldHash,
2191                                        reject_reason, _dominfo);
2192         if (!NT_STATUS_IS_OK(nt_status)) {
2193                 ldb_transaction_cancel(ldb);
2194                 talloc_free(user_dn);
2195                 return nt_status;
2196         }
2197
2198         ret = ldb_transaction_commit(ldb);
2199         if (ret != LDB_SUCCESS) {
2200                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2201                          ldb_dn_get_linearized(user_dn),
2202                          ldb_errstring(ldb)));
2203                 talloc_free(user_dn);
2204                 return NT_STATUS_TRANSACTION_ABORTED;
2205         }
2206
2207         talloc_free(user_dn);
2208         return NT_STATUS_OK;
2209 }
2210
2211
2212 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2213                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2214 {
2215         struct ldb_message *msg;
2216         struct ldb_dn *basedn;
2217         char *sidstr;
2218         int ret;
2219
2220         sidstr = dom_sid_string(mem_ctx, sid);
2221         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2222
2223         /* We might have to create a ForeignSecurityPrincipal, even if this user
2224          * is in our own domain */
2225
2226         msg = ldb_msg_new(sidstr);
2227         if (msg == NULL) {
2228                 talloc_free(sidstr);
2229                 return NT_STATUS_NO_MEMORY;
2230         }
2231
2232         ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2233                                 ldb_get_default_basedn(sam_ctx),
2234                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2235                                 &basedn);
2236         if (ret != LDB_SUCCESS) {
2237                 DEBUG(0, ("Failed to find DN for "
2238                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2239                 talloc_free(sidstr);
2240                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2241         }
2242
2243         /* add core elements to the ldb_message for the alias */
2244         msg->dn = basedn;
2245         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2246                 talloc_free(sidstr);
2247                 return NT_STATUS_NO_MEMORY;
2248         }
2249
2250         ret = ldb_msg_add_string(msg, "objectClass",
2251                                  "foreignSecurityPrincipal");
2252         if (ret != LDB_SUCCESS) {
2253                 talloc_free(sidstr);
2254                 return NT_STATUS_NO_MEMORY;
2255         }
2256
2257         /* create the alias */
2258         ret = ldb_add(sam_ctx, msg);
2259         if (ret != LDB_SUCCESS) {
2260                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2261                          "record %s: %s\n", 
2262                          ldb_dn_get_linearized(msg->dn),
2263                          ldb_errstring(sam_ctx)));
2264                 talloc_free(sidstr);
2265                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2266         }
2267
2268         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2269         talloc_free(sidstr);
2270
2271         return NT_STATUS_OK;
2272 }
2273
2274
2275 /*
2276   Find the DN of a domain, assuming it to be a dotted.dns name
2277 */
2278
2279 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2280 {
2281         unsigned int i;
2282         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2283         const char *binary_encoded;
2284         const char **split_realm;
2285         struct ldb_dn *dn;
2286
2287         if (!tmp_ctx) {
2288                 return NULL;
2289         }
2290
2291         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2292         if (!split_realm) {
2293                 talloc_free(tmp_ctx);
2294                 return NULL;
2295         }
2296         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2297         for (i=0; split_realm[i]; i++) {
2298                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2299                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2300                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2301                                   binary_encoded, ldb_dn_get_linearized(dn)));
2302                         talloc_free(tmp_ctx);
2303                         return NULL;
2304                 }
2305         }
2306         if (!ldb_dn_validate(dn)) {
2307                 DEBUG(2, ("Failed to validated DN %s\n",
2308                           ldb_dn_get_linearized(dn)));
2309                 talloc_free(tmp_ctx);
2310                 return NULL;
2311         }
2312         talloc_free(tmp_ctx);
2313         return dn;
2314 }
2315
2316
2317 /*
2318   Find the DNS equivalent of a DN, in dotted DNS form
2319 */
2320 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
2321 {
2322         int i, num_components = ldb_dn_get_comp_num(dn);
2323         char *dns_name = talloc_strdup(mem_ctx, "");
2324         if (dns_name == NULL) {
2325                 return NULL;
2326         }
2327
2328         for (i=0; i<num_components; i++) {
2329                 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
2330                 char *s;
2331                 if (v == NULL) {
2332                         talloc_free(dns_name);
2333                         return NULL;
2334                 }
2335                 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
2336                                                   (int)v->length, (int)v->length, (char *)v->data);
2337                 if (s == NULL) {
2338                         talloc_free(dns_name);
2339                         return NULL;
2340                 }
2341                 dns_name = s;
2342         }
2343
2344         /* remove the last '.' */
2345         if (dns_name[0] != 0) {
2346                 dns_name[strlen(dns_name)-1] = 0;
2347         }
2348
2349         return dns_name;
2350 }
2351
2352 /*
2353   Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
2354   name is based on the forest DNS name
2355 */
2356 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
2357                                 TALLOC_CTX *mem_ctx,
2358                                 const struct GUID *ntds_guid)
2359 {
2360         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2361         const char *guid_str;
2362         struct ldb_dn *forest_dn;
2363         const char *dnsforest;
2364         char *ret;
2365
2366         guid_str = GUID_string(tmp_ctx, ntds_guid);
2367         if (guid_str == NULL) {
2368                 talloc_free(tmp_ctx);
2369                 return NULL;
2370         }
2371         forest_dn = ldb_get_root_basedn(samdb);
2372         if (forest_dn == NULL) {
2373                 talloc_free(tmp_ctx);
2374                 return NULL;
2375         }
2376         dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
2377         if (dnsforest == NULL) {
2378                 talloc_free(tmp_ctx);
2379                 return NULL;
2380         }
2381         ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
2382         talloc_free(tmp_ctx);
2383         return ret;
2384 }
2385
2386
2387 /*
2388   Find the DN of a domain, be it the netbios or DNS name 
2389 */
2390 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2391                                   const char *domain_name) 
2392 {
2393         const char * const domain_ref_attrs[] = {
2394                 "ncName", NULL
2395         };
2396         const char * const domain_ref2_attrs[] = {
2397                 NULL
2398         };
2399         struct ldb_result *res_domain_ref;
2400         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2401         /* find the domain's DN */
2402         int ret_domain = ldb_search(ldb, mem_ctx,
2403                                             &res_domain_ref, 
2404                                             samdb_partitions_dn(ldb, mem_ctx), 
2405                                             LDB_SCOPE_ONELEVEL, 
2406                                             domain_ref_attrs,
2407                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2408                                             escaped_domain);
2409         if (ret_domain != LDB_SUCCESS) {
2410                 return NULL;
2411         }
2412
2413         if (res_domain_ref->count == 0) {
2414                 ret_domain = ldb_search(ldb, mem_ctx,
2415                                                 &res_domain_ref, 
2416                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2417                                                 LDB_SCOPE_BASE,
2418                                                 domain_ref2_attrs,
2419                                                 "(objectclass=domain)");
2420                 if (ret_domain != LDB_SUCCESS) {
2421                         return NULL;
2422                 }
2423
2424                 if (res_domain_ref->count == 1) {
2425                         return res_domain_ref->msgs[0]->dn;
2426                 }
2427                 return NULL;
2428         }
2429
2430         if (res_domain_ref->count > 1) {
2431                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2432                          ret_domain, domain_name));
2433                 return NULL;
2434         }
2435
2436         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2437
2438 }
2439
2440
2441 /*
2442   use a GUID to find a DN
2443  */
2444 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2445                          TALLOC_CTX *mem_ctx,
2446                          const struct GUID *guid, struct ldb_dn **dn)
2447 {
2448         int ret;
2449         struct ldb_result *res;
2450         const char *attrs[] = { NULL };
2451         char *guid_str = GUID_string(mem_ctx, guid);
2452
2453         if (!guid_str) {
2454                 return ldb_operr(ldb);
2455         }
2456
2457         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2458                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2459                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2460                           DSDB_SEARCH_ONE_ONLY,
2461                           "objectGUID=%s", guid_str);
2462         talloc_free(guid_str);
2463         if (ret != LDB_SUCCESS) {
2464                 return ret;
2465         }
2466
2467         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2468         talloc_free(res);
2469
2470         return LDB_SUCCESS;
2471 }
2472
2473 /*
2474   use a DN to find a GUID with a given attribute name
2475  */
2476 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2477                               struct ldb_dn *dn, const char *attribute,
2478                               struct GUID *guid)
2479 {
2480         int ret;
2481         struct ldb_result *res;
2482         const char *attrs[2];
2483         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2484
2485         attrs[0] = attribute;
2486         attrs[1] = NULL;
2487
2488         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2489                              DSDB_SEARCH_SHOW_DELETED |
2490                              DSDB_SEARCH_SHOW_RECYCLED);
2491         if (ret != LDB_SUCCESS) {
2492                 talloc_free(tmp_ctx);
2493                 return ret;
2494         }
2495         if (res->count < 1) {
2496                 talloc_free(tmp_ctx);
2497                 return LDB_ERR_NO_SUCH_OBJECT;
2498         }
2499         *guid = samdb_result_guid(res->msgs[0], attribute);
2500         talloc_free(tmp_ctx);
2501         return LDB_SUCCESS;
2502 }
2503
2504 /*
2505   use a DN to find a GUID
2506  */
2507 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2508                          struct ldb_dn *dn, struct GUID *guid)
2509 {
2510         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2511 }
2512
2513
2514
2515 /*
2516  adds the given GUID to the given ldb_message. This value is added
2517  for the given attr_name (may be either "objectGUID" or "parentGUID").
2518  */
2519 int dsdb_msg_add_guid(struct ldb_message *msg,
2520                 struct GUID *guid,
2521                 const char *attr_name)
2522 {
2523         int ret;
2524         struct ldb_val v;
2525         NTSTATUS status;
2526         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2527
2528         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2529         if (!NT_STATUS_IS_OK(status)) {
2530                 ret = LDB_ERR_OPERATIONS_ERROR;
2531                 goto done;
2532         }
2533
2534         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2535         if (ret != LDB_SUCCESS) {
2536                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2537                                          attr_name));
2538                 goto done;
2539         }
2540
2541         ret = LDB_SUCCESS;
2542
2543 done:
2544         talloc_free(tmp_ctx);
2545         return ret;
2546
2547 }
2548
2549
2550 /*
2551   use a DN to find a SID
2552  */
2553 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2554                         struct ldb_dn *dn, struct dom_sid *sid)
2555 {
2556         int ret;
2557         struct ldb_result *res;
2558         const char *attrs[] = { "objectSid", NULL };
2559         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2560         struct dom_sid *s;
2561
2562         ZERO_STRUCTP(sid);
2563
2564         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2565                              DSDB_SEARCH_SHOW_DELETED |
2566                              DSDB_SEARCH_SHOW_RECYCLED);
2567         if (ret != LDB_SUCCESS) {
2568                 talloc_free(tmp_ctx);
2569                 return ret;
2570         }
2571         if (res->count < 1) {
2572                 talloc_free(tmp_ctx);
2573                 return LDB_ERR_NO_SUCH_OBJECT;
2574         }
2575         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
2576         if (s == NULL) {
2577                 talloc_free(tmp_ctx);
2578                 return LDB_ERR_NO_SUCH_OBJECT;
2579         }
2580         *sid = *s;
2581         talloc_free(tmp_ctx);
2582         return LDB_SUCCESS;
2583 }
2584
2585 /*
2586   use a SID to find a DN
2587  */
2588 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
2589                         TALLOC_CTX *mem_ctx,
2590                         struct dom_sid *sid, struct ldb_dn **dn)
2591 {
2592         int ret;
2593         struct ldb_result *res;
2594         const char *attrs[] = { NULL };
2595         char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
2596
2597         if (!sid_str) {
2598                 return ldb_operr(ldb);
2599         }
2600
2601         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2602                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2603                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2604                           DSDB_SEARCH_ONE_ONLY,
2605                           "objectSid=%s", sid_str);
2606         talloc_free(sid_str);
2607         if (ret != LDB_SUCCESS) {
2608                 return ret;
2609         }
2610
2611         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2612         talloc_free(res);
2613
2614         return LDB_SUCCESS;
2615 }
2616
2617 /*
2618   load a repsFromTo blob list for a given partition GUID
2619   attr must be "repsFrom" or "repsTo"
2620  */
2621 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2622                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2623 {
2624         const char *attrs[] = { attr, NULL };
2625         struct ldb_result *res = NULL;
2626         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2627         unsigned int i;
2628         struct ldb_message_element *el;
2629         int ret;
2630
2631         *r = NULL;
2632         *count = 0;
2633
2634         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
2635         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2636                 /* partition hasn't been replicated yet */
2637                 return WERR_OK;
2638         }
2639         if (ret != LDB_SUCCESS) {
2640                 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
2641                 talloc_free(tmp_ctx);
2642                 return WERR_DS_DRA_INTERNAL_ERROR;
2643         }
2644
2645         el = ldb_msg_find_element(res->msgs[0], attr);
2646         if (el == NULL) {
2647                 /* it's OK to be empty */
2648                 talloc_free(tmp_ctx);
2649                 return WERR_OK;
2650         }
2651
2652         *count = el->num_values;
2653         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2654         if (*r == NULL) {
2655                 talloc_free(tmp_ctx);
2656                 return WERR_DS_DRA_INTERNAL_ERROR;
2657         }
2658
2659         for (i=0; i<(*count); i++) {
2660                 enum ndr_err_code ndr_err;
2661                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2662                                                mem_ctx, 
2663                                                &(*r)[i], 
2664                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2665                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2666                         talloc_free(tmp_ctx);
2667                         return WERR_DS_DRA_INTERNAL_ERROR;
2668                 }
2669         }
2670
2671         talloc_free(tmp_ctx);
2672         
2673         return WERR_OK;
2674 }
2675
2676 /*
2677   save the repsFromTo blob list for a given partition GUID
2678   attr must be "repsFrom" or "repsTo"
2679  */
2680 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2681                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2682 {
2683         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2684         struct ldb_message *msg;
2685         struct ldb_message_element *el;
2686         unsigned int i;
2687
2688         msg = ldb_msg_new(tmp_ctx);
2689         msg->dn = dn;
2690         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2691                 goto failed;
2692         }
2693
2694         el->values = talloc_array(msg, struct ldb_val, count);
2695         if (!el->values) {
2696                 goto failed;
2697         }
2698
2699         for (i=0; i<count; i++) {
2700                 struct ldb_val v;
2701                 enum ndr_err_code ndr_err;
2702
2703                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, 
2704                                                &r[i], 
2705                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2706                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2707                         goto failed;
2708                 }
2709
2710                 el->num_values++;
2711                 el->values[i] = v;
2712         }
2713
2714         if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
2715                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2716                 goto failed;
2717         }
2718
2719         talloc_free(tmp_ctx);
2720         
2721         return WERR_OK;
2722
2723 failed:
2724         talloc_free(tmp_ctx);
2725         return WERR_DS_DRA_INTERNAL_ERROR;
2726 }
2727
2728
2729 /*
2730   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2731   object for a partition
2732  */
2733 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2734                                 uint64_t *uSN, uint64_t *urgent_uSN)
2735 {
2736         struct ldb_request *req;
2737         int ret;
2738         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2739         struct dsdb_control_current_partition *p_ctrl;
2740         struct ldb_result *res;
2741
2742         res = talloc_zero(tmp_ctx, struct ldb_result);
2743         if (!res) {
2744                 talloc_free(tmp_ctx);
2745                 return ldb_oom(ldb);
2746         }
2747
2748         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2749                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2750                                    LDB_SCOPE_BASE,
2751                                    NULL, NULL,
2752                                    NULL,
2753                                    res, ldb_search_default_callback,
2754                                    NULL);
2755         if (ret != LDB_SUCCESS) {
2756                 talloc_free(tmp_ctx);
2757                 return ret;
2758         }
2759
2760         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2761         if (p_ctrl == NULL) {
2762                 talloc_free(tmp_ctx);
2763                 return ldb_oom(ldb);
2764         }
2765         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2766         p_ctrl->dn = dn;
2767         
2768         ret = ldb_request_add_control(req,
2769                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2770                                       false, p_ctrl);
2771         if (ret != LDB_SUCCESS) {
2772                 talloc_free(tmp_ctx);
2773                 return ret;
2774         }
2775         
2776         /* Run the new request */
2777         ret = ldb_request(ldb, req);
2778         
2779         if (ret == LDB_SUCCESS) {
2780                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2781         }
2782
2783         if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
2784                 /* it hasn't been created yet, which means
2785                    an implicit value of zero */
2786                 *uSN = 0;
2787                 talloc_free(tmp_ctx);
2788                 return LDB_SUCCESS;
2789         }
2790
2791         if (ret != LDB_SUCCESS) {
2792                 talloc_free(tmp_ctx);
2793                 return ret;
2794         }
2795
2796         if (res->count < 1) {
2797                 *uSN = 0;
2798                 if (urgent_uSN) {
2799                         *urgent_uSN = 0;
2800                 }
2801         } else {
2802                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2803                 if (urgent_uSN) {
2804                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2805                 }
2806         }
2807
2808         talloc_free(tmp_ctx);
2809
2810         return LDB_SUCCESS;     
2811 }
2812
2813 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2814                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2815 {
2816         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2817 }
2818
2819 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2820                                     const struct drsuapi_DsReplicaCursor *c2)
2821 {
2822         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2823 }
2824
2825
2826 /*
2827   see if a computer identified by its invocationId is a RODC
2828 */
2829 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
2830 {
2831         /* 1) find the DN for this servers NTDSDSA object
2832            2) search for the msDS-isRODC attribute
2833            3) if not present then not a RODC
2834            4) if present and TRUE then is a RODC
2835         */
2836         struct ldb_dn *config_dn;
2837         const char *attrs[] = { "msDS-isRODC", NULL };
2838         int ret;
2839         struct ldb_result *res;
2840         TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
2841
2842         config_dn = ldb_get_config_basedn(sam_ctx);
2843         if (!config_dn) {
2844                 talloc_free(tmp_ctx);
2845                 return ldb_operr(sam_ctx);
2846         }
2847
2848         ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
2849                           DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
2850
2851         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2852                 *is_rodc = false;
2853                 talloc_free(tmp_ctx);
2854                 return LDB_SUCCESS;
2855         }
2856
2857         if (ret != LDB_SUCCESS) {
2858                 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
2859                          GUID_string(tmp_ctx, objectGUID)));
2860                 *is_rodc = false;
2861                 talloc_free(tmp_ctx);
2862                 return ret;
2863         }
2864
2865         ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
2866         *is_rodc = (ret == 1);
2867
2868         talloc_free(tmp_ctx);
2869         return LDB_SUCCESS;
2870 }
2871
2872
2873 /*
2874   see if we are a RODC
2875 */
2876 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
2877 {
2878         const struct GUID *objectGUID;
2879         int ret;
2880         bool *cached;
2881
2882         /* see if we have a cached copy */
2883         cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
2884         if (cached) {
2885                 *am_rodc = *cached;
2886                 return LDB_SUCCESS;
2887         }
2888
2889         objectGUID = samdb_ntds_objectGUID(sam_ctx);
2890         if (!objectGUID) {
2891                 return ldb_operr(sam_ctx);
2892         }
2893
2894         ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
2895         if (ret != LDB_SUCCESS) {
2896                 return ret;
2897         }
2898
2899         cached = talloc(sam_ctx, bool);
2900         if (cached == NULL) {
2901                 return ldb_oom(sam_ctx);
2902         }
2903         *cached = *am_rodc;
2904
2905         ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
2906         if (ret != LDB_SUCCESS) {
2907                 talloc_free(cached);
2908                 return ldb_operr(sam_ctx);
2909         }
2910
2911         return LDB_SUCCESS;
2912 }
2913
2914 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
2915 {
2916         TALLOC_CTX *tmp_ctx;
2917         bool *cached;
2918
2919         tmp_ctx = talloc_new(ldb);
2920         if (tmp_ctx == NULL) {
2921                 goto failed;
2922         }
2923
2924         cached = talloc(tmp_ctx, bool);
2925         if (!cached) {
2926                 goto failed;
2927         }
2928
2929         *cached = am_rodc;
2930         if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
2931                 goto failed;
2932         }
2933
2934         talloc_steal(ldb, cached);
2935         talloc_free(tmp_ctx);
2936         return true;
2937
2938 failed:
2939         DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
2940         talloc_free(tmp_ctx);
2941         return false;
2942 }
2943
2944
2945 /*
2946  * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
2947  * flags are DS_NTDSSETTINGS_OPT_*
2948  */
2949 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
2950                                         uint32_t *options)
2951 {
2952         int rc;
2953         TALLOC_CTX *tmp_ctx;
2954         struct ldb_result *res;
2955         struct ldb_dn *site_dn;
2956         const char *attrs[] = { "options", NULL };
2957
2958         tmp_ctx = talloc_new(ldb_ctx);
2959         if (tmp_ctx == NULL)
2960                 goto failed;
2961
2962         /* Retrieve the site dn for the ldb that we
2963          * have open.  This is our local site.
2964          */
2965         site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
2966         if (site_dn == NULL)
2967                 goto failed;
2968
2969         /* Perform a one level (child) search from the local
2970          * site distinguided name.   We're looking for the
2971          * "options" attribute within the nTDSSiteSettings
2972          * object
2973          */
2974         rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
2975                         LDB_SCOPE_ONELEVEL, attrs,
2976                         "objectClass=nTDSSiteSettings");
2977
2978         if (rc != LDB_SUCCESS || res->count != 1)
2979                 goto failed;
2980
2981         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
2982
2983         talloc_free(tmp_ctx);
2984
2985         return LDB_SUCCESS;
2986
2987 failed:
2988         DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
2989         talloc_free(tmp_ctx);
2990         return LDB_ERR_NO_SUCH_OBJECT;
2991 }
2992
2993 /*
2994   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2995
2996   flags are DS_NTDS_OPTION_*
2997 */
2998 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2999 {
3000         TALLOC_CTX *tmp_ctx;
3001         const char *attrs[] = { "options", NULL };
3002         int ret;
3003         struct ldb_result *res;
3004
3005         tmp_ctx = talloc_new(ldb);
3006         if (tmp_ctx == NULL) {
3007                 goto failed;
3008         }
3009
3010         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
3011         if (ret != LDB_SUCCESS) {
3012                 goto failed;
3013         }
3014
3015         if (res->count != 1) {
3016                 goto failed;
3017         }
3018
3019         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3020
3021         talloc_free(tmp_ctx);
3022
3023         return LDB_SUCCESS;
3024
3025 failed:
3026         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3027         talloc_free(tmp_ctx);
3028         return LDB_ERR_NO_SUCH_OBJECT;
3029 }
3030
3031 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3032 {
3033         const char *attrs[] = { "objectCategory", NULL };
3034         int ret;
3035         struct ldb_result *res;
3036
3037         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
3038         if (ret != LDB_SUCCESS) {
3039                 goto failed;
3040         }
3041
3042         if (res->count != 1) {
3043                 goto failed;
3044         }
3045
3046         return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3047
3048 failed:
3049         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3050         return NULL;
3051 }
3052
3053 /*
3054  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3055  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3056  */
3057 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3058 {
3059         char **tokens, *ret;
3060         size_t i;
3061
3062         tokens = str_list_make(mem_ctx, cn, " -_");
3063         if (tokens == NULL)
3064                 return NULL;
3065
3066         /* "tolower()" and "toupper()" should also work properly on 0x00 */
3067         tokens[0][0] = tolower(tokens[0][0]);
3068         for (i = 1; i < str_list_length((const char **)tokens); i++)
3069                 tokens[i][0] = toupper(tokens[i][0]);
3070
3071         ret = talloc_strdup(mem_ctx, tokens[0]);
3072         for (i = 1; i < str_list_length((const char **)tokens); i++)
3073                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3074
3075         talloc_free(tokens);
3076
3077         return ret;
3078 }
3079
3080 /*
3081  * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3082  */
3083 int dsdb_functional_level(struct ldb_context *ldb)
3084 {
3085         int *domainFunctionality =
3086                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3087         if (!domainFunctionality) {
3088                 /* this is expected during initial provision */
3089                 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3090                 return DS_DOMAIN_FUNCTION_2000;
3091         }
3092         return *domainFunctionality;
3093 }
3094
3095 /*
3096  * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3097  */
3098 int dsdb_forest_functional_level(struct ldb_context *ldb)
3099 {
3100         int *forestFunctionality =
3101                 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3102         if (!forestFunctionality) {
3103                 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3104                 return DS_DOMAIN_FUNCTION_2000;
3105         }
3106         return *forestFunctionality;
3107 }
3108
3109 /*
3110   set a GUID in an extended DN structure
3111  */
3112 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3113 {
3114         struct ldb_val v;
3115         NTSTATUS status;
3116         int ret;
3117
3118         status = GUID_to_ndr_blob(guid, dn, &v);
3119         if (!NT_STATUS_IS_OK(status)) {
3120                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3121         }
3122
3123         ret = ldb_dn_set_extended_component(dn, component_name, &v);
3124         data_blob_free(&v);
3125         return ret;
3126 }
3127
3128 /*
3129   return a GUID from a extended DN structure
3130  */
3131 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3132 {
3133         const struct ldb_val *v;
3134
3135         v = ldb_dn_get_extended_component(dn, component_name);
3136         if (v == NULL) {
3137                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3138         }
3139
3140         return GUID_from_ndr_blob(v, guid);
3141 }
3142
3143 /*
3144   return a uint64_t from a extended DN structure
3145  */
3146 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3147 {
3148         const struct ldb_val *v;
3149         char *s;
3150
3151         v = ldb_dn_get_extended_component(dn, component_name);
3152         if (v == NULL) {
3153                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3154         }
3155         s = talloc_strndup(dn, (const char *)v->data, v->length);
3156         NT_STATUS_HAVE_NO_MEMORY(s);
3157
3158         *val = strtoull(s, NULL, 0);
3159
3160         talloc_free(s);
3161         return NT_STATUS_OK;
3162 }
3163
3164 /*
3165   return a NTTIME from a extended DN structure
3166  */
3167 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3168 {
3169         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3170 }
3171
3172 /*
3173   return a uint32_t from a extended DN structure
3174  */
3175 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3176 {
3177         const struct ldb_val *v;
3178         char *s;
3179
3180         v = ldb_dn_get_extended_component(dn, component_name);
3181         if (v == NULL) {
3182                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3183         }
3184
3185         s = talloc_strndup(dn, (const char *)v->data, v->length);
3186         NT_STATUS_HAVE_NO_MEMORY(s);
3187
3188         *val = strtoul(s, NULL, 0);
3189
3190         talloc_free(s);
3191         return NT_STATUS_OK;
3192 }
3193
3194 /*
3195   return a dom_sid from a extended DN structure
3196  */
3197 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3198 {
3199         const struct ldb_val *sid_blob;
3200         struct TALLOC_CTX *tmp_ctx;
3201         enum ndr_err_code ndr_err;
3202
3203         sid_blob = ldb_dn_get_extended_component(dn, component_name);
3204         if (!sid_blob) {
3205                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3206         }
3207
3208         tmp_ctx = talloc_new(NULL);
3209
3210         ndr_err = ndr_pull_struct_blob_all(sid_blob, tmp_ctx, sid,
3211                                            (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3212         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3213                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3214                 talloc_free(tmp_ctx);
3215                 return status;
3216         }
3217
3218         talloc_free(tmp_ctx);
3219         return NT_STATUS_OK;
3220 }
3221
3222
3223 /*
3224   return RMD_FLAGS directly from a ldb_dn
3225   returns 0 if not found
3226  */
3227 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3228 {
3229         const struct ldb_val *v;
3230         char buf[32];
3231         v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
3232         if (!v || v->length > sizeof(buf)-1) return 0;
3233         strncpy(buf, (const char *)v->data, v->length);
3234         buf[v->length] = 0;
3235         return strtoul(buf, NULL, 10);
3236 }
3237
3238 /*
3239   return RMD_FLAGS directly from a ldb_val for a DN
3240   returns 0 if RMD_FLAGS is not found
3241  */
3242 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3243 {
3244         const char *p;
3245         uint32_t flags;
3246         char *end;
3247
3248         if (val->length < 13) {
3249                 return 0;
3250         }
3251         p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3252         if (!p) {
3253                 return 0;
3254         }
3255         flags = strtoul(p+11, &end, 10);
3256         if (!end || *end != '>') {
3257                 /* it must end in a > */
3258                 return 0;
3259         }
3260         return flags;
3261 }
3262
3263 /*
3264   return true if a ldb_val containing a DN in storage form is deleted
3265  */
3266 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3267 {
3268         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3269 }
3270
3271 /*
3272   return true if a ldb_val containing a DN in storage form is
3273   in the upgraded w2k3 linked attribute format
3274  */
3275 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3276 {
3277         return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
3278 }
3279
3280 /*
3281   return a DN for a wellknown GUID
3282  */
3283 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3284                       struct ldb_dn *nc_root, const char *wk_guid,
3285                       struct ldb_dn **wkguid_dn)
3286 {
3287         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3288         const char *attrs[] = { NULL };
3289         int ret;
3290         struct ldb_dn *dn;
3291         struct ldb_result *res;
3292
3293         /* construct the magic WKGUID DN */
3294         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3295                             wk_guid, ldb_dn_get_linearized(nc_root));
3296         if (!wkguid_dn) {
3297                 talloc_free(tmp_ctx);
3298                 return ldb_operr(samdb);
3299         }
3300
3301         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
3302                              DSDB_SEARCH_SHOW_DELETED |
3303                              DSDB_SEARCH_SHOW_RECYCLED);
3304         if (ret != LDB_SUCCESS) {
3305                 talloc_free(tmp_ctx);
3306                 return ret;
3307         }
3308
3309         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3310         talloc_free(tmp_ctx);
3311         return LDB_SUCCESS;
3312 }
3313
3314
3315 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3316 {
3317         return ldb_dn_compare(*dn1, *dn2);
3318 }
3319
3320 /*
3321   find a NC root given a DN within the NC
3322  */
3323 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3324                       struct ldb_dn **nc_root)
3325 {
3326         const char *root_attrs[] = { "namingContexts", NULL };
3327         TALLOC_CTX *tmp_ctx;
3328         int ret;
3329         struct ldb_message_element *el;
3330         struct ldb_result *root_res;
3331         unsigned int i;
3332         struct ldb_dn **nc_dns;
3333
3334         tmp_ctx = talloc_new(samdb);
3335         if (tmp_ctx == NULL) {
3336                 return ldb_oom(samdb);
3337         }
3338
3339         ret = ldb_search(samdb, tmp_ctx, &root_res,
3340                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3341         if (ret != LDB_SUCCESS) {
3342                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3343                 talloc_free(tmp_ctx);
3344                 return ret;
3345         }
3346
3347         el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3348         if ((el == NULL) || (el->num_values < 3)) {
3349                 struct ldb_message *tmp_msg;
3350
3351                 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list."));
3352
3353                 /* This generates a temporary list of NCs in order to let the
3354                  * provisioning work. */
3355                 tmp_msg = ldb_msg_new(tmp_ctx);
3356                 if (tmp_msg == NULL) {
3357                         talloc_free(tmp_ctx);
3358                         return ldb_oom(samdb);
3359                 }
3360                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3361                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
3362                 if (ret != LDB_SUCCESS) {
3363                         talloc_free(tmp_ctx);
3364                         return ret;
3365                 }
3366                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3367                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
3368                 if (ret != LDB_SUCCESS) {
3369                         talloc_free(tmp_ctx);
3370                         return ret;
3371                 }
3372                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3373                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
3374                 if (ret != LDB_SUCCESS) {
3375                         talloc_free(tmp_ctx);
3376                         return ret;
3377                 }
3378                 el = &tmp_msg->elements[0];
3379         }
3380
3381        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3382        if (!nc_dns) {
3383                talloc_free(tmp_ctx);
3384                return ldb_oom(samdb);
3385        }
3386
3387        for (i=0; i<el->num_values; i++) {
3388                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3389                if (nc_dns[i] == NULL) {
3390                        talloc_free(tmp_ctx);
3391                        return ldb_operr(samdb);
3392                }
3393        }
3394
3395        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3396
3397        for (i=0; i<el->num_values; i++) {
3398                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3399                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3400                        talloc_free(tmp_ctx);
3401                        return LDB_SUCCESS;
3402                }
3403        }
3404
3405        talloc_free(tmp_ctx);
3406        return LDB_ERR_NO_SUCH_OBJECT;
3407 }
3408
3409
3410 /*
3411   find the deleted objects DN for any object, by looking for the NC
3412   root, then looking up the wellknown GUID
3413  */
3414 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3415                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3416                                 struct ldb_dn **do_dn)
3417 {
3418         struct ldb_dn *nc_root;
3419         int ret;
3420
3421         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3422         if (ret != LDB_SUCCESS) {
3423                 return ret;
3424         }
3425
3426         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3427         talloc_free(nc_root);
3428         return ret;
3429 }
3430
3431 /*
3432   return the tombstoneLifetime, in days
3433  */
3434 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3435 {
3436         struct ldb_dn *dn;
3437         dn = ldb_get_config_basedn(ldb);
3438         if (!dn) {
3439                 return LDB_ERR_NO_SUCH_OBJECT;
3440         }
3441         dn = ldb_dn_copy(ldb, dn);
3442         if (!dn) {
3443                 return ldb_operr(ldb);
3444         }
3445         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3446          be a wellknown GUID for this */
3447         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3448                 talloc_free(dn);
3449                 return ldb_operr(ldb);
3450         }
3451
3452         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3453         talloc_free(dn);
3454         return LDB_SUCCESS;
3455 }
3456
3457 /*
3458   compare a ldb_val to a string case insensitively
3459  */
3460 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3461 {
3462         size_t len = strlen(s);
3463         int ret;
3464         if (len > v->length) return 1;
3465         ret = strncasecmp(s, (const char *)v->data, v->length);
3466         if (ret != 0) return ret;
3467         if (v->length > len && v->data[len] != 0) {
3468                 return -1;
3469         }
3470         return 0;
3471 }
3472
3473
3474 /*
3475   load the UDV for a partition in v2 format
3476   The list is returned sorted, and with our local cursor added
3477  */
3478 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3479                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3480 {
3481         static const char *attrs[] = { "replUpToDateVector", NULL };
3482         struct ldb_result *r;
3483         const struct ldb_val *ouv_value;
3484         unsigned int i;
3485         int ret;
3486         uint64_t highest_usn;
3487         const struct GUID *our_invocation_id;
3488         struct timeval now = timeval_current();
3489
3490         ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3491         if (ret != LDB_SUCCESS) {
3492                 return ret;
3493         }
3494
3495         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3496         if (ouv_value) {
3497                 enum ndr_err_code ndr_err;
3498                 struct replUpToDateVectorBlob ouv;
3499
3500                 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
3501                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3502                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3503                         talloc_free(r);
3504                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3505                 }
3506                 if (ouv.version != 2) {
3507                         /* we always store as version 2, and
3508                          * replUpToDateVector is not replicated
3509                          */
3510                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3511                 }
3512
3513                 *count = ouv.ctr.ctr2.count;
3514                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3515         } else {
3516                 *count = 0;
3517                 *cursors = NULL;
3518         }
3519
3520         talloc_free(r);
3521
3522         our_invocation_id = samdb_ntds_invocation_id(samdb);
3523         if (!our_invocation_id) {
3524                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3525                 talloc_free(*cursors);
3526                 return ldb_operr(samdb);
3527         }
3528
3529         ret = dsdb_load_partition_usn(samdb, dn, &highest_usn, NULL);
3530         if (ret != LDB_SUCCESS) {
3531                 /* nothing to add - this can happen after a vampire */
3532                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3533                 return LDB_SUCCESS;
3534         }
3535
3536         for (i=0; i<*count; i++) {
3537                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3538                         (*cursors)[i].highest_usn = highest_usn;
3539                         (*cursors)[i].last_sync_success = timeval_to_nttime(&now);
3540                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3541                         return LDB_SUCCESS;
3542                 }
3543         }
3544
3545         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3546         if (! *cursors) {
3547                 return ldb_oom(samdb);
3548         }
3549
3550         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3551         (*cursors)[*count].highest_usn = highest_usn;
3552         (*cursors)[*count].last_sync_success = timeval_to_nttime(&now);
3553         (*count)++;
3554
3555         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3556
3557         return LDB_SUCCESS;
3558 }
3559
3560 /*
3561   load the UDV for a partition in version 1 format
3562   The list is returned sorted, and with our local cursor added
3563  */
3564 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3565                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3566 {
3567         struct drsuapi_DsReplicaCursor2 *v2;
3568         uint32_t i;
3569         int ret;
3570
3571         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3572         if (ret != LDB_SUCCESS) {
3573                 return ret;
3574         }
3575
3576         if (*count == 0) {
3577                 talloc_free(v2);
3578                 *cursors = NULL;
3579                 return LDB_SUCCESS;
3580         }
3581
3582         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3583         if (*cursors == NULL) {
3584                 talloc_free(v2);
3585                 return ldb_oom(samdb);
3586         }
3587
3588         for (i=0; i<*count; i++) {
3589                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3590                 (*cursors)[i].highest_usn = v2[i].highest_usn;
3591         }
3592         talloc_free(v2);
3593         return LDB_SUCCESS;
3594 }
3595
3596 /*
3597   add a set of controls to a ldb_request structure based on a set of
3598   flags. See util.h for a list of available flags
3599  */
3600 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3601 {
3602         int ret;
3603         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3604                 struct ldb_search_options_control *options;
3605                 /* Using the phantom root control allows us to search all partitions */
3606                 options = talloc(req, struct ldb_search_options_control);
3607                 if (options == NULL) {
3608                         return LDB_ERR_OPERATIONS_ERROR;
3609                 }
3610                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3611
3612                 ret = ldb_request_add_control(req,
3613                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
3614                                               true, options);
3615                 if (ret != LDB_SUCCESS) {
3616                         return ret;
3617                 }
3618         }
3619
3620         if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
3621                 ret = ldb_request_add_control(req,
3622                                               DSDB_CONTROL_NO_GLOBAL_CATALOG,
3623                                               false, NULL);
3624                 if (ret != LDB_SUCCESS) {
3625                         return ret;
3626                 }
3627         }
3628
3629         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3630                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3631                 if (ret != LDB_SUCCESS) {
3632                         return ret;
3633                 }
3634         }
3635
3636         if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
3637                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
3638                 if (ret != LDB_SUCCESS) {
3639                         return ret;
3640                 }
3641         }
3642
3643         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3644                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
3645                 if (ret != LDB_SUCCESS) {
3646                         return ret;
3647                 }
3648         }
3649
3650         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3651                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3652                 if (!extended_ctrl) {
3653                         return LDB_ERR_OPERATIONS_ERROR;
3654                 }
3655                 extended_ctrl->type = 1;
3656
3657                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3658                 if (ret != LDB_SUCCESS) {
3659                         return ret;
3660                 }
3661         }
3662
3663         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3664                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3665                 if (ret != LDB_SUCCESS) {
3666                         return ret;
3667                 }
3668         }
3669
3670         if (dsdb_flags & DSDB_MODIFY_RELAX) {
3671                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3672                 if (ret != LDB_SUCCESS) {
3673                         return ret;
3674                 }
3675         }
3676
3677         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3678                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3679                 if (ret != LDB_SUCCESS) {
3680                         return ret;
3681                 }
3682         }
3683
3684         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3685                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3686                 if (ret != LDB_SUCCESS) {
3687                         return ret;
3688                 }
3689         }
3690
3691         if (dsdb_flags & DSDB_TREE_DELETE) {
3692                 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
3693                 if (ret != LDB_SUCCESS) {
3694                         return ret;
3695                 }
3696         }
3697
3698         if (dsdb_flags & DSDB_PROVISION) {
3699                 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
3700                 if (ret != LDB_SUCCESS) {
3701                         return ret;
3702                 }
3703         }
3704
3705         /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
3706         if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
3707                 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
3708                 if (ret != LDB_SUCCESS) {
3709                         return ret;
3710                 }
3711         }
3712
3713         if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
3714                 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, true, NULL);
3715                 if (ret != LDB_SUCCESS) {
3716                         return ret;
3717                 }
3718         }
3719
3720         if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
3721                 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
3722                 if (ret != LDB_SUCCESS) {
3723                         return ret;
3724                 }
3725         }
3726
3727         return LDB_SUCCESS;
3728 }
3729
3730 /*
3731   an add with a set of controls
3732 */
3733 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
3734              uint32_t dsdb_flags)
3735 {
3736         struct ldb_request *req;
3737         int ret;
3738
3739         ret = ldb_build_add_req(&req, ldb, ldb,
3740                                 message,
3741                                 NULL,
3742                                 NULL,
3743                                 ldb_op_default_callback,
3744                                 NULL);
3745
3746         if (ret != LDB_SUCCESS) return ret;
3747
3748         ret = dsdb_request_add_controls(req, dsdb_flags);
3749         if (ret != LDB_SUCCESS) {
3750                 talloc_free(req);
3751                 return ret;
3752         }
3753
3754         ret = dsdb_autotransaction_request(ldb, req);
3755
3756         talloc_free(req);
3757         return ret;
3758 }
3759
3760 /*
3761   a modify with a set of controls
3762 */
3763 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3764                 uint32_t dsdb_flags)
3765 {
3766         struct ldb_request *req;
3767         int ret;
3768
3769         ret = ldb_build_mod_req(&req, ldb, ldb,
3770                                 message,
3771                                 NULL,
3772                                 NULL,
3773                                 ldb_op_default_callback,
3774                                 NULL);
3775
3776         if (ret != LDB_SUCCESS) return ret;
3777
3778         ret = dsdb_request_add_controls(req, dsdb_flags);
3779         if (ret != LDB_SUCCESS) {
3780                 talloc_free(req);
3781                 return ret;
3782         }
3783
3784         ret = dsdb_autotransaction_request(ldb, req);
3785
3786         talloc_free(req);
3787         return ret;
3788 }
3789
3790 /*
3791   a delete with a set of flags
3792 */
3793 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
3794                 uint32_t dsdb_flags)
3795 {
3796         struct ldb_request *req;
3797         int ret;
3798
3799         ret = ldb_build_del_req(&req, ldb, ldb,
3800                                 dn,
3801                                 NULL,
3802                                 NULL,
3803                                 ldb_op_default_callback,
3804                                 NULL);
3805
3806         if (ret != LDB_SUCCESS) return ret;
3807
3808         ret = dsdb_request_add_controls(req, dsdb_flags);
3809         if (ret != LDB_SUCCESS) {
3810                 talloc_free(req);
3811                 return ret;
3812         }
3813
3814         ret = dsdb_autotransaction_request(ldb, req);
3815
3816         talloc_free(req);
3817         return ret;
3818 }
3819
3820 /*
3821   like dsdb_modify() but set all the element flags to
3822   LDB_FLAG_MOD_REPLACE
3823  */
3824 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3825 {
3826         unsigned int i;
3827
3828         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3829         for (i=0;i<msg->num_elements;i++) {
3830                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3831         }
3832
3833         return dsdb_modify(ldb, msg, dsdb_flags);
3834 }
3835
3836
3837 /*
3838   search for attrs on one DN, allowing for dsdb_flags controls
3839  */
3840 int dsdb_search_dn(struct ldb_context *ldb,
3841                    TALLOC_CTX *mem_ctx,
3842                    struct ldb_result **_res,
3843                    struct ldb_dn *basedn,
3844                    const char * const *attrs,
3845                    uint32_t dsdb_flags)
3846 {
3847         int ret;
3848         struct ldb_request *req;
3849         struct ldb_result *res;
3850
3851         res = talloc_zero(mem_ctx, struct ldb_result);
3852         if (!res) {
3853                 return ldb_oom(ldb);
3854         }
3855
3856         ret = ldb_build_search_req(&req, ldb, res,
3857                                    basedn,
3858                                    LDB_SCOPE_BASE,
3859                                    NULL,
3860                                    attrs,
3861                                    NULL,
3862                                    res,
3863                                    ldb_search_default_callback,
3864                                    NULL);
3865         if (ret != LDB_SUCCESS) {
3866                 talloc_free(res);
3867                 return ret;
3868         }
3869
3870         ret = dsdb_request_add_controls(req, dsdb_flags);
3871         if (ret != LDB_SUCCESS) {
3872                 talloc_free(res);
3873                 return ret;
3874         }
3875
3876         ret = ldb_request(ldb, req);
3877         if (ret == LDB_SUCCESS) {
3878                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3879         }
3880
3881         talloc_free(req);
3882         if (ret != LDB_SUCCESS) {
3883                 talloc_free(res);
3884                 return ret;
3885         }
3886
3887         *_res = res;
3888         return LDB_SUCCESS;
3889 }
3890
3891 /*
3892   search for attrs on one DN, by the GUID of the DN, allowing for
3893   dsdb_flags controls
3894  */
3895 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
3896                            TALLOC_CTX *mem_ctx,
3897                            struct ldb_result **_res,
3898                            const struct GUID *guid,
3899                            const char * const *attrs,
3900                            uint32_t dsdb_flags)
3901 {
3902         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3903         struct ldb_dn *dn;
3904         int ret;
3905
3906         dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
3907         if (dn == NULL) {
3908                 talloc_free(tmp_ctx);
3909                 return ldb_oom(ldb);
3910         }
3911
3912         ret = dsdb_search_dn(ldb, mem_ctx, _res, dn, attrs, dsdb_flags);
3913         talloc_free(tmp_ctx);
3914         return ret;
3915 }
3916
3917 /*
3918   general search with dsdb_flags for controls
3919  */
3920 int dsdb_search(struct ldb_context *ldb,
3921                 TALLOC_CTX *mem_ctx,
3922                 struct ldb_result **_res,
3923                 struct ldb_dn *basedn,
3924                 enum ldb_scope scope,
3925                 const char * const *attrs,
3926                 uint32_t dsdb_flags,
3927                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3928 {
3929         int ret;
3930         struct ldb_request *req;
3931         struct ldb_result *res;
3932         va_list ap;
3933         char *expression = NULL;
3934         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3935
3936         /* cross-partitions searches with a basedn break multi-domain support */
3937         SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
3938
3939         res = talloc_zero(tmp_ctx, struct ldb_result);
3940         if (!res) {
3941                 talloc_free(tmp_ctx);
3942                 return ldb_oom(ldb);
3943         }
3944
3945         if (exp_fmt) {
3946                 va_start(ap, exp_fmt);
3947                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3948                 va_end(ap);
3949
3950                 if (!expression) {
3951                         talloc_free(tmp_ctx);
3952                         return ldb_oom(ldb);
3953                 }
3954         }
3955
3956         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3957                                    basedn,
3958                                    scope,
3959                                    expression,
3960                                    attrs,
3961                                    NULL,
3962                                    res,
3963                                    ldb_search_default_callback,
3964                                    NULL);
3965         if (ret != LDB_SUCCESS) {
3966                 talloc_free(tmp_ctx);
3967                 return ret;
3968         }
3969
3970         ret = dsdb_request_add_controls(req, dsdb_flags);
3971         if (ret != LDB_SUCCESS) {
3972                 talloc_free(tmp_ctx);
3973                 ldb_reset_err_string(ldb);
3974                 return ret;
3975         }
3976
3977         ret = ldb_request(ldb, req);
3978         if (ret == LDB_SUCCESS) {
3979                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3980         }
3981
3982         if (ret != LDB_SUCCESS) {
3983                 talloc_free(tmp_ctx);
3984                 return ret;
3985         }
3986
3987         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
3988                 if (res->count == 0) {
3989                         talloc_free(tmp_ctx);
3990                         ldb_reset_err_string(ldb);
3991                         return LDB_ERR_NO_SUCH_OBJECT;
3992                 }
3993                 if (res->count != 1) {
3994                         talloc_free(tmp_ctx);
3995                         ldb_reset_err_string(ldb);
3996                         return LDB_ERR_CONSTRAINT_VIOLATION;
3997                 }
3998         }
3999
4000         *_res = talloc_steal(mem_ctx, res);
4001         talloc_free(tmp_ctx);
4002
4003         return LDB_SUCCESS;
4004 }
4005
4006
4007 /*
4008   general search with dsdb_flags for controls
4009   returns exactly 1 record or an error
4010  */
4011 int dsdb_search_one(struct ldb_context *ldb,
4012                     TALLOC_CTX *mem_ctx,
4013                     struct ldb_message **msg,
4014                     struct ldb_dn *basedn,
4015                     enum ldb_scope scope,
4016                     const char * const *attrs,
4017                     uint32_t dsdb_flags,
4018                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4019 {
4020         int ret;
4021         struct ldb_result *res;
4022         va_list ap;
4023         char *expression = NULL;
4024         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4025
4026         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4027
4028         res = talloc_zero(tmp_ctx, struct ldb_result);
4029         if (!res) {
4030                 talloc_free(tmp_ctx);
4031                 return ldb_oom(ldb);
4032         }
4033
4034         if (exp_fmt) {
4035                 va_start(ap, exp_fmt);
4036                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4037                 va_end(ap);
4038
4039                 if (!expression) {
4040                         talloc_free(tmp_ctx);
4041                         return ldb_oom(ldb);
4042                 }
4043                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4044                                   dsdb_flags, "%s", expression);
4045         } else {
4046                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4047                                   dsdb_flags, NULL);
4048         }
4049
4050         if (ret != LDB_SUCCESS) {
4051                 talloc_free(tmp_ctx);
4052                 return ret;
4053         }
4054
4055         *msg = talloc_steal(mem_ctx, res->msgs[0]);
4056         talloc_free(tmp_ctx);
4057
4058         return LDB_SUCCESS;
4059 }
4060
4061 /* returns back the forest DNS name */
4062 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4063 {
4064         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4065                                                           ldb_get_root_basedn(ldb));
4066         char *p;
4067
4068         if (forest_name == NULL) {
4069                 return NULL;
4070         }
4071
4072         p = strchr(forest_name, '/');
4073         if (p) {
4074                 *p = '\0';
4075         }
4076
4077         return forest_name;
4078 }
4079
4080 /* returns back the default domain DNS name */
4081 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4082 {
4083         const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4084                                                           ldb_get_default_basedn(ldb));
4085         char *p;
4086
4087         if (domain_name == NULL) {
4088                 return NULL;
4089         }
4090
4091         p = strchr(domain_name, '/');
4092         if (p) {
4093                 *p = '\0';
4094         }
4095
4096         return domain_name;
4097 }
4098
4099 /*
4100    validate that an DSA GUID belongs to the specified user sid.
4101    The user SID must be a domain controller account (either RODC or
4102    RWDC)
4103  */
4104 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4105                            const struct GUID *dsa_guid,
4106                            const struct dom_sid *sid)
4107 {
4108         /* strategy:
4109             - find DN of record with the DSA GUID in the
4110               configuration partition (objectGUID)
4111             - remove "NTDS Settings" component from DN
4112             - do a base search on that DN for serverReference with
4113               extended-dn enabled
4114             - extract objectSid from resulting serverReference
4115               attribute
4116             - check this sid matches the sid argument
4117         */
4118         struct ldb_dn *config_dn;
4119         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4120         struct ldb_message *msg;
4121         const char *attrs1[] = { NULL };
4122         const char *attrs2[] = { "serverReference", NULL };
4123         int ret;
4124         struct ldb_dn *dn, *account_dn;
4125         struct dom_sid sid2;
4126         NTSTATUS status;
4127
4128         config_dn = ldb_get_config_basedn(ldb);
4129
4130         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4131                               attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4132         if (ret != LDB_SUCCESS) {
4133                 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4134                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4135                 talloc_free(tmp_ctx);
4136                 return ldb_operr(ldb);
4137         }
4138         dn = msg->dn;
4139
4140         if (!ldb_dn_remove_child_components(dn, 1)) {
4141                 talloc_free(tmp_ctx);
4142                 return ldb_operr(ldb);
4143         }
4144
4145         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4146                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4147                               "(objectClass=server)");
4148         if (ret != LDB_SUCCESS) {
4149                 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4150                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4151                 talloc_free(tmp_ctx);
4152                 return ldb_operr(ldb);
4153         }
4154
4155         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4156         if (account_dn == NULL) {
4157                 DEBUG(1,(__location__ ": Failed to find account_dn for DSA with objectGUID %s, sid %s\n",
4158                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4159                 talloc_free(tmp_ctx);
4160                 return ldb_operr(ldb);
4161         }
4162
4163         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4164         if (!NT_STATUS_IS_OK(status)) {
4165                 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4166                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4167                 talloc_free(tmp_ctx);
4168                 return ldb_operr(ldb);
4169         }
4170
4171         if (!dom_sid_equal(sid, &sid2)) {
4172                 /* someone is trying to spoof another account */
4173                 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4174                          GUID_string(tmp_ctx, dsa_guid),
4175                          dom_sid_string(tmp_ctx, sid),
4176                          dom_sid_string(tmp_ctx, &sid2)));
4177                 talloc_free(tmp_ctx);
4178                 return ldb_operr(ldb);
4179         }
4180
4181         talloc_free(tmp_ctx);
4182         return LDB_SUCCESS;
4183 }
4184
4185 static const char * const secret_attributes[] = {
4186         DSDB_SECRET_ATTRIBUTES,
4187         NULL
4188 };
4189
4190 /*
4191   check if the attribute belongs to the RODC filtered attribute set
4192   Note that attributes that are in the filtered attribute set are the
4193   ones that _are_ always sent to a RODC
4194 */
4195 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4196 {
4197         /* they never get secret attributes */
4198         if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4199                 return false;
4200         }
4201
4202         /* they do get non-secret critical attributes */
4203         if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4204                 return true;
4205         }
4206
4207         /* they do get non-secret attributes marked as being in the FAS  */
4208         if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4209                 return true;
4210         }
4211
4212         /* other attributes are denied */
4213         return false;
4214 }
4215
4216 /* return fsmo role dn and role owner dn for a particular role*/
4217 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4218                                struct ldb_context *ldb,
4219                                uint32_t role,
4220                                struct ldb_dn **fsmo_role_dn,
4221                                struct ldb_dn **role_owner_dn)
4222 {
4223         int ret;
4224         switch (role) {
4225         case DREPL_NAMING_MASTER:
4226                 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4227                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4228                 if (ret != LDB_SUCCESS) {
4229                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4230                                  ldb_errstring(ldb)));
4231                         talloc_free(tmp_ctx);
4232                         return WERR_DS_DRA_INTERNAL_ERROR;
4233                 }
4234                 break;
4235         case DREPL_INFRASTRUCTURE_MASTER:
4236                 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4237                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4238                 if (ret != LDB_SUCCESS) {
4239                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4240                                  ldb_errstring(ldb)));
4241                         talloc_free(tmp_ctx);
4242                         return WERR_DS_DRA_INTERNAL_ERROR;
4243                 }
4244                 break;
4245         case DREPL_RID_MASTER:
4246                 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
4247                 if (ret != LDB_SUCCESS) {
4248                         DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
4249                         talloc_free(tmp_ctx);
4250                         return WERR_DS_DRA_INTERNAL_ERROR;
4251                 }
4252
4253                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4254                 if (ret != LDB_SUCCESS) {
4255                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
4256                                  ldb_errstring(ldb)));
4257                         talloc_free(tmp_ctx);
4258                         return WERR_DS_DRA_INTERNAL_ERROR;
4259                 }
4260                 break;
4261         case DREPL_SCHEMA_MASTER:
4262                 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
4263                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4264                 if (ret != LDB_SUCCESS) {
4265                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4266                                  ldb_errstring(ldb)));
4267                         talloc_free(tmp_ctx);
4268                         return WERR_DS_DRA_INTERNAL_ERROR;
4269                 }
4270                 break;
4271         case DREPL_PDC_MASTER:
4272                 *fsmo_role_dn = ldb_get_default_basedn(ldb);
4273                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4274                 if (ret != LDB_SUCCESS) {
4275                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
4276                                  ldb_errstring(ldb)));
4277                         talloc_free(tmp_ctx);
4278                         return WERR_DS_DRA_INTERNAL_ERROR;
4279                 }
4280                 break;
4281         default:
4282                 return WERR_DS_DRA_INTERNAL_ERROR;
4283         }
4284         return WERR_OK;
4285 }
4286
4287 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
4288                                     TALLOC_CTX *mem_ctx,
4289                                     struct ldb_dn *server_dn)
4290 {
4291         int ldb_ret;
4292         struct ldb_result *res = NULL;
4293         const char * const attrs[] = { "dNSHostName", NULL};
4294
4295         ldb_ret = ldb_search(ldb, mem_ctx, &res,
4296                              server_dn,
4297                              LDB_SCOPE_BASE,
4298                              attrs, NULL);
4299         if (ldb_ret != LDB_SUCCESS) {
4300                 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
4301                           ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
4302                 return NULL;
4303         }
4304
4305         return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
4306 }
4307
4308 /*
4309   returns true if an attribute is in the filter,
4310   false otherwise, provided that attribute value is provided with the expression
4311 */
4312 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
4313                              const char *attr)
4314 {
4315        unsigned int i;
4316        switch (tree->operation) {
4317        case LDB_OP_AND:
4318        case LDB_OP_OR:
4319                for (i=0;i<tree->u.list.num_elements;i++) {
4320                        if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
4321                                                        attr))
4322                                return true;
4323                }
4324                return false;
4325        case LDB_OP_NOT:
4326                return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
4327        case LDB_OP_EQUALITY:
4328        case LDB_OP_GREATER:
4329        case LDB_OP_LESS:
4330        case LDB_OP_APPROX:
4331                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
4332                        return true;
4333                }
4334                return false;
4335        case LDB_OP_SUBSTRING:
4336                if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
4337                        return true;
4338                }
4339                return false;
4340        case LDB_OP_PRESENT:
4341                /* (attrname=*) is not filtered out */
4342                return false;
4343        case LDB_OP_EXTENDED:
4344                if (tree->u.extended.attr &&
4345                    ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
4346                        return true;
4347                }
4348                return false;
4349        }
4350        return false;
4351 }
4352
4353 bool is_attr_in_list(const char * const * attrs, const char *attr)
4354 {
4355         unsigned int i;
4356
4357         for (i = 0; attrs[i]; i++) {
4358                 if (ldb_attr_cmp(attrs[i], attr) == 0)
4359                         return true;
4360         }
4361
4362         return false;
4363 }
4364
4365
4366 /*
4367   map an ldb error code to an approximate NTSTATUS code
4368  */
4369 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
4370 {
4371         switch (err) {
4372         case LDB_SUCCESS:
4373                 return NT_STATUS_OK;
4374
4375         case LDB_ERR_PROTOCOL_ERROR:
4376                 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
4377
4378         case LDB_ERR_TIME_LIMIT_EXCEEDED:
4379                 return NT_STATUS_IO_TIMEOUT;
4380
4381         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
4382                 return NT_STATUS_BUFFER_TOO_SMALL;
4383
4384         case LDB_ERR_COMPARE_FALSE:
4385         case LDB_ERR_COMPARE_TRUE:
4386                 return NT_STATUS_REVISION_MISMATCH;
4387
4388         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
4389                 return NT_STATUS_NOT_SUPPORTED;
4390
4391         case LDB_ERR_STRONG_AUTH_REQUIRED:
4392         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
4393         case LDB_ERR_SASL_BIND_IN_PROGRESS:
4394         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
4395         case LDB_ERR_INVALID_CREDENTIALS:
4396         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
4397         case LDB_ERR_UNWILLING_TO_PERFORM:
4398                 return NT_STATUS_ACCESS_DENIED;
4399
4400         case LDB_ERR_NO_SUCH_OBJECT:
4401                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4402
4403         case LDB_ERR_REFERRAL:
4404         case LDB_ERR_NO_SUCH_ATTRIBUTE:
4405                 return NT_STATUS_NOT_FOUND;
4406
4407         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
4408                 return NT_STATUS_NOT_SUPPORTED;
4409
4410         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
4411                 return NT_STATUS_BUFFER_TOO_SMALL;
4412
4413         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
4414         case LDB_ERR_INAPPROPRIATE_MATCHING:
4415         case LDB_ERR_CONSTRAINT_VIOLATION:
4416         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
4417         case LDB_ERR_INVALID_DN_SYNTAX:
4418         case LDB_ERR_NAMING_VIOLATION:
4419         case LDB_ERR_OBJECT_CLASS_VIOLATION:
4420         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
4421         case LDB_ERR_NOT_ALLOWED_ON_RDN:
4422                 return NT_STATUS_INVALID_PARAMETER;
4423
4424         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
4425         case LDB_ERR_ENTRY_ALREADY_EXISTS:
4426                 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
4427
4428         case LDB_ERR_BUSY:
4429                 return NT_STATUS_NETWORK_BUSY;
4430
4431         case LDB_ERR_ALIAS_PROBLEM:
4432         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
4433         case LDB_ERR_UNAVAILABLE:
4434         case LDB_ERR_LOOP_DETECT:
4435         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
4436         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
4437         case LDB_ERR_OTHER:
4438         case LDB_ERR_OPERATIONS_ERROR:
4439                 break;
4440         }
4441         return NT_STATUS_UNSUCCESSFUL;
4442 }
4443
4444
4445 /*
4446   create a new naming context that will hold a partial replica
4447  */
4448 int dsdb_create_partial_replica_NC(struct ldb_context *ldb,  struct ldb_dn *dn)
4449 {
4450         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4451         struct ldb_message *msg;
4452         int ret;
4453
4454         msg = ldb_msg_new(tmp_ctx);
4455         if (msg == NULL) {
4456                 talloc_free(tmp_ctx);
4457                 return ldb_oom(ldb);
4458         }
4459
4460         msg->dn = dn;
4461         ret = ldb_msg_add_string(msg, "objectClass", "top");
4462         if (ret != LDB_SUCCESS) {
4463                 talloc_free(tmp_ctx);
4464                 return ldb_oom(ldb);
4465         }
4466
4467         /* [MS-DRSR] implies that we should only add the 'top'
4468          * objectclass, but that would cause lots of problems with our
4469          * objectclass code as top is not structural, so we add
4470          * 'domainDNS' as well to keep things sane. We're expecting
4471          * this new NC to be of objectclass domainDNS after
4472          * replication anyway
4473          */
4474         ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
4475         if (ret != LDB_SUCCESS) {
4476                 talloc_free(tmp_ctx);
4477                 return ldb_oom(ldb);
4478         }
4479
4480         ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
4481                               INSTANCE_TYPE_IS_NC_HEAD|
4482                               INSTANCE_TYPE_NC_ABOVE|
4483                               INSTANCE_TYPE_UNINSTANT);
4484         if (ret != LDB_SUCCESS) {
4485                 talloc_free(tmp_ctx);
4486                 return ldb_oom(ldb);
4487         }
4488
4489         ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
4490         if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
4491                 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
4492                          ldb_dn_get_linearized(dn),
4493                          ldb_errstring(ldb), ldb_strerror(ret)));
4494                 talloc_free(tmp_ctx);
4495                 return ret;
4496         }
4497
4498         DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
4499
4500         talloc_free(tmp_ctx);
4501         return LDB_SUCCESS;
4502 }