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