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