bfb2f0caa5a213f18a4bcc8c7767b58f90c7a946
[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;
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                 return NT_STATUS_NO_MEMORY;
1938         }
1939
1940         msg->dn = ldb_dn_copy(msg, user_dn);
1941         if (!msg->dn) {
1942                 ldb_transaction_cancel(ldb);
1943                 return NT_STATUS_NO_MEMORY;
1944         }
1945
1946         nt_status = samdb_set_password(ldb, mem_ctx,
1947                                        user_dn, NULL,
1948                                        msg, new_password,
1949                                        lmNewHash, ntNewHash,
1950                                        user_change, /* This is a password set, not change */
1951                                        reject_reason, _dominfo);
1952         if (!NT_STATUS_IS_OK(nt_status)) {
1953                 ldb_transaction_cancel(ldb);
1954                 return nt_status;
1955         }
1956
1957         /* modify the samdb record */
1958         ret = samdb_replace(ldb, mem_ctx, msg);
1959         if (ret != LDB_SUCCESS) {
1960                 ldb_transaction_cancel(ldb);
1961                 return NT_STATUS_ACCESS_DENIED;
1962         }
1963
1964         ret = ldb_transaction_commit(ldb);
1965         if (ret != LDB_SUCCESS) {
1966                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
1967                          ldb_dn_get_linearized(msg->dn),
1968                          ldb_errstring(ldb)));
1969                 return NT_STATUS_TRANSACTION_ABORTED;
1970         }
1971         return NT_STATUS_OK;
1972 }
1973
1974
1975 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
1976                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
1977 {
1978         struct ldb_message *msg;
1979         struct ldb_dn *basedn;
1980         const char *sidstr;
1981         int ret;
1982
1983         sidstr = dom_sid_string(mem_ctx, sid);
1984         NT_STATUS_HAVE_NO_MEMORY(sidstr);
1985
1986         /* We might have to create a ForeignSecurityPrincipal, even if this user
1987          * is in our own domain */
1988
1989         msg = ldb_msg_new(mem_ctx);
1990         if (msg == NULL) {
1991                 return NT_STATUS_NO_MEMORY;
1992         }
1993
1994         /* TODO: Hmmm. This feels wrong. How do I find the base dn to
1995          * put the ForeignSecurityPrincipals? d_state->domain_dn does
1996          * not work, this is wrong for the Builtin domain, there's no
1997          * cn=For...,cn=Builtin,dc={BASEDN}.  -- vl
1998          */
1999
2000         basedn = samdb_search_dn(sam_ctx, mem_ctx, NULL,
2001                                  "(&(objectClass=container)(cn=ForeignSecurityPrincipals))");
2002
2003         if (basedn == NULL) {
2004                 DEBUG(0, ("Failed to find DN for "
2005                           "ForeignSecurityPrincipal container\n"));
2006                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2007         }
2008
2009         /* add core elements to the ldb_message for the alias */
2010         msg->dn = ldb_dn_copy(mem_ctx, basedn);
2011         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr))
2012                 return NT_STATUS_NO_MEMORY;
2013
2014         samdb_msg_add_string(sam_ctx, mem_ctx, msg,
2015                              "objectClass",
2016                              "foreignSecurityPrincipal");
2017
2018         /* create the alias */
2019         ret = ldb_add(sam_ctx, msg);
2020         if (ret != 0) {
2021                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2022                          "record %s: %s\n", 
2023                          ldb_dn_get_linearized(msg->dn),
2024                          ldb_errstring(sam_ctx)));
2025                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2026         }
2027         *ret_dn = msg->dn;
2028         return NT_STATUS_OK;
2029 }
2030
2031
2032 /*
2033   Find the DN of a domain, assuming it to be a dotted.dns name
2034 */
2035
2036 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2037 {
2038         int i;
2039         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2040         const char *binary_encoded;
2041         const char **split_realm;
2042         struct ldb_dn *dn;
2043
2044         if (!tmp_ctx) {
2045                 return NULL;
2046         }
2047
2048         split_realm = (const char **)str_list_make(tmp_ctx, dns_domain, ".");
2049         if (!split_realm) {
2050                 talloc_free(tmp_ctx);
2051                 return NULL;
2052         }
2053         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2054         for (i=0; split_realm[i]; i++) {
2055                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2056                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2057                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2058                                   binary_encoded, ldb_dn_get_linearized(dn)));
2059                         talloc_free(tmp_ctx);
2060                         return NULL;
2061                 }
2062         }
2063         if (!ldb_dn_validate(dn)) {
2064                 DEBUG(2, ("Failed to validated DN %s\n",
2065                           ldb_dn_get_linearized(dn)));
2066                 return NULL;
2067         }
2068         return dn;
2069 }
2070 /*
2071   Find the DN of a domain, be it the netbios or DNS name 
2072 */
2073
2074 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2075                                   const char *domain_name) 
2076 {
2077         const char * const domain_ref_attrs[] = {
2078                 "ncName", NULL
2079         };
2080         const char * const domain_ref2_attrs[] = {
2081                 NULL
2082         };
2083         struct ldb_result *res_domain_ref;
2084         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2085         /* find the domain's DN */
2086         int ret_domain = ldb_search(ldb, mem_ctx,
2087                                             &res_domain_ref, 
2088                                             samdb_partitions_dn(ldb, mem_ctx), 
2089                                             LDB_SCOPE_ONELEVEL, 
2090                                             domain_ref_attrs,
2091                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2092                                             escaped_domain);
2093         if (ret_domain != 0) {
2094                 return NULL;
2095         }
2096
2097         if (res_domain_ref->count == 0) {
2098                 ret_domain = ldb_search(ldb, mem_ctx,
2099                                                 &res_domain_ref, 
2100                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2101                                                 LDB_SCOPE_BASE,
2102                                                 domain_ref2_attrs,
2103                                                 "(objectclass=domain)");
2104                 if (ret_domain != 0) {
2105                         return NULL;
2106                 }
2107
2108                 if (res_domain_ref->count == 1) {
2109                         return res_domain_ref->msgs[0]->dn;
2110                 }
2111                 return NULL;
2112         }
2113
2114         if (res_domain_ref->count > 1) {
2115                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2116                          ret_domain, domain_name));
2117                 return NULL;
2118         }
2119
2120         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2121
2122 }
2123
2124
2125 /*
2126   use a GUID to find a DN
2127  */
2128 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2129                          TALLOC_CTX *mem_ctx,
2130                          const char *guid_str, struct ldb_dn **dn)
2131 {
2132         int ret;
2133         struct ldb_result *res;
2134         const char *attrs[] = { NULL };
2135         struct ldb_request *search_req;
2136         char *expression;
2137         struct ldb_search_options_control *options;
2138
2139         expression = talloc_asprintf(mem_ctx, "objectGUID=%s", guid_str);
2140         if (!expression) {
2141                 DEBUG(0, (__location__ ": out of memory\n"));
2142                 return LDB_ERR_OPERATIONS_ERROR;
2143         }
2144
2145         res = talloc_zero(mem_ctx, struct ldb_result);
2146         if (!res) {
2147                 DEBUG(0, (__location__ ": out of memory\n"));
2148                 return LDB_ERR_OPERATIONS_ERROR;
2149         }
2150
2151         ret = ldb_build_search_req(&search_req, ldb, mem_ctx,
2152                                    ldb_get_default_basedn(ldb),
2153                                    LDB_SCOPE_SUBTREE,
2154                                    expression, attrs,
2155                                    NULL,
2156                                    res, ldb_search_default_callback,
2157                                    NULL);
2158         if (ret != LDB_SUCCESS) {
2159                 return ret;
2160         }
2161
2162         /* we need to cope with cross-partition links, so search for
2163            the GUID over all partitions */
2164         options = talloc(search_req, struct ldb_search_options_control);
2165         if (options == NULL) {
2166                 DEBUG(0, (__location__ ": out of memory\n"));
2167                 return LDB_ERR_OPERATIONS_ERROR;
2168         }
2169         options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
2170
2171         ret = ldb_request_add_control(search_req, LDB_CONTROL_EXTENDED_DN_OID, true, NULL);
2172         if (ret != LDB_SUCCESS) {
2173                 return ret;
2174         }
2175
2176         ret = ldb_request_add_control(search_req,
2177                                       LDB_CONTROL_SEARCH_OPTIONS_OID,
2178                                       true, options);
2179         if (ret != LDB_SUCCESS) {
2180                 return ret;
2181         }
2182
2183         ret = ldb_request(ldb, search_req);
2184         if (ret != LDB_SUCCESS) {
2185                 return ret;
2186         }
2187
2188         ret = ldb_wait(search_req->handle, LDB_WAIT_ALL);
2189         if (ret != LDB_SUCCESS) {
2190                 return ret;
2191         }
2192
2193         /* this really should be exactly 1, but there is a bug in the
2194            partitions module that can return two here with the
2195            search_options control set */
2196         if (res->count < 1) {
2197                 return LDB_ERR_NO_SUCH_OBJECT;
2198         }
2199
2200         *dn = res->msgs[0]->dn;
2201
2202         return LDB_SUCCESS;
2203 }
2204
2205 /*
2206   search for attrs on one DN, allowing for deleted objects
2207  */
2208 int dsdb_search_dn_with_deleted(struct ldb_context *ldb,
2209                                 TALLOC_CTX *mem_ctx,
2210                                 struct ldb_result **_res,
2211                                 struct ldb_dn *basedn,
2212                                 const char * const *attrs)
2213 {
2214         int ret;
2215         struct ldb_request *req;
2216         TALLOC_CTX *tmp_ctx;
2217         struct ldb_result *res;
2218
2219         tmp_ctx = talloc_new(mem_ctx);
2220
2221         res = talloc_zero(tmp_ctx, struct ldb_result);
2222         if (!res) {
2223                 return LDB_ERR_OPERATIONS_ERROR;
2224         }
2225
2226         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2227                                    basedn,
2228                                    LDB_SCOPE_BASE,
2229                                    NULL,
2230                                    attrs,
2231                                    NULL,
2232                                    res,
2233                                    ldb_search_default_callback,
2234                                    NULL);
2235         if (ret != LDB_SUCCESS) {
2236                 talloc_free(tmp_ctx);
2237                 return ret;
2238         }
2239
2240         ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
2241         if (ret != LDB_SUCCESS) {
2242                 return ret;
2243         }
2244
2245         ret = ldb_request(ldb, req);
2246         if (ret == LDB_SUCCESS) {
2247                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2248         }
2249
2250         talloc_free(req);
2251         *_res = talloc_steal(mem_ctx, res);
2252         return ret;
2253 }
2254
2255
2256 /*
2257   use a DN to find a GUID
2258  */
2259 int dsdb_find_guid_by_dn(struct ldb_context *ldb, 
2260                          struct ldb_dn *dn, struct GUID *guid)
2261 {
2262         int ret;
2263         struct ldb_result *res;
2264         const char *attrs[] = { "objectGUID", NULL };
2265         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2266
2267         ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2268         if (ret != LDB_SUCCESS) {
2269                 talloc_free(tmp_ctx);
2270                 return ret;
2271         }
2272         if (res->count < 1) {
2273                 talloc_free(tmp_ctx);
2274                 return LDB_ERR_NO_SUCH_OBJECT;
2275         }
2276         *guid = samdb_result_guid(res->msgs[0], "objectGUID");
2277         talloc_free(tmp_ctx);
2278         return LDB_SUCCESS;
2279 }
2280
2281
2282
2283 /*
2284  adds the given GUID to the given ldb_message. This value is added
2285  for the given attr_name (may be either "objectGUID" or "parentGUID").
2286  */
2287 int dsdb_msg_add_guid(struct ldb_message *msg,
2288                 struct GUID *guid,
2289                 const char *attr_name)
2290 {
2291         int ret;
2292         struct ldb_val v;
2293         NTSTATUS status;
2294         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2295
2296         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2297         if (!NT_STATUS_IS_OK(status)) {
2298                 ret = LDB_ERR_OPERATIONS_ERROR;
2299                 goto done;
2300         }
2301
2302         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2303         if (ret != LDB_SUCCESS) {
2304                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2305                                          attr_name));
2306                 goto done;
2307         }
2308
2309         ret = LDB_SUCCESS;
2310
2311 done:
2312         talloc_free(tmp_ctx);
2313         return ret;
2314
2315 }
2316
2317
2318 /*
2319   use a DN to find a SID
2320  */
2321 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2322                         struct ldb_dn *dn, struct dom_sid *sid)
2323 {
2324         int ret;
2325         struct ldb_result *res;
2326         const char *attrs[] = { "objectSID", NULL };
2327         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2328         struct dom_sid *s;
2329
2330         ZERO_STRUCTP(sid);
2331
2332         ret = dsdb_search_dn_with_deleted(ldb, tmp_ctx, &res, dn, attrs);
2333         if (ret != LDB_SUCCESS) {
2334                 talloc_free(tmp_ctx);
2335                 return ret;
2336         }
2337         if (res->count < 1) {
2338                 talloc_free(tmp_ctx);
2339                 return LDB_ERR_NO_SUCH_OBJECT;
2340         }
2341         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSID");
2342         if (s == NULL) {
2343                 talloc_free(tmp_ctx);
2344                 return LDB_ERR_NO_SUCH_OBJECT;
2345         }
2346         *sid = *s;
2347         talloc_free(tmp_ctx);
2348         return LDB_SUCCESS;
2349 }
2350
2351
2352
2353 /*
2354   load a repsFromTo blob list for a given partition GUID
2355   attr must be "repsFrom" or "repsTo"
2356  */
2357 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2358                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2359 {
2360         const char *attrs[] = { attr, NULL };
2361         struct ldb_result *res = NULL;
2362         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2363         int i;
2364         struct ldb_message_element *el;
2365
2366         *r = NULL;
2367         *count = 0;
2368
2369         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
2370             res->count < 1) {
2371                 DEBUG(0,("dsdb_loadreps: failed to read partition object\n"));
2372                 talloc_free(tmp_ctx);
2373                 return WERR_DS_DRA_INTERNAL_ERROR;
2374         }
2375
2376         el = ldb_msg_find_element(res->msgs[0], attr);
2377         if (el == NULL) {
2378                 /* it's OK to be empty */
2379                 talloc_free(tmp_ctx);
2380                 return WERR_OK;
2381         }
2382
2383         *count = el->num_values;
2384         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2385         if (*r == NULL) {
2386                 talloc_free(tmp_ctx);
2387                 return WERR_DS_DRA_INTERNAL_ERROR;
2388         }
2389
2390         for (i=0; i<(*count); i++) {
2391                 enum ndr_err_code ndr_err;
2392                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2393                                                mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2394                                                &(*r)[i], 
2395                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2396                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2397                         talloc_free(tmp_ctx);
2398                         return WERR_DS_DRA_INTERNAL_ERROR;
2399                 }
2400         }
2401
2402         talloc_free(tmp_ctx);
2403         
2404         return WERR_OK;
2405 }
2406
2407 /*
2408   save the repsFromTo blob list for a given partition GUID
2409   attr must be "repsFrom" or "repsTo"
2410  */
2411 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2412                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2413 {
2414         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2415         struct ldb_message *msg;
2416         struct ldb_message_element *el;
2417         int i;
2418
2419         msg = ldb_msg_new(tmp_ctx);
2420         msg->dn = dn;
2421         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2422                 goto failed;
2423         }
2424
2425         el->values = talloc_array(msg, struct ldb_val, count);
2426         if (!el->values) {
2427                 goto failed;
2428         }
2429
2430         for (i=0; i<count; i++) {
2431                 struct ldb_val v;
2432                 enum ndr_err_code ndr_err;
2433
2434                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
2435                                                &r[i], 
2436                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2437                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2438                         goto failed;
2439                 }
2440
2441                 el->num_values++;
2442                 el->values[i] = v;
2443         }
2444
2445         if (ldb_modify(sam_ctx, msg) != LDB_SUCCESS) {
2446                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2447                 goto failed;
2448         }
2449
2450         talloc_free(tmp_ctx);
2451         
2452         return WERR_OK;
2453
2454 failed:
2455         talloc_free(tmp_ctx);
2456         return WERR_DS_DRA_INTERNAL_ERROR;
2457 }
2458
2459
2460 /*
2461   load the uSNHighest attribute from the @REPLCHANGED object for a
2462   partition
2463  */
2464 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t *uSN)
2465 {
2466         struct ldb_request *req;
2467         int ret;
2468         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2469         struct dsdb_control_current_partition *p_ctrl;
2470         struct ldb_result *res;
2471
2472         res = talloc_zero(tmp_ctx, struct ldb_result);
2473         if (!res) {
2474                 talloc_free(tmp_ctx);
2475                 return LDB_ERR_OPERATIONS_ERROR;
2476         }
2477
2478         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2479                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2480                                    LDB_SCOPE_BASE,
2481                                    NULL, NULL,
2482                                    NULL,
2483                                    res, ldb_search_default_callback,
2484                                    NULL);
2485         if (ret != LDB_SUCCESS) {
2486                 talloc_free(tmp_ctx);
2487                 return ret;
2488         }
2489
2490         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2491         if (p_ctrl == NULL) {
2492                 talloc_free(res);
2493                 return LDB_ERR_OPERATIONS_ERROR;
2494         }
2495         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2496         p_ctrl->dn = dn;
2497         
2498
2499         ret = ldb_request_add_control(req,
2500                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2501                                       false, p_ctrl);
2502         if (ret != LDB_SUCCESS) {
2503                 talloc_free(tmp_ctx);
2504                 return ret;
2505         }
2506         
2507         /* Run the new request */
2508         ret = ldb_request(ldb, req);
2509         
2510         if (ret == LDB_SUCCESS) {
2511                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2512         }
2513
2514         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2515                 /* it hasn't been created yet, which means
2516                    an implicit value of zero */
2517                 *uSN = 0;
2518                 talloc_free(tmp_ctx);
2519                 return LDB_SUCCESS;
2520         }
2521
2522         if (ret != LDB_SUCCESS) {
2523                 talloc_free(tmp_ctx);
2524                 return ret;
2525         }
2526
2527         if (res->count < 1) {
2528                 *uSN = 0;
2529         } else {
2530                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2531         }
2532
2533         talloc_free(tmp_ctx);
2534
2535         return LDB_SUCCESS;     
2536 }
2537
2538 /*
2539   save the uSNHighest attribute in the @REPLCHANGED object for a
2540   partition
2541  */
2542 int dsdb_save_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn, uint64_t uSN)
2543 {
2544         struct ldb_request *req;
2545         struct ldb_message *msg;
2546         struct dsdb_control_current_partition *p_ctrl;
2547         int ret;
2548
2549         msg = ldb_msg_new(ldb);
2550         if (msg == NULL) {
2551                 return LDB_ERR_OPERATIONS_ERROR;
2552         }
2553
2554         msg->dn = ldb_dn_new(msg, ldb, "@REPLCHANGED");
2555         if (msg->dn == NULL) {
2556                 talloc_free(msg);
2557                 return LDB_ERR_OPERATIONS_ERROR;
2558         }
2559         
2560         ret = ldb_msg_add_fmt(msg, "uSNHighest", "%llu", (unsigned long long)uSN);
2561         if (ret != LDB_SUCCESS) {
2562                 talloc_free(msg);
2563                 return ret;
2564         }
2565         msg->elements[0].flags = LDB_FLAG_MOD_REPLACE;
2566         
2567
2568         p_ctrl = talloc(msg, struct dsdb_control_current_partition);
2569         if (p_ctrl == NULL) {
2570                 talloc_free(msg);
2571                 return LDB_ERR_OPERATIONS_ERROR;
2572         }
2573         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2574         p_ctrl->dn = dn;
2575
2576         ret = ldb_build_mod_req(&req, ldb, msg,
2577                                 msg,
2578                                 NULL,
2579                                 NULL, ldb_op_default_callback,
2580                                 NULL);
2581 again:
2582         if (ret != LDB_SUCCESS) {
2583                 talloc_free(msg);
2584                 return ret;
2585         }
2586         
2587         ret = ldb_request_add_control(req,
2588                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2589                                       false, p_ctrl);
2590         if (ret != LDB_SUCCESS) {
2591                 talloc_free(msg);
2592                 return ret;
2593         }
2594         
2595         /* Run the new request */
2596         ret = ldb_request(ldb, req);
2597         
2598         if (ret == LDB_SUCCESS) {
2599                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2600         }
2601         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2602                 ret = ldb_build_add_req(&req, ldb, msg,
2603                                         msg,
2604                                         NULL,
2605                                         NULL, ldb_op_default_callback,
2606                                         NULL);
2607                 goto again;
2608         }
2609         
2610         talloc_free(msg);
2611         
2612         return ret;
2613 }
2614
2615 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2616                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2617 {
2618         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2619 }
2620
2621 /*
2622   see if we are a RODC
2623
2624   TODO: This should take a sam_ctx, and lookup the right object (with
2625   a cache)
2626 */
2627 bool samdb_rodc(struct loadparm_context *lp_ctx)
2628 {
2629         return lp_parm_bool(lp_ctx, NULL, "repl", "RODC", false);
2630 }
2631
2632
2633 /*
2634   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2635
2636   flags are DS_NTDS_OPTION_*
2637 */
2638 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2639 {
2640         TALLOC_CTX *tmp_ctx;
2641         const char *attrs[] = { "options", NULL };
2642         int ret;
2643         struct ldb_result *res;
2644
2645         tmp_ctx = talloc_new(ldb);
2646         if (tmp_ctx == NULL) {
2647                 goto failed;
2648         }
2649
2650         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2651         if (ret) {
2652                 goto failed;
2653         }
2654
2655         if (res->count != 1) {
2656                 goto failed;
2657         }
2658
2659         *options = samdb_result_uint(res->msgs[0], "options", 0);
2660
2661         talloc_free(tmp_ctx);
2662
2663         return LDB_SUCCESS;
2664
2665 failed:
2666         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
2667         talloc_free(tmp_ctx);
2668         return LDB_ERR_NO_SUCH_OBJECT;
2669 }
2670
2671 /*
2672  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
2673  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
2674  */
2675 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
2676 {
2677         char **tokens, *ret;
2678         size_t i;
2679
2680         tokens = str_list_make(mem_ctx, cn, " -_");
2681         if (tokens == NULL)
2682                 return NULL;
2683
2684         /* "tolower()" and "toupper()" should also work properly on 0x00 */
2685         tokens[0][0] = tolower(tokens[0][0]);
2686         for (i = 1; i < str_list_length((const char **)tokens); i++)
2687                 tokens[i][0] = toupper(tokens[i][0]);
2688
2689         ret = talloc_strdup(mem_ctx, tokens[0]);
2690         for (i = 1; i < str_list_length((const char **)tokens); i++)
2691                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
2692
2693         talloc_free(tokens);
2694
2695         return ret;
2696 }
2697
2698 /*
2699   return domain functional level
2700   returns DS_DOMAIN_FUNCTION_*
2701  */
2702 int dsdb_functional_level(struct ldb_context *ldb)
2703 {
2704         int *domainFunctionality =
2705                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
2706         if (!domainFunctionality) {
2707                 DEBUG(0,(__location__ ": WARNING: domainFunctionality not setup\n"));
2708                 return DS_DOMAIN_FUNCTION_2000;
2709         }
2710         return *domainFunctionality;
2711 }
2712
2713 /*
2714   return a GUID from a extended DN structure
2715  */
2716 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid)
2717 {
2718         const struct ldb_val *v;
2719
2720         v = ldb_dn_get_extended_component(dn, "GUID");
2721         if (v == NULL) {
2722                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
2723         }
2724
2725         return GUID_from_ndr_blob(v, guid);
2726 }