s4:dsdb/common/util.c - samdb_msg_add_string - the attribute name doesn't need to...
[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         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
930 }
931
932 /*
933   add a unsigned int element to a message
934 */
935 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
936                        const char *attr_name, unsigned int v)
937 {
938         return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
939 }
940
941 /*
942   add a (signed) int64_t element to a message
943 */
944 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
945                         const char *attr_name, int64_t v)
946 {
947         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
948         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
949 }
950
951 /*
952   add a uint64_t element to a message
953 */
954 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
955                         const char *attr_name, uint64_t v)
956 {
957         return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
958 }
959
960 /*
961   add a samr_Password element to a message
962 */
963 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
964                        const char *attr_name, const struct samr_Password *hash)
965 {
966         struct ldb_val val;
967         val.data = talloc_memdup(mem_ctx, hash->hash, 16);
968         if (!val.data) {
969                 return ldb_oom(sam_ldb);
970         }
971         val.length = 16;
972         return ldb_msg_add_value(msg, attr_name, &val, NULL);
973 }
974
975 /*
976   add a samr_Password array to a message
977 */
978 int samdb_msg_add_hashes(struct ldb_context *ldb,
979                          TALLOC_CTX *mem_ctx, struct ldb_message *msg,
980                          const char *attr_name, struct samr_Password *hashes,
981                          unsigned int count)
982 {
983         struct ldb_val val;
984         unsigned int i;
985         val.data = talloc_array_size(mem_ctx, 16, count);
986         val.length = count*16;
987         if (!val.data) {
988                 return ldb_oom(ldb);
989         }
990         for (i=0;i<count;i++) {
991                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
992         }
993         return ldb_msg_add_value(msg, attr_name, &val, NULL);
994 }
995
996 /*
997   add a acct_flags element to a message
998 */
999 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1000                              const char *attr_name, uint32_t v)
1001 {
1002         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
1003 }
1004
1005 /*
1006   add a logon_hours element to a message
1007 */
1008 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1009                               const char *attr_name, struct samr_LogonHours *hours)
1010 {
1011         struct ldb_val val;
1012         val.length = hours->units_per_week / 8;
1013         val.data = hours->bits;
1014         return ldb_msg_add_value(msg, attr_name, &val, NULL);
1015 }
1016
1017 /*
1018   add a parameters element to a message
1019 */
1020 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1021                              const char *attr_name, struct lsa_BinaryString *parameters)
1022 {
1023         struct ldb_val val;
1024         val.length = parameters->length;
1025         val.data = (uint8_t *)parameters->array;
1026         return ldb_msg_add_value(msg, attr_name, &val, NULL);
1027 }
1028
1029 /*
1030   sets a general value element to a message
1031 */
1032 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1033                         const char *attr_name, const struct ldb_val *val)
1034 {
1035         struct ldb_message_element *el;
1036
1037         el = ldb_msg_find_element(msg, attr_name);
1038         if (el) {
1039                 el->num_values = 0;
1040         }
1041         return ldb_msg_add_value(msg, attr_name, val, NULL);
1042 }
1043
1044 /*
1045   set a string element in a message
1046 */
1047 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
1048                          const char *attr_name, const char *str)
1049 {
1050         struct ldb_message_element *el;
1051
1052         el = ldb_msg_find_element(msg, attr_name);
1053         if (el) {
1054                 el->num_values = 0;
1055         }
1056         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, str);
1057 }
1058
1059 /*
1060  * sets a signed integer in a message
1061  */
1062 int samdb_msg_set_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1063                       struct ldb_message *msg, const char *attr_name, int v)
1064 {
1065         struct ldb_message_element *el;
1066
1067         el = ldb_msg_find_element(msg, attr_name);
1068         if (el) {
1069                 el->num_values = 0;
1070         }
1071         return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, v);
1072 }
1073
1074 /*
1075  * sets an unsigned integer in a message
1076  */
1077 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1078                        struct ldb_message *msg, const char *attr_name,
1079                        unsigned int v)
1080 {
1081         struct ldb_message_element *el;
1082
1083         el = ldb_msg_find_element(msg, attr_name);
1084         if (el) {
1085                 el->num_values = 0;
1086         }
1087         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1088 }
1089
1090 /*
1091  * Handle ldb_request in transaction
1092  */
1093 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1094                                         struct ldb_request *req)
1095 {
1096         int ret;
1097
1098         ret = ldb_transaction_start(sam_ldb);
1099         if (ret != LDB_SUCCESS) {
1100                 return ret;
1101         }
1102
1103         ret = ldb_request(sam_ldb, req);
1104         if (ret == LDB_SUCCESS) {
1105                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1106         }
1107
1108         if (ret == LDB_SUCCESS) {
1109                 return ldb_transaction_commit(sam_ldb);
1110         }
1111         ldb_transaction_cancel(sam_ldb);
1112
1113         return ret;
1114 }
1115
1116 /*
1117   return a default security descriptor
1118 */
1119 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1120 {
1121         struct security_descriptor *sd;
1122
1123         sd = security_descriptor_initialise(mem_ctx);
1124
1125         return sd;
1126 }
1127
1128 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx) 
1129 {
1130         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1131         struct ldb_dn *aggregate_dn;
1132         if (!schema_dn) {
1133                 return NULL;
1134         }
1135
1136         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1137         if (!aggregate_dn) {
1138                 return NULL;
1139         }
1140         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1141                 return NULL;
1142         }
1143         return aggregate_dn;
1144 }
1145
1146 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1147 {
1148         struct ldb_dn *new_dn;
1149
1150         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1151         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1152                 talloc_free(new_dn);
1153                 return NULL;
1154         }
1155         return new_dn;
1156 }
1157
1158 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1159 {
1160        struct ldb_dn *new_dn;
1161
1162        new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1163        if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1164                talloc_free(new_dn);
1165                return NULL;
1166        }
1167        return new_dn;
1168 }
1169
1170 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1171 {
1172         struct ldb_dn *new_dn;
1173
1174         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1175         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1176                 talloc_free(new_dn);
1177                 return NULL;
1178         }
1179         return new_dn;
1180 }
1181
1182 /*
1183   work out the domain sid for the current open ldb
1184 */
1185 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1186 {
1187         TALLOC_CTX *tmp_ctx;
1188         const struct dom_sid *domain_sid;
1189         const char *attrs[] = {
1190                 "objectSid",
1191                 NULL
1192         };
1193         struct ldb_result *res;
1194         int ret;
1195
1196         /* see if we have a cached copy */
1197         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1198         if (domain_sid) {
1199                 return domain_sid;
1200         }
1201
1202         tmp_ctx = talloc_new(ldb);
1203         if (tmp_ctx == NULL) {
1204                 goto failed;
1205         }
1206
1207         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1208
1209         if (ret != LDB_SUCCESS) {
1210                 goto failed;
1211         }
1212
1213         if (res->count != 1) {
1214                 goto failed;
1215         }
1216
1217         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1218         if (domain_sid == NULL) {
1219                 goto failed;
1220         }
1221
1222         /* cache the domain_sid in the ldb */
1223         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1224                 goto failed;
1225         }
1226
1227         talloc_steal(ldb, domain_sid);
1228         talloc_free(tmp_ctx);
1229
1230         return domain_sid;
1231
1232 failed:
1233         talloc_free(tmp_ctx);
1234         return NULL;
1235 }
1236
1237 /*
1238   get domain sid from cache
1239 */
1240 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1241 {
1242         return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1243 }
1244
1245 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1246 {
1247         TALLOC_CTX *tmp_ctx;
1248         struct dom_sid *dom_sid_new;
1249         struct dom_sid *dom_sid_old;
1250
1251         /* see if we have a cached copy */
1252         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1253                                                      "cache.domain_sid"), struct dom_sid);
1254
1255         tmp_ctx = talloc_new(ldb);
1256         if (tmp_ctx == NULL) {
1257                 goto failed;
1258         }
1259
1260         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1261         if (!dom_sid_new) {
1262                 goto failed;
1263         }
1264
1265         /* cache the domain_sid in the ldb */
1266         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1267                 goto failed;
1268         }
1269
1270         talloc_steal(ldb, dom_sid_new);
1271         talloc_free(tmp_ctx);
1272         talloc_free(dom_sid_old);
1273
1274         return true;
1275
1276 failed:
1277         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1278         talloc_free(tmp_ctx);
1279         return false;
1280 }
1281
1282 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1283 {
1284         TALLOC_CTX *tmp_ctx;
1285         struct ldb_dn *ntds_settings_dn_new;
1286         struct ldb_dn *ntds_settings_dn_old;
1287
1288         /* see if we have a cached copy */
1289         ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb, 
1290                                                               "cache.ntds_settings_dn"), struct ldb_dn);
1291
1292         tmp_ctx = talloc_new(ldb);
1293         if (tmp_ctx == NULL) {
1294                 goto failed;
1295         }
1296
1297         ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1298         if (!ntds_settings_dn_new) {
1299                 goto failed;
1300         }
1301
1302         /* cache the domain_sid in the ldb */
1303         if (ldb_set_opaque(ldb, "cache.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1304                 goto failed;
1305         }
1306
1307         talloc_steal(ldb, ntds_settings_dn_new);
1308         talloc_free(tmp_ctx);
1309         talloc_free(ntds_settings_dn_old);
1310
1311         return true;
1312
1313 failed:
1314         DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1315         talloc_free(tmp_ctx);
1316         return false;
1317 }
1318
1319 /* Obtain the short name of the flexible single master operator
1320  * (FSMO), such as the PDC Emulator */
1321 const char *samdb_result_fsmo_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
1322                              const char *attr)
1323 {
1324         /* Format is cn=NTDS Settings,cn=<NETBIOS name of FSMO>,.... */
1325         struct ldb_dn *fsmo_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
1326         const struct ldb_val *val = ldb_dn_get_component_val(fsmo_dn, 1);
1327         const char *name = ldb_dn_get_component_name(fsmo_dn, 1);
1328
1329         if (!name || (ldb_attr_cmp(name, "cn") != 0)) {
1330                 /* Ensure this matches the format.  This gives us a
1331                  * bit more confidence that a 'cn' value will be a
1332                  * ascii string */
1333                 return NULL;
1334         }
1335         if (val) {
1336                 return (char *)val->data;
1337         }
1338         return NULL;
1339 }
1340
1341 /*
1342   work out the ntds settings dn for the current open ldb
1343 */
1344 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1345 {
1346         TALLOC_CTX *tmp_ctx;
1347         const char *root_attrs[] = { "dsServiceName", NULL };
1348         int ret;
1349         struct ldb_result *root_res;
1350         struct ldb_dn *settings_dn;
1351
1352         /* see if we have a cached copy */
1353         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "cache.ntds_settings_dn");
1354         if (settings_dn) {
1355                 return settings_dn;
1356         }
1357
1358         tmp_ctx = talloc_new(ldb);
1359         if (tmp_ctx == NULL) {
1360                 goto failed;
1361         }
1362
1363         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1364         if (ret) {
1365                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1366                          ldb_errstring(ldb)));
1367                 goto failed;
1368         }
1369
1370         if (root_res->count != 1) {
1371                 goto failed;
1372         }
1373
1374         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1375
1376         /* cache the domain_sid in the ldb */
1377         if (ldb_set_opaque(ldb, "cache.settings_dn", settings_dn) != LDB_SUCCESS) {
1378                 goto failed;
1379         }
1380
1381         talloc_steal(ldb, settings_dn);
1382         talloc_free(tmp_ctx);
1383
1384         return settings_dn;
1385
1386 failed:
1387         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1388         talloc_free(tmp_ctx);
1389         return NULL;
1390 }
1391
1392 /*
1393   work out the ntds settings invocationId for the current open ldb
1394 */
1395 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1396 {
1397         TALLOC_CTX *tmp_ctx;
1398         const char *attrs[] = { "invocationId", NULL };
1399         int ret;
1400         struct ldb_result *res;
1401         struct GUID *invocation_id;
1402
1403         /* see if we have a cached copy */
1404         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1405         if (invocation_id) {
1406                 return invocation_id;
1407         }
1408
1409         tmp_ctx = talloc_new(ldb);
1410         if (tmp_ctx == NULL) {
1411                 goto failed;
1412         }
1413
1414         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1415         if (ret) {
1416                 goto failed;
1417         }
1418
1419         if (res->count != 1) {
1420                 goto failed;
1421         }
1422
1423         invocation_id = talloc(tmp_ctx, struct GUID);
1424         if (!invocation_id) {
1425                 goto failed;
1426         }
1427
1428         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1429
1430         /* cache the domain_sid in the ldb */
1431         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1432                 goto failed;
1433         }
1434
1435         talloc_steal(ldb, invocation_id);
1436         talloc_free(tmp_ctx);
1437
1438         return invocation_id;
1439
1440 failed:
1441         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1442         talloc_free(tmp_ctx);
1443         return NULL;
1444 }
1445
1446 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1447 {
1448         TALLOC_CTX *tmp_ctx;
1449         struct GUID *invocation_id_new;
1450         struct GUID *invocation_id_old;
1451
1452         /* see if we have a cached copy */
1453         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1454                                                          "cache.invocation_id");
1455
1456         tmp_ctx = talloc_new(ldb);
1457         if (tmp_ctx == NULL) {
1458                 goto failed;
1459         }
1460
1461         invocation_id_new = talloc(tmp_ctx, struct GUID);
1462         if (!invocation_id_new) {
1463                 goto failed;
1464         }
1465
1466         *invocation_id_new = *invocation_id_in;
1467
1468         /* cache the domain_sid in the ldb */
1469         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1470                 goto failed;
1471         }
1472
1473         talloc_steal(ldb, invocation_id_new);
1474         talloc_free(tmp_ctx);
1475         talloc_free(invocation_id_old);
1476
1477         return true;
1478
1479 failed:
1480         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1481         talloc_free(tmp_ctx);
1482         return false;
1483 }
1484
1485 /*
1486   work out the ntds settings objectGUID for the current open ldb
1487 */
1488 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1489 {
1490         TALLOC_CTX *tmp_ctx;
1491         const char *attrs[] = { "objectGUID", NULL };
1492         int ret;
1493         struct ldb_result *res;
1494         struct GUID *ntds_guid;
1495
1496         /* see if we have a cached copy */
1497         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1498         if (ntds_guid) {
1499                 return ntds_guid;
1500         }
1501
1502         tmp_ctx = talloc_new(ldb);
1503         if (tmp_ctx == NULL) {
1504                 goto failed;
1505         }
1506
1507         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1508         if (ret) {
1509                 goto failed;
1510         }
1511
1512         if (res->count != 1) {
1513                 goto failed;
1514         }
1515
1516         ntds_guid = talloc(tmp_ctx, struct GUID);
1517         if (!ntds_guid) {
1518                 goto failed;
1519         }
1520
1521         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1522
1523         /* cache the domain_sid in the ldb */
1524         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1525                 goto failed;
1526         }
1527
1528         talloc_steal(ldb, ntds_guid);
1529         talloc_free(tmp_ctx);
1530
1531         return ntds_guid;
1532
1533 failed:
1534         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1535         talloc_free(tmp_ctx);
1536         return NULL;
1537 }
1538
1539 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1540 {
1541         TALLOC_CTX *tmp_ctx;
1542         struct GUID *ntds_guid_new;
1543         struct GUID *ntds_guid_old;
1544
1545         /* see if we have a cached copy */
1546         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1547
1548         tmp_ctx = talloc_new(ldb);
1549         if (tmp_ctx == NULL) {
1550                 goto failed;
1551         }
1552
1553         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1554         if (!ntds_guid_new) {
1555                 goto failed;
1556         }
1557
1558         *ntds_guid_new = *ntds_guid_in;
1559
1560         /* cache the domain_sid in the ldb */
1561         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1562                 goto failed;
1563         }
1564
1565         talloc_steal(ldb, ntds_guid_new);
1566         talloc_free(tmp_ctx);
1567         talloc_free(ntds_guid_old);
1568
1569         return true;
1570
1571 failed:
1572         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1573         talloc_free(tmp_ctx);
1574         return false;
1575 }
1576
1577 /*
1578   work out the server dn for the current open ldb
1579 */
1580 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1581 {
1582         return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1583 }
1584
1585 /*
1586   work out the server dn for the current open ldb
1587 */
1588 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1589 {
1590         struct ldb_dn *server_dn;
1591         struct ldb_dn *servers_dn;
1592         struct ldb_dn *server_site_dn;
1593
1594         /* TODO: there must be a saner way to do this!! */
1595         server_dn = samdb_server_dn(ldb, mem_ctx);
1596         if (!server_dn) return NULL;
1597
1598         servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1599         talloc_free(server_dn);
1600         if (!servers_dn) return NULL;
1601
1602         server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1603         talloc_free(servers_dn);
1604
1605         return server_site_dn;
1606 }
1607
1608 /*
1609   find the site name from a computers DN record
1610  */
1611 int samdb_find_site_for_computer(struct ldb_context *ldb,
1612                                  TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1613                                  const char **site_name)
1614 {
1615         int ret;
1616         struct ldb_dn *dn;
1617         const struct ldb_val *rdn_val;
1618
1619         *site_name = NULL;
1620
1621         ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1622         if (ret != LDB_SUCCESS) {
1623                 return ret;
1624         }
1625
1626         if (!ldb_dn_remove_child_components(dn, 2)) {
1627                 talloc_free(dn);
1628                 return LDB_ERR_INVALID_DN_SYNTAX;
1629         }
1630         rdn_val = ldb_dn_get_rdn_val(dn);
1631         (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1632         talloc_free(dn);
1633         if (!*site_name) {
1634                 return LDB_ERR_OPERATIONS_ERROR;
1635         }
1636         return LDB_SUCCESS;
1637 }
1638
1639 /*
1640   find the NTDS GUID from a computers DN record
1641  */
1642 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1643                                      struct GUID *ntds_guid)
1644 {
1645         int ret;
1646         struct ldb_dn *dn;
1647
1648         *ntds_guid = GUID_zero();
1649
1650         ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1651         if (ret != LDB_SUCCESS) {
1652                 return ret;
1653         }
1654
1655         if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1656                 talloc_free(dn);
1657                 return LDB_ERR_OPERATIONS_ERROR;
1658         }
1659
1660         ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1661         talloc_free(dn);
1662         return ret;
1663 }
1664
1665 /*
1666   find a 'reference' DN that points at another object
1667   (eg. serverReference, rIDManagerReference etc)
1668  */
1669 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1670                        const char *attribute, struct ldb_dn **dn)
1671 {
1672         const char *attrs[2];
1673         struct ldb_result *res;
1674         int ret;
1675
1676         attrs[0] = attribute;
1677         attrs[1] = NULL;
1678
1679         ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY, NULL);
1680         if (ret != LDB_SUCCESS) {
1681                 return ret;
1682         }
1683
1684         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1685         if (!*dn) {
1686                 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1687                         ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1688                                                ldb_dn_get_linearized(base));
1689                 } else {
1690                         ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1691                                                ldb_dn_get_linearized(base));
1692                 }
1693                 talloc_free(res);
1694                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1695         }
1696
1697         talloc_free(res);
1698         return LDB_SUCCESS;
1699 }
1700
1701 /*
1702   find our machine account via the serverReference attribute in the
1703   server DN
1704  */
1705 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1706 {
1707         struct ldb_dn *server_dn;
1708         int ret;
1709
1710         server_dn = samdb_server_dn(ldb, mem_ctx);
1711         if (server_dn == NULL) {
1712                 return LDB_ERR_NO_SUCH_OBJECT;
1713         }
1714
1715         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1716         talloc_free(server_dn);
1717
1718         return ret;
1719 }
1720
1721 /*
1722   find the RID Manager$ DN via the rIDManagerReference attribute in the
1723   base DN
1724  */
1725 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1726 {
1727         return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1728                                   "rIDManagerReference", dn);
1729 }
1730
1731 /*
1732   find the RID Set DN via the rIDSetReferences attribute in our
1733   machine account DN
1734  */
1735 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1736 {
1737         struct ldb_dn *server_ref_dn;
1738         int ret;
1739
1740         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1741         if (ret != LDB_SUCCESS) {
1742                 return ret;
1743         }
1744         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1745         talloc_free(server_ref_dn);
1746         return ret;
1747 }
1748
1749 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1750 {
1751         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1752                                                                             mem_ctx));
1753
1754         if (val == NULL) {
1755                 return NULL;
1756         }
1757
1758         return (const char *) val->data;
1759 }
1760
1761 /*
1762  * Finds the client site by using the client's IP address.
1763  * The "subnet_name" returns the name of the subnet if parameter != NULL
1764  */
1765 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1766                                    const char *ip_address, char **subnet_name)
1767 {
1768         const char *attrs[] = { "cn", "siteObject", NULL };
1769         struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1770         struct ldb_result *res;
1771         const struct ldb_val *val;
1772         const char *site_name = NULL, *l_subnet_name = NULL;
1773         const char *allow_list[2] = { NULL, NULL };
1774         unsigned int i, count;
1775         int cnt, ret;
1776
1777         /*
1778          * if we don't have a client ip e.g. ncalrpc
1779          * the server site is the client site
1780          */
1781         if (ip_address == NULL) {
1782                 return samdb_server_site_name(ldb, mem_ctx);
1783         }
1784
1785         sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1786         if (sites_container_dn == NULL) {
1787                 return NULL;
1788         }
1789
1790         subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1791         if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1792                 talloc_free(sites_container_dn);
1793                 talloc_free(subnets_dn);
1794                 return NULL;
1795         }
1796
1797         ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1798                          attrs, NULL);
1799         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1800                 count = 0;
1801         } else if (ret != LDB_SUCCESS) {
1802                 talloc_free(sites_container_dn);
1803                 talloc_free(subnets_dn);
1804                 return NULL;
1805         } else {
1806                 count = res->count;
1807         }
1808
1809         for (i = 0; i < count; i++) {
1810                 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1811                                                             NULL);
1812
1813                 allow_list[0] = l_subnet_name;
1814
1815                 if (allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1816                         sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1817                                                            res->msgs[i],
1818                                                            "siteObject");
1819                         if (sites_dn == NULL) {
1820                                 /* No reference, maybe another subnet matches */
1821                                 continue;
1822                         }
1823
1824                         /* "val" cannot be NULL here since "sites_dn" != NULL */
1825                         val = ldb_dn_get_rdn_val(sites_dn);
1826                         site_name = talloc_strdup(mem_ctx,
1827                                                   (const char *) val->data);
1828
1829                         talloc_free(sites_dn);
1830
1831                         break;
1832                 }
1833         }
1834
1835         if (site_name == NULL) {
1836                 /* This is the Windows Server fallback rule: when no subnet
1837                  * exists and we have only one site available then use it (it
1838                  * is for sure the same as our server site). If more sites do
1839                  * exist then we don't know which one to use and set the site
1840                  * name to "". */
1841                 cnt = samdb_search_count(ldb, sites_container_dn,
1842                                          "(objectClass=site)");
1843                 if (cnt == 1) {
1844                         site_name = samdb_server_site_name(ldb, mem_ctx);
1845                 } else {
1846                         site_name = talloc_strdup(mem_ctx, "");
1847                 }
1848                 l_subnet_name = NULL;
1849         }
1850
1851         if (subnet_name != NULL) {
1852                 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1853         }
1854
1855         talloc_free(sites_container_dn);
1856         talloc_free(subnets_dn);
1857         talloc_free(res);
1858
1859         return site_name;
1860 }
1861
1862 /*
1863   work out if we are the PDC for the domain of the current open ldb
1864 */
1865 bool samdb_is_pdc(struct ldb_context *ldb)
1866 {
1867         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1868         int ret;
1869         struct ldb_result *dom_res;
1870         TALLOC_CTX *tmp_ctx;
1871         bool is_pdc;
1872         struct ldb_dn *pdc;
1873
1874         tmp_ctx = talloc_new(ldb);
1875         if (tmp_ctx == NULL) {
1876                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1877                 return false;
1878         }
1879
1880         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1881         if (ret != LDB_SUCCESS) {
1882                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1883                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1884                          ldb_errstring(ldb)));
1885                 goto failed;
1886         }
1887         if (dom_res->count != 1) {
1888                 goto failed;
1889         }
1890
1891         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1892
1893         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1894                 is_pdc = true;
1895         } else {
1896                 is_pdc = false;
1897         }
1898
1899         talloc_free(tmp_ctx);
1900
1901         return is_pdc;
1902
1903 failed:
1904         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1905         talloc_free(tmp_ctx);
1906         return false;
1907 }
1908
1909 /*
1910   work out if we are a Global Catalog server for the domain of the current open ldb
1911 */
1912 bool samdb_is_gc(struct ldb_context *ldb)
1913 {
1914         const char *attrs[] = { "options", NULL };
1915         int ret, options;
1916         struct ldb_result *res;
1917         TALLOC_CTX *tmp_ctx;
1918
1919         tmp_ctx = talloc_new(ldb);
1920         if (tmp_ctx == NULL) {
1921                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1922                 return false;
1923         }
1924
1925         /* Query cn=ntds settings,.... */
1926         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1927         if (ret != LDB_SUCCESS) {
1928                 talloc_free(tmp_ctx);
1929                 return false;
1930         }
1931         if (res->count != 1) {
1932                 talloc_free(tmp_ctx);
1933                 return false;
1934         }
1935
1936         options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1937         talloc_free(tmp_ctx);
1938
1939         /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1940         if (options & 0x000000001) {
1941                 return true;
1942         }
1943         return false;
1944 }
1945
1946 /* Find a domain object in the parents of a particular DN.  */
1947 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1948                                    struct ldb_dn **parent_dn, const char **errstring)
1949 {
1950         TALLOC_CTX *local_ctx;
1951         struct ldb_dn *sdn = dn;
1952         struct ldb_result *res = NULL;
1953         int ret = LDB_SUCCESS;
1954         const char *attrs[] = { NULL };
1955
1956         local_ctx = talloc_new(mem_ctx);
1957         if (local_ctx == NULL) return ldb_oom(ldb);
1958
1959         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1960                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1961                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1962                 if (ret == LDB_SUCCESS) {
1963                         if (res->count == 1) {
1964                                 break;
1965                         }
1966                 } else {
1967                         break;
1968                 }
1969         }
1970
1971         if (ret != LDB_SUCCESS) {
1972                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1973                                              ldb_dn_get_linearized(dn),
1974                                              ldb_dn_get_linearized(sdn),
1975                                              ldb_errstring(ldb));
1976                 talloc_free(local_ctx);
1977                 return ret;
1978         }
1979         if (res->count != 1) {
1980                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1981                                              ldb_dn_get_linearized(dn));
1982                 DEBUG(0,(__location__ ": %s\n", *errstring));
1983                 talloc_free(local_ctx);
1984                 return LDB_ERR_CONSTRAINT_VIOLATION;
1985         }
1986
1987         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1988         talloc_free(local_ctx);
1989         return ret;
1990 }
1991
1992
1993 /*
1994  * Performs checks on a user password (plaintext UNIX format - attribute
1995  * "password"). The remaining parameters have to be extracted from the domain
1996  * object in the AD.
1997  *
1998  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1999  */
2000 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
2001                                                 const uint32_t pwdProperties,
2002                                                 const uint32_t minPwdLength)
2003 {
2004         /* checks if the "minPwdLength" property is satisfied */
2005         if (minPwdLength > password->length)
2006                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
2007
2008         /* checks the password complexity */
2009         if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
2010                         && (password->data != NULL)
2011                         && (!check_password_quality((const char *) password->data)))
2012                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
2013
2014         return SAMR_VALIDATION_STATUS_SUCCESS;
2015 }
2016
2017 /*
2018  * Callback for "samdb_set_password" password change
2019  */
2020 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
2021 {
2022         int ret;
2023
2024         if (!ares) {
2025                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2026         }
2027
2028         if (ares->error != LDB_SUCCESS) {
2029                 ret = ares->error;
2030                 req->context = talloc_steal(req,
2031                                             ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2032                 talloc_free(ares);
2033                 return ldb_request_done(req, ret);
2034         }
2035
2036         if (ares->type != LDB_REPLY_DONE) {
2037                 talloc_free(ares);
2038                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
2039         }
2040
2041         req->context = talloc_steal(req,
2042                                     ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
2043         talloc_free(ares);
2044         return ldb_request_done(req, LDB_SUCCESS);
2045 }
2046
2047 /*
2048  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2049  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2050  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2051  * user change or not. The "rejectReason" gives some more informations if the
2052  * change failed.
2053  *
2054  * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2055  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
2056  */
2057 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2058                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
2059                             const DATA_BLOB *new_password,
2060                             const struct samr_Password *lmNewHash,
2061                             const struct samr_Password *ntNewHash,
2062                             const struct samr_Password *lmOldHash,
2063                             const struct samr_Password *ntOldHash,
2064                             enum samPwdChangeReason *reject_reason,
2065                             struct samr_DomInfo1 **_dominfo)
2066 {
2067         struct ldb_message *msg;
2068         struct ldb_message_element *el;
2069         struct ldb_request *req;
2070         struct dsdb_control_password_change_status *pwd_stat = NULL;
2071         int ret;
2072         NTSTATUS status = NT_STATUS_OK;
2073
2074 #define CHECK_RET(x) \
2075         if (x != LDB_SUCCESS) { \
2076                 talloc_free(msg); \
2077                 return NT_STATUS_NO_MEMORY; \
2078         }
2079
2080         msg = ldb_msg_new(mem_ctx);
2081         if (msg == NULL) {
2082                 return NT_STATUS_NO_MEMORY;
2083         }
2084         msg->dn = user_dn;
2085         if ((new_password != NULL)
2086                         && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2087                 /* we have the password as plaintext UTF16 */
2088                 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2089                                             new_password, NULL));
2090                 el = ldb_msg_find_element(msg, "clearTextPassword");
2091                 el->flags = LDB_FLAG_MOD_REPLACE;
2092         } else if ((new_password == NULL)
2093                         && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2094                 /* we have a password as LM and/or NT hash */
2095                 if (lmNewHash != NULL) {
2096                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2097                                 "dBCSPwd", lmNewHash));
2098                         el = ldb_msg_find_element(msg, "dBCSPwd");
2099                         el->flags = LDB_FLAG_MOD_REPLACE;
2100                 }
2101                 if (ntNewHash != NULL) {
2102                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2103                                 "unicodePwd", ntNewHash));
2104                         el = ldb_msg_find_element(msg, "unicodePwd");
2105                         el->flags = LDB_FLAG_MOD_REPLACE;
2106                 }
2107         } else {
2108                 /* the password wasn't specified correctly */
2109                 talloc_free(msg);
2110                 return NT_STATUS_INVALID_PARAMETER;
2111         }
2112
2113         /* build modify request */
2114         ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2115                                 samdb_set_password_callback, NULL);
2116         if (ret != LDB_SUCCESS) {
2117                 talloc_free(msg);
2118                 return NT_STATUS_NO_MEMORY;
2119         }
2120
2121         /* A password change operation */
2122         if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2123                 struct dsdb_control_password_change *change;
2124
2125                 change = talloc(req, struct dsdb_control_password_change);
2126                 if (change == NULL) {
2127                         talloc_free(req);
2128                         talloc_free(msg);
2129                         return NT_STATUS_NO_MEMORY;
2130                 }
2131
2132                 change->old_nt_pwd_hash = ntOldHash;
2133                 change->old_lm_pwd_hash = lmOldHash;
2134
2135                 ret = ldb_request_add_control(req,
2136                                               DSDB_CONTROL_PASSWORD_CHANGE_OID,
2137                                               true, change);
2138                 if (ret != LDB_SUCCESS) {
2139                         talloc_free(req);
2140                         talloc_free(msg);
2141                         return NT_STATUS_NO_MEMORY;
2142                 }
2143         }
2144         ret = ldb_request_add_control(req,
2145                                       DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2146                                       true, NULL);
2147         if (ret != LDB_SUCCESS) {
2148                 talloc_free(req);
2149                 talloc_free(msg);
2150                 return NT_STATUS_NO_MEMORY;
2151         }
2152         ret = ldb_request_add_control(req,
2153                                       DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2154                                       true, NULL);
2155         if (ret != LDB_SUCCESS) {
2156                 talloc_free(req);
2157                 talloc_free(msg);
2158                 return NT_STATUS_NO_MEMORY;
2159         }
2160
2161         ret = dsdb_autotransaction_request(ldb, req);
2162
2163         if (req->context != NULL) {
2164                 pwd_stat = talloc_steal(mem_ctx,
2165                                         ((struct ldb_control *)req->context)->data);
2166         }
2167
2168         talloc_free(req);
2169         talloc_free(msg);
2170
2171         /* Sets the domain info (if requested) */
2172         if (_dominfo != NULL) {
2173                 struct samr_DomInfo1 *dominfo;
2174
2175                 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2176                 if (dominfo == NULL) {
2177                         return NT_STATUS_NO_MEMORY;
2178                 }
2179
2180                 if (pwd_stat != NULL) {
2181                         dominfo->min_password_length     = pwd_stat->domain_data.minPwdLength;
2182                         dominfo->password_properties     = pwd_stat->domain_data.pwdProperties;
2183                         dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2184                         dominfo->max_password_age        = pwd_stat->domain_data.maxPwdAge;
2185                         dominfo->min_password_age        = pwd_stat->domain_data.minPwdAge;
2186                 }
2187
2188                 *_dominfo = dominfo;
2189         }
2190
2191         if (reject_reason != NULL) {
2192                 if (pwd_stat != NULL) {
2193                         *reject_reason = pwd_stat->reject_reason;
2194                 } else {
2195                         *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2196                 }
2197         }
2198
2199         if (pwd_stat != NULL) {
2200                 talloc_free(pwd_stat);
2201         }
2202
2203         if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2204                 const char *errmsg = ldb_errstring(ldb);
2205                 char *endptr = NULL;
2206                 WERROR werr = WERR_GENERAL_FAILURE;
2207                 status = NT_STATUS_UNSUCCESSFUL;
2208                 if (errmsg != NULL) {
2209                         werr = W_ERROR(strtol(errmsg, &endptr, 16));
2210                 }
2211                 if (endptr != errmsg) {
2212                         if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2213                                 status = NT_STATUS_WRONG_PASSWORD;
2214                         }
2215                         if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2216                                 status = NT_STATUS_PASSWORD_RESTRICTION;
2217                         }
2218                 }
2219         } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2220                 /* don't let the caller know if an account doesn't exist */
2221                 status = NT_STATUS_WRONG_PASSWORD;
2222         } else if (ret != LDB_SUCCESS) {
2223                 status = NT_STATUS_UNSUCCESSFUL;
2224         }
2225
2226         return status;
2227 }
2228
2229 /*
2230  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2231  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2232  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2233  * user change or not. The "rejectReason" gives some more informations if the
2234  * change failed.
2235  *
2236  * This wrapper function for "samdb_set_password" takes a SID as input rather
2237  * than a user DN.
2238  *
2239  * This call encapsulates a new LDB transaction for changing the password;
2240  * therefore the user hasn't to start a new one.
2241  *
2242  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2243  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2244  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2245  *   NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2246  */
2247 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2248                                 const struct dom_sid *user_sid,
2249                                 const DATA_BLOB *new_password,
2250                                 const struct samr_Password *lmNewHash,
2251                                 const struct samr_Password *ntNewHash,
2252                                 const struct samr_Password *lmOldHash,
2253                                 const struct samr_Password *ntOldHash,
2254                                 enum samPwdChangeReason *reject_reason,
2255                                 struct samr_DomInfo1 **_dominfo) 
2256 {
2257         NTSTATUS nt_status;
2258         struct ldb_dn *user_dn;
2259         int ret;
2260
2261         ret = ldb_transaction_start(ldb);
2262         if (ret != LDB_SUCCESS) {
2263                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2264                 return NT_STATUS_TRANSACTION_ABORTED;
2265         }
2266
2267         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2268                                   "(&(objectSid=%s)(objectClass=user))", 
2269                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2270         if (!user_dn) {
2271                 ldb_transaction_cancel(ldb);
2272                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2273                           dom_sid_string(mem_ctx, user_sid)));
2274                 return NT_STATUS_NO_SUCH_USER;
2275         }
2276
2277         nt_status = samdb_set_password(ldb, mem_ctx,
2278                                        user_dn, NULL,
2279                                        new_password,
2280                                        lmNewHash, ntNewHash,
2281                                        lmOldHash, ntOldHash,
2282                                        reject_reason, _dominfo);
2283         if (!NT_STATUS_IS_OK(nt_status)) {
2284                 ldb_transaction_cancel(ldb);
2285                 talloc_free(user_dn);
2286                 return nt_status;
2287         }
2288
2289         ret = ldb_transaction_commit(ldb);
2290         if (ret != LDB_SUCCESS) {
2291                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2292                          ldb_dn_get_linearized(user_dn),
2293                          ldb_errstring(ldb)));
2294                 talloc_free(user_dn);
2295                 return NT_STATUS_TRANSACTION_ABORTED;
2296         }
2297
2298         talloc_free(user_dn);
2299         return NT_STATUS_OK;
2300 }
2301
2302
2303 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2304                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2305 {
2306         struct ldb_message *msg;
2307         struct ldb_dn *basedn;
2308         char *sidstr;
2309         int ret;
2310
2311         sidstr = dom_sid_string(mem_ctx, sid);
2312         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2313
2314         /* We might have to create a ForeignSecurityPrincipal, even if this user
2315          * is in our own domain */
2316
2317         msg = ldb_msg_new(sidstr);
2318         if (msg == NULL) {
2319                 talloc_free(sidstr);
2320                 return NT_STATUS_NO_MEMORY;
2321         }
2322
2323         ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2324                                 ldb_get_default_basedn(sam_ctx),
2325                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2326                                 &basedn);
2327         if (ret != LDB_SUCCESS) {
2328                 DEBUG(0, ("Failed to find DN for "
2329                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2330                 talloc_free(sidstr);
2331                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2332         }
2333
2334         /* add core elements to the ldb_message for the alias */
2335         msg->dn = basedn;
2336         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2337                 talloc_free(sidstr);
2338                 return NT_STATUS_NO_MEMORY;
2339         }
2340
2341         samdb_msg_add_string(sam_ctx, msg, msg,
2342                              "objectClass",
2343                              "foreignSecurityPrincipal");
2344
2345         /* create the alias */
2346         ret = ldb_add(sam_ctx, msg);
2347         if (ret != LDB_SUCCESS) {
2348                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2349                          "record %s: %s\n", 
2350                          ldb_dn_get_linearized(msg->dn),
2351                          ldb_errstring(sam_ctx)));
2352                 talloc_free(sidstr);
2353                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2354         }
2355
2356         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2357         talloc_free(sidstr);
2358
2359         return NT_STATUS_OK;
2360 }
2361
2362
2363 /*
2364   Find the DN of a domain, assuming it to be a dotted.dns name
2365 */
2366
2367 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2368 {
2369         unsigned int i;
2370         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2371         const char *binary_encoded;
2372         const char **split_realm;
2373         struct ldb_dn *dn;
2374
2375         if (!tmp_ctx) {
2376                 return NULL;
2377         }
2378
2379         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2380         if (!split_realm) {
2381                 talloc_free(tmp_ctx);
2382                 return NULL;
2383         }
2384         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2385         for (i=0; split_realm[i]; i++) {
2386                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2387                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2388                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2389                                   binary_encoded, ldb_dn_get_linearized(dn)));
2390                         talloc_free(tmp_ctx);
2391                         return NULL;
2392                 }
2393         }
2394         if (!ldb_dn_validate(dn)) {
2395                 DEBUG(2, ("Failed to validated DN %s\n",
2396                           ldb_dn_get_linearized(dn)));
2397                 talloc_free(tmp_ctx);
2398                 return NULL;
2399         }
2400         talloc_free(tmp_ctx);
2401         return dn;
2402 }
2403
2404 /*
2405   Find the DN of a domain, be it the netbios or DNS name 
2406 */
2407 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2408                                   const char *domain_name) 
2409 {
2410         const char * const domain_ref_attrs[] = {
2411                 "ncName", NULL
2412         };
2413         const char * const domain_ref2_attrs[] = {
2414                 NULL
2415         };
2416         struct ldb_result *res_domain_ref;
2417         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2418         /* find the domain's DN */
2419         int ret_domain = ldb_search(ldb, mem_ctx,
2420                                             &res_domain_ref, 
2421                                             samdb_partitions_dn(ldb, mem_ctx), 
2422                                             LDB_SCOPE_ONELEVEL, 
2423                                             domain_ref_attrs,
2424                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2425                                             escaped_domain);
2426         if (ret_domain != LDB_SUCCESS) {
2427                 return NULL;
2428         }
2429
2430         if (res_domain_ref->count == 0) {
2431                 ret_domain = ldb_search(ldb, mem_ctx,
2432                                                 &res_domain_ref, 
2433                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2434                                                 LDB_SCOPE_BASE,
2435                                                 domain_ref2_attrs,
2436                                                 "(objectclass=domain)");
2437                 if (ret_domain != LDB_SUCCESS) {
2438                         return NULL;
2439                 }
2440
2441                 if (res_domain_ref->count == 1) {
2442                         return res_domain_ref->msgs[0]->dn;
2443                 }
2444                 return NULL;
2445         }
2446
2447         if (res_domain_ref->count > 1) {
2448                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2449                          ret_domain, domain_name));
2450                 return NULL;
2451         }
2452
2453         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2454
2455 }
2456
2457
2458 /*
2459   use a GUID to find a DN
2460  */
2461 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2462                          TALLOC_CTX *mem_ctx,
2463                          const struct GUID *guid, struct ldb_dn **dn)
2464 {
2465         int ret;
2466         struct ldb_result *res;
2467         const char *attrs[] = { NULL };
2468         char *guid_str = GUID_string(mem_ctx, guid);
2469
2470         if (!guid_str) {
2471                 return ldb_operr(ldb);
2472         }
2473
2474         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2475                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2476                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2477                           DSDB_SEARCH_ONE_ONLY,
2478                           "objectGUID=%s", guid_str);
2479         talloc_free(guid_str);
2480         if (ret != LDB_SUCCESS) {
2481                 return ret;
2482         }
2483
2484         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2485         talloc_free(res);
2486
2487         return LDB_SUCCESS;
2488 }
2489
2490 /*
2491   use a DN to find a GUID with a given attribute name
2492  */
2493 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2494                               struct ldb_dn *dn, const char *attribute,
2495                               struct GUID *guid)
2496 {
2497         int ret;
2498         struct ldb_result *res;
2499         const char *attrs[2];
2500         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2501
2502         attrs[0] = attribute;
2503         attrs[1] = NULL;
2504
2505         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2506                              DSDB_SEARCH_SHOW_DELETED |
2507                              DSDB_SEARCH_SHOW_RECYCLED);
2508         if (ret != LDB_SUCCESS) {
2509                 talloc_free(tmp_ctx);
2510                 return ret;
2511         }
2512         if (res->count < 1) {
2513                 talloc_free(tmp_ctx);
2514                 return LDB_ERR_NO_SUCH_OBJECT;
2515         }
2516         *guid = samdb_result_guid(res->msgs[0], attribute);
2517         talloc_free(tmp_ctx);
2518         return LDB_SUCCESS;
2519 }
2520
2521 /*
2522   use a DN to find a GUID
2523  */
2524 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2525                          struct ldb_dn *dn, struct GUID *guid)
2526 {
2527         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2528 }
2529
2530
2531
2532 /*
2533  adds the given GUID to the given ldb_message. This value is added
2534  for the given attr_name (may be either "objectGUID" or "parentGUID").
2535  */
2536 int dsdb_msg_add_guid(struct ldb_message *msg,
2537                 struct GUID *guid,
2538                 const char *attr_name)
2539 {
2540         int ret;
2541         struct ldb_val v;
2542         NTSTATUS status;
2543         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2544
2545         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2546         if (!NT_STATUS_IS_OK(status)) {
2547                 ret = LDB_ERR_OPERATIONS_ERROR;
2548                 goto done;
2549         }
2550
2551         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2552         if (ret != LDB_SUCCESS) {
2553                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2554                                          attr_name));
2555                 goto done;
2556         }
2557
2558         ret = LDB_SUCCESS;
2559
2560 done:
2561         talloc_free(tmp_ctx);
2562         return ret;
2563
2564 }
2565
2566
2567 /*
2568   use a DN to find a SID
2569  */
2570 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2571                         struct ldb_dn *dn, struct dom_sid *sid)
2572 {
2573         int ret;
2574         struct ldb_result *res;
2575         const char *attrs[] = { "objectSid", NULL };
2576         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2577         struct dom_sid *s;
2578
2579         ZERO_STRUCTP(sid);
2580
2581         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2582                              DSDB_SEARCH_SHOW_DELETED |
2583                              DSDB_SEARCH_SHOW_RECYCLED);
2584         if (ret != LDB_SUCCESS) {
2585                 talloc_free(tmp_ctx);
2586                 return ret;
2587         }
2588         if (res->count < 1) {
2589                 talloc_free(tmp_ctx);
2590                 return LDB_ERR_NO_SUCH_OBJECT;
2591         }
2592         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
2593         if (s == NULL) {
2594                 talloc_free(tmp_ctx);
2595                 return LDB_ERR_NO_SUCH_OBJECT;
2596         }
2597         *sid = *s;
2598         talloc_free(tmp_ctx);
2599         return LDB_SUCCESS;
2600 }
2601
2602 /*
2603   use a SID to find a DN
2604  */
2605 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
2606                         TALLOC_CTX *mem_ctx,
2607                         struct dom_sid *sid, struct ldb_dn **dn)
2608 {
2609         int ret;
2610         struct ldb_result *res;
2611         const char *attrs[] = { NULL };
2612         char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
2613
2614         if (!sid_str) {
2615                 return ldb_operr(ldb);
2616         }
2617
2618         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2619                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2620                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2621                           DSDB_SEARCH_ONE_ONLY,
2622                           "objectSid=%s", sid_str);
2623         talloc_free(sid_str);
2624         if (ret != LDB_SUCCESS) {
2625                 return ret;
2626         }
2627
2628         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2629         talloc_free(res);
2630
2631         return LDB_SUCCESS;
2632 }
2633
2634 /*
2635   load a repsFromTo blob list for a given partition GUID
2636   attr must be "repsFrom" or "repsTo"
2637  */
2638 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2639                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2640 {
2641         const char *attrs[] = { attr, NULL };
2642         struct ldb_result *res = NULL;
2643         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2644         unsigned int i;
2645         struct ldb_message_element *el;
2646
2647         *r = NULL;
2648         *count = 0;
2649
2650         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2651             res->count < 1) {
2652                 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2653                 talloc_free(tmp_ctx);
2654                 return WERR_DS_DRA_INTERNAL_ERROR;
2655         }
2656
2657         el = ldb_msg_find_element(res->msgs[0], attr);
2658         if (el == NULL) {
2659                 /* it's OK to be empty */
2660                 talloc_free(tmp_ctx);
2661                 return WERR_OK;
2662         }
2663
2664         *count = el->num_values;
2665         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2666         if (*r == NULL) {
2667                 talloc_free(tmp_ctx);
2668                 return WERR_DS_DRA_INTERNAL_ERROR;
2669         }
2670
2671         for (i=0; i<(*count); i++) {
2672                 enum ndr_err_code ndr_err;
2673                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2674                                                mem_ctx, 
2675                                                &(*r)[i], 
2676                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2677                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2678                         talloc_free(tmp_ctx);
2679                         return WERR_DS_DRA_INTERNAL_ERROR;
2680                 }
2681         }
2682
2683         talloc_free(tmp_ctx);
2684         
2685         return WERR_OK;
2686 }
2687
2688 /*
2689   save the repsFromTo blob list for a given partition GUID
2690   attr must be "repsFrom" or "repsTo"
2691  */
2692 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2693                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2694 {
2695         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2696         struct ldb_message *msg;
2697         struct ldb_message_element *el;
2698         unsigned int i;
2699
2700         msg = ldb_msg_new(tmp_ctx);
2701         msg->dn = dn;
2702         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2703                 goto failed;
2704         }
2705
2706         el->values = talloc_array(msg, struct ldb_val, count);
2707         if (!el->values) {
2708                 goto failed;
2709         }
2710
2711         for (i=0; i<count; i++) {
2712                 struct ldb_val v;
2713                 enum ndr_err_code ndr_err;
2714
2715                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, 
2716                                                &r[i], 
2717                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2718                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2719                         goto failed;
2720                 }
2721
2722                 el->num_values++;
2723                 el->values[i] = v;
2724         }
2725
2726         if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2727                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2728                 goto failed;
2729         }
2730
2731         talloc_free(tmp_ctx);
2732         
2733         return WERR_OK;
2734
2735 failed:
2736         talloc_free(tmp_ctx);
2737         return WERR_DS_DRA_INTERNAL_ERROR;
2738 }
2739
2740
2741 /*
2742   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2743   object for a partition
2744  */
2745 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2746                                 uint64_t *uSN, uint64_t *urgent_uSN)
2747 {
2748         struct ldb_request *req;
2749         int ret;
2750         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2751         struct dsdb_control_current_partition *p_ctrl;
2752         struct ldb_result *res;
2753
2754         res = talloc_zero(tmp_ctx, struct ldb_result);
2755         if (!res) {
2756                 talloc_free(tmp_ctx);
2757                 return ldb_oom(ldb);
2758         }
2759
2760         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2761                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2762                                    LDB_SCOPE_BASE,
2763                                    NULL, NULL,
2764                                    NULL,
2765                                    res, ldb_search_default_callback,
2766                                    NULL);
2767         if (ret != LDB_SUCCESS) {
2768                 talloc_free(tmp_ctx);
2769                 return ret;
2770         }
2771
2772         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2773         if (p_ctrl == NULL) {
2774                 talloc_free(tmp_ctx);
2775                 return ldb_oom(ldb);
2776         }
2777         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2778         p_ctrl->dn = dn;
2779         
2780         ret = ldb_request_add_control(req,
2781                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2782                                       false, p_ctrl);
2783         if (ret != LDB_SUCCESS) {
2784                 talloc_free(tmp_ctx);
2785                 return ret;
2786         }
2787         
2788         /* Run the new request */
2789         ret = ldb_request(ldb, req);
2790         
2791         if (ret == LDB_SUCCESS) {
2792                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2793         }
2794
2795         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2796                 /* it hasn't been created yet, which means
2797                    an implicit value of zero */
2798                 *uSN = 0;
2799                 talloc_free(tmp_ctx);
2800                 return LDB_SUCCESS;
2801         }
2802
2803         if (ret != LDB_SUCCESS) {
2804                 talloc_free(tmp_ctx);
2805                 return ret;
2806         }
2807
2808         if (res->count < 1) {
2809                 *uSN = 0;
2810                 if (urgent_uSN) {
2811                         *urgent_uSN = 0;
2812                 }
2813         } else {
2814                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2815                 if (urgent_uSN) {
2816                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2817                 }
2818         }
2819
2820         talloc_free(tmp_ctx);
2821
2822         return LDB_SUCCESS;     
2823 }
2824
2825 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2826                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2827 {
2828         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2829 }
2830
2831 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2832                                     const struct drsuapi_DsReplicaCursor *c2)
2833 {
2834         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2835 }
2836
2837
2838 /*
2839   see if a computer identified by its invocationId is a RODC
2840 */
2841 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
2842 {
2843         /* 1) find the DN for this servers NTDSDSA object
2844            2) search for the msDS-isRODC attribute
2845            3) if not present then not a RODC
2846            4) if present and TRUE then is a RODC
2847         */
2848         struct ldb_dn *config_dn;
2849         const char *attrs[] = { "msDS-isRODC", NULL };
2850         int ret;
2851         struct ldb_result *res;
2852         TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
2853
2854         config_dn = ldb_get_config_basedn(sam_ctx);
2855         if (!config_dn) {
2856                 talloc_free(tmp_ctx);
2857                 return ldb_operr(sam_ctx);
2858         }
2859
2860         ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
2861                           DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
2862
2863         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2864                 *is_rodc = false;
2865                 talloc_free(tmp_ctx);
2866                 return LDB_SUCCESS;
2867         }
2868
2869         if (ret != LDB_SUCCESS) {
2870                 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
2871                          GUID_string(tmp_ctx, objectGUID)));
2872                 *is_rodc = false;
2873                 talloc_free(tmp_ctx);
2874                 return ret;
2875         }
2876
2877         ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
2878         *is_rodc = (ret == 1);
2879
2880         talloc_free(tmp_ctx);
2881         return LDB_SUCCESS;
2882 }
2883
2884
2885 /*
2886   see if we are a RODC
2887 */
2888 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
2889 {
2890         const struct GUID *objectGUID;
2891         int ret;
2892         bool *cached;
2893
2894         /* see if we have a cached copy */
2895         cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
2896         if (cached) {
2897                 *am_rodc = *cached;
2898                 return LDB_SUCCESS;
2899         }
2900
2901         objectGUID = samdb_ntds_objectGUID(sam_ctx);
2902         if (!objectGUID) {
2903                 return ldb_operr(sam_ctx);
2904         }
2905
2906         ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
2907         if (ret != LDB_SUCCESS) {
2908                 return ret;
2909         }
2910
2911         cached = talloc(sam_ctx, bool);
2912         if (cached == NULL) {
2913                 return ldb_oom(sam_ctx);
2914         }
2915         *cached = *am_rodc;
2916
2917         ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
2918         if (ret != LDB_SUCCESS) {
2919                 talloc_free(cached);
2920                 return ldb_operr(sam_ctx);
2921         }
2922
2923         return LDB_SUCCESS;
2924 }
2925
2926 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
2927 {
2928         TALLOC_CTX *tmp_ctx;
2929         bool *cached;
2930
2931         tmp_ctx = talloc_new(ldb);
2932         if (tmp_ctx == NULL) {
2933                 goto failed;
2934         }
2935
2936         cached = talloc(tmp_ctx, bool);
2937         if (!cached) {
2938                 goto failed;
2939         }
2940
2941         *cached = am_rodc;
2942         if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
2943                 goto failed;
2944         }
2945
2946         talloc_steal(ldb, cached);
2947         talloc_free(tmp_ctx);
2948         return true;
2949
2950 failed:
2951         DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
2952         talloc_free(tmp_ctx);
2953         return false;
2954 }
2955
2956
2957 /*
2958   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2959
2960   flags are DS_NTDS_OPTION_*
2961 */
2962 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2963 {
2964         TALLOC_CTX *tmp_ctx;
2965         const char *attrs[] = { "options", NULL };
2966         int ret;
2967         struct ldb_result *res;
2968
2969         tmp_ctx = talloc_new(ldb);
2970         if (tmp_ctx == NULL) {
2971                 goto failed;
2972         }
2973
2974         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2975         if (ret != LDB_SUCCESS) {
2976                 goto failed;
2977         }
2978
2979         if (res->count != 1) {
2980                 goto failed;
2981         }
2982
2983         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
2984
2985         talloc_free(tmp_ctx);
2986
2987         return LDB_SUCCESS;
2988
2989 failed:
2990         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
2991         talloc_free(tmp_ctx);
2992         return LDB_ERR_NO_SUCH_OBJECT;
2993 }
2994
2995 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
2996 {
2997         const char *attrs[] = { "objectCategory", NULL };
2998         int ret;
2999         struct ldb_result *res;
3000
3001         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
3002         if (ret != LDB_SUCCESS) {
3003                 goto failed;
3004         }
3005
3006         if (res->count != 1) {
3007                 goto failed;
3008         }
3009
3010         return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3011
3012 failed:
3013         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3014         return NULL;
3015 }
3016
3017 /*
3018  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3019  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3020  */
3021 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3022 {
3023         char **tokens, *ret;
3024         size_t i;
3025
3026         tokens = str_list_make(mem_ctx, cn, " -_");
3027         if (tokens == NULL)
3028                 return NULL;
3029
3030         /* "tolower()" and "toupper()" should also work properly on 0x00 */
3031         tokens[0][0] = tolower(tokens[0][0]);
3032         for (i = 1; i < str_list_length((const char **)tokens); i++)
3033                 tokens[i][0] = toupper(tokens[i][0]);
3034
3035         ret = talloc_strdup(mem_ctx, tokens[0]);
3036         for (i = 1; i < str_list_length((const char **)tokens); i++)
3037                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3038
3039         talloc_free(tokens);
3040
3041         return ret;
3042 }
3043
3044 /*
3045  * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3046  */
3047 int dsdb_functional_level(struct ldb_context *ldb)
3048 {
3049         int *domainFunctionality =
3050                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3051         if (!domainFunctionality) {
3052                 /* this is expected during initial provision */
3053                 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3054                 return DS_DOMAIN_FUNCTION_2000;
3055         }
3056         return *domainFunctionality;
3057 }
3058
3059 /*
3060  * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3061  */
3062 int dsdb_forest_functional_level(struct ldb_context *ldb)
3063 {
3064         int *forestFunctionality =
3065                 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3066         if (!forestFunctionality) {
3067                 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3068                 return DS_DOMAIN_FUNCTION_2000;
3069         }
3070         return *forestFunctionality;
3071 }
3072
3073 /*
3074   set a GUID in an extended DN structure
3075  */
3076 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3077 {
3078         struct ldb_val v;
3079         NTSTATUS status;
3080         int ret;
3081
3082         status = GUID_to_ndr_blob(guid, dn, &v);
3083         if (!NT_STATUS_IS_OK(status)) {
3084                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3085         }
3086
3087         ret = ldb_dn_set_extended_component(dn, component_name, &v);
3088         data_blob_free(&v);
3089         return ret;
3090 }
3091
3092 /*
3093   return a GUID from a extended DN structure
3094  */
3095 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3096 {
3097         const struct ldb_val *v;
3098
3099         v = ldb_dn_get_extended_component(dn, component_name);
3100         if (v == NULL) {
3101                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3102         }
3103
3104         return GUID_from_ndr_blob(v, guid);
3105 }
3106
3107 /*
3108   return a uint64_t from a extended DN structure
3109  */
3110 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3111 {
3112         const struct ldb_val *v;
3113         char *s;
3114
3115         v = ldb_dn_get_extended_component(dn, component_name);
3116         if (v == NULL) {
3117                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3118         }
3119         s = talloc_strndup(dn, (const char *)v->data, v->length);
3120         NT_STATUS_HAVE_NO_MEMORY(s);
3121
3122         *val = strtoull(s, NULL, 0);
3123
3124         talloc_free(s);
3125         return NT_STATUS_OK;
3126 }
3127
3128 /*
3129   return a NTTIME from a extended DN structure
3130  */
3131 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3132 {
3133         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3134 }
3135
3136 /*
3137   return a uint32_t from a extended DN structure
3138  */
3139 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3140 {
3141         const struct ldb_val *v;
3142         char *s;
3143
3144         v = ldb_dn_get_extended_component(dn, component_name);
3145         if (v == NULL) {
3146                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3147         }
3148
3149         s = talloc_strndup(dn, (const char *)v->data, v->length);
3150         NT_STATUS_HAVE_NO_MEMORY(s);
3151
3152         *val = strtoul(s, NULL, 0);
3153
3154         talloc_free(s);
3155         return NT_STATUS_OK;
3156 }
3157
3158 /*
3159   return a dom_sid from a extended DN structure
3160  */
3161 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3162 {
3163         const struct ldb_val *sid_blob;
3164         struct TALLOC_CTX *tmp_ctx;
3165         enum ndr_err_code ndr_err;
3166
3167         sid_blob = ldb_dn_get_extended_component(dn, component_name);
3168         if (!sid_blob) {
3169                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3170         }
3171
3172         tmp_ctx = talloc_new(NULL);
3173
3174         ndr_err = ndr_pull_struct_blob_all(sid_blob, tmp_ctx, sid,
3175                                            (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3176         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3177                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3178                 talloc_free(tmp_ctx);
3179                 return status;
3180         }
3181
3182         talloc_free(tmp_ctx);
3183         return NT_STATUS_OK;
3184 }
3185
3186
3187 /*
3188   return RMD_FLAGS directly from a ldb_dn
3189   returns 0 if not found
3190  */
3191 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3192 {
3193         const struct ldb_val *v;
3194         char buf[32];
3195         v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
3196         if (!v || v->length > sizeof(buf)-1) return 0;
3197         strncpy(buf, (const char *)v->data, v->length);
3198         buf[v->length] = 0;
3199         return strtoul(buf, NULL, 10);
3200 }
3201
3202 /*
3203   return RMD_FLAGS directly from a ldb_val for a DN
3204   returns 0 if RMD_FLAGS is not found
3205  */
3206 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3207 {
3208         const char *p;
3209         uint32_t flags;
3210         char *end;
3211
3212         if (val->length < 13) {
3213                 return 0;
3214         }
3215         p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3216         if (!p) {
3217                 return 0;
3218         }
3219         flags = strtoul(p+11, &end, 10);
3220         if (!end || *end != '>') {
3221                 /* it must end in a > */
3222                 return 0;
3223         }
3224         return flags;
3225 }
3226
3227 /*
3228   return true if a ldb_val containing a DN in storage form is deleted
3229  */
3230 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3231 {
3232         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3233 }
3234
3235 /*
3236   return true if a ldb_val containing a DN in storage form is
3237   in the upgraded w2k3 linked attribute format
3238  */
3239 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3240 {
3241         return memmem(val->data, val->length, "<RMD_ADDTIME=", 13) != NULL;
3242 }
3243
3244 /*
3245   return a DN for a wellknown GUID
3246  */
3247 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3248                       struct ldb_dn *nc_root, const char *wk_guid,
3249                       struct ldb_dn **wkguid_dn)
3250 {
3251         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3252         const char *attrs[] = { NULL };
3253         int ret;
3254         struct ldb_dn *dn;
3255         struct ldb_result *res;
3256
3257         /* construct the magic WKGUID DN */
3258         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3259                             wk_guid, ldb_dn_get_linearized(nc_root));
3260         if (!wkguid_dn) {
3261                 talloc_free(tmp_ctx);
3262                 return ldb_operr(samdb);
3263         }
3264
3265         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
3266                              DSDB_SEARCH_SHOW_DELETED |
3267                              DSDB_SEARCH_SHOW_RECYCLED);
3268         if (ret != LDB_SUCCESS) {
3269                 talloc_free(tmp_ctx);
3270                 return ret;
3271         }
3272
3273         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3274         talloc_free(tmp_ctx);
3275         return LDB_SUCCESS;
3276 }
3277
3278
3279 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3280 {
3281         return ldb_dn_compare(*dn1, *dn2);
3282 }
3283
3284 /*
3285   find a NC root given a DN within the NC
3286  */
3287 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3288                       struct ldb_dn **nc_root)
3289 {
3290         const char *root_attrs[] = { "namingContexts", NULL };
3291         TALLOC_CTX *tmp_ctx;
3292         int ret;
3293         struct ldb_message_element *el;
3294         struct ldb_result *root_res;
3295         unsigned int i;
3296         struct ldb_dn **nc_dns;
3297
3298         tmp_ctx = talloc_new(samdb);
3299         if (tmp_ctx == NULL) {
3300                 return ldb_oom(samdb);
3301         }
3302
3303         ret = ldb_search(samdb, tmp_ctx, &root_res,
3304                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3305         if (ret != LDB_SUCCESS) {
3306                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3307                 talloc_free(tmp_ctx);
3308                 return ret;
3309        }
3310
3311        el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3312        if (!el) {
3313                DEBUG(1,("Finding namingContexts element in root_res failed: %s\n",
3314                         ldb_errstring(samdb)));
3315                talloc_free(tmp_ctx);
3316                return LDB_ERR_NO_SUCH_ATTRIBUTE;
3317        }
3318
3319        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3320        if (!nc_dns) {
3321                talloc_free(tmp_ctx);
3322                return ldb_oom(samdb);
3323        }
3324
3325        for (i=0; i<el->num_values; i++) {
3326                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3327                if (nc_dns[i] == NULL) {
3328                        talloc_free(tmp_ctx);
3329                        return ldb_operr(samdb);
3330                }
3331        }
3332
3333        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3334
3335        for (i=0; i<el->num_values; i++) {
3336                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3337                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3338                        talloc_free(tmp_ctx);
3339                        return LDB_SUCCESS;
3340                }
3341        }
3342
3343        talloc_free(tmp_ctx);
3344        return LDB_ERR_NO_SUCH_OBJECT;
3345 }
3346
3347
3348 /*
3349   find the deleted objects DN for any object, by looking for the NC
3350   root, then looking up the wellknown GUID
3351  */
3352 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3353                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3354                                 struct ldb_dn **do_dn)
3355 {
3356         struct ldb_dn *nc_root;
3357         int ret;
3358
3359         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3360         if (ret != LDB_SUCCESS) {
3361                 return ret;
3362         }
3363
3364         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3365         talloc_free(nc_root);
3366         return ret;
3367 }
3368
3369 /*
3370   return the tombstoneLifetime, in days
3371  */
3372 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3373 {
3374         struct ldb_dn *dn;
3375         dn = ldb_get_config_basedn(ldb);
3376         if (!dn) {
3377                 return LDB_ERR_NO_SUCH_OBJECT;
3378         }
3379         dn = ldb_dn_copy(ldb, dn);
3380         if (!dn) {
3381                 return ldb_operr(ldb);
3382         }
3383         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3384          be a wellknown GUID for this */
3385         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3386                 talloc_free(dn);
3387                 return ldb_operr(ldb);
3388         }
3389
3390         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3391         talloc_free(dn);
3392         return LDB_SUCCESS;
3393 }
3394
3395 /*
3396   compare a ldb_val to a string case insensitively
3397  */
3398 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3399 {
3400         size_t len = strlen(s);
3401         int ret;
3402         if (len > v->length) return 1;
3403         ret = strncasecmp(s, (const char *)v->data, v->length);
3404         if (ret != 0) return ret;
3405         if (v->length > len && v->data[len] != 0) {
3406                 return -1;
3407         }
3408         return 0;
3409 }
3410
3411
3412 /*
3413   load the UDV for a partition in v2 format
3414   The list is returned sorted, and with our local cursor added
3415  */
3416 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3417                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3418 {
3419         static const char *attrs[] = { "replUpToDateVector", NULL };
3420         struct ldb_result *r;
3421         const struct ldb_val *ouv_value;
3422         unsigned int i;
3423         int ret;
3424         uint64_t highest_usn;
3425         const struct GUID *our_invocation_id;
3426         struct timeval now = timeval_current();
3427
3428         ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3429         if (ret != LDB_SUCCESS) {
3430                 return ret;
3431         }
3432
3433         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3434         if (ouv_value) {
3435                 enum ndr_err_code ndr_err;
3436                 struct replUpToDateVectorBlob ouv;
3437
3438                 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
3439                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3440                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3441                         talloc_free(r);
3442                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3443                 }
3444                 if (ouv.version != 2) {
3445                         /* we always store as version 2, and
3446                          * replUpToDateVector is not replicated
3447                          */
3448                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3449                 }
3450
3451                 *count = ouv.ctr.ctr2.count;
3452                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3453         } else {
3454                 *count = 0;
3455                 *cursors = NULL;
3456         }
3457
3458         talloc_free(r);
3459
3460         our_invocation_id = samdb_ntds_invocation_id(samdb);
3461         if (!our_invocation_id) {
3462                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3463                 talloc_free(*cursors);
3464                 return ldb_operr(samdb);
3465         }
3466
3467         ret = dsdb_load_partition_usn(samdb, dn, &highest_usn, NULL);
3468         if (ret != LDB_SUCCESS) {
3469                 /* nothing to add - this can happen after a vampire */
3470                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3471                 return LDB_SUCCESS;
3472         }
3473
3474         for (i=0; i<*count; i++) {
3475                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3476                         (*cursors)[i].highest_usn = highest_usn;
3477                         (*cursors)[i].last_sync_success = timeval_to_nttime(&now);
3478                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3479                         return LDB_SUCCESS;
3480                 }
3481         }
3482
3483         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3484         if (! *cursors) {
3485                 return ldb_oom(samdb);
3486         }
3487
3488         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3489         (*cursors)[*count].highest_usn = highest_usn;
3490         (*cursors)[*count].last_sync_success = timeval_to_nttime(&now);
3491         (*count)++;
3492
3493         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3494
3495         return LDB_SUCCESS;
3496 }
3497
3498 /*
3499   load the UDV for a partition in version 1 format
3500   The list is returned sorted, and with our local cursor added
3501  */
3502 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3503                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3504 {
3505         struct drsuapi_DsReplicaCursor2 *v2;
3506         uint32_t i;
3507         int ret;
3508
3509         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3510         if (ret != LDB_SUCCESS) {
3511                 return ret;
3512         }
3513
3514         if (*count == 0) {
3515                 talloc_free(v2);
3516                 *cursors = NULL;
3517                 return LDB_SUCCESS;
3518         }
3519
3520         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3521         if (*cursors == NULL) {
3522                 talloc_free(v2);
3523                 return ldb_oom(samdb);
3524         }
3525
3526         for (i=0; i<*count; i++) {
3527                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3528                 (*cursors)[i].highest_usn = v2[i].highest_usn;
3529         }
3530         talloc_free(v2);
3531         return LDB_SUCCESS;
3532 }
3533
3534 /*
3535   add a set of controls to a ldb_request structure based on a set of
3536   flags. See util.h for a list of available flags
3537  */
3538 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3539 {
3540         int ret;
3541         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3542                 struct ldb_search_options_control *options;
3543                 /* Using the phantom root control allows us to search all partitions */
3544                 options = talloc(req, struct ldb_search_options_control);
3545                 if (options == NULL) {
3546                         return LDB_ERR_OPERATIONS_ERROR;
3547                 }
3548                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3549
3550                 ret = ldb_request_add_control(req,
3551                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
3552                                               true, options);
3553                 if (ret != LDB_SUCCESS) {
3554                         return ret;
3555                 }
3556         }
3557
3558         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3559                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3560                 if (ret != LDB_SUCCESS) {
3561                         return ret;
3562                 }
3563         }
3564
3565         if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
3566                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
3567                 if (ret != LDB_SUCCESS) {
3568                         return ret;
3569                 }
3570         }
3571
3572         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3573                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, true, NULL);
3574                 if (ret != LDB_SUCCESS) {
3575                         return ret;
3576                 }
3577         }
3578
3579         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3580                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3581                 if (!extended_ctrl) {
3582                         return LDB_ERR_OPERATIONS_ERROR;
3583                 }
3584                 extended_ctrl->type = 1;
3585
3586                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3587                 if (ret != LDB_SUCCESS) {
3588                         return ret;
3589                 }
3590         }
3591
3592         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3593                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3594                 if (ret != LDB_SUCCESS) {
3595                         return ret;
3596                 }
3597         }
3598
3599         if (dsdb_flags & DSDB_MODIFY_RELAX) {
3600                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3601                 if (ret != LDB_SUCCESS) {
3602                         return ret;
3603                 }
3604         }
3605
3606         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3607                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3608                 if (ret != LDB_SUCCESS) {
3609                         return ret;
3610                 }
3611         }
3612
3613         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3614                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3615                 if (ret != LDB_SUCCESS) {
3616                         return ret;
3617                 }
3618         }
3619
3620         if (dsdb_flags & DSDB_TREE_DELETE) {
3621                 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
3622                 if (ret != LDB_SUCCESS) {
3623                         return ret;
3624                 }
3625         }
3626
3627         return LDB_SUCCESS;
3628 }
3629
3630 /*
3631   an add with a set of controls
3632 */
3633 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
3634              uint32_t dsdb_flags)
3635 {
3636         struct ldb_request *req;
3637         int ret;
3638
3639         ret = ldb_build_add_req(&req, ldb, ldb,
3640                                 message,
3641                                 NULL,
3642                                 NULL,
3643                                 ldb_op_default_callback,
3644                                 NULL);
3645
3646         if (ret != LDB_SUCCESS) return ret;
3647
3648         ret = dsdb_request_add_controls(req, dsdb_flags);
3649         if (ret != LDB_SUCCESS) {
3650                 talloc_free(req);
3651                 return ret;
3652         }
3653
3654         ret = dsdb_autotransaction_request(ldb, req);
3655
3656         talloc_free(req);
3657         return ret;
3658 }
3659
3660 /*
3661   a modify with a set of controls
3662 */
3663 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3664                 uint32_t dsdb_flags)
3665 {
3666         struct ldb_request *req;
3667         int ret;
3668
3669         ret = ldb_build_mod_req(&req, ldb, ldb,
3670                                 message,
3671                                 NULL,
3672                                 NULL,
3673                                 ldb_op_default_callback,
3674                                 NULL);
3675
3676         if (ret != LDB_SUCCESS) return ret;
3677
3678         ret = dsdb_request_add_controls(req, dsdb_flags);
3679         if (ret != LDB_SUCCESS) {
3680                 talloc_free(req);
3681                 return ret;
3682         }
3683
3684         ret = dsdb_autotransaction_request(ldb, req);
3685
3686         talloc_free(req);
3687         return ret;
3688 }
3689
3690 /*
3691   like dsdb_modify() but set all the element flags to
3692   LDB_FLAG_MOD_REPLACE
3693  */
3694 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3695 {
3696         unsigned int i;
3697
3698         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3699         for (i=0;i<msg->num_elements;i++) {
3700                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3701         }
3702
3703         return dsdb_modify(ldb, msg, dsdb_flags);
3704 }
3705
3706
3707 /*
3708   search for attrs on one DN, allowing for dsdb_flags controls
3709  */
3710 int dsdb_search_dn(struct ldb_context *ldb,
3711                    TALLOC_CTX *mem_ctx,
3712                    struct ldb_result **_res,
3713                    struct ldb_dn *basedn,
3714                    const char * const *attrs,
3715                    uint32_t dsdb_flags)
3716 {
3717         int ret;
3718         struct ldb_request *req;
3719         struct ldb_result *res;
3720
3721         res = talloc_zero(mem_ctx, struct ldb_result);
3722         if (!res) {
3723                 return ldb_oom(ldb);
3724         }
3725
3726         ret = ldb_build_search_req(&req, ldb, res,
3727                                    basedn,
3728                                    LDB_SCOPE_BASE,
3729                                    NULL,
3730                                    attrs,
3731                                    NULL,
3732                                    res,
3733                                    ldb_search_default_callback,
3734                                    NULL);
3735         if (ret != LDB_SUCCESS) {
3736                 talloc_free(res);
3737                 return ret;
3738         }
3739
3740         ret = dsdb_request_add_controls(req, dsdb_flags);
3741         if (ret != LDB_SUCCESS) {
3742                 talloc_free(res);
3743                 return ret;
3744         }
3745
3746         ret = ldb_request(ldb, req);
3747         if (ret == LDB_SUCCESS) {
3748                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3749         }
3750
3751         talloc_free(req);
3752         if (ret != LDB_SUCCESS) {
3753                 talloc_free(res);
3754                 return ret;
3755         }
3756
3757         *_res = res;
3758         return LDB_SUCCESS;
3759 }
3760
3761 /*
3762   search for attrs on one DN, by the GUID of the DN, allowing for
3763   dsdb_flags controls
3764  */
3765 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
3766                            TALLOC_CTX *mem_ctx,
3767                            struct ldb_result **_res,
3768                            const struct GUID *guid,
3769                            const char * const *attrs,
3770                            uint32_t dsdb_flags)
3771 {
3772         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3773         struct ldb_dn *dn;
3774         int ret;
3775
3776         dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
3777         if (!ldb_dn_validate(dn)) {
3778                 talloc_free(tmp_ctx);
3779                 return LDB_ERR_INVALID_DN_SYNTAX;
3780         }
3781
3782         ret = dsdb_search_dn(ldb, mem_ctx, _res, dn, attrs, dsdb_flags);
3783         talloc_free(tmp_ctx);
3784         return ret;
3785 }
3786
3787 /*
3788   general search with dsdb_flags for controls
3789  */
3790 int dsdb_search(struct ldb_context *ldb,
3791                 TALLOC_CTX *mem_ctx,
3792                 struct ldb_result **_res,
3793                 struct ldb_dn *basedn,
3794                 enum ldb_scope scope,
3795                 const char * const *attrs,
3796                 uint32_t dsdb_flags,
3797                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3798 {
3799         int ret;
3800         struct ldb_request *req;
3801         struct ldb_result *res;
3802         va_list ap;
3803         char *expression = NULL;
3804         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3805
3806         res = talloc_zero(tmp_ctx, struct ldb_result);
3807         if (!res) {
3808                 talloc_free(tmp_ctx);
3809                 return ldb_oom(ldb);
3810         }
3811
3812         if (exp_fmt) {
3813                 va_start(ap, exp_fmt);
3814                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3815                 va_end(ap);
3816
3817                 if (!expression) {
3818                         talloc_free(tmp_ctx);
3819                         return ldb_oom(ldb);
3820                 }
3821         }
3822
3823         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3824                                    basedn,
3825                                    scope,
3826                                    expression,
3827                                    attrs,
3828                                    NULL,
3829                                    res,
3830                                    ldb_search_default_callback,
3831                                    NULL);
3832         if (ret != LDB_SUCCESS) {
3833                 talloc_free(tmp_ctx);
3834                 return ret;
3835         }
3836
3837         ret = dsdb_request_add_controls(req, dsdb_flags);
3838         if (ret != LDB_SUCCESS) {
3839                 talloc_free(tmp_ctx);
3840                 ldb_reset_err_string(ldb);
3841                 return ret;
3842         }
3843
3844         ret = ldb_request(ldb, req);
3845         if (ret == LDB_SUCCESS) {
3846                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3847         }
3848
3849         if (ret != LDB_SUCCESS) {
3850                 talloc_free(tmp_ctx);
3851                 return ret;
3852         }
3853
3854         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
3855                 if (res->count == 0) {
3856                         talloc_free(tmp_ctx);
3857                         ldb_reset_err_string(ldb);
3858                         return LDB_ERR_NO_SUCH_OBJECT;
3859                 }
3860                 if (res->count != 1) {
3861                         talloc_free(tmp_ctx);
3862                         ldb_reset_err_string(ldb);
3863                         return LDB_ERR_CONSTRAINT_VIOLATION;
3864                 }
3865         }
3866
3867         *_res = talloc_steal(mem_ctx, res);
3868         talloc_free(tmp_ctx);
3869
3870         return LDB_SUCCESS;
3871 }
3872
3873
3874 /*
3875   general search with dsdb_flags for controls
3876   returns exactly 1 record or an error
3877  */
3878 int dsdb_search_one(struct ldb_context *ldb,
3879                     TALLOC_CTX *mem_ctx,
3880                     struct ldb_message **msg,
3881                     struct ldb_dn *basedn,
3882                     enum ldb_scope scope,
3883                     const char * const *attrs,
3884                     uint32_t dsdb_flags,
3885                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3886 {
3887         int ret;
3888         struct ldb_result *res;
3889         va_list ap;
3890         char *expression = NULL;
3891         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3892
3893         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
3894
3895         res = talloc_zero(tmp_ctx, struct ldb_result);
3896         if (!res) {
3897                 talloc_free(tmp_ctx);
3898                 return ldb_oom(ldb);
3899         }
3900
3901         if (exp_fmt) {
3902                 va_start(ap, exp_fmt);
3903                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3904                 va_end(ap);
3905
3906                 if (!expression) {
3907                         talloc_free(tmp_ctx);
3908                         return ldb_oom(ldb);
3909                 }
3910                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
3911                                   dsdb_flags, "%s", expression);
3912         } else {
3913                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
3914                                   dsdb_flags, NULL);
3915         }
3916
3917         if (ret != LDB_SUCCESS) {
3918                 talloc_free(tmp_ctx);
3919                 return ret;
3920         }
3921
3922         *msg = talloc_steal(mem_ctx, res->msgs[0]);
3923         talloc_free(tmp_ctx);
3924
3925         return LDB_SUCCESS;
3926 }
3927
3928 /* returns back the forest DNS name */
3929 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
3930 {
3931         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
3932                                                           ldb_get_root_basedn(ldb));
3933         char *p;
3934
3935         if (forest_name == NULL) {
3936                 return NULL;
3937         }
3938
3939         p = strchr(forest_name, '/');
3940         if (p) {
3941                 *p = '\0';
3942         }
3943
3944         return forest_name;
3945 }
3946
3947 /*
3948    validate that an DSA GUID belongs to the specified user sid.
3949    The user SID must be a domain controller account (either RODC or
3950    RWDC)
3951  */
3952 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
3953                            const struct GUID *dsa_guid,
3954                            const struct dom_sid *sid)
3955 {
3956         /* strategy:
3957             - find DN of record with the DSA GUID in the
3958               configuration partition (objectGUID)
3959             - remove "NTDS Settings" component from DN
3960             - do a base search on that DN for serverReference with
3961               extended-dn enabled
3962             - extract objectSid from resulting serverReference
3963               attribute
3964             - check this sid matches the sid argument
3965         */
3966         struct ldb_dn *config_dn;
3967         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
3968         struct ldb_message *msg;
3969         const char *attrs1[] = { NULL };
3970         const char *attrs2[] = { "serverReference", NULL };
3971         int ret;
3972         struct ldb_dn *dn, *account_dn;
3973         struct dom_sid sid2;
3974         NTSTATUS status;
3975
3976         config_dn = ldb_get_config_basedn(ldb);
3977
3978         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
3979                               attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
3980         if (ret != LDB_SUCCESS) {
3981                 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
3982                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3983                 talloc_free(tmp_ctx);
3984                 return ldb_operr(ldb);
3985         }
3986         dn = msg->dn;
3987
3988         if (!ldb_dn_remove_child_components(dn, 1)) {
3989                 talloc_free(tmp_ctx);
3990                 return ldb_operr(ldb);
3991         }
3992
3993         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
3994                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
3995                               "(objectClass=server)");
3996         if (ret != LDB_SUCCESS) {
3997                 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
3998                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
3999                 talloc_free(tmp_ctx);
4000                 return ldb_operr(ldb);
4001         }
4002
4003         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4004         if (account_dn == NULL) {
4005                 DEBUG(1,(__location__ ": Failed to find account_dn for DSA with objectGUID %s, sid %s\n",
4006                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4007                 talloc_free(tmp_ctx);
4008                 return ldb_operr(ldb);
4009         }
4010
4011         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4012         if (!NT_STATUS_IS_OK(status)) {
4013                 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4014                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4015                 talloc_free(tmp_ctx);
4016                 return ldb_operr(ldb);
4017         }
4018
4019         if (!dom_sid_equal(sid, &sid2)) {
4020                 /* someone is trying to spoof another account */
4021                 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4022                          GUID_string(tmp_ctx, dsa_guid),
4023                          dom_sid_string(tmp_ctx, sid),
4024                          dom_sid_string(tmp_ctx, &sid2)));
4025                 talloc_free(tmp_ctx);
4026                 return ldb_operr(ldb);
4027         }
4028
4029         talloc_free(tmp_ctx);
4030         return LDB_SUCCESS;
4031 }
4032
4033 static const char *secret_attributes[] = {
4034         "currentValue",
4035         "dBCSPwd",
4036         "initialAuthIncoming",
4037         "initialAuthOutgoing",
4038         "lmPwdHistory",
4039         "ntPwdHistory",
4040         "priorValue",
4041         "supplementalCredentials",
4042         "trustAuthIncoming",
4043         "trustAuthOutgoing",
4044         "unicodePwd",
4045         NULL
4046 };
4047
4048 /*
4049   check if the attribute belongs to the RODC filtered attribute set
4050   Note that attributes that are in the filtered attribute set are the
4051   ones that _are_ always sent to a RODC
4052 */
4053 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4054 {
4055         /* they never get secret attributes */
4056         if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4057                 return false;
4058         }
4059
4060         /* they do get non-secret critical attributes */
4061         if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4062                 return true;
4063         }
4064
4065         /* they do get non-secret attributes marked as being in the FAS  */
4066         if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4067                 return true;
4068         }
4069
4070         /* other attributes are denied */
4071         return false;
4072 }
4073
4074 /* return fsmo role dn and role owner dn for a particular role*/
4075 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4076                                struct ldb_context *ldb,
4077                                uint32_t role,
4078                                struct ldb_dn **fsmo_role_dn,
4079                                struct ldb_dn **role_owner_dn)
4080 {
4081         int ret;
4082         switch (role) {
4083         case DREPL_NAMING_MASTER:
4084                 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4085                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4086                 if (ret != LDB_SUCCESS) {
4087                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4088                                  ldb_errstring(ldb)));
4089                         talloc_free(tmp_ctx);
4090                         return WERR_DS_DRA_INTERNAL_ERROR;
4091                 }
4092                 break;
4093         case DREPL_INFRASTRUCTURE_MASTER:
4094                 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4095                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4096                 if (ret != LDB_SUCCESS) {
4097                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4098                                  ldb_errstring(ldb)));
4099                         talloc_free(tmp_ctx);
4100                         return WERR_DS_DRA_INTERNAL_ERROR;
4101                 }
4102                 break;
4103         case DREPL_RID_MASTER:
4104                 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
4105                 if (ret != LDB_SUCCESS) {
4106                         DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
4107                         talloc_free(tmp_ctx);
4108                         return WERR_DS_DRA_INTERNAL_ERROR;
4109                 }
4110
4111                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4112                 if (ret != LDB_SUCCESS) {
4113                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
4114                                  ldb_errstring(ldb)));
4115                         talloc_free(tmp_ctx);
4116                         return WERR_DS_DRA_INTERNAL_ERROR;
4117                 }
4118                 break;
4119         case DREPL_SCHEMA_MASTER:
4120                 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
4121                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4122                 if (ret != LDB_SUCCESS) {
4123                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4124                                  ldb_errstring(ldb)));
4125                         talloc_free(tmp_ctx);
4126                         return WERR_DS_DRA_INTERNAL_ERROR;
4127                 }
4128                 break;
4129         case DREPL_PDC_MASTER:
4130                 *fsmo_role_dn = ldb_get_default_basedn(ldb);
4131                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4132                 if (ret != LDB_SUCCESS) {
4133                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
4134                                  ldb_errstring(ldb)));
4135                         talloc_free(tmp_ctx);
4136                         return WERR_DS_DRA_INTERNAL_ERROR;
4137                 }
4138                 break;
4139         default:
4140                 return WERR_DS_DRA_INTERNAL_ERROR;
4141         }
4142         return WERR_OK;
4143 }
4144
4145 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
4146                                     TALLOC_CTX *mem_ctx,
4147                                     struct ldb_dn *server_dn)
4148 {
4149         int ldb_ret;
4150         struct ldb_result *res = NULL;
4151         const char * const attrs[] = { "dNSHostName", NULL};
4152
4153         ldb_ret = ldb_search(ldb, mem_ctx, &res,
4154                              server_dn,
4155                              LDB_SCOPE_BASE,
4156                              attrs, NULL);
4157         if (ldb_ret != LDB_SUCCESS) {
4158                 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
4159                           ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
4160                 return NULL;
4161         }
4162
4163         return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
4164 }
4165
4166 /*
4167   returns true if an attribute is in the filter,
4168   false otherwise, provided that attribute value is provided with the expression
4169 */
4170 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
4171                              const char *attr)
4172 {
4173        unsigned int i;
4174        switch (tree->operation) {
4175        case LDB_OP_AND:
4176        case LDB_OP_OR:
4177                for (i=0;i<tree->u.list.num_elements;i++) {
4178                        if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
4179                                                        attr))
4180                                return true;
4181                }
4182                return false;
4183        case LDB_OP_NOT:
4184                return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
4185        case LDB_OP_EQUALITY:
4186        case LDB_OP_GREATER:
4187        case LDB_OP_LESS:
4188        case LDB_OP_APPROX:
4189                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
4190                        return true;
4191                }
4192                return false;
4193        case LDB_OP_SUBSTRING:
4194                if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
4195                        return true;
4196                }
4197                return false;
4198        case LDB_OP_PRESENT:
4199                /* (attrname=*) is not filtered out */
4200                return false;
4201        case LDB_OP_EXTENDED:
4202                if (tree->u.extended.attr &&
4203                    ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
4204                        return true;
4205                }
4206                return false;
4207        }
4208        return false;
4209 }
4210
4211 bool is_attr_in_list(const char * const * attrs, const char *attr)
4212 {
4213         unsigned int i;
4214
4215         for (i = 0; attrs[i]; i++) {
4216                 if (ldb_attr_cmp(attrs[i], attr) == 0)
4217                         return true;
4218         }
4219
4220         return false;
4221 }
4222