s4-lib: Remove unused samdb_msg_set_string()
[sfrench/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  * Sets an unsigned int element in a message
1004  *
1005  * The issue here is that we have not yet first cast to int32_t explicitly,
1006  * before we cast to an signed int to printf() into the %d or cast to a
1007  * int64_t before we then cast to a long long to printf into a %lld.
1008  *
1009  * There are *no* unsigned integers in Active Directory LDAP, even the RID
1010  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
1011  * (See the schema, and the syntax definitions in schema_syntax.c).
1012  *
1013  */
1014 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1015                        struct ldb_message *msg, const char *attr_name,
1016                        unsigned int v)
1017 {
1018         struct ldb_message_element *el;
1019
1020         el = ldb_msg_find_element(msg, attr_name);
1021         if (el) {
1022                 el->num_values = 0;
1023         }
1024         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1025 }
1026
1027 /*
1028  * Handle ldb_request in transaction
1029  */
1030 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1031                                         struct ldb_request *req)
1032 {
1033         int ret;
1034
1035         ret = ldb_transaction_start(sam_ldb);
1036         if (ret != LDB_SUCCESS) {
1037                 return ret;
1038         }
1039
1040         ret = ldb_request(sam_ldb, req);
1041         if (ret == LDB_SUCCESS) {
1042                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1043         }
1044
1045         if (ret == LDB_SUCCESS) {
1046                 return ldb_transaction_commit(sam_ldb);
1047         }
1048         ldb_transaction_cancel(sam_ldb);
1049
1050         return ret;
1051 }
1052
1053 /*
1054   return a default security descriptor
1055 */
1056 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1057 {
1058         struct security_descriptor *sd;
1059
1060         sd = security_descriptor_initialise(mem_ctx);
1061
1062         return sd;
1063 }
1064
1065 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx) 
1066 {
1067         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1068         struct ldb_dn *aggregate_dn;
1069         if (!schema_dn) {
1070                 return NULL;
1071         }
1072
1073         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1074         if (!aggregate_dn) {
1075                 return NULL;
1076         }
1077         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1078                 return NULL;
1079         }
1080         return aggregate_dn;
1081 }
1082
1083 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1084 {
1085         struct ldb_dn *new_dn;
1086
1087         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1088         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1089                 talloc_free(new_dn);
1090                 return NULL;
1091         }
1092         return new_dn;
1093 }
1094
1095 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1096 {
1097        struct ldb_dn *new_dn;
1098
1099        new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1100        if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1101                talloc_free(new_dn);
1102                return NULL;
1103        }
1104        return new_dn;
1105 }
1106
1107 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1108 {
1109         struct ldb_dn *new_dn;
1110
1111         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1112         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1113                 talloc_free(new_dn);
1114                 return NULL;
1115         }
1116         return new_dn;
1117 }
1118
1119 /*
1120   work out the domain sid for the current open ldb
1121 */
1122 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1123 {
1124         TALLOC_CTX *tmp_ctx;
1125         const struct dom_sid *domain_sid;
1126         const char *attrs[] = {
1127                 "objectSid",
1128                 NULL
1129         };
1130         struct ldb_result *res;
1131         int ret;
1132
1133         /* see if we have a cached copy */
1134         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1135         if (domain_sid) {
1136                 return domain_sid;
1137         }
1138
1139         tmp_ctx = talloc_new(ldb);
1140         if (tmp_ctx == NULL) {
1141                 goto failed;
1142         }
1143
1144         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1145
1146         if (ret != LDB_SUCCESS) {
1147                 goto failed;
1148         }
1149
1150         if (res->count != 1) {
1151                 goto failed;
1152         }
1153
1154         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1155         if (domain_sid == NULL) {
1156                 goto failed;
1157         }
1158
1159         /* cache the domain_sid in the ldb */
1160         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1161                 goto failed;
1162         }
1163
1164         talloc_steal(ldb, domain_sid);
1165         talloc_free(tmp_ctx);
1166
1167         return domain_sid;
1168
1169 failed:
1170         talloc_free(tmp_ctx);
1171         return NULL;
1172 }
1173
1174 /*
1175   get domain sid from cache
1176 */
1177 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1178 {
1179         return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1180 }
1181
1182 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1183 {
1184         TALLOC_CTX *tmp_ctx;
1185         struct dom_sid *dom_sid_new;
1186         struct dom_sid *dom_sid_old;
1187
1188         /* see if we have a cached copy */
1189         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1190                                                      "cache.domain_sid"), struct dom_sid);
1191
1192         tmp_ctx = talloc_new(ldb);
1193         if (tmp_ctx == NULL) {
1194                 goto failed;
1195         }
1196
1197         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1198         if (!dom_sid_new) {
1199                 goto failed;
1200         }
1201
1202         /* cache the domain_sid in the ldb */
1203         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1204                 goto failed;
1205         }
1206
1207         talloc_steal(ldb, dom_sid_new);
1208         talloc_free(tmp_ctx);
1209         talloc_free(dom_sid_old);
1210
1211         return true;
1212
1213 failed:
1214         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1215         talloc_free(tmp_ctx);
1216         return false;
1217 }
1218
1219 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1220 {
1221         TALLOC_CTX *tmp_ctx;
1222         struct ldb_dn *ntds_settings_dn_new;
1223         struct ldb_dn *ntds_settings_dn_old;
1224
1225         /* see if we have a forced copy from provision */
1226         ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb, 
1227                                                               "forced.ntds_settings_dn"), struct ldb_dn);
1228
1229         tmp_ctx = talloc_new(ldb);
1230         if (tmp_ctx == NULL) {
1231                 goto failed;
1232         }
1233
1234         ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1235         if (!ntds_settings_dn_new) {
1236                 goto failed;
1237         }
1238
1239         /* set the DN in the ldb to avoid lookups during provision */
1240         if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1241                 goto failed;
1242         }
1243
1244         talloc_steal(ldb, ntds_settings_dn_new);
1245         talloc_free(tmp_ctx);
1246         talloc_free(ntds_settings_dn_old);
1247
1248         return true;
1249
1250 failed:
1251         DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1252         talloc_free(tmp_ctx);
1253         return false;
1254 }
1255
1256 /*
1257   work out the ntds settings dn for the current open ldb
1258 */
1259 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1260 {
1261         TALLOC_CTX *tmp_ctx;
1262         const char *root_attrs[] = { "dsServiceName", NULL };
1263         int ret;
1264         struct ldb_result *root_res;
1265         struct ldb_dn *settings_dn;
1266
1267         /* see if we have a cached copy */
1268         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1269         if (settings_dn) {
1270                 return settings_dn;
1271         }
1272
1273         tmp_ctx = talloc_new(ldb);
1274         if (tmp_ctx == NULL) {
1275                 goto failed;
1276         }
1277
1278         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1279         if (ret != LDB_SUCCESS) {
1280                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1281                          ldb_errstring(ldb)));
1282                 goto failed;
1283         }
1284
1285         if (root_res->count != 1) {
1286                 goto failed;
1287         }
1288
1289         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1290
1291         /* note that we do not cache the DN here, as that would mean
1292          * we could not handle server renames at runtime. Only
1293          * provision sets up forced.ntds_settings_dn */
1294
1295         talloc_steal(ldb, settings_dn);
1296         talloc_free(tmp_ctx);
1297
1298         return settings_dn;
1299
1300 failed:
1301         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1302         talloc_free(tmp_ctx);
1303         return NULL;
1304 }
1305
1306 /*
1307   work out the ntds settings invocationId for the current open ldb
1308 */
1309 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1310 {
1311         TALLOC_CTX *tmp_ctx;
1312         const char *attrs[] = { "invocationId", NULL };
1313         int ret;
1314         struct ldb_result *res;
1315         struct GUID *invocation_id;
1316
1317         /* see if we have a cached copy */
1318         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1319         if (invocation_id) {
1320                 return invocation_id;
1321         }
1322
1323         tmp_ctx = talloc_new(ldb);
1324         if (tmp_ctx == NULL) {
1325                 goto failed;
1326         }
1327
1328         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1329         if (ret) {
1330                 goto failed;
1331         }
1332
1333         if (res->count != 1) {
1334                 goto failed;
1335         }
1336
1337         invocation_id = talloc(tmp_ctx, struct GUID);
1338         if (!invocation_id) {
1339                 goto failed;
1340         }
1341
1342         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1343
1344         /* cache the domain_sid in the ldb */
1345         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1346                 goto failed;
1347         }
1348
1349         talloc_steal(ldb, invocation_id);
1350         talloc_free(tmp_ctx);
1351
1352         return invocation_id;
1353
1354 failed:
1355         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1356         talloc_free(tmp_ctx);
1357         return NULL;
1358 }
1359
1360 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1361 {
1362         TALLOC_CTX *tmp_ctx;
1363         struct GUID *invocation_id_new;
1364         struct GUID *invocation_id_old;
1365
1366         /* see if we have a cached copy */
1367         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1368                                                          "cache.invocation_id");
1369
1370         tmp_ctx = talloc_new(ldb);
1371         if (tmp_ctx == NULL) {
1372                 goto failed;
1373         }
1374
1375         invocation_id_new = talloc(tmp_ctx, struct GUID);
1376         if (!invocation_id_new) {
1377                 goto failed;
1378         }
1379
1380         *invocation_id_new = *invocation_id_in;
1381
1382         /* cache the domain_sid in the ldb */
1383         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1384                 goto failed;
1385         }
1386
1387         talloc_steal(ldb, invocation_id_new);
1388         talloc_free(tmp_ctx);
1389         talloc_free(invocation_id_old);
1390
1391         return true;
1392
1393 failed:
1394         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1395         talloc_free(tmp_ctx);
1396         return false;
1397 }
1398
1399 /*
1400   work out the ntds settings objectGUID for the current open ldb
1401 */
1402 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1403 {
1404         TALLOC_CTX *tmp_ctx;
1405         const char *attrs[] = { "objectGUID", NULL };
1406         int ret;
1407         struct ldb_result *res;
1408         struct GUID *ntds_guid;
1409
1410         /* see if we have a cached copy */
1411         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1412         if (ntds_guid) {
1413                 return ntds_guid;
1414         }
1415
1416         tmp_ctx = talloc_new(ldb);
1417         if (tmp_ctx == NULL) {
1418                 goto failed;
1419         }
1420
1421         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1422         if (ret) {
1423                 goto failed;
1424         }
1425
1426         if (res->count != 1) {
1427                 goto failed;
1428         }
1429
1430         ntds_guid = talloc(tmp_ctx, struct GUID);
1431         if (!ntds_guid) {
1432                 goto failed;
1433         }
1434
1435         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1436
1437         /* cache the domain_sid in the ldb */
1438         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1439                 goto failed;
1440         }
1441
1442         talloc_steal(ldb, ntds_guid);
1443         talloc_free(tmp_ctx);
1444
1445         return ntds_guid;
1446
1447 failed:
1448         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1449         talloc_free(tmp_ctx);
1450         return NULL;
1451 }
1452
1453 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1454 {
1455         TALLOC_CTX *tmp_ctx;
1456         struct GUID *ntds_guid_new;
1457         struct GUID *ntds_guid_old;
1458
1459         /* see if we have a cached copy */
1460         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1461
1462         tmp_ctx = talloc_new(ldb);
1463         if (tmp_ctx == NULL) {
1464                 goto failed;
1465         }
1466
1467         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1468         if (!ntds_guid_new) {
1469                 goto failed;
1470         }
1471
1472         *ntds_guid_new = *ntds_guid_in;
1473
1474         /* cache the domain_sid in the ldb */
1475         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1476                 goto failed;
1477         }
1478
1479         talloc_steal(ldb, ntds_guid_new);
1480         talloc_free(tmp_ctx);
1481         talloc_free(ntds_guid_old);
1482
1483         return true;
1484
1485 failed:
1486         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1487         talloc_free(tmp_ctx);
1488         return false;
1489 }
1490
1491 /*
1492   work out the server dn for the current open ldb
1493 */
1494 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1495 {
1496         return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1497 }
1498
1499 /*
1500   work out the server dn for the current open ldb
1501 */
1502 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1503 {
1504         struct ldb_dn *server_dn;
1505         struct ldb_dn *servers_dn;
1506         struct ldb_dn *server_site_dn;
1507
1508         /* TODO: there must be a saner way to do this!! */
1509         server_dn = samdb_server_dn(ldb, mem_ctx);
1510         if (!server_dn) return NULL;
1511
1512         servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1513         talloc_free(server_dn);
1514         if (!servers_dn) return NULL;
1515
1516         server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1517         talloc_free(servers_dn);
1518
1519         return server_site_dn;
1520 }
1521
1522 /*
1523   find the site name from a computers DN record
1524  */
1525 int samdb_find_site_for_computer(struct ldb_context *ldb,
1526                                  TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1527                                  const char **site_name)
1528 {
1529         int ret;
1530         struct ldb_dn *dn;
1531         const struct ldb_val *rdn_val;
1532
1533         *site_name = NULL;
1534
1535         ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1536         if (ret != LDB_SUCCESS) {
1537                 return ret;
1538         }
1539
1540         if (!ldb_dn_remove_child_components(dn, 2)) {
1541                 talloc_free(dn);
1542                 return LDB_ERR_INVALID_DN_SYNTAX;
1543         }
1544
1545         rdn_val = ldb_dn_get_rdn_val(dn);
1546         if (rdn_val == NULL) {
1547                 return LDB_ERR_OPERATIONS_ERROR;
1548         }
1549
1550         (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1551         talloc_free(dn);
1552         if (!*site_name) {
1553                 return LDB_ERR_OPERATIONS_ERROR;
1554         }
1555         return LDB_SUCCESS;
1556 }
1557
1558 /*
1559   find the NTDS GUID from a computers DN record
1560  */
1561 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1562                                      struct GUID *ntds_guid)
1563 {
1564         int ret;
1565         struct ldb_dn *dn;
1566
1567         *ntds_guid = GUID_zero();
1568
1569         ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1570         if (ret != LDB_SUCCESS) {
1571                 return ret;
1572         }
1573
1574         if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1575                 talloc_free(dn);
1576                 return LDB_ERR_OPERATIONS_ERROR;
1577         }
1578
1579         ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1580         talloc_free(dn);
1581         return ret;
1582 }
1583
1584 /*
1585   find a 'reference' DN that points at another object
1586   (eg. serverReference, rIDManagerReference etc)
1587  */
1588 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1589                        const char *attribute, struct ldb_dn **dn)
1590 {
1591         const char *attrs[2];
1592         struct ldb_result *res;
1593         int ret;
1594
1595         attrs[0] = attribute;
1596         attrs[1] = NULL;
1597
1598         ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY, NULL);
1599         if (ret != LDB_SUCCESS) {
1600                 return ret;
1601         }
1602
1603         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1604         if (!*dn) {
1605                 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1606                         ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1607                                                ldb_dn_get_linearized(base));
1608                 } else {
1609                         ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1610                                                ldb_dn_get_linearized(base));
1611                 }
1612                 talloc_free(res);
1613                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1614         }
1615
1616         talloc_free(res);
1617         return LDB_SUCCESS;
1618 }
1619
1620 /*
1621   find our machine account via the serverReference attribute in the
1622   server DN
1623  */
1624 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1625 {
1626         struct ldb_dn *server_dn;
1627         int ret;
1628
1629         server_dn = samdb_server_dn(ldb, mem_ctx);
1630         if (server_dn == NULL) {
1631                 return LDB_ERR_NO_SUCH_OBJECT;
1632         }
1633
1634         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1635         talloc_free(server_dn);
1636
1637         return ret;
1638 }
1639
1640 /*
1641   find the RID Manager$ DN via the rIDManagerReference attribute in the
1642   base DN
1643  */
1644 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1645 {
1646         return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1647                                   "rIDManagerReference", dn);
1648 }
1649
1650 /*
1651   find the RID Set DN via the rIDSetReferences attribute in our
1652   machine account DN
1653  */
1654 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1655 {
1656         struct ldb_dn *server_ref_dn;
1657         int ret;
1658
1659         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1660         if (ret != LDB_SUCCESS) {
1661                 return ret;
1662         }
1663         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1664         talloc_free(server_ref_dn);
1665         return ret;
1666 }
1667
1668 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1669 {
1670         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1671                                                                             mem_ctx));
1672
1673         if (val == NULL) {
1674                 return NULL;
1675         }
1676
1677         return (const char *) val->data;
1678 }
1679
1680 /*
1681  * Finds the client site by using the client's IP address.
1682  * The "subnet_name" returns the name of the subnet if parameter != NULL
1683  */
1684 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1685                                    const char *ip_address, char **subnet_name)
1686 {
1687         const char *attrs[] = { "cn", "siteObject", NULL };
1688         struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1689         struct ldb_result *res;
1690         const struct ldb_val *val;
1691         const char *site_name = NULL, *l_subnet_name = NULL;
1692         const char *allow_list[2] = { NULL, NULL };
1693         unsigned int i, count;
1694         int cnt, ret;
1695
1696         /*
1697          * if we don't have a client ip e.g. ncalrpc
1698          * the server site is the client site
1699          */
1700         if (ip_address == NULL) {
1701                 return samdb_server_site_name(ldb, mem_ctx);
1702         }
1703
1704         sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1705         if (sites_container_dn == NULL) {
1706                 return NULL;
1707         }
1708
1709         subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1710         if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1711                 talloc_free(sites_container_dn);
1712                 talloc_free(subnets_dn);
1713                 return NULL;
1714         }
1715
1716         ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1717                          attrs, NULL);
1718         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1719                 count = 0;
1720         } else if (ret != LDB_SUCCESS) {
1721                 talloc_free(sites_container_dn);
1722                 talloc_free(subnets_dn);
1723                 return NULL;
1724         } else {
1725                 count = res->count;
1726         }
1727
1728         for (i = 0; i < count; i++) {
1729                 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1730                                                             NULL);
1731
1732                 allow_list[0] = l_subnet_name;
1733
1734                 if (socket_allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1735                         sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1736                                                            res->msgs[i],
1737                                                            "siteObject");
1738                         if (sites_dn == NULL) {
1739                                 /* No reference, maybe another subnet matches */
1740                                 continue;
1741                         }
1742
1743                         /* "val" cannot be NULL here since "sites_dn" != NULL */
1744                         val = ldb_dn_get_rdn_val(sites_dn);
1745                         site_name = talloc_strdup(mem_ctx,
1746                                                   (const char *) val->data);
1747
1748                         talloc_free(sites_dn);
1749
1750                         break;
1751                 }
1752         }
1753
1754         if (site_name == NULL) {
1755                 /* This is the Windows Server fallback rule: when no subnet
1756                  * exists and we have only one site available then use it (it
1757                  * is for sure the same as our server site). If more sites do
1758                  * exist then we don't know which one to use and set the site
1759                  * name to "". */
1760                 cnt = samdb_search_count(ldb, mem_ctx, sites_container_dn,
1761                                          "(objectClass=site)");
1762                 if (cnt == 1) {
1763                         site_name = samdb_server_site_name(ldb, mem_ctx);
1764                 } else {
1765                         site_name = talloc_strdup(mem_ctx, "");
1766                 }
1767                 l_subnet_name = NULL;
1768         }
1769
1770         if (subnet_name != NULL) {
1771                 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1772         }
1773
1774         talloc_free(sites_container_dn);
1775         talloc_free(subnets_dn);
1776         talloc_free(res);
1777
1778         return site_name;
1779 }
1780
1781 /*
1782   work out if we are the PDC for the domain of the current open ldb
1783 */
1784 bool samdb_is_pdc(struct ldb_context *ldb)
1785 {
1786         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1787         int ret;
1788         struct ldb_result *dom_res;
1789         TALLOC_CTX *tmp_ctx;
1790         bool is_pdc;
1791         struct ldb_dn *pdc;
1792
1793         tmp_ctx = talloc_new(ldb);
1794         if (tmp_ctx == NULL) {
1795                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1796                 return false;
1797         }
1798
1799         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1800         if (ret != LDB_SUCCESS) {
1801                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1802                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1803                          ldb_errstring(ldb)));
1804                 goto failed;
1805         }
1806         if (dom_res->count != 1) {
1807                 goto failed;
1808         }
1809
1810         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1811
1812         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1813                 is_pdc = true;
1814         } else {
1815                 is_pdc = false;
1816         }
1817
1818         talloc_free(tmp_ctx);
1819
1820         return is_pdc;
1821
1822 failed:
1823         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1824         talloc_free(tmp_ctx);
1825         return false;
1826 }
1827
1828 /*
1829   work out if we are a Global Catalog server for the domain of the current open ldb
1830 */
1831 bool samdb_is_gc(struct ldb_context *ldb)
1832 {
1833         uint32_t options;
1834         if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
1835                 return false;
1836         }
1837         return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
1838 }
1839
1840 /* Find a domain object in the parents of a particular DN.  */
1841 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1842                                    struct ldb_dn **parent_dn, const char **errstring)
1843 {
1844         TALLOC_CTX *local_ctx;
1845         struct ldb_dn *sdn = dn;
1846         struct ldb_result *res = NULL;
1847         int ret = LDB_SUCCESS;
1848         const char *attrs[] = { NULL };
1849
1850         local_ctx = talloc_new(mem_ctx);
1851         if (local_ctx == NULL) return ldb_oom(ldb);
1852
1853         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1854                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1855                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1856                 if (ret == LDB_SUCCESS) {
1857                         if (res->count == 1) {
1858                                 break;
1859                         }
1860                 } else {
1861                         break;
1862                 }
1863         }
1864
1865         if (ret != LDB_SUCCESS) {
1866                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1867                                              ldb_dn_get_linearized(dn),
1868                                              ldb_dn_get_linearized(sdn),
1869                                              ldb_errstring(ldb));
1870                 talloc_free(local_ctx);
1871                 return ret;
1872         }
1873         if (res->count != 1) {
1874                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1875                                              ldb_dn_get_linearized(dn));
1876                 DEBUG(0,(__location__ ": %s\n", *errstring));
1877                 talloc_free(local_ctx);
1878                 return LDB_ERR_CONSTRAINT_VIOLATION;
1879         }
1880
1881         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1882         talloc_free(local_ctx);
1883         return ret;
1884 }
1885
1886
1887 /*
1888  * Performs checks on a user password (plaintext UNIX format - attribute
1889  * "password"). The remaining parameters have to be extracted from the domain
1890  * object in the AD.
1891  *
1892  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1893  */
1894 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1895                                                 const uint32_t pwdProperties,
1896                                                 const uint32_t minPwdLength)
1897 {
1898         /* checks if the "minPwdLength" property is satisfied */
1899         if (minPwdLength > password->length)
1900                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1901
1902         /* checks the password complexity */
1903         if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1904                         && (password->data != NULL)
1905                         && (!check_password_quality((const char *) password->data)))
1906                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1907
1908         return SAMR_VALIDATION_STATUS_SUCCESS;
1909 }
1910
1911 /*
1912  * Callback for "samdb_set_password" password change
1913  */
1914 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
1915 {
1916         int ret;
1917
1918         if (!ares) {
1919                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1920         }
1921
1922         if (ares->error != LDB_SUCCESS) {
1923                 ret = ares->error;
1924                 req->context = talloc_steal(req,
1925                                             ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1926                 talloc_free(ares);
1927                 return ldb_request_done(req, ret);
1928         }
1929
1930         if (ares->type != LDB_REPLY_DONE) {
1931                 talloc_free(ares);
1932                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1933         }
1934
1935         req->context = talloc_steal(req,
1936                                     ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1937         talloc_free(ares);
1938         return ldb_request_done(req, LDB_SUCCESS);
1939 }
1940
1941 /*
1942  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1943  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1944  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
1945  * user change or not. The "rejectReason" gives some more information if the
1946  * change failed.
1947  *
1948  * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1949  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
1950  */
1951 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1952                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1953                             const DATA_BLOB *new_password,
1954                             const struct samr_Password *lmNewHash,
1955                             const struct samr_Password *ntNewHash,
1956                             const struct samr_Password *lmOldHash,
1957                             const struct samr_Password *ntOldHash,
1958                             enum samPwdChangeReason *reject_reason,
1959                             struct samr_DomInfo1 **_dominfo)
1960 {
1961         struct ldb_message *msg;
1962         struct ldb_message_element *el;
1963         struct ldb_request *req;
1964         struct dsdb_control_password_change_status *pwd_stat = NULL;
1965         int ret;
1966         NTSTATUS status = NT_STATUS_OK;
1967
1968 #define CHECK_RET(x) \
1969         if (x != LDB_SUCCESS) { \
1970                 talloc_free(msg); \
1971                 return NT_STATUS_NO_MEMORY; \
1972         }
1973
1974         msg = ldb_msg_new(mem_ctx);
1975         if (msg == NULL) {
1976                 return NT_STATUS_NO_MEMORY;
1977         }
1978         msg->dn = user_dn;
1979         if ((new_password != NULL)
1980                         && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
1981                 /* we have the password as plaintext UTF16 */
1982                 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
1983                                             new_password, NULL));
1984                 el = ldb_msg_find_element(msg, "clearTextPassword");
1985                 el->flags = LDB_FLAG_MOD_REPLACE;
1986         } else if ((new_password == NULL)
1987                         && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
1988                 /* we have a password as LM and/or NT hash */
1989                 if (lmNewHash != NULL) {
1990                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
1991                                 "dBCSPwd", lmNewHash));
1992                         el = ldb_msg_find_element(msg, "dBCSPwd");
1993                         el->flags = LDB_FLAG_MOD_REPLACE;
1994                 }
1995                 if (ntNewHash != NULL) {
1996                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
1997                                 "unicodePwd", ntNewHash));
1998                         el = ldb_msg_find_element(msg, "unicodePwd");
1999                         el->flags = LDB_FLAG_MOD_REPLACE;
2000                 }
2001         } else {
2002                 /* the password wasn't specified correctly */
2003                 talloc_free(msg);
2004                 return NT_STATUS_INVALID_PARAMETER;
2005         }
2006
2007         /* build modify request */
2008         ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2009                                 samdb_set_password_callback, NULL);
2010         if (ret != LDB_SUCCESS) {
2011                 talloc_free(msg);
2012                 return NT_STATUS_NO_MEMORY;
2013         }
2014
2015         /* A password change operation */
2016         if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2017                 struct dsdb_control_password_change *change;
2018
2019                 change = talloc(req, struct dsdb_control_password_change);
2020                 if (change == NULL) {
2021                         talloc_free(req);
2022                         talloc_free(msg);
2023                         return NT_STATUS_NO_MEMORY;
2024                 }
2025
2026                 change->old_nt_pwd_hash = ntOldHash;
2027                 change->old_lm_pwd_hash = lmOldHash;
2028
2029                 ret = ldb_request_add_control(req,
2030                                               DSDB_CONTROL_PASSWORD_CHANGE_OID,
2031                                               true, change);
2032                 if (ret != LDB_SUCCESS) {
2033                         talloc_free(req);
2034                         talloc_free(msg);
2035                         return NT_STATUS_NO_MEMORY;
2036                 }
2037         }
2038         ret = ldb_request_add_control(req,
2039                                       DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2040                                       true, NULL);
2041         if (ret != LDB_SUCCESS) {
2042                 talloc_free(req);
2043                 talloc_free(msg);
2044                 return NT_STATUS_NO_MEMORY;
2045         }
2046         ret = ldb_request_add_control(req,
2047                                       DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2048                                       true, NULL);
2049         if (ret != LDB_SUCCESS) {
2050                 talloc_free(req);
2051                 talloc_free(msg);
2052                 return NT_STATUS_NO_MEMORY;
2053         }
2054
2055         ret = dsdb_autotransaction_request(ldb, req);
2056
2057         if (req->context != NULL) {
2058                 pwd_stat = talloc_steal(mem_ctx,
2059                                         ((struct ldb_control *)req->context)->data);
2060         }
2061
2062         talloc_free(req);
2063         talloc_free(msg);
2064
2065         /* Sets the domain info (if requested) */
2066         if (_dominfo != NULL) {
2067                 struct samr_DomInfo1 *dominfo;
2068
2069                 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2070                 if (dominfo == NULL) {
2071                         return NT_STATUS_NO_MEMORY;
2072                 }
2073
2074                 if (pwd_stat != NULL) {
2075                         dominfo->min_password_length     = pwd_stat->domain_data.minPwdLength;
2076                         dominfo->password_properties     = pwd_stat->domain_data.pwdProperties;
2077                         dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2078                         dominfo->max_password_age        = pwd_stat->domain_data.maxPwdAge;
2079                         dominfo->min_password_age        = pwd_stat->domain_data.minPwdAge;
2080                 }
2081
2082                 *_dominfo = dominfo;
2083         }
2084
2085         if (reject_reason != NULL) {
2086                 if (pwd_stat != NULL) {
2087                         *reject_reason = pwd_stat->reject_reason;
2088                 } else {
2089                         *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2090                 }
2091         }
2092
2093         if (pwd_stat != NULL) {
2094                 talloc_free(pwd_stat);
2095         }
2096
2097         if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2098                 const char *errmsg = ldb_errstring(ldb);
2099                 char *endptr = NULL;
2100                 WERROR werr = WERR_GENERAL_FAILURE;
2101                 status = NT_STATUS_UNSUCCESSFUL;
2102                 if (errmsg != NULL) {
2103                         werr = W_ERROR(strtol(errmsg, &endptr, 16));
2104                 }
2105                 if (endptr != errmsg) {
2106                         if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2107                                 status = NT_STATUS_WRONG_PASSWORD;
2108                         }
2109                         if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2110                                 status = NT_STATUS_PASSWORD_RESTRICTION;
2111                         }
2112                 }
2113         } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2114                 /* don't let the caller know if an account doesn't exist */
2115                 status = NT_STATUS_WRONG_PASSWORD;
2116         } else if (ret != LDB_SUCCESS) {
2117                 status = NT_STATUS_UNSUCCESSFUL;
2118         }
2119
2120         return status;
2121 }
2122
2123 /*
2124  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2125  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2126  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2127  * user change or not. The "rejectReason" gives some more information if the
2128  * change failed.
2129  *
2130  * This wrapper function for "samdb_set_password" takes a SID as input rather
2131  * than a user DN.
2132  *
2133  * This call encapsulates a new LDB transaction for changing the password;
2134  * therefore the user hasn't to start a new one.
2135  *
2136  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2137  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2138  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2139  *   NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2140  */
2141 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2142                                 const struct dom_sid *user_sid,
2143                                 const DATA_BLOB *new_password,
2144                                 const struct samr_Password *lmNewHash,
2145                                 const struct samr_Password *ntNewHash,
2146                                 const struct samr_Password *lmOldHash,
2147                                 const struct samr_Password *ntOldHash,
2148                                 enum samPwdChangeReason *reject_reason,
2149                                 struct samr_DomInfo1 **_dominfo) 
2150 {
2151         NTSTATUS nt_status;
2152         struct ldb_dn *user_dn;
2153         int ret;
2154
2155         ret = ldb_transaction_start(ldb);
2156         if (ret != LDB_SUCCESS) {
2157                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2158                 return NT_STATUS_TRANSACTION_ABORTED;
2159         }
2160
2161         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2162                                   "(&(objectSid=%s)(objectClass=user))", 
2163                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2164         if (!user_dn) {
2165                 ldb_transaction_cancel(ldb);
2166                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2167                           dom_sid_string(mem_ctx, user_sid)));
2168                 return NT_STATUS_NO_SUCH_USER;
2169         }
2170
2171         nt_status = samdb_set_password(ldb, mem_ctx,
2172                                        user_dn, NULL,
2173                                        new_password,
2174                                        lmNewHash, ntNewHash,
2175                                        lmOldHash, ntOldHash,
2176                                        reject_reason, _dominfo);
2177         if (!NT_STATUS_IS_OK(nt_status)) {
2178                 ldb_transaction_cancel(ldb);
2179                 talloc_free(user_dn);
2180                 return nt_status;
2181         }
2182
2183         ret = ldb_transaction_commit(ldb);
2184         if (ret != LDB_SUCCESS) {
2185                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2186                          ldb_dn_get_linearized(user_dn),
2187                          ldb_errstring(ldb)));
2188                 talloc_free(user_dn);
2189                 return NT_STATUS_TRANSACTION_ABORTED;
2190         }
2191
2192         talloc_free(user_dn);
2193         return NT_STATUS_OK;
2194 }
2195
2196
2197 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2198                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2199 {
2200         struct ldb_message *msg;
2201         struct ldb_dn *basedn;
2202         char *sidstr;
2203         int ret;
2204
2205         sidstr = dom_sid_string(mem_ctx, sid);
2206         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2207
2208         /* We might have to create a ForeignSecurityPrincipal, even if this user
2209          * is in our own domain */
2210
2211         msg = ldb_msg_new(sidstr);
2212         if (msg == NULL) {
2213                 talloc_free(sidstr);
2214                 return NT_STATUS_NO_MEMORY;
2215         }
2216
2217         ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2218                                 ldb_get_default_basedn(sam_ctx),
2219                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2220                                 &basedn);
2221         if (ret != LDB_SUCCESS) {
2222                 DEBUG(0, ("Failed to find DN for "
2223                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2224                 talloc_free(sidstr);
2225                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2226         }
2227
2228         /* add core elements to the ldb_message for the alias */
2229         msg->dn = basedn;
2230         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2231                 talloc_free(sidstr);
2232                 return NT_STATUS_NO_MEMORY;
2233         }
2234
2235         ret = ldb_msg_add_string(msg, "objectClass",
2236                                  "foreignSecurityPrincipal");
2237         if (ret != LDB_SUCCESS) {
2238                 talloc_free(sidstr);
2239                 return NT_STATUS_NO_MEMORY;
2240         }
2241
2242         /* create the alias */
2243         ret = ldb_add(sam_ctx, msg);
2244         if (ret != LDB_SUCCESS) {
2245                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2246                          "record %s: %s\n", 
2247                          ldb_dn_get_linearized(msg->dn),
2248                          ldb_errstring(sam_ctx)));
2249                 talloc_free(sidstr);
2250                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2251         }
2252
2253         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2254         talloc_free(sidstr);
2255
2256         return NT_STATUS_OK;
2257 }
2258
2259
2260 /*
2261   Find the DN of a domain, assuming it to be a dotted.dns name
2262 */
2263
2264 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2265 {
2266         unsigned int i;
2267         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2268         const char *binary_encoded;
2269         const char **split_realm;
2270         struct ldb_dn *dn;
2271
2272         if (!tmp_ctx) {
2273                 return NULL;
2274         }
2275
2276         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2277         if (!split_realm) {
2278                 talloc_free(tmp_ctx);
2279                 return NULL;
2280         }
2281         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2282         for (i=0; split_realm[i]; i++) {
2283                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2284                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2285                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2286                                   binary_encoded, ldb_dn_get_linearized(dn)));
2287                         talloc_free(tmp_ctx);
2288                         return NULL;
2289                 }
2290         }
2291         if (!ldb_dn_validate(dn)) {
2292                 DEBUG(2, ("Failed to validated DN %s\n",
2293                           ldb_dn_get_linearized(dn)));
2294                 talloc_free(tmp_ctx);
2295                 return NULL;
2296         }
2297         talloc_free(tmp_ctx);
2298         return dn;
2299 }
2300
2301
2302 /*
2303   Find the DNS equivalent of a DN, in dotted DNS form
2304 */
2305 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
2306 {
2307         int i, num_components = ldb_dn_get_comp_num(dn);
2308         char *dns_name = talloc_strdup(mem_ctx, "");
2309         if (dns_name == NULL) {
2310                 return NULL;
2311         }
2312
2313         for (i=0; i<num_components; i++) {
2314                 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
2315                 char *s;
2316                 if (v == NULL) {
2317                         talloc_free(dns_name);
2318                         return NULL;
2319                 }
2320                 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
2321                                                   (int)v->length, (int)v->length, (char *)v->data);
2322                 if (s == NULL) {
2323                         talloc_free(dns_name);
2324                         return NULL;
2325                 }
2326                 dns_name = s;
2327         }
2328
2329         /* remove the last '.' */
2330         if (dns_name[0] != 0) {
2331                 dns_name[strlen(dns_name)-1] = 0;
2332         }
2333
2334         return dns_name;
2335 }
2336
2337 /*
2338   Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
2339   name is based on the forest DNS name
2340 */
2341 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
2342                                 TALLOC_CTX *mem_ctx,
2343                                 const struct GUID *ntds_guid)
2344 {
2345         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2346         const char *guid_str;
2347         struct ldb_dn *forest_dn;
2348         const char *dnsforest;
2349         char *ret;
2350
2351         guid_str = GUID_string(tmp_ctx, ntds_guid);
2352         if (guid_str == NULL) {
2353                 talloc_free(tmp_ctx);
2354                 return NULL;
2355         }
2356         forest_dn = ldb_get_root_basedn(samdb);
2357         if (forest_dn == NULL) {
2358                 talloc_free(tmp_ctx);
2359                 return NULL;
2360         }
2361         dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
2362         if (dnsforest == NULL) {
2363                 talloc_free(tmp_ctx);
2364                 return NULL;
2365         }
2366         ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
2367         talloc_free(tmp_ctx);
2368         return ret;
2369 }
2370
2371
2372 /*
2373   Find the DN of a domain, be it the netbios or DNS name 
2374 */
2375 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2376                                   const char *domain_name) 
2377 {
2378         const char * const domain_ref_attrs[] = {
2379                 "ncName", NULL
2380         };
2381         const char * const domain_ref2_attrs[] = {
2382                 NULL
2383         };
2384         struct ldb_result *res_domain_ref;
2385         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2386         /* find the domain's DN */
2387         int ret_domain = ldb_search(ldb, mem_ctx,
2388                                             &res_domain_ref, 
2389                                             samdb_partitions_dn(ldb, mem_ctx), 
2390                                             LDB_SCOPE_ONELEVEL, 
2391                                             domain_ref_attrs,
2392                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2393                                             escaped_domain);
2394         if (ret_domain != LDB_SUCCESS) {
2395                 return NULL;
2396         }
2397
2398         if (res_domain_ref->count == 0) {
2399                 ret_domain = ldb_search(ldb, mem_ctx,
2400                                                 &res_domain_ref, 
2401                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2402                                                 LDB_SCOPE_BASE,
2403                                                 domain_ref2_attrs,
2404                                                 "(objectclass=domain)");
2405                 if (ret_domain != LDB_SUCCESS) {
2406                         return NULL;
2407                 }
2408
2409                 if (res_domain_ref->count == 1) {
2410                         return res_domain_ref->msgs[0]->dn;
2411                 }
2412                 return NULL;
2413         }
2414
2415         if (res_domain_ref->count > 1) {
2416                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2417                          ret_domain, domain_name));
2418                 return NULL;
2419         }
2420
2421         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2422
2423 }
2424
2425
2426 /*
2427   use a GUID to find a DN
2428  */
2429 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2430                          TALLOC_CTX *mem_ctx,
2431                          const struct GUID *guid, struct ldb_dn **dn)
2432 {
2433         int ret;
2434         struct ldb_result *res;
2435         const char *attrs[] = { NULL };
2436         char *guid_str = GUID_string(mem_ctx, guid);
2437
2438         if (!guid_str) {
2439                 return ldb_operr(ldb);
2440         }
2441
2442         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2443                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2444                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2445                           DSDB_SEARCH_ONE_ONLY,
2446                           "objectGUID=%s", guid_str);
2447         talloc_free(guid_str);
2448         if (ret != LDB_SUCCESS) {
2449                 return ret;
2450         }
2451
2452         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2453         talloc_free(res);
2454
2455         return LDB_SUCCESS;
2456 }
2457
2458 /*
2459   use a DN to find a GUID with a given attribute name
2460  */
2461 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2462                               struct ldb_dn *dn, const char *attribute,
2463                               struct GUID *guid)
2464 {
2465         int ret;
2466         struct ldb_result *res;
2467         const char *attrs[2];
2468         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2469
2470         attrs[0] = attribute;
2471         attrs[1] = NULL;
2472
2473         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2474                              DSDB_SEARCH_SHOW_DELETED |
2475                              DSDB_SEARCH_SHOW_RECYCLED);
2476         if (ret != LDB_SUCCESS) {
2477                 talloc_free(tmp_ctx);
2478                 return ret;
2479         }
2480         if (res->count < 1) {
2481                 talloc_free(tmp_ctx);
2482                 return LDB_ERR_NO_SUCH_OBJECT;
2483         }
2484         *guid = samdb_result_guid(res->msgs[0], attribute);
2485         talloc_free(tmp_ctx);
2486         return LDB_SUCCESS;
2487 }
2488
2489 /*
2490   use a DN to find a GUID
2491  */
2492 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2493                          struct ldb_dn *dn, struct GUID *guid)
2494 {
2495         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2496 }
2497
2498
2499
2500 /*
2501  adds the given GUID to the given ldb_message. This value is added
2502  for the given attr_name (may be either "objectGUID" or "parentGUID").
2503  */
2504 int dsdb_msg_add_guid(struct ldb_message *msg,
2505                 struct GUID *guid,
2506                 const char *attr_name)
2507 {
2508         int ret;
2509         struct ldb_val v;
2510         NTSTATUS status;
2511         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2512
2513         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2514         if (!NT_STATUS_IS_OK(status)) {
2515                 ret = LDB_ERR_OPERATIONS_ERROR;
2516                 goto done;
2517         }
2518
2519         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2520         if (ret != LDB_SUCCESS) {
2521                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2522                                          attr_name));
2523                 goto done;
2524         }
2525
2526         ret = LDB_SUCCESS;
2527
2528 done:
2529         talloc_free(tmp_ctx);
2530         return ret;
2531
2532 }
2533
2534
2535 /*
2536   use a DN to find a SID
2537  */
2538 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2539                         struct ldb_dn *dn, struct dom_sid *sid)
2540 {
2541         int ret;
2542         struct ldb_result *res;
2543         const char *attrs[] = { "objectSid", NULL };
2544         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2545         struct dom_sid *s;
2546
2547         ZERO_STRUCTP(sid);
2548
2549         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2550                              DSDB_SEARCH_SHOW_DELETED |
2551                              DSDB_SEARCH_SHOW_RECYCLED);
2552         if (ret != LDB_SUCCESS) {
2553                 talloc_free(tmp_ctx);
2554                 return ret;
2555         }
2556         if (res->count < 1) {
2557                 talloc_free(tmp_ctx);
2558                 return LDB_ERR_NO_SUCH_OBJECT;
2559         }
2560         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
2561         if (s == NULL) {
2562                 talloc_free(tmp_ctx);
2563                 return LDB_ERR_NO_SUCH_OBJECT;
2564         }
2565         *sid = *s;
2566         talloc_free(tmp_ctx);
2567         return LDB_SUCCESS;
2568 }
2569
2570 /*
2571   use a SID to find a DN
2572  */
2573 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
2574                         TALLOC_CTX *mem_ctx,
2575                         struct dom_sid *sid, struct ldb_dn **dn)
2576 {
2577         int ret;
2578         struct ldb_result *res;
2579         const char *attrs[] = { NULL };
2580         char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
2581
2582         if (!sid_str) {
2583                 return ldb_operr(ldb);
2584         }
2585
2586         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2587                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2588                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2589                           DSDB_SEARCH_ONE_ONLY,
2590                           "objectSid=%s", sid_str);
2591         talloc_free(sid_str);
2592         if (ret != LDB_SUCCESS) {
2593                 return ret;
2594         }
2595
2596         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2597         talloc_free(res);
2598
2599         return LDB_SUCCESS;
2600 }
2601
2602 /*
2603   load a repsFromTo blob list for a given partition GUID
2604   attr must be "repsFrom" or "repsTo"
2605  */
2606 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2607                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2608 {
2609         const char *attrs[] = { attr, NULL };
2610         struct ldb_result *res = NULL;
2611         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2612         unsigned int i;
2613         struct ldb_message_element *el;
2614         int ret;
2615
2616         *r = NULL;
2617         *count = 0;
2618
2619         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
2620         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2621                 /* partition hasn't been replicated yet */
2622                 return WERR_OK;
2623         }
2624         if (ret != LDB_SUCCESS) {
2625                 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
2626                 talloc_free(tmp_ctx);
2627                 return WERR_DS_DRA_INTERNAL_ERROR;
2628         }
2629
2630         el = ldb_msg_find_element(res->msgs[0], attr);
2631         if (el == NULL) {
2632                 /* it's OK to be empty */
2633                 talloc_free(tmp_ctx);
2634                 return WERR_OK;
2635         }
2636
2637         *count = el->num_values;
2638         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2639         if (*r == NULL) {
2640                 talloc_free(tmp_ctx);
2641                 return WERR_DS_DRA_INTERNAL_ERROR;
2642         }
2643
2644         for (i=0; i<(*count); i++) {
2645                 enum ndr_err_code ndr_err;
2646                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2647                                                mem_ctx, 
2648                                                &(*r)[i], 
2649                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2650                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2651                         talloc_free(tmp_ctx);
2652                         return WERR_DS_DRA_INTERNAL_ERROR;
2653                 }
2654         }
2655
2656         talloc_free(tmp_ctx);
2657         
2658         return WERR_OK;
2659 }
2660
2661 /*
2662   save the repsFromTo blob list for a given partition GUID
2663   attr must be "repsFrom" or "repsTo"
2664  */
2665 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2666                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2667 {
2668         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2669         struct ldb_message *msg;
2670         struct ldb_message_element *el;
2671         unsigned int i;
2672
2673         msg = ldb_msg_new(tmp_ctx);
2674         msg->dn = dn;
2675         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2676                 goto failed;
2677         }
2678
2679         el->values = talloc_array(msg, struct ldb_val, count);
2680         if (!el->values) {
2681                 goto failed;
2682         }
2683
2684         for (i=0; i<count; i++) {
2685                 struct ldb_val v;
2686                 enum ndr_err_code ndr_err;
2687
2688                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, 
2689                                                &r[i], 
2690                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2691                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2692                         goto failed;
2693                 }
2694
2695                 el->num_values++;
2696                 el->values[i] = v;
2697         }
2698
2699         if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
2700                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2701                 goto failed;
2702         }
2703
2704         talloc_free(tmp_ctx);
2705         
2706         return WERR_OK;
2707
2708 failed:
2709         talloc_free(tmp_ctx);
2710         return WERR_DS_DRA_INTERNAL_ERROR;
2711 }
2712
2713
2714 /*
2715   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2716   object for a partition
2717  */
2718 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2719                                 uint64_t *uSN, uint64_t *urgent_uSN)
2720 {
2721         struct ldb_request *req;
2722         int ret;
2723         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2724         struct dsdb_control_current_partition *p_ctrl;
2725         struct ldb_result *res;
2726
2727         res = talloc_zero(tmp_ctx, struct ldb_result);
2728         if (!res) {
2729                 talloc_free(tmp_ctx);
2730                 return ldb_oom(ldb);
2731         }
2732
2733         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2734                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2735                                    LDB_SCOPE_BASE,
2736                                    NULL, NULL,
2737                                    NULL,
2738                                    res, ldb_search_default_callback,
2739                                    NULL);
2740         if (ret != LDB_SUCCESS) {
2741                 talloc_free(tmp_ctx);
2742                 return ret;
2743         }
2744
2745         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2746         if (p_ctrl == NULL) {
2747                 talloc_free(tmp_ctx);
2748                 return ldb_oom(ldb);
2749         }
2750         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2751         p_ctrl->dn = dn;
2752         
2753         ret = ldb_request_add_control(req,
2754                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2755                                       false, p_ctrl);
2756         if (ret != LDB_SUCCESS) {
2757                 talloc_free(tmp_ctx);
2758                 return ret;
2759         }
2760         
2761         /* Run the new request */
2762         ret = ldb_request(ldb, req);
2763         
2764         if (ret == LDB_SUCCESS) {
2765                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2766         }
2767
2768         if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
2769                 /* it hasn't been created yet, which means
2770                    an implicit value of zero */
2771                 *uSN = 0;
2772                 talloc_free(tmp_ctx);
2773                 return LDB_SUCCESS;
2774         }
2775
2776         if (ret != LDB_SUCCESS) {
2777                 talloc_free(tmp_ctx);
2778                 return ret;
2779         }
2780
2781         if (res->count < 1) {
2782                 *uSN = 0;
2783                 if (urgent_uSN) {
2784                         *urgent_uSN = 0;
2785                 }
2786         } else {
2787                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2788                 if (urgent_uSN) {
2789                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2790                 }
2791         }
2792
2793         talloc_free(tmp_ctx);
2794
2795         return LDB_SUCCESS;     
2796 }
2797
2798 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2799                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2800 {
2801         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2802 }
2803
2804 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2805                                     const struct drsuapi_DsReplicaCursor *c2)
2806 {
2807         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2808 }
2809
2810
2811 /*
2812   see if a computer identified by its invocationId is a RODC
2813 */
2814 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
2815 {
2816         /* 1) find the DN for this servers NTDSDSA object
2817            2) search for the msDS-isRODC attribute
2818            3) if not present then not a RODC
2819            4) if present and TRUE then is a RODC
2820         */
2821         struct ldb_dn *config_dn;
2822         const char *attrs[] = { "msDS-isRODC", NULL };
2823         int ret;
2824         struct ldb_result *res;
2825         TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
2826
2827         config_dn = ldb_get_config_basedn(sam_ctx);
2828         if (!config_dn) {
2829                 talloc_free(tmp_ctx);
2830                 return ldb_operr(sam_ctx);
2831         }
2832
2833         ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
2834                           DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
2835
2836         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2837                 *is_rodc = false;
2838                 talloc_free(tmp_ctx);
2839                 return LDB_SUCCESS;
2840         }
2841
2842         if (ret != LDB_SUCCESS) {
2843                 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
2844                          GUID_string(tmp_ctx, objectGUID)));
2845                 *is_rodc = false;
2846                 talloc_free(tmp_ctx);
2847                 return ret;
2848         }
2849
2850         ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
2851         *is_rodc = (ret == 1);
2852
2853         talloc_free(tmp_ctx);
2854         return LDB_SUCCESS;
2855 }
2856
2857
2858 /*
2859   see if we are a RODC
2860 */
2861 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
2862 {
2863         const struct GUID *objectGUID;
2864         int ret;
2865         bool *cached;
2866
2867         /* see if we have a cached copy */
2868         cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
2869         if (cached) {
2870                 *am_rodc = *cached;
2871                 return LDB_SUCCESS;
2872         }
2873
2874         objectGUID = samdb_ntds_objectGUID(sam_ctx);
2875         if (!objectGUID) {
2876                 return ldb_operr(sam_ctx);
2877         }
2878
2879         ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
2880         if (ret != LDB_SUCCESS) {
2881                 return ret;
2882         }
2883
2884         cached = talloc(sam_ctx, bool);
2885         if (cached == NULL) {
2886                 return ldb_oom(sam_ctx);
2887         }
2888         *cached = *am_rodc;
2889
2890         ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
2891         if (ret != LDB_SUCCESS) {
2892                 talloc_free(cached);
2893                 return ldb_operr(sam_ctx);
2894         }
2895
2896         return LDB_SUCCESS;
2897 }
2898
2899 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
2900 {
2901         TALLOC_CTX *tmp_ctx;
2902         bool *cached;
2903
2904         tmp_ctx = talloc_new(ldb);
2905         if (tmp_ctx == NULL) {
2906                 goto failed;
2907         }
2908
2909         cached = talloc(tmp_ctx, bool);
2910         if (!cached) {
2911                 goto failed;
2912         }
2913
2914         *cached = am_rodc;
2915         if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
2916                 goto failed;
2917         }
2918
2919         talloc_steal(ldb, cached);
2920         talloc_free(tmp_ctx);
2921         return true;
2922
2923 failed:
2924         DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
2925         talloc_free(tmp_ctx);
2926         return false;
2927 }
2928
2929
2930 /*
2931  * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
2932  * flags are DS_NTDSSETTINGS_OPT_*
2933  */
2934 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
2935                                         uint32_t *options)
2936 {
2937         int rc;
2938         TALLOC_CTX *tmp_ctx;
2939         struct ldb_result *res;
2940         struct ldb_dn *site_dn;
2941         const char *attrs[] = { "options", NULL };
2942
2943         tmp_ctx = talloc_new(ldb_ctx);
2944         if (tmp_ctx == NULL)
2945                 goto failed;
2946
2947         /* Retrieve the site dn for the ldb that we
2948          * have open.  This is our local site.
2949          */
2950         site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
2951         if (site_dn == NULL)
2952                 goto failed;
2953
2954         /* Perform a one level (child) search from the local
2955          * site distinguided name.   We're looking for the
2956          * "options" attribute within the nTDSSiteSettings
2957          * object
2958          */
2959         rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
2960                         LDB_SCOPE_ONELEVEL, attrs,
2961                         "objectClass=nTDSSiteSettings");
2962
2963         if (rc != LDB_SUCCESS || res->count != 1)
2964                 goto failed;
2965
2966         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
2967
2968         talloc_free(tmp_ctx);
2969
2970         return LDB_SUCCESS;
2971
2972 failed:
2973         DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
2974         talloc_free(tmp_ctx);
2975         return LDB_ERR_NO_SUCH_OBJECT;
2976 }
2977
2978 /*
2979   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2980
2981   flags are DS_NTDS_OPTION_*
2982 */
2983 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2984 {
2985         TALLOC_CTX *tmp_ctx;
2986         const char *attrs[] = { "options", NULL };
2987         int ret;
2988         struct ldb_result *res;
2989
2990         tmp_ctx = talloc_new(ldb);
2991         if (tmp_ctx == NULL) {
2992                 goto failed;
2993         }
2994
2995         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2996         if (ret != LDB_SUCCESS) {
2997                 goto failed;
2998         }
2999
3000         if (res->count != 1) {
3001                 goto failed;
3002         }
3003
3004         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3005
3006         talloc_free(tmp_ctx);
3007
3008         return LDB_SUCCESS;
3009
3010 failed:
3011         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3012         talloc_free(tmp_ctx);
3013         return LDB_ERR_NO_SUCH_OBJECT;
3014 }
3015
3016 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3017 {
3018         const char *attrs[] = { "objectCategory", NULL };
3019         int ret;
3020         struct ldb_result *res;
3021
3022         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
3023         if (ret != LDB_SUCCESS) {
3024                 goto failed;
3025         }
3026
3027         if (res->count != 1) {
3028                 goto failed;
3029         }
3030
3031         return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3032
3033 failed:
3034         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3035         return NULL;
3036 }
3037
3038 /*
3039  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3040  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3041  */
3042 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3043 {
3044         char **tokens, *ret;
3045         size_t i;
3046
3047         tokens = str_list_make(mem_ctx, cn, " -_");
3048         if (tokens == NULL)
3049                 return NULL;
3050
3051         /* "tolower()" and "toupper()" should also work properly on 0x00 */
3052         tokens[0][0] = tolower(tokens[0][0]);
3053         for (i = 1; i < str_list_length((const char **)tokens); i++)
3054                 tokens[i][0] = toupper(tokens[i][0]);
3055
3056         ret = talloc_strdup(mem_ctx, tokens[0]);
3057         for (i = 1; i < str_list_length((const char **)tokens); i++)
3058                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3059
3060         talloc_free(tokens);
3061
3062         return ret;
3063 }
3064
3065 /*
3066  * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3067  */
3068 int dsdb_functional_level(struct ldb_context *ldb)
3069 {
3070         int *domainFunctionality =
3071                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3072         if (!domainFunctionality) {
3073                 /* this is expected during initial provision */
3074                 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3075                 return DS_DOMAIN_FUNCTION_2000;
3076         }
3077         return *domainFunctionality;
3078 }
3079
3080 /*
3081  * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3082  */
3083 int dsdb_forest_functional_level(struct ldb_context *ldb)
3084 {
3085         int *forestFunctionality =
3086                 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3087         if (!forestFunctionality) {
3088                 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3089                 return DS_DOMAIN_FUNCTION_2000;
3090         }
3091         return *forestFunctionality;
3092 }
3093
3094 /*
3095   set a GUID in an extended DN structure
3096  */
3097 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3098 {
3099         struct ldb_val v;
3100         NTSTATUS status;
3101         int ret;
3102
3103         status = GUID_to_ndr_blob(guid, dn, &v);
3104         if (!NT_STATUS_IS_OK(status)) {
3105                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3106         }
3107
3108         ret = ldb_dn_set_extended_component(dn, component_name, &v);
3109         data_blob_free(&v);
3110         return ret;
3111 }
3112
3113 /*
3114   return a GUID from a extended DN structure
3115  */
3116 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3117 {
3118         const struct ldb_val *v;
3119
3120         v = ldb_dn_get_extended_component(dn, component_name);
3121         if (v == NULL) {
3122                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3123         }
3124
3125         return GUID_from_ndr_blob(v, guid);
3126 }
3127
3128 /*
3129   return a uint64_t from a extended DN structure
3130  */
3131 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3132 {
3133         const struct ldb_val *v;
3134         char *s;
3135
3136         v = ldb_dn_get_extended_component(dn, component_name);
3137         if (v == NULL) {
3138                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3139         }
3140         s = talloc_strndup(dn, (const char *)v->data, v->length);
3141         NT_STATUS_HAVE_NO_MEMORY(s);
3142
3143         *val = strtoull(s, NULL, 0);
3144
3145         talloc_free(s);
3146         return NT_STATUS_OK;
3147 }
3148
3149 /*
3150   return a NTTIME from a extended DN structure
3151  */
3152 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3153 {
3154         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3155 }
3156
3157 /*
3158   return a uint32_t from a extended DN structure
3159  */
3160 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3161 {
3162         const struct ldb_val *v;
3163         char *s;
3164
3165         v = ldb_dn_get_extended_component(dn, component_name);
3166         if (v == NULL) {
3167                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3168         }
3169
3170         s = talloc_strndup(dn, (const char *)v->data, v->length);
3171         NT_STATUS_HAVE_NO_MEMORY(s);
3172
3173         *val = strtoul(s, NULL, 0);
3174
3175         talloc_free(s);
3176         return NT_STATUS_OK;
3177 }
3178
3179 /*
3180   return a dom_sid from a extended DN structure
3181  */
3182 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3183 {
3184         const struct ldb_val *sid_blob;
3185         struct TALLOC_CTX *tmp_ctx;
3186         enum ndr_err_code ndr_err;
3187
3188         sid_blob = ldb_dn_get_extended_component(dn, component_name);
3189         if (!sid_blob) {
3190                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3191         }
3192
3193         tmp_ctx = talloc_new(NULL);
3194
3195         ndr_err = ndr_pull_struct_blob_all(sid_blob, tmp_ctx, sid,
3196                                            (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3197         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3198                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3199                 talloc_free(tmp_ctx);
3200                 return status;
3201         }
3202
3203         talloc_free(tmp_ctx);
3204         return NT_STATUS_OK;
3205 }
3206
3207
3208 /*
3209   return RMD_FLAGS directly from a ldb_dn
3210   returns 0 if not found
3211  */
3212 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3213 {
3214         const struct ldb_val *v;
3215         char buf[32];
3216         v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
3217         if (!v || v->length > sizeof(buf)-1) return 0;
3218         strncpy(buf, (const char *)v->data, v->length);
3219         buf[v->length] = 0;
3220         return strtoul(buf, NULL, 10);
3221 }
3222
3223 /*
3224   return RMD_FLAGS directly from a ldb_val for a DN
3225   returns 0 if RMD_FLAGS is not found
3226  */
3227 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3228 {
3229         const char *p;
3230         uint32_t flags;
3231         char *end;
3232
3233         if (val->length < 13) {
3234                 return 0;
3235         }
3236         p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3237         if (!p) {
3238                 return 0;
3239         }
3240         flags = strtoul(p+11, &end, 10);
3241         if (!end || *end != '>') {
3242                 /* it must end in a > */
3243                 return 0;
3244         }
3245         return flags;
3246 }
3247
3248 /*
3249   return true if a ldb_val containing a DN in storage form is deleted
3250  */
3251 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3252 {
3253         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3254 }
3255
3256 /*
3257   return true if a ldb_val containing a DN in storage form is
3258   in the upgraded w2k3 linked attribute format
3259  */
3260 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3261 {
3262         return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
3263 }
3264
3265 /*
3266   return a DN for a wellknown GUID
3267  */
3268 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3269                       struct ldb_dn *nc_root, const char *wk_guid,
3270                       struct ldb_dn **wkguid_dn)
3271 {
3272         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3273         const char *attrs[] = { NULL };
3274         int ret;
3275         struct ldb_dn *dn;
3276         struct ldb_result *res;
3277
3278         /* construct the magic WKGUID DN */
3279         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3280                             wk_guid, ldb_dn_get_linearized(nc_root));
3281         if (!wkguid_dn) {
3282                 talloc_free(tmp_ctx);
3283                 return ldb_operr(samdb);
3284         }
3285
3286         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
3287                              DSDB_SEARCH_SHOW_DELETED |
3288                              DSDB_SEARCH_SHOW_RECYCLED);
3289         if (ret != LDB_SUCCESS) {
3290                 talloc_free(tmp_ctx);
3291                 return ret;
3292         }
3293
3294         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3295         talloc_free(tmp_ctx);
3296         return LDB_SUCCESS;
3297 }
3298
3299
3300 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3301 {
3302         return ldb_dn_compare(*dn1, *dn2);
3303 }
3304
3305 /*
3306   find a NC root given a DN within the NC
3307  */
3308 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3309                       struct ldb_dn **nc_root)
3310 {
3311         const char *root_attrs[] = { "namingContexts", NULL };
3312         TALLOC_CTX *tmp_ctx;
3313         int ret;
3314         struct ldb_message_element *el;
3315         struct ldb_result *root_res;
3316         unsigned int i;
3317         struct ldb_dn **nc_dns;
3318
3319         tmp_ctx = talloc_new(samdb);
3320         if (tmp_ctx == NULL) {
3321                 return ldb_oom(samdb);
3322         }
3323
3324         ret = ldb_search(samdb, tmp_ctx, &root_res,
3325                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3326         if (ret != LDB_SUCCESS) {
3327                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3328                 talloc_free(tmp_ctx);
3329                 return ret;
3330         }
3331
3332         el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3333         if ((el == NULL) || (el->num_values < 3)) {
3334                 struct ldb_message *tmp_msg;
3335
3336                 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list."));
3337
3338                 /* This generates a temporary list of NCs in order to let the
3339                  * provisioning work. */
3340                 tmp_msg = ldb_msg_new(tmp_ctx);
3341                 if (tmp_msg == NULL) {
3342                         talloc_free(tmp_ctx);
3343                         return ldb_oom(samdb);
3344                 }
3345                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3346                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
3347                 if (ret != LDB_SUCCESS) {
3348                         talloc_free(tmp_ctx);
3349                         return ret;
3350                 }
3351                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3352                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
3353                 if (ret != LDB_SUCCESS) {
3354                         talloc_free(tmp_ctx);
3355                         return ret;
3356                 }
3357                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3358                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
3359                 if (ret != LDB_SUCCESS) {
3360                         talloc_free(tmp_ctx);
3361                         return ret;
3362                 }
3363                 el = &tmp_msg->elements[0];
3364         }
3365
3366        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3367        if (!nc_dns) {
3368                talloc_free(tmp_ctx);
3369                return ldb_oom(samdb);
3370        }
3371
3372        for (i=0; i<el->num_values; i++) {
3373                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3374                if (nc_dns[i] == NULL) {
3375                        talloc_free(tmp_ctx);
3376                        return ldb_operr(samdb);
3377                }
3378        }
3379
3380        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3381
3382        for (i=0; i<el->num_values; i++) {
3383                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3384                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3385                        talloc_free(tmp_ctx);
3386                        return LDB_SUCCESS;
3387                }
3388        }
3389
3390        talloc_free(tmp_ctx);
3391        return LDB_ERR_NO_SUCH_OBJECT;
3392 }
3393
3394
3395 /*
3396   find the deleted objects DN for any object, by looking for the NC
3397   root, then looking up the wellknown GUID
3398  */
3399 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3400                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3401                                 struct ldb_dn **do_dn)
3402 {
3403         struct ldb_dn *nc_root;
3404         int ret;
3405
3406         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3407         if (ret != LDB_SUCCESS) {
3408                 return ret;
3409         }
3410
3411         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3412         talloc_free(nc_root);
3413         return ret;
3414 }
3415
3416 /*
3417   return the tombstoneLifetime, in days
3418  */
3419 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3420 {
3421         struct ldb_dn *dn;
3422         dn = ldb_get_config_basedn(ldb);
3423         if (!dn) {
3424                 return LDB_ERR_NO_SUCH_OBJECT;
3425         }
3426         dn = ldb_dn_copy(ldb, dn);
3427         if (!dn) {
3428                 return ldb_operr(ldb);
3429         }
3430         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3431          be a wellknown GUID for this */
3432         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3433                 talloc_free(dn);
3434                 return ldb_operr(ldb);
3435         }
3436
3437         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3438         talloc_free(dn);
3439         return LDB_SUCCESS;
3440 }
3441
3442 /*
3443   compare a ldb_val to a string case insensitively
3444  */
3445 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3446 {
3447         size_t len = strlen(s);
3448         int ret;
3449         if (len > v->length) return 1;
3450         ret = strncasecmp(s, (const char *)v->data, v->length);
3451         if (ret != 0) return ret;
3452         if (v->length > len && v->data[len] != 0) {
3453                 return -1;
3454         }
3455         return 0;
3456 }
3457
3458
3459 /*
3460   load the UDV for a partition in v2 format
3461   The list is returned sorted, and with our local cursor added
3462  */
3463 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3464                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3465 {
3466         static const char *attrs[] = { "replUpToDateVector", NULL };
3467         struct ldb_result *r;
3468         const struct ldb_val *ouv_value;
3469         unsigned int i;
3470         int ret;
3471         uint64_t highest_usn;
3472         const struct GUID *our_invocation_id;
3473         struct timeval now = timeval_current();
3474
3475         ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3476         if (ret != LDB_SUCCESS) {
3477                 return ret;
3478         }
3479
3480         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3481         if (ouv_value) {
3482                 enum ndr_err_code ndr_err;
3483                 struct replUpToDateVectorBlob ouv;
3484
3485                 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
3486                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3487                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3488                         talloc_free(r);
3489                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3490                 }
3491                 if (ouv.version != 2) {
3492                         /* we always store as version 2, and
3493                          * replUpToDateVector is not replicated
3494                          */
3495                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3496                 }
3497
3498                 *count = ouv.ctr.ctr2.count;
3499                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3500         } else {
3501                 *count = 0;
3502                 *cursors = NULL;
3503         }
3504
3505         talloc_free(r);
3506
3507         our_invocation_id = samdb_ntds_invocation_id(samdb);
3508         if (!our_invocation_id) {
3509                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3510                 talloc_free(*cursors);
3511                 return ldb_operr(samdb);
3512         }
3513
3514         ret = dsdb_load_partition_usn(samdb, dn, &highest_usn, NULL);
3515         if (ret != LDB_SUCCESS) {
3516                 /* nothing to add - this can happen after a vampire */
3517                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3518                 return LDB_SUCCESS;
3519         }
3520
3521         for (i=0; i<*count; i++) {
3522                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3523                         (*cursors)[i].highest_usn = highest_usn;
3524                         (*cursors)[i].last_sync_success = timeval_to_nttime(&now);
3525                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3526                         return LDB_SUCCESS;
3527                 }
3528         }
3529
3530         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3531         if (! *cursors) {
3532                 return ldb_oom(samdb);
3533         }
3534
3535         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3536         (*cursors)[*count].highest_usn = highest_usn;
3537         (*cursors)[*count].last_sync_success = timeval_to_nttime(&now);
3538         (*count)++;
3539
3540         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3541
3542         return LDB_SUCCESS;
3543 }
3544
3545 /*
3546   load the UDV for a partition in version 1 format
3547   The list is returned sorted, and with our local cursor added
3548  */
3549 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3550                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3551 {
3552         struct drsuapi_DsReplicaCursor2 *v2;
3553         uint32_t i;
3554         int ret;
3555
3556         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3557         if (ret != LDB_SUCCESS) {
3558                 return ret;
3559         }
3560
3561         if (*count == 0) {
3562                 talloc_free(v2);
3563                 *cursors = NULL;
3564                 return LDB_SUCCESS;
3565         }
3566
3567         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3568         if (*cursors == NULL) {
3569                 talloc_free(v2);
3570                 return ldb_oom(samdb);
3571         }
3572
3573         for (i=0; i<*count; i++) {
3574                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3575                 (*cursors)[i].highest_usn = v2[i].highest_usn;
3576         }
3577         talloc_free(v2);
3578         return LDB_SUCCESS;
3579 }
3580
3581 /*
3582   add a set of controls to a ldb_request structure based on a set of
3583   flags. See util.h for a list of available flags
3584  */
3585 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3586 {
3587         int ret;
3588         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3589                 struct ldb_search_options_control *options;
3590                 /* Using the phantom root control allows us to search all partitions */
3591                 options = talloc(req, struct ldb_search_options_control);
3592                 if (options == NULL) {
3593                         return LDB_ERR_OPERATIONS_ERROR;
3594                 }
3595                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3596
3597                 ret = ldb_request_add_control(req,
3598                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
3599                                               true, options);
3600                 if (ret != LDB_SUCCESS) {
3601                         return ret;
3602                 }
3603         }
3604
3605         if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
3606                 ret = ldb_request_add_control(req,
3607                                               DSDB_CONTROL_NO_GLOBAL_CATALOG,
3608                                               false, NULL);
3609                 if (ret != LDB_SUCCESS) {
3610                         return ret;
3611                 }
3612         }
3613
3614         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3615                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3616                 if (ret != LDB_SUCCESS) {
3617                         return ret;
3618                 }
3619         }
3620
3621         if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
3622                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
3623                 if (ret != LDB_SUCCESS) {
3624                         return ret;
3625                 }
3626         }
3627
3628         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3629                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
3630                 if (ret != LDB_SUCCESS) {
3631                         return ret;
3632                 }
3633         }
3634
3635         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3636                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3637                 if (!extended_ctrl) {
3638                         return LDB_ERR_OPERATIONS_ERROR;
3639                 }
3640                 extended_ctrl->type = 1;
3641
3642                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3643                 if (ret != LDB_SUCCESS) {
3644                         return ret;
3645                 }
3646         }
3647
3648         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3649                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3650                 if (ret != LDB_SUCCESS) {
3651                         return ret;
3652                 }
3653         }
3654
3655         if (dsdb_flags & DSDB_MODIFY_RELAX) {
3656                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3657                 if (ret != LDB_SUCCESS) {
3658                         return ret;
3659                 }
3660         }
3661
3662         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3663                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3664                 if (ret != LDB_SUCCESS) {
3665                         return ret;
3666                 }
3667         }
3668
3669         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3670                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3671                 if (ret != LDB_SUCCESS) {
3672                         return ret;
3673                 }
3674         }
3675
3676         if (dsdb_flags & DSDB_TREE_DELETE) {
3677                 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
3678                 if (ret != LDB_SUCCESS) {
3679                         return ret;
3680                 }
3681         }
3682
3683         if (dsdb_flags & DSDB_PROVISION) {
3684                 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
3685                 if (ret != LDB_SUCCESS) {
3686                         return ret;
3687                 }
3688         }
3689
3690         /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
3691         if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
3692                 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
3693                 if (ret != LDB_SUCCESS) {
3694                         return ret;
3695                 }
3696         }
3697
3698         if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
3699                 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, true, NULL);
3700                 if (ret != LDB_SUCCESS) {
3701                         return ret;
3702                 }
3703         }
3704
3705         if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
3706                 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
3707                 if (ret != LDB_SUCCESS) {
3708                         return ret;
3709                 }
3710         }
3711
3712         return LDB_SUCCESS;
3713 }
3714
3715 /*
3716   an add with a set of controls
3717 */
3718 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
3719              uint32_t dsdb_flags)
3720 {
3721         struct ldb_request *req;
3722         int ret;
3723
3724         ret = ldb_build_add_req(&req, ldb, ldb,
3725                                 message,
3726                                 NULL,
3727                                 NULL,
3728                                 ldb_op_default_callback,
3729                                 NULL);
3730
3731         if (ret != LDB_SUCCESS) return ret;
3732
3733         ret = dsdb_request_add_controls(req, dsdb_flags);
3734         if (ret != LDB_SUCCESS) {
3735                 talloc_free(req);
3736                 return ret;
3737         }
3738
3739         ret = dsdb_autotransaction_request(ldb, req);
3740
3741         talloc_free(req);
3742         return ret;
3743 }
3744
3745 /*
3746   a modify with a set of controls
3747 */
3748 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3749                 uint32_t dsdb_flags)
3750 {
3751         struct ldb_request *req;
3752         int ret;
3753
3754         ret = ldb_build_mod_req(&req, ldb, ldb,
3755                                 message,
3756                                 NULL,
3757                                 NULL,
3758                                 ldb_op_default_callback,
3759                                 NULL);
3760
3761         if (ret != LDB_SUCCESS) return ret;
3762
3763         ret = dsdb_request_add_controls(req, dsdb_flags);
3764         if (ret != LDB_SUCCESS) {
3765                 talloc_free(req);
3766                 return ret;
3767         }
3768
3769         ret = dsdb_autotransaction_request(ldb, req);
3770
3771         talloc_free(req);
3772         return ret;
3773 }
3774
3775 /*
3776   a delete with a set of flags
3777 */
3778 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
3779                 uint32_t dsdb_flags)
3780 {
3781         struct ldb_request *req;
3782         int ret;
3783
3784         ret = ldb_build_del_req(&req, ldb, ldb,
3785                                 dn,
3786                                 NULL,
3787                                 NULL,
3788                                 ldb_op_default_callback,
3789                                 NULL);
3790
3791         if (ret != LDB_SUCCESS) return ret;
3792
3793         ret = dsdb_request_add_controls(req, dsdb_flags);
3794         if (ret != LDB_SUCCESS) {
3795                 talloc_free(req);
3796                 return ret;
3797         }
3798
3799         ret = dsdb_autotransaction_request(ldb, req);
3800
3801         talloc_free(req);
3802         return ret;
3803 }
3804
3805 /*
3806   like dsdb_modify() but set all the element flags to
3807   LDB_FLAG_MOD_REPLACE
3808  */
3809 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3810 {
3811         unsigned int i;
3812
3813         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3814         for (i=0;i<msg->num_elements;i++) {
3815                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3816         }
3817
3818         return dsdb_modify(ldb, msg, dsdb_flags);
3819 }
3820
3821
3822 /*
3823   search for attrs on one DN, allowing for dsdb_flags controls
3824  */
3825 int dsdb_search_dn(struct ldb_context *ldb,
3826                    TALLOC_CTX *mem_ctx,
3827                    struct ldb_result **_res,
3828                    struct ldb_dn *basedn,
3829                    const char * const *attrs,
3830                    uint32_t dsdb_flags)
3831 {
3832         int ret;
3833         struct ldb_request *req;
3834         struct ldb_result *res;
3835
3836         res = talloc_zero(mem_ctx, struct ldb_result);
3837         if (!res) {
3838                 return ldb_oom(ldb);
3839         }
3840
3841         ret = ldb_build_search_req(&req, ldb, res,
3842                                    basedn,
3843                                    LDB_SCOPE_BASE,
3844                                    NULL,
3845                                    attrs,
3846                                    NULL,
3847                                    res,
3848                                    ldb_search_default_callback,
3849                                    NULL);
3850         if (ret != LDB_SUCCESS) {
3851                 talloc_free(res);
3852                 return ret;
3853         }
3854
3855         ret = dsdb_request_add_controls(req, dsdb_flags);
3856         if (ret != LDB_SUCCESS) {
3857                 talloc_free(res);
3858                 return ret;
3859         }
3860
3861         ret = ldb_request(ldb, req);
3862         if (ret == LDB_SUCCESS) {
3863                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3864         }
3865
3866         talloc_free(req);
3867         if (ret != LDB_SUCCESS) {
3868                 talloc_free(res);
3869                 return ret;
3870         }
3871
3872         *_res = res;
3873         return LDB_SUCCESS;
3874 }
3875
3876 /*
3877   search for attrs on one DN, by the GUID of the DN, allowing for
3878   dsdb_flags controls
3879  */
3880 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
3881                            TALLOC_CTX *mem_ctx,
3882                            struct ldb_result **_res,
3883                            const struct GUID *guid,
3884                            const char * const *attrs,
3885                            uint32_t dsdb_flags)
3886 {
3887         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3888         struct ldb_dn *dn;
3889         int ret;
3890
3891         dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
3892         if (dn == NULL) {
3893                 talloc_free(tmp_ctx);
3894                 return ldb_oom(ldb);
3895         }
3896
3897         ret = dsdb_search_dn(ldb, mem_ctx, _res, dn, attrs, dsdb_flags);
3898         talloc_free(tmp_ctx);
3899         return ret;
3900 }
3901
3902 /*
3903   general search with dsdb_flags for controls
3904  */
3905 int dsdb_search(struct ldb_context *ldb,
3906                 TALLOC_CTX *mem_ctx,
3907                 struct ldb_result **_res,
3908                 struct ldb_dn *basedn,
3909                 enum ldb_scope scope,
3910                 const char * const *attrs,
3911                 uint32_t dsdb_flags,
3912                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3913 {
3914         int ret;
3915         struct ldb_request *req;
3916         struct ldb_result *res;
3917         va_list ap;
3918         char *expression = NULL;
3919         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3920
3921         /* cross-partitions searches with a basedn break multi-domain support */
3922         SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
3923
3924         res = talloc_zero(tmp_ctx, struct ldb_result);
3925         if (!res) {
3926                 talloc_free(tmp_ctx);
3927                 return ldb_oom(ldb);
3928         }
3929
3930         if (exp_fmt) {
3931                 va_start(ap, exp_fmt);
3932                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3933                 va_end(ap);
3934
3935                 if (!expression) {
3936                         talloc_free(tmp_ctx);
3937                         return ldb_oom(ldb);
3938                 }
3939         }
3940
3941         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3942                                    basedn,
3943                                    scope,
3944                                    expression,
3945                                    attrs,
3946                                    NULL,
3947                                    res,
3948                                    ldb_search_default_callback,
3949                                    NULL);
3950         if (ret != LDB_SUCCESS) {
3951                 talloc_free(tmp_ctx);
3952                 return ret;
3953         }
3954
3955         ret = dsdb_request_add_controls(req, dsdb_flags);
3956         if (ret != LDB_SUCCESS) {
3957                 talloc_free(tmp_ctx);
3958                 ldb_reset_err_string(ldb);
3959                 return ret;
3960         }
3961
3962         ret = ldb_request(ldb, req);
3963         if (ret == LDB_SUCCESS) {
3964                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3965         }
3966
3967         if (ret != LDB_SUCCESS) {
3968                 talloc_free(tmp_ctx);
3969                 return ret;
3970         }
3971
3972         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
3973                 if (res->count == 0) {
3974                         talloc_free(tmp_ctx);
3975                         ldb_reset_err_string(ldb);
3976                         return LDB_ERR_NO_SUCH_OBJECT;
3977                 }
3978                 if (res->count != 1) {
3979                         talloc_free(tmp_ctx);
3980                         ldb_reset_err_string(ldb);
3981                         return LDB_ERR_CONSTRAINT_VIOLATION;
3982                 }
3983         }
3984
3985         *_res = talloc_steal(mem_ctx, res);
3986         talloc_free(tmp_ctx);
3987
3988         return LDB_SUCCESS;
3989 }
3990
3991
3992 /*
3993   general search with dsdb_flags for controls
3994   returns exactly 1 record or an error
3995  */
3996 int dsdb_search_one(struct ldb_context *ldb,
3997                     TALLOC_CTX *mem_ctx,
3998                     struct ldb_message **msg,
3999                     struct ldb_dn *basedn,
4000                     enum ldb_scope scope,
4001                     const char * const *attrs,
4002                     uint32_t dsdb_flags,
4003                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4004 {
4005         int ret;
4006         struct ldb_result *res;
4007         va_list ap;
4008         char *expression = NULL;
4009         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4010
4011         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4012
4013         res = talloc_zero(tmp_ctx, struct ldb_result);
4014         if (!res) {
4015                 talloc_free(tmp_ctx);
4016                 return ldb_oom(ldb);
4017         }
4018
4019         if (exp_fmt) {
4020                 va_start(ap, exp_fmt);
4021                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4022                 va_end(ap);
4023
4024                 if (!expression) {
4025                         talloc_free(tmp_ctx);
4026                         return ldb_oom(ldb);
4027                 }
4028                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4029                                   dsdb_flags, "%s", expression);
4030         } else {
4031                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4032                                   dsdb_flags, NULL);
4033         }
4034
4035         if (ret != LDB_SUCCESS) {
4036                 talloc_free(tmp_ctx);
4037                 return ret;
4038         }
4039
4040         *msg = talloc_steal(mem_ctx, res->msgs[0]);
4041         talloc_free(tmp_ctx);
4042
4043         return LDB_SUCCESS;
4044 }
4045
4046 /* returns back the forest DNS name */
4047 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4048 {
4049         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4050                                                           ldb_get_root_basedn(ldb));
4051         char *p;
4052
4053         if (forest_name == NULL) {
4054                 return NULL;
4055         }
4056
4057         p = strchr(forest_name, '/');
4058         if (p) {
4059                 *p = '\0';
4060         }
4061
4062         return forest_name;
4063 }
4064
4065 /* returns back the default domain DNS name */
4066 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4067 {
4068         const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4069                                                           ldb_get_default_basedn(ldb));
4070         char *p;
4071
4072         if (domain_name == NULL) {
4073                 return NULL;
4074         }
4075
4076         p = strchr(domain_name, '/');
4077         if (p) {
4078                 *p = '\0';
4079         }
4080
4081         return domain_name;
4082 }
4083
4084 /*
4085    validate that an DSA GUID belongs to the specified user sid.
4086    The user SID must be a domain controller account (either RODC or
4087    RWDC)
4088  */
4089 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4090                            const struct GUID *dsa_guid,
4091                            const struct dom_sid *sid)
4092 {
4093         /* strategy:
4094             - find DN of record with the DSA GUID in the
4095               configuration partition (objectGUID)
4096             - remove "NTDS Settings" component from DN
4097             - do a base search on that DN for serverReference with
4098               extended-dn enabled
4099             - extract objectSid from resulting serverReference
4100               attribute
4101             - check this sid matches the sid argument
4102         */
4103         struct ldb_dn *config_dn;
4104         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4105         struct ldb_message *msg;
4106         const char *attrs1[] = { NULL };
4107         const char *attrs2[] = { "serverReference", NULL };
4108         int ret;
4109         struct ldb_dn *dn, *account_dn;
4110         struct dom_sid sid2;
4111         NTSTATUS status;
4112
4113         config_dn = ldb_get_config_basedn(ldb);
4114
4115         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4116                               attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4117         if (ret != LDB_SUCCESS) {
4118                 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4119                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4120                 talloc_free(tmp_ctx);
4121                 return ldb_operr(ldb);
4122         }
4123         dn = msg->dn;
4124
4125         if (!ldb_dn_remove_child_components(dn, 1)) {
4126                 talloc_free(tmp_ctx);
4127                 return ldb_operr(ldb);
4128         }
4129
4130         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4131                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4132                               "(objectClass=server)");
4133         if (ret != LDB_SUCCESS) {
4134                 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4135                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4136                 talloc_free(tmp_ctx);
4137                 return ldb_operr(ldb);
4138         }
4139
4140         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4141         if (account_dn == NULL) {
4142                 DEBUG(1,(__location__ ": Failed to find account_dn for DSA with objectGUID %s, sid %s\n",
4143                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4144                 talloc_free(tmp_ctx);
4145                 return ldb_operr(ldb);
4146         }
4147
4148         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4149         if (!NT_STATUS_IS_OK(status)) {
4150                 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4151                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4152                 talloc_free(tmp_ctx);
4153                 return ldb_operr(ldb);
4154         }
4155
4156         if (!dom_sid_equal(sid, &sid2)) {
4157                 /* someone is trying to spoof another account */
4158                 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4159                          GUID_string(tmp_ctx, dsa_guid),
4160                          dom_sid_string(tmp_ctx, sid),
4161                          dom_sid_string(tmp_ctx, &sid2)));
4162                 talloc_free(tmp_ctx);
4163                 return ldb_operr(ldb);
4164         }
4165
4166         talloc_free(tmp_ctx);
4167         return LDB_SUCCESS;
4168 }
4169
4170 static const char * const secret_attributes[] = {
4171         DSDB_SECRET_ATTRIBUTES,
4172         NULL
4173 };
4174
4175 /*
4176   check if the attribute belongs to the RODC filtered attribute set
4177   Note that attributes that are in the filtered attribute set are the
4178   ones that _are_ always sent to a RODC
4179 */
4180 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4181 {
4182         /* they never get secret attributes */
4183         if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4184                 return false;
4185         }
4186
4187         /* they do get non-secret critical attributes */
4188         if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4189                 return true;
4190         }
4191
4192         /* they do get non-secret attributes marked as being in the FAS  */
4193         if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4194                 return true;
4195         }
4196
4197         /* other attributes are denied */
4198         return false;
4199 }
4200
4201 /* return fsmo role dn and role owner dn for a particular role*/
4202 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4203                                struct ldb_context *ldb,
4204                                uint32_t role,
4205                                struct ldb_dn **fsmo_role_dn,
4206                                struct ldb_dn **role_owner_dn)
4207 {
4208         int ret;
4209         switch (role) {
4210         case DREPL_NAMING_MASTER:
4211                 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4212                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4213                 if (ret != LDB_SUCCESS) {
4214                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4215                                  ldb_errstring(ldb)));
4216                         talloc_free(tmp_ctx);
4217                         return WERR_DS_DRA_INTERNAL_ERROR;
4218                 }
4219                 break;
4220         case DREPL_INFRASTRUCTURE_MASTER:
4221                 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4222                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4223                 if (ret != LDB_SUCCESS) {
4224                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4225                                  ldb_errstring(ldb)));
4226                         talloc_free(tmp_ctx);
4227                         return WERR_DS_DRA_INTERNAL_ERROR;
4228                 }
4229                 break;
4230         case DREPL_RID_MASTER:
4231                 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
4232                 if (ret != LDB_SUCCESS) {
4233                         DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
4234                         talloc_free(tmp_ctx);
4235                         return WERR_DS_DRA_INTERNAL_ERROR;
4236                 }
4237
4238                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4239                 if (ret != LDB_SUCCESS) {
4240                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
4241                                  ldb_errstring(ldb)));
4242                         talloc_free(tmp_ctx);
4243                         return WERR_DS_DRA_INTERNAL_ERROR;
4244                 }
4245                 break;
4246         case DREPL_SCHEMA_MASTER:
4247                 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
4248                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4249                 if (ret != LDB_SUCCESS) {
4250                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4251                                  ldb_errstring(ldb)));
4252                         talloc_free(tmp_ctx);
4253                         return WERR_DS_DRA_INTERNAL_ERROR;
4254                 }
4255                 break;
4256         case DREPL_PDC_MASTER:
4257                 *fsmo_role_dn = ldb_get_default_basedn(ldb);
4258                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4259                 if (ret != LDB_SUCCESS) {
4260                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
4261                                  ldb_errstring(ldb)));
4262                         talloc_free(tmp_ctx);
4263                         return WERR_DS_DRA_INTERNAL_ERROR;
4264                 }
4265                 break;
4266         default:
4267                 return WERR_DS_DRA_INTERNAL_ERROR;
4268         }
4269         return WERR_OK;
4270 }
4271
4272 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
4273                                     TALLOC_CTX *mem_ctx,
4274                                     struct ldb_dn *server_dn)
4275 {
4276         int ldb_ret;
4277         struct ldb_result *res = NULL;
4278         const char * const attrs[] = { "dNSHostName", NULL};
4279
4280         ldb_ret = ldb_search(ldb, mem_ctx, &res,
4281                              server_dn,
4282                              LDB_SCOPE_BASE,
4283                              attrs, NULL);
4284         if (ldb_ret != LDB_SUCCESS) {
4285                 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
4286                           ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
4287                 return NULL;
4288         }
4289
4290         return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
4291 }
4292
4293 /*
4294   returns true if an attribute is in the filter,
4295   false otherwise, provided that attribute value is provided with the expression
4296 */
4297 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
4298                              const char *attr)
4299 {
4300        unsigned int i;
4301        switch (tree->operation) {
4302        case LDB_OP_AND:
4303        case LDB_OP_OR:
4304                for (i=0;i<tree->u.list.num_elements;i++) {
4305                        if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
4306                                                        attr))
4307                                return true;
4308                }
4309                return false;
4310        case LDB_OP_NOT:
4311                return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
4312        case LDB_OP_EQUALITY:
4313        case LDB_OP_GREATER:
4314        case LDB_OP_LESS:
4315        case LDB_OP_APPROX:
4316                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
4317                        return true;
4318                }
4319                return false;
4320        case LDB_OP_SUBSTRING:
4321                if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
4322                        return true;
4323                }
4324                return false;
4325        case LDB_OP_PRESENT:
4326                /* (attrname=*) is not filtered out */
4327                return false;
4328        case LDB_OP_EXTENDED:
4329                if (tree->u.extended.attr &&
4330                    ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
4331                        return true;
4332                }
4333                return false;
4334        }
4335        return false;
4336 }
4337
4338 bool is_attr_in_list(const char * const * attrs, const char *attr)
4339 {
4340         unsigned int i;
4341
4342         for (i = 0; attrs[i]; i++) {
4343                 if (ldb_attr_cmp(attrs[i], attr) == 0)
4344                         return true;
4345         }
4346
4347         return false;
4348 }
4349
4350
4351 /*
4352   map an ldb error code to an approximate NTSTATUS code
4353  */
4354 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
4355 {
4356         switch (err) {
4357         case LDB_SUCCESS:
4358                 return NT_STATUS_OK;
4359
4360         case LDB_ERR_PROTOCOL_ERROR:
4361                 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
4362
4363         case LDB_ERR_TIME_LIMIT_EXCEEDED:
4364                 return NT_STATUS_IO_TIMEOUT;
4365
4366         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
4367                 return NT_STATUS_BUFFER_TOO_SMALL;
4368
4369         case LDB_ERR_COMPARE_FALSE:
4370         case LDB_ERR_COMPARE_TRUE:
4371                 return NT_STATUS_REVISION_MISMATCH;
4372
4373         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
4374                 return NT_STATUS_NOT_SUPPORTED;
4375
4376         case LDB_ERR_STRONG_AUTH_REQUIRED:
4377         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
4378         case LDB_ERR_SASL_BIND_IN_PROGRESS:
4379         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
4380         case LDB_ERR_INVALID_CREDENTIALS:
4381         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
4382         case LDB_ERR_UNWILLING_TO_PERFORM:
4383                 return NT_STATUS_ACCESS_DENIED;
4384
4385         case LDB_ERR_NO_SUCH_OBJECT:
4386                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4387
4388         case LDB_ERR_REFERRAL:
4389         case LDB_ERR_NO_SUCH_ATTRIBUTE:
4390                 return NT_STATUS_NOT_FOUND;
4391
4392         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
4393                 return NT_STATUS_NOT_SUPPORTED;
4394
4395         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
4396                 return NT_STATUS_BUFFER_TOO_SMALL;
4397
4398         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
4399         case LDB_ERR_INAPPROPRIATE_MATCHING:
4400         case LDB_ERR_CONSTRAINT_VIOLATION:
4401         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
4402         case LDB_ERR_INVALID_DN_SYNTAX:
4403         case LDB_ERR_NAMING_VIOLATION:
4404         case LDB_ERR_OBJECT_CLASS_VIOLATION:
4405         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
4406         case LDB_ERR_NOT_ALLOWED_ON_RDN:
4407                 return NT_STATUS_INVALID_PARAMETER;
4408
4409         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
4410         case LDB_ERR_ENTRY_ALREADY_EXISTS:
4411                 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
4412
4413         case LDB_ERR_BUSY:
4414                 return NT_STATUS_NETWORK_BUSY;
4415
4416         case LDB_ERR_ALIAS_PROBLEM:
4417         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
4418         case LDB_ERR_UNAVAILABLE:
4419         case LDB_ERR_LOOP_DETECT:
4420         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
4421         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
4422         case LDB_ERR_OTHER:
4423         case LDB_ERR_OPERATIONS_ERROR:
4424                 break;
4425         }
4426         return NT_STATUS_UNSUCCESSFUL;
4427 }
4428
4429
4430 /*
4431   create a new naming context that will hold a partial replica
4432  */
4433 int dsdb_create_partial_replica_NC(struct ldb_context *ldb,  struct ldb_dn *dn)
4434 {
4435         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4436         struct ldb_message *msg;
4437         int ret;
4438
4439         msg = ldb_msg_new(tmp_ctx);
4440         if (msg == NULL) {
4441                 talloc_free(tmp_ctx);
4442                 return ldb_oom(ldb);
4443         }
4444
4445         msg->dn = dn;
4446         ret = ldb_msg_add_string(msg, "objectClass", "top");
4447         if (ret != LDB_SUCCESS) {
4448                 talloc_free(tmp_ctx);
4449                 return ldb_oom(ldb);
4450         }
4451
4452         /* [MS-DRSR] implies that we should only add the 'top'
4453          * objectclass, but that would cause lots of problems with our
4454          * objectclass code as top is not structural, so we add
4455          * 'domainDNS' as well to keep things sane. We're expecting
4456          * this new NC to be of objectclass domainDNS after
4457          * replication anyway
4458          */
4459         ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
4460         if (ret != LDB_SUCCESS) {
4461                 talloc_free(tmp_ctx);
4462                 return ldb_oom(ldb);
4463         }
4464
4465         ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
4466                               INSTANCE_TYPE_IS_NC_HEAD|
4467                               INSTANCE_TYPE_NC_ABOVE|
4468                               INSTANCE_TYPE_UNINSTANT);
4469         if (ret != LDB_SUCCESS) {
4470                 talloc_free(tmp_ctx);
4471                 return ldb_oom(ldb);
4472         }
4473
4474         ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
4475         if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
4476                 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
4477                          ldb_dn_get_linearized(dn),
4478                          ldb_errstring(ldb), ldb_strerror(ret)));
4479                 talloc_free(tmp_ctx);
4480                 return ret;
4481         }
4482
4483         DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
4484
4485         talloc_free(tmp_ctx);
4486         return LDB_SUCCESS;
4487 }