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