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