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