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