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