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