s4-dsdb: fixed the fetch of the server site name
[amitay/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 structutres 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                 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                         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         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, unsigned int count)
898 {
899         struct ldb_val val;
900         int i;
901         val.data = talloc_array_size(mem_ctx, 16, count);
902         val.length = count*16;
903         if (!val.data) {
904                 return LDB_ERR_OPERATIONS_ERROR;
905         }
906         for (i=0;i<count;i++) {
907                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
908         }
909         return ldb_msg_add_value(msg, attr_name, &val, NULL);
910 }
911
912 /*
913   add a acct_flags element to a message
914 */
915 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
916                              const char *attr_name, uint32_t v)
917 {
918         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
919 }
920
921 /*
922   add a logon_hours element to a message
923 */
924 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
925                               const char *attr_name, struct samr_LogonHours *hours)
926 {
927         struct ldb_val val;
928         val.length = hours->units_per_week / 8;
929         val.data = hours->bits;
930         return ldb_msg_add_value(msg, attr_name, &val, NULL);
931 }
932
933 /*
934   add a parameters element to a message
935 */
936 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
937                              const char *attr_name, struct lsa_BinaryString *parameters)
938 {
939         struct ldb_val val;
940         val.length = parameters->length;
941         val.data = (uint8_t *)parameters->array;
942         return ldb_msg_add_value(msg, attr_name, &val, NULL);
943 }
944 /*
945   add a general value element to a message
946 */
947 int samdb_msg_add_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
948                               const char *attr_name, const struct ldb_val *val)
949 {
950         return ldb_msg_add_value(msg, attr_name, val, NULL);
951 }
952
953 /*
954   sets a general value element to a message
955 */
956 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
957                         const char *attr_name, const struct ldb_val *val)
958 {
959         struct ldb_message_element *el;
960
961         el = ldb_msg_find_element(msg, attr_name);
962         if (el) {
963                 el->num_values = 0;
964         }
965         return ldb_msg_add_value(msg, attr_name, val, NULL);
966 }
967
968 /*
969   set a string element in a message
970 */
971 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
972                          const char *attr_name, const char *str)
973 {
974         struct ldb_message_element *el;
975
976         el = ldb_msg_find_element(msg, attr_name);
977         if (el) {
978                 el->num_values = 0;
979         }
980         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, str);
981 }
982
983 /*
984  * Handle ldb_request in transaction
985  */
986 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
987                                         struct ldb_request *req)
988 {
989         int ret;
990
991         ret = ldb_transaction_start(sam_ldb);
992         if (ret != LDB_SUCCESS) {
993                 return ret;
994         }
995
996         ret = ldb_request(sam_ldb, req);
997         if (ret == LDB_SUCCESS) {
998                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
999         }
1000
1001         if (ret == LDB_SUCCESS) {
1002                 return ldb_transaction_commit(sam_ldb);
1003         }
1004         ldb_transaction_cancel(sam_ldb);
1005
1006         return ret;
1007 }
1008
1009 /*
1010   return a default security descriptor
1011 */
1012 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1013 {
1014         struct security_descriptor *sd;
1015
1016         sd = security_descriptor_initialise(mem_ctx);
1017
1018         return sd;
1019 }
1020
1021 struct ldb_dn *samdb_base_dn(struct ldb_context *sam_ctx) 
1022 {
1023         return ldb_get_default_basedn(sam_ctx);
1024 }
1025
1026 struct ldb_dn *samdb_config_dn(struct ldb_context *sam_ctx) 
1027 {
1028         return ldb_get_config_basedn(sam_ctx);
1029 }
1030
1031 struct ldb_dn *samdb_schema_dn(struct ldb_context *sam_ctx) 
1032 {
1033         return ldb_get_schema_basedn(sam_ctx);
1034 }
1035
1036 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx) 
1037 {
1038         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1039         struct ldb_dn *aggregate_dn;
1040         if (!schema_dn) {
1041                 return NULL;
1042         }
1043
1044         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1045         if (!aggregate_dn) {
1046                 return NULL;
1047         }
1048         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1049                 return NULL;
1050         }
1051         return aggregate_dn;
1052 }
1053
1054 struct ldb_dn *samdb_root_dn(struct ldb_context *sam_ctx) 
1055 {
1056         return ldb_get_root_basedn(sam_ctx);
1057 }
1058
1059 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1060 {
1061         struct ldb_dn *new_dn;
1062
1063         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1064         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1065                 talloc_free(new_dn);
1066                 return NULL;
1067         }
1068         return new_dn;
1069 }
1070
1071 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1072 {
1073         struct ldb_dn *new_dn;
1074
1075         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1076         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1077                 talloc_free(new_dn);
1078                 return NULL;
1079         }
1080         return new_dn;
1081 }
1082
1083 /*
1084   work out the domain sid for the current open ldb
1085 */
1086 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1087 {
1088         TALLOC_CTX *tmp_ctx;
1089         const struct dom_sid *domain_sid;
1090         const char *attrs[] = {
1091                 "objectSid",
1092                 NULL
1093         };
1094         struct ldb_result *res;
1095         int ret;
1096
1097         /* see if we have a cached copy */
1098         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1099         if (domain_sid) {
1100                 return domain_sid;
1101         }
1102
1103         tmp_ctx = talloc_new(ldb);
1104         if (tmp_ctx == NULL) {
1105                 goto failed;
1106         }
1107
1108         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1109
1110         if (ret != LDB_SUCCESS) {
1111                 goto failed;
1112         }
1113
1114         if (res->count != 1) {
1115                 goto failed;
1116         }
1117
1118         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1119         if (domain_sid == NULL) {
1120                 goto failed;
1121         }
1122
1123         /* cache the domain_sid in the ldb */
1124         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1125                 goto failed;
1126         }
1127
1128         talloc_steal(ldb, domain_sid);
1129         talloc_free(tmp_ctx);
1130
1131         return domain_sid;
1132
1133 failed:
1134         talloc_free(tmp_ctx);
1135         return NULL;
1136 }
1137
1138 /*
1139   get domain sid from cache
1140 */
1141 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1142 {
1143         return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1144 }
1145
1146 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1147 {
1148         TALLOC_CTX *tmp_ctx;
1149         struct dom_sid *dom_sid_new;
1150         struct dom_sid *dom_sid_old;
1151
1152         /* see if we have a cached copy */
1153         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1154                                                      "cache.domain_sid"), struct dom_sid);
1155
1156         tmp_ctx = talloc_new(ldb);
1157         if (tmp_ctx == NULL) {
1158                 goto failed;
1159         }
1160
1161         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1162         if (!dom_sid_new) {
1163                 goto failed;
1164         }
1165
1166         /* cache the domain_sid in the ldb */
1167         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1168                 goto failed;
1169         }
1170
1171         talloc_steal(ldb, dom_sid_new);
1172         talloc_free(tmp_ctx);
1173         talloc_free(dom_sid_old);
1174
1175         return true;
1176
1177 failed:
1178         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1179         talloc_free(tmp_ctx);
1180         return false;
1181 }
1182
1183 /* Obtain the short name of the flexible single master operator
1184  * (FSMO), such as the PDC Emulator */
1185 const char *samdb_result_fsmo_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
1186                              const char *attr)
1187 {
1188         /* Format is cn=NTDS Settings,cn=<NETBIOS name of FSMO>,.... */
1189         struct ldb_dn *fsmo_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
1190         const struct ldb_val *val = ldb_dn_get_component_val(fsmo_dn, 1);
1191         const char *name = ldb_dn_get_component_name(fsmo_dn, 1);
1192
1193         if (!name || (ldb_attr_cmp(name, "cn") != 0)) {
1194                 /* Ensure this matches the format.  This gives us a
1195                  * bit more confidence that a 'cn' value will be a
1196                  * ascii string */
1197                 return NULL;
1198         }
1199         if (val) {
1200                 return (char *)val->data;
1201         }
1202         return NULL;
1203 }
1204
1205 /*
1206   work out the ntds settings dn for the current open ldb
1207 */
1208 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1209 {
1210         TALLOC_CTX *tmp_ctx;
1211         const char *root_attrs[] = { "dsServiceName", NULL };
1212         int ret;
1213         struct ldb_result *root_res;
1214         struct ldb_dn *settings_dn;
1215
1216         /* see if we have a cached copy */
1217         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "cache.settings_dn");
1218         if (settings_dn) {
1219                 return settings_dn;
1220         }
1221
1222         tmp_ctx = talloc_new(ldb);
1223         if (tmp_ctx == NULL) {
1224                 goto failed;
1225         }
1226
1227         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1228         if (ret) {
1229                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1230                          ldb_errstring(ldb)));
1231                 goto failed;
1232         }
1233
1234         if (root_res->count != 1) {
1235                 goto failed;
1236         }
1237
1238         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1239
1240         /* cache the domain_sid in the ldb */
1241         if (ldb_set_opaque(ldb, "cache.settings_dn", settings_dn) != LDB_SUCCESS) {
1242                 goto failed;
1243         }
1244
1245         talloc_steal(ldb, settings_dn);
1246         talloc_free(tmp_ctx);
1247
1248         return settings_dn;
1249
1250 failed:
1251         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1252         talloc_free(tmp_ctx);
1253         return NULL;
1254 }
1255
1256 /*
1257   work out the ntds settings invocationId for the current open ldb
1258 */
1259 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1260 {
1261         TALLOC_CTX *tmp_ctx;
1262         const char *attrs[] = { "invocationId", NULL };
1263         int ret;
1264         struct ldb_result *res;
1265         struct GUID *invocation_id;
1266
1267         /* see if we have a cached copy */
1268         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1269         if (invocation_id) {
1270                 return invocation_id;
1271         }
1272
1273         tmp_ctx = talloc_new(ldb);
1274         if (tmp_ctx == NULL) {
1275                 goto failed;
1276         }
1277
1278         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1279         if (ret) {
1280                 goto failed;
1281         }
1282
1283         if (res->count != 1) {
1284                 goto failed;
1285         }
1286
1287         invocation_id = talloc(tmp_ctx, struct GUID);
1288         if (!invocation_id) {
1289                 goto failed;
1290         }
1291
1292         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1293
1294         /* cache the domain_sid in the ldb */
1295         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1296                 goto failed;
1297         }
1298
1299         talloc_steal(ldb, invocation_id);
1300         talloc_free(tmp_ctx);
1301
1302         return invocation_id;
1303
1304 failed:
1305         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1306         talloc_free(tmp_ctx);
1307         return NULL;
1308 }
1309
1310 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1311 {
1312         TALLOC_CTX *tmp_ctx;
1313         struct GUID *invocation_id_new;
1314         struct GUID *invocation_id_old;
1315
1316         /* see if we have a cached copy */
1317         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1318                                                          "cache.invocation_id");
1319
1320         tmp_ctx = talloc_new(ldb);
1321         if (tmp_ctx == NULL) {
1322                 goto failed;
1323         }
1324
1325         invocation_id_new = talloc(tmp_ctx, struct GUID);
1326         if (!invocation_id_new) {
1327                 goto failed;
1328         }
1329
1330         *invocation_id_new = *invocation_id_in;
1331
1332         /* cache the domain_sid in the ldb */
1333         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1334                 goto failed;
1335         }
1336
1337         talloc_steal(ldb, invocation_id_new);
1338         talloc_free(tmp_ctx);
1339         talloc_free(invocation_id_old);
1340
1341         return true;
1342
1343 failed:
1344         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1345         talloc_free(tmp_ctx);
1346         return false;
1347 }
1348
1349 /*
1350   work out the ntds settings objectGUID for the current open ldb
1351 */
1352 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1353 {
1354         TALLOC_CTX *tmp_ctx;
1355         const char *attrs[] = { "objectGUID", NULL };
1356         int ret;
1357         struct ldb_result *res;
1358         struct GUID *ntds_guid;
1359
1360         /* see if we have a cached copy */
1361         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1362         if (ntds_guid) {
1363                 return ntds_guid;
1364         }
1365
1366         tmp_ctx = talloc_new(ldb);
1367         if (tmp_ctx == NULL) {
1368                 goto failed;
1369         }
1370
1371         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1372         if (ret) {
1373                 goto failed;
1374         }
1375
1376         if (res->count != 1) {
1377                 goto failed;
1378         }
1379
1380         ntds_guid = talloc(tmp_ctx, struct GUID);
1381         if (!ntds_guid) {
1382                 goto failed;
1383         }
1384
1385         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1386
1387         /* cache the domain_sid in the ldb */
1388         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1389                 goto failed;
1390         }
1391
1392         talloc_steal(ldb, ntds_guid);
1393         talloc_free(tmp_ctx);
1394
1395         return ntds_guid;
1396
1397 failed:
1398         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1399         talloc_free(tmp_ctx);
1400         return NULL;
1401 }
1402
1403 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1404 {
1405         TALLOC_CTX *tmp_ctx;
1406         struct GUID *ntds_guid_new;
1407         struct GUID *ntds_guid_old;
1408
1409         /* see if we have a cached copy */
1410         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1411
1412         tmp_ctx = talloc_new(ldb);
1413         if (tmp_ctx == NULL) {
1414                 goto failed;
1415         }
1416
1417         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1418         if (!ntds_guid_new) {
1419                 goto failed;
1420         }
1421
1422         *ntds_guid_new = *ntds_guid_in;
1423
1424         /* cache the domain_sid in the ldb */
1425         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1426                 goto failed;
1427         }
1428
1429         talloc_steal(ldb, ntds_guid_new);
1430         talloc_free(tmp_ctx);
1431         talloc_free(ntds_guid_old);
1432
1433         return true;
1434
1435 failed:
1436         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1437         talloc_free(tmp_ctx);
1438         return false;
1439 }
1440
1441 /*
1442   work out the server dn for the current open ldb
1443 */
1444 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1445 {
1446         return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1447 }
1448
1449 /*
1450   work out the server dn for the current open ldb
1451 */
1452 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1453 {
1454         struct ldb_dn *server_dn;
1455         struct ldb_dn *servers_dn;
1456         struct ldb_dn *server_site_dn;
1457
1458         /* TODO: there must be a saner way to do this!! */
1459
1460         server_dn = samdb_server_dn(ldb, mem_ctx);
1461         if (!server_dn) return NULL;
1462
1463         servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1464         if (!servers_dn) return NULL;
1465
1466         server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1467
1468         talloc_free(server_dn);
1469         return server_site_dn;
1470 }
1471
1472 /*
1473   find a 'reference' DN that points at another object
1474   (eg. serverReference, rIDManagerReference etc)
1475  */
1476 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1477                        const char *attribute, struct ldb_dn **dn)
1478 {
1479         const char *attrs[2];
1480         struct ldb_result *res;
1481         int ret;
1482
1483         attrs[0] = attribute;
1484         attrs[1] = NULL;
1485
1486         ret = ldb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, NULL);
1487         if (ret != LDB_SUCCESS) {
1488                 return ret;
1489         }
1490         if (res->count != 1) {
1491                 talloc_free(res);
1492                 return LDB_ERR_NO_SUCH_OBJECT;
1493         }
1494
1495         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1496         if (!*dn) {
1497                 talloc_free(res);
1498                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1499         }
1500
1501         talloc_free(res);
1502         return LDB_SUCCESS;
1503 }
1504
1505 /*
1506   find our machine account via the serverReference attribute in the
1507   server DN
1508  */
1509 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1510 {
1511         struct ldb_dn *server_dn;
1512         int ret;
1513
1514         server_dn = samdb_server_dn(ldb, mem_ctx);
1515         if (server_dn == NULL) {
1516                 return LDB_ERR_NO_SUCH_OBJECT;
1517         }
1518
1519         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1520         talloc_free(server_dn);
1521
1522         return ret;
1523 }
1524
1525 /*
1526   find the RID Manager$ DN via the rIDManagerReference attribute in the
1527   base DN
1528  */
1529 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1530 {
1531         return samdb_reference_dn(ldb, mem_ctx, samdb_base_dn(ldb), "rIDManagerReference", dn);
1532 }
1533
1534 /*
1535   find the RID Set DN via the rIDSetReferences attribute in our
1536   machine account DN
1537  */
1538 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1539 {
1540         struct ldb_dn *server_ref_dn;
1541         int ret;
1542
1543         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1544         if (ret != LDB_SUCCESS) {
1545                 return ret;
1546         }
1547         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1548         talloc_free(server_ref_dn);
1549         return ret;
1550 }
1551
1552 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1553 {
1554         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb, mem_ctx));
1555
1556         if (val != NULL)
1557                 return (const char *) val->data;
1558         else
1559                 return NULL;
1560 }
1561
1562 /*
1563   work out if we are the PDC for the domain of the current open ldb
1564 */
1565 bool samdb_is_pdc(struct ldb_context *ldb)
1566 {
1567         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1568         int ret;
1569         struct ldb_result *dom_res;
1570         TALLOC_CTX *tmp_ctx;
1571         bool is_pdc;
1572         struct ldb_dn *pdc;
1573
1574         tmp_ctx = talloc_new(ldb);
1575         if (tmp_ctx == NULL) {
1576                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1577                 return false;
1578         }
1579
1580         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1581         if (ret) {
1582                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1583                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1584                          ldb_errstring(ldb)));
1585                 goto failed;
1586         }
1587         if (dom_res->count != 1) {
1588                 goto failed;
1589         }
1590
1591         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1592
1593         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1594                 is_pdc = true;
1595         } else {
1596                 is_pdc = false;
1597         }
1598
1599         talloc_free(tmp_ctx);
1600
1601         return is_pdc;
1602
1603 failed:
1604         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1605         talloc_free(tmp_ctx);
1606         return false;
1607 }
1608
1609 /*
1610   work out if we are a Global Catalog server for the domain of the current open ldb
1611 */
1612 bool samdb_is_gc(struct ldb_context *ldb)
1613 {
1614         const char *attrs[] = { "options", NULL };
1615         int ret, options;
1616         struct ldb_result *res;
1617         TALLOC_CTX *tmp_ctx;
1618
1619         tmp_ctx = talloc_new(ldb);
1620         if (tmp_ctx == NULL) {
1621                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1622                 return false;
1623         }
1624
1625         /* Query cn=ntds settings,.... */
1626         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1627         if (ret) {
1628                 talloc_free(tmp_ctx);
1629                 return false;
1630         }
1631         if (res->count != 1) {
1632                 talloc_free(tmp_ctx);
1633                 return false;
1634         }
1635
1636         options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1637         talloc_free(tmp_ctx);
1638
1639         /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1640         if (options & 0x000000001) {
1641                 return true;
1642         }
1643         return false;
1644 }
1645
1646 /* Find a domain object in the parents of a particular DN.  */
1647 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1648                                    struct ldb_dn **parent_dn, const char **errstring)
1649 {
1650         TALLOC_CTX *local_ctx;
1651         struct ldb_dn *sdn = dn;
1652         struct ldb_result *res = NULL;
1653         int ret = 0;
1654         const char *attrs[] = { NULL };
1655
1656         local_ctx = talloc_new(mem_ctx);
1657         if (local_ctx == NULL) return LDB_ERR_OPERATIONS_ERROR;
1658
1659         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1660                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1661                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1662                 if (ret == LDB_SUCCESS) {
1663                         if (res->count == 1) {
1664                                 break;
1665                         }
1666                 } else {
1667                         break;
1668                 }
1669         }
1670
1671         if (ret != LDB_SUCCESS) {
1672                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1673                                              ldb_dn_get_linearized(dn),
1674                                              ldb_dn_get_linearized(sdn),
1675                                              ldb_errstring(ldb));
1676                 talloc_free(local_ctx);
1677                 return ret;
1678         }
1679         if (res->count != 1) {
1680                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1681                                              ldb_dn_get_linearized(dn));
1682                 DEBUG(0,(__location__ ": %s\n", *errstring));
1683                 talloc_free(local_ctx);
1684                 return LDB_ERR_CONSTRAINT_VIOLATION;
1685         }
1686
1687         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1688         talloc_free(local_ctx);
1689         return ret;
1690 }
1691
1692
1693 /*
1694  * Performs checks on a user password (plaintext UNIX format - attribute
1695  * "password"). The remaining parameters have to be extracted from the domain
1696  * object in the AD.
1697  *
1698  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1699  */
1700 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1701                                                 const uint32_t pwdProperties,
1702                                                 const uint32_t minPwdLength)
1703 {
1704         /* checks if the "minPwdLength" property is satisfied */
1705         if (minPwdLength > password->length)
1706                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1707
1708         /* checks the password complexity */
1709         if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1710                         && (password->data != NULL)
1711                         && (!check_password_quality((const char *) password->data)))
1712                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1713
1714         return SAMR_VALIDATION_STATUS_SUCCESS;
1715 }
1716
1717 /*
1718  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1719  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1720  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1721  * gives some more informations if the changed failed.
1722  *
1723  * The caller should have a LDB transaction wrapping this.
1724  *
1725  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
1726  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1727  *   NT_STATUS_PASSWORD_RESTRICTION
1728  */
1729 NTSTATUS samdb_set_password(struct ldb_context *ctx, TALLOC_CTX *mem_ctx,
1730                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1731                             struct ldb_message *mod,
1732                             const DATA_BLOB *new_password,
1733                             struct samr_Password *param_lmNewHash,
1734                             struct samr_Password *param_ntNewHash,
1735                             bool user_change,
1736                             enum samPwdChangeReason *reject_reason,
1737                             struct samr_DomInfo1 **_dominfo)
1738 {
1739         const char * const user_attrs[] = { "userAccountControl",
1740                                             "lmPwdHistory",
1741                                             "ntPwdHistory", 
1742                                             "dBCSPwd", "unicodePwd", 
1743                                             "objectSid", 
1744                                             "pwdLastSet", NULL };
1745         const char * const domain_attrs[] = { "minPwdLength", "pwdProperties",
1746                                               "pwdHistoryLength",
1747                                               "maxPwdAge", "minPwdAge", NULL };
1748         NTTIME pwdLastSet;
1749         uint32_t minPwdLength, pwdProperties, pwdHistoryLength;
1750         int64_t maxPwdAge, minPwdAge;
1751         uint32_t userAccountControl;
1752         struct samr_Password *sambaLMPwdHistory, *sambaNTPwdHistory,
1753                 *lmPwdHash, *ntPwdHash, *lmNewHash, *ntNewHash;
1754         struct samr_Password local_lmNewHash, local_ntNewHash;
1755         int sambaLMPwdHistory_len, sambaNTPwdHistory_len;
1756         struct dom_sid *domain_sid;
1757         struct ldb_message **res;
1758         bool restrictions;
1759         int count;
1760         time_t now = time(NULL);
1761         NTTIME now_nt;
1762         int i;
1763
1764         /* we need to know the time to compute password age */
1765         unix_to_nt_time(&now_nt, now);
1766
1767         /* pull all the user parameters */
1768         count = gendb_search_dn(ctx, mem_ctx, user_dn, &res, user_attrs);
1769         if (count != 1) {
1770                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1771         }
1772         userAccountControl = samdb_result_uint(res[0], "userAccountControl", 0);
1773         sambaLMPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1774                                          "lmPwdHistory", &sambaLMPwdHistory);
1775         sambaNTPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1776                                          "ntPwdHistory", &sambaNTPwdHistory);
1777         lmPwdHash = samdb_result_hash(mem_ctx, res[0], "dBCSPwd");
1778         ntPwdHash = samdb_result_hash(mem_ctx, res[0], "unicodePwd");
1779         pwdLastSet = samdb_result_uint64(res[0], "pwdLastSet", 0);
1780
1781         /* Copy parameters */
1782         lmNewHash = param_lmNewHash;
1783         ntNewHash = param_ntNewHash;
1784
1785         /* Only non-trust accounts have restrictions (possibly this
1786          * test is the wrong way around, but I like to be restrictive
1787          * if possible */
1788         restrictions = !(userAccountControl & (UF_INTERDOMAIN_TRUST_ACCOUNT
1789                                                |UF_WORKSTATION_TRUST_ACCOUNT
1790                                                |UF_SERVER_TRUST_ACCOUNT)); 
1791
1792         if (domain_dn != NULL) {
1793                 /* pull the domain parameters */
1794                 count = gendb_search_dn(ctx, mem_ctx, domain_dn, &res,
1795                                                                 domain_attrs);
1796                 if (count != 1) {
1797                         DEBUG(2, ("samdb_set_password: Domain DN %s is invalid, for user %s\n", 
1798                                   ldb_dn_get_linearized(domain_dn),
1799                                   ldb_dn_get_linearized(user_dn)));
1800                         return NT_STATUS_NO_SUCH_DOMAIN;
1801                 }
1802         } else {
1803                 /* work out the domain sid, and pull the domain from there */
1804                 domain_sid = samdb_result_sid_prefix(mem_ctx, res[0],
1805                                                                 "objectSid");
1806                 if (domain_sid == NULL) {
1807                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
1808                 }
1809
1810                 count = gendb_search(ctx, mem_ctx, NULL, &res, domain_attrs, 
1811                                 "(objectSid=%s)",
1812                                 ldap_encode_ndr_dom_sid(mem_ctx, domain_sid));
1813                 if (count != 1) {
1814                         DEBUG(2, ("samdb_set_password: Could not find domain to match SID: %s, for user %s\n", 
1815                                   dom_sid_string(mem_ctx, domain_sid),
1816                                   ldb_dn_get_linearized(user_dn)));
1817                         return NT_STATUS_NO_SUCH_DOMAIN;
1818                 }
1819         }
1820
1821         minPwdLength = samdb_result_uint(res[0], "minPwdLength", 0);
1822         pwdProperties = samdb_result_uint(res[0], "pwdProperties", 0);
1823         pwdHistoryLength = samdb_result_uint(res[0], "pwdHistoryLength", 0);
1824         maxPwdAge = samdb_result_int64(res[0], "maxPwdAge", 0);
1825         minPwdAge = samdb_result_int64(res[0], "minPwdAge", 0);
1826
1827         if ((userAccountControl & UF_PASSWD_NOTREQD) != 0) {
1828                 /* see [MS-ADTS] 2.2.15 */
1829                 minPwdLength = 0;
1830         }
1831
1832         if (_dominfo != NULL) {
1833                 struct samr_DomInfo1 *dominfo;
1834                 /* on failure we need to fill in the reject reasons */
1835                 dominfo = talloc(mem_ctx, struct samr_DomInfo1);
1836                 if (dominfo == NULL) {
1837                         return NT_STATUS_NO_MEMORY;
1838                 }
1839                 dominfo->min_password_length     = minPwdLength;
1840                 dominfo->password_properties     = pwdProperties;
1841                 dominfo->password_history_length = pwdHistoryLength;
1842                 dominfo->max_password_age        = maxPwdAge;
1843                 dominfo->min_password_age        = minPwdAge;
1844                 *_dominfo = dominfo;
1845         }
1846
1847         if ((restrictions != 0) && (new_password != 0)) {
1848                 char *new_pass;
1849
1850                 /* checks if the "minPwdLength" property is satisfied */
1851                 if ((restrictions != 0)
1852                         && (minPwdLength > utf16_len_n(
1853                                 new_password->data, new_password->length)/2)) {
1854                         if (reject_reason) {
1855                                 *reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
1856                         }
1857                         return NT_STATUS_PASSWORD_RESTRICTION;
1858                 }
1859
1860                 /* Create the NT hash */
1861                 mdfour(local_ntNewHash.hash, new_password->data,
1862                                                         new_password->length);
1863
1864                 ntNewHash = &local_ntNewHash;
1865
1866                 /* Only check complexity if we can convert it at all.  Assuming unconvertable passwords are 'strong' */
1867                 if (convert_string_talloc_convenience(mem_ctx,
1868                           lp_iconv_convenience(ldb_get_opaque(ctx, "loadparm")),
1869                           CH_UTF16, CH_UNIX,
1870                           new_password->data, new_password->length,
1871                           (void **)&new_pass, NULL, false)) {
1872
1873                         /* checks the password complexity */
1874                         if ((restrictions != 0)
1875                                 && ((pwdProperties
1876                                         & DOMAIN_PASSWORD_COMPLEX) != 0)
1877                                 && (!check_password_quality(new_pass))) {
1878                                 if (reject_reason) {
1879                                         *reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
1880                                 }
1881                                 return NT_STATUS_PASSWORD_RESTRICTION;
1882                         }
1883
1884                         /* compute the new lm hashes (for checking history - case insenitivly!) */
1885                         if (E_deshash(new_pass, local_lmNewHash.hash)) {
1886                                 lmNewHash = &local_lmNewHash;
1887                         }
1888                 }
1889         }
1890
1891         if ((restrictions != 0) && user_change) {
1892                 /* are all password changes disallowed? */
1893                 if ((pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) != 0) {
1894                         if (reject_reason) {
1895                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1896                         }
1897                         return NT_STATUS_PASSWORD_RESTRICTION;
1898                 }
1899
1900                 /* can this user change the password? */
1901                 if ((userAccountControl & UF_PASSWD_CANT_CHANGE) != 0) {
1902                         if (reject_reason) {
1903                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1904                         }
1905                         return NT_STATUS_PASSWORD_RESTRICTION;
1906                 }
1907
1908                 /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
1909                 if (pwdLastSet - minPwdAge > now_nt) {
1910                         if (reject_reason) {
1911                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1912                         }
1913                         return NT_STATUS_PASSWORD_RESTRICTION;
1914                 }
1915
1916                 /* check the immediately past password */
1917                 if (pwdHistoryLength > 0) {
1918                         if (lmNewHash && lmPwdHash && memcmp(lmNewHash->hash,
1919                                         lmPwdHash->hash, 16) == 0) {
1920                                 if (reject_reason) {
1921                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1922                                 }
1923                                 return NT_STATUS_PASSWORD_RESTRICTION;
1924                         }
1925                         if (ntNewHash && ntPwdHash && memcmp(ntNewHash->hash,
1926                                         ntPwdHash->hash, 16) == 0) {
1927                                 if (reject_reason) {
1928                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1929                                 }
1930                                 return NT_STATUS_PASSWORD_RESTRICTION;
1931                         }
1932                 }
1933
1934                 /* check the password history */
1935                 sambaLMPwdHistory_len = MIN(sambaLMPwdHistory_len,
1936                                                         pwdHistoryLength);
1937                 sambaNTPwdHistory_len = MIN(sambaNTPwdHistory_len,
1938                                                         pwdHistoryLength);
1939
1940                 for (i=0; lmNewHash && i<sambaLMPwdHistory_len;i++) {
1941                         if (memcmp(lmNewHash->hash, sambaLMPwdHistory[i].hash,
1942                                         16) == 0) {
1943                                 if (reject_reason) {
1944                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1945                                 }
1946                                 return NT_STATUS_PASSWORD_RESTRICTION;
1947                         }
1948                 }
1949                 for (i=0; ntNewHash && i<sambaNTPwdHistory_len;i++) {
1950                         if (memcmp(ntNewHash->hash, sambaNTPwdHistory[i].hash,
1951                                          16) == 0) {
1952                                 if (reject_reason) {
1953                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1954                                 }
1955                                 return NT_STATUS_PASSWORD_RESTRICTION;
1956                         }
1957                 }
1958         }
1959
1960 #define CHECK_RET(x) do { if (x != 0) return NT_STATUS_NO_MEMORY; } while(0)
1961
1962         /* the password is acceptable. Start forming the new fields */
1963         if (new_password != NULL) {
1964                 /* if we know the cleartext UTF16 password, then set it.
1965                  * Modules in ldb will set all the appropriate
1966                  * hashes */
1967                 CHECK_RET(ldb_msg_add_value(mod, "clearTextPassword", new_password, NULL));
1968         } else {
1969                 /* we don't have the cleartext, so set what we have of the
1970                  * hashes */
1971
1972                 if (lmNewHash) {
1973                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "dBCSPwd", lmNewHash));
1974                 }
1975
1976                 if (ntNewHash) {
1977                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "unicodePwd", ntNewHash));
1978                 }
1979         }
1980
1981         if (reject_reason) {
1982                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1983         }
1984         return NT_STATUS_OK;
1985 }
1986
1987
1988 /*
1989  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1990  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1991  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1992  * gives some more informations if the changed failed.
1993  *
1994  * This wrapper function for "samdb_set_password" takes a SID as input rather
1995  * than a user DN.
1996  *
1997  * This call encapsulates a new LDB transaction for changing the password;
1998  * therefore the user hasn't to start a new one.
1999  *
2000  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2001  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2002  *   NT_STATUS_PASSWORD_RESTRICTION
2003  */
2004 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2005                                 const struct dom_sid *user_sid,
2006                                 const DATA_BLOB *new_password,
2007                                 struct samr_Password *lmNewHash, 
2008                                 struct samr_Password *ntNewHash,
2009                                 bool user_change,
2010                                 enum samPwdChangeReason *reject_reason,
2011                                 struct samr_DomInfo1 **_dominfo) 
2012 {
2013         NTSTATUS nt_status;
2014         struct ldb_dn *user_dn;
2015         struct ldb_message *msg;
2016         int ret;
2017
2018         ret = ldb_transaction_start(ldb);
2019         if (ret != LDB_SUCCESS) {
2020                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2021                 return NT_STATUS_TRANSACTION_ABORTED;
2022         }
2023
2024         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2025                                   "(&(objectSid=%s)(objectClass=user))", 
2026                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2027         if (!user_dn) {
2028                 ldb_transaction_cancel(ldb);
2029                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2030                           dom_sid_string(mem_ctx, user_sid)));
2031                 return NT_STATUS_NO_SUCH_USER;
2032         }
2033
2034         msg = ldb_msg_new(mem_ctx);
2035         if (msg == NULL) {
2036                 ldb_transaction_cancel(ldb);
2037                 talloc_free(user_dn);
2038                 return NT_STATUS_NO_MEMORY;
2039         }
2040
2041         msg->dn = ldb_dn_copy(msg, user_dn);
2042         if (!msg->dn) {
2043                 ldb_transaction_cancel(ldb);
2044                 talloc_free(user_dn);
2045                 talloc_free(msg);
2046                 return NT_STATUS_NO_MEMORY;
2047         }
2048
2049         nt_status = samdb_set_password(ldb, mem_ctx,
2050                                        user_dn, NULL,
2051                                        msg, new_password,
2052                                        lmNewHash, ntNewHash,
2053                                        user_change,
2054                                        reject_reason, _dominfo);
2055         if (!NT_STATUS_IS_OK(nt_status)) {
2056                 ldb_transaction_cancel(ldb);
2057                 talloc_free(user_dn);
2058                 talloc_free(msg);
2059                 return nt_status;
2060         }
2061
2062         /* modify the samdb record */
2063         ret = dsdb_replace(ldb, msg, 0);
2064         if (ret != LDB_SUCCESS) {
2065                 ldb_transaction_cancel(ldb);
2066                 talloc_free(user_dn);
2067                 talloc_free(msg);
2068                 return NT_STATUS_ACCESS_DENIED;
2069         }
2070
2071         talloc_free(msg);
2072
2073         ret = ldb_transaction_commit(ldb);
2074         if (ret != LDB_SUCCESS) {
2075                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2076                          ldb_dn_get_linearized(user_dn),
2077                          ldb_errstring(ldb)));
2078                 talloc_free(user_dn);
2079                 return NT_STATUS_TRANSACTION_ABORTED;
2080         }
2081
2082         talloc_free(user_dn);
2083         return NT_STATUS_OK;
2084 }
2085
2086
2087 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2088                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2089 {
2090         struct ldb_message *msg;
2091         struct ldb_dn *basedn;
2092         char *sidstr;
2093         int ret;
2094
2095         sidstr = dom_sid_string(mem_ctx, sid);
2096         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2097
2098         /* We might have to create a ForeignSecurityPrincipal, even if this user
2099          * is in our own domain */
2100
2101         msg = ldb_msg_new(sidstr);
2102         if (msg == NULL) {
2103                 talloc_free(sidstr);
2104                 return NT_STATUS_NO_MEMORY;
2105         }
2106
2107         ret = dsdb_wellknown_dn(sam_ctx, sidstr, samdb_base_dn(sam_ctx),
2108                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2109                                 &basedn);
2110         if (ret != LDB_SUCCESS) {
2111                 DEBUG(0, ("Failed to find DN for "
2112                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2113                 talloc_free(sidstr);
2114                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2115         }
2116
2117         /* add core elements to the ldb_message for the alias */
2118         msg->dn = basedn;
2119         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2120                 talloc_free(sidstr);
2121                 return NT_STATUS_NO_MEMORY;
2122         }
2123
2124         samdb_msg_add_string(sam_ctx, msg, msg,
2125                              "objectClass",
2126                              "foreignSecurityPrincipal");
2127
2128         /* create the alias */
2129         ret = ldb_add(sam_ctx, msg);
2130         if (ret != LDB_SUCCESS) {
2131                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2132                          "record %s: %s\n", 
2133                          ldb_dn_get_linearized(msg->dn),
2134                          ldb_errstring(sam_ctx)));
2135                 talloc_free(sidstr);
2136                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2137         }
2138
2139         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2140         talloc_free(sidstr);
2141
2142         return NT_STATUS_OK;
2143 }
2144
2145
2146 /*
2147   Find the DN of a domain, assuming it to be a dotted.dns name
2148 */
2149
2150 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2151 {
2152         int i;
2153         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2154         const char *binary_encoded;
2155         const char **split_realm;
2156         struct ldb_dn *dn;
2157
2158         if (!tmp_ctx) {
2159                 return NULL;
2160         }
2161
2162         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2163         if (!split_realm) {
2164                 talloc_free(tmp_ctx);
2165                 return NULL;
2166         }
2167         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2168         for (i=0; split_realm[i]; i++) {
2169                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2170                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2171                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2172                                   binary_encoded, ldb_dn_get_linearized(dn)));
2173                         talloc_free(tmp_ctx);
2174                         return NULL;
2175                 }
2176         }
2177         if (!ldb_dn_validate(dn)) {
2178                 DEBUG(2, ("Failed to validated DN %s\n",
2179                           ldb_dn_get_linearized(dn)));
2180                 talloc_free(tmp_ctx);
2181                 return NULL;
2182         }
2183         talloc_free(tmp_ctx);
2184         return dn;
2185 }
2186
2187 /*
2188   Find the DN of a domain, be it the netbios or DNS name 
2189 */
2190 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2191                                   const char *domain_name) 
2192 {
2193         const char * const domain_ref_attrs[] = {
2194                 "ncName", NULL
2195         };
2196         const char * const domain_ref2_attrs[] = {
2197                 NULL
2198         };
2199         struct ldb_result *res_domain_ref;
2200         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2201         /* find the domain's DN */
2202         int ret_domain = ldb_search(ldb, mem_ctx,
2203                                             &res_domain_ref, 
2204                                             samdb_partitions_dn(ldb, mem_ctx), 
2205                                             LDB_SCOPE_ONELEVEL, 
2206                                             domain_ref_attrs,
2207                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2208                                             escaped_domain);
2209         if (ret_domain != 0) {
2210                 return NULL;
2211         }
2212
2213         if (res_domain_ref->count == 0) {
2214                 ret_domain = ldb_search(ldb, mem_ctx,
2215                                                 &res_domain_ref, 
2216                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2217                                                 LDB_SCOPE_BASE,
2218                                                 domain_ref2_attrs,
2219                                                 "(objectclass=domain)");
2220                 if (ret_domain != 0) {
2221                         return NULL;
2222                 }
2223
2224                 if (res_domain_ref->count == 1) {
2225                         return res_domain_ref->msgs[0]->dn;
2226                 }
2227                 return NULL;
2228         }
2229
2230         if (res_domain_ref->count > 1) {
2231                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2232                          ret_domain, domain_name));
2233                 return NULL;
2234         }
2235
2236         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2237
2238 }
2239
2240
2241 /*
2242   use a GUID to find a DN
2243  */
2244 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2245                          TALLOC_CTX *mem_ctx,
2246                          const struct GUID *guid, struct ldb_dn **dn)
2247 {
2248         int ret;
2249         struct ldb_result *res;
2250         const char *attrs[] = { NULL };
2251         char *guid_str = GUID_string(mem_ctx, guid);
2252
2253         if (!guid_str) {
2254                 return LDB_ERR_OPERATIONS_ERROR;
2255         }
2256
2257         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2258                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2259                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2260                           DSDB_SEARCH_ONE_ONLY,
2261                           "objectGUID=%s", guid_str);
2262         talloc_free(guid_str);
2263         if (ret != LDB_SUCCESS) {
2264                 return ret;
2265         }
2266
2267         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2268         talloc_free(res);
2269
2270         return LDB_SUCCESS;
2271 }
2272
2273 /*
2274   use a DN to find a GUID with a given attribute name
2275  */
2276 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2277                               struct ldb_dn *dn, const char *attribute,
2278                               struct GUID *guid)
2279 {
2280         int ret;
2281         struct ldb_result *res;
2282         const char *attrs[2];
2283         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2284
2285         attrs[0] = attribute;
2286         attrs[1] = NULL;
2287
2288         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2289         if (ret != LDB_SUCCESS) {
2290                 talloc_free(tmp_ctx);
2291                 return ret;
2292         }
2293         if (res->count < 1) {
2294                 talloc_free(tmp_ctx);
2295                 return LDB_ERR_NO_SUCH_OBJECT;
2296         }
2297         *guid = samdb_result_guid(res->msgs[0], attribute);
2298         talloc_free(tmp_ctx);
2299         return LDB_SUCCESS;
2300 }
2301
2302 /*
2303   use a DN to find a GUID
2304  */
2305 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2306                          struct ldb_dn *dn, struct GUID *guid)
2307 {
2308         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2309 }
2310
2311
2312
2313 /*
2314  adds the given GUID to the given ldb_message. This value is added
2315  for the given attr_name (may be either "objectGUID" or "parentGUID").
2316  */
2317 int dsdb_msg_add_guid(struct ldb_message *msg,
2318                 struct GUID *guid,
2319                 const char *attr_name)
2320 {
2321         int ret;
2322         struct ldb_val v;
2323         NTSTATUS status;
2324         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2325
2326         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2327         if (!NT_STATUS_IS_OK(status)) {
2328                 ret = LDB_ERR_OPERATIONS_ERROR;
2329                 goto done;
2330         }
2331
2332         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2333         if (ret != LDB_SUCCESS) {
2334                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2335                                          attr_name));
2336                 goto done;
2337         }
2338
2339         ret = LDB_SUCCESS;
2340
2341 done:
2342         talloc_free(tmp_ctx);
2343         return ret;
2344
2345 }
2346
2347
2348 /*
2349   use a DN to find a SID
2350  */
2351 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2352                         struct ldb_dn *dn, struct dom_sid *sid)
2353 {
2354         int ret;
2355         struct ldb_result *res;
2356         const char *attrs[] = { "objectSID", NULL };
2357         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2358         struct dom_sid *s;
2359
2360         ZERO_STRUCTP(sid);
2361
2362         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2363         if (ret != LDB_SUCCESS) {
2364                 talloc_free(tmp_ctx);
2365                 return ret;
2366         }
2367         if (res->count < 1) {
2368                 talloc_free(tmp_ctx);
2369                 return LDB_ERR_NO_SUCH_OBJECT;
2370         }
2371         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2372         if (s == NULL) {
2373                 talloc_free(tmp_ctx);
2374                 return LDB_ERR_NO_SUCH_OBJECT;
2375         }
2376         *sid = *s;
2377         talloc_free(tmp_ctx);
2378         return LDB_SUCCESS;
2379 }
2380
2381
2382
2383 /*
2384   load a repsFromTo blob list for a given partition GUID
2385   attr must be "repsFrom" or "repsTo"
2386  */
2387 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2388                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2389 {
2390         const char *attrs[] = { attr, NULL };
2391         struct ldb_result *res = NULL;
2392         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2393         int i;
2394         struct ldb_message_element *el;
2395
2396         *r = NULL;
2397         *count = 0;
2398
2399         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2400             res->count < 1) {
2401                 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2402                 talloc_free(tmp_ctx);
2403                 return WERR_DS_DRA_INTERNAL_ERROR;
2404         }
2405
2406         el = ldb_msg_find_element(res->msgs[0], attr);
2407         if (el == NULL) {
2408                 /* it's OK to be empty */
2409                 talloc_free(tmp_ctx);
2410                 return WERR_OK;
2411         }
2412
2413         *count = el->num_values;
2414         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2415         if (*r == NULL) {
2416                 talloc_free(tmp_ctx);
2417                 return WERR_DS_DRA_INTERNAL_ERROR;
2418         }
2419
2420         for (i=0; i<(*count); i++) {
2421                 enum ndr_err_code ndr_err;
2422                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2423                                                mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2424                                                &(*r)[i], 
2425                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2426                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2427                         talloc_free(tmp_ctx);
2428                         return WERR_DS_DRA_INTERNAL_ERROR;
2429                 }
2430         }
2431
2432         talloc_free(tmp_ctx);
2433         
2434         return WERR_OK;
2435 }
2436
2437 /*
2438   save the repsFromTo blob list for a given partition GUID
2439   attr must be "repsFrom" or "repsTo"
2440  */
2441 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2442                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2443 {
2444         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2445         struct ldb_message *msg;
2446         struct ldb_message_element *el;
2447         int i;
2448
2449         msg = ldb_msg_new(tmp_ctx);
2450         msg->dn = dn;
2451         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2452                 goto failed;
2453         }
2454
2455         el->values = talloc_array(msg, struct ldb_val, count);
2456         if (!el->values) {
2457                 goto failed;
2458         }
2459
2460         for (i=0; i<count; i++) {
2461                 struct ldb_val v;
2462                 enum ndr_err_code ndr_err;
2463
2464                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2465                                                &r[i], 
2466                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2467                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2468                         goto failed;
2469                 }
2470
2471                 el->num_values++;
2472                 el->values[i] = v;
2473         }
2474
2475         if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2476                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2477                 goto failed;
2478         }
2479
2480         talloc_free(tmp_ctx);
2481         
2482         return WERR_OK;
2483
2484 failed:
2485         talloc_free(tmp_ctx);
2486         return WERR_DS_DRA_INTERNAL_ERROR;
2487 }
2488
2489
2490 /*
2491   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2492   object for a partition
2493  */
2494 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2495                                 uint64_t *uSN, uint64_t *urgent_uSN)
2496 {
2497         struct ldb_request *req;
2498         int ret;
2499         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2500         struct dsdb_control_current_partition *p_ctrl;
2501         struct ldb_result *res;
2502
2503         res = talloc_zero(tmp_ctx, struct ldb_result);
2504         if (!res) {
2505                 talloc_free(tmp_ctx);
2506                 return LDB_ERR_OPERATIONS_ERROR;
2507         }
2508
2509         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2510                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2511                                    LDB_SCOPE_BASE,
2512                                    NULL, NULL,
2513                                    NULL,
2514                                    res, ldb_search_default_callback,
2515                                    NULL);
2516         if (ret != LDB_SUCCESS) {
2517                 talloc_free(tmp_ctx);
2518                 return ret;
2519         }
2520
2521         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2522         if (p_ctrl == NULL) {
2523                 talloc_free(res);
2524                 return LDB_ERR_OPERATIONS_ERROR;
2525         }
2526         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2527         p_ctrl->dn = dn;
2528         
2529
2530         ret = ldb_request_add_control(req,
2531                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2532                                       false, p_ctrl);
2533         if (ret != LDB_SUCCESS) {
2534                 talloc_free(tmp_ctx);
2535                 return ret;
2536         }
2537         
2538         /* Run the new request */
2539         ret = ldb_request(ldb, req);
2540         
2541         if (ret == LDB_SUCCESS) {
2542                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2543         }
2544
2545         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2546                 /* it hasn't been created yet, which means
2547                    an implicit value of zero */
2548                 *uSN = 0;
2549                 talloc_free(tmp_ctx);
2550                 return LDB_SUCCESS;
2551         }
2552
2553         if (ret != LDB_SUCCESS) {
2554                 talloc_free(tmp_ctx);
2555                 return ret;
2556         }
2557
2558         if (res->count < 1) {
2559                 *uSN = 0;
2560                 if (urgent_uSN) {
2561                         *urgent_uSN = 0;
2562                 }
2563         } else {
2564                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2565                 if (urgent_uSN) {
2566                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2567                 }
2568         }
2569
2570         talloc_free(tmp_ctx);
2571
2572         return LDB_SUCCESS;     
2573 }
2574
2575 /*
2576   save uSNHighest and uSNUrgent attributes in the @REPLCHANGED object for a
2577   partition
2578  */
2579 int dsdb_save_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2580                                 uint64_t uSN, uint64_t urgent_uSN)
2581 {
2582         struct ldb_request *req;
2583         struct ldb_message *msg;
2584         struct dsdb_control_current_partition *p_ctrl;
2585         int ret;
2586
2587         msg = ldb_msg_new(ldb);
2588         if (msg == NULL) {
2589                 return LDB_ERR_OPERATIONS_ERROR;
2590         }
2591
2592         msg->dn = ldb_dn_new(msg, ldb, "@REPLCHANGED");
2593         if (msg->dn == NULL) {
2594                 talloc_free(msg);
2595                 return LDB_ERR_OPERATIONS_ERROR;
2596         }
2597         
2598         ret = ldb_msg_add_fmt(msg, "uSNHighest", "%llu", (unsigned long long)uSN);
2599         if (ret != LDB_SUCCESS) {
2600                 talloc_free(msg);
2601                 return ret;
2602         }
2603         msg->elements[0].flags = LDB_FLAG_MOD_REPLACE;
2604         
2605         /* urgent_uSN is optional so may not be stored */
2606         if (urgent_uSN) {
2607                 ret = ldb_msg_add_fmt(msg, "uSNUrgent", "%llu", (unsigned long long)urgent_uSN);
2608                 if (ret != LDB_SUCCESS) {
2609                         talloc_free(msg);
2610                         return ret;
2611                 }
2612                 msg->elements[1].flags = LDB_FLAG_MOD_REPLACE;
2613         }
2614
2615
2616         p_ctrl = talloc(msg, struct dsdb_control_current_partition);
2617         if (p_ctrl == NULL) {
2618                 talloc_free(msg);
2619                 return LDB_ERR_OPERATIONS_ERROR;
2620         }
2621         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2622         p_ctrl->dn = dn;
2623
2624         ret = ldb_build_mod_req(&req, ldb, msg,
2625                                 msg,
2626                                 NULL,
2627                                 NULL, ldb_op_default_callback,
2628                                 NULL);
2629 again:
2630         if (ret != LDB_SUCCESS) {
2631                 talloc_free(msg);
2632                 return ret;
2633         }
2634         
2635         ret = ldb_request_add_control(req,
2636                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2637                                       false, p_ctrl);
2638         if (ret != LDB_SUCCESS) {
2639                 talloc_free(msg);
2640                 return ret;
2641         }
2642         
2643         /* Run the new request */
2644         ret = ldb_request(ldb, req);
2645         
2646         if (ret == LDB_SUCCESS) {
2647                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2648         }
2649         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2650                 ret = ldb_build_add_req(&req, ldb, msg,
2651                                         msg,
2652                                         NULL,
2653                                         NULL, ldb_op_default_callback,
2654                                         NULL);
2655                 goto again;
2656         }
2657         
2658         talloc_free(msg);
2659         
2660         return ret;
2661 }
2662
2663 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2664                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2665 {
2666         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2667 }
2668
2669 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2670                                     const struct drsuapi_DsReplicaCursor *c2)
2671 {
2672         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2673 }
2674
2675 /*
2676   see if we are a RODC
2677
2678   TODO: This should take a sam_ctx, and lookup the right object (with
2679   a cache)
2680 */
2681 bool samdb_rodc(struct loadparm_context *lp_ctx)
2682 {
2683         return lp_parm_bool(lp_ctx, NULL, "repl", "RODC", false);
2684 }
2685
2686
2687 /*
2688   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2689
2690   flags are DS_NTDS_OPTION_*
2691 */
2692 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2693 {
2694         TALLOC_CTX *tmp_ctx;
2695         const char *attrs[] = { "options", NULL };
2696         int ret;
2697         struct ldb_result *res;
2698
2699         tmp_ctx = talloc_new(ldb);
2700         if (tmp_ctx == NULL) {
2701                 goto failed;
2702         }
2703
2704         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2705         if (ret) {
2706                 goto failed;
2707         }
2708
2709         if (res->count != 1) {
2710                 goto failed;
2711         }
2712
2713         *options = samdb_result_uint(res->msgs[0], "options", 0);
2714
2715         talloc_free(tmp_ctx);
2716
2717         return LDB_SUCCESS;
2718
2719 failed:
2720         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
2721         talloc_free(tmp_ctx);
2722         return LDB_ERR_NO_SUCH_OBJECT;
2723 }
2724
2725 /*
2726  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
2727  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
2728  */
2729 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
2730 {
2731         char **tokens, *ret;
2732         size_t i;
2733
2734         tokens = str_list_make(mem_ctx, cn, " -_");
2735         if (tokens == NULL)
2736                 return NULL;
2737
2738         /* "tolower()" and "toupper()" should also work properly on 0x00 */
2739         tokens[0][0] = tolower(tokens[0][0]);
2740         for (i = 1; i < str_list_length((const char **)tokens); i++)
2741                 tokens[i][0] = toupper(tokens[i][0]);
2742
2743         ret = talloc_strdup(mem_ctx, tokens[0]);
2744         for (i = 1; i < str_list_length((const char **)tokens); i++)
2745                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
2746
2747         talloc_free(tokens);
2748
2749         return ret;
2750 }
2751
2752 /*
2753   return domain functional level
2754   returns DS_DOMAIN_FUNCTION_*
2755  */
2756 int dsdb_functional_level(struct ldb_context *ldb)
2757 {
2758         int *domainFunctionality =
2759                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
2760         if (!domainFunctionality) {
2761                 DEBUG(0,(__location__ ": WARNING: domainFunctionality not setup\n"));
2762                 return DS_DOMAIN_FUNCTION_2000;
2763         }
2764         return *domainFunctionality;
2765 }
2766
2767 /*
2768   set a GUID in an extended DN structure
2769  */
2770 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
2771 {
2772         struct ldb_val v;
2773         NTSTATUS status;
2774         int ret;
2775
2776         status = GUID_to_ndr_blob(guid, dn, &v);
2777         if (!NT_STATUS_IS_OK(status)) {
2778                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
2779         }
2780
2781         ret = ldb_dn_set_extended_component(dn, component_name, &v);
2782         data_blob_free(&v);
2783         return ret;
2784 }
2785
2786 /*
2787   return a GUID from a extended DN structure
2788  */
2789 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
2790 {
2791         const struct ldb_val *v;
2792
2793         v = ldb_dn_get_extended_component(dn, component_name);
2794         if (v == NULL) {
2795                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2796         }
2797
2798         return GUID_from_ndr_blob(v, guid);
2799 }
2800
2801 /*
2802   return a uint64_t from a extended DN structure
2803  */
2804 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
2805 {
2806         const struct ldb_val *v;
2807         char *s;
2808
2809         v = ldb_dn_get_extended_component(dn, component_name);
2810         if (v == NULL) {
2811                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2812         }
2813         s = talloc_strndup(dn, (const char *)v->data, v->length);
2814         NT_STATUS_HAVE_NO_MEMORY(s);
2815
2816         *val = strtoull(s, NULL, 0);
2817
2818         talloc_free(s);
2819         return NT_STATUS_OK;
2820 }
2821
2822 /*
2823   return a NTTIME from a extended DN structure
2824  */
2825 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
2826 {
2827         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
2828 }
2829
2830 /*
2831   return a uint32_t from a extended DN structure
2832  */
2833 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
2834 {
2835         const struct ldb_val *v;
2836         char *s;
2837
2838         v = ldb_dn_get_extended_component(dn, component_name);
2839         if (v == NULL) {
2840                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2841         }
2842
2843         s = talloc_strndup(dn, (const char *)v->data, v->length);
2844         NT_STATUS_HAVE_NO_MEMORY(s);
2845
2846         *val = strtoul(s, NULL, 0);
2847
2848         talloc_free(s);
2849         return NT_STATUS_OK;
2850 }
2851
2852 /*
2853   return RMD_FLAGS directly from a ldb_dn
2854   returns 0 if not found
2855  */
2856 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
2857 {
2858         const struct ldb_val *v;
2859         char buf[32];
2860         v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
2861         if (!v || v->length > sizeof(buf)-1) return 0;
2862         strncpy(buf, (const char *)v->data, v->length);
2863         buf[v->length] = 0;
2864         return strtoul(buf, NULL, 10);
2865 }
2866
2867 /*
2868   return RMD_FLAGS directly from a ldb_val for a DN
2869   returns 0 if RMD_FLAGS is not found
2870  */
2871 uint32_t dsdb_dn_val_rmd_flags(struct ldb_val *val)
2872 {
2873         const char *p;
2874         uint32_t flags;
2875         char *end;
2876
2877         if (val->length < 13) {
2878                 return 0;
2879         }
2880         p = memmem(val->data, val->length-2, "<RMD_FLAGS=", 11);
2881         if (!p) {
2882                 return 0;
2883         }
2884         flags = strtoul(p+11, &end, 10);
2885         if (!end || *end != '>') {
2886                 /* it must end in a > */
2887                 return 0;
2888         }
2889         return flags;
2890 }
2891
2892 /*
2893   return true if a ldb_val containing a DN in storage form is deleted
2894  */
2895 bool dsdb_dn_is_deleted_val(struct ldb_val *val)
2896 {
2897         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
2898 }
2899
2900 /*
2901   return true if a ldb_val containing a DN in storage form is
2902   in the upgraded w2k3 linked attribute format
2903  */
2904 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
2905 {
2906         return memmem(val->data, val->length, "<RMD_ADDTIME=", 13) != NULL;
2907 }
2908
2909 /*
2910   return a DN for a wellknown GUID
2911  */
2912 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
2913                       struct ldb_dn *nc_root, const char *wk_guid,
2914                       struct ldb_dn **wkguid_dn)
2915 {
2916         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2917         const char *attrs[] = { NULL };
2918         int ret;
2919         struct ldb_dn *dn;
2920         struct ldb_result *res;
2921
2922         /* construct the magic WKGUID DN */
2923         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
2924                             wk_guid, ldb_dn_get_linearized(nc_root));
2925         if (!wkguid_dn) {
2926                 talloc_free(tmp_ctx);
2927                 return LDB_ERR_OPERATIONS_ERROR;
2928         }
2929
2930         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs, DSDB_SEARCH_SHOW_DELETED);
2931         if (ret != LDB_SUCCESS) {
2932                 talloc_free(tmp_ctx);
2933                 return ret;
2934         }
2935
2936         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
2937         talloc_free(tmp_ctx);
2938         return LDB_SUCCESS;
2939 }
2940
2941
2942 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
2943 {
2944         return ldb_dn_compare(*dn1, *dn2);
2945 }
2946
2947 /*
2948   find a NC root given a DN within the NC
2949  */
2950 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2951                       struct ldb_dn **nc_root)
2952 {
2953         const char *root_attrs[] = { "namingContexts", NULL };
2954         TALLOC_CTX *tmp_ctx;
2955         int ret;
2956         struct ldb_message_element *el;
2957         struct ldb_result *root_res;
2958         int i;
2959         struct ldb_dn **nc_dns;
2960
2961         tmp_ctx = talloc_new(samdb);
2962         if (tmp_ctx == NULL) {
2963                 return LDB_ERR_OPERATIONS_ERROR;
2964         }
2965
2966         ret = ldb_search(samdb, tmp_ctx, &root_res,
2967                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
2968         if (ret) {
2969                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
2970                 talloc_free(tmp_ctx);
2971                 return ret;
2972        }
2973
2974        el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
2975        if (!el) {
2976                DEBUG(1,("Finding namingContexts element in root_res failed: %s\n",
2977                         ldb_errstring(samdb)));
2978                talloc_free(tmp_ctx);
2979                return LDB_ERR_NO_SUCH_ATTRIBUTE;
2980        }
2981
2982        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
2983        if (!nc_dns) {
2984                talloc_free(tmp_ctx);
2985                return LDB_ERR_OPERATIONS_ERROR;
2986        }
2987
2988        for (i=0; i<el->num_values; i++) {
2989                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
2990                if (nc_dns[i] == NULL) {
2991                        talloc_free(tmp_ctx);
2992                        return LDB_ERR_OPERATIONS_ERROR;
2993                }
2994        }
2995
2996        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
2997
2998        for (i=0; i<el->num_values; i++) {
2999                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3000                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3001                        talloc_free(tmp_ctx);
3002                        return LDB_SUCCESS;
3003                }
3004        }
3005
3006        talloc_free(tmp_ctx);
3007        return LDB_ERR_NO_SUCH_OBJECT;
3008 }
3009
3010
3011 /*
3012   find the deleted objects DN for any object, by looking for the NC
3013   root, then looking up the wellknown GUID
3014  */
3015 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3016                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3017                                 struct ldb_dn **do_dn)
3018 {
3019         struct ldb_dn *nc_root;
3020         int ret;
3021
3022         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3023         if (ret != LDB_SUCCESS) {
3024                 return ret;
3025         }
3026
3027         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3028         talloc_free(nc_root);
3029         return ret;
3030 }
3031
3032 /*
3033   return the tombstoneLifetime, in days
3034  */
3035 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3036 {
3037         struct ldb_dn *dn;
3038         dn = samdb_config_dn(ldb);
3039         if (!dn) {
3040                 return LDB_ERR_NO_SUCH_OBJECT;
3041         }
3042         dn = ldb_dn_copy(ldb, dn);
3043         if (!dn) {
3044                 return LDB_ERR_OPERATIONS_ERROR;
3045         }
3046         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3047          be a wellknown GUID for this */
3048         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3049                 talloc_free(dn);
3050                 return LDB_ERR_OPERATIONS_ERROR;
3051         }
3052
3053         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3054         talloc_free(dn);
3055         return LDB_SUCCESS;
3056 }
3057
3058 /*
3059   compare a ldb_val to a string case insensitively
3060  */
3061 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3062 {
3063         size_t len = strlen(s);
3064         int ret;
3065         if (len > v->length) return 1;
3066         ret = strncasecmp(s, (const char *)v->data, v->length);
3067         if (ret != 0) return ret;
3068         if (v->length > len && v->data[len] != 0) {
3069                 return -1;
3070         }
3071         return 0;
3072 }
3073
3074
3075 /*
3076   load the UDV for a partition in v2 format
3077   The list is returned sorted, and with our local cursor added
3078  */
3079 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3080                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3081 {
3082         static const char *attrs[] = { "replUpToDateVector", NULL };
3083         struct ldb_result *r;
3084         const struct ldb_val *ouv_value;
3085         int ret, i;
3086         uint64_t highest_usn;
3087         const struct GUID *our_invocation_id;
3088         struct timeval now = timeval_current();
3089
3090         ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3091         if (ret != LDB_SUCCESS) {
3092                 return ret;
3093         }
3094
3095         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3096         if (ouv_value) {
3097                 enum ndr_err_code ndr_err;
3098                 struct replUpToDateVectorBlob ouv;
3099
3100                 ndr_err = ndr_pull_struct_blob(ouv_value, r,
3101                                                lp_iconv_convenience(ldb_get_opaque(samdb, "loadparm")), &ouv,
3102                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3103                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3104                         talloc_free(r);
3105                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3106                 }
3107                 if (ouv.version != 2) {
3108                         /* we always store as version 2, and
3109                          * replUpToDateVector is not replicated
3110                          */
3111                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3112                 }
3113
3114                 *count = ouv.ctr.ctr2.count;
3115                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3116         } else {
3117                 *count = 0;
3118                 *cursors = NULL;
3119         }
3120
3121         talloc_free(r);
3122
3123         our_invocation_id = samdb_ntds_invocation_id(samdb);
3124         if (!our_invocation_id) {
3125                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3126                 talloc_free(*cursors);
3127                 return LDB_ERR_OPERATIONS_ERROR;
3128         }
3129
3130         ret = dsdb_load_partition_usn(samdb, dn, &highest_usn, NULL);
3131         if (ret != LDB_SUCCESS) {
3132                 /* nothing to add - this can happen after a vampire */
3133                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3134                 return LDB_SUCCESS;
3135         }
3136
3137         for (i=0; i<*count; i++) {
3138                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3139                         (*cursors)[i].highest_usn = highest_usn;
3140                         (*cursors)[i].last_sync_success = timeval_to_nttime(&now);
3141                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3142                         return LDB_SUCCESS;
3143                 }
3144         }
3145
3146         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3147         if (! *cursors) {
3148                 return LDB_ERR_OPERATIONS_ERROR;
3149         }
3150
3151         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3152         (*cursors)[*count].highest_usn = highest_usn;
3153         (*cursors)[*count].last_sync_success = timeval_to_nttime(&now);
3154         (*count)++;
3155
3156         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3157
3158         return LDB_SUCCESS;
3159 }
3160
3161 /*
3162   load the UDV for a partition in version 1 format
3163   The list is returned sorted, and with our local cursor added
3164  */
3165 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3166                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3167 {
3168         struct drsuapi_DsReplicaCursor2 *v2;
3169         int ret, i;
3170
3171         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3172         if (ret != LDB_SUCCESS) {
3173                 return ret;
3174         }
3175
3176         if (*count == 0) {
3177                 talloc_free(v2);
3178                 *cursors = NULL;
3179                 return LDB_SUCCESS;
3180         }
3181
3182         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3183         if (*cursors == NULL) {
3184                 talloc_free(v2);
3185                 return LDB_ERR_OPERATIONS_ERROR;
3186         }
3187
3188         for (i=0; i<*count; i++) {
3189                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3190                 (*cursors)[i].highest_usn = v2[i].highest_usn;
3191         }
3192         talloc_free(v2);
3193         return LDB_SUCCESS;
3194 }
3195
3196 /*
3197   add a set of controls to a ldb_request structure based on a set of
3198   flags. See util.h for a list of available flags
3199  */
3200 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3201 {
3202         int ret;
3203         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3204                 struct ldb_search_options_control *options;
3205                 /* Using the phantom root control allows us to search all partitions */
3206                 options = talloc(req, struct ldb_search_options_control);
3207                 if (options == NULL) {
3208                         return LDB_ERR_OPERATIONS_ERROR;
3209                 }
3210                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3211
3212                 ret = ldb_request_add_control(req,
3213                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
3214                                               true, options);
3215                 if (ret != LDB_SUCCESS) {
3216                         return ret;
3217                 }
3218         }
3219
3220         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3221                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3222                 if (ret != LDB_SUCCESS) {
3223                         return ret;
3224                 }
3225         }
3226
3227         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3228                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, true, NULL);
3229                 if (ret != LDB_SUCCESS) {
3230                         return ret;
3231                 }
3232         }
3233
3234         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3235                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3236                 if (!extended_ctrl) {
3237                         return LDB_ERR_OPERATIONS_ERROR;
3238                 }
3239                 extended_ctrl->type = 1;
3240
3241                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3242                 if (ret != LDB_SUCCESS) {
3243                         return ret;
3244                 }
3245         }
3246
3247         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3248                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3249                 if (ret != LDB_SUCCESS) {
3250                         return ret;
3251                 }
3252         }
3253
3254         if (dsdb_flags & DSDB_MODIFY_RELAX) {
3255                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3256                 if (ret != LDB_SUCCESS) {
3257                         return ret;
3258                 }
3259         }
3260
3261         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3262                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3263                 if (ret != LDB_SUCCESS) {
3264                         return ret;
3265                 }
3266         }
3267
3268         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3269                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3270                 if (ret != LDB_SUCCESS) {
3271                         return ret;
3272                 }
3273         }
3274
3275         return LDB_SUCCESS;
3276 }
3277
3278 /*
3279   a modify with a set of controls
3280 */
3281 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3282                 uint32_t dsdb_flags)
3283 {
3284         struct ldb_request *req;
3285         int ret;
3286
3287         ret = ldb_build_mod_req(&req, ldb, ldb,
3288                                 message,
3289                                 NULL,
3290                                 NULL,
3291                                 ldb_op_default_callback,
3292                                 NULL);
3293
3294         if (ret != LDB_SUCCESS) return ret;
3295
3296         ret = dsdb_request_add_controls(req, dsdb_flags);
3297         if (ret != LDB_SUCCESS) {
3298                 talloc_free(req);
3299                 return ret;
3300         }
3301
3302         ret = dsdb_autotransaction_request(ldb, req);
3303
3304         talloc_free(req);
3305         return ret;
3306 }
3307
3308 /*
3309   like dsdb_modify() but set all the element flags to
3310   LDB_FLAG_MOD_REPLACE
3311  */
3312 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3313 {
3314         int i;
3315
3316         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3317         for (i=0;i<msg->num_elements;i++) {
3318                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3319         }
3320
3321         return dsdb_modify(ldb, msg, dsdb_flags);
3322 }
3323
3324
3325 /*
3326   search for attrs on one DN, allowing for dsdb_flags controls
3327  */
3328 int dsdb_search_dn(struct ldb_context *ldb,
3329                    TALLOC_CTX *mem_ctx,
3330                    struct ldb_result **_res,
3331                    struct ldb_dn *basedn,
3332                    const char * const *attrs,
3333                    uint32_t dsdb_flags)
3334 {
3335         int ret;
3336         struct ldb_request *req;
3337         struct ldb_result *res;
3338
3339         res = talloc_zero(mem_ctx, struct ldb_result);
3340         if (!res) {
3341                 return LDB_ERR_OPERATIONS_ERROR;
3342         }
3343
3344         ret = ldb_build_search_req(&req, ldb, res,
3345                                    basedn,
3346                                    LDB_SCOPE_BASE,
3347                                    NULL,
3348                                    attrs,
3349                                    NULL,
3350                                    res,
3351                                    ldb_search_default_callback,
3352                                    NULL);
3353         if (ret != LDB_SUCCESS) {
3354                 talloc_free(res);
3355                 return ret;
3356         }
3357
3358         ret = dsdb_request_add_controls(req, dsdb_flags);
3359         if (ret != LDB_SUCCESS) {
3360                 talloc_free(res);
3361                 return ret;
3362         }
3363
3364         ret = ldb_request(ldb, req);
3365         if (ret == LDB_SUCCESS) {
3366                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3367         }
3368
3369         talloc_free(req);
3370         if (ret != LDB_SUCCESS) {
3371                 talloc_free(res);
3372                 return ret;
3373         }
3374
3375         *_res = res;
3376         return LDB_SUCCESS;
3377 }
3378
3379 /*
3380   general search with dsdb_flags for controls
3381  */
3382 int dsdb_search(struct ldb_context *ldb,
3383                 TALLOC_CTX *mem_ctx,
3384                 struct ldb_result **_res,
3385                 struct ldb_dn *basedn,
3386                 enum ldb_scope scope,
3387                 const char * const *attrs,
3388                 uint32_t dsdb_flags,
3389                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3390 {
3391         int ret;
3392         struct ldb_request *req;
3393         struct ldb_result *res;
3394         va_list ap;
3395         char *expression = NULL;
3396         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3397
3398         res = talloc_zero(tmp_ctx, struct ldb_result);
3399         if (!res) {
3400                 talloc_free(tmp_ctx);
3401                 return LDB_ERR_OPERATIONS_ERROR;
3402         }
3403
3404         if (exp_fmt) {
3405                 va_start(ap, exp_fmt);
3406                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3407                 va_end(ap);
3408
3409                 if (!expression) {
3410                         talloc_free(tmp_ctx);
3411                         return LDB_ERR_OPERATIONS_ERROR;
3412                 }
3413         }
3414
3415         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3416                                    basedn,
3417                                    scope,
3418                                    expression,
3419                                    attrs,
3420                                    NULL,
3421                                    res,
3422                                    ldb_search_default_callback,
3423                                    NULL);
3424         if (ret != LDB_SUCCESS) {
3425                 talloc_free(tmp_ctx);
3426                 return ret;
3427         }
3428
3429         ret = dsdb_request_add_controls(req, dsdb_flags);
3430         if (ret != LDB_SUCCESS) {
3431                 talloc_free(tmp_ctx);
3432                 return ret;
3433         }
3434
3435         ret = ldb_request(ldb, req);
3436         if (ret == LDB_SUCCESS) {
3437                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3438         }
3439
3440         if (ret != LDB_SUCCESS) {
3441                 talloc_free(tmp_ctx);
3442                 return ret;
3443         }
3444
3445         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
3446                 if (res->count == 0) {
3447                         talloc_free(tmp_ctx);
3448                         return LDB_ERR_NO_SUCH_OBJECT;
3449                 }
3450                 if (res->count != 1) {
3451                         talloc_free(tmp_ctx);
3452                         return LDB_ERR_CONSTRAINT_VIOLATION;
3453                 }
3454         }
3455
3456         *_res = talloc_steal(mem_ctx, res);
3457         talloc_free(tmp_ctx);
3458
3459         return LDB_SUCCESS;
3460 }
3461
3462
3463 /*
3464   general search with dsdb_flags for controls
3465   returns exactly 1 record or an error
3466  */
3467 int dsdb_search_one(struct ldb_context *ldb,
3468                     TALLOC_CTX *mem_ctx,
3469                     struct ldb_message **msg,
3470                     struct ldb_dn *basedn,
3471                     enum ldb_scope scope,
3472                     const char * const *attrs,
3473                     uint32_t dsdb_flags,
3474                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3475 {
3476         int ret;
3477         struct ldb_result *res;
3478         va_list ap;
3479         char *expression = NULL;
3480         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3481
3482         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
3483
3484         res = talloc_zero(tmp_ctx, struct ldb_result);
3485         if (!res) {
3486                 talloc_free(tmp_ctx);
3487                 return LDB_ERR_OPERATIONS_ERROR;
3488         }
3489
3490         if (exp_fmt) {
3491                 va_start(ap, exp_fmt);
3492                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3493                 va_end(ap);
3494
3495                 if (!expression) {
3496                         talloc_free(tmp_ctx);
3497                         return LDB_ERR_OPERATIONS_ERROR;
3498                 }
3499         }
3500
3501         ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
3502                           dsdb_flags, "%s", expression);
3503         if (ret != LDB_SUCCESS) {
3504                 talloc_free(tmp_ctx);
3505                 return ret;
3506         }
3507
3508         *msg = talloc_steal(mem_ctx, res->msgs[0]);
3509         talloc_free(tmp_ctx);
3510
3511         return LDB_SUCCESS;
3512 }