s4-dsdb: added dsdb_get_deleted_objects_dn()
[ira/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
42 /*
43   search the sam for the specified attributes in a specific domain, filter on
44   objectSid being in domain_sid.
45 */
46 int samdb_search_domain(struct ldb_context *sam_ldb,
47                         TALLOC_CTX *mem_ctx, 
48                         struct ldb_dn *basedn,
49                         struct ldb_message ***res,
50                         const char * const *attrs,
51                         const struct dom_sid *domain_sid,
52                         const char *format, ...)  _PRINTF_ATTRIBUTE(7,8)
53 {
54         va_list ap;
55         int i, count;
56
57         va_start(ap, format);
58         count = gendb_search_v(sam_ldb, mem_ctx, basedn,
59                                res, attrs, format, ap);
60         va_end(ap);
61
62         i=0;
63
64         while (i<count) {
65                 struct dom_sid *entry_sid;
66
67                 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
68
69                 if ((entry_sid == NULL) ||
70                     (!dom_sid_in_domain(domain_sid, entry_sid))) {
71                         /* Delete that entry from the result set */
72                         (*res)[i] = (*res)[count-1];
73                         count -= 1;
74                         talloc_free(entry_sid);
75                         continue;
76                 }
77                 talloc_free(entry_sid);
78                 i += 1;
79         }
80
81         return count;
82 }
83
84 /*
85   search the sam for a single string attribute in exactly 1 record
86 */
87 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
88                                   TALLOC_CTX *mem_ctx,
89                                   struct ldb_dn *basedn,
90                                   const char *attr_name,
91                                   const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
92 {
93         int count;
94         const char *attrs[2] = { NULL, NULL };
95         struct ldb_message **res = NULL;
96
97         attrs[0] = attr_name;
98
99         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
100         if (count > 1) {                
101                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
102                          attr_name, format, count));
103         }
104         if (count != 1) {
105                 talloc_free(res);
106                 return NULL;
107         }
108
109         return samdb_result_string(res[0], attr_name, NULL);
110 }
111
112 /*
113   search the sam for a single string attribute in exactly 1 record
114 */
115 const char *samdb_search_string(struct ldb_context *sam_ldb,
116                                 TALLOC_CTX *mem_ctx,
117                                 struct ldb_dn *basedn,
118                                 const char *attr_name,
119                                 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
120 {
121         va_list ap;
122         const char *str;
123
124         va_start(ap, format);
125         str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
126         va_end(ap);
127
128         return str;
129 }
130
131 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
132                                TALLOC_CTX *mem_ctx,
133                                struct ldb_dn *basedn,
134                                const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
135 {
136         va_list ap;
137         struct ldb_dn *ret;
138         struct ldb_message **res = NULL;
139         int count;
140
141         va_start(ap, format);
142         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
143         va_end(ap);
144
145         if (count != 1) return NULL;
146
147         ret = talloc_steal(mem_ctx, res[0]->dn);
148         talloc_free(res);
149
150         return ret;
151 }
152
153 /*
154   search the sam for a dom_sid attribute in exactly 1 record
155 */
156 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
157                                      TALLOC_CTX *mem_ctx,
158                                      struct ldb_dn *basedn,
159                                      const char *attr_name,
160                                      const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
161 {
162         va_list ap;
163         int count;
164         struct ldb_message **res;
165         const char *attrs[2] = { NULL, NULL };
166         struct dom_sid *sid;
167
168         attrs[0] = attr_name;
169
170         va_start(ap, format);
171         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
172         va_end(ap);
173         if (count > 1) {                
174                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
175                          attr_name, format, count));
176         }
177         if (count != 1) {
178                 talloc_free(res);
179                 return NULL;
180         }
181         sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
182         talloc_free(res);
183         return sid;     
184 }
185
186 /*
187   return the count of the number of records in the sam matching the query
188 */
189 int samdb_search_count(struct ldb_context *sam_ldb,
190                        struct ldb_dn *basedn,
191                        const char *format, ...) _PRINTF_ATTRIBUTE(3,4)
192 {
193         va_list ap;
194         struct ldb_message **res;
195         const char *attrs[] = { NULL };
196         int ret;
197         TALLOC_CTX *tmp_ctx = talloc_new(sam_ldb);
198
199         va_start(ap, format);
200         ret = gendb_search_v(sam_ldb, tmp_ctx, basedn, &res, attrs, format, ap);
201         va_end(ap);
202         talloc_free(tmp_ctx);
203
204         return ret;
205 }
206
207
208 /*
209   search the sam for a single integer attribute in exactly 1 record
210 */
211 uint_t samdb_search_uint(struct ldb_context *sam_ldb,
212                          TALLOC_CTX *mem_ctx,
213                          uint_t default_value,
214                          struct ldb_dn *basedn,
215                          const char *attr_name,
216                          const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
217 {
218         va_list ap;
219         int count;
220         struct ldb_message **res;
221         const char *attrs[2] = { NULL, NULL };
222
223         attrs[0] = attr_name;
224
225         va_start(ap, format);
226         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
227         va_end(ap);
228
229         if (count != 1) {
230                 return default_value;
231         }
232
233         return samdb_result_uint(res[0], attr_name, default_value);
234 }
235
236 /*
237   search the sam for a single signed 64 bit integer attribute in exactly 1 record
238 */
239 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
240                            TALLOC_CTX *mem_ctx,
241                            int64_t default_value,
242                            struct ldb_dn *basedn,
243                            const char *attr_name,
244                            const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
245 {
246         va_list ap;
247         int count;
248         struct ldb_message **res;
249         const char *attrs[2] = { NULL, NULL };
250
251         attrs[0] = attr_name;
252
253         va_start(ap, format);
254         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
255         va_end(ap);
256
257         if (count != 1) {
258                 return default_value;
259         }
260
261         return samdb_result_int64(res[0], attr_name, default_value);
262 }
263
264 /*
265   search the sam for multipe records each giving a single string attribute
266   return the number of matches, or -1 on error
267 */
268 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
269                                  TALLOC_CTX *mem_ctx,
270                                  struct ldb_dn *basedn,
271                                  const char ***strs,
272                                  const char *attr_name,
273                                  const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
274 {
275         va_list ap;
276         int count, i;
277         const char *attrs[2] = { NULL, NULL };
278         struct ldb_message **res = NULL;
279
280         attrs[0] = attr_name;
281
282         va_start(ap, format);
283         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
284         va_end(ap);
285
286         if (count <= 0) {
287                 return count;
288         }
289
290         /* make sure its single valued */
291         for (i=0;i<count;i++) {
292                 if (res[i]->num_elements != 1) {
293                         DEBUG(1,("samdb: search for %s %s not single valued\n", 
294                                  attr_name, format));
295                         talloc_free(res);
296                         return -1;
297                 }
298         }
299
300         *strs = talloc_array(mem_ctx, const char *, count+1);
301         if (! *strs) {
302                 talloc_free(res);
303                 return -1;
304         }
305
306         for (i=0;i<count;i++) {
307                 (*strs)[i] = samdb_result_string(res[i], attr_name, NULL);
308         }
309         (*strs)[count] = NULL;
310
311         return count;
312 }
313
314 /*
315   pull a uint from a result set. 
316 */
317 uint_t samdb_result_uint(const struct ldb_message *msg, const char *attr, uint_t default_value)
318 {
319         return ldb_msg_find_attr_as_uint(msg, attr, default_value);
320 }
321
322 /*
323   pull a (signed) int64 from a result set. 
324 */
325 int64_t samdb_result_int64(const struct ldb_message *msg, const char *attr, int64_t default_value)
326 {
327         return ldb_msg_find_attr_as_int64(msg, attr, default_value);
328 }
329
330 /*
331   pull a string from a result set. 
332 */
333 const char *samdb_result_string(const struct ldb_message *msg, const char *attr, 
334                                 const char *default_value)
335 {
336         return ldb_msg_find_attr_as_string(msg, attr, default_value);
337 }
338
339 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
340                                const char *attr, struct ldb_dn *default_value)
341 {
342         struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
343         if (!ret_dn) {
344                 return default_value;
345         }
346         return ret_dn;
347 }
348
349 /*
350   pull a rid from a objectSid in a result set. 
351 */
352 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
353                                    const char *attr, uint32_t default_value)
354 {
355         struct dom_sid *sid;
356         uint32_t rid;
357
358         sid = samdb_result_dom_sid(mem_ctx, msg, attr);
359         if (sid == NULL) {
360                 return default_value;
361         }
362         rid = sid->sub_auths[sid->num_auths-1];
363         talloc_free(sid);
364         return rid;
365 }
366
367 /*
368   pull a dom_sid structure from a objectSid in a result set. 
369 */
370 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
371                                      const char *attr)
372 {
373         const struct ldb_val *v;
374         struct dom_sid *sid;
375         enum ndr_err_code ndr_err;
376         v = ldb_msg_find_ldb_val(msg, attr);
377         if (v == NULL) {
378                 return NULL;
379         }
380         sid = talloc(mem_ctx, struct dom_sid);
381         if (sid == NULL) {
382                 return NULL;
383         }
384         ndr_err = ndr_pull_struct_blob(v, sid, NULL, sid,
385                                        (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
386         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
387                 talloc_free(sid);
388                 return NULL;
389         }
390         return sid;
391 }
392
393 /*
394   pull a guid structure from a objectGUID in a result set. 
395 */
396 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
397 {
398         const struct ldb_val *v;
399         struct GUID guid;
400         NTSTATUS status;
401
402         v = ldb_msg_find_ldb_val(msg, attr);
403         if (!v) return GUID_zero();
404
405         status = GUID_from_ndr_blob(v, &guid);
406         if (!NT_STATUS_IS_OK(status)) {
407                 return GUID_zero();
408         }
409
410         return guid;
411 }
412
413 /*
414   pull a sid prefix from a objectSid in a result set. 
415   this is used to find the domain sid for a user
416 */
417 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
418                                         const char *attr)
419 {
420         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
421         if (!sid || sid->num_auths < 1) return NULL;
422         sid->num_auths--;
423         return sid;
424 }
425
426 /*
427   pull a NTTIME in a result set. 
428 */
429 NTTIME samdb_result_nttime(struct ldb_message *msg, const char *attr, NTTIME default_value)
430 {
431         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
432 }
433
434 /*
435  * Windows stores 0 for lastLogoff.
436  * But when a MS DC return the lastLogoff (as Logoff Time)
437  * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
438  * cause windows 2008 and newer version to fail for SMB requests
439  */
440 NTTIME samdb_result_last_logoff(struct ldb_message *msg)
441 {
442         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
443
444         if (ret == 0)
445                 ret = 0x7FFFFFFFFFFFFFFFULL;
446
447         return ret;
448 }
449
450 /*
451  * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
452  * indicate an account doesn't expire.
453  *
454  * When Windows initially creates an account, it sets
455  * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF).  However,
456  * when changing from an account having a specific expiration date to
457  * that account never expiring, it sets accountExpires = 0.
458  *
459  * Consolidate that logic here to allow clearer logic for account expiry in
460  * the rest of the code.
461  */
462 NTTIME samdb_result_account_expires(struct ldb_message *msg)
463 {
464         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
465                                                  0);
466
467         if (ret == 0)
468                 ret = 0x7FFFFFFFFFFFFFFFULL;
469
470         return ret;
471 }
472
473 /*
474   pull a uint64_t from a result set. 
475 */
476 uint64_t samdb_result_uint64(struct ldb_message *msg, const char *attr, uint64_t default_value)
477 {
478         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
479 }
480
481
482 /*
483   construct the allow_password_change field from the PwdLastSet attribute and the 
484   domain password settings
485 */
486 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb, 
487                                           TALLOC_CTX *mem_ctx, 
488                                           struct ldb_dn *domain_dn, 
489                                           struct ldb_message *msg, 
490                                           const char *attr)
491 {
492         uint64_t attr_time = samdb_result_uint64(msg, attr, 0);
493         int64_t minPwdAge;
494
495         if (attr_time == 0) {
496                 return 0;
497         }
498
499         minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
500
501         /* yes, this is a -= not a += as minPwdAge is stored as the negative
502            of the number of 100-nano-seconds */
503         attr_time -= minPwdAge;
504
505         return attr_time;
506 }
507
508 /*
509   construct the force_password_change field from the PwdLastSet
510   attribute, the userAccountControl and the domain password settings
511 */
512 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb, 
513                                           TALLOC_CTX *mem_ctx, 
514                                           struct ldb_dn *domain_dn, 
515                                           struct ldb_message *msg)
516 {
517         uint64_t attr_time = samdb_result_uint64(msg, "pwdLastSet", 0);
518         uint32_t userAccountControl = samdb_result_uint64(msg, "userAccountControl", 0);
519         int64_t maxPwdAge;
520
521         /* Machine accounts don't expire, and there is a flag for 'no expiry' */
522         if (!(userAccountControl & UF_NORMAL_ACCOUNT)
523             || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
524                 return 0x7FFFFFFFFFFFFFFFULL;
525         }
526
527         if (attr_time == 0) {
528                 return 0;
529         }
530
531         maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "maxPwdAge", NULL);
532         if (maxPwdAge == 0) {
533                 return 0x7FFFFFFFFFFFFFFFULL;
534         } else {
535                 attr_time -= maxPwdAge;
536         }
537
538         return attr_time;
539 }
540
541 /*
542   pull a samr_Password structutre from a result set. 
543 */
544 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
545 {
546         struct samr_Password *hash = NULL;
547         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
548         if (val && (val->length >= sizeof(hash->hash))) {
549                 hash = talloc(mem_ctx, struct samr_Password);
550                 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
551         }
552         return hash;
553 }
554
555 /*
556   pull an array of samr_Password structutres from a result set. 
557 */
558 uint_t samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
559                            const char *attr, struct samr_Password **hashes)
560 {
561         uint_t count, i;
562         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
563
564         *hashes = NULL;
565         if (!val) {
566                 return 0;
567         }
568         count = val->length / 16;
569         if (count == 0) {
570                 return 0;
571         }
572
573         *hashes = talloc_array(mem_ctx, struct samr_Password, count);
574         if (! *hashes) {
575                 return 0;
576         }
577
578         for (i=0;i<count;i++) {
579                 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
580         }
581
582         return count;
583 }
584
585 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct ldb_message *msg, 
586                                 struct samr_Password **lm_pwd, struct samr_Password **nt_pwd) 
587 {
588         struct samr_Password *lmPwdHash, *ntPwdHash;
589         if (nt_pwd) {
590                 int num_nt;
591                 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
592                 if (num_nt == 0) {
593                         *nt_pwd = NULL;
594                 } else if (num_nt > 1) {
595                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
596                 } else {
597                         *nt_pwd = &ntPwdHash[0];
598                 }
599         }
600         if (lm_pwd) {
601                 /* Ensure that if we have turned off LM
602                  * authentication, that we never use the LM hash, even
603                  * if we store it */
604                 if (lp_lanman_auth(lp_ctx)) {
605                         int num_lm;
606                         num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
607                         if (num_lm == 0) {
608                                 *lm_pwd = NULL;
609                         } else if (num_lm > 1) {
610                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
611                         } else {
612                                 *lm_pwd = &lmPwdHash[0];
613                         }
614                 } else {
615                         *lm_pwd = NULL;
616                 }
617         }
618         return NT_STATUS_OK;
619 }
620
621 /*
622   pull a samr_LogonHours structutre from a result set. 
623 */
624 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
625 {
626         struct samr_LogonHours hours;
627         const int units_per_week = 168;
628         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
629         ZERO_STRUCT(hours);
630         hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week);
631         if (!hours.bits) {
632                 return hours;
633         }
634         hours.units_per_week = units_per_week;
635         memset(hours.bits, 0xFF, units_per_week);
636         if (val) {
637                 memcpy(hours.bits, val->data, MIN(val->length, units_per_week));
638         }
639         return hours;
640 }
641
642 /*
643   pull a set of account_flags from a result set. 
644
645   This requires that the attributes: 
646    pwdLastSet
647    userAccountControl
648   be included in 'msg'
649 */
650 uint32_t samdb_result_acct_flags(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
651                                  struct ldb_message *msg, struct ldb_dn *domain_dn)
652 {
653         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
654         uint32_t acct_flags = ds_uf2acb(userAccountControl);
655         NTTIME must_change_time;
656         NTTIME now;
657
658         must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx, 
659                                                               domain_dn, msg);
660
661         /* Test account expire time */
662         unix_to_nt_time(&now, time(NULL));
663         /* check for expired password */
664         if (must_change_time < now) {
665                 acct_flags |= ACB_PW_EXPIRED;
666         }
667         return acct_flags;
668 }
669
670 struct lsa_BinaryString samdb_result_parameters(TALLOC_CTX *mem_ctx,
671                                                 struct ldb_message *msg,
672                                                 const char *attr)
673 {
674         struct lsa_BinaryString s;
675         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
676
677         ZERO_STRUCT(s);
678
679         if (!val) {
680                 return s;
681         }
682
683         s.array = talloc_array(mem_ctx, uint16_t, val->length/2);
684         if (!s.array) {
685                 return s;
686         }
687         s.length = s.size = val->length/2;
688         memcpy(s.array, val->data, val->length);
689
690         return s;
691 }
692
693 /* Find an attribute, with a particular value */
694
695 /* The current callers of this function expect a very specific
696  * behaviour: In particular, objectClass subclass equivilance is not
697  * wanted.  This means that we should not lookup the schema for the
698  * comparison function */
699 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb, 
700                                                  const struct ldb_message *msg, 
701                                                  const char *name, const char *value)
702 {
703         int i;
704         struct ldb_message_element *el = ldb_msg_find_element(msg, name);
705
706         if (!el) {
707                 return NULL;
708         }
709
710         for (i=0;i<el->num_values;i++) {
711                 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
712                         return el;
713                 }
714         }
715
716         return NULL;
717 }
718
719 int samdb_find_or_add_value(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
720 {
721         if (samdb_find_attribute(ldb, msg, name, set_value) == NULL) {
722                 return samdb_msg_add_string(ldb, msg, msg, name, set_value);
723         }
724         return LDB_SUCCESS;
725 }
726
727 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
728 {
729         struct ldb_message_element *el;
730
731         el = ldb_msg_find_element(msg, name);
732         if (el) {
733                 return LDB_SUCCESS;
734         }
735
736         return samdb_msg_add_string(ldb, msg, msg, name, set_value);
737 }
738
739
740
741 /*
742   add a string element to a message
743 */
744 int samdb_msg_add_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
745                          const char *attr_name, const char *str)
746 {
747         char *s = talloc_strdup(mem_ctx, str);
748         char *a = talloc_strdup(mem_ctx, attr_name);
749         if (s == NULL || a == NULL) {
750                 return LDB_ERR_OPERATIONS_ERROR;
751         }
752         return ldb_msg_add_string(msg, a, s);
753 }
754
755 /*
756   add a dom_sid element to a message
757 */
758 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
759                          const char *attr_name, struct dom_sid *sid)
760 {
761         struct ldb_val v;
762         enum ndr_err_code ndr_err;
763
764         ndr_err = ndr_push_struct_blob(&v, mem_ctx, 
765                                        lp_iconv_convenience(ldb_get_opaque(sam_ldb, "loadparm")),
766                                        sid,
767                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
768         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
769                 return -1;
770         }
771         return ldb_msg_add_value(msg, attr_name, &v, NULL);
772 }
773
774
775 /*
776   add a delete element operation to a message
777 */
778 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
779                          const char *attr_name)
780 {
781         /* we use an empty replace rather than a delete, as it allows for 
782            samdb_replace() to be used everywhere */
783         return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
784 }
785
786 /*
787   add a add attribute value to a message
788 */
789 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
790                          const char *attr_name, const char *value)
791 {
792         struct ldb_message_element *el;
793         char *a, *v;
794         int ret;
795         a = talloc_strdup(mem_ctx, attr_name);
796         if (a == NULL)
797                 return -1;
798         v = talloc_strdup(mem_ctx, value);
799         if (v == NULL)
800                 return -1;
801         ret = ldb_msg_add_string(msg, a, v);
802         if (ret != 0)
803                 return ret;
804         el = ldb_msg_find_element(msg, a);
805         if (el == NULL)
806                 return -1;
807         el->flags = LDB_FLAG_MOD_ADD;
808         return 0;
809 }
810
811 /*
812   add a delete attribute value to a message
813 */
814 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
815                          const char *attr_name, const char *value)
816 {
817         struct ldb_message_element *el;
818         char *a, *v;
819         int ret;
820         a = talloc_strdup(mem_ctx, attr_name);
821         if (a == NULL)
822                 return -1;
823         v = talloc_strdup(mem_ctx, value);
824         if (v == NULL)
825                 return -1;
826         ret = ldb_msg_add_string(msg, a, v);
827         if (ret != 0)
828                 return ret;
829         el = ldb_msg_find_element(msg, a);
830         if (el == NULL)
831                 return -1;
832         el->flags = LDB_FLAG_MOD_DELETE;
833         return 0;
834 }
835
836 /*
837   add a int element to a message
838 */
839 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
840                        const char *attr_name, int v)
841 {
842         const char *s = talloc_asprintf(mem_ctx, "%d", v);
843         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
844 }
845
846 /*
847   add a uint_t element to a message
848 */
849 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
850                        const char *attr_name, uint_t v)
851 {
852         const char *s = talloc_asprintf(mem_ctx, "%u", v);
853         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
854 }
855
856 /*
857   add a (signed) int64_t element to a message
858 */
859 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
860                         const char *attr_name, int64_t v)
861 {
862         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
863         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
864 }
865
866 /*
867   add a uint64_t element to a message
868 */
869 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
870                         const char *attr_name, uint64_t v)
871 {
872         const char *s = talloc_asprintf(mem_ctx, "%llu", (unsigned long long)v);
873         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, s);
874 }
875
876 /*
877   add a samr_Password element to a message
878 */
879 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
880                        const char *attr_name, struct samr_Password *hash)
881 {
882         struct ldb_val val;
883         val.data = talloc_memdup(mem_ctx, hash->hash, 16);
884         if (!val.data) {
885                 return -1;
886         }
887         val.length = 16;
888         return ldb_msg_add_value(msg, attr_name, &val, NULL);
889 }
890
891 /*
892   add a samr_Password array to a message
893 */
894 int samdb_msg_add_hashes(TALLOC_CTX *mem_ctx, struct ldb_message *msg,
895                          const char *attr_name, struct samr_Password *hashes, uint_t count)
896 {
897         struct ldb_val val;
898         int i;
899         val.data = talloc_array_size(mem_ctx, 16, count);
900         val.length = count*16;
901         if (!val.data) {
902                 return -1;
903         }
904         for (i=0;i<count;i++) {
905                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
906         }
907         return ldb_msg_add_value(msg, attr_name, &val, NULL);
908 }
909
910 /*
911   add a acct_flags element to a message
912 */
913 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
914                              const char *attr_name, uint32_t v)
915 {
916         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
917 }
918
919 /*
920   add a logon_hours element to a message
921 */
922 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
923                               const char *attr_name, struct samr_LogonHours *hours)
924 {
925         struct ldb_val val;
926         val.length = hours->units_per_week / 8;
927         val.data = hours->bits;
928         return ldb_msg_add_value(msg, attr_name, &val, NULL);
929 }
930
931 /*
932   add a parameters element to a message
933 */
934 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
935                              const char *attr_name, struct lsa_BinaryString *parameters)
936 {
937         struct ldb_val val;
938         val.length = parameters->length * 2;
939         val.data = (uint8_t *)parameters->array;
940         return ldb_msg_add_value(msg, attr_name, &val, NULL);
941 }
942 /*
943   add a general value element to a message
944 */
945 int samdb_msg_add_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
946                               const char *attr_name, const struct ldb_val *val)
947 {
948         return ldb_msg_add_value(msg, attr_name, val, NULL);
949 }
950
951 /*
952   sets a general value element to a message
953 */
954 int samdb_msg_set_value(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
955                         const char *attr_name, const struct ldb_val *val)
956 {
957         struct ldb_message_element *el;
958
959         el = ldb_msg_find_element(msg, attr_name);
960         if (el) {
961                 el->num_values = 0;
962         }
963         return ldb_msg_add_value(msg, attr_name, val, NULL);
964 }
965
966 /*
967   set a string element in a message
968 */
969 int samdb_msg_set_string(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
970                          const char *attr_name, const char *str)
971 {
972         struct ldb_message_element *el;
973
974         el = ldb_msg_find_element(msg, attr_name);
975         if (el) {
976                 el->num_values = 0;
977         }
978         return samdb_msg_add_string(sam_ldb, mem_ctx, msg, attr_name, str);
979 }
980
981 /*
982   replace elements in a record
983 */
984 int samdb_replace(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg)
985 {
986         int i;
987
988         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
989         for (i=0;i<msg->num_elements;i++) {
990                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
991         }
992
993         /* modify the samdb record */
994         return ldb_modify(sam_ldb, msg);
995 }
996
997 /*
998   return a default security descriptor
999 */
1000 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1001 {
1002         struct security_descriptor *sd;
1003
1004         sd = security_descriptor_initialise(mem_ctx);
1005
1006         return sd;
1007 }
1008
1009 struct ldb_dn *samdb_base_dn(struct ldb_context *sam_ctx) 
1010 {
1011         return ldb_get_default_basedn(sam_ctx);
1012 }
1013
1014 struct ldb_dn *samdb_config_dn(struct ldb_context *sam_ctx) 
1015 {
1016         return ldb_get_config_basedn(sam_ctx);
1017 }
1018
1019 struct ldb_dn *samdb_schema_dn(struct ldb_context *sam_ctx) 
1020 {
1021         return ldb_get_schema_basedn(sam_ctx);
1022 }
1023
1024 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx) 
1025 {
1026         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1027         struct ldb_dn *aggregate_dn;
1028         if (!schema_dn) {
1029                 return NULL;
1030         }
1031
1032         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1033         if (!aggregate_dn) {
1034                 return NULL;
1035         }
1036         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1037                 return NULL;
1038         }
1039         return aggregate_dn;
1040 }
1041
1042 struct ldb_dn *samdb_root_dn(struct ldb_context *sam_ctx) 
1043 {
1044         return ldb_get_root_basedn(sam_ctx);
1045 }
1046
1047 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1048 {
1049         struct ldb_dn *new_dn;
1050
1051         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1052         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1053                 talloc_free(new_dn);
1054                 return NULL;
1055         }
1056         return new_dn;
1057 }
1058
1059 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1060 {
1061         struct ldb_dn *new_dn;
1062
1063         new_dn = ldb_dn_copy(mem_ctx, samdb_config_dn(sam_ctx));
1064         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1065                 talloc_free(new_dn);
1066                 return NULL;
1067         }
1068         return new_dn;
1069 }
1070
1071 /*
1072   work out the domain sid for the current open ldb
1073 */
1074 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1075 {
1076         TALLOC_CTX *tmp_ctx;
1077         const struct dom_sid *domain_sid;
1078         const char *attrs[] = {
1079                 "objectSid",
1080                 NULL
1081         };
1082         struct ldb_result *res;
1083         int ret;
1084
1085         /* see if we have a cached copy */
1086         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1087         if (domain_sid) {
1088                 return domain_sid;
1089         }
1090
1091         tmp_ctx = talloc_new(ldb);
1092         if (tmp_ctx == NULL) {
1093                 goto failed;
1094         }
1095
1096         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1097
1098         if (ret != LDB_SUCCESS) {
1099                 goto failed;
1100         }
1101
1102         if (res->count != 1) {
1103                 goto failed;
1104         }
1105
1106         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1107         if (domain_sid == NULL) {
1108                 goto failed;
1109         }
1110
1111         /* cache the domain_sid in the ldb */
1112         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1113                 goto failed;
1114         }
1115
1116         talloc_steal(ldb, domain_sid);
1117         talloc_free(tmp_ctx);
1118
1119         return domain_sid;
1120
1121 failed:
1122         DEBUG(1,("Failed to find domain_sid for open ldb\n"));
1123         talloc_free(tmp_ctx);
1124         return NULL;
1125 }
1126
1127 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1128 {
1129         TALLOC_CTX *tmp_ctx;
1130         struct dom_sid *dom_sid_new;
1131         struct dom_sid *dom_sid_old;
1132
1133         /* see if we have a cached copy */
1134         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1135                                                      "cache.domain_sid"), struct dom_sid);
1136
1137         tmp_ctx = talloc_new(ldb);
1138         if (tmp_ctx == NULL) {
1139                 goto failed;
1140         }
1141
1142         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1143         if (!dom_sid_new) {
1144                 goto failed;
1145         }
1146
1147         /* cache the domain_sid in the ldb */
1148         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1149                 goto failed;
1150         }
1151
1152         talloc_steal(ldb, dom_sid_new);
1153         talloc_free(tmp_ctx);
1154         talloc_free(dom_sid_old);
1155
1156         return true;
1157
1158 failed:
1159         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1160         talloc_free(tmp_ctx);
1161         return false;
1162 }
1163
1164 /* Obtain the short name of the flexible single master operator
1165  * (FSMO), such as the PDC Emulator */
1166 const char *samdb_result_fsmo_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
1167                              const char *attr)
1168 {
1169         /* Format is cn=NTDS Settings,cn=<NETBIOS name of FSMO>,.... */
1170         struct ldb_dn *fsmo_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
1171         const struct ldb_val *val = ldb_dn_get_component_val(fsmo_dn, 1);
1172         const char *name = ldb_dn_get_component_name(fsmo_dn, 1);
1173
1174         if (!name || (ldb_attr_cmp(name, "cn") != 0)) {
1175                 /* Ensure this matches the format.  This gives us a
1176                  * bit more confidence that a 'cn' value will be a
1177                  * ascii string */
1178                 return NULL;
1179         }
1180         if (val) {
1181                 return (char *)val->data;
1182         }
1183         return NULL;
1184 }
1185
1186 /*
1187   work out the ntds settings dn for the current open ldb
1188 */
1189 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1190 {
1191         TALLOC_CTX *tmp_ctx;
1192         const char *root_attrs[] = { "dsServiceName", NULL };
1193         int ret;
1194         struct ldb_result *root_res;
1195         struct ldb_dn *settings_dn;
1196
1197         /* see if we have a cached copy */
1198         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "cache.settings_dn");
1199         if (settings_dn) {
1200                 return settings_dn;
1201         }
1202
1203         tmp_ctx = talloc_new(ldb);
1204         if (tmp_ctx == NULL) {
1205                 goto failed;
1206         }
1207
1208         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1209         if (ret) {
1210                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1211                          ldb_errstring(ldb)));
1212                 goto failed;
1213         }
1214
1215         if (root_res->count != 1) {
1216                 goto failed;
1217         }
1218
1219         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1220
1221         /* cache the domain_sid in the ldb */
1222         if (ldb_set_opaque(ldb, "cache.settings_dn", settings_dn) != LDB_SUCCESS) {
1223                 goto failed;
1224         }
1225
1226         talloc_steal(ldb, settings_dn);
1227         talloc_free(tmp_ctx);
1228
1229         return settings_dn;
1230
1231 failed:
1232         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1233         talloc_free(tmp_ctx);
1234         return NULL;
1235 }
1236
1237 /*
1238   work out the ntds settings invocationId for the current open ldb
1239 */
1240 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1241 {
1242         TALLOC_CTX *tmp_ctx;
1243         const char *attrs[] = { "invocationId", NULL };
1244         int ret;
1245         struct ldb_result *res;
1246         struct GUID *invocation_id;
1247
1248         /* see if we have a cached copy */
1249         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1250         if (invocation_id) {
1251                 return invocation_id;
1252         }
1253
1254         tmp_ctx = talloc_new(ldb);
1255         if (tmp_ctx == NULL) {
1256                 goto failed;
1257         }
1258
1259         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1260         if (ret) {
1261                 goto failed;
1262         }
1263
1264         if (res->count != 1) {
1265                 goto failed;
1266         }
1267
1268         invocation_id = talloc(tmp_ctx, struct GUID);
1269         if (!invocation_id) {
1270                 goto failed;
1271         }
1272
1273         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1274
1275         /* cache the domain_sid in the ldb */
1276         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1277                 goto failed;
1278         }
1279
1280         talloc_steal(ldb, invocation_id);
1281         talloc_free(tmp_ctx);
1282
1283         return invocation_id;
1284
1285 failed:
1286         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1287         talloc_free(tmp_ctx);
1288         return NULL;
1289 }
1290
1291 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1292 {
1293         TALLOC_CTX *tmp_ctx;
1294         struct GUID *invocation_id_new;
1295         struct GUID *invocation_id_old;
1296
1297         /* see if we have a cached copy */
1298         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1299                                                          "cache.invocation_id");
1300
1301         tmp_ctx = talloc_new(ldb);
1302         if (tmp_ctx == NULL) {
1303                 goto failed;
1304         }
1305
1306         invocation_id_new = talloc(tmp_ctx, struct GUID);
1307         if (!invocation_id_new) {
1308                 goto failed;
1309         }
1310
1311         *invocation_id_new = *invocation_id_in;
1312
1313         /* cache the domain_sid in the ldb */
1314         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1315                 goto failed;
1316         }
1317
1318         talloc_steal(ldb, invocation_id_new);
1319         talloc_free(tmp_ctx);
1320         talloc_free(invocation_id_old);
1321
1322         return true;
1323
1324 failed:
1325         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1326         talloc_free(tmp_ctx);
1327         return false;
1328 }
1329
1330 /*
1331   work out the ntds settings objectGUID for the current open ldb
1332 */
1333 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1334 {
1335         TALLOC_CTX *tmp_ctx;
1336         const char *attrs[] = { "objectGUID", NULL };
1337         int ret;
1338         struct ldb_result *res;
1339         struct GUID *ntds_guid;
1340
1341         /* see if we have a cached copy */
1342         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1343         if (ntds_guid) {
1344                 return ntds_guid;
1345         }
1346
1347         tmp_ctx = talloc_new(ldb);
1348         if (tmp_ctx == NULL) {
1349                 goto failed;
1350         }
1351
1352         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1353         if (ret) {
1354                 goto failed;
1355         }
1356
1357         if (res->count != 1) {
1358                 goto failed;
1359         }
1360
1361         ntds_guid = talloc(tmp_ctx, struct GUID);
1362         if (!ntds_guid) {
1363                 goto failed;
1364         }
1365
1366         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1367
1368         /* cache the domain_sid in the ldb */
1369         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1370                 goto failed;
1371         }
1372
1373         talloc_steal(ldb, ntds_guid);
1374         talloc_free(tmp_ctx);
1375
1376         return ntds_guid;
1377
1378 failed:
1379         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1380         talloc_free(tmp_ctx);
1381         return NULL;
1382 }
1383
1384 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1385 {
1386         TALLOC_CTX *tmp_ctx;
1387         struct GUID *ntds_guid_new;
1388         struct GUID *ntds_guid_old;
1389
1390         /* see if we have a cached copy */
1391         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1392
1393         tmp_ctx = talloc_new(ldb);
1394         if (tmp_ctx == NULL) {
1395                 goto failed;
1396         }
1397
1398         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1399         if (!ntds_guid_new) {
1400                 goto failed;
1401         }
1402
1403         *ntds_guid_new = *ntds_guid_in;
1404
1405         /* cache the domain_sid in the ldb */
1406         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1407                 goto failed;
1408         }
1409
1410         talloc_steal(ldb, ntds_guid_new);
1411         talloc_free(tmp_ctx);
1412         talloc_free(ntds_guid_old);
1413
1414         return true;
1415
1416 failed:
1417         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1418         talloc_free(tmp_ctx);
1419         return false;
1420 }
1421
1422 /*
1423   work out the server dn for the current open ldb
1424 */
1425 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1426 {
1427         return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1428 }
1429
1430 /*
1431   work out the server dn for the current open ldb
1432 */
1433 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1434 {
1435         struct ldb_dn *server_dn;
1436         struct ldb_dn *server_site_dn;
1437
1438         server_dn = samdb_server_dn(ldb, mem_ctx);
1439         if (!server_dn) return NULL;
1440
1441         server_site_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1442
1443         talloc_free(server_dn);
1444         return server_site_dn;
1445 }
1446
1447 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1448 {
1449         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb, mem_ctx));
1450
1451         if (val != NULL)
1452                 return (const char *) val->data;
1453         else
1454                 return NULL;
1455 }
1456
1457 /*
1458   work out if we are the PDC for the domain of the current open ldb
1459 */
1460 bool samdb_is_pdc(struct ldb_context *ldb)
1461 {
1462         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1463         int ret;
1464         struct ldb_result *dom_res;
1465         TALLOC_CTX *tmp_ctx;
1466         bool is_pdc;
1467         struct ldb_dn *pdc;
1468
1469         tmp_ctx = talloc_new(ldb);
1470         if (tmp_ctx == NULL) {
1471                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1472                 return false;
1473         }
1474
1475         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1476         if (ret) {
1477                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1478                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1479                          ldb_errstring(ldb)));
1480                 goto failed;
1481         }
1482         if (dom_res->count != 1) {
1483                 goto failed;
1484         }
1485
1486         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0], "fSMORoleOwner");
1487
1488         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1489                 is_pdc = true;
1490         } else {
1491                 is_pdc = false;
1492         }
1493
1494         talloc_free(tmp_ctx);
1495
1496         return is_pdc;
1497
1498 failed:
1499         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1500         talloc_free(tmp_ctx);
1501         return false;
1502 }
1503
1504 /*
1505   work out if we are a Global Catalog server for the domain of the current open ldb
1506 */
1507 bool samdb_is_gc(struct ldb_context *ldb)
1508 {
1509         const char *attrs[] = { "options", NULL };
1510         int ret, options;
1511         struct ldb_result *res;
1512         TALLOC_CTX *tmp_ctx;
1513
1514         tmp_ctx = talloc_new(ldb);
1515         if (tmp_ctx == NULL) {
1516                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1517                 return false;
1518         }
1519
1520         /* Query cn=ntds settings,.... */
1521         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1522         if (ret) {
1523                 talloc_free(tmp_ctx);
1524                 return false;
1525         }
1526         if (res->count != 1) {
1527                 talloc_free(tmp_ctx);
1528                 return false;
1529         }
1530
1531         options = ldb_msg_find_attr_as_int(res->msgs[0], "options", 0);
1532         talloc_free(tmp_ctx);
1533
1534         /* if options attribute has the 0x00000001 flag set, then enable the global catlog */
1535         if (options & 0x000000001) {
1536                 return true;
1537         }
1538         return false;
1539 }
1540
1541 /* Find a domain object in the parents of a particular DN.  */
1542 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1543                                    struct ldb_dn **parent_dn, const char **errstring)
1544 {
1545         TALLOC_CTX *local_ctx;
1546         struct ldb_dn *sdn = dn;
1547         struct ldb_result *res = NULL;
1548         int ret = 0;
1549         const char *attrs[] = { NULL };
1550
1551         local_ctx = talloc_new(mem_ctx);
1552         if (local_ctx == NULL) return LDB_ERR_OPERATIONS_ERROR;
1553
1554         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1555                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1556                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1557                 if (ret == LDB_SUCCESS) {
1558                         if (res->count == 1) {
1559                                 break;
1560                         }
1561                 } else {
1562                         break;
1563                 }
1564         }
1565
1566         if (ret != LDB_SUCCESS) {
1567                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1568                                              ldb_dn_get_linearized(dn),
1569                                              ldb_dn_get_linearized(sdn),
1570                                              ldb_errstring(ldb));
1571                 talloc_free(local_ctx);
1572                 return ret;
1573         }
1574         if (res->count != 1) {
1575                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1576                                              ldb_dn_get_linearized(dn));
1577                 DEBUG(0,(__location__ ": %s\n", *errstring));
1578                 talloc_free(local_ctx);
1579                 return LDB_ERR_CONSTRAINT_VIOLATION;
1580         }
1581
1582         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1583         talloc_free(local_ctx);
1584         return ret;
1585 }
1586
1587
1588 /*
1589  * Performs checks on a user password (plaintext UNIX format - attribute
1590  * "password"). The remaining parameters have to be extracted from the domain
1591  * object in the AD.
1592  *
1593  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1594  */
1595 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1596                                                 const uint32_t pwdProperties,
1597                                                 const uint32_t minPwdLength)
1598 {
1599         /* checks if the "minPwdLength" property is satisfied */
1600         if (minPwdLength > password->length)
1601                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1602
1603         /* checks the password complexity */
1604         if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1605                         && (password->data != NULL)
1606                         && (!check_password_quality((const char *) password->data)))
1607                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1608
1609         return SAMR_VALIDATION_STATUS_SUCCESS;
1610 }
1611
1612 /*
1613  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1614  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1615  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1616  * gives some more informations if the changed failed.
1617  *
1618  * The caller should have a LDB transaction wrapping this.
1619  *
1620  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
1621  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1622  *   NT_STATUS_PASSWORD_RESTRICTION
1623  */
1624 NTSTATUS samdb_set_password(struct ldb_context *ctx, TALLOC_CTX *mem_ctx,
1625                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1626                             struct ldb_message *mod,
1627                             const DATA_BLOB *new_password,
1628                             struct samr_Password *param_lmNewHash,
1629                             struct samr_Password *param_ntNewHash,
1630                             bool user_change,
1631                             enum samPwdChangeReason *reject_reason,
1632                             struct samr_DomInfo1 **_dominfo)
1633 {
1634         const char * const user_attrs[] = { "userAccountControl",
1635                                             "lmPwdHistory",
1636                                             "ntPwdHistory", 
1637                                             "dBCSPwd", "unicodePwd", 
1638                                             "objectSid", 
1639                                             "pwdLastSet", NULL };
1640         const char * const domain_attrs[] = { "minPwdLength", "pwdProperties",
1641                                               "pwdHistoryLength",
1642                                               "maxPwdAge", "minPwdAge", NULL };
1643         NTTIME pwdLastSet;
1644         uint32_t minPwdLength, pwdProperties, pwdHistoryLength;
1645         int64_t maxPwdAge, minPwdAge;
1646         uint32_t userAccountControl;
1647         struct samr_Password *sambaLMPwdHistory, *sambaNTPwdHistory,
1648                 *lmPwdHash, *ntPwdHash, *lmNewHash, *ntNewHash;
1649         struct samr_Password local_lmNewHash, local_ntNewHash;
1650         int sambaLMPwdHistory_len, sambaNTPwdHistory_len;
1651         struct dom_sid *domain_sid;
1652         struct ldb_message **res;
1653         bool restrictions;
1654         int count;
1655         time_t now = time(NULL);
1656         NTTIME now_nt;
1657         int i;
1658
1659         /* we need to know the time to compute password age */
1660         unix_to_nt_time(&now_nt, now);
1661
1662         /* pull all the user parameters */
1663         count = gendb_search_dn(ctx, mem_ctx, user_dn, &res, user_attrs);
1664         if (count != 1) {
1665                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1666         }
1667         userAccountControl = samdb_result_uint(res[0], "userAccountControl", 0);
1668         sambaLMPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1669                                          "lmPwdHistory", &sambaLMPwdHistory);
1670         sambaNTPwdHistory_len = samdb_result_hashes(mem_ctx, res[0],
1671                                          "ntPwdHistory", &sambaNTPwdHistory);
1672         lmPwdHash = samdb_result_hash(mem_ctx, res[0], "dBCSPwd");
1673         ntPwdHash = samdb_result_hash(mem_ctx, res[0], "unicodePwd");
1674         pwdLastSet = samdb_result_uint64(res[0], "pwdLastSet", 0);
1675
1676         /* Copy parameters */
1677         lmNewHash = param_lmNewHash;
1678         ntNewHash = param_ntNewHash;
1679
1680         /* Only non-trust accounts have restrictions (possibly this
1681          * test is the wrong way around, but I like to be restrictive
1682          * if possible */
1683         restrictions = !(userAccountControl & (UF_INTERDOMAIN_TRUST_ACCOUNT
1684                                                |UF_WORKSTATION_TRUST_ACCOUNT
1685                                                |UF_SERVER_TRUST_ACCOUNT)); 
1686
1687         if (domain_dn != NULL) {
1688                 /* pull the domain parameters */
1689                 count = gendb_search_dn(ctx, mem_ctx, domain_dn, &res,
1690                                                                 domain_attrs);
1691                 if (count != 1) {
1692                         DEBUG(2, ("samdb_set_password: Domain DN %s is invalid, for user %s\n", 
1693                                   ldb_dn_get_linearized(domain_dn),
1694                                   ldb_dn_get_linearized(user_dn)));
1695                         return NT_STATUS_NO_SUCH_DOMAIN;
1696                 }
1697         } else {
1698                 /* work out the domain sid, and pull the domain from there */
1699                 domain_sid = samdb_result_sid_prefix(mem_ctx, res[0],
1700                                                                 "objectSid");
1701                 if (domain_sid == NULL) {
1702                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
1703                 }
1704
1705                 count = gendb_search(ctx, mem_ctx, NULL, &res, domain_attrs, 
1706                                 "(objectSid=%s)",
1707                                 ldap_encode_ndr_dom_sid(mem_ctx, domain_sid));
1708                 if (count != 1) {
1709                         DEBUG(2, ("samdb_set_password: Could not find domain to match SID: %s, for user %s\n", 
1710                                   dom_sid_string(mem_ctx, domain_sid),
1711                                   ldb_dn_get_linearized(user_dn)));
1712                         return NT_STATUS_NO_SUCH_DOMAIN;
1713                 }
1714         }
1715
1716         minPwdLength = samdb_result_uint(res[0], "minPwdLength", 0);
1717         pwdProperties = samdb_result_uint(res[0], "pwdProperties", 0);
1718         pwdHistoryLength = samdb_result_uint(res[0], "pwdHistoryLength", 0);
1719         maxPwdAge = samdb_result_int64(res[0], "maxPwdAge", 0);
1720         minPwdAge = samdb_result_int64(res[0], "minPwdAge", 0);
1721
1722         if ((userAccountControl & UF_PASSWD_NOTREQD) != 0) {
1723                 /* see [MS-ADTS] 2.2.15 */
1724                 minPwdLength = 0;
1725         }
1726
1727         if (_dominfo != NULL) {
1728                 struct samr_DomInfo1 *dominfo;
1729                 /* on failure we need to fill in the reject reasons */
1730                 dominfo = talloc(mem_ctx, struct samr_DomInfo1);
1731                 if (dominfo == NULL) {
1732                         return NT_STATUS_NO_MEMORY;
1733                 }
1734                 dominfo->min_password_length     = minPwdLength;
1735                 dominfo->password_properties     = pwdProperties;
1736                 dominfo->password_history_length = pwdHistoryLength;
1737                 dominfo->max_password_age        = maxPwdAge;
1738                 dominfo->min_password_age        = minPwdAge;
1739                 *_dominfo = dominfo;
1740         }
1741
1742         if ((restrictions != 0) && (new_password != 0)) {
1743                 char *new_pass;
1744
1745                 /* checks if the "minPwdLength" property is satisfied */
1746                 if ((restrictions != 0)
1747                         && (minPwdLength > utf16_len_n(
1748                                 new_password->data, new_password->length)/2)) {
1749                         if (reject_reason) {
1750                                 *reject_reason = SAM_PWD_CHANGE_PASSWORD_TOO_SHORT;
1751                         }
1752                         return NT_STATUS_PASSWORD_RESTRICTION;
1753                 }
1754
1755                 /* Create the NT hash */
1756                 mdfour(local_ntNewHash.hash, new_password->data,
1757                                                         new_password->length);
1758
1759                 ntNewHash = &local_ntNewHash;
1760
1761                 /* Only check complexity if we can convert it at all.  Assuming unconvertable passwords are 'strong' */
1762                 if (convert_string_talloc_convenience(mem_ctx,
1763                           lp_iconv_convenience(ldb_get_opaque(ctx, "loadparm")),
1764                           CH_UTF16, CH_UNIX,
1765                           new_password->data, new_password->length,
1766                           (void **)&new_pass, NULL, false)) {
1767
1768                         /* checks the password complexity */
1769                         if ((restrictions != 0)
1770                                 && ((pwdProperties
1771                                         & DOMAIN_PASSWORD_COMPLEX) != 0)
1772                                 && (!check_password_quality(new_pass))) {
1773                                 if (reject_reason) {
1774                                         *reject_reason = SAM_PWD_CHANGE_NOT_COMPLEX;
1775                                 }
1776                                 return NT_STATUS_PASSWORD_RESTRICTION;
1777                         }
1778
1779                         /* compute the new lm hashes (for checking history - case insenitivly!) */
1780                         if (E_deshash(new_pass, local_lmNewHash.hash)) {
1781                                 lmNewHash = &local_lmNewHash;
1782                         }
1783                 }
1784         }
1785
1786         if ((restrictions != 0) && user_change) {
1787                 /* are all password changes disallowed? */
1788                 if ((pwdProperties & DOMAIN_REFUSE_PASSWORD_CHANGE) != 0) {
1789                         if (reject_reason) {
1790                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1791                         }
1792                         return NT_STATUS_PASSWORD_RESTRICTION;
1793                 }
1794
1795                 /* can this user change the password? */
1796                 if ((userAccountControl & UF_PASSWD_CANT_CHANGE) != 0) {
1797                         if (reject_reason) {
1798                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1799                         }
1800                         return NT_STATUS_PASSWORD_RESTRICTION;
1801                 }
1802
1803                 /* Password minimum age: yes, this is a minus. The ages are in negative 100nsec units! */
1804                 if (pwdLastSet - minPwdAge > now_nt) {
1805                         if (reject_reason) {
1806                                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1807                         }
1808                         return NT_STATUS_PASSWORD_RESTRICTION;
1809                 }
1810
1811                 /* check the immediately past password */
1812                 if (pwdHistoryLength > 0) {
1813                         if (lmNewHash && lmPwdHash && memcmp(lmNewHash->hash,
1814                                         lmPwdHash->hash, 16) == 0) {
1815                                 if (reject_reason) {
1816                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1817                                 }
1818                                 return NT_STATUS_PASSWORD_RESTRICTION;
1819                         }
1820                         if (ntNewHash && ntPwdHash && memcmp(ntNewHash->hash,
1821                                         ntPwdHash->hash, 16) == 0) {
1822                                 if (reject_reason) {
1823                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1824                                 }
1825                                 return NT_STATUS_PASSWORD_RESTRICTION;
1826                         }
1827                 }
1828
1829                 /* check the password history */
1830                 sambaLMPwdHistory_len = MIN(sambaLMPwdHistory_len,
1831                                                         pwdHistoryLength);
1832                 sambaNTPwdHistory_len = MIN(sambaNTPwdHistory_len,
1833                                                         pwdHistoryLength);
1834
1835                 for (i=0; lmNewHash && i<sambaLMPwdHistory_len;i++) {
1836                         if (memcmp(lmNewHash->hash, sambaLMPwdHistory[i].hash,
1837                                         16) == 0) {
1838                                 if (reject_reason) {
1839                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1840                                 }
1841                                 return NT_STATUS_PASSWORD_RESTRICTION;
1842                         }
1843                 }
1844                 for (i=0; ntNewHash && i<sambaNTPwdHistory_len;i++) {
1845                         if (memcmp(ntNewHash->hash, sambaNTPwdHistory[i].hash,
1846                                          16) == 0) {
1847                                 if (reject_reason) {
1848                                         *reject_reason = SAM_PWD_CHANGE_PWD_IN_HISTORY;
1849                                 }
1850                                 return NT_STATUS_PASSWORD_RESTRICTION;
1851                         }
1852                 }
1853         }
1854
1855 #define CHECK_RET(x) do { if (x != 0) return NT_STATUS_NO_MEMORY; } while(0)
1856
1857         /* the password is acceptable. Start forming the new fields */
1858         if (new_password != NULL) {
1859                 /* if we know the cleartext UTF16 password, then set it.
1860                  * Modules in ldb will set all the appropriate
1861                  * hashes */
1862                 CHECK_RET(ldb_msg_add_value(mod, "clearTextPassword", new_password, NULL));
1863         } else {
1864                 /* We don't have the cleartext, so delete the old one
1865                  * and set what we have of the hashes */
1866                 CHECK_RET(samdb_msg_add_delete(ctx, mem_ctx, mod, "clearTextPassword"));
1867
1868                 if (lmNewHash) {
1869                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "dBCSPwd", lmNewHash));
1870                 } else {
1871                         CHECK_RET(samdb_msg_add_delete(ctx, mem_ctx, mod, "dBCSPwd"));
1872                 }
1873
1874                 if (ntNewHash) {
1875                         CHECK_RET(samdb_msg_add_hash(ctx, mem_ctx, mod, "unicodePwd", ntNewHash));
1876                 } else {
1877                         CHECK_RET(samdb_msg_add_delete(ctx, mem_ctx, mod, "unicodePwd"));
1878                 }
1879         }
1880
1881         if (reject_reason) {
1882                 *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
1883         }
1884         return NT_STATUS_OK;
1885 }
1886
1887
1888 /*
1889  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1890  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1891  * as parameter if it's a user change or not ("userChange"). The "rejectReason"
1892  * gives some more informations if the changed failed.
1893  *
1894  * This wrapper function for "samdb_set_password" takes a SID as input rather
1895  * than a user DN.
1896  *
1897  * This call encapsulates a new LDB transaction for changing the password;
1898  * therefore the user hasn't to start a new one.
1899  *
1900  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
1901  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1902  *   NT_STATUS_PASSWORD_RESTRICTION
1903  */
1904 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1905                                 const struct dom_sid *user_sid,
1906                                 const DATA_BLOB *new_password,
1907                                 struct samr_Password *lmNewHash, 
1908                                 struct samr_Password *ntNewHash,
1909                                 bool user_change,
1910                                 enum samPwdChangeReason *reject_reason,
1911                                 struct samr_DomInfo1 **_dominfo) 
1912 {
1913         NTSTATUS nt_status;
1914         struct ldb_dn *user_dn;
1915         struct ldb_message *msg;
1916         int ret;
1917
1918         ret = ldb_transaction_start(ldb);
1919         if (ret != LDB_SUCCESS) {
1920                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
1921                 return NT_STATUS_TRANSACTION_ABORTED;
1922         }
1923
1924         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
1925                                   "(&(objectSid=%s)(objectClass=user))", 
1926                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
1927         if (!user_dn) {
1928                 ldb_transaction_cancel(ldb);
1929                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
1930                           dom_sid_string(mem_ctx, user_sid)));
1931                 return NT_STATUS_NO_SUCH_USER;
1932         }
1933
1934         msg = ldb_msg_new(mem_ctx);
1935         if (msg == NULL) {
1936                 ldb_transaction_cancel(ldb);
1937                 talloc_free(user_dn);
1938                 return NT_STATUS_NO_MEMORY;
1939         }
1940
1941         msg->dn = ldb_dn_copy(msg, user_dn);
1942         if (!msg->dn) {
1943                 ldb_transaction_cancel(ldb);
1944                 talloc_free(user_dn);
1945                 talloc_free(msg);
1946                 return NT_STATUS_NO_MEMORY;
1947         }
1948
1949         nt_status = samdb_set_password(ldb, mem_ctx,
1950                                        user_dn, NULL,
1951                                        msg, new_password,
1952                                        lmNewHash, ntNewHash,
1953                                        user_change,
1954                                        reject_reason, _dominfo);
1955         if (!NT_STATUS_IS_OK(nt_status)) {
1956                 ldb_transaction_cancel(ldb);
1957                 talloc_free(user_dn);
1958                 talloc_free(msg);
1959                 return nt_status;
1960         }
1961
1962         /* modify the samdb record */
1963         ret = samdb_replace(ldb, mem_ctx, msg);
1964         if (ret != LDB_SUCCESS) {
1965                 ldb_transaction_cancel(ldb);
1966                 talloc_free(user_dn);
1967                 talloc_free(msg);
1968                 return NT_STATUS_ACCESS_DENIED;
1969         }
1970
1971         talloc_free(msg);
1972
1973         ret = ldb_transaction_commit(ldb);
1974         if (ret != LDB_SUCCESS) {
1975                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
1976                          ldb_dn_get_linearized(user_dn),
1977                          ldb_errstring(ldb)));
1978                 talloc_free(user_dn);
1979                 return NT_STATUS_TRANSACTION_ABORTED;
1980         }
1981
1982         talloc_free(user_dn);
1983         return NT_STATUS_OK;
1984 }
1985
1986
1987 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
1988                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
1989 {
1990         struct ldb_message *msg;
1991         struct ldb_dn *basedn;
1992         const char *sidstr;
1993         int ret;
1994
1995         sidstr = dom_sid_string(mem_ctx, sid);
1996         NT_STATUS_HAVE_NO_MEMORY(sidstr);
1997
1998         /* We might have to create a ForeignSecurityPrincipal, even if this user
1999          * is in our own domain */
2000
2001         msg = ldb_msg_new(mem_ctx);
2002         if (msg == NULL) {
2003                 return NT_STATUS_NO_MEMORY;
2004         }
2005
2006         /* TODO: Hmmm. This feels wrong. How do I find the base dn to
2007          * put the ForeignSecurityPrincipals? d_state->domain_dn does
2008          * not work, this is wrong for the Builtin domain, there's no
2009          * cn=For...,cn=Builtin,dc={BASEDN}.  -- vl
2010          */
2011
2012         basedn = samdb_search_dn(sam_ctx, mem_ctx, NULL,
2013                                  "(&(objectClass=container)(cn=ForeignSecurityPrincipals))");
2014
2015         if (basedn == NULL) {
2016                 DEBUG(0, ("Failed to find DN for "
2017                           "ForeignSecurityPrincipal container\n"));
2018                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2019         }
2020
2021         /* add core elements to the ldb_message for the alias */
2022         msg->dn = ldb_dn_copy(mem_ctx, basedn);
2023         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr))
2024                 return NT_STATUS_NO_MEMORY;
2025
2026         samdb_msg_add_string(sam_ctx, mem_ctx, msg,
2027                              "objectClass",
2028                              "foreignSecurityPrincipal");
2029
2030         /* create the alias */
2031         ret = ldb_add(sam_ctx, msg);
2032         if (ret != 0) {
2033                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2034                          "record %s: %s\n", 
2035                          ldb_dn_get_linearized(msg->dn),
2036                          ldb_errstring(sam_ctx)));
2037                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2038         }
2039         *ret_dn = msg->dn;
2040         return NT_STATUS_OK;
2041 }
2042
2043
2044 /*
2045   Find the DN of a domain, assuming it to be a dotted.dns name
2046 */
2047
2048 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2049 {
2050         int i;
2051         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2052         const char *binary_encoded;
2053         const char **split_realm;
2054         struct ldb_dn *dn;
2055
2056         if (!tmp_ctx) {
2057                 return NULL;
2058         }
2059
2060         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2061         if (!split_realm) {
2062                 talloc_free(tmp_ctx);
2063                 return NULL;
2064         }
2065         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2066         for (i=0; split_realm[i]; i++) {
2067                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2068                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2069                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2070                                   binary_encoded, ldb_dn_get_linearized(dn)));
2071                         talloc_free(tmp_ctx);
2072                         return NULL;
2073                 }
2074         }
2075         if (!ldb_dn_validate(dn)) {
2076                 DEBUG(2, ("Failed to validated DN %s\n",
2077                           ldb_dn_get_linearized(dn)));
2078                 return NULL;
2079         }
2080         return dn;
2081 }
2082 /*
2083   Find the DN of a domain, be it the netbios or DNS name 
2084 */
2085
2086 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2087                                   const char *domain_name) 
2088 {
2089         const char * const domain_ref_attrs[] = {
2090                 "ncName", NULL
2091         };
2092         const char * const domain_ref2_attrs[] = {
2093                 NULL
2094         };
2095         struct ldb_result *res_domain_ref;
2096         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2097         /* find the domain's DN */
2098         int ret_domain = ldb_search(ldb, mem_ctx,
2099                                             &res_domain_ref, 
2100                                             samdb_partitions_dn(ldb, mem_ctx), 
2101                                             LDB_SCOPE_ONELEVEL, 
2102                                             domain_ref_attrs,
2103                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2104                                             escaped_domain);
2105         if (ret_domain != 0) {
2106                 return NULL;
2107         }
2108
2109         if (res_domain_ref->count == 0) {
2110                 ret_domain = ldb_search(ldb, mem_ctx,
2111                                                 &res_domain_ref, 
2112                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2113                                                 LDB_SCOPE_BASE,
2114                                                 domain_ref2_attrs,
2115                                                 "(objectclass=domain)");
2116                 if (ret_domain != 0) {
2117                         return NULL;
2118                 }
2119
2120                 if (res_domain_ref->count == 1) {
2121                         return res_domain_ref->msgs[0]->dn;
2122                 }
2123                 return NULL;
2124         }
2125
2126         if (res_domain_ref->count > 1) {
2127                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2128                          ret_domain, domain_name));
2129                 return NULL;
2130         }
2131
2132         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2133
2134 }
2135
2136
2137 /*
2138   use a GUID to find a DN
2139  */
2140 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2141                          TALLOC_CTX *mem_ctx,
2142                          const char *guid_str, struct ldb_dn **dn)
2143 {
2144         int ret;
2145         struct ldb_result *res;
2146         const char *attrs[] = { NULL };
2147         struct ldb_request *search_req;
2148         char *expression;
2149         struct ldb_search_options_control *options;
2150
2151         expression = talloc_asprintf(mem_ctx, "objectGUID=%s", guid_str);
2152         if (!expression) {
2153                 DEBUG(0, (__location__ ": out of memory\n"));
2154                 return LDB_ERR_OPERATIONS_ERROR;
2155         }
2156
2157         res = talloc_zero(mem_ctx, struct ldb_result);
2158         if (!res) {
2159                 DEBUG(0, (__location__ ": out of memory\n"));
2160                 return LDB_ERR_OPERATIONS_ERROR;
2161         }
2162
2163         ret = ldb_build_search_req(&search_req, ldb, mem_ctx,
2164                                    ldb_get_default_basedn(ldb),
2165                                    LDB_SCOPE_SUBTREE,
2166                                    expression, attrs,
2167                                    NULL,
2168                                    res, ldb_search_default_callback,
2169                                    NULL);
2170         if (ret != LDB_SUCCESS) {
2171                 return ret;
2172         }
2173
2174         /* we need to cope with cross-partition links, so search for
2175            the GUID over all partitions */
2176         options = talloc(search_req, struct ldb_search_options_control);
2177         if (options == NULL) {
2178                 DEBUG(0, (__location__ ": out of memory\n"));
2179                 return LDB_ERR_OPERATIONS_ERROR;
2180         }
2181         options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
2182
2183         ret = ldb_request_add_control(search_req, LDB_CONTROL_EXTENDED_DN_OID, true, NULL);
2184         if (ret != LDB_SUCCESS) {
2185                 return ret;
2186         }
2187
2188         ret = ldb_request_add_control(search_req,
2189                                       LDB_CONTROL_SEARCH_OPTIONS_OID,
2190                                       true, options);
2191         if (ret != LDB_SUCCESS) {
2192                 return ret;
2193         }
2194
2195         ret = ldb_request(ldb, search_req);
2196         if (ret != LDB_SUCCESS) {
2197                 return ret;
2198         }
2199
2200         ret = ldb_wait(search_req->handle, LDB_WAIT_ALL);
2201         if (ret != LDB_SUCCESS) {
2202                 return ret;
2203         }
2204
2205         /* this really should be exactly 1, but there is a bug in the
2206            partitions module that can return two here with the
2207            search_options control set */
2208         if (res->count < 1) {
2209                 return LDB_ERR_NO_SUCH_OBJECT;
2210         }
2211
2212         *dn = res->msgs[0]->dn;
2213
2214         return LDB_SUCCESS;
2215 }
2216
2217 /*
2218   search for attrs on one DN, allowing for deleted objects
2219  */
2220 int dsdb_search_dn_with_deleted(struct ldb_context *ldb,
2221                                 TALLOC_CTX *mem_ctx,
2222                                 struct ldb_result **_res,
2223                                 struct ldb_dn *basedn,
2224                                 const char * const *attrs)
2225 {
2226         int ret;
2227         struct ldb_request *req;
2228         TALLOC_CTX *tmp_ctx;
2229         struct ldb_result *res;
2230
2231         tmp_ctx = talloc_new(mem_ctx);
2232
2233         res = talloc_zero(tmp_ctx, struct ldb_result);
2234         if (!res) {
2235                 return LDB_ERR_OPERATIONS_ERROR;
2236         }
2237
2238         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2239                                    basedn,
2240                                    LDB_SCOPE_BASE,
2241                                    NULL,
2242                                    attrs,
2243                                    NULL,
2244                                    res,
2245                                    ldb_search_default_callback,
2246                                    NULL);
2247         if (ret != LDB_SUCCESS) {
2248                 talloc_free(tmp_ctx);
2249                 return ret;
2250         }
2251
2252         ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
2253         if (ret != LDB_SUCCESS) {
2254                 return ret;
2255         }
2256
2257         ret = ldb_request(ldb, req);
2258         if (ret == LDB_SUCCESS) {
2259                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2260         }
2261
2262         talloc_free(req);
2263         *_res = talloc_steal(mem_ctx, res);
2264         return ret;
2265 }
2266
2267
2268 /*
2269   use a DN to find a GUID
2270  */
2271 int dsdb_find_guid_by_dn(struct ldb_context *ldb, 
2272                          struct ldb_dn *dn, struct GUID *guid)
2273 {
2274         int ret;
2275         struct ldb_result *res;
2276         const char *attrs[] = { "objectGUID", NULL };
2277         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2278
2279         ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2280         if (ret != LDB_SUCCESS) {
2281                 talloc_free(tmp_ctx);
2282                 return ret;
2283         }
2284         if (res->count < 1) {
2285                 talloc_free(tmp_ctx);
2286                 return LDB_ERR_NO_SUCH_OBJECT;
2287         }
2288         *guid = samdb_result_guid(res->msgs[0], "objectGUID");
2289         talloc_free(tmp_ctx);
2290         return LDB_SUCCESS;
2291 }
2292
2293
2294
2295 /*
2296  adds the given GUID to the given ldb_message. This value is added
2297  for the given attr_name (may be either "objectGUID" or "parentGUID").
2298  */
2299 int dsdb_msg_add_guid(struct ldb_message *msg,
2300                 struct GUID *guid,
2301                 const char *attr_name)
2302 {
2303         int ret;
2304         struct ldb_val v;
2305         NTSTATUS status;
2306         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2307
2308         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2309         if (!NT_STATUS_IS_OK(status)) {
2310                 ret = LDB_ERR_OPERATIONS_ERROR;
2311                 goto done;
2312         }
2313
2314         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2315         if (ret != LDB_SUCCESS) {
2316                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2317                                          attr_name));
2318                 goto done;
2319         }
2320
2321         ret = LDB_SUCCESS;
2322
2323 done:
2324         talloc_free(tmp_ctx);
2325         return ret;
2326
2327 }
2328
2329
2330 /*
2331   use a DN to find a SID
2332  */
2333 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2334                         struct ldb_dn *dn, struct dom_sid *sid)
2335 {
2336         int ret;
2337         struct ldb_result *res;
2338         const char *attrs[] = { "objectSID", NULL };
2339         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2340         struct dom_sid *s;
2341
2342         ZERO_STRUCTP(sid);
2343
2344         ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2345         if (ret != LDB_SUCCESS) {
2346                 talloc_free(tmp_ctx);
2347                 return ret;
2348         }
2349         if (res->count < 1) {
2350                 talloc_free(tmp_ctx);
2351                 return LDB_ERR_NO_SUCH_OBJECT;
2352         }
2353         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2354         if (s == NULL) {
2355                 talloc_free(tmp_ctx);
2356                 return LDB_ERR_NO_SUCH_OBJECT;
2357         }
2358         *sid = *s;
2359         talloc_free(tmp_ctx);
2360         return LDB_SUCCESS;
2361 }
2362
2363
2364
2365 /*
2366   load a repsFromTo blob list for a given partition GUID
2367   attr must be "repsFrom" or "repsTo"
2368  */
2369 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2370                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2371 {
2372         const char *attrs[] = { attr, NULL };
2373         struct ldb_result *res = NULL;
2374         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2375         int i;
2376         struct ldb_message_element *el;
2377
2378         *r = NULL;
2379         *count = 0;
2380
2381         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2382             res->count < 1) {
2383                 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2384                 talloc_free(tmp_ctx);
2385                 return WERR_DS_DRA_INTERNAL_ERROR;
2386         }
2387
2388         el = ldb_msg_find_element(res->msgs[0], attr);
2389         if (el == NULL) {
2390                 /* it's OK to be empty */
2391                 talloc_free(tmp_ctx);
2392                 return WERR_OK;
2393         }
2394
2395         *count = el->num_values;
2396         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2397         if (*r == NULL) {
2398                 talloc_free(tmp_ctx);
2399                 return WERR_DS_DRA_INTERNAL_ERROR;
2400         }
2401
2402         for (i=0; i<(*count); i++) {
2403                 enum ndr_err_code ndr_err;
2404                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2405                                                mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2406                                                &(*r)[i], 
2407                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2408                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2409                         talloc_free(tmp_ctx);
2410                         return WERR_DS_DRA_INTERNAL_ERROR;
2411                 }
2412         }
2413
2414         talloc_free(tmp_ctx);
2415         
2416         return WERR_OK;
2417 }
2418
2419 /*
2420   save the repsFromTo blob list for a given partition GUID
2421   attr must be "repsFrom" or "repsTo"
2422  */
2423 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2424                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2425 {
2426         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2427         struct ldb_message *msg;
2428         struct ldb_message_element *el;
2429         int i;
2430
2431         msg = ldb_msg_new(tmp_ctx);
2432         msg->dn = dn;
2433         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2434                 goto failed;
2435         }
2436
2437         el->values = talloc_array(msg, struct ldb_val, count);
2438         if (!el->values) {
2439                 goto failed;
2440         }
2441
2442         for (i=0; i<count; i++) {
2443                 struct ldb_val v;
2444                 enum ndr_err_code ndr_err;
2445
2446                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2447                                                &r[i], 
2448                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2449                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2450                         goto failed;
2451                 }
2452
2453                 el->num_values++;
2454                 el->values[i] = v;
2455         }
2456
2457         if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2458                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2459                 goto failed;
2460         }
2461
2462         talloc_free(tmp_ctx);
2463         
2464         return WERR_OK;
2465
2466 failed:
2467         talloc_free(tmp_ctx);
2468         return WERR_DS_DRA_INTERNAL_ERROR;
2469 }
2470
2471
2472 /*
2473   load the uSNHighest attribute from the @REPLCHANGED object for a
2474   partition
2475  */
2476 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t *uSN)
2477 {
2478         struct ldb_request *req;
2479         int ret;
2480         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2481         struct dsdb_control_current_partition *p_ctrl;
2482         struct ldb_result *res;
2483
2484         res = talloc_zero(tmp_ctx, struct ldb_result);
2485         if (!res) {
2486                 talloc_free(tmp_ctx);
2487                 return LDB_ERR_OPERATIONS_ERROR;
2488         }
2489
2490         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2491                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2492                                    LDB_SCOPE_BASE,
2493                                    NULL, NULL,
2494                                    NULL,
2495                                    res, ldb_search_default_callback,
2496                                    NULL);
2497         if (ret != LDB_SUCCESS) {
2498                 talloc_free(tmp_ctx);
2499                 return ret;
2500         }
2501
2502         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2503         if (p_ctrl == NULL) {
2504                 talloc_free(res);
2505                 return LDB_ERR_OPERATIONS_ERROR;
2506         }
2507         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2508         p_ctrl->dn = dn;
2509         
2510
2511         ret = ldb_request_add_control(req,
2512                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2513                                       false, p_ctrl);
2514         if (ret != LDB_SUCCESS) {
2515                 talloc_free(tmp_ctx);
2516                 return ret;
2517         }
2518         
2519         /* Run the new request */
2520         ret = ldb_request(ldb, req);
2521         
2522         if (ret == LDB_SUCCESS) {
2523                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2524         }
2525
2526         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2527                 /* it hasn't been created yet, which means
2528                    an implicit value of zero */
2529                 *uSN = 0;
2530                 talloc_free(tmp_ctx);
2531                 return LDB_SUCCESS;
2532         }
2533
2534         if (ret != LDB_SUCCESS) {
2535                 talloc_free(tmp_ctx);
2536                 return ret;
2537         }
2538
2539         if (res->count < 1) {
2540                 *uSN = 0;
2541         } else {
2542                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2543         }
2544
2545         talloc_free(tmp_ctx);
2546
2547         return LDB_SUCCESS;     
2548 }
2549
2550 /*
2551   save the uSNHighest attribute in the @REPLCHANGED object for a
2552   partition
2553  */
2554 int dsdb_save_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t uSN)
2555 {
2556         struct ldb_request *req;
2557         struct ldb_message *msg;
2558         struct dsdb_control_current_partition *p_ctrl;
2559         int ret;
2560
2561         msg = ldb_msg_new(ldb);
2562         if (msg == NULL) {
2563                 return LDB_ERR_OPERATIONS_ERROR;
2564         }
2565
2566         msg->dn = ldb_dn_new(msg, ldb, "@REPLCHANGED");
2567         if (msg->dn == NULL) {
2568                 talloc_free(msg);
2569                 return LDB_ERR_OPERATIONS_ERROR;
2570         }
2571         
2572         ret = ldb_msg_add_fmt(msg, "uSNHighest", "%llu", (unsigned long long)uSN);
2573         if (ret != LDB_SUCCESS) {
2574                 talloc_free(msg);
2575                 return ret;
2576         }
2577         msg->elements[0].flags = LDB_FLAG_MOD_REPLACE;
2578         
2579
2580         p_ctrl = talloc(msg, struct dsdb_control_current_partition);
2581         if (p_ctrl == NULL) {
2582                 talloc_free(msg);
2583                 return LDB_ERR_OPERATIONS_ERROR;
2584         }
2585         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2586         p_ctrl->dn = dn;
2587
2588         ret = ldb_build_mod_req(&req, ldb, msg,
2589                                 msg,
2590                                 NULL,
2591                                 NULL, ldb_op_default_callback,
2592                                 NULL);
2593 again:
2594         if (ret != LDB_SUCCESS) {
2595                 talloc_free(msg);
2596                 return ret;
2597         }
2598         
2599         ret = ldb_request_add_control(req,
2600                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2601                                       false, p_ctrl);
2602         if (ret != LDB_SUCCESS) {
2603                 talloc_free(msg);
2604                 return ret;
2605         }
2606         
2607         /* Run the new request */
2608         ret = ldb_request(ldb, req);
2609         
2610         if (ret == LDB_SUCCESS) {
2611                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2612         }
2613         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2614                 ret = ldb_build_add_req(&req, ldb, msg,
2615                                         msg,
2616                                         NULL,
2617                                         NULL, ldb_op_default_callback,
2618                                         NULL);
2619                 goto again;
2620         }
2621         
2622         talloc_free(msg);
2623         
2624         return ret;
2625 }
2626
2627 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2628                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2629 {
2630         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2631 }
2632
2633 /*
2634   see if we are a RODC
2635
2636   TODO: This should take a sam_ctx, and lookup the right object (with
2637   a cache)
2638 */
2639 bool samdb_rodc(struct loadparm_context *lp_ctx)
2640 {
2641         return lp_parm_bool(lp_ctx, NULL, "repl", "RODC", false);
2642 }
2643
2644
2645 /*
2646   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2647
2648   flags are DS_NTDS_OPTION_*
2649 */
2650 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2651 {
2652         TALLOC_CTX *tmp_ctx;
2653         const char *attrs[] = { "options", NULL };
2654         int ret;
2655         struct ldb_result *res;
2656
2657         tmp_ctx = talloc_new(ldb);
2658         if (tmp_ctx == NULL) {
2659                 goto failed;
2660         }
2661
2662         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2663         if (ret) {
2664                 goto failed;
2665         }
2666
2667         if (res->count != 1) {
2668                 goto failed;
2669         }
2670
2671         *options = samdb_result_uint(res->msgs[0], "options", 0);
2672
2673         talloc_free(tmp_ctx);
2674
2675         return LDB_SUCCESS;
2676
2677 failed:
2678         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
2679         talloc_free(tmp_ctx);
2680         return LDB_ERR_NO_SUCH_OBJECT;
2681 }
2682
2683 /*
2684  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
2685  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
2686  */
2687 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
2688 {
2689         char **tokens, *ret;
2690         size_t i;
2691
2692         tokens = str_list_make(mem_ctx, cn, " -_");
2693         if (tokens == NULL)
2694                 return NULL;
2695
2696         /* "tolower()" and "toupper()" should also work properly on 0x00 */
2697         tokens[0][0] = tolower(tokens[0][0]);
2698         for (i = 1; i < str_list_length((const char **)tokens); i++)
2699                 tokens[i][0] = toupper(tokens[i][0]);
2700
2701         ret = talloc_strdup(mem_ctx, tokens[0]);
2702         for (i = 1; i < str_list_length((const char **)tokens); i++)
2703                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
2704
2705         talloc_free(tokens);
2706
2707         return ret;
2708 }
2709
2710 /*
2711   return domain functional level
2712   returns DS_DOMAIN_FUNCTION_*
2713  */
2714 int dsdb_functional_level(struct ldb_context *ldb)
2715 {
2716         int *domainFunctionality =
2717                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
2718         if (!domainFunctionality) {
2719                 DEBUG(0,(__location__ ": WARNING: domainFunctionality not setup\n"));
2720                 return DS_DOMAIN_FUNCTION_2000;
2721         }
2722         return *domainFunctionality;
2723 }
2724
2725 /*
2726   return a GUID from a extended DN structure
2727  */
2728 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid)
2729 {
2730         const struct ldb_val *v;
2731
2732         v = ldb_dn_get_extended_component(dn, "GUID");
2733         if (v == NULL) {
2734                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2735         }
2736
2737         return GUID_from_ndr_blob(v, guid);
2738 }
2739
2740 /*
2741   return true if a ldb_val containing a DN in storage form is deleted
2742  */
2743 bool dsdb_dn_is_deleted_val(struct ldb_val *val)
2744 {
2745         /* this relies on the sort order and exact format of
2746            linearized extended DNs */
2747         if (val->length >= 12 &&
2748             strncmp((const char *)val->data, "<DELETED=1>;", 12) == 0) {
2749                 return true;
2750         }
2751         return false;
2752 }
2753
2754 /*
2755   return a DN for a wellknown GUID
2756  */
2757 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
2758                       struct ldb_dn *nc_root, const char *wk_guid,
2759                       struct ldb_dn **wkguid_dn)
2760 {
2761         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2762         const char *attrs[] = { NULL };
2763         int ret;
2764         struct ldb_dn *dn;
2765         struct ldb_result *res;
2766
2767         /* construct the magic WKGUID DN */
2768         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
2769                             wk_guid, ldb_dn_get_linearized(nc_root));
2770         if (!wkguid_dn) {
2771                 talloc_free(tmp_ctx);
2772                 return LDB_ERR_OPERATIONS_ERROR;
2773         }
2774
2775         ret = dsdb_search_dn_with_deleted(samdb, tmp_ctx, &res, dn, attrs);
2776         if (ret != LDB_SUCCESS) {
2777                 talloc_free(tmp_ctx);
2778                 return ret;
2779         }
2780
2781         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
2782         talloc_free(tmp_ctx);
2783         return LDB_SUCCESS;
2784 }
2785
2786
2787 /*
2788   find a NC root given a DN within the NC
2789  */
2790 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2791                       struct ldb_dn **nc_root)
2792 {
2793         const char *root_attrs[] = { "namingContexts", NULL };
2794         TALLOC_CTX *tmp_ctx;
2795         int ret;
2796         struct ldb_message_element *el;
2797         struct ldb_result *root_res;
2798         int i;
2799         struct ldb_dn **nc_dns;
2800
2801         tmp_ctx = talloc_new(samdb);
2802         if (tmp_ctx == NULL) {
2803                 return LDB_ERR_OPERATIONS_ERROR;
2804         }
2805
2806         ret = ldb_search(samdb, tmp_ctx, &root_res,
2807                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
2808         if (ret) {
2809                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
2810                 talloc_free(tmp_ctx);
2811                 return ret;
2812        }
2813
2814        el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
2815        if (!el) {
2816                DEBUG(1,("Finding namingContexts element in root_res failed: %s\n",
2817                         ldb_errstring(samdb)));
2818                talloc_free(tmp_ctx);
2819                return LDB_ERR_NO_SUCH_ATTRIBUTE;
2820        }
2821
2822        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
2823        if (!nc_dns) {
2824                talloc_free(tmp_ctx);
2825                return LDB_ERR_OPERATIONS_ERROR;
2826        }
2827
2828        for (i=0; i<el->num_values; i++) {
2829                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
2830                if (nc_dns[i] == NULL) {
2831                        talloc_free(tmp_ctx);
2832                        return LDB_ERR_OPERATIONS_ERROR;
2833                }
2834        }
2835
2836        qsort(nc_dns, el->num_values, sizeof(nc_dns[0]), (comparison_fn_t)ldb_dn_compare);
2837
2838        for (i=0; i<el->num_values; i++) {
2839                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
2840                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
2841                        talloc_free(tmp_ctx);
2842                        return LDB_SUCCESS;
2843                }
2844        }
2845
2846        talloc_free(tmp_ctx);
2847        return LDB_ERR_NO_SUCH_OBJECT;
2848 }
2849
2850
2851 /*
2852   find the deleted objects DN for any object, by looking for the NC
2853   root, then looking up the wellknown GUID
2854  */
2855 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
2856                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
2857                                 struct ldb_dn **do_dn)
2858 {
2859         struct ldb_dn *nc_root;
2860         int ret;
2861
2862         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
2863         if (ret != LDB_SUCCESS) {
2864                 return ret;
2865         }
2866
2867         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
2868         talloc_free(nc_root);
2869         return ret;
2870 }