s4:dsdb Move dsdb_save_partition_usn() to be a module helper function
[mat/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_errors.h"
28 #include "../lib/util/util_ldb.h"
29 #include "../lib/crypto/crypto.h"
30 #include "dsdb/samdb/samdb.h"
31 #include "libcli/security/security.h"
32 #include "librpc/gen_ndr/ndr_security.h"
33 #include "librpc/gen_ndr/ndr_misc.h"
34 #include "../libds/common/flags.h"
35 #include "dsdb/common/proto.h"
36 #include "libcli/ldap/ldap_ndr.h"
37 #include "param/param.h"
38 #include "libcli/auth/libcli_auth.h"
39 #include "librpc/gen_ndr/ndr_drsblobs.h"
40 #include "system/locale.h"
41 #include "lib/util/tsort.h"
42 #include "dsdb/common/util.h"
43
44 /*
45   search the sam for the specified attributes in a specific domain, filter on
46   objectSid being in domain_sid.
47 */
48 int samdb_search_domain(struct ldb_context *sam_ldb,
49                         TALLOC_CTX *mem_ctx, 
50                         struct ldb_dn *basedn,
51                         struct ldb_message ***res,
52                         const char * const *attrs,
53                         const struct dom_sid *domain_sid,
54                         const char *format, ...)  _PRINTF_ATTRIBUTE(7,8)
55 {
56         va_list ap;
57         int i, count;
58
59         va_start(ap, format);
60         count = gendb_search_v(sam_ldb, mem_ctx, basedn,
61                                res, attrs, format, ap);
62         va_end(ap);
63
64         i=0;
65
66         while (i<count) {
67                 struct dom_sid *entry_sid;
68
69                 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
70
71                 if ((entry_sid == NULL) ||
72                     (!dom_sid_in_domain(domain_sid, entry_sid))) {
73                         /* Delete that entry from the result set */
74                         (*res)[i] = (*res)[count-1];
75                         count -= 1;
76                         talloc_free(entry_sid);
77                         continue;
78                 }
79                 talloc_free(entry_sid);
80                 i += 1;
81         }
82
83         return count;
84 }
85
86 /*
87   search the sam for a single string attribute in exactly 1 record
88 */
89 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
90                                   TALLOC_CTX *mem_ctx,
91                                   struct ldb_dn *basedn,
92                                   const char *attr_name,
93                                   const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
94 {
95         int count;
96         const char *attrs[2] = { NULL, NULL };
97         struct ldb_message **res = NULL;
98
99         attrs[0] = attr_name;
100
101         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
102         if (count > 1) {                
103                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
104                          attr_name, format, count));
105         }
106         if (count != 1) {
107                 talloc_free(res);
108                 return NULL;
109         }
110
111         return samdb_result_string(res[0], attr_name, NULL);
112 }
113
114 /*
115   search the sam for a single string attribute in exactly 1 record
116 */
117 const char *samdb_search_string(struct ldb_context *sam_ldb,
118                                 TALLOC_CTX *mem_ctx,
119                                 struct ldb_dn *basedn,
120                                 const char *attr_name,
121                                 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
122 {
123         va_list ap;
124         const char *str;
125
126         va_start(ap, format);
127         str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
128         va_end(ap);
129
130         return str;
131 }
132
133 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
134                                TALLOC_CTX *mem_ctx,
135                                struct ldb_dn *basedn,
136                                const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
137 {
138         va_list ap;
139         struct ldb_dn *ret;
140         struct ldb_message **res = NULL;
141         int count;
142
143         va_start(ap, format);
144         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
145         va_end(ap);
146
147         if (count != 1) return NULL;
148
149         ret = talloc_steal(mem_ctx, res[0]->dn);
150         talloc_free(res);
151
152         return ret;
153 }
154
155 /*
156   search the sam for a dom_sid attribute in exactly 1 record
157 */
158 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
159                                      TALLOC_CTX *mem_ctx,
160                                      struct ldb_dn *basedn,
161                                      const char *attr_name,
162                                      const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
163 {
164         va_list ap;
165         int count;
166         struct ldb_message **res;
167         const char *attrs[2] = { NULL, NULL };
168         struct dom_sid *sid;
169
170         attrs[0] = attr_name;
171
172         va_start(ap, format);
173         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
174         va_end(ap);
175         if (count > 1) {                
176                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
177                          attr_name, format, count));
178         }
179         if (count != 1) {
180                 talloc_free(res);
181                 return NULL;
182         }
183         sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
184         talloc_free(res);
185         return sid;     
186 }
187
188 /*
189   return the count of the number of records in the sam matching the query
190 */
191 int samdb_search_count(struct ldb_context *sam_ldb,
192                        struct ldb_dn *basedn,
193                        const char *format, ...) _PRINTF_ATTRIBUTE(3,4)
194 {
195         va_list ap;
196         struct ldb_message **res;
197         const char *attrs[] = { NULL };
198         int ret;
199         TALLOC_CTX *tmp_ctx = talloc_new(sam_ldb);
200
201         va_start(ap, format);
202         ret = gendb_search_v(sam_ldb, tmp_ctx, basedn, &res, attrs, format, ap);
203         va_end(ap);
204         talloc_free(tmp_ctx);
205
206         return ret;
207 }
208
209
210 /*
211   search the sam for a single integer attribute in exactly 1 record
212 */
213 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
214                          TALLOC_CTX *mem_ctx,
215                          unsigned int default_value,
216                          struct ldb_dn *basedn,
217                          const char *attr_name,
218                          const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
219 {
220         va_list ap;
221         int count;
222         struct ldb_message **res;
223         const char *attrs[2] = { NULL, NULL };
224
225         attrs[0] = attr_name;
226
227         va_start(ap, format);
228         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
229         va_end(ap);
230
231         if (count != 1) {
232                 return default_value;
233         }
234
235         return samdb_result_uint(res[0], attr_name, default_value);
236 }
237
238 /*
239   search the sam for a single signed 64 bit integer attribute in exactly 1 record
240 */
241 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
242                            TALLOC_CTX *mem_ctx,
243                            int64_t default_value,
244                            struct ldb_dn *basedn,
245                            const char *attr_name,
246                            const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
247 {
248         va_list ap;
249         int count;
250         struct ldb_message **res;
251         const char *attrs[2] = { NULL, NULL };
252
253         attrs[0] = attr_name;
254
255         va_start(ap, format);
256         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
257         va_end(ap);
258
259         if (count != 1) {
260                 return default_value;
261         }
262
263         return samdb_result_int64(res[0], attr_name, default_value);
264 }
265
266 /*
267   search the sam for multipe records each giving a single string attribute
268   return the number of matches, or -1 on error
269 */
270 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
271                                  TALLOC_CTX *mem_ctx,
272                                  struct ldb_dn *basedn,
273                                  const char ***strs,
274                                  const char *attr_name,
275                                  const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
276 {
277         va_list ap;
278         int count, i;
279         const char *attrs[2] = { NULL, NULL };
280         struct ldb_message **res = NULL;
281
282         attrs[0] = attr_name;
283
284         va_start(ap, format);
285         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
286         va_end(ap);
287
288         if (count <= 0) {
289                 return count;
290         }
291
292         /* make sure its single valued */
293         for (i=0;i<count;i++) {
294                 if (res[i]->num_elements != 1) {
295                         DEBUG(1,("samdb: search for %s %s not single valued\n", 
296                                  attr_name, format));
297                         talloc_free(res);
298                         return -1;
299                 }
300         }
301
302         *strs = talloc_array(mem_ctx, const char *, count+1);
303         if (! *strs) {
304                 talloc_free(res);
305                 return -1;
306         }
307
308         for (i=0;i<count;i++) {
309                 (*strs)[i] = samdb_result_string(res[i], attr_name, NULL);
310         }
311         (*strs)[count] = NULL;
312
313         return count;
314 }
315
316 /*
317   pull a uint from a result set. 
318 */
319 unsigned int samdb_result_uint(const struct ldb_message *msg, const char *attr, unsigned int default_value)
320 {
321         return ldb_msg_find_attr_as_uint(msg, attr, default_value);
322 }
323
324 /*
325   pull a (signed) int64 from a result set. 
326 */
327 int64_t samdb_result_int64(const struct ldb_message *msg, const char *attr, int64_t default_value)
328 {
329         return ldb_msg_find_attr_as_int64(msg, attr, default_value);
330 }
331
332 /*
333   pull a string from a result set. 
334 */
335 const char *samdb_result_string(const struct ldb_message *msg, const char *attr, 
336                                 const char *default_value)
337 {
338         return ldb_msg_find_attr_as_string(msg, attr, default_value);
339 }
340
341 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
342                                const char *attr, struct ldb_dn *default_value)
343 {
344         struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
345         if (!ret_dn) {
346                 return default_value;
347         }
348         return ret_dn;
349 }
350
351 /*
352   pull a rid from a objectSid in a result set. 
353 */
354 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
355                                    const char *attr, uint32_t default_value)
356 {
357         struct dom_sid *sid;
358         uint32_t rid;
359
360         sid = samdb_result_dom_sid(mem_ctx, msg, attr);
361         if (sid == NULL) {
362                 return default_value;
363         }
364         rid = sid->sub_auths[sid->num_auths-1];
365         talloc_free(sid);
366         return rid;
367 }
368
369 /*
370   pull a dom_sid structure from a objectSid in a result set. 
371 */
372 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
373                                      const char *attr)
374 {
375         const struct ldb_val *v;
376         struct dom_sid *sid;
377         enum ndr_err_code ndr_err;
378         v = ldb_msg_find_ldb_val(msg, attr);
379         if (v == NULL) {
380                 return NULL;
381         }
382         sid = talloc(mem_ctx, struct dom_sid);
383         if (sid == NULL) {
384                 return NULL;
385         }
386         ndr_err = ndr_pull_struct_blob(v, sid, NULL, sid,
387                                        (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
388         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
389                 talloc_free(sid);
390                 return NULL;
391         }
392         return sid;
393 }
394
395 /*
396   pull a guid structure from a objectGUID in a result set. 
397 */
398 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
399 {
400         const struct ldb_val *v;
401         struct GUID guid;
402         NTSTATUS status;
403
404         v = ldb_msg_find_ldb_val(msg, attr);
405         if (!v) return GUID_zero();
406
407         status = GUID_from_ndr_blob(v, &guid);
408         if (!NT_STATUS_IS_OK(status)) {
409                 return GUID_zero();
410         }
411
412         return guid;
413 }
414
415 /*
416   pull a sid prefix from a objectSid in a result set. 
417   this is used to find the domain sid for a user
418 */
419 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
420                                         const char *attr)
421 {
422         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
423         if (!sid || sid->num_auths < 1) return NULL;
424         sid->num_auths--;
425         return sid;
426 }
427
428 /*
429   pull a NTTIME in a result set. 
430 */
431 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
432                            NTTIME default_value)
433 {
434         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
435 }
436
437 /*
438  * Windows stores 0 for lastLogoff.
439  * But when a MS DC return the lastLogoff (as Logoff Time)
440  * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
441  * cause windows 2008 and newer version to fail for SMB requests
442  */
443 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
444 {
445         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
446
447         if (ret == 0)
448                 ret = 0x7FFFFFFFFFFFFFFFULL;
449
450         return ret;
451 }
452
453 /*
454  * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
455  * indicate an account doesn't expire.
456  *
457  * When Windows initially creates an account, it sets
458  * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF).  However,
459  * when changing from an account having a specific expiration date to
460  * that account never expiring, it sets accountExpires = 0.
461  *
462  * Consolidate that logic here to allow clearer logic for account expiry in
463  * the rest of the code.
464  */
465 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
466 {
467         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
468                                                  0);
469
470         if (ret == 0)
471                 ret = 0x7FFFFFFFFFFFFFFFULL;
472
473         return ret;
474 }
475
476 /*
477   pull a uint64_t from a result set. 
478 */
479 uint64_t samdb_result_uint64(const struct ldb_message *msg, const char *attr,
480                              uint64_t default_value)
481 {
482         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
483 }
484
485
486 /*
487   construct the allow_password_change field from the PwdLastSet attribute and the 
488   domain password settings
489 */
490 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb, 
491                                           TALLOC_CTX *mem_ctx, 
492                                           struct ldb_dn *domain_dn, 
493                                           struct ldb_message *msg, 
494                                           const char *attr)
495 {
496         uint64_t attr_time = samdb_result_uint64(msg, attr, 0);
497         int64_t minPwdAge;
498
499         if (attr_time == 0) {
500                 return 0;
501         }
502
503         minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
504
505         /* yes, this is a -= not a += as minPwdAge is stored as the negative
506            of the number of 100-nano-seconds */
507         attr_time -= minPwdAge;
508
509         return attr_time;
510 }
511
512 /*
513   construct the force_password_change field from the PwdLastSet
514   attribute, the userAccountControl and the domain password settings
515 */
516 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb, 
517                                           TALLOC_CTX *mem_ctx, 
518                                           struct ldb_dn *domain_dn, 
519                                           struct ldb_message *msg)
520 {
521         uint64_t attr_time = samdb_result_uint64(msg, "pwdLastSet", 0);
522         uint32_t userAccountControl = samdb_result_uint64(msg, "userAccountControl", 0);
523         int64_t maxPwdAge;
524
525         /* Machine accounts don't expire, and there is a flag for 'no expiry' */
526         if (!(userAccountControl & UF_NORMAL_ACCOUNT)
527             || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
528                 return 0x7FFFFFFFFFFFFFFFULL;
529         }
530
531         if (attr_time == 0) {
532                 return 0;
533         }
534
535         maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "maxPwdAge", NULL);
536         if (maxPwdAge == 0) {
537                 return 0x7FFFFFFFFFFFFFFFULL;
538         } else {
539                 attr_time -= maxPwdAge;
540         }
541
542         return attr_time;
543 }
544
545 /*
546   pull a samr_Password structutre from a result set. 
547 */
548 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
549 {
550         struct samr_Password *hash = NULL;
551         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
552         if (val && (val->length >= sizeof(hash->hash))) {
553                 hash = talloc(mem_ctx, struct samr_Password);
554                 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
555         }
556         return hash;
557 }
558
559 /*
560   pull an array of samr_Password structures from a result set.
561 */
562 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
563                            const char *attr, struct samr_Password **hashes)
564 {
565         unsigned int count, i;
566         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
567
568         *hashes = NULL;
569         if (!val) {
570                 return 0;
571         }
572         count = val->length / 16;
573         if (count == 0) {
574                 return 0;
575         }
576
577         *hashes = talloc_array(mem_ctx, struct samr_Password, count);
578         if (! *hashes) {
579                 return 0;
580         }
581
582         for (i=0;i<count;i++) {
583                 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
584         }
585
586         return count;
587 }
588
589 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct ldb_message *msg, 
590                                 struct samr_Password **lm_pwd, struct samr_Password **nt_pwd) 
591 {
592         struct samr_Password *lmPwdHash, *ntPwdHash;
593         if (nt_pwd) {
594                 unsigned int num_nt;
595                 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
596                 if (num_nt == 0) {
597                         *nt_pwd = NULL;
598                 } else if (num_nt > 1) {
599                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
600                 } else {
601                         *nt_pwd = &ntPwdHash[0];
602                 }
603         }
604         if (lm_pwd) {
605                 /* Ensure that if we have turned off LM
606                  * authentication, that we never use the LM hash, even
607                  * if we store it */
608                 if (lp_lanman_auth(lp_ctx)) {
609                         unsigned int num_lm;
610                         num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
611                         if (num_lm == 0) {
612                                 *lm_pwd = NULL;
613                         } else if (num_lm > 1) {
614                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
615                         } else {
616                                 *lm_pwd = &lmPwdHash[0];
617                         }
618                 } else {
619                         *lm_pwd = NULL;
620                 }
621         }
622         return NT_STATUS_OK;
623 }
624
625 /*
626   pull a samr_LogonHours structutre from a result set. 
627 */
628 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
629 {
630         struct samr_LogonHours hours;
631         const int units_per_week = 168;
632         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
633         ZERO_STRUCT(hours);
634         hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week);
635         if (!hours.bits) {
636                 return hours;
637         }
638         hours.units_per_week = units_per_week;
639         memset(hours.bits, 0xFF, units_per_week);
640         if (val) {
641                 memcpy(hours.bits, val->data, MIN(val->length, units_per_week));
642         }
643         return hours;
644 }
645
646 /*
647   pull a set of account_flags from a result set. 
648
649   This requires that the attributes: 
650    pwdLastSet
651    userAccountControl
652   be included in 'msg'
653 */
654 uint32_t samdb_result_acct_flags(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
655                                  struct ldb_message *msg, struct ldb_dn *domain_dn)
656 {
657         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
658         uint32_t acct_flags = ds_uf2acb(userAccountControl);
659         NTTIME must_change_time;
660         NTTIME now;
661
662         must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx, 
663                                                               domain_dn, msg);
664
665         /* Test account expire time */
666         unix_to_nt_time(&now, time(NULL));
667         /* check for expired password */
668         if (must_change_time < now) {
669                 acct_flags |= ACB_PW_EXPIRED;
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_value(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
724 {
725         if (samdb_find_attribute(ldb, msg, name, set_value) == NULL) {
726                 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
727         }
728         return LDB_SUCCESS;
729 }
730
731 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
732 {
733         struct ldb_message_element *el;
734
735         el = ldb_msg_find_element(msg, name);
736         if (el) {
737                 return LDB_SUCCESS;
738         }
739
740         return samdb_msg_add_string(ldb, msg, msg, name, set_value);
741 }
742
743
744
745 /*
746   add a string element to a message
747 */
748 int samdb_msg_add_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
749                          const char *attr_name, const char *str)
750 {
751         char *s = talloc_strdup(mem_ctx, str);
752         char *a = talloc_strdup(mem_ctx, attr_name);
753         if (s == NULL || a == NULL) {
754                 return LDB_ERR_OPERATIONS_ERROR;
755         }
756         return ldb_msg_add_string(msg, a, s);
757 }
758
759 /*
760   add a dom_sid element to a message
761 */
762 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
763                          const char *attr_name, struct dom_sid *sid)
764 {
765         struct ldb_val v;
766         enum ndr_err_code ndr_err;
767
768         ndr_err = ndr_push_struct_blob(&v, mem_ctx, 
769                                        lp_iconv_convenience(ldb_get_opaque(sam_ldb, "loadparm")),
770                                        sid,
771                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
772         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
773                 return LDB_ERR_OPERATIONS_ERROR;
774         }
775         return ldb_msg_add_value(msg, attr_name, &v, NULL);
776 }
777
778
779 /*
780   add a delete element operation to a message
781 */
782 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
783                          const char *attr_name)
784 {
785         /* we use an empty replace rather than a delete, as it allows for 
786            dsdb_replace() to be used everywhere */
787         return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
788 }
789
790 /*
791   add a add attribute value to a message
792 */
793 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
794                          const char *attr_name, const char *value)
795 {
796         struct ldb_message_element *el;
797         char *a, *v;
798         int ret;
799         a = talloc_strdup(mem_ctx, attr_name);
800         if (a == NULL)
801                 return LDB_ERR_OPERATIONS_ERROR;
802         v = talloc_strdup(mem_ctx, value);
803         if (v == NULL)
804                 return LDB_ERR_OPERATIONS_ERROR;
805         ret = ldb_msg_add_string(msg, a, v);
806         if (ret != 0)
807                 return ret;
808         el = ldb_msg_find_element(msg, a);
809         if (el == NULL)
810                 return LDB_ERR_OPERATIONS_ERROR;
811         el->flags = LDB_FLAG_MOD_ADD;
812         return LDB_SUCCESS;
813 }
814
815 /*
816   add a delete attribute value to a message
817 */
818 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
819                          const char *attr_name, const char *value)
820 {
821         struct ldb_message_element *el;
822         char *a, *v;
823         int ret;
824         a = talloc_strdup(mem_ctx, attr_name);
825         if (a == NULL)
826                 return LDB_ERR_OPERATIONS_ERROR;
827         v = talloc_strdup(mem_ctx, value);
828         if (v == NULL)
829                 return LDB_ERR_OPERATIONS_ERROR;
830         ret = ldb_msg_add_string(msg, a, v);
831         if (ret != 0)
832                 return ret;
833         el = ldb_msg_find_element(msg, a);
834         if (el == NULL)
835                 return LDB_ERR_OPERATIONS_ERROR;
836         el->flags = LDB_FLAG_MOD_DELETE;
837         return LDB_SUCCESS;
838 }
839
840 /*
841   add a int element to a message
842 */
843 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
844                        const char *attr_name, int v)
845 {
846         const char *s = talloc_asprintf(mem_ctx, "%d", v);
847         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
848 }
849
850 /*
851   add a unsigned int element to a message
852 */
853 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
854                        const char *attr_name, unsigned int v)
855 {
856         return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
857 }
858
859 /*
860   add a (signed) int64_t element to a message
861 */
862 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
863                         const char *attr_name, int64_t v)
864 {
865         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
866         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
867 }
868
869 /*
870   add a uint64_t element to a message
871 */
872 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
873                         const char *attr_name, uint64_t v)
874 {
875         return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
876 }
877
878 /*
879   add a samr_Password element to a message
880 */
881 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
882                        const char *attr_name, struct samr_Password *hash)
883 {
884         struct ldb_val val;
885         val.data = talloc_memdup(mem_ctx, hash->hash, 16);
886         if (!val.data) {
887                 return LDB_ERR_OPERATIONS_ERROR;
888         }
889         val.length = 16;
890         return ldb_msg_add_value(msg, attr_name, &val, NULL);
891 }
892
893 /*
894   add a samr_Password array to a message
895 */
896 int samdb_msg_add_hashes(TALLOC_CTX *mem_ctx, struct ldb_message *msg,
897                          const char *attr_name, struct samr_Password *hashes,
898                          unsigned int count)
899 {
900         struct ldb_val val;
901         unsigned int i;
902         val.data = talloc_array_size(mem_ctx, 16, count);
903         val.length = count*16;
904         if (!val.data) {
905                 return LDB_ERR_OPERATIONS_ERROR;
906         }
907         for (i=0;i<count;i++) {
908                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
909         }
910         return ldb_msg_add_value(msg, attr_name, &val, NULL);
911 }
912
913 /*
914   add a acct_flags element to a message
915 */
916 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
917                              const char *attr_name, uint32_t v)
918 {
919         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
920 }
921
922 /*
923   add a logon_hours element to a message
924 */
925 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
926                               const char *attr_name, struct samr_LogonHours *hours)
927 {
928         struct ldb_val val;
929         val.length = hours->units_per_week / 8;
930         val.data = hours->bits;
931         return ldb_msg_add_value(msg, attr_name, &val, NULL);
932 }
933
934 /*
935   add a parameters element to a message
936 */
937 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
938                              const char *attr_name, struct lsa_BinaryString *parameters)
939 {
940         struct ldb_val val;
941         val.length = parameters->length;
942         val.data = (uint8_t *)parameters->array;
943         return ldb_msg_add_value(msg, attr_name, &val, NULL);
944 }
945 /*
946   add a general value element to a message
947 */
948 int samdb_msg_add_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
949                               const char *attr_name, const struct ldb_val *val)
950 {
951         return ldb_msg_add_value(msg, attr_name, val, NULL);
952 }
953
954 /*
955   sets a general value element to a message
956 */
957 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
958                         const char *attr_name, const struct ldb_val *val)
959 {
960         struct ldb_message_element *el;
961
962         el = ldb_msg_find_element(msg, attr_name);
963         if (el) {
964                 el->num_values = 0;
965         }
966         return ldb_msg_add_value(msg, attr_name, val, NULL);
967 }
968
969 /*
970   set a string element in a message
971 */
972 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
973                          const char *attr_name, const char *str)
974 {
975         struct ldb_message_element *el;
976
977         el = ldb_msg_find_element(msg, attr_name);
978         if (el) {
979                 el->num_values = 0;
980         }
981         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, str);
982 }
983
984 /*
985  * Handle ldb_request in transaction
986  */
987 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
988                                         struct ldb_request *req)
989 {
990         int ret;
991
992         ret = ldb_transaction_start(sam_ldb);
993         if (ret != LDB_SUCCESS) {
994                 return ret;
995         }
996
997         ret = ldb_request(sam_ldb, req);
998         if (ret == LDB_SUCCESS) {
999                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1000         }
1001
1002         if (ret == LDB_SUCCESS) {
1003                 return ldb_transaction_commit(sam_ldb);
1004         }
1005         ldb_transaction_cancel(sam_ldb);
1006
1007         return ret;
1008 }
1009
1010 /*
1011   return a default security descriptor
1012 */
1013 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1014 {
1015         struct security_descriptor *sd;
1016
1017         sd = security_descriptor_initialise(mem_ctx);
1018
1019         return sd;
1020 }
1021
1022 struct ldb_dn *samdb_base_dn(struct ldb_context *sam_ctx) 
1023 {
1024         return ldb_get_default_basedn(sam_ctx);
1025 }
1026
1027 struct ldb_dn *samdb_config_dn(struct ldb_context *sam_ctx) 
1028 {
1029         return ldb_get_config_basedn(sam_ctx);
1030 }
1031
1032 struct ldb_dn *samdb_schema_dn(struct ldb_context *sam_ctx) 
1033 {
1034         return ldb_get_schema_basedn(sam_ctx);
1035 }
1036
1037 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx) 
1038 {
1039         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1040         struct ldb_dn *aggregate_dn;
1041         if (!schema_dn) {
1042                 return NULL;
1043         }
1044
1045         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1046         if (!aggregate_dn) {
1047                 return NULL;
1048         }
1049         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1050                 return NULL;
1051         }
1052         return aggregate_dn;
1053 }
1054
1055 struct ldb_dn *samdb_root_dn(struct ldb_context *sam_ctx) 
1056 {
1057         return ldb_get_root_basedn(sam_ctx);
1058 }
1059
1060 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1061 {
1062         struct ldb_dn *new_dn;
1063
1064         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1065         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1066                 talloc_free(new_dn);
1067                 return NULL;
1068         }
1069         return new_dn;
1070 }
1071
1072 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1073 {
1074        struct ldb_dn *new_dn;
1075
1076        new_dn = ldb_dn_copy(mem_ctx, samdb_base_dn(sam_ctx));
1077        if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1078                talloc_free(new_dn);
1079                return NULL;
1080        }
1081        return new_dn;
1082 }
1083
1084 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1085 {
1086         struct ldb_dn *new_dn;
1087
1088         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1089         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1090                 talloc_free(new_dn);
1091                 return NULL;
1092         }
1093         return new_dn;
1094 }
1095
1096 /*
1097   work out the domain sid for the current open ldb
1098 */
1099 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1100 {
1101         TALLOC_CTX *tmp_ctx;
1102         const struct dom_sid *domain_sid;
1103         const char *attrs[] = {
1104                 "objectSid",
1105                 NULL
1106         };
1107         struct ldb_result *res;
1108         int ret;
1109
1110         /* see if we have a cached copy */
1111         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1112         if (domain_sid) {
1113                 return domain_sid;
1114         }
1115
1116         tmp_ctx = talloc_new(ldb);
1117         if (tmp_ctx == NULL) {
1118                 goto failed;
1119         }
1120
1121         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1122
1123         if (ret != LDB_SUCCESS) {
1124                 goto failed;
1125         }
1126
1127         if (res->count != 1) {
1128                 goto failed;
1129         }
1130
1131         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1132         if (domain_sid == NULL) {
1133                 goto failed;
1134         }
1135
1136         /* cache the domain_sid in the ldb */
1137         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1138                 goto failed;
1139         }
1140
1141         talloc_steal(ldb, domain_sid);
1142         talloc_free(tmp_ctx);
1143
1144         return domain_sid;
1145
1146 failed:
1147         talloc_free(tmp_ctx);
1148         return NULL;
1149 }
1150
1151 /*
1152   get domain sid from cache
1153 */
1154 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1155 {
1156         return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1157 }
1158
1159 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1160 {
1161         TALLOC_CTX *tmp_ctx;
1162         struct dom_sid *dom_sid_new;
1163         struct dom_sid *dom_sid_old;
1164
1165         /* see if we have a cached copy */
1166         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1167                                                      "cache.domain_sid"), struct dom_sid);
1168
1169         tmp_ctx = talloc_new(ldb);
1170         if (tmp_ctx == NULL) {
1171                 goto failed;
1172         }
1173
1174         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1175         if (!dom_sid_new) {
1176                 goto failed;
1177         }
1178
1179         /* cache the domain_sid in the ldb */
1180         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1181                 goto failed;
1182         }
1183
1184         talloc_steal(ldb, dom_sid_new);
1185         talloc_free(tmp_ctx);
1186         talloc_free(dom_sid_old);
1187
1188         return true;
1189
1190 failed:
1191         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1192         talloc_free(tmp_ctx);
1193         return false;
1194 }
1195
1196 /* Obtain the short name of the flexible single master operator
1197  * (FSMO), such as the PDC Emulator */
1198 const char *samdb_result_fsmo_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
1199                              const char *attr)
1200 {
1201         /* Format is cn=NTDS Settings,cn=<NETBIOS name of FSMO>,.... */
1202         struct ldb_dn *fsmo_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
1203         const struct ldb_val *val = ldb_dn_get_component_val(fsmo_dn, 1);
1204         const char *name = ldb_dn_get_component_name(fsmo_dn, 1);
1205
1206         if (!name || (ldb_attr_cmp(name, "cn") != 0)) {
1207                 /* Ensure this matches the format.  This gives us a
1208                  * bit more confidence that a 'cn' value will be a
1209                  * ascii string */
1210                 return NULL;
1211         }
1212         if (val) {
1213                 return (char *)val->data;
1214         }
1215         return NULL;
1216 }
1217
1218 /*
1219   work out the ntds settings dn for the current open ldb
1220 */
1221 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1222 {
1223         TALLOC_CTX *tmp_ctx;
1224         const char *root_attrs[] = { "dsServiceName", NULL };
1225         int ret;
1226         struct ldb_result *root_res;
1227         struct ldb_dn *settings_dn;
1228
1229         /* see if we have a cached copy */
1230         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "cache.settings_dn");
1231         if (settings_dn) {
1232                 return settings_dn;
1233         }
1234
1235         tmp_ctx = talloc_new(ldb);
1236         if (tmp_ctx == NULL) {
1237                 goto failed;
1238         }
1239
1240         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1241         if (ret) {
1242                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1243                          ldb_errstring(ldb)));
1244                 goto failed;
1245         }
1246
1247         if (root_res->count != 1) {
1248                 goto failed;
1249         }
1250
1251         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1252
1253         /* cache the domain_sid in the ldb */
1254         if (ldb_set_opaque(ldb, "cache.settings_dn", settings_dn) != LDB_SUCCESS) {
1255                 goto failed;
1256         }
1257
1258         talloc_steal(ldb, settings_dn);
1259         talloc_free(tmp_ctx);
1260
1261         return settings_dn;
1262
1263 failed:
1264         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1265         talloc_free(tmp_ctx);
1266         return NULL;
1267 }
1268
1269 /*
1270   work out the ntds settings invocationId for the current open ldb
1271 */
1272 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1273 {
1274         TALLOC_CTX *tmp_ctx;
1275         const char *attrs[] = { "invocationId", NULL };
1276         int ret;
1277         struct ldb_result *res;
1278         struct GUID *invocation_id;
1279
1280         /* see if we have a cached copy */
1281         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1282         if (invocation_id) {
1283                 return invocation_id;
1284         }
1285
1286         tmp_ctx = talloc_new(ldb);
1287         if (tmp_ctx == NULL) {
1288                 goto failed;
1289         }
1290
1291         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1292         if (ret) {
1293                 goto failed;
1294         }
1295
1296         if (res->count != 1) {
1297                 goto failed;
1298         }
1299
1300         invocation_id = talloc(tmp_ctx, struct GUID);
1301         if (!invocation_id) {
1302                 goto failed;
1303         }
1304
1305         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1306
1307         /* cache the domain_sid in the ldb */
1308         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1309                 goto failed;
1310         }
1311
1312         talloc_steal(ldb, invocation_id);
1313         talloc_free(tmp_ctx);
1314
1315         return invocation_id;
1316
1317 failed:
1318         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1319         talloc_free(tmp_ctx);
1320         return NULL;
1321 }
1322
1323 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1324 {
1325         TALLOC_CTX *tmp_ctx;
1326         struct GUID *invocation_id_new;
1327         struct GUID *invocation_id_old;
1328
1329         /* see if we have a cached copy */
1330         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1331                                                          "cache.invocation_id");
1332
1333         tmp_ctx = talloc_new(ldb);
1334         if (tmp_ctx == NULL) {
1335                 goto failed;
1336         }
1337
1338         invocation_id_new = talloc(tmp_ctx, struct GUID);
1339         if (!invocation_id_new) {
1340                 goto failed;
1341         }
1342
1343         *invocation_id_new = *invocation_id_in;
1344
1345         /* cache the domain_sid in the ldb */
1346         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1347                 goto failed;
1348         }
1349
1350         talloc_steal(ldb, invocation_id_new);
1351         talloc_free(tmp_ctx);
1352         talloc_free(invocation_id_old);
1353
1354         return true;
1355
1356 failed:
1357         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1358         talloc_free(tmp_ctx);
1359         return false;
1360 }
1361
1362 /*
1363   work out the ntds settings objectGUID for the current open ldb
1364 */
1365 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1366 {
1367         TALLOC_CTX *tmp_ctx;
1368         const char *attrs[] = { "objectGUID", NULL };
1369         int ret;
1370         struct ldb_result *res;
1371         struct GUID *ntds_guid;
1372
1373         /* see if we have a cached copy */
1374         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1375         if (ntds_guid) {
1376                 return ntds_guid;
1377         }
1378
1379         tmp_ctx = talloc_new(ldb);
1380         if (tmp_ctx == NULL) {
1381                 goto failed;
1382         }
1383
1384         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1385         if (ret) {
1386                 goto failed;
1387         }
1388
1389         if (res->count != 1) {
1390                 goto failed;
1391         }
1392
1393         ntds_guid = talloc(tmp_ctx, struct GUID);
1394         if (!ntds_guid) {
1395                 goto failed;
1396         }
1397
1398         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1399
1400         /* cache the domain_sid in the ldb */
1401         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1402                 goto failed;
1403         }
1404
1405         talloc_steal(ldb, ntds_guid);
1406         talloc_free(tmp_ctx);
1407
1408         return ntds_guid;
1409
1410 failed:
1411         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1412         talloc_free(tmp_ctx);
1413         return NULL;
1414 }
1415
1416 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1417 {
1418         TALLOC_CTX *tmp_ctx;
1419         struct GUID *ntds_guid_new;
1420         struct GUID *ntds_guid_old;
1421
1422         /* see if we have a cached copy */
1423         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1424
1425         tmp_ctx = talloc_new(ldb);
1426         if (tmp_ctx == NULL) {
1427                 goto failed;
1428         }
1429
1430         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1431         if (!ntds_guid_new) {
1432                 goto failed;
1433         }
1434
1435         *ntds_guid_new = *ntds_guid_in;
1436
1437         /* cache the domain_sid in the ldb */
1438         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1439                 goto failed;
1440         }
1441
1442         talloc_steal(ldb, ntds_guid_new);
1443         talloc_free(tmp_ctx);
1444         talloc_free(ntds_guid_old);
1445
1446         return true;
1447
1448 failed:
1449         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1450         talloc_free(tmp_ctx);
1451         return false;
1452 }
1453
1454 /*
1455   work out the server dn for the current open ldb
1456 */
1457 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1458 {
1459         return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1460 }
1461
1462 /*
1463   work out the server dn for the current open ldb
1464 */
1465 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1466 {
1467         struct ldb_dn *server_dn;
1468         struct ldb_dn *servers_dn;
1469         struct ldb_dn *server_site_dn;
1470
1471         /* TODO: there must be a saner way to do this!! */
1472
1473         server_dn = samdb_server_dn(ldb, mem_ctx);
1474         if (!server_dn) return NULL;
1475
1476         servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1477         if (!servers_dn) return NULL;
1478
1479         server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1480
1481         talloc_free(server_dn);
1482         return server_site_dn;
1483 }
1484
1485 /*
1486   find a 'reference' DN that points at another object
1487   (eg. serverReference, rIDManagerReference etc)
1488  */
1489 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1490                        const char *attribute, struct ldb_dn **dn)
1491 {
1492         const char *attrs[2];
1493         struct ldb_result *res;
1494         int ret;
1495
1496         attrs[0] = attribute;
1497         attrs[1] = NULL;
1498
1499         ret = ldb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, NULL);
1500         if (ret != LDB_SUCCESS) {
1501                 return ret;
1502         }
1503         if (res->count != 1) {
1504                 talloc_free(res);
1505                 return LDB_ERR_NO_SUCH_OBJECT;
1506         }
1507
1508         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1509         if (!*dn) {
1510                 talloc_free(res);
1511                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1512         }
1513
1514         talloc_free(res);
1515         return LDB_SUCCESS;
1516 }
1517
1518 /*
1519   find our machine account via the serverReference attribute in the
1520   server DN
1521  */
1522 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1523 {
1524         struct ldb_dn *server_dn;
1525         int ret;
1526
1527         server_dn = samdb_server_dn(ldb, mem_ctx);
1528         if (server_dn == NULL) {
1529                 return LDB_ERR_NO_SUCH_OBJECT;
1530         }
1531
1532         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1533         talloc_free(server_dn);
1534
1535         return ret;
1536 }
1537
1538 /*
1539   find the RID Manager$ DN via the rIDManagerReference attribute in the
1540   base DN
1541  */
1542 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1543 {
1544         return samdb_reference_dn(ldb, mem_ctx, samdb_base_dn(ldb), "rIDManagerReference", dn);
1545 }
1546
1547 /*
1548   find the RID Set DN via the rIDSetReferences attribute in our
1549   machine account DN
1550  */
1551 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1552 {
1553         struct ldb_dn *server_ref_dn;
1554         int ret;
1555
1556         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1557         if (ret != LDB_SUCCESS) {
1558                 return ret;
1559         }
1560         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1561         talloc_free(server_ref_dn);
1562         return ret;
1563 }
1564
1565 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1566 {
1567         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb, mem_ctx));
1568
1569         if (val != NULL)
1570                 return (const char *) val->data;
1571         else
1572                 return NULL;
1573 }
1574
1575 /*
1576   work out if we are the PDC for the domain of the current open ldb
1577 */
1578 bool samdb_is_pdc(struct ldb_context *ldb)
1579 {
1580         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1581         int ret;
1582         struct ldb_result *dom_res;
1583         TALLOC_CTX *tmp_ctx;
1584         bool is_pdc;
1585         struct ldb_dn *pdc;
1586
1587         tmp_ctx = talloc_new(ldb);
1588         if (tmp_ctx == NULL) {
1589                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1590                 return false;
1591         }
1592
1593         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1594         if (ret) {
1595                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1596                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1597                          ldb_errstring(ldb)));
1598                 goto failed;
1599         }
1600         if (dom_res->count != 1) {
1601                 goto failed;
1602         }
1603
1604         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1605
1606         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1607                 is_pdc = true;
1608         } else {
1609                 is_pdc = false;
1610         }
1611
1612         talloc_free(tmp_ctx);
1613
1614         return is_pdc;
1615
1616 failed:
1617         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1618         talloc_free(tmp_ctx);
1619         return false;
1620 }
1621
1622 /*
1623   work out if we are a Global Catalog server for the domain of the current open ldb
1624 */
1625 bool samdb_is_gc(struct ldb_context *ldb)
1626 {
1627         const char *attrs[] = { "options", NULL };
1628         int ret, options;
1629         struct ldb_result *res;
1630         TALLOC_CTX *tmp_ctx;
1631
1632         tmp_ctx = talloc_new(ldb);
1633         if (tmp_ctx == NULL) {
1634                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1635                 return false;
1636         }
1637
1638         /* Query cn=ntds settings,.... */
1639         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1640         if (ret) {
1641                 talloc_free(tmp_ctx);
1642                 return false;
1643         }
1644         if (res->count != 1) {
1645                 talloc_free(tmp_ctx);
1646                 return false;
1647         }
1648
1649         options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1650         talloc_free(tmp_ctx);
1651
1652         /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1653         if (options & 0x000000001) {
1654                 return true;
1655         }
1656         return false;
1657 }
1658
1659 /* Find a domain object in the parents of a particular DN.  */
1660 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1661                                    struct ldb_dn **parent_dn, const char **errstring)
1662 {
1663         TALLOC_CTX *local_ctx;
1664         struct ldb_dn *sdn = dn;
1665         struct ldb_result *res = NULL;
1666         int ret = 0;
1667         const char *attrs[] = { NULL };
1668
1669         local_ctx = talloc_new(mem_ctx);
1670         if (local_ctx == NULL) return LDB_ERR_OPERATIONS_ERROR;
1671
1672         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1673                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1674                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1675                 if (ret == LDB_SUCCESS) {
1676                         if (res->count == 1) {
1677                                 break;
1678                         }
1679                 } else {
1680                         break;
1681                 }
1682         }
1683
1684         if (ret != LDB_SUCCESS) {
1685                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1686                                              ldb_dn_get_linearized(dn),
1687                                              ldb_dn_get_linearized(sdn),
1688                                              ldb_errstring(ldb));
1689                 talloc_free(local_ctx);
1690                 return ret;
1691         }
1692         if (res->count != 1) {
1693                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1694                                              ldb_dn_get_linearized(dn));
1695                 DEBUG(0,(__location__ ": %s\n", *errstring));
1696                 talloc_free(local_ctx);
1697                 return LDB_ERR_CONSTRAINT_VIOLATION;
1698         }
1699
1700         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1701         talloc_free(local_ctx);
1702         return ret;
1703 }
1704
1705
1706 /*
1707  * Performs checks on a user password (plaintext UNIX format - attribute
1708  * "password"). The remaining parameters have to be extracted from the domain
1709  * object in the AD.
1710  *
1711  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1712  */
1713 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1714                                                 const uint32_t pwdProperties,
1715                                                 const uint32_t minPwdLength)
1716 {
1717         /* checks if the "minPwdLength" property is satisfied */
1718         if (minPwdLength > password->length)
1719                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1720
1721         /* checks the password complexity */
1722         if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1723                         && (password->data != NULL)
1724                         && (!check_password_quality((const char *) password->data)))
1725                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1726
1727         return SAMR_VALIDATION_STATUS_SUCCESS;
1728 }
1729
1730 /*
1731  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1732  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1733  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1734  * gives some more informations if the changed failed.
1735  *
1736  * The caller should have a LDB transaction wrapping this.
1737  *
1738  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
1739  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1740  *   NT_STATUS_PASSWORD_RESTRICTION
1741  */
1742 NTSTATUS samdb_set_password(struct ldb_context *ctx, TALLOC_CTX *mem_ctx,
1743                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1744                             struct ldb_message *mod,
1745                             const DATA_BLOB *new_password,
1746                             struct samr_Password *param_lmNewHash,
1747                             struct samr_Password *param_ntNewHash,
1748                             bool user_change,
1749                             enum samPwdChangeReason *reject_reason,
1750                             struct samr_DomInfo1 **_dominfo)
1751 {
1752         const char * const user_attrs[] = { "userAccountControl",
1753                                             "lmPwdHistory",
1754                                             "ntPwdHistory", 
1755                                             "dBCSPwd", "unicodePwd", 
1756                                             "objectSid", 
1757                                             "pwdLastSet", NULL };
1758         const char * const domain_attrs[] = { "minPwdLength", "pwdProperties",
1759                                               "pwdHistoryLength",
1760                                               "maxPwdAge", "minPwdAge", NULL };
1761         NTTIME pwdLastSet;
1762         uint32_t minPwdLength, pwdProperties, pwdHistoryLength;
1763         int64_t maxPwdAge, minPwdAge;
1764         uint32_t userAccountControl;
1765         struct samr_Password *sambaLMPwdHistory, *sambaNTPwdHistory,
1766                 *lmPwdHash, *ntPwdHash, *lmNewHash, *ntNewHash;
1767         struct samr_Password local_lmNewHash, local_ntNewHash;
1768         int sambaLMPwdHistory_len, sambaNTPwdHistory_len;
1769         struct dom_sid *domain_sid;
1770         struct ldb_message **res;
1771         bool restrictions;
1772         int count;
1773         time_t now = time(NULL);
1774         NTTIME now_nt;
1775         unsigned int i;
1776
1777         /* we need to know the time to compute password age */
1778         unix_to_nt_time(&now_nt, now);
1779
1780         /* pull all the user parameters */
1781         count = gendb_search_dn(ctx, mem_ctx, user_dn, &res, user_attrs);
1782         if (count != 1) {
1783                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1784         }
1785         userAccountControl = samdb_result_uint(res[0], "userAccountControl", 0);
1786         sambaLMPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1787                                          "lmPwdHistory", &sambaLMPwdHistory);
1788         sambaNTPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1789                                          "ntPwdHistory", &sambaNTPwdHistory);
1790         lmPwdHash = samdb_result_hash(mem_ctx, res[0], "dBCSPwd");
1791         ntPwdHash = samdb_result_hash(mem_ctx, res[0], "unicodePwd");
1792         pwdLastSet = samdb_result_uint64(res[0], "pwdLastSet", 0);
1793
1794         /* Copy parameters */
1795         lmNewHash = param_lmNewHash;
1796         ntNewHash = param_ntNewHash;
1797
1798         /* Only non-trust accounts have restrictions (possibly this
1799          * test is the wrong way around, but I like to be restrictive
1800          * if possible */
1801         restrictions = !(userAccountControl & (UF_INTERDOMAIN_TRUST_ACCOUNT
1802                                                |UF_WORKSTATION_TRUST_ACCOUNT
1803                                                |UF_SERVER_TRUST_ACCOUNT)); 
1804
1805         if (domain_dn != NULL) {
1806                 /* pull the domain parameters */
1807                 count = gendb_search_dn(ctx, mem_ctx, domain_dn, &res,
1808                                                                 domain_attrs);
1809                 if (count != 1) {
1810                         DEBUG(2, ("samdb_set_password: Domain DN %s is invalid, for user %s\n", 
1811                                   ldb_dn_get_linearized(domain_dn),
1812                                   ldb_dn_get_linearized(user_dn)));
1813                         return NT_STATUS_NO_SUCH_DOMAIN;
1814                 }
1815         } else {
1816                 /* work out the domain sid, and pull the domain from there */
1817                 domain_sid = samdb_result_sid_prefix(mem_ctx, res[0],
1818                                                                 "objectSid");
1819                 if (domain_sid == NULL) {
1820                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
1821                 }
1822
1823                 count = gendb_search(ctx, mem_ctx, NULL, &res, domain_attrs, 
1824                                 "(objectSid=%s)",
1825                                 ldap_encode_ndr_dom_sid(mem_ctx, domain_sid));
1826                 if (count != 1) {
1827                         DEBUG(2, ("samdb_set_password: Could not find domain to match SID: %s, for user %s\n", 
1828                                   dom_sid_string(mem_ctx, domain_sid),
1829                                   ldb_dn_get_linearized(user_dn)));
1830                         return NT_STATUS_NO_SUCH_DOMAIN;
1831                 }
1832         }
1833
1834         minPwdLength = samdb_result_uint(res[0], "minPwdLength", 0);
1835         pwdProperties = samdb_result_uint(res[0], "pwdProperties", 0);
1836         pwdHistoryLength = samdb_result_uint(res[0], "pwdHistoryLength", 0);
1837         maxPwdAge = samdb_result_int64(res[0], "maxPwdAge", 0);
1838         minPwdAge = samdb_result_int64(res[0], "minPwdAge", 0);
1839
1840         if ((userAccountControl & UF_PASSWD_NOTREQD) != 0) {
1841                 /* see [MS-ADTS] 2.2.15 */
1842                 minPwdLength = 0;
1843         }
1844
1845         if (_dominfo != NULL) {
1846                 struct samr_DomInfo1 *dominfo;
1847                 /* on failure we need to fill in the reject reasons */
1848                 dominfo = talloc(mem_ctx, struct samr_DomInfo1);
1849                 if (dominfo == NULL) {
1850                         return NT_STATUS_NO_MEMORY;
1851                 }
1852                 dominfo->min_password_length     = minPwdLength;
1853                 dominfo->password_properties     = pwdProperties;
1854                 dominfo->password_history_length = pwdHistoryLength;
1855                 dominfo->max_password_age        = maxPwdAge;
1856                 dominfo->min_password_age        = minPwdAge;
1857                 *_dominfo = dominfo;
1858         }
1859
1860         if ((restrictions != 0) && (new_password != 0)) {
1861                 char *new_pass;
1862
1863                 /* checks if the "minPwdLength" property is satisfied */
1864                 if ((restrictions != 0)
1865                         && (minPwdLength > utf16_len_n(
1866                                 new_password->data, new_password->length)/2)) {
1867                         if (reject_reason) {
1868                                 *reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
1869                         }
1870                         return NT_STATUS_PASSWORD_RESTRICTION;
1871                 }
1872
1873                 /* Create the NT hash */
1874                 mdfour(local_ntNewHash.hash, new_password->data,
1875                                                         new_password->length);
1876
1877                 ntNewHash = &local_ntNewHash;
1878
1879                 /* Only check complexity if we can convert it at all.  Assuming unconvertable passwords are 'strong' */
1880                 if (convert_string_talloc_convenience(mem_ctx,
1881                           lp_iconv_convenience(ldb_get_opaque(ctx, "loadparm")),
1882                           CH_UTF16, CH_UNIX,
1883                           new_password->data, new_password->length,
1884                           (void **)&new_pass, NULL, false)) {
1885
1886                         /* checks the password complexity */
1887                         if ((restrictions != 0)
1888                                 && ((pwdProperties
1889                                         & DOMAIN_PASSWORD_COMPLEX) != 0)
1890                                 && (!check_password_quality(new_pass))) {
1891                                 if (reject_reason) {
1892                                         *reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
1893                                 }
1894                                 return NT_STATUS_PASSWORD_RESTRICTION;
1895                         }
1896
1897                         /* compute the new lm hashes (for checking history - case insenitivly!) */
1898                         if (E_deshash(new_pass, local_lmNewHash.hash)) {
1899                                 lmNewHash = &local_lmNewHash;
1900                         }
1901                 }
1902         }
1903
1904         if ((restrictions != 0) && user_change) {
1905                 /* are all password changes disallowed? */
1906                 if ((pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) != 0) {
1907                         if (reject_reason) {
1908                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1909                         }
1910                         return NT_STATUS_PASSWORD_RESTRICTION;
1911                 }
1912
1913                 /* can this user change the password? */
1914                 if ((userAccountControl & UF_PASSWD_CANT_CHANGE) != 0) {
1915                         if (reject_reason) {
1916                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1917                         }
1918                         return NT_STATUS_PASSWORD_RESTRICTION;
1919                 }
1920
1921                 /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
1922                 if (pwdLastSet - minPwdAge > now_nt) {
1923                         if (reject_reason) {
1924                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1925                         }
1926                         return NT_STATUS_PASSWORD_RESTRICTION;
1927                 }
1928
1929                 /* check the immediately past password */
1930                 if (pwdHistoryLength > 0) {
1931                         if (lmNewHash && lmPwdHash && memcmp(lmNewHash->hash,
1932                                         lmPwdHash->hash, 16) == 0) {
1933                                 if (reject_reason) {
1934                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1935                                 }
1936                                 return NT_STATUS_PASSWORD_RESTRICTION;
1937                         }
1938                         if (ntNewHash && ntPwdHash && memcmp(ntNewHash->hash,
1939                                         ntPwdHash->hash, 16) == 0) {
1940                                 if (reject_reason) {
1941                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1942                                 }
1943                                 return NT_STATUS_PASSWORD_RESTRICTION;
1944                         }
1945                 }
1946
1947                 /* check the password history */
1948                 sambaLMPwdHistory_len = MIN(sambaLMPwdHistory_len,
1949                                                         pwdHistoryLength);
1950                 sambaNTPwdHistory_len = MIN(sambaNTPwdHistory_len,
1951                                                         pwdHistoryLength);
1952
1953                 for (i=0; lmNewHash && i<sambaLMPwdHistory_len;i++) {
1954                         if (memcmp(lmNewHash->hash, sambaLMPwdHistory[i].hash,
1955                                         16) == 0) {
1956                                 if (reject_reason) {
1957                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1958                                 }
1959                                 return NT_STATUS_PASSWORD_RESTRICTION;
1960                         }
1961                 }
1962                 for (i=0; ntNewHash && i<sambaNTPwdHistory_len;i++) {
1963                         if (memcmp(ntNewHash->hash, sambaNTPwdHistory[i].hash,
1964                                          16) == 0) {
1965                                 if (reject_reason) {
1966                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1967                                 }
1968                                 return NT_STATUS_PASSWORD_RESTRICTION;
1969                         }
1970                 }
1971         }
1972
1973 #define CHECK_RET(x) do { if (x != 0) return NT_STATUS_NO_MEMORY; } while(0)
1974
1975         /* the password is acceptable. Start forming the new fields */
1976         if (new_password != NULL) {
1977                 /* if we know the cleartext UTF16 password, then set it.
1978                  * Modules in ldb will set all the appropriate
1979                  * hashes */
1980                 CHECK_RET(ldb_msg_add_value(mod, "clearTextPassword", new_password, NULL));
1981         } else {
1982                 /* we don't have the cleartext, so set what we have of the
1983                  * hashes */
1984
1985                 if (lmNewHash) {
1986                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "dBCSPwd", lmNewHash));
1987                 }
1988
1989                 if (ntNewHash) {
1990                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "unicodePwd", ntNewHash));
1991                 }
1992         }
1993
1994         if (reject_reason) {
1995                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1996         }
1997         return NT_STATUS_OK;
1998 }
1999
2000
2001 /*
2002  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2003  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2004  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
2005  * gives some more informations if the changed failed.
2006  *
2007  * This wrapper function for "samdb_set_password" takes a SID as input rather
2008  * than a user DN.
2009  *
2010  * This call encapsulates a new LDB transaction for changing the password;
2011  * therefore the user hasn't to start a new one.
2012  *
2013  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2014  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2015  *   NT_STATUS_PASSWORD_RESTRICTION
2016  */
2017 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2018                                 const struct dom_sid *user_sid,
2019                                 const DATA_BLOB *new_password,
2020                                 struct samr_Password *lmNewHash, 
2021                                 struct samr_Password *ntNewHash,
2022                                 bool user_change,
2023                                 enum samPwdChangeReason *reject_reason,
2024                                 struct samr_DomInfo1 **_dominfo) 
2025 {
2026         NTSTATUS nt_status;
2027         struct ldb_dn *user_dn;
2028         struct ldb_message *msg;
2029         int ret;
2030
2031         ret = ldb_transaction_start(ldb);
2032         if (ret != LDB_SUCCESS) {
2033                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2034                 return NT_STATUS_TRANSACTION_ABORTED;
2035         }
2036
2037         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2038                                   "(&(objectSid=%s)(objectClass=user))", 
2039                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2040         if (!user_dn) {
2041                 ldb_transaction_cancel(ldb);
2042                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2043                           dom_sid_string(mem_ctx, user_sid)));
2044                 return NT_STATUS_NO_SUCH_USER;
2045         }
2046
2047         msg = ldb_msg_new(mem_ctx);
2048         if (msg == NULL) {
2049                 ldb_transaction_cancel(ldb);
2050                 talloc_free(user_dn);
2051                 return NT_STATUS_NO_MEMORY;
2052         }
2053
2054         msg->dn = ldb_dn_copy(msg, user_dn);
2055         if (!msg->dn) {
2056                 ldb_transaction_cancel(ldb);
2057                 talloc_free(user_dn);
2058                 talloc_free(msg);
2059                 return NT_STATUS_NO_MEMORY;
2060         }
2061
2062         nt_status = samdb_set_password(ldb, mem_ctx,
2063                                        user_dn, NULL,
2064                                        msg, new_password,
2065                                        lmNewHash, ntNewHash,
2066                                        user_change,
2067                                        reject_reason, _dominfo);
2068         if (!NT_STATUS_IS_OK(nt_status)) {
2069                 ldb_transaction_cancel(ldb);
2070                 talloc_free(user_dn);
2071                 talloc_free(msg);
2072                 return nt_status;
2073         }
2074
2075         /* modify the samdb record */
2076         ret = dsdb_replace(ldb, msg, 0);
2077         if (ret != LDB_SUCCESS) {
2078                 ldb_transaction_cancel(ldb);
2079                 talloc_free(user_dn);
2080                 talloc_free(msg);
2081                 return NT_STATUS_ACCESS_DENIED;
2082         }
2083
2084         talloc_free(msg);
2085
2086         ret = ldb_transaction_commit(ldb);
2087         if (ret != LDB_SUCCESS) {
2088                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2089                          ldb_dn_get_linearized(user_dn),
2090                          ldb_errstring(ldb)));
2091                 talloc_free(user_dn);
2092                 return NT_STATUS_TRANSACTION_ABORTED;
2093         }
2094
2095         talloc_free(user_dn);
2096         return NT_STATUS_OK;
2097 }
2098
2099
2100 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2101                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2102 {
2103         struct ldb_message *msg;
2104         struct ldb_dn *basedn;
2105         char *sidstr;
2106         int ret;
2107
2108         sidstr = dom_sid_string(mem_ctx, sid);
2109         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2110
2111         /* We might have to create a ForeignSecurityPrincipal, even if this user
2112          * is in our own domain */
2113
2114         msg = ldb_msg_new(sidstr);
2115         if (msg == NULL) {
2116                 talloc_free(sidstr);
2117                 return NT_STATUS_NO_MEMORY;
2118         }
2119
2120         ret = dsdb_wellknown_dn(sam_ctx, sidstr, samdb_base_dn(sam_ctx),
2121                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2122                                 &basedn);
2123         if (ret != LDB_SUCCESS) {
2124                 DEBUG(0, ("Failed to find DN for "
2125                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2126                 talloc_free(sidstr);
2127                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2128         }
2129
2130         /* add core elements to the ldb_message for the alias */
2131         msg->dn = basedn;
2132         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2133                 talloc_free(sidstr);
2134                 return NT_STATUS_NO_MEMORY;
2135         }
2136
2137         samdb_msg_add_string(sam_ctx, msg, msg,
2138                              "objectClass",
2139                              "foreignSecurityPrincipal");
2140
2141         /* create the alias */
2142         ret = ldb_add(sam_ctx, msg);
2143         if (ret != LDB_SUCCESS) {
2144                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2145                          "record %s: %s\n", 
2146                          ldb_dn_get_linearized(msg->dn),
2147                          ldb_errstring(sam_ctx)));
2148                 talloc_free(sidstr);
2149                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2150         }
2151
2152         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2153         talloc_free(sidstr);
2154
2155         return NT_STATUS_OK;
2156 }
2157
2158
2159 /*
2160   Find the DN of a domain, assuming it to be a dotted.dns name
2161 */
2162
2163 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2164 {
2165         unsigned int i;
2166         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2167         const char *binary_encoded;
2168         const char **split_realm;
2169         struct ldb_dn *dn;
2170
2171         if (!tmp_ctx) {
2172                 return NULL;
2173         }
2174
2175         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2176         if (!split_realm) {
2177                 talloc_free(tmp_ctx);
2178                 return NULL;
2179         }
2180         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2181         for (i=0; split_realm[i]; i++) {
2182                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2183                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2184                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2185                                   binary_encoded, ldb_dn_get_linearized(dn)));
2186                         talloc_free(tmp_ctx);
2187                         return NULL;
2188                 }
2189         }
2190         if (!ldb_dn_validate(dn)) {
2191                 DEBUG(2, ("Failed to validated DN %s\n",
2192                           ldb_dn_get_linearized(dn)));
2193                 talloc_free(tmp_ctx);
2194                 return NULL;
2195         }
2196         talloc_free(tmp_ctx);
2197         return dn;
2198 }
2199
2200 /*
2201   Find the DN of a domain, be it the netbios or DNS name 
2202 */
2203 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2204                                   const char *domain_name) 
2205 {
2206         const char * const domain_ref_attrs[] = {
2207                 "ncName", NULL
2208         };
2209         const char * const domain_ref2_attrs[] = {
2210                 NULL
2211         };
2212         struct ldb_result *res_domain_ref;
2213         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2214         /* find the domain's DN */
2215         int ret_domain = ldb_search(ldb, mem_ctx,
2216                                             &res_domain_ref, 
2217                                             samdb_partitions_dn(ldb, mem_ctx), 
2218                                             LDB_SCOPE_ONELEVEL, 
2219                                             domain_ref_attrs,
2220                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2221                                             escaped_domain);
2222         if (ret_domain != 0) {
2223                 return NULL;
2224         }
2225
2226         if (res_domain_ref->count == 0) {
2227                 ret_domain = ldb_search(ldb, mem_ctx,
2228                                                 &res_domain_ref, 
2229                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2230                                                 LDB_SCOPE_BASE,
2231                                                 domain_ref2_attrs,
2232                                                 "(objectclass=domain)");
2233                 if (ret_domain != 0) {
2234                         return NULL;
2235                 }
2236
2237                 if (res_domain_ref->count == 1) {
2238                         return res_domain_ref->msgs[0]->dn;
2239                 }
2240                 return NULL;
2241         }
2242
2243         if (res_domain_ref->count > 1) {
2244                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2245                          ret_domain, domain_name));
2246                 return NULL;
2247         }
2248
2249         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2250
2251 }
2252
2253
2254 /*
2255   use a GUID to find a DN
2256  */
2257 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2258                          TALLOC_CTX *mem_ctx,
2259                          const struct GUID *guid, struct ldb_dn **dn)
2260 {
2261         int ret;
2262         struct ldb_result *res;
2263         const char *attrs[] = { NULL };
2264         char *guid_str = GUID_string(mem_ctx, guid);
2265
2266         if (!guid_str) {
2267                 return LDB_ERR_OPERATIONS_ERROR;
2268         }
2269
2270         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2271                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2272                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2273                           DSDB_SEARCH_ONE_ONLY,
2274                           "objectGUID=%s", guid_str);
2275         talloc_free(guid_str);
2276         if (ret != LDB_SUCCESS) {
2277                 return ret;
2278         }
2279
2280         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2281         talloc_free(res);
2282
2283         return LDB_SUCCESS;
2284 }
2285
2286 /*
2287   use a DN to find a GUID with a given attribute name
2288  */
2289 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2290                               struct ldb_dn *dn, const char *attribute,
2291                               struct GUID *guid)
2292 {
2293         int ret;
2294         struct ldb_result *res;
2295         const char *attrs[2];
2296         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2297
2298         attrs[0] = attribute;
2299         attrs[1] = NULL;
2300
2301         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2302         if (ret != LDB_SUCCESS) {
2303                 talloc_free(tmp_ctx);
2304                 return ret;
2305         }
2306         if (res->count < 1) {
2307                 talloc_free(tmp_ctx);
2308                 return LDB_ERR_NO_SUCH_OBJECT;
2309         }
2310         *guid = samdb_result_guid(res->msgs[0], attribute);
2311         talloc_free(tmp_ctx);
2312         return LDB_SUCCESS;
2313 }
2314
2315 /*
2316   use a DN to find a GUID
2317  */
2318 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2319                          struct ldb_dn *dn, struct GUID *guid)
2320 {
2321         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2322 }
2323
2324
2325
2326 /*
2327  adds the given GUID to the given ldb_message. This value is added
2328  for the given attr_name (may be either "objectGUID" or "parentGUID").
2329  */
2330 int dsdb_msg_add_guid(struct ldb_message *msg,
2331                 struct GUID *guid,
2332                 const char *attr_name)
2333 {
2334         int ret;
2335         struct ldb_val v;
2336         NTSTATUS status;
2337         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2338
2339         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2340         if (!NT_STATUS_IS_OK(status)) {
2341                 ret = LDB_ERR_OPERATIONS_ERROR;
2342                 goto done;
2343         }
2344
2345         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2346         if (ret != LDB_SUCCESS) {
2347                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2348                                          attr_name));
2349                 goto done;
2350         }
2351
2352         ret = LDB_SUCCESS;
2353
2354 done:
2355         talloc_free(tmp_ctx);
2356         return ret;
2357
2358 }
2359
2360
2361 /*
2362   use a DN to find a SID
2363  */
2364 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2365                         struct ldb_dn *dn, struct dom_sid *sid)
2366 {
2367         int ret;
2368         struct ldb_result *res;
2369         const char *attrs[] = { "objectSID", NULL };
2370         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2371         struct dom_sid *s;
2372
2373         ZERO_STRUCTP(sid);
2374
2375         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2376         if (ret != LDB_SUCCESS) {
2377                 talloc_free(tmp_ctx);
2378                 return ret;
2379         }
2380         if (res->count < 1) {
2381                 talloc_free(tmp_ctx);
2382                 return LDB_ERR_NO_SUCH_OBJECT;
2383         }
2384         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2385         if (s == NULL) {
2386                 talloc_free(tmp_ctx);
2387                 return LDB_ERR_NO_SUCH_OBJECT;
2388         }
2389         *sid = *s;
2390         talloc_free(tmp_ctx);
2391         return LDB_SUCCESS;
2392 }
2393
2394
2395
2396 /*
2397   load a repsFromTo blob list for a given partition GUID
2398   attr must be "repsFrom" or "repsTo"
2399  */
2400 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2401                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2402 {
2403         const char *attrs[] = { attr, NULL };
2404         struct ldb_result *res = NULL;
2405         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2406         unsigned int i;
2407         struct ldb_message_element *el;
2408
2409         *r = NULL;
2410         *count = 0;
2411
2412         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2413             res->count < 1) {
2414                 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2415                 talloc_free(tmp_ctx);
2416                 return WERR_DS_DRA_INTERNAL_ERROR;
2417         }
2418
2419         el = ldb_msg_find_element(res->msgs[0], attr);
2420         if (el == NULL) {
2421                 /* it's OK to be empty */
2422                 talloc_free(tmp_ctx);
2423                 return WERR_OK;
2424         }
2425
2426         *count = el->num_values;
2427         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2428         if (*r == NULL) {
2429                 talloc_free(tmp_ctx);
2430                 return WERR_DS_DRA_INTERNAL_ERROR;
2431         }
2432
2433         for (i=0; i<(*count); i++) {
2434                 enum ndr_err_code ndr_err;
2435                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2436                                                mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2437                                                &(*r)[i], 
2438                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2439                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2440                         talloc_free(tmp_ctx);
2441                         return WERR_DS_DRA_INTERNAL_ERROR;
2442                 }
2443         }
2444
2445         talloc_free(tmp_ctx);
2446         
2447         return WERR_OK;
2448 }
2449
2450 /*
2451   save the repsFromTo blob list for a given partition GUID
2452   attr must be "repsFrom" or "repsTo"
2453  */
2454 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2455                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2456 {
2457         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2458         struct ldb_message *msg;
2459         struct ldb_message_element *el;
2460         unsigned int i;
2461
2462         msg = ldb_msg_new(tmp_ctx);
2463         msg->dn = dn;
2464         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2465                 goto failed;
2466         }
2467
2468         el->values = talloc_array(msg, struct ldb_val, count);
2469         if (!el->values) {
2470                 goto failed;
2471         }
2472
2473         for (i=0; i<count; i++) {
2474                 struct ldb_val v;
2475                 enum ndr_err_code ndr_err;
2476
2477                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2478                                                &r[i], 
2479                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2480                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2481                         goto failed;
2482                 }
2483
2484                 el->num_values++;
2485                 el->values[i] = v;
2486         }
2487
2488         if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2489                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2490                 goto failed;
2491         }
2492
2493         talloc_free(tmp_ctx);
2494         
2495         return WERR_OK;
2496
2497 failed:
2498         talloc_free(tmp_ctx);
2499         return WERR_DS_DRA_INTERNAL_ERROR;
2500 }
2501
2502
2503 /*
2504   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2505   object for a partition
2506  */
2507 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2508                                 uint64_t *uSN, uint64_t *urgent_uSN)
2509 {
2510         struct ldb_request *req;
2511         int ret;
2512         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2513         struct dsdb_control_current_partition *p_ctrl;
2514         struct ldb_result *res;
2515
2516         res = talloc_zero(tmp_ctx, struct ldb_result);
2517         if (!res) {
2518                 talloc_free(tmp_ctx);
2519                 return LDB_ERR_OPERATIONS_ERROR;
2520         }
2521
2522         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2523                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2524                                    LDB_SCOPE_BASE,
2525                                    NULL, NULL,
2526                                    NULL,
2527                                    res, ldb_search_default_callback,
2528                                    NULL);
2529         if (ret != LDB_SUCCESS) {
2530                 talloc_free(tmp_ctx);
2531                 return ret;
2532         }
2533
2534         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2535         if (p_ctrl == NULL) {
2536                 talloc_free(res);
2537                 return LDB_ERR_OPERATIONS_ERROR;
2538         }
2539         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2540         p_ctrl->dn = dn;
2541         
2542
2543         ret = ldb_request_add_control(req,
2544                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2545                                       false, p_ctrl);
2546         if (ret != LDB_SUCCESS) {
2547                 talloc_free(tmp_ctx);
2548                 return ret;
2549         }
2550         
2551         /* Run the new request */
2552         ret = ldb_request(ldb, req);
2553         
2554         if (ret == LDB_SUCCESS) {
2555                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2556         }
2557
2558         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2559                 /* it hasn't been created yet, which means
2560                    an implicit value of zero */
2561                 *uSN = 0;
2562                 talloc_free(tmp_ctx);
2563                 return LDB_SUCCESS;
2564         }
2565
2566         if (ret != LDB_SUCCESS) {
2567                 talloc_free(tmp_ctx);
2568                 return ret;
2569         }
2570
2571         if (res->count < 1) {
2572                 *uSN = 0;
2573                 if (urgent_uSN) {
2574                         *urgent_uSN = 0;
2575                 }
2576         } else {
2577                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2578                 if (urgent_uSN) {
2579                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2580                 }
2581         }
2582
2583         talloc_free(tmp_ctx);
2584
2585         return LDB_SUCCESS;     
2586 }
2587
2588 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2589                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2590 {
2591         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2592 }
2593
2594 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2595                                     const struct drsuapi_DsReplicaCursor *c2)
2596 {
2597         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2598 }
2599
2600 /*
2601   see if we are a RODC
2602 */
2603 bool samdb_rodc(struct ldb_context *sam_ctx)
2604 {
2605         TALLOC_CTX *tmp_ctx;
2606         const char *obj_category;
2607         struct ldb_dn *obj_category_dn;
2608         const struct ldb_val *obj_category_dn_rdn_val;
2609
2610         tmp_ctx = talloc_new(sam_ctx);
2611         if (tmp_ctx == NULL) {
2612                 DEBUG(1,("samdb_rodc: Failed to talloc new context.\n"));
2613                 goto failed;
2614         }
2615
2616         obj_category = samdb_ntds_object_category(tmp_ctx, sam_ctx);
2617         if (!obj_category) {
2618                 DEBUG(1,("samdb_rodc: Failed to get object category.\n"));
2619                 goto failed;
2620         }
2621
2622         obj_category_dn = ldb_dn_new(tmp_ctx, sam_ctx, obj_category);
2623         if (!obj_category_dn) {
2624                 DEBUG(1,("samdb_rodc: Failed to create object category dn.\n"));
2625                 goto failed;
2626         }
2627
2628         obj_category_dn_rdn_val = ldb_dn_get_rdn_val(obj_category_dn);
2629         if (!obj_category_dn_rdn_val) {
2630                 DEBUG(1, ("samdb_rodc: Failed to get object category dn rdn value.\n"));
2631                 goto failed;
2632         }
2633
2634         if (strequal((const char*)obj_category_dn_rdn_val->data, "NTDS-DSA-RO")) {
2635                 talloc_free(tmp_ctx);
2636                 return true;
2637         }
2638
2639 failed:
2640         talloc_free(tmp_ctx);
2641         return false;
2642 }
2643
2644 /*
2645   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2646
2647   flags are DS_NTDS_OPTION_*
2648 */
2649 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2650 {
2651         TALLOC_CTX *tmp_ctx;
2652         const char *attrs[] = { "options", NULL };
2653         int ret;
2654         struct ldb_result *res;
2655
2656         tmp_ctx = talloc_new(ldb);
2657         if (tmp_ctx == NULL) {
2658                 goto failed;
2659         }
2660
2661         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2662         if (ret) {
2663                 goto failed;
2664         }
2665
2666         if (res->count != 1) {
2667                 goto failed;
2668         }
2669
2670         *options = samdb_result_uint(res->msgs[0], "options", 0);
2671
2672         talloc_free(tmp_ctx);
2673
2674         return LDB_SUCCESS;
2675
2676 failed:
2677         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
2678         talloc_free(tmp_ctx);
2679         return LDB_ERR_NO_SUCH_OBJECT;
2680 }
2681
2682 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
2683 {
2684         const char *attrs[] = { "objectCategory", NULL };
2685         int ret;
2686         struct ldb_result *res;
2687
2688         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2689         if (ret) {
2690                 goto failed;
2691         }
2692
2693         if (res->count != 1) {
2694                 goto failed;
2695         }
2696
2697         return samdb_result_string(res->msgs[0], "objectCategory", NULL);
2698
2699 failed:
2700         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
2701         return NULL;
2702 }
2703
2704 /*
2705  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
2706  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
2707  */
2708 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
2709 {
2710         char **tokens, *ret;
2711         size_t i;
2712
2713         tokens = str_list_make(mem_ctx, cn, " -_");
2714         if (tokens == NULL)
2715                 return NULL;
2716
2717         /* "tolower()" and "toupper()" should also work properly on 0x00 */
2718         tokens[0][0] = tolower(tokens[0][0]);
2719         for (i = 1; i < str_list_length((const char **)tokens); i++)
2720                 tokens[i][0] = toupper(tokens[i][0]);
2721
2722         ret = talloc_strdup(mem_ctx, tokens[0]);
2723         for (i = 1; i < str_list_length((const char **)tokens); i++)
2724                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
2725
2726         talloc_free(tokens);
2727
2728         return ret;
2729 }
2730
2731 /*
2732   return domain functional level
2733   returns DS_DOMAIN_FUNCTION_*
2734  */
2735 int dsdb_functional_level(struct ldb_context *ldb)
2736 {
2737         int *domainFunctionality =
2738                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
2739         if (!domainFunctionality) {
2740                 DEBUG(0,(__location__ ": WARNING: domainFunctionality not setup\n"));
2741                 return DS_DOMAIN_FUNCTION_2000;
2742         }
2743         return *domainFunctionality;
2744 }
2745
2746 /*
2747   set a GUID in an extended DN structure
2748  */
2749 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
2750 {
2751         struct ldb_val v;
2752         NTSTATUS status;
2753         int ret;
2754
2755         status = GUID_to_ndr_blob(guid, dn, &v);
2756         if (!NT_STATUS_IS_OK(status)) {
2757                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
2758         }
2759
2760         ret = ldb_dn_set_extended_component(dn, component_name, &v);
2761         data_blob_free(&v);
2762         return ret;
2763 }
2764
2765 /*
2766   return a GUID from a extended DN structure
2767  */
2768 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
2769 {
2770         const struct ldb_val *v;
2771
2772         v = ldb_dn_get_extended_component(dn, component_name);
2773         if (v == NULL) {
2774                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2775         }
2776
2777         return GUID_from_ndr_blob(v, guid);
2778 }
2779
2780 /*
2781   return a uint64_t from a extended DN structure
2782  */
2783 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
2784 {
2785         const struct ldb_val *v;
2786         char *s;
2787
2788         v = ldb_dn_get_extended_component(dn, component_name);
2789         if (v == NULL) {
2790                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2791         }
2792         s = talloc_strndup(dn, (const char *)v->data, v->length);
2793         NT_STATUS_HAVE_NO_MEMORY(s);
2794
2795         *val = strtoull(s, NULL, 0);
2796
2797         talloc_free(s);
2798         return NT_STATUS_OK;
2799 }
2800
2801 /*
2802   return a NTTIME from a extended DN structure
2803  */
2804 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
2805 {
2806         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
2807 }
2808
2809 /*
2810   return a uint32_t from a extended DN structure
2811  */
2812 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
2813 {
2814         const struct ldb_val *v;
2815         char *s;
2816
2817         v = ldb_dn_get_extended_component(dn, component_name);
2818         if (v == NULL) {
2819                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2820         }
2821
2822         s = talloc_strndup(dn, (const char *)v->data, v->length);
2823         NT_STATUS_HAVE_NO_MEMORY(s);
2824
2825         *val = strtoul(s, NULL, 0);
2826
2827         talloc_free(s);
2828         return NT_STATUS_OK;
2829 }
2830
2831 /*
2832   return RMD_FLAGS directly from a ldb_dn
2833   returns 0 if not found
2834  */
2835 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
2836 {
2837         const struct ldb_val *v;
2838         char buf[32];
2839         v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
2840         if (!v || v->length > sizeof(buf)-1) return 0;
2841         strncpy(buf, (const char *)v->data, v->length);
2842         buf[v->length] = 0;
2843         return strtoul(buf, NULL, 10);
2844 }
2845
2846 /*
2847   return RMD_FLAGS directly from a ldb_val for a DN
2848   returns 0 if RMD_FLAGS is not found
2849  */
2850 uint32_t dsdb_dn_val_rmd_flags(struct ldb_val *val)
2851 {
2852         const char *p;
2853         uint32_t flags;
2854         char *end;
2855
2856         if (val->length < 13) {
2857                 return 0;
2858         }
2859         p = memmem(val->data, val->length-2, "<RMD_FLAGS=", 11);
2860         if (!p) {
2861                 return 0;
2862         }
2863         flags = strtoul(p+11, &end, 10);
2864         if (!end || *end != '>') {
2865                 /* it must end in a > */
2866                 return 0;
2867         }
2868         return flags;
2869 }
2870
2871 /*
2872   return true if a ldb_val containing a DN in storage form is deleted
2873  */
2874 bool dsdb_dn_is_deleted_val(struct ldb_val *val)
2875 {
2876         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
2877 }
2878
2879 /*
2880   return true if a ldb_val containing a DN in storage form is
2881   in the upgraded w2k3 linked attribute format
2882  */
2883 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
2884 {
2885         return memmem(val->data, val->length, "<RMD_ADDTIME=", 13) != NULL;
2886 }
2887
2888 /*
2889   return a DN for a wellknown GUID
2890  */
2891 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
2892                       struct ldb_dn *nc_root, const char *wk_guid,
2893                       struct ldb_dn **wkguid_dn)
2894 {
2895         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2896         const char *attrs[] = { NULL };
2897         int ret;
2898         struct ldb_dn *dn;
2899         struct ldb_result *res;
2900
2901         /* construct the magic WKGUID DN */
2902         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
2903                             wk_guid, ldb_dn_get_linearized(nc_root));
2904         if (!wkguid_dn) {
2905                 talloc_free(tmp_ctx);
2906                 return LDB_ERR_OPERATIONS_ERROR;
2907         }
2908
2909         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2910         if (ret != LDB_SUCCESS) {
2911                 talloc_free(tmp_ctx);
2912                 return ret;
2913         }
2914
2915         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
2916         talloc_free(tmp_ctx);
2917         return LDB_SUCCESS;
2918 }
2919
2920
2921 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
2922 {
2923         return ldb_dn_compare(*dn1, *dn2);
2924 }
2925
2926 /*
2927   find a NC root given a DN within the NC
2928  */
2929 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2930                       struct ldb_dn **nc_root)
2931 {
2932         const char *root_attrs[] = { "namingContexts", NULL };
2933         TALLOC_CTX *tmp_ctx;
2934         int ret;
2935         struct ldb_message_element *el;
2936         struct ldb_result *root_res;
2937         int i;
2938         struct ldb_dn **nc_dns;
2939
2940         tmp_ctx = talloc_new(samdb);
2941         if (tmp_ctx == NULL) {
2942                 return LDB_ERR_OPERATIONS_ERROR;
2943         }
2944
2945         ret = ldb_search(samdb, tmp_ctx, &root_res,
2946                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
2947         if (ret) {
2948                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
2949                 talloc_free(tmp_ctx);
2950                 return ret;
2951        }
2952
2953        el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
2954        if (!el) {
2955                DEBUG(1,("Finding namingContexts element in root_res failed: %s\n",
2956                         ldb_errstring(samdb)));
2957                talloc_free(tmp_ctx);
2958                return LDB_ERR_NO_SUCH_ATTRIBUTE;
2959        }
2960
2961        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
2962        if (!nc_dns) {
2963                talloc_free(tmp_ctx);
2964                return LDB_ERR_OPERATIONS_ERROR;
2965        }
2966
2967        for (i=0; i<el->num_values; i++) {
2968                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
2969                if (nc_dns[i] == NULL) {
2970                        talloc_free(tmp_ctx);
2971                        return LDB_ERR_OPERATIONS_ERROR;
2972                }
2973        }
2974
2975        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
2976
2977        for (i=0; i<el->num_values; i++) {
2978                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
2979                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
2980                        talloc_free(tmp_ctx);
2981                        return LDB_SUCCESS;
2982                }
2983        }
2984
2985        talloc_free(tmp_ctx);
2986        return LDB_ERR_NO_SUCH_OBJECT;
2987 }
2988
2989
2990 /*
2991   find the deleted objects DN for any object, by looking for the NC
2992   root, then looking up the wellknown GUID
2993  */
2994 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
2995                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
2996                                 struct ldb_dn **do_dn)
2997 {
2998         struct ldb_dn *nc_root;
2999         int ret;
3000
3001         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3002         if (ret != LDB_SUCCESS) {
3003                 return ret;
3004         }
3005
3006         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3007         talloc_free(nc_root);
3008         return ret;
3009 }
3010
3011 /*
3012   return the tombstoneLifetime, in days
3013  */
3014 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3015 {
3016         struct ldb_dn *dn;
3017         dn = samdb_config_dn(ldb);
3018         if (!dn) {
3019                 return LDB_ERR_NO_SUCH_OBJECT;
3020         }
3021         dn = ldb_dn_copy(ldb, dn);
3022         if (!dn) {
3023                 return LDB_ERR_OPERATIONS_ERROR;
3024         }
3025         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3026          be a wellknown GUID for this */
3027         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3028                 talloc_free(dn);
3029                 return LDB_ERR_OPERATIONS_ERROR;
3030         }
3031
3032         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3033         talloc_free(dn);
3034         return LDB_SUCCESS;
3035 }
3036
3037 /*
3038   compare a ldb_val to a string case insensitively
3039  */
3040 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3041 {
3042         size_t len = strlen(s);
3043         int ret;
3044         if (len > v->length) return 1;
3045         ret = strncasecmp(s, (const char *)v->data, v->length);
3046         if (ret != 0) return ret;
3047         if (v->length > len && v->data[len] != 0) {
3048                 return -1;
3049         }
3050         return 0;
3051 }
3052
3053
3054 /*
3055   load the UDV for a partition in v2 format
3056   The list is returned sorted, and with our local cursor added
3057  */
3058 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3059                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3060 {
3061         static const char *attrs[] = { "replUpToDateVector", NULL };
3062         struct ldb_result *r;
3063         const struct ldb_val *ouv_value;
3064         unsigned int i;
3065         int ret;
3066         uint64_t highest_usn;
3067         const struct GUID *our_invocation_id;
3068         struct timeval now = timeval_current();
3069
3070         ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3071         if (ret != LDB_SUCCESS) {
3072                 return ret;
3073         }
3074
3075         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3076         if (ouv_value) {
3077                 enum ndr_err_code ndr_err;
3078                 struct replUpToDateVectorBlob ouv;
3079
3080                 ndr_err = ndr_pull_struct_blob(ouv_value, r,
3081                                                lp_iconv_convenience(ldb_get_opaque(samdb, "loadparm")), &ouv,
3082                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3083                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3084                         talloc_free(r);
3085                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3086                 }
3087                 if (ouv.version != 2) {
3088                         /* we always store as version 2, and
3089                          * replUpToDateVector is not replicated
3090                          */
3091                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3092                 }
3093
3094                 *count = ouv.ctr.ctr2.count;
3095                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3096         } else {
3097                 *count = 0;
3098                 *cursors = NULL;
3099         }
3100
3101         talloc_free(r);
3102
3103         our_invocation_id = samdb_ntds_invocation_id(samdb);
3104         if (!our_invocation_id) {
3105                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3106                 talloc_free(*cursors);
3107                 return LDB_ERR_OPERATIONS_ERROR;
3108         }
3109
3110         ret = dsdb_load_partition_usn(samdb, dn, &highest_usn, NULL);
3111         if (ret != LDB_SUCCESS) {
3112                 /* nothing to add - this can happen after a vampire */
3113                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3114                 return LDB_SUCCESS;
3115         }
3116
3117         for (i=0; i<*count; i++) {
3118                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3119                         (*cursors)[i].highest_usn = highest_usn;
3120                         (*cursors)[i].last_sync_success = timeval_to_nttime(&now);
3121                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3122                         return LDB_SUCCESS;
3123                 }
3124         }
3125
3126         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3127         if (! *cursors) {
3128                 return LDB_ERR_OPERATIONS_ERROR;
3129         }
3130
3131         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3132         (*cursors)[*count].highest_usn = highest_usn;
3133         (*cursors)[*count].last_sync_success = timeval_to_nttime(&now);
3134         (*count)++;
3135
3136         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3137
3138         return LDB_SUCCESS;
3139 }
3140
3141 /*
3142   load the UDV for a partition in version 1 format
3143   The list is returned sorted, and with our local cursor added
3144  */
3145 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3146                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3147 {
3148         struct drsuapi_DsReplicaCursor2 *v2;
3149         unsigned int i;
3150         int ret;
3151
3152         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3153         if (ret != LDB_SUCCESS) {
3154                 return ret;
3155         }
3156
3157         if (*count == 0) {
3158                 talloc_free(v2);
3159                 *cursors = NULL;
3160                 return LDB_SUCCESS;
3161         }
3162
3163         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3164         if (*cursors == NULL) {
3165                 talloc_free(v2);
3166                 return LDB_ERR_OPERATIONS_ERROR;
3167         }
3168
3169         for (i=0; i<*count; i++) {
3170                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3171                 (*cursors)[i].highest_usn = v2[i].highest_usn;
3172         }
3173         talloc_free(v2);
3174         return LDB_SUCCESS;
3175 }
3176
3177 /*
3178   add a set of controls to a ldb_request structure based on a set of
3179   flags. See util.h for a list of available flags
3180  */
3181 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3182 {
3183         int ret;
3184         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3185                 struct ldb_search_options_control *options;
3186                 /* Using the phantom root control allows us to search all partitions */
3187                 options = talloc(req, struct ldb_search_options_control);
3188                 if (options == NULL) {
3189                         return LDB_ERR_OPERATIONS_ERROR;
3190                 }
3191                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3192
3193                 ret = ldb_request_add_control(req,
3194                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
3195                                               true, options);
3196                 if (ret != LDB_SUCCESS) {
3197                         return ret;
3198                 }
3199         }
3200
3201         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3202                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3203                 if (ret != LDB_SUCCESS) {
3204                         return ret;
3205                 }
3206         }
3207
3208         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3209                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, true, NULL);
3210                 if (ret != LDB_SUCCESS) {
3211                         return ret;
3212                 }
3213         }
3214
3215         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3216                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3217                 if (!extended_ctrl) {
3218                         return LDB_ERR_OPERATIONS_ERROR;
3219                 }
3220                 extended_ctrl->type = 1;
3221
3222                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3223                 if (ret != LDB_SUCCESS) {
3224                         return ret;
3225                 }
3226         }
3227
3228         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3229                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3230                 if (ret != LDB_SUCCESS) {
3231                         return ret;
3232                 }
3233         }
3234
3235         if (dsdb_flags & DSDB_MODIFY_RELAX) {
3236                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3237                 if (ret != LDB_SUCCESS) {
3238                         return ret;
3239                 }
3240         }
3241
3242         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3243                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3244                 if (ret != LDB_SUCCESS) {
3245                         return ret;
3246                 }
3247         }
3248
3249         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3250                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3251                 if (ret != LDB_SUCCESS) {
3252                         return ret;
3253                 }
3254         }
3255
3256         return LDB_SUCCESS;
3257 }
3258
3259 /*
3260   a modify with a set of controls
3261 */
3262 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3263                 uint32_t dsdb_flags)
3264 {
3265         struct ldb_request *req;
3266         int ret;
3267
3268         ret = ldb_build_mod_req(&req, ldb, ldb,
3269                                 message,
3270                                 NULL,
3271                                 NULL,
3272                                 ldb_op_default_callback,
3273                                 NULL);
3274
3275         if (ret != LDB_SUCCESS) return ret;
3276
3277         ret = dsdb_request_add_controls(req, dsdb_flags);
3278         if (ret != LDB_SUCCESS) {
3279                 talloc_free(req);
3280                 return ret;
3281         }
3282
3283         ret = dsdb_autotransaction_request(ldb, req);
3284
3285         talloc_free(req);
3286         return ret;
3287 }
3288
3289 /*
3290   like dsdb_modify() but set all the element flags to
3291   LDB_FLAG_MOD_REPLACE
3292  */
3293 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3294 {
3295         unsigned int i;
3296
3297         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3298         for (i=0;i<msg->num_elements;i++) {
3299                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3300         }
3301
3302         return dsdb_modify(ldb, msg, dsdb_flags);
3303 }
3304
3305
3306 /*
3307   search for attrs on one DN, allowing for dsdb_flags controls
3308  */
3309 int dsdb_search_dn(struct ldb_context *ldb,
3310                    TALLOC_CTX *mem_ctx,
3311                    struct ldb_result **_res,
3312                    struct ldb_dn *basedn,
3313                    const char * const *attrs,
3314                    uint32_t dsdb_flags)
3315 {
3316         int ret;
3317         struct ldb_request *req;
3318         struct ldb_result *res;
3319
3320         res = talloc_zero(mem_ctx, struct ldb_result);
3321         if (!res) {
3322                 return LDB_ERR_OPERATIONS_ERROR;
3323         }
3324
3325         ret = ldb_build_search_req(&req, ldb, res,
3326                                    basedn,
3327                                    LDB_SCOPE_BASE,
3328                                    NULL,
3329                                    attrs,
3330                                    NULL,
3331                                    res,
3332                                    ldb_search_default_callback,
3333                                    NULL);
3334         if (ret != LDB_SUCCESS) {
3335                 talloc_free(res);
3336                 return ret;
3337         }
3338
3339         ret = dsdb_request_add_controls(req, dsdb_flags);
3340         if (ret != LDB_SUCCESS) {
3341                 talloc_free(res);
3342                 return ret;
3343         }
3344
3345         ret = ldb_request(ldb, req);
3346         if (ret == LDB_SUCCESS) {
3347                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3348         }
3349
3350         talloc_free(req);
3351         if (ret != LDB_SUCCESS) {
3352                 talloc_free(res);
3353                 return ret;
3354         }
3355
3356         *_res = res;
3357         return LDB_SUCCESS;
3358 }
3359
3360 /*
3361   general search with dsdb_flags for controls
3362  */
3363 int dsdb_search(struct ldb_context *ldb,
3364                 TALLOC_CTX *mem_ctx,
3365                 struct ldb_result **_res,
3366                 struct ldb_dn *basedn,
3367                 enum ldb_scope scope,
3368                 const char * const *attrs,
3369                 uint32_t dsdb_flags,
3370                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3371 {
3372         int ret;
3373         struct ldb_request *req;
3374         struct ldb_result *res;
3375         va_list ap;
3376         char *expression = NULL;
3377         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3378
3379         res = talloc_zero(tmp_ctx, struct ldb_result);
3380         if (!res) {
3381                 talloc_free(tmp_ctx);
3382                 return LDB_ERR_OPERATIONS_ERROR;
3383         }
3384
3385         if (exp_fmt) {
3386                 va_start(ap, exp_fmt);
3387                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3388                 va_end(ap);
3389
3390                 if (!expression) {
3391                         talloc_free(tmp_ctx);
3392                         return LDB_ERR_OPERATIONS_ERROR;
3393                 }
3394         }
3395
3396         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3397                                    basedn,
3398                                    scope,
3399                                    expression,
3400                                    attrs,
3401                                    NULL,
3402                                    res,
3403                                    ldb_search_default_callback,
3404                                    NULL);
3405         if (ret != LDB_SUCCESS) {
3406                 talloc_free(tmp_ctx);
3407                 return ret;
3408         }
3409
3410         ret = dsdb_request_add_controls(req, dsdb_flags);
3411         if (ret != LDB_SUCCESS) {
3412                 talloc_free(tmp_ctx);
3413                 return ret;
3414         }
3415
3416         ret = ldb_request(ldb, req);
3417         if (ret == LDB_SUCCESS) {
3418                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3419         }
3420
3421         if (ret != LDB_SUCCESS) {
3422                 talloc_free(tmp_ctx);
3423                 return ret;
3424         }
3425
3426         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
3427                 if (res->count == 0) {
3428                         talloc_free(tmp_ctx);
3429                         return LDB_ERR_NO_SUCH_OBJECT;
3430                 }
3431                 if (res->count != 1) {
3432                         talloc_free(tmp_ctx);
3433                         return LDB_ERR_CONSTRAINT_VIOLATION;
3434                 }
3435         }
3436
3437         *_res = talloc_steal(mem_ctx, res);
3438         talloc_free(tmp_ctx);
3439
3440         return LDB_SUCCESS;
3441 }
3442
3443
3444 /*
3445   general search with dsdb_flags for controls
3446   returns exactly 1 record or an error
3447  */
3448 int dsdb_search_one(struct ldb_context *ldb,
3449                     TALLOC_CTX *mem_ctx,
3450                     struct ldb_message **msg,
3451                     struct ldb_dn *basedn,
3452                     enum ldb_scope scope,
3453                     const char * const *attrs,
3454                     uint32_t dsdb_flags,
3455                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3456 {
3457         int ret;
3458         struct ldb_result *res;
3459         va_list ap;
3460         char *expression = NULL;
3461         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3462
3463         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
3464
3465         res = talloc_zero(tmp_ctx, struct ldb_result);
3466         if (!res) {
3467                 talloc_free(tmp_ctx);
3468                 return LDB_ERR_OPERATIONS_ERROR;
3469         }
3470
3471         if (exp_fmt) {
3472                 va_start(ap, exp_fmt);
3473                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3474                 va_end(ap);
3475
3476                 if (!expression) {
3477                         talloc_free(tmp_ctx);
3478                         return LDB_ERR_OPERATIONS_ERROR;
3479                 }
3480         }
3481
3482         ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
3483                           dsdb_flags, "%s", expression);
3484         if (ret != LDB_SUCCESS) {
3485                 talloc_free(tmp_ctx);
3486                 return ret;
3487         }
3488
3489         *msg = talloc_steal(mem_ctx, res->msgs[0]);
3490         talloc_free(tmp_ctx);
3491
3492         return LDB_SUCCESS;
3493 }