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