s4-dsdb: Add const
[kai/samba.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_module.h"
28 #include "ldb_errors.h"
29 #include "../lib/util/util_ldb.h"
30 #include "../lib/crypto/crypto.h"
31 #include "dsdb/samdb/samdb.h"
32 #include "libcli/security/security.h"
33 #include "librpc/gen_ndr/ndr_security.h"
34 #include "librpc/gen_ndr/ndr_misc.h"
35 #include "../libds/common/flags.h"
36 #include "dsdb/common/proto.h"
37 #include "libcli/ldap/ldap_ndr.h"
38 #include "param/param.h"
39 #include "libcli/auth/libcli_auth.h"
40 #include "librpc/gen_ndr/ndr_drsblobs.h"
41 #include "system/locale.h"
42 #include "lib/util/tsort.h"
43 #include "dsdb/common/util.h"
44 #include "lib/socket/socket.h"
45 #include "librpc/gen_ndr/irpc.h"
46 #include "libds/common/flag_mapping.h"
47
48 /*
49   search the sam for the specified attributes in a specific domain, filter on
50   objectSid being in domain_sid.
51 */
52 int samdb_search_domain(struct ldb_context *sam_ldb,
53                         TALLOC_CTX *mem_ctx, 
54                         struct ldb_dn *basedn,
55                         struct ldb_message ***res,
56                         const char * const *attrs,
57                         const struct dom_sid *domain_sid,
58                         const char *format, ...)  _PRINTF_ATTRIBUTE(7,8)
59 {
60         va_list ap;
61         int i, count;
62
63         va_start(ap, format);
64         count = gendb_search_v(sam_ldb, mem_ctx, basedn,
65                                res, attrs, format, ap);
66         va_end(ap);
67
68         i=0;
69
70         while (i<count) {
71                 struct dom_sid *entry_sid;
72
73                 entry_sid = samdb_result_dom_sid(mem_ctx, (*res)[i], "objectSid");
74
75                 if ((entry_sid == NULL) ||
76                     (!dom_sid_in_domain(domain_sid, entry_sid))) {
77                         /* Delete that entry from the result set */
78                         (*res)[i] = (*res)[count-1];
79                         count -= 1;
80                         talloc_free(entry_sid);
81                         continue;
82                 }
83                 talloc_free(entry_sid);
84                 i += 1;
85         }
86
87         return count;
88 }
89
90 /*
91   search the sam for a single string attribute in exactly 1 record
92 */
93 const char *samdb_search_string_v(struct ldb_context *sam_ldb,
94                                   TALLOC_CTX *mem_ctx,
95                                   struct ldb_dn *basedn,
96                                   const char *attr_name,
97                                   const char *format, va_list ap) _PRINTF_ATTRIBUTE(5,0)
98 {
99         int count;
100         const char *attrs[2] = { NULL, NULL };
101         struct ldb_message **res = NULL;
102
103         attrs[0] = attr_name;
104
105         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
106         if (count > 1) {                
107                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
108                          attr_name, format, count));
109         }
110         if (count != 1) {
111                 talloc_free(res);
112                 return NULL;
113         }
114
115         return ldb_msg_find_attr_as_string(res[0], attr_name, NULL);
116 }
117
118 /*
119   search the sam for a single string attribute in exactly 1 record
120 */
121 const char *samdb_search_string(struct ldb_context *sam_ldb,
122                                 TALLOC_CTX *mem_ctx,
123                                 struct ldb_dn *basedn,
124                                 const char *attr_name,
125                                 const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
126 {
127         va_list ap;
128         const char *str;
129
130         va_start(ap, format);
131         str = samdb_search_string_v(sam_ldb, mem_ctx, basedn, attr_name, format, ap);
132         va_end(ap);
133
134         return str;
135 }
136
137 struct ldb_dn *samdb_search_dn(struct ldb_context *sam_ldb,
138                                TALLOC_CTX *mem_ctx,
139                                struct ldb_dn *basedn,
140                                const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
141 {
142         va_list ap;
143         struct ldb_dn *ret;
144         struct ldb_message **res = NULL;
145         int count;
146
147         va_start(ap, format);
148         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, NULL, format, ap);
149         va_end(ap);
150
151         if (count != 1) return NULL;
152
153         ret = talloc_steal(mem_ctx, res[0]->dn);
154         talloc_free(res);
155
156         return ret;
157 }
158
159 /*
160   search the sam for a dom_sid attribute in exactly 1 record
161 */
162 struct dom_sid *samdb_search_dom_sid(struct ldb_context *sam_ldb,
163                                      TALLOC_CTX *mem_ctx,
164                                      struct ldb_dn *basedn,
165                                      const char *attr_name,
166                                      const char *format, ...) _PRINTF_ATTRIBUTE(5,6)
167 {
168         va_list ap;
169         int count;
170         struct ldb_message **res;
171         const char *attrs[2] = { NULL, NULL };
172         struct dom_sid *sid;
173
174         attrs[0] = attr_name;
175
176         va_start(ap, format);
177         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
178         va_end(ap);
179         if (count > 1) {                
180                 DEBUG(1,("samdb: search for %s %s not single valued (count=%d)\n", 
181                          attr_name, format, count));
182         }
183         if (count != 1) {
184                 talloc_free(res);
185                 return NULL;
186         }
187         sid = samdb_result_dom_sid(mem_ctx, res[0], attr_name);
188         talloc_free(res);
189         return sid;     
190 }
191
192 /*
193   return the count of the number of records in the sam matching the query
194 */
195 int samdb_search_count(struct ldb_context *sam_ldb,
196                        TALLOC_CTX *mem_ctx,
197                        struct ldb_dn *basedn,
198                        const char *format, ...) _PRINTF_ATTRIBUTE(4,5)
199 {
200         va_list ap;
201         const char *attrs[] = { NULL };
202         int ret;
203
204         va_start(ap, format);
205         ret = gendb_search_v(sam_ldb, mem_ctx, basedn, NULL, attrs, format, ap);
206         va_end(ap);
207
208         return ret;
209 }
210
211
212 /*
213   search the sam for a single integer attribute in exactly 1 record
214 */
215 unsigned int samdb_search_uint(struct ldb_context *sam_ldb,
216                          TALLOC_CTX *mem_ctx,
217                          unsigned int default_value,
218                          struct ldb_dn *basedn,
219                          const char *attr_name,
220                          const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
221 {
222         va_list ap;
223         int count;
224         struct ldb_message **res;
225         const char *attrs[2] = { NULL, NULL };
226
227         attrs[0] = attr_name;
228
229         va_start(ap, format);
230         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
231         va_end(ap);
232
233         if (count != 1) {
234                 return default_value;
235         }
236
237         return ldb_msg_find_attr_as_uint(res[0], attr_name, default_value);
238 }
239
240 /*
241   search the sam for a single signed 64 bit integer attribute in exactly 1 record
242 */
243 int64_t samdb_search_int64(struct ldb_context *sam_ldb,
244                            TALLOC_CTX *mem_ctx,
245                            int64_t default_value,
246                            struct ldb_dn *basedn,
247                            const char *attr_name,
248                            const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
249 {
250         va_list ap;
251         int count;
252         struct ldb_message **res;
253         const char *attrs[2] = { NULL, NULL };
254
255         attrs[0] = attr_name;
256
257         va_start(ap, format);
258         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
259         va_end(ap);
260
261         if (count != 1) {
262                 return default_value;
263         }
264
265         return ldb_msg_find_attr_as_int64(res[0], attr_name, default_value);
266 }
267
268 /*
269   search the sam for multipe records each giving a single string attribute
270   return the number of matches, or -1 on error
271 */
272 int samdb_search_string_multiple(struct ldb_context *sam_ldb,
273                                  TALLOC_CTX *mem_ctx,
274                                  struct ldb_dn *basedn,
275                                  const char ***strs,
276                                  const char *attr_name,
277                                  const char *format, ...) _PRINTF_ATTRIBUTE(6,7)
278 {
279         va_list ap;
280         int count, i;
281         const char *attrs[2] = { NULL, NULL };
282         struct ldb_message **res = NULL;
283
284         attrs[0] = attr_name;
285
286         va_start(ap, format);
287         count = gendb_search_v(sam_ldb, mem_ctx, basedn, &res, attrs, format, ap);
288         va_end(ap);
289
290         if (count <= 0) {
291                 return count;
292         }
293
294         /* make sure its single valued */
295         for (i=0;i<count;i++) {
296                 if (res[i]->num_elements != 1) {
297                         DEBUG(1,("samdb: search for %s %s not single valued\n", 
298                                  attr_name, format));
299                         talloc_free(res);
300                         return -1;
301                 }
302         }
303
304         *strs = talloc_array(mem_ctx, const char *, count+1);
305         if (! *strs) {
306                 talloc_free(res);
307                 return -1;
308         }
309
310         for (i=0;i<count;i++) {
311                 (*strs)[i] = ldb_msg_find_attr_as_string(res[i], attr_name, NULL);
312         }
313         (*strs)[count] = NULL;
314
315         return count;
316 }
317
318 struct ldb_dn *samdb_result_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
319                                const char *attr, struct ldb_dn *default_value)
320 {
321         struct ldb_dn *ret_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, msg, attr);
322         if (!ret_dn) {
323                 return default_value;
324         }
325         return ret_dn;
326 }
327
328 /*
329   pull a rid from a objectSid in a result set. 
330 */
331 uint32_t samdb_result_rid_from_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
332                                    const char *attr, uint32_t default_value)
333 {
334         struct dom_sid *sid;
335         uint32_t rid;
336
337         sid = samdb_result_dom_sid(mem_ctx, msg, attr);
338         if (sid == NULL) {
339                 return default_value;
340         }
341         rid = sid->sub_auths[sid->num_auths-1];
342         talloc_free(sid);
343         return rid;
344 }
345
346 /*
347   pull a dom_sid structure from a objectSid in a result set. 
348 */
349 struct dom_sid *samdb_result_dom_sid(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
350                                      const char *attr)
351 {
352         bool ok;
353         const struct ldb_val *v;
354         struct dom_sid *sid;
355         v = ldb_msg_find_ldb_val(msg, attr);
356         if (v == NULL) {
357                 return NULL;
358         }
359         sid = talloc(mem_ctx, struct dom_sid);
360         if (sid == NULL) {
361                 return NULL;
362         }
363         ok = sid_blob_parse(*v, sid);
364         if (!ok) {
365                 talloc_free(sid);
366                 return NULL;
367         }
368         return sid;
369 }
370
371 /*
372   pull a guid structure from a objectGUID in a result set. 
373 */
374 struct GUID samdb_result_guid(const struct ldb_message *msg, const char *attr)
375 {
376         const struct ldb_val *v;
377         struct GUID guid;
378         NTSTATUS status;
379
380         v = ldb_msg_find_ldb_val(msg, attr);
381         if (!v) return GUID_zero();
382
383         status = GUID_from_ndr_blob(v, &guid);
384         if (!NT_STATUS_IS_OK(status)) {
385                 return GUID_zero();
386         }
387
388         return guid;
389 }
390
391 /*
392   pull a sid prefix from a objectSid in a result set. 
393   this is used to find the domain sid for a user
394 */
395 struct dom_sid *samdb_result_sid_prefix(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, 
396                                         const char *attr)
397 {
398         struct dom_sid *sid = samdb_result_dom_sid(mem_ctx, msg, attr);
399         if (!sid || sid->num_auths < 1) return NULL;
400         sid->num_auths--;
401         return sid;
402 }
403
404 /*
405   pull a NTTIME in a result set. 
406 */
407 NTTIME samdb_result_nttime(const struct ldb_message *msg, const char *attr,
408                            NTTIME default_value)
409 {
410         return ldb_msg_find_attr_as_uint64(msg, attr, default_value);
411 }
412
413 /*
414  * Windows stores 0 for lastLogoff.
415  * But when a MS DC return the lastLogoff (as Logoff Time)
416  * it returns 0x7FFFFFFFFFFFFFFF, not returning this value in this case
417  * cause windows 2008 and newer version to fail for SMB requests
418  */
419 NTTIME samdb_result_last_logoff(const struct ldb_message *msg)
420 {
421         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "lastLogoff",0);
422
423         if (ret == 0)
424                 ret = 0x7FFFFFFFFFFFFFFFULL;
425
426         return ret;
427 }
428
429 /*
430  * Windows uses both 0 and 9223372036854775807 (0x7FFFFFFFFFFFFFFFULL) to
431  * indicate an account doesn't expire.
432  *
433  * When Windows initially creates an account, it sets
434  * accountExpires = 9223372036854775807 (0x7FFFFFFFFFFFFFFF).  However,
435  * when changing from an account having a specific expiration date to
436  * that account never expiring, it sets accountExpires = 0.
437  *
438  * Consolidate that logic here to allow clearer logic for account expiry in
439  * the rest of the code.
440  */
441 NTTIME samdb_result_account_expires(const struct ldb_message *msg)
442 {
443         NTTIME ret = ldb_msg_find_attr_as_uint64(msg, "accountExpires",
444                                                  0);
445
446         if (ret == 0)
447                 ret = 0x7FFFFFFFFFFFFFFFULL;
448
449         return ret;
450 }
451
452 /*
453   construct the allow_password_change field from the PwdLastSet attribute and the 
454   domain password settings
455 */
456 NTTIME samdb_result_allow_password_change(struct ldb_context *sam_ldb, 
457                                           TALLOC_CTX *mem_ctx, 
458                                           struct ldb_dn *domain_dn, 
459                                           struct ldb_message *msg, 
460                                           const char *attr)
461 {
462         uint64_t attr_time = ldb_msg_find_attr_as_uint64(msg, attr, 0);
463         int64_t minPwdAge;
464
465         if (attr_time == 0) {
466                 return 0;
467         }
468
469         minPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn, "minPwdAge", NULL);
470
471         /* yes, this is a -= not a += as minPwdAge is stored as the negative
472            of the number of 100-nano-seconds */
473         attr_time -= minPwdAge;
474
475         return attr_time;
476 }
477
478 /*
479   construct the force_password_change field from the PwdLastSet
480   attribute, the userAccountControl and the domain password settings
481 */
482 NTTIME samdb_result_force_password_change(struct ldb_context *sam_ldb, 
483                                           TALLOC_CTX *mem_ctx, 
484                                           struct ldb_dn *domain_dn, 
485                                           struct ldb_message *msg)
486 {
487         int64_t attr_time = ldb_msg_find_attr_as_int64(msg, "pwdLastSet", 0);
488         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg,
489                                                                 "userAccountControl",
490                                                                 0);
491         int64_t maxPwdAge;
492
493         /* Machine accounts don't expire, and there is a flag for 'no expiry' */
494         if (!(userAccountControl & UF_NORMAL_ACCOUNT)
495             || (userAccountControl & UF_DONT_EXPIRE_PASSWD)) {
496                 return 0x7FFFFFFFFFFFFFFFULL;
497         }
498
499         if (attr_time == 0) {
500                 return 0;
501         }
502         if (attr_time == -1) {
503                 return 0x7FFFFFFFFFFFFFFFULL;
504         }
505
506         maxPwdAge = samdb_search_int64(sam_ldb, mem_ctx, 0, domain_dn,
507                                        "maxPwdAge", NULL);
508         if (maxPwdAge == 0 || maxPwdAge == -0x8000000000000000ULL) {
509                 return 0x7FFFFFFFFFFFFFFFULL;
510         } else {
511                 attr_time -= maxPwdAge;
512         }
513
514         return attr_time;
515 }
516
517 /*
518   pull a samr_Password structutre from a result set. 
519 */
520 struct samr_Password *samdb_result_hash(TALLOC_CTX *mem_ctx, const struct ldb_message *msg, const char *attr)
521 {
522         struct samr_Password *hash = NULL;
523         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
524         if (val && (val->length >= sizeof(hash->hash))) {
525                 hash = talloc(mem_ctx, struct samr_Password);
526                 memcpy(hash->hash, val->data, MIN(val->length, sizeof(hash->hash)));
527         }
528         return hash;
529 }
530
531 /*
532   pull an array of samr_Password structures from a result set.
533 */
534 unsigned int samdb_result_hashes(TALLOC_CTX *mem_ctx, const struct ldb_message *msg,
535                            const char *attr, struct samr_Password **hashes)
536 {
537         unsigned int count, i;
538         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
539
540         *hashes = NULL;
541         if (!val) {
542                 return 0;
543         }
544         count = val->length / 16;
545         if (count == 0) {
546                 return 0;
547         }
548
549         *hashes = talloc_array(mem_ctx, struct samr_Password, count);
550         if (! *hashes) {
551                 return 0;
552         }
553
554         for (i=0;i<count;i++) {
555                 memcpy((*hashes)[i].hash, (i*16)+(char *)val->data, 16);
556         }
557
558         return count;
559 }
560
561 NTSTATUS samdb_result_passwords(TALLOC_CTX *mem_ctx, struct loadparm_context *lp_ctx, struct ldb_message *msg,
562                                 struct samr_Password **lm_pwd, struct samr_Password **nt_pwd) 
563 {
564         struct samr_Password *lmPwdHash, *ntPwdHash;
565         if (nt_pwd) {
566                 unsigned int num_nt;
567                 num_nt = samdb_result_hashes(mem_ctx, msg, "unicodePwd", &ntPwdHash);
568                 if (num_nt == 0) {
569                         *nt_pwd = NULL;
570                 } else if (num_nt > 1) {
571                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
572                 } else {
573                         *nt_pwd = &ntPwdHash[0];
574                 }
575         }
576         if (lm_pwd) {
577                 /* Ensure that if we have turned off LM
578                  * authentication, that we never use the LM hash, even
579                  * if we store it */
580                 if (lpcfg_lanman_auth(lp_ctx)) {
581                         unsigned int num_lm;
582                         num_lm = samdb_result_hashes(mem_ctx, msg, "dBCSPwd", &lmPwdHash);
583                         if (num_lm == 0) {
584                                 *lm_pwd = NULL;
585                         } else if (num_lm > 1) {
586                                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
587                         } else {
588                                 *lm_pwd = &lmPwdHash[0];
589                         }
590                 } else {
591                         *lm_pwd = NULL;
592                 }
593         }
594         return NT_STATUS_OK;
595 }
596
597 /*
598   pull a samr_LogonHours structutre from a result set. 
599 */
600 struct samr_LogonHours samdb_result_logon_hours(TALLOC_CTX *mem_ctx, struct ldb_message *msg, const char *attr)
601 {
602         struct samr_LogonHours hours;
603         size_t units_per_week = 168;
604         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
605
606         ZERO_STRUCT(hours);
607
608         if (val) {
609                 units_per_week = val->length * 8;
610         }
611
612         hours.bits = talloc_array(mem_ctx, uint8_t, units_per_week/8);
613         if (!hours.bits) {
614                 return hours;
615         }
616         hours.units_per_week = units_per_week;
617         memset(hours.bits, 0xFF, units_per_week/8);
618         if (val) {
619                 memcpy(hours.bits, val->data, val->length);
620         }
621
622         return hours;
623 }
624
625 /*
626   pull a set of account_flags from a result set. 
627
628   This requires that the attributes: 
629    pwdLastSet
630    userAccountControl
631   be included in 'msg'
632 */
633 uint32_t samdb_result_acct_flags(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
634                                  struct ldb_message *msg, struct ldb_dn *domain_dn)
635 {
636         uint32_t userAccountControl = ldb_msg_find_attr_as_uint(msg, "userAccountControl", 0);
637         uint32_t acct_flags = ds_uf2acb(userAccountControl);
638         NTTIME must_change_time;
639         NTTIME now;
640
641         must_change_time = samdb_result_force_password_change(sam_ctx, mem_ctx, 
642                                                               domain_dn, msg);
643
644         /* Test account expire time */
645         unix_to_nt_time(&now, time(NULL));
646         /* check for expired password */
647         if (must_change_time < now) {
648                 acct_flags |= ACB_PW_EXPIRED;
649         }
650         return acct_flags;
651 }
652
653 struct lsa_BinaryString samdb_result_parameters(TALLOC_CTX *mem_ctx,
654                                                 struct ldb_message *msg,
655                                                 const char *attr)
656 {
657         struct lsa_BinaryString s;
658         const struct ldb_val *val = ldb_msg_find_ldb_val(msg, attr);
659
660         ZERO_STRUCT(s);
661
662         if (!val) {
663                 return s;
664         }
665
666         s.array = talloc_array(mem_ctx, uint16_t, val->length/2);
667         if (!s.array) {
668                 return s;
669         }
670         s.length = s.size = val->length;
671         memcpy(s.array, val->data, val->length);
672
673         return s;
674 }
675
676 /* Find an attribute, with a particular value */
677
678 /* The current callers of this function expect a very specific
679  * behaviour: In particular, objectClass subclass equivilance is not
680  * wanted.  This means that we should not lookup the schema for the
681  * comparison function */
682 struct ldb_message_element *samdb_find_attribute(struct ldb_context *ldb, 
683                                                  const struct ldb_message *msg, 
684                                                  const char *name, const char *value)
685 {
686         unsigned int i;
687         struct ldb_message_element *el = ldb_msg_find_element(msg, name);
688
689         if (!el) {
690                 return NULL;
691         }
692
693         for (i=0;i<el->num_values;i++) {
694                 if (ldb_attr_cmp(value, (char *)el->values[i].data) == 0) {
695                         return el;
696                 }
697         }
698
699         return NULL;
700 }
701
702 int samdb_find_or_add_attribute(struct ldb_context *ldb, struct ldb_message *msg, const char *name, const char *set_value)
703 {
704         struct ldb_message_element *el;
705
706         el = ldb_msg_find_element(msg, name);
707         if (el) {
708                 return LDB_SUCCESS;
709         }
710
711         return ldb_msg_add_string(msg, name, set_value);
712 }
713
714 /*
715   add a dom_sid element to a message
716 */
717 int samdb_msg_add_dom_sid(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
718                           const char *attr_name, const struct dom_sid *sid)
719 {
720         struct ldb_val v;
721         enum ndr_err_code ndr_err;
722
723         ndr_err = ndr_push_struct_blob(&v, mem_ctx, 
724                                        sid,
725                                        (ndr_push_flags_fn_t)ndr_push_dom_sid);
726         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
727                 return ldb_operr(sam_ldb);
728         }
729         return ldb_msg_add_value(msg, attr_name, &v, NULL);
730 }
731
732
733 /*
734   add a delete element operation to a message
735 */
736 int samdb_msg_add_delete(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
737                          const char *attr_name)
738 {
739         /* we use an empty replace rather than a delete, as it allows for 
740            dsdb_replace() to be used everywhere */
741         return ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_REPLACE, NULL);
742 }
743
744 /*
745   add an add attribute value to a message or enhance an existing attribute
746   which has the same name and the add flag set.
747 */
748 int samdb_msg_add_addval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
749                          struct ldb_message *msg, const char *attr_name,
750                          const char *value)
751 {
752         struct ldb_message_element *el;
753         struct ldb_val val, *vals;
754         char *v;
755         unsigned int i;
756         bool found = false;
757         int ret;
758
759         v = talloc_strdup(mem_ctx, value);
760         if (v == NULL) {
761                 return ldb_oom(sam_ldb);
762         }
763
764         val.data = (uint8_t *) v;
765         val.length = strlen(v);
766
767         if (val.length == 0) {
768                 /* allow empty strings as non-existent attributes */
769                 return LDB_SUCCESS;
770         }
771
772         for (i = 0; i < msg->num_elements; i++) {
773                 el = &msg->elements[i];
774                 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
775                     (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_ADD)) {
776                         found = true;
777                         break;
778                 }
779         }
780         if (!found) {
781                 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_ADD,
782                                         &el);
783                 if (ret != LDB_SUCCESS) {
784                         return ret;
785                 }
786         }
787
788         vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
789                               el->num_values + 1);
790         if (vals == NULL) {
791                 return ldb_oom(sam_ldb);
792         }
793         el->values = vals;
794         el->values[el->num_values] = val;
795         ++(el->num_values);
796
797         return LDB_SUCCESS;
798 }
799
800 /*
801   add a delete attribute value to a message or enhance an existing attribute
802   which has the same name and the delete flag set.
803 */
804 int samdb_msg_add_delval(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
805                          struct ldb_message *msg, const char *attr_name,
806                          const char *value)
807 {
808         struct ldb_message_element *el;
809         struct ldb_val val, *vals;
810         char *v;
811         unsigned int i;
812         bool found = false;
813         int ret;
814
815         v = talloc_strdup(mem_ctx, value);
816         if (v == NULL) {
817                 return ldb_oom(sam_ldb);
818         }
819
820         val.data = (uint8_t *) v;
821         val.length = strlen(v);
822
823         if (val.length == 0) {
824                 /* allow empty strings as non-existent attributes */
825                 return LDB_SUCCESS;
826         }
827
828         for (i = 0; i < msg->num_elements; i++) {
829                 el = &msg->elements[i];
830                 if ((ldb_attr_cmp(el->name, attr_name) == 0) &&
831                     (LDB_FLAG_MOD_TYPE(el->flags) == LDB_FLAG_MOD_DELETE)) {
832                         found = true;
833                         break;
834                 }
835         }
836         if (!found) {
837                 ret = ldb_msg_add_empty(msg, attr_name, LDB_FLAG_MOD_DELETE,
838                                         &el);
839                 if (ret != LDB_SUCCESS) {
840                         return ret;
841                 }
842         }
843
844         vals = talloc_realloc(msg->elements, el->values, struct ldb_val,
845                               el->num_values + 1);
846         if (vals == NULL) {
847                 return ldb_oom(sam_ldb);
848         }
849         el->values = vals;
850         el->values[el->num_values] = val;
851         ++(el->num_values);
852
853         return LDB_SUCCESS;
854 }
855
856 /*
857   add a int element to a message
858 */
859 int samdb_msg_add_int(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
860                        const char *attr_name, int v)
861 {
862         const char *s = talloc_asprintf(mem_ctx, "%d", v);
863         if (s == NULL) {
864                 return ldb_oom(sam_ldb);
865         }
866         return ldb_msg_add_string(msg, attr_name, s);
867 }
868
869 /*
870  * Add an unsigned int element to a message
871  *
872  * The issue here is that we have not yet first cast to int32_t explicitly,
873  * before we cast to an signed int to printf() into the %d or cast to a
874  * int64_t before we then cast to a long long to printf into a %lld.
875  *
876  * There are *no* unsigned integers in Active Directory LDAP, even the RID
877  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
878  * (See the schema, and the syntax definitions in schema_syntax.c).
879  *
880  */
881 int samdb_msg_add_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
882                        const char *attr_name, unsigned int v)
883 {
884         return samdb_msg_add_int(sam_ldb, mem_ctx, msg, attr_name, (int)v);
885 }
886
887 /*
888   add a (signed) int64_t element to a message
889 */
890 int samdb_msg_add_int64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
891                         const char *attr_name, int64_t v)
892 {
893         const char *s = talloc_asprintf(mem_ctx, "%lld", (long long)v);
894         if (s == NULL) {
895                 return ldb_oom(sam_ldb);
896         }
897         return ldb_msg_add_string(msg, attr_name, s);
898 }
899
900 /*
901  * Add an unsigned int64_t (uint64_t) element to a message
902  *
903  * The issue here is that we have not yet first cast to int32_t explicitly,
904  * before we cast to an signed int to printf() into the %d or cast to a
905  * int64_t before we then cast to a long long to printf into a %lld.
906  *
907  * There are *no* unsigned integers in Active Directory LDAP, even the RID
908  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
909  * (See the schema, and the syntax definitions in schema_syntax.c).
910  *
911  */
912 int samdb_msg_add_uint64(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
913                         const char *attr_name, uint64_t v)
914 {
915         return samdb_msg_add_int64(sam_ldb, mem_ctx, msg, attr_name, (int64_t)v);
916 }
917
918 /*
919   add a samr_Password element to a message
920 */
921 int samdb_msg_add_hash(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
922                        const char *attr_name, const struct samr_Password *hash)
923 {
924         struct ldb_val val;
925         val.data = talloc_memdup(mem_ctx, hash->hash, 16);
926         if (!val.data) {
927                 return ldb_oom(sam_ldb);
928         }
929         val.length = 16;
930         return ldb_msg_add_value(msg, attr_name, &val, NULL);
931 }
932
933 /*
934   add a samr_Password array to a message
935 */
936 int samdb_msg_add_hashes(struct ldb_context *ldb,
937                          TALLOC_CTX *mem_ctx, struct ldb_message *msg,
938                          const char *attr_name, struct samr_Password *hashes,
939                          unsigned int count)
940 {
941         struct ldb_val val;
942         unsigned int i;
943         val.data = talloc_array_size(mem_ctx, 16, count);
944         val.length = count*16;
945         if (!val.data) {
946                 return ldb_oom(ldb);
947         }
948         for (i=0;i<count;i++) {
949                 memcpy(i*16 + (char *)val.data, hashes[i].hash, 16);
950         }
951         return ldb_msg_add_value(msg, attr_name, &val, NULL);
952 }
953
954 /*
955   add a acct_flags element to a message
956 */
957 int samdb_msg_add_acct_flags(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
958                              const char *attr_name, uint32_t v)
959 {
960         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, ds_acb2uf(v));
961 }
962
963 /*
964   add a logon_hours element to a message
965 */
966 int samdb_msg_add_logon_hours(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
967                               const char *attr_name, struct samr_LogonHours *hours)
968 {
969         struct ldb_val val;
970         val.length = hours->units_per_week / 8;
971         val.data = hours->bits;
972         return ldb_msg_add_value(msg, attr_name, &val, NULL);
973 }
974
975 /*
976   add a parameters element to a message
977 */
978 int samdb_msg_add_parameters(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx, struct ldb_message *msg,
979                              const char *attr_name, struct lsa_BinaryString *parameters)
980 {
981         struct ldb_val val;
982         val.length = parameters->length;
983         val.data = (uint8_t *)parameters->array;
984         return ldb_msg_add_value(msg, attr_name, &val, NULL);
985 }
986
987 /*
988  * Sets an unsigned int element in a message
989  *
990  * The issue here is that we have not yet first cast to int32_t explicitly,
991  * before we cast to an signed int to printf() into the %d or cast to a
992  * int64_t before we then cast to a long long to printf into a %lld.
993  *
994  * There are *no* unsigned integers in Active Directory LDAP, even the RID
995  * allocations and ms-DS-Secondary-KrbTgt-Number are *signed* quantities.
996  * (See the schema, and the syntax definitions in schema_syntax.c).
997  *
998  */
999 int samdb_msg_set_uint(struct ldb_context *sam_ldb, TALLOC_CTX *mem_ctx,
1000                        struct ldb_message *msg, const char *attr_name,
1001                        unsigned int v)
1002 {
1003         struct ldb_message_element *el;
1004
1005         el = ldb_msg_find_element(msg, attr_name);
1006         if (el) {
1007                 el->num_values = 0;
1008         }
1009         return samdb_msg_add_uint(sam_ldb, mem_ctx, msg, attr_name, v);
1010 }
1011
1012 /*
1013  * Handle ldb_request in transaction
1014  */
1015 static int dsdb_autotransaction_request(struct ldb_context *sam_ldb,
1016                                         struct ldb_request *req)
1017 {
1018         int ret;
1019
1020         ret = ldb_transaction_start(sam_ldb);
1021         if (ret != LDB_SUCCESS) {
1022                 return ret;
1023         }
1024
1025         ret = ldb_request(sam_ldb, req);
1026         if (ret == LDB_SUCCESS) {
1027                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
1028         }
1029
1030         if (ret == LDB_SUCCESS) {
1031                 return ldb_transaction_commit(sam_ldb);
1032         }
1033         ldb_transaction_cancel(sam_ldb);
1034
1035         return ret;
1036 }
1037
1038 /*
1039   return a default security descriptor
1040 */
1041 struct security_descriptor *samdb_default_security_descriptor(TALLOC_CTX *mem_ctx)
1042 {
1043         struct security_descriptor *sd;
1044
1045         sd = security_descriptor_initialise(mem_ctx);
1046
1047         return sd;
1048 }
1049
1050 struct ldb_dn *samdb_aggregate_schema_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx) 
1051 {
1052         struct ldb_dn *schema_dn = ldb_get_schema_basedn(sam_ctx);
1053         struct ldb_dn *aggregate_dn;
1054         if (!schema_dn) {
1055                 return NULL;
1056         }
1057
1058         aggregate_dn = ldb_dn_copy(mem_ctx, schema_dn);
1059         if (!aggregate_dn) {
1060                 return NULL;
1061         }
1062         if (!ldb_dn_add_child_fmt(aggregate_dn, "CN=Aggregate")) {
1063                 return NULL;
1064         }
1065         return aggregate_dn;
1066 }
1067
1068 struct ldb_dn *samdb_partitions_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1069 {
1070         struct ldb_dn *new_dn;
1071
1072         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1073         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Partitions")) {
1074                 talloc_free(new_dn);
1075                 return NULL;
1076         }
1077         return new_dn;
1078 }
1079
1080 struct ldb_dn *samdb_infrastructure_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1081 {
1082        struct ldb_dn *new_dn;
1083
1084        new_dn = ldb_dn_copy(mem_ctx, ldb_get_default_basedn(sam_ctx));
1085        if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Infrastructure")) {
1086                talloc_free(new_dn);
1087                return NULL;
1088        }
1089        return new_dn;
1090 }
1091
1092 struct ldb_dn *samdb_sites_dn(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx)
1093 {
1094         struct ldb_dn *new_dn;
1095
1096         new_dn = ldb_dn_copy(mem_ctx, ldb_get_config_basedn(sam_ctx));
1097         if ( ! ldb_dn_add_child_fmt(new_dn, "CN=Sites")) {
1098                 talloc_free(new_dn);
1099                 return NULL;
1100         }
1101         return new_dn;
1102 }
1103
1104 /*
1105   work out the domain sid for the current open ldb
1106 */
1107 const struct dom_sid *samdb_domain_sid(struct ldb_context *ldb)
1108 {
1109         TALLOC_CTX *tmp_ctx;
1110         const struct dom_sid *domain_sid;
1111         const char *attrs[] = {
1112                 "objectSid",
1113                 NULL
1114         };
1115         struct ldb_result *res;
1116         int ret;
1117
1118         /* see if we have a cached copy */
1119         domain_sid = (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1120         if (domain_sid) {
1121                 return domain_sid;
1122         }
1123
1124         tmp_ctx = talloc_new(ldb);
1125         if (tmp_ctx == NULL) {
1126                 goto failed;
1127         }
1128
1129         ret = ldb_search(ldb, tmp_ctx, &res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, attrs, "objectSid=*");
1130
1131         if (ret != LDB_SUCCESS) {
1132                 goto failed;
1133         }
1134
1135         if (res->count != 1) {
1136                 goto failed;
1137         }
1138
1139         domain_sid = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
1140         if (domain_sid == NULL) {
1141                 goto failed;
1142         }
1143
1144         /* cache the domain_sid in the ldb */
1145         if (ldb_set_opaque(ldb, "cache.domain_sid", discard_const_p(struct dom_sid, domain_sid)) != LDB_SUCCESS) {
1146                 goto failed;
1147         }
1148
1149         talloc_steal(ldb, domain_sid);
1150         talloc_free(tmp_ctx);
1151
1152         return domain_sid;
1153
1154 failed:
1155         talloc_free(tmp_ctx);
1156         return NULL;
1157 }
1158
1159 /*
1160   get domain sid from cache
1161 */
1162 const struct dom_sid *samdb_domain_sid_cache_only(struct ldb_context *ldb)
1163 {
1164         return (struct dom_sid *)ldb_get_opaque(ldb, "cache.domain_sid");
1165 }
1166
1167 bool samdb_set_domain_sid(struct ldb_context *ldb, const struct dom_sid *dom_sid_in)
1168 {
1169         TALLOC_CTX *tmp_ctx;
1170         struct dom_sid *dom_sid_new;
1171         struct dom_sid *dom_sid_old;
1172
1173         /* see if we have a cached copy */
1174         dom_sid_old = talloc_get_type(ldb_get_opaque(ldb, 
1175                                                      "cache.domain_sid"), struct dom_sid);
1176
1177         tmp_ctx = talloc_new(ldb);
1178         if (tmp_ctx == NULL) {
1179                 goto failed;
1180         }
1181
1182         dom_sid_new = dom_sid_dup(tmp_ctx, dom_sid_in);
1183         if (!dom_sid_new) {
1184                 goto failed;
1185         }
1186
1187         /* cache the domain_sid in the ldb */
1188         if (ldb_set_opaque(ldb, "cache.domain_sid", dom_sid_new) != LDB_SUCCESS) {
1189                 goto failed;
1190         }
1191
1192         talloc_steal(ldb, dom_sid_new);
1193         talloc_free(tmp_ctx);
1194         talloc_free(dom_sid_old);
1195
1196         return true;
1197
1198 failed:
1199         DEBUG(1,("Failed to set our own cached domain SID in the ldb!\n"));
1200         talloc_free(tmp_ctx);
1201         return false;
1202 }
1203
1204 bool samdb_set_ntds_settings_dn(struct ldb_context *ldb, struct ldb_dn *ntds_settings_dn_in)
1205 {
1206         TALLOC_CTX *tmp_ctx;
1207         struct ldb_dn *ntds_settings_dn_new;
1208         struct ldb_dn *ntds_settings_dn_old;
1209
1210         /* see if we have a forced copy from provision */
1211         ntds_settings_dn_old = talloc_get_type(ldb_get_opaque(ldb, 
1212                                                               "forced.ntds_settings_dn"), struct ldb_dn);
1213
1214         tmp_ctx = talloc_new(ldb);
1215         if (tmp_ctx == NULL) {
1216                 goto failed;
1217         }
1218
1219         ntds_settings_dn_new = ldb_dn_copy(tmp_ctx, ntds_settings_dn_in);
1220         if (!ntds_settings_dn_new) {
1221                 goto failed;
1222         }
1223
1224         /* set the DN in the ldb to avoid lookups during provision */
1225         if (ldb_set_opaque(ldb, "forced.ntds_settings_dn", ntds_settings_dn_new) != LDB_SUCCESS) {
1226                 goto failed;
1227         }
1228
1229         talloc_steal(ldb, ntds_settings_dn_new);
1230         talloc_free(tmp_ctx);
1231         talloc_free(ntds_settings_dn_old);
1232
1233         return true;
1234
1235 failed:
1236         DEBUG(1,("Failed to set our NTDS Settings DN in the ldb!\n"));
1237         talloc_free(tmp_ctx);
1238         return false;
1239 }
1240
1241 /*
1242   work out the ntds settings dn for the current open ldb
1243 */
1244 struct ldb_dn *samdb_ntds_settings_dn(struct ldb_context *ldb)
1245 {
1246         TALLOC_CTX *tmp_ctx;
1247         const char *root_attrs[] = { "dsServiceName", NULL };
1248         int ret;
1249         struct ldb_result *root_res;
1250         struct ldb_dn *settings_dn;
1251
1252         /* see if we have a cached copy */
1253         settings_dn = (struct ldb_dn *)ldb_get_opaque(ldb, "forced.ntds_settings_dn");
1254         if (settings_dn) {
1255                 return settings_dn;
1256         }
1257
1258         tmp_ctx = talloc_new(ldb);
1259         if (tmp_ctx == NULL) {
1260                 goto failed;
1261         }
1262
1263         ret = ldb_search(ldb, tmp_ctx, &root_res, ldb_dn_new(tmp_ctx, ldb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
1264         if (ret != LDB_SUCCESS) {
1265                 DEBUG(1,("Searching for dsServiceName in rootDSE failed: %s\n", 
1266                          ldb_errstring(ldb)));
1267                 goto failed;
1268         }
1269
1270         if (root_res->count != 1) {
1271                 goto failed;
1272         }
1273
1274         settings_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, root_res->msgs[0], "dsServiceName");
1275
1276         /* note that we do not cache the DN here, as that would mean
1277          * we could not handle server renames at runtime. Only
1278          * provision sets up forced.ntds_settings_dn */
1279
1280         talloc_steal(ldb, settings_dn);
1281         talloc_free(tmp_ctx);
1282
1283         return settings_dn;
1284
1285 failed:
1286         DEBUG(1,("Failed to find our own NTDS Settings DN in the ldb!\n"));
1287         talloc_free(tmp_ctx);
1288         return NULL;
1289 }
1290
1291 /*
1292   work out the ntds settings invocationId for the current open ldb
1293 */
1294 const struct GUID *samdb_ntds_invocation_id(struct ldb_context *ldb)
1295 {
1296         TALLOC_CTX *tmp_ctx;
1297         const char *attrs[] = { "invocationId", NULL };
1298         int ret;
1299         struct ldb_result *res;
1300         struct GUID *invocation_id;
1301
1302         /* see if we have a cached copy */
1303         invocation_id = (struct GUID *)ldb_get_opaque(ldb, "cache.invocation_id");
1304         if (invocation_id) {
1305                 return invocation_id;
1306         }
1307
1308         tmp_ctx = talloc_new(ldb);
1309         if (tmp_ctx == NULL) {
1310                 goto failed;
1311         }
1312
1313         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1314         if (ret) {
1315                 goto failed;
1316         }
1317
1318         if (res->count != 1) {
1319                 goto failed;
1320         }
1321
1322         invocation_id = talloc(tmp_ctx, struct GUID);
1323         if (!invocation_id) {
1324                 goto failed;
1325         }
1326
1327         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1328
1329         /* cache the domain_sid in the ldb */
1330         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1331                 goto failed;
1332         }
1333
1334         talloc_steal(ldb, invocation_id);
1335         talloc_free(tmp_ctx);
1336
1337         return invocation_id;
1338
1339 failed:
1340         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1341         talloc_free(tmp_ctx);
1342         return NULL;
1343 }
1344
1345 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1346 {
1347         TALLOC_CTX *tmp_ctx;
1348         struct GUID *invocation_id_new;
1349         struct GUID *invocation_id_old;
1350
1351         /* see if we have a cached copy */
1352         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1353                                                          "cache.invocation_id");
1354
1355         tmp_ctx = talloc_new(ldb);
1356         if (tmp_ctx == NULL) {
1357                 goto failed;
1358         }
1359
1360         invocation_id_new = talloc(tmp_ctx, struct GUID);
1361         if (!invocation_id_new) {
1362                 goto failed;
1363         }
1364
1365         *invocation_id_new = *invocation_id_in;
1366
1367         /* cache the domain_sid in the ldb */
1368         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1369                 goto failed;
1370         }
1371
1372         talloc_steal(ldb, invocation_id_new);
1373         talloc_free(tmp_ctx);
1374         talloc_free(invocation_id_old);
1375
1376         return true;
1377
1378 failed:
1379         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1380         talloc_free(tmp_ctx);
1381         return false;
1382 }
1383
1384 /*
1385   work out the ntds settings objectGUID for the current open ldb
1386 */
1387 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1388 {
1389         TALLOC_CTX *tmp_ctx;
1390         const char *attrs[] = { "objectGUID", NULL };
1391         int ret;
1392         struct ldb_result *res;
1393         struct GUID *ntds_guid;
1394
1395         /* see if we have a cached copy */
1396         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1397         if (ntds_guid) {
1398                 return ntds_guid;
1399         }
1400
1401         tmp_ctx = talloc_new(ldb);
1402         if (tmp_ctx == NULL) {
1403                 goto failed;
1404         }
1405
1406         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
1407         if (ret) {
1408                 goto failed;
1409         }
1410
1411         if (res->count != 1) {
1412                 goto failed;
1413         }
1414
1415         ntds_guid = talloc(tmp_ctx, struct GUID);
1416         if (!ntds_guid) {
1417                 goto failed;
1418         }
1419
1420         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1421
1422         /* cache the domain_sid in the ldb */
1423         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1424                 goto failed;
1425         }
1426
1427         talloc_steal(ldb, ntds_guid);
1428         talloc_free(tmp_ctx);
1429
1430         return ntds_guid;
1431
1432 failed:
1433         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1434         talloc_free(tmp_ctx);
1435         return NULL;
1436 }
1437
1438 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1439 {
1440         TALLOC_CTX *tmp_ctx;
1441         struct GUID *ntds_guid_new;
1442         struct GUID *ntds_guid_old;
1443
1444         /* see if we have a cached copy */
1445         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1446
1447         tmp_ctx = talloc_new(ldb);
1448         if (tmp_ctx == NULL) {
1449                 goto failed;
1450         }
1451
1452         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1453         if (!ntds_guid_new) {
1454                 goto failed;
1455         }
1456
1457         *ntds_guid_new = *ntds_guid_in;
1458
1459         /* cache the domain_sid in the ldb */
1460         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1461                 goto failed;
1462         }
1463
1464         talloc_steal(ldb, ntds_guid_new);
1465         talloc_free(tmp_ctx);
1466         talloc_free(ntds_guid_old);
1467
1468         return true;
1469
1470 failed:
1471         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1472         talloc_free(tmp_ctx);
1473         return false;
1474 }
1475
1476 /*
1477   work out the server dn for the current open ldb
1478 */
1479 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1480 {
1481         return ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb));
1482 }
1483
1484 /*
1485   work out the server dn for the current open ldb
1486 */
1487 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1488 {
1489         struct ldb_dn *server_dn;
1490         struct ldb_dn *servers_dn;
1491         struct ldb_dn *server_site_dn;
1492
1493         /* TODO: there must be a saner way to do this!! */
1494         server_dn = samdb_server_dn(ldb, mem_ctx);
1495         if (!server_dn) return NULL;
1496
1497         servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1498         talloc_free(server_dn);
1499         if (!servers_dn) return NULL;
1500
1501         server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1502         talloc_free(servers_dn);
1503
1504         return server_site_dn;
1505 }
1506
1507 /*
1508   find the site name from a computers DN record
1509  */
1510 int samdb_find_site_for_computer(struct ldb_context *ldb,
1511                                  TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1512                                  const char **site_name)
1513 {
1514         int ret;
1515         struct ldb_dn *dn;
1516         const struct ldb_val *rdn_val;
1517
1518         *site_name = NULL;
1519
1520         ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1521         if (ret != LDB_SUCCESS) {
1522                 return ret;
1523         }
1524
1525         if (!ldb_dn_remove_child_components(dn, 2)) {
1526                 talloc_free(dn);
1527                 return LDB_ERR_INVALID_DN_SYNTAX;
1528         }
1529
1530         rdn_val = ldb_dn_get_rdn_val(dn);
1531         if (rdn_val == NULL) {
1532                 return LDB_ERR_OPERATIONS_ERROR;
1533         }
1534
1535         (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1536         talloc_free(dn);
1537         if (!*site_name) {
1538                 return LDB_ERR_OPERATIONS_ERROR;
1539         }
1540         return LDB_SUCCESS;
1541 }
1542
1543 /*
1544   find the NTDS GUID from a computers DN record
1545  */
1546 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1547                                      struct GUID *ntds_guid)
1548 {
1549         int ret;
1550         struct ldb_dn *dn;
1551
1552         *ntds_guid = GUID_zero();
1553
1554         ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1555         if (ret != LDB_SUCCESS) {
1556                 return ret;
1557         }
1558
1559         if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1560                 talloc_free(dn);
1561                 return LDB_ERR_OPERATIONS_ERROR;
1562         }
1563
1564         ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1565         talloc_free(dn);
1566         return ret;
1567 }
1568
1569 /*
1570   find a 'reference' DN that points at another object
1571   (eg. serverReference, rIDManagerReference etc)
1572  */
1573 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1574                        const char *attribute, struct ldb_dn **dn)
1575 {
1576         const char *attrs[2];
1577         struct ldb_result *res;
1578         int ret;
1579
1580         attrs[0] = attribute;
1581         attrs[1] = NULL;
1582
1583         ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY, NULL);
1584         if (ret != LDB_SUCCESS) {
1585                 return ret;
1586         }
1587
1588         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1589         if (!*dn) {
1590                 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1591                         ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1592                                                ldb_dn_get_linearized(base));
1593                 } else {
1594                         ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1595                                                ldb_dn_get_linearized(base));
1596                 }
1597                 talloc_free(res);
1598                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1599         }
1600
1601         talloc_free(res);
1602         return LDB_SUCCESS;
1603 }
1604
1605 /*
1606   find our machine account via the serverReference attribute in the
1607   server DN
1608  */
1609 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1610 {
1611         struct ldb_dn *server_dn;
1612         int ret;
1613
1614         server_dn = samdb_server_dn(ldb, mem_ctx);
1615         if (server_dn == NULL) {
1616                 return LDB_ERR_NO_SUCH_OBJECT;
1617         }
1618
1619         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1620         talloc_free(server_dn);
1621
1622         return ret;
1623 }
1624
1625 /*
1626   find the RID Manager$ DN via the rIDManagerReference attribute in the
1627   base DN
1628  */
1629 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1630 {
1631         return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1632                                   "rIDManagerReference", dn);
1633 }
1634
1635 /*
1636   find the RID Set DN via the rIDSetReferences attribute in our
1637   machine account DN
1638  */
1639 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1640 {
1641         struct ldb_dn *server_ref_dn;
1642         int ret;
1643
1644         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1645         if (ret != LDB_SUCCESS) {
1646                 return ret;
1647         }
1648         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1649         talloc_free(server_ref_dn);
1650         return ret;
1651 }
1652
1653 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1654 {
1655         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1656                                                                             mem_ctx));
1657
1658         if (val == NULL) {
1659                 return NULL;
1660         }
1661
1662         return (const char *) val->data;
1663 }
1664
1665 /*
1666  * Finds the client site by using the client's IP address.
1667  * The "subnet_name" returns the name of the subnet if parameter != NULL
1668  */
1669 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1670                                    const char *ip_address, char **subnet_name)
1671 {
1672         const char *attrs[] = { "cn", "siteObject", NULL };
1673         struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1674         struct ldb_result *res;
1675         const struct ldb_val *val;
1676         const char *site_name = NULL, *l_subnet_name = NULL;
1677         const char *allow_list[2] = { NULL, NULL };
1678         unsigned int i, count;
1679         int cnt, ret;
1680
1681         /*
1682          * if we don't have a client ip e.g. ncalrpc
1683          * the server site is the client site
1684          */
1685         if (ip_address == NULL) {
1686                 return samdb_server_site_name(ldb, mem_ctx);
1687         }
1688
1689         sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1690         if (sites_container_dn == NULL) {
1691                 return NULL;
1692         }
1693
1694         subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1695         if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1696                 talloc_free(sites_container_dn);
1697                 talloc_free(subnets_dn);
1698                 return NULL;
1699         }
1700
1701         ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1702                          attrs, NULL);
1703         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1704                 count = 0;
1705         } else if (ret != LDB_SUCCESS) {
1706                 talloc_free(sites_container_dn);
1707                 talloc_free(subnets_dn);
1708                 return NULL;
1709         } else {
1710                 count = res->count;
1711         }
1712
1713         for (i = 0; i < count; i++) {
1714                 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1715                                                             NULL);
1716
1717                 allow_list[0] = l_subnet_name;
1718
1719                 if (socket_allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1720                         sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1721                                                            res->msgs[i],
1722                                                            "siteObject");
1723                         if (sites_dn == NULL) {
1724                                 /* No reference, maybe another subnet matches */
1725                                 continue;
1726                         }
1727
1728                         /* "val" cannot be NULL here since "sites_dn" != NULL */
1729                         val = ldb_dn_get_rdn_val(sites_dn);
1730                         site_name = talloc_strdup(mem_ctx,
1731                                                   (const char *) val->data);
1732
1733                         talloc_free(sites_dn);
1734
1735                         break;
1736                 }
1737         }
1738
1739         if (site_name == NULL) {
1740                 /* This is the Windows Server fallback rule: when no subnet
1741                  * exists and we have only one site available then use it (it
1742                  * is for sure the same as our server site). If more sites do
1743                  * exist then we don't know which one to use and set the site
1744                  * name to "". */
1745                 cnt = samdb_search_count(ldb, mem_ctx, sites_container_dn,
1746                                          "(objectClass=site)");
1747                 if (cnt == 1) {
1748                         site_name = samdb_server_site_name(ldb, mem_ctx);
1749                 } else {
1750                         site_name = talloc_strdup(mem_ctx, "");
1751                 }
1752                 l_subnet_name = NULL;
1753         }
1754
1755         if (subnet_name != NULL) {
1756                 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1757         }
1758
1759         talloc_free(sites_container_dn);
1760         talloc_free(subnets_dn);
1761         talloc_free(res);
1762
1763         return site_name;
1764 }
1765
1766 /*
1767   work out if we are the PDC for the domain of the current open ldb
1768 */
1769 bool samdb_is_pdc(struct ldb_context *ldb)
1770 {
1771         const char *dom_attrs[] = { "fSMORoleOwner", NULL };
1772         int ret;
1773         struct ldb_result *dom_res;
1774         TALLOC_CTX *tmp_ctx;
1775         bool is_pdc;
1776         struct ldb_dn *pdc;
1777
1778         tmp_ctx = talloc_new(ldb);
1779         if (tmp_ctx == NULL) {
1780                 DEBUG(1, ("talloc_new failed in samdb_is_pdc"));
1781                 return false;
1782         }
1783
1784         ret = ldb_search(ldb, tmp_ctx, &dom_res, ldb_get_default_basedn(ldb), LDB_SCOPE_BASE, dom_attrs, NULL);
1785         if (ret != LDB_SUCCESS) {
1786                 DEBUG(1,("Searching for fSMORoleOwner in %s failed: %s\n", 
1787                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1788                          ldb_errstring(ldb)));
1789                 goto failed;
1790         }
1791         if (dom_res->count != 1) {
1792                 goto failed;
1793         }
1794
1795         pdc = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, dom_res->msgs[0],
1796                                       "fSMORoleOwner");
1797         if (pdc == NULL) {
1798                 goto failed;
1799         }
1800
1801         if (ldb_dn_compare(samdb_ntds_settings_dn(ldb), pdc) == 0) {
1802                 is_pdc = true;
1803         } else {
1804                 is_pdc = false;
1805         }
1806
1807         talloc_free(tmp_ctx);
1808
1809         return is_pdc;
1810
1811 failed:
1812         DEBUG(1,("Failed to find if we are the PDC for this ldb\n"));
1813         talloc_free(tmp_ctx);
1814         return false;
1815 }
1816
1817 /*
1818   work out if we are a Global Catalog server for the domain of the current open ldb
1819 */
1820 bool samdb_is_gc(struct ldb_context *ldb)
1821 {
1822         uint32_t options;
1823         if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
1824                 return false;
1825         }
1826         return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
1827 }
1828
1829 /* Find a domain object in the parents of a particular DN.  */
1830 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1831                                    struct ldb_dn **parent_dn, const char **errstring)
1832 {
1833         TALLOC_CTX *local_ctx;
1834         struct ldb_dn *sdn = dn;
1835         struct ldb_result *res = NULL;
1836         int ret = LDB_SUCCESS;
1837         const char *attrs[] = { NULL };
1838
1839         local_ctx = talloc_new(mem_ctx);
1840         if (local_ctx == NULL) return ldb_oom(ldb);
1841
1842         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1843                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1844                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1845                 if (ret == LDB_SUCCESS) {
1846                         if (res->count == 1) {
1847                                 break;
1848                         }
1849                 } else {
1850                         break;
1851                 }
1852         }
1853
1854         if (ret != LDB_SUCCESS) {
1855                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1856                                              ldb_dn_get_linearized(dn),
1857                                              ldb_dn_get_linearized(sdn),
1858                                              ldb_errstring(ldb));
1859                 talloc_free(local_ctx);
1860                 return ret;
1861         }
1862         if (res->count != 1) {
1863                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1864                                              ldb_dn_get_linearized(dn));
1865                 DEBUG(0,(__location__ ": %s\n", *errstring));
1866                 talloc_free(local_ctx);
1867                 return LDB_ERR_CONSTRAINT_VIOLATION;
1868         }
1869
1870         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1871         talloc_free(local_ctx);
1872         return ret;
1873 }
1874
1875
1876 /*
1877  * Performs checks on a user password (plaintext UNIX format - attribute
1878  * "password"). The remaining parameters have to be extracted from the domain
1879  * object in the AD.
1880  *
1881  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1882  */
1883 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *password,
1884                                                 const uint32_t pwdProperties,
1885                                                 const uint32_t minPwdLength)
1886 {
1887         /* checks if the "minPwdLength" property is satisfied */
1888         if (minPwdLength > password->length)
1889                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1890
1891         /* checks the password complexity */
1892         if (((pwdProperties & DOMAIN_PASSWORD_COMPLEX) != 0)
1893                         && (password->data != NULL)
1894                         && (!check_password_quality((const char *) password->data)))
1895                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1896
1897         return SAMR_VALIDATION_STATUS_SUCCESS;
1898 }
1899
1900 /*
1901  * Callback for "samdb_set_password" password change
1902  */
1903 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
1904 {
1905         int ret;
1906
1907         if (!ares) {
1908                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1909         }
1910
1911         if (ares->error != LDB_SUCCESS) {
1912                 ret = ares->error;
1913                 req->context = talloc_steal(req,
1914                                             ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1915                 talloc_free(ares);
1916                 return ldb_request_done(req, ret);
1917         }
1918
1919         if (ares->type != LDB_REPLY_DONE) {
1920                 talloc_free(ares);
1921                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1922         }
1923
1924         req->context = talloc_steal(req,
1925                                     ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1926         talloc_free(ares);
1927         return ldb_request_done(req, LDB_SUCCESS);
1928 }
1929
1930 /*
1931  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1932  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1933  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
1934  * user change or not. The "rejectReason" gives some more information if the
1935  * change failed.
1936  *
1937  * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1938  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
1939  */
1940 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1941                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1942                             const DATA_BLOB *new_password,
1943                             const struct samr_Password *lmNewHash,
1944                             const struct samr_Password *ntNewHash,
1945                             const struct samr_Password *lmOldHash,
1946                             const struct samr_Password *ntOldHash,
1947                             enum samPwdChangeReason *reject_reason,
1948                             struct samr_DomInfo1 **_dominfo)
1949 {
1950         struct ldb_message *msg;
1951         struct ldb_message_element *el;
1952         struct ldb_request *req;
1953         struct dsdb_control_password_change_status *pwd_stat = NULL;
1954         int ret;
1955         NTSTATUS status = NT_STATUS_OK;
1956
1957 #define CHECK_RET(x) \
1958         if (x != LDB_SUCCESS) { \
1959                 talloc_free(msg); \
1960                 return NT_STATUS_NO_MEMORY; \
1961         }
1962
1963         msg = ldb_msg_new(mem_ctx);
1964         if (msg == NULL) {
1965                 return NT_STATUS_NO_MEMORY;
1966         }
1967         msg->dn = user_dn;
1968         if ((new_password != NULL)
1969                         && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
1970                 /* we have the password as plaintext UTF16 */
1971                 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
1972                                             new_password, NULL));
1973                 el = ldb_msg_find_element(msg, "clearTextPassword");
1974                 el->flags = LDB_FLAG_MOD_REPLACE;
1975         } else if ((new_password == NULL)
1976                         && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
1977                 /* we have a password as LM and/or NT hash */
1978                 if (lmNewHash != NULL) {
1979                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
1980                                 "dBCSPwd", lmNewHash));
1981                         el = ldb_msg_find_element(msg, "dBCSPwd");
1982                         el->flags = LDB_FLAG_MOD_REPLACE;
1983                 }
1984                 if (ntNewHash != NULL) {
1985                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
1986                                 "unicodePwd", ntNewHash));
1987                         el = ldb_msg_find_element(msg, "unicodePwd");
1988                         el->flags = LDB_FLAG_MOD_REPLACE;
1989                 }
1990         } else {
1991                 /* the password wasn't specified correctly */
1992                 talloc_free(msg);
1993                 return NT_STATUS_INVALID_PARAMETER;
1994         }
1995
1996         /* build modify request */
1997         ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
1998                                 samdb_set_password_callback, NULL);
1999         if (ret != LDB_SUCCESS) {
2000                 talloc_free(msg);
2001                 return NT_STATUS_NO_MEMORY;
2002         }
2003
2004         /* A password change operation */
2005         if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2006                 struct dsdb_control_password_change *change;
2007
2008                 change = talloc(req, struct dsdb_control_password_change);
2009                 if (change == NULL) {
2010                         talloc_free(req);
2011                         talloc_free(msg);
2012                         return NT_STATUS_NO_MEMORY;
2013                 }
2014
2015                 change->old_nt_pwd_hash = ntOldHash;
2016                 change->old_lm_pwd_hash = lmOldHash;
2017
2018                 ret = ldb_request_add_control(req,
2019                                               DSDB_CONTROL_PASSWORD_CHANGE_OID,
2020                                               true, change);
2021                 if (ret != LDB_SUCCESS) {
2022                         talloc_free(req);
2023                         talloc_free(msg);
2024                         return NT_STATUS_NO_MEMORY;
2025                 }
2026         }
2027         ret = ldb_request_add_control(req,
2028                                       DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2029                                       true, NULL);
2030         if (ret != LDB_SUCCESS) {
2031                 talloc_free(req);
2032                 talloc_free(msg);
2033                 return NT_STATUS_NO_MEMORY;
2034         }
2035         ret = ldb_request_add_control(req,
2036                                       DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2037                                       true, NULL);
2038         if (ret != LDB_SUCCESS) {
2039                 talloc_free(req);
2040                 talloc_free(msg);
2041                 return NT_STATUS_NO_MEMORY;
2042         }
2043
2044         ret = dsdb_autotransaction_request(ldb, req);
2045
2046         if (req->context != NULL) {
2047                 pwd_stat = talloc_steal(mem_ctx,
2048                                         ((struct ldb_control *)req->context)->data);
2049         }
2050
2051         talloc_free(req);
2052         talloc_free(msg);
2053
2054         /* Sets the domain info (if requested) */
2055         if (_dominfo != NULL) {
2056                 struct samr_DomInfo1 *dominfo;
2057
2058                 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2059                 if (dominfo == NULL) {
2060                         return NT_STATUS_NO_MEMORY;
2061                 }
2062
2063                 if (pwd_stat != NULL) {
2064                         dominfo->min_password_length     = pwd_stat->domain_data.minPwdLength;
2065                         dominfo->password_properties     = pwd_stat->domain_data.pwdProperties;
2066                         dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2067                         dominfo->max_password_age        = pwd_stat->domain_data.maxPwdAge;
2068                         dominfo->min_password_age        = pwd_stat->domain_data.minPwdAge;
2069                 }
2070
2071                 *_dominfo = dominfo;
2072         }
2073
2074         if (reject_reason != NULL) {
2075                 if (pwd_stat != NULL) {
2076                         *reject_reason = pwd_stat->reject_reason;
2077                 } else {
2078                         *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2079                 }
2080         }
2081
2082         if (pwd_stat != NULL) {
2083                 talloc_free(pwd_stat);
2084         }
2085
2086         if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2087                 const char *errmsg = ldb_errstring(ldb);
2088                 char *endptr = NULL;
2089                 WERROR werr = WERR_GENERAL_FAILURE;
2090                 status = NT_STATUS_UNSUCCESSFUL;
2091                 if (errmsg != NULL) {
2092                         werr = W_ERROR(strtol(errmsg, &endptr, 16));
2093                 }
2094                 if (endptr != errmsg) {
2095                         if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2096                                 status = NT_STATUS_WRONG_PASSWORD;
2097                         }
2098                         if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2099                                 status = NT_STATUS_PASSWORD_RESTRICTION;
2100                         }
2101                 }
2102         } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2103                 /* don't let the caller know if an account doesn't exist */
2104                 status = NT_STATUS_WRONG_PASSWORD;
2105         } else if (ret != LDB_SUCCESS) {
2106                 status = NT_STATUS_UNSUCCESSFUL;
2107         }
2108
2109         return status;
2110 }
2111
2112 /*
2113  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2114  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2115  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2116  * user change or not. The "rejectReason" gives some more information if the
2117  * change failed.
2118  *
2119  * This wrapper function for "samdb_set_password" takes a SID as input rather
2120  * than a user DN.
2121  *
2122  * This call encapsulates a new LDB transaction for changing the password;
2123  * therefore the user hasn't to start a new one.
2124  *
2125  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2126  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2127  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2128  *   NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2129  */
2130 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2131                                 const struct dom_sid *user_sid,
2132                                 const DATA_BLOB *new_password,
2133                                 const struct samr_Password *lmNewHash,
2134                                 const struct samr_Password *ntNewHash,
2135                                 const struct samr_Password *lmOldHash,
2136                                 const struct samr_Password *ntOldHash,
2137                                 enum samPwdChangeReason *reject_reason,
2138                                 struct samr_DomInfo1 **_dominfo) 
2139 {
2140         NTSTATUS nt_status;
2141         struct ldb_dn *user_dn;
2142         int ret;
2143
2144         ret = ldb_transaction_start(ldb);
2145         if (ret != LDB_SUCCESS) {
2146                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2147                 return NT_STATUS_TRANSACTION_ABORTED;
2148         }
2149
2150         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2151                                   "(&(objectSid=%s)(objectClass=user))", 
2152                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2153         if (!user_dn) {
2154                 ldb_transaction_cancel(ldb);
2155                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2156                           dom_sid_string(mem_ctx, user_sid)));
2157                 return NT_STATUS_NO_SUCH_USER;
2158         }
2159
2160         nt_status = samdb_set_password(ldb, mem_ctx,
2161                                        user_dn, NULL,
2162                                        new_password,
2163                                        lmNewHash, ntNewHash,
2164                                        lmOldHash, ntOldHash,
2165                                        reject_reason, _dominfo);
2166         if (!NT_STATUS_IS_OK(nt_status)) {
2167                 ldb_transaction_cancel(ldb);
2168                 talloc_free(user_dn);
2169                 return nt_status;
2170         }
2171
2172         ret = ldb_transaction_commit(ldb);
2173         if (ret != LDB_SUCCESS) {
2174                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2175                          ldb_dn_get_linearized(user_dn),
2176                          ldb_errstring(ldb)));
2177                 talloc_free(user_dn);
2178                 return NT_STATUS_TRANSACTION_ABORTED;
2179         }
2180
2181         talloc_free(user_dn);
2182         return NT_STATUS_OK;
2183 }
2184
2185
2186 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2187                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2188 {
2189         struct ldb_message *msg;
2190         struct ldb_dn *basedn;
2191         char *sidstr;
2192         int ret;
2193
2194         sidstr = dom_sid_string(mem_ctx, sid);
2195         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2196
2197         /* We might have to create a ForeignSecurityPrincipal, even if this user
2198          * is in our own domain */
2199
2200         msg = ldb_msg_new(sidstr);
2201         if (msg == NULL) {
2202                 talloc_free(sidstr);
2203                 return NT_STATUS_NO_MEMORY;
2204         }
2205
2206         ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2207                                 ldb_get_default_basedn(sam_ctx),
2208                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2209                                 &basedn);
2210         if (ret != LDB_SUCCESS) {
2211                 DEBUG(0, ("Failed to find DN for "
2212                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2213                 talloc_free(sidstr);
2214                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2215         }
2216
2217         /* add core elements to the ldb_message for the alias */
2218         msg->dn = basedn;
2219         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2220                 talloc_free(sidstr);
2221                 return NT_STATUS_NO_MEMORY;
2222         }
2223
2224         ret = ldb_msg_add_string(msg, "objectClass",
2225                                  "foreignSecurityPrincipal");
2226         if (ret != LDB_SUCCESS) {
2227                 talloc_free(sidstr);
2228                 return NT_STATUS_NO_MEMORY;
2229         }
2230
2231         /* create the alias */
2232         ret = ldb_add(sam_ctx, msg);
2233         if (ret != LDB_SUCCESS) {
2234                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2235                          "record %s: %s\n", 
2236                          ldb_dn_get_linearized(msg->dn),
2237                          ldb_errstring(sam_ctx)));
2238                 talloc_free(sidstr);
2239                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2240         }
2241
2242         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2243         talloc_free(sidstr);
2244
2245         return NT_STATUS_OK;
2246 }
2247
2248
2249 /*
2250   Find the DN of a domain, assuming it to be a dotted.dns name
2251 */
2252
2253 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2254 {
2255         unsigned int i;
2256         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2257         const char *binary_encoded;
2258         const char * const *split_realm;
2259         struct ldb_dn *dn;
2260
2261         if (!tmp_ctx) {
2262                 return NULL;
2263         }
2264
2265         split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
2266         if (!split_realm) {
2267                 talloc_free(tmp_ctx);
2268                 return NULL;
2269         }
2270         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2271         for (i=0; split_realm[i]; i++) {
2272                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2273                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2274                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2275                                   binary_encoded, ldb_dn_get_linearized(dn)));
2276                         talloc_free(tmp_ctx);
2277                         return NULL;
2278                 }
2279         }
2280         if (!ldb_dn_validate(dn)) {
2281                 DEBUG(2, ("Failed to validated DN %s\n",
2282                           ldb_dn_get_linearized(dn)));
2283                 talloc_free(tmp_ctx);
2284                 return NULL;
2285         }
2286         talloc_free(tmp_ctx);
2287         return dn;
2288 }
2289
2290
2291 /*
2292   Find the DNS equivalent of a DN, in dotted DNS form
2293 */
2294 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
2295 {
2296         int i, num_components = ldb_dn_get_comp_num(dn);
2297         char *dns_name = talloc_strdup(mem_ctx, "");
2298         if (dns_name == NULL) {
2299                 return NULL;
2300         }
2301
2302         for (i=0; i<num_components; i++) {
2303                 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
2304                 char *s;
2305                 if (v == NULL) {
2306                         talloc_free(dns_name);
2307                         return NULL;
2308                 }
2309                 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
2310                                                   (int)v->length, (int)v->length, (char *)v->data);
2311                 if (s == NULL) {
2312                         talloc_free(dns_name);
2313                         return NULL;
2314                 }
2315                 dns_name = s;
2316         }
2317
2318         /* remove the last '.' */
2319         if (dns_name[0] != 0) {
2320                 dns_name[strlen(dns_name)-1] = 0;
2321         }
2322
2323         return dns_name;
2324 }
2325
2326 /*
2327   Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
2328   name is based on the forest DNS name
2329 */
2330 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
2331                                 TALLOC_CTX *mem_ctx,
2332                                 const struct GUID *ntds_guid)
2333 {
2334         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2335         const char *guid_str;
2336         struct ldb_dn *forest_dn;
2337         const char *dnsforest;
2338         char *ret;
2339
2340         guid_str = GUID_string(tmp_ctx, ntds_guid);
2341         if (guid_str == NULL) {
2342                 talloc_free(tmp_ctx);
2343                 return NULL;
2344         }
2345         forest_dn = ldb_get_root_basedn(samdb);
2346         if (forest_dn == NULL) {
2347                 talloc_free(tmp_ctx);
2348                 return NULL;
2349         }
2350         dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
2351         if (dnsforest == NULL) {
2352                 talloc_free(tmp_ctx);
2353                 return NULL;
2354         }
2355         ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
2356         talloc_free(tmp_ctx);
2357         return ret;
2358 }
2359
2360
2361 /*
2362   Find the DN of a domain, be it the netbios or DNS name 
2363 */
2364 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2365                                   const char *domain_name) 
2366 {
2367         const char * const domain_ref_attrs[] = {
2368                 "ncName", NULL
2369         };
2370         const char * const domain_ref2_attrs[] = {
2371                 NULL
2372         };
2373         struct ldb_result *res_domain_ref;
2374         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2375         /* find the domain's DN */
2376         int ret_domain = ldb_search(ldb, mem_ctx,
2377                                             &res_domain_ref, 
2378                                             samdb_partitions_dn(ldb, mem_ctx), 
2379                                             LDB_SCOPE_ONELEVEL, 
2380                                             domain_ref_attrs,
2381                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2382                                             escaped_domain);
2383         if (ret_domain != LDB_SUCCESS) {
2384                 return NULL;
2385         }
2386
2387         if (res_domain_ref->count == 0) {
2388                 ret_domain = ldb_search(ldb, mem_ctx,
2389                                                 &res_domain_ref, 
2390                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2391                                                 LDB_SCOPE_BASE,
2392                                                 domain_ref2_attrs,
2393                                                 "(objectclass=domain)");
2394                 if (ret_domain != LDB_SUCCESS) {
2395                         return NULL;
2396                 }
2397
2398                 if (res_domain_ref->count == 1) {
2399                         return res_domain_ref->msgs[0]->dn;
2400                 }
2401                 return NULL;
2402         }
2403
2404         if (res_domain_ref->count > 1) {
2405                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2406                          ret_domain, domain_name));
2407                 return NULL;
2408         }
2409
2410         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2411
2412 }
2413
2414
2415 /*
2416   use a GUID to find a DN
2417  */
2418 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2419                          TALLOC_CTX *mem_ctx,
2420                          const struct GUID *guid, struct ldb_dn **dn)
2421 {
2422         int ret;
2423         struct ldb_result *res;
2424         const char *attrs[] = { NULL };
2425         char *guid_str = GUID_string(mem_ctx, guid);
2426
2427         if (!guid_str) {
2428                 return ldb_operr(ldb);
2429         }
2430
2431         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2432                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2433                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2434                           DSDB_SEARCH_ONE_ONLY,
2435                           "objectGUID=%s", guid_str);
2436         talloc_free(guid_str);
2437         if (ret != LDB_SUCCESS) {
2438                 return ret;
2439         }
2440
2441         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2442         talloc_free(res);
2443
2444         return LDB_SUCCESS;
2445 }
2446
2447 /*
2448   use a DN to find a GUID with a given attribute name
2449  */
2450 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2451                               struct ldb_dn *dn, const char *attribute,
2452                               struct GUID *guid)
2453 {
2454         int ret;
2455         struct ldb_result *res;
2456         const char *attrs[2];
2457         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2458
2459         attrs[0] = attribute;
2460         attrs[1] = NULL;
2461
2462         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2463                              DSDB_SEARCH_SHOW_DELETED |
2464                              DSDB_SEARCH_SHOW_RECYCLED);
2465         if (ret != LDB_SUCCESS) {
2466                 talloc_free(tmp_ctx);
2467                 return ret;
2468         }
2469         if (res->count < 1) {
2470                 talloc_free(tmp_ctx);
2471                 return LDB_ERR_NO_SUCH_OBJECT;
2472         }
2473         *guid = samdb_result_guid(res->msgs[0], attribute);
2474         talloc_free(tmp_ctx);
2475         return LDB_SUCCESS;
2476 }
2477
2478 /*
2479   use a DN to find a GUID
2480  */
2481 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2482                          struct ldb_dn *dn, struct GUID *guid)
2483 {
2484         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2485 }
2486
2487
2488
2489 /*
2490  adds the given GUID to the given ldb_message. This value is added
2491  for the given attr_name (may be either "objectGUID" or "parentGUID").
2492  */
2493 int dsdb_msg_add_guid(struct ldb_message *msg,
2494                 struct GUID *guid,
2495                 const char *attr_name)
2496 {
2497         int ret;
2498         struct ldb_val v;
2499         NTSTATUS status;
2500         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2501
2502         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2503         if (!NT_STATUS_IS_OK(status)) {
2504                 ret = LDB_ERR_OPERATIONS_ERROR;
2505                 goto done;
2506         }
2507
2508         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2509         if (ret != LDB_SUCCESS) {
2510                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2511                                          attr_name));
2512                 goto done;
2513         }
2514
2515         ret = LDB_SUCCESS;
2516
2517 done:
2518         talloc_free(tmp_ctx);
2519         return ret;
2520
2521 }
2522
2523
2524 /*
2525   use a DN to find a SID
2526  */
2527 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2528                         struct ldb_dn *dn, struct dom_sid *sid)
2529 {
2530         int ret;
2531         struct ldb_result *res;
2532         const char *attrs[] = { "objectSid", NULL };
2533         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2534         struct dom_sid *s;
2535
2536         ZERO_STRUCTP(sid);
2537
2538         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2539                              DSDB_SEARCH_SHOW_DELETED |
2540                              DSDB_SEARCH_SHOW_RECYCLED);
2541         if (ret != LDB_SUCCESS) {
2542                 talloc_free(tmp_ctx);
2543                 return ret;
2544         }
2545         if (res->count < 1) {
2546                 talloc_free(tmp_ctx);
2547                 return LDB_ERR_NO_SUCH_OBJECT;
2548         }
2549         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
2550         if (s == NULL) {
2551                 talloc_free(tmp_ctx);
2552                 return LDB_ERR_NO_SUCH_OBJECT;
2553         }
2554         *sid = *s;
2555         talloc_free(tmp_ctx);
2556         return LDB_SUCCESS;
2557 }
2558
2559 /*
2560   use a SID to find a DN
2561  */
2562 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
2563                         TALLOC_CTX *mem_ctx,
2564                         struct dom_sid *sid, struct ldb_dn **dn)
2565 {
2566         int ret;
2567         struct ldb_result *res;
2568         const char *attrs[] = { NULL };
2569         char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
2570
2571         if (!sid_str) {
2572                 return ldb_operr(ldb);
2573         }
2574
2575         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2576                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2577                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2578                           DSDB_SEARCH_ONE_ONLY,
2579                           "objectSid=%s", sid_str);
2580         talloc_free(sid_str);
2581         if (ret != LDB_SUCCESS) {
2582                 return ret;
2583         }
2584
2585         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2586         talloc_free(res);
2587
2588         return LDB_SUCCESS;
2589 }
2590
2591 /*
2592   load a repsFromTo blob list for a given partition GUID
2593   attr must be "repsFrom" or "repsTo"
2594  */
2595 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2596                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2597 {
2598         const char *attrs[] = { attr, NULL };
2599         struct ldb_result *res = NULL;
2600         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2601         unsigned int i;
2602         struct ldb_message_element *el;
2603         int ret;
2604
2605         *r = NULL;
2606         *count = 0;
2607
2608         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
2609         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2610                 /* partition hasn't been replicated yet */
2611                 return WERR_OK;
2612         }
2613         if (ret != LDB_SUCCESS) {
2614                 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
2615                 talloc_free(tmp_ctx);
2616                 return WERR_DS_DRA_INTERNAL_ERROR;
2617         }
2618
2619         el = ldb_msg_find_element(res->msgs[0], attr);
2620         if (el == NULL) {
2621                 /* it's OK to be empty */
2622                 talloc_free(tmp_ctx);
2623                 return WERR_OK;
2624         }
2625
2626         *count = el->num_values;
2627         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2628         if (*r == NULL) {
2629                 talloc_free(tmp_ctx);
2630                 return WERR_DS_DRA_INTERNAL_ERROR;
2631         }
2632
2633         for (i=0; i<(*count); i++) {
2634                 enum ndr_err_code ndr_err;
2635                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2636                                                mem_ctx, 
2637                                                &(*r)[i], 
2638                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2639                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2640                         talloc_free(tmp_ctx);
2641                         return WERR_DS_DRA_INTERNAL_ERROR;
2642                 }
2643         }
2644
2645         talloc_free(tmp_ctx);
2646         
2647         return WERR_OK;
2648 }
2649
2650 /*
2651   save the repsFromTo blob list for a given partition GUID
2652   attr must be "repsFrom" or "repsTo"
2653  */
2654 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2655                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2656 {
2657         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2658         struct ldb_message *msg;
2659         struct ldb_message_element *el;
2660         unsigned int i;
2661
2662         msg = ldb_msg_new(tmp_ctx);
2663         msg->dn = dn;
2664         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2665                 goto failed;
2666         }
2667
2668         el->values = talloc_array(msg, struct ldb_val, count);
2669         if (!el->values) {
2670                 goto failed;
2671         }
2672
2673         for (i=0; i<count; i++) {
2674                 struct ldb_val v;
2675                 enum ndr_err_code ndr_err;
2676
2677                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, 
2678                                                &r[i], 
2679                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2680                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2681                         goto failed;
2682                 }
2683
2684                 el->num_values++;
2685                 el->values[i] = v;
2686         }
2687
2688         if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
2689                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2690                 goto failed;
2691         }
2692
2693         talloc_free(tmp_ctx);
2694         
2695         return WERR_OK;
2696
2697 failed:
2698         talloc_free(tmp_ctx);
2699         return WERR_DS_DRA_INTERNAL_ERROR;
2700 }
2701
2702
2703 /*
2704   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2705   object for a partition
2706  */
2707 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2708                                 uint64_t *uSN, uint64_t *urgent_uSN)
2709 {
2710         struct ldb_request *req;
2711         int ret;
2712         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2713         struct dsdb_control_current_partition *p_ctrl;
2714         struct ldb_result *res;
2715
2716         res = talloc_zero(tmp_ctx, struct ldb_result);
2717         if (!res) {
2718                 talloc_free(tmp_ctx);
2719                 return ldb_oom(ldb);
2720         }
2721
2722         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2723                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2724                                    LDB_SCOPE_BASE,
2725                                    NULL, NULL,
2726                                    NULL,
2727                                    res, ldb_search_default_callback,
2728                                    NULL);
2729         if (ret != LDB_SUCCESS) {
2730                 talloc_free(tmp_ctx);
2731                 return ret;
2732         }
2733
2734         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2735         if (p_ctrl == NULL) {
2736                 talloc_free(tmp_ctx);
2737                 return ldb_oom(ldb);
2738         }
2739         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2740         p_ctrl->dn = dn;
2741         
2742         ret = ldb_request_add_control(req,
2743                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2744                                       false, p_ctrl);
2745         if (ret != LDB_SUCCESS) {
2746                 talloc_free(tmp_ctx);
2747                 return ret;
2748         }
2749         
2750         /* Run the new request */
2751         ret = ldb_request(ldb, req);
2752         
2753         if (ret == LDB_SUCCESS) {
2754                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2755         }
2756
2757         if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
2758                 /* it hasn't been created yet, which means
2759                    an implicit value of zero */
2760                 *uSN = 0;
2761                 talloc_free(tmp_ctx);
2762                 return LDB_SUCCESS;
2763         }
2764
2765         if (ret != LDB_SUCCESS) {
2766                 talloc_free(tmp_ctx);
2767                 return ret;
2768         }
2769
2770         if (res->count < 1) {
2771                 *uSN = 0;
2772                 if (urgent_uSN) {
2773                         *urgent_uSN = 0;
2774                 }
2775         } else {
2776                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2777                 if (urgent_uSN) {
2778                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2779                 }
2780         }
2781
2782         talloc_free(tmp_ctx);
2783
2784         return LDB_SUCCESS;     
2785 }
2786
2787 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2788                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2789 {
2790         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2791 }
2792
2793 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2794                                     const struct drsuapi_DsReplicaCursor *c2)
2795 {
2796         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2797 }
2798
2799
2800 /*
2801   see if a computer identified by its invocationId is a RODC
2802 */
2803 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
2804 {
2805         /* 1) find the DN for this servers NTDSDSA object
2806            2) search for the msDS-isRODC attribute
2807            3) if not present then not a RODC
2808            4) if present and TRUE then is a RODC
2809         */
2810         struct ldb_dn *config_dn;
2811         const char *attrs[] = { "msDS-isRODC", NULL };
2812         int ret;
2813         struct ldb_result *res;
2814         TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
2815
2816         config_dn = ldb_get_config_basedn(sam_ctx);
2817         if (!config_dn) {
2818                 talloc_free(tmp_ctx);
2819                 return ldb_operr(sam_ctx);
2820         }
2821
2822         ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
2823                           DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
2824
2825         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2826                 *is_rodc = false;
2827                 talloc_free(tmp_ctx);
2828                 return LDB_SUCCESS;
2829         }
2830
2831         if (ret != LDB_SUCCESS) {
2832                 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
2833                          GUID_string(tmp_ctx, objectGUID)));
2834                 *is_rodc = false;
2835                 talloc_free(tmp_ctx);
2836                 return ret;
2837         }
2838
2839         ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
2840         *is_rodc = (ret == 1);
2841
2842         talloc_free(tmp_ctx);
2843         return LDB_SUCCESS;
2844 }
2845
2846
2847 /*
2848   see if we are a RODC
2849 */
2850 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
2851 {
2852         const struct GUID *objectGUID;
2853         int ret;
2854         bool *cached;
2855
2856         /* see if we have a cached copy */
2857         cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
2858         if (cached) {
2859                 *am_rodc = *cached;
2860                 return LDB_SUCCESS;
2861         }
2862
2863         objectGUID = samdb_ntds_objectGUID(sam_ctx);
2864         if (!objectGUID) {
2865                 return ldb_operr(sam_ctx);
2866         }
2867
2868         ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
2869         if (ret != LDB_SUCCESS) {
2870                 return ret;
2871         }
2872
2873         cached = talloc(sam_ctx, bool);
2874         if (cached == NULL) {
2875                 return ldb_oom(sam_ctx);
2876         }
2877         *cached = *am_rodc;
2878
2879         ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
2880         if (ret != LDB_SUCCESS) {
2881                 talloc_free(cached);
2882                 return ldb_operr(sam_ctx);
2883         }
2884
2885         return LDB_SUCCESS;
2886 }
2887
2888 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
2889 {
2890         TALLOC_CTX *tmp_ctx;
2891         bool *cached;
2892
2893         tmp_ctx = talloc_new(ldb);
2894         if (tmp_ctx == NULL) {
2895                 goto failed;
2896         }
2897
2898         cached = talloc(tmp_ctx, bool);
2899         if (!cached) {
2900                 goto failed;
2901         }
2902
2903         *cached = am_rodc;
2904         if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
2905                 goto failed;
2906         }
2907
2908         talloc_steal(ldb, cached);
2909         talloc_free(tmp_ctx);
2910         return true;
2911
2912 failed:
2913         DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
2914         talloc_free(tmp_ctx);
2915         return false;
2916 }
2917
2918
2919 /*
2920  * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
2921  * flags are DS_NTDSSETTINGS_OPT_*
2922  */
2923 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
2924                                         uint32_t *options)
2925 {
2926         int rc;
2927         TALLOC_CTX *tmp_ctx;
2928         struct ldb_result *res;
2929         struct ldb_dn *site_dn;
2930         const char *attrs[] = { "options", NULL };
2931
2932         tmp_ctx = talloc_new(ldb_ctx);
2933         if (tmp_ctx == NULL)
2934                 goto failed;
2935
2936         /* Retrieve the site dn for the ldb that we
2937          * have open.  This is our local site.
2938          */
2939         site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
2940         if (site_dn == NULL)
2941                 goto failed;
2942
2943         /* Perform a one level (child) search from the local
2944          * site distinguided name.   We're looking for the
2945          * "options" attribute within the nTDSSiteSettings
2946          * object
2947          */
2948         rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
2949                         LDB_SCOPE_ONELEVEL, attrs,
2950                         "objectClass=nTDSSiteSettings");
2951
2952         if (rc != LDB_SUCCESS || res->count != 1)
2953                 goto failed;
2954
2955         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
2956
2957         talloc_free(tmp_ctx);
2958
2959         return LDB_SUCCESS;
2960
2961 failed:
2962         DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
2963         talloc_free(tmp_ctx);
2964         return LDB_ERR_NO_SUCH_OBJECT;
2965 }
2966
2967 /*
2968   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
2969
2970   flags are DS_NTDS_OPTION_*
2971 */
2972 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
2973 {
2974         TALLOC_CTX *tmp_ctx;
2975         const char *attrs[] = { "options", NULL };
2976         int ret;
2977         struct ldb_result *res;
2978
2979         tmp_ctx = talloc_new(ldb);
2980         if (tmp_ctx == NULL) {
2981                 goto failed;
2982         }
2983
2984         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
2985         if (ret != LDB_SUCCESS) {
2986                 goto failed;
2987         }
2988
2989         if (res->count != 1) {
2990                 goto failed;
2991         }
2992
2993         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
2994
2995         talloc_free(tmp_ctx);
2996
2997         return LDB_SUCCESS;
2998
2999 failed:
3000         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3001         talloc_free(tmp_ctx);
3002         return LDB_ERR_NO_SUCH_OBJECT;
3003 }
3004
3005 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3006 {
3007         const char *attrs[] = { "objectCategory", NULL };
3008         int ret;
3009         struct ldb_result *res;
3010
3011         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb), LDB_SCOPE_BASE, attrs, NULL);
3012         if (ret != LDB_SUCCESS) {
3013                 goto failed;
3014         }
3015
3016         if (res->count != 1) {
3017                 goto failed;
3018         }
3019
3020         return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3021
3022 failed:
3023         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3024         return NULL;
3025 }
3026
3027 /*
3028  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3029  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3030  */
3031 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3032 {
3033         char **tokens, *ret;
3034         size_t i;
3035
3036         tokens = str_list_make(mem_ctx, cn, " -_");
3037         if (tokens == NULL)
3038                 return NULL;
3039
3040         /* "tolower()" and "toupper()" should also work properly on 0x00 */
3041         tokens[0][0] = tolower(tokens[0][0]);
3042         for (i = 1; i < str_list_length((const char * const *)tokens); i++)
3043                 tokens[i][0] = toupper(tokens[i][0]);
3044
3045         ret = talloc_strdup(mem_ctx, tokens[0]);
3046         for (i = 1; i < str_list_length((const char * const *)tokens); i++)
3047                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3048
3049         talloc_free(tokens);
3050
3051         return ret;
3052 }
3053
3054 /*
3055  * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3056  */
3057 int dsdb_functional_level(struct ldb_context *ldb)
3058 {
3059         int *domainFunctionality =
3060                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3061         if (!domainFunctionality) {
3062                 /* this is expected during initial provision */
3063                 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3064                 return DS_DOMAIN_FUNCTION_2000;
3065         }
3066         return *domainFunctionality;
3067 }
3068
3069 /*
3070  * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3071  */
3072 int dsdb_forest_functional_level(struct ldb_context *ldb)
3073 {
3074         int *forestFunctionality =
3075                 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3076         if (!forestFunctionality) {
3077                 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3078                 return DS_DOMAIN_FUNCTION_2000;
3079         }
3080         return *forestFunctionality;
3081 }
3082
3083 /*
3084   set a GUID in an extended DN structure
3085  */
3086 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3087 {
3088         struct ldb_val v;
3089         NTSTATUS status;
3090         int ret;
3091
3092         status = GUID_to_ndr_blob(guid, dn, &v);
3093         if (!NT_STATUS_IS_OK(status)) {
3094                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3095         }
3096
3097         ret = ldb_dn_set_extended_component(dn, component_name, &v);
3098         data_blob_free(&v);
3099         return ret;
3100 }
3101
3102 /*
3103   return a GUID from a extended DN structure
3104  */
3105 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3106 {
3107         const struct ldb_val *v;
3108
3109         v = ldb_dn_get_extended_component(dn, component_name);
3110         if (v == NULL) {
3111                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3112         }
3113
3114         return GUID_from_ndr_blob(v, guid);
3115 }
3116
3117 /*
3118   return a uint64_t from a extended DN structure
3119  */
3120 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3121 {
3122         const struct ldb_val *v;
3123         char *s;
3124
3125         v = ldb_dn_get_extended_component(dn, component_name);
3126         if (v == NULL) {
3127                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3128         }
3129         s = talloc_strndup(dn, (const char *)v->data, v->length);
3130         NT_STATUS_HAVE_NO_MEMORY(s);
3131
3132         *val = strtoull(s, NULL, 0);
3133
3134         talloc_free(s);
3135         return NT_STATUS_OK;
3136 }
3137
3138 /*
3139   return a NTTIME from a extended DN structure
3140  */
3141 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3142 {
3143         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3144 }
3145
3146 /*
3147   return a uint32_t from a extended DN structure
3148  */
3149 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3150 {
3151         const struct ldb_val *v;
3152         char *s;
3153
3154         v = ldb_dn_get_extended_component(dn, component_name);
3155         if (v == NULL) {
3156                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3157         }
3158
3159         s = talloc_strndup(dn, (const char *)v->data, v->length);
3160         NT_STATUS_HAVE_NO_MEMORY(s);
3161
3162         *val = strtoul(s, NULL, 0);
3163
3164         talloc_free(s);
3165         return NT_STATUS_OK;
3166 }
3167
3168 /*
3169   return a dom_sid from a extended DN structure
3170  */
3171 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3172 {
3173         const struct ldb_val *sid_blob;
3174         struct TALLOC_CTX *tmp_ctx;
3175         enum ndr_err_code ndr_err;
3176
3177         sid_blob = ldb_dn_get_extended_component(dn, component_name);
3178         if (!sid_blob) {
3179                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3180         }
3181
3182         tmp_ctx = talloc_new(NULL);
3183
3184         ndr_err = ndr_pull_struct_blob_all(sid_blob, tmp_ctx, sid,
3185                                            (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3186         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3187                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3188                 talloc_free(tmp_ctx);
3189                 return status;
3190         }
3191
3192         talloc_free(tmp_ctx);
3193         return NT_STATUS_OK;
3194 }
3195
3196
3197 /*
3198   return RMD_FLAGS directly from a ldb_dn
3199   returns 0 if not found
3200  */
3201 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3202 {
3203         const struct ldb_val *v;
3204         char buf[32];
3205         v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
3206         if (!v || v->length > sizeof(buf)-1) return 0;
3207         strncpy(buf, (const char *)v->data, v->length);
3208         buf[v->length] = 0;
3209         return strtoul(buf, NULL, 10);
3210 }
3211
3212 /*
3213   return RMD_FLAGS directly from a ldb_val for a DN
3214   returns 0 if RMD_FLAGS is not found
3215  */
3216 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3217 {
3218         const char *p;
3219         uint32_t flags;
3220         char *end;
3221
3222         if (val->length < 13) {
3223                 return 0;
3224         }
3225         p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3226         if (!p) {
3227                 return 0;
3228         }
3229         flags = strtoul(p+11, &end, 10);
3230         if (!end || *end != '>') {
3231                 /* it must end in a > */
3232                 return 0;
3233         }
3234         return flags;
3235 }
3236
3237 /*
3238   return true if a ldb_val containing a DN in storage form is deleted
3239  */
3240 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3241 {
3242         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3243 }
3244
3245 /*
3246   return true if a ldb_val containing a DN in storage form is
3247   in the upgraded w2k3 linked attribute format
3248  */
3249 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3250 {
3251         return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
3252 }
3253
3254 /*
3255   return a DN for a wellknown GUID
3256  */
3257 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3258                       struct ldb_dn *nc_root, const char *wk_guid,
3259                       struct ldb_dn **wkguid_dn)
3260 {
3261         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3262         const char *attrs[] = { NULL };
3263         int ret;
3264         struct ldb_dn *dn;
3265         struct ldb_result *res;
3266
3267         /* construct the magic WKGUID DN */
3268         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3269                             wk_guid, ldb_dn_get_linearized(nc_root));
3270         if (!wkguid_dn) {
3271                 talloc_free(tmp_ctx);
3272                 return ldb_operr(samdb);
3273         }
3274
3275         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
3276                              DSDB_SEARCH_SHOW_DELETED |
3277                              DSDB_SEARCH_SHOW_RECYCLED);
3278         if (ret != LDB_SUCCESS) {
3279                 talloc_free(tmp_ctx);
3280                 return ret;
3281         }
3282
3283         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3284         talloc_free(tmp_ctx);
3285         return LDB_SUCCESS;
3286 }
3287
3288
3289 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3290 {
3291         return ldb_dn_compare(*dn1, *dn2);
3292 }
3293
3294 /*
3295   find a NC root given a DN within the NC
3296  */
3297 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3298                       struct ldb_dn **nc_root)
3299 {
3300         const char *root_attrs[] = { "namingContexts", NULL };
3301         TALLOC_CTX *tmp_ctx;
3302         int ret;
3303         struct ldb_message_element *el;
3304         struct ldb_result *root_res;
3305         unsigned int i;
3306         struct ldb_dn **nc_dns;
3307
3308         tmp_ctx = talloc_new(samdb);
3309         if (tmp_ctx == NULL) {
3310                 return ldb_oom(samdb);
3311         }
3312
3313         ret = ldb_search(samdb, tmp_ctx, &root_res,
3314                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3315         if (ret != LDB_SUCCESS) {
3316                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3317                 talloc_free(tmp_ctx);
3318                 return ret;
3319         }
3320
3321         el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3322         if ((el == NULL) || (el->num_values < 3)) {
3323                 struct ldb_message *tmp_msg;
3324
3325                 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list."));
3326
3327                 /* This generates a temporary list of NCs in order to let the
3328                  * provisioning work. */
3329                 tmp_msg = ldb_msg_new(tmp_ctx);
3330                 if (tmp_msg == NULL) {
3331                         talloc_free(tmp_ctx);
3332                         return ldb_oom(samdb);
3333                 }
3334                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3335                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
3336                 if (ret != LDB_SUCCESS) {
3337                         talloc_free(tmp_ctx);
3338                         return ret;
3339                 }
3340                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3341                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
3342                 if (ret != LDB_SUCCESS) {
3343                         talloc_free(tmp_ctx);
3344                         return ret;
3345                 }
3346                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3347                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
3348                 if (ret != LDB_SUCCESS) {
3349                         talloc_free(tmp_ctx);
3350                         return ret;
3351                 }
3352                 el = &tmp_msg->elements[0];
3353         }
3354
3355        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3356        if (!nc_dns) {
3357                talloc_free(tmp_ctx);
3358                return ldb_oom(samdb);
3359        }
3360
3361        for (i=0; i<el->num_values; i++) {
3362                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3363                if (nc_dns[i] == NULL) {
3364                        talloc_free(tmp_ctx);
3365                        return ldb_operr(samdb);
3366                }
3367        }
3368
3369        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3370
3371        for (i=0; i<el->num_values; i++) {
3372                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3373                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3374                        talloc_free(tmp_ctx);
3375                        return LDB_SUCCESS;
3376                }
3377        }
3378
3379        talloc_free(tmp_ctx);
3380        return LDB_ERR_NO_SUCH_OBJECT;
3381 }
3382
3383
3384 /*
3385   find the deleted objects DN for any object, by looking for the NC
3386   root, then looking up the wellknown GUID
3387  */
3388 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3389                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3390                                 struct ldb_dn **do_dn)
3391 {
3392         struct ldb_dn *nc_root;
3393         int ret;
3394
3395         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3396         if (ret != LDB_SUCCESS) {
3397                 return ret;
3398         }
3399
3400         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3401         talloc_free(nc_root);
3402         return ret;
3403 }
3404
3405 /*
3406   return the tombstoneLifetime, in days
3407  */
3408 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3409 {
3410         struct ldb_dn *dn;
3411         dn = ldb_get_config_basedn(ldb);
3412         if (!dn) {
3413                 return LDB_ERR_NO_SUCH_OBJECT;
3414         }
3415         dn = ldb_dn_copy(ldb, dn);
3416         if (!dn) {
3417                 return ldb_operr(ldb);
3418         }
3419         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3420          be a wellknown GUID for this */
3421         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3422                 talloc_free(dn);
3423                 return ldb_operr(ldb);
3424         }
3425
3426         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3427         talloc_free(dn);
3428         return LDB_SUCCESS;
3429 }
3430
3431 /*
3432   compare a ldb_val to a string case insensitively
3433  */
3434 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3435 {
3436         size_t len = strlen(s);
3437         int ret;
3438         if (len > v->length) return 1;
3439         ret = strncasecmp(s, (const char *)v->data, v->length);
3440         if (ret != 0) return ret;
3441         if (v->length > len && v->data[len] != 0) {
3442                 return -1;
3443         }
3444         return 0;
3445 }
3446
3447
3448 /*
3449   load the UDV for a partition in v2 format
3450   The list is returned sorted, and with our local cursor added
3451  */
3452 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3453                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3454 {
3455         static const char *attrs[] = { "replUpToDateVector", NULL };
3456         struct ldb_result *r;
3457         const struct ldb_val *ouv_value;
3458         unsigned int i;
3459         int ret;
3460         uint64_t highest_usn;
3461         const struct GUID *our_invocation_id;
3462         struct timeval now = timeval_current();
3463
3464         ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3465         if (ret != LDB_SUCCESS) {
3466                 return ret;
3467         }
3468
3469         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3470         if (ouv_value) {
3471                 enum ndr_err_code ndr_err;
3472                 struct replUpToDateVectorBlob ouv;
3473
3474                 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
3475                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3476                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3477                         talloc_free(r);
3478                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3479                 }
3480                 if (ouv.version != 2) {
3481                         /* we always store as version 2, and
3482                          * replUpToDateVector is not replicated
3483                          */
3484                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3485                 }
3486
3487                 *count = ouv.ctr.ctr2.count;
3488                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3489         } else {
3490                 *count = 0;
3491                 *cursors = NULL;
3492         }
3493
3494         talloc_free(r);
3495
3496         our_invocation_id = samdb_ntds_invocation_id(samdb);
3497         if (!our_invocation_id) {
3498                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3499                 talloc_free(*cursors);
3500                 return ldb_operr(samdb);
3501         }
3502
3503         ret = dsdb_load_partition_usn(samdb, dn, &highest_usn, NULL);
3504         if (ret != LDB_SUCCESS) {
3505                 /* nothing to add - this can happen after a vampire */
3506                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3507                 return LDB_SUCCESS;
3508         }
3509
3510         for (i=0; i<*count; i++) {
3511                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3512                         (*cursors)[i].highest_usn = highest_usn;
3513                         (*cursors)[i].last_sync_success = timeval_to_nttime(&now);
3514                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3515                         return LDB_SUCCESS;
3516                 }
3517         }
3518
3519         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3520         if (! *cursors) {
3521                 return ldb_oom(samdb);
3522         }
3523
3524         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3525         (*cursors)[*count].highest_usn = highest_usn;
3526         (*cursors)[*count].last_sync_success = timeval_to_nttime(&now);
3527         (*count)++;
3528
3529         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3530
3531         return LDB_SUCCESS;
3532 }
3533
3534 /*
3535   load the UDV for a partition in version 1 format
3536   The list is returned sorted, and with our local cursor added
3537  */
3538 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3539                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3540 {
3541         struct drsuapi_DsReplicaCursor2 *v2;
3542         uint32_t i;
3543         int ret;
3544
3545         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3546         if (ret != LDB_SUCCESS) {
3547                 return ret;
3548         }
3549
3550         if (*count == 0) {
3551                 talloc_free(v2);
3552                 *cursors = NULL;
3553                 return LDB_SUCCESS;
3554         }
3555
3556         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3557         if (*cursors == NULL) {
3558                 talloc_free(v2);
3559                 return ldb_oom(samdb);
3560         }
3561
3562         for (i=0; i<*count; i++) {
3563                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3564                 (*cursors)[i].highest_usn = v2[i].highest_usn;
3565         }
3566         talloc_free(v2);
3567         return LDB_SUCCESS;
3568 }
3569
3570 /*
3571   add a set of controls to a ldb_request structure based on a set of
3572   flags. See util.h for a list of available flags
3573  */
3574 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3575 {
3576         int ret;
3577         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3578                 struct ldb_search_options_control *options;
3579                 /* Using the phantom root control allows us to search all partitions */
3580                 options = talloc(req, struct ldb_search_options_control);
3581                 if (options == NULL) {
3582                         return LDB_ERR_OPERATIONS_ERROR;
3583                 }
3584                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3585
3586                 ret = ldb_request_add_control(req,
3587                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
3588                                               true, options);
3589                 if (ret != LDB_SUCCESS) {
3590                         return ret;
3591                 }
3592         }
3593
3594         if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
3595                 ret = ldb_request_add_control(req,
3596                                               DSDB_CONTROL_NO_GLOBAL_CATALOG,
3597                                               false, NULL);
3598                 if (ret != LDB_SUCCESS) {
3599                         return ret;
3600                 }
3601         }
3602
3603         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3604                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3605                 if (ret != LDB_SUCCESS) {
3606                         return ret;
3607                 }
3608         }
3609
3610         if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
3611                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
3612                 if (ret != LDB_SUCCESS) {
3613                         return ret;
3614                 }
3615         }
3616
3617         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3618                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
3619                 if (ret != LDB_SUCCESS) {
3620                         return ret;
3621                 }
3622         }
3623
3624         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3625                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3626                 if (!extended_ctrl) {
3627                         return LDB_ERR_OPERATIONS_ERROR;
3628                 }
3629                 extended_ctrl->type = 1;
3630
3631                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3632                 if (ret != LDB_SUCCESS) {
3633                         return ret;
3634                 }
3635         }
3636
3637         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3638                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3639                 if (ret != LDB_SUCCESS) {
3640                         return ret;
3641                 }
3642         }
3643
3644         if (dsdb_flags & DSDB_MODIFY_RELAX) {
3645                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3646                 if (ret != LDB_SUCCESS) {
3647                         return ret;
3648                 }
3649         }
3650
3651         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3652                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3653                 if (ret != LDB_SUCCESS) {
3654                         return ret;
3655                 }
3656         }
3657
3658         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3659                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3660                 if (ret != LDB_SUCCESS) {
3661                         return ret;
3662                 }
3663         }
3664
3665         if (dsdb_flags & DSDB_TREE_DELETE) {
3666                 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
3667                 if (ret != LDB_SUCCESS) {
3668                         return ret;
3669                 }
3670         }
3671
3672         if (dsdb_flags & DSDB_PROVISION) {
3673                 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
3674                 if (ret != LDB_SUCCESS) {
3675                         return ret;
3676                 }
3677         }
3678
3679         /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
3680         if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
3681                 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
3682                 if (ret != LDB_SUCCESS) {
3683                         return ret;
3684                 }
3685         }
3686
3687         if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
3688                 /* 
3689                  * This must not be critical, as it will only be
3690                  * handled (and need to be handled) if the other
3691                  * attributes in the request bring password_hash into
3692                  * action
3693                  */
3694                 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
3695                 if (ret != LDB_SUCCESS) {
3696                         return ret;
3697                 }
3698         }
3699
3700         if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
3701                 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
3702                 if (ret != LDB_SUCCESS) {
3703                         return ret;
3704                 }
3705         }
3706
3707         return LDB_SUCCESS;
3708 }
3709
3710 /*
3711   an add with a set of controls
3712 */
3713 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
3714              uint32_t dsdb_flags)
3715 {
3716         struct ldb_request *req;
3717         int ret;
3718
3719         ret = ldb_build_add_req(&req, ldb, ldb,
3720                                 message,
3721                                 NULL,
3722                                 NULL,
3723                                 ldb_op_default_callback,
3724                                 NULL);
3725
3726         if (ret != LDB_SUCCESS) return ret;
3727
3728         ret = dsdb_request_add_controls(req, dsdb_flags);
3729         if (ret != LDB_SUCCESS) {
3730                 talloc_free(req);
3731                 return ret;
3732         }
3733
3734         ret = dsdb_autotransaction_request(ldb, req);
3735
3736         talloc_free(req);
3737         return ret;
3738 }
3739
3740 /*
3741   a modify with a set of controls
3742 */
3743 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3744                 uint32_t dsdb_flags)
3745 {
3746         struct ldb_request *req;
3747         int ret;
3748
3749         ret = ldb_build_mod_req(&req, ldb, ldb,
3750                                 message,
3751                                 NULL,
3752                                 NULL,
3753                                 ldb_op_default_callback,
3754                                 NULL);
3755
3756         if (ret != LDB_SUCCESS) return ret;
3757
3758         ret = dsdb_request_add_controls(req, dsdb_flags);
3759         if (ret != LDB_SUCCESS) {
3760                 talloc_free(req);
3761                 return ret;
3762         }
3763
3764         ret = dsdb_autotransaction_request(ldb, req);
3765
3766         talloc_free(req);
3767         return ret;
3768 }
3769
3770 /*
3771   a delete with a set of flags
3772 */
3773 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
3774                 uint32_t dsdb_flags)
3775 {
3776         struct ldb_request *req;
3777         int ret;
3778
3779         ret = ldb_build_del_req(&req, ldb, ldb,
3780                                 dn,
3781                                 NULL,
3782                                 NULL,
3783                                 ldb_op_default_callback,
3784                                 NULL);
3785
3786         if (ret != LDB_SUCCESS) return ret;
3787
3788         ret = dsdb_request_add_controls(req, dsdb_flags);
3789         if (ret != LDB_SUCCESS) {
3790                 talloc_free(req);
3791                 return ret;
3792         }
3793
3794         ret = dsdb_autotransaction_request(ldb, req);
3795
3796         talloc_free(req);
3797         return ret;
3798 }
3799
3800 /*
3801   like dsdb_modify() but set all the element flags to
3802   LDB_FLAG_MOD_REPLACE
3803  */
3804 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3805 {
3806         unsigned int i;
3807
3808         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3809         for (i=0;i<msg->num_elements;i++) {
3810                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3811         }
3812
3813         return dsdb_modify(ldb, msg, dsdb_flags);
3814 }
3815
3816
3817 /*
3818   search for attrs on one DN, allowing for dsdb_flags controls
3819  */
3820 int dsdb_search_dn(struct ldb_context *ldb,
3821                    TALLOC_CTX *mem_ctx,
3822                    struct ldb_result **_res,
3823                    struct ldb_dn *basedn,
3824                    const char * const *attrs,
3825                    uint32_t dsdb_flags)
3826 {
3827         int ret;
3828         struct ldb_request *req;
3829         struct ldb_result *res;
3830
3831         res = talloc_zero(mem_ctx, struct ldb_result);
3832         if (!res) {
3833                 return ldb_oom(ldb);
3834         }
3835
3836         ret = ldb_build_search_req(&req, ldb, res,
3837                                    basedn,
3838                                    LDB_SCOPE_BASE,
3839                                    NULL,
3840                                    attrs,
3841                                    NULL,
3842                                    res,
3843                                    ldb_search_default_callback,
3844                                    NULL);
3845         if (ret != LDB_SUCCESS) {
3846                 talloc_free(res);
3847                 return ret;
3848         }
3849
3850         ret = dsdb_request_add_controls(req, dsdb_flags);
3851         if (ret != LDB_SUCCESS) {
3852                 talloc_free(res);
3853                 return ret;
3854         }
3855
3856         ret = ldb_request(ldb, req);
3857         if (ret == LDB_SUCCESS) {
3858                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3859         }
3860
3861         talloc_free(req);
3862         if (ret != LDB_SUCCESS) {
3863                 talloc_free(res);
3864                 return ret;
3865         }
3866
3867         *_res = res;
3868         return LDB_SUCCESS;
3869 }
3870
3871 /*
3872   search for attrs on one DN, by the GUID of the DN, allowing for
3873   dsdb_flags controls
3874  */
3875 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
3876                            TALLOC_CTX *mem_ctx,
3877                            struct ldb_result **_res,
3878                            const struct GUID *guid,
3879                            const char * const *attrs,
3880                            uint32_t dsdb_flags)
3881 {
3882         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3883         struct ldb_dn *dn;
3884         int ret;
3885
3886         dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
3887         if (dn == NULL) {
3888                 talloc_free(tmp_ctx);
3889                 return ldb_oom(ldb);
3890         }
3891
3892         ret = dsdb_search_dn(ldb, mem_ctx, _res, dn, attrs, dsdb_flags);
3893         talloc_free(tmp_ctx);
3894         return ret;
3895 }
3896
3897 /*
3898   general search with dsdb_flags for controls
3899  */
3900 int dsdb_search(struct ldb_context *ldb,
3901                 TALLOC_CTX *mem_ctx,
3902                 struct ldb_result **_res,
3903                 struct ldb_dn *basedn,
3904                 enum ldb_scope scope,
3905                 const char * const *attrs,
3906                 uint32_t dsdb_flags,
3907                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3908 {
3909         int ret;
3910         struct ldb_request *req;
3911         struct ldb_result *res;
3912         va_list ap;
3913         char *expression = NULL;
3914         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3915
3916         /* cross-partitions searches with a basedn break multi-domain support */
3917         SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
3918
3919         res = talloc_zero(tmp_ctx, struct ldb_result);
3920         if (!res) {
3921                 talloc_free(tmp_ctx);
3922                 return ldb_oom(ldb);
3923         }
3924
3925         if (exp_fmt) {
3926                 va_start(ap, exp_fmt);
3927                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3928                 va_end(ap);
3929
3930                 if (!expression) {
3931                         talloc_free(tmp_ctx);
3932                         return ldb_oom(ldb);
3933                 }
3934         }
3935
3936         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3937                                    basedn,
3938                                    scope,
3939                                    expression,
3940                                    attrs,
3941                                    NULL,
3942                                    res,
3943                                    ldb_search_default_callback,
3944                                    NULL);
3945         if (ret != LDB_SUCCESS) {
3946                 talloc_free(tmp_ctx);
3947                 return ret;
3948         }
3949
3950         ret = dsdb_request_add_controls(req, dsdb_flags);
3951         if (ret != LDB_SUCCESS) {
3952                 talloc_free(tmp_ctx);
3953                 ldb_reset_err_string(ldb);
3954                 return ret;
3955         }
3956
3957         ret = ldb_request(ldb, req);
3958         if (ret == LDB_SUCCESS) {
3959                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3960         }
3961
3962         if (ret != LDB_SUCCESS) {
3963                 talloc_free(tmp_ctx);
3964                 return ret;
3965         }
3966
3967         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
3968                 if (res->count == 0) {
3969                         talloc_free(tmp_ctx);
3970                         ldb_reset_err_string(ldb);
3971                         return LDB_ERR_NO_SUCH_OBJECT;
3972                 }
3973                 if (res->count != 1) {
3974                         talloc_free(tmp_ctx);
3975                         ldb_reset_err_string(ldb);
3976                         return LDB_ERR_CONSTRAINT_VIOLATION;
3977                 }
3978         }
3979
3980         *_res = talloc_steal(mem_ctx, res);
3981         talloc_free(tmp_ctx);
3982
3983         return LDB_SUCCESS;
3984 }
3985
3986
3987 /*
3988   general search with dsdb_flags for controls
3989   returns exactly 1 record or an error
3990  */
3991 int dsdb_search_one(struct ldb_context *ldb,
3992                     TALLOC_CTX *mem_ctx,
3993                     struct ldb_message **msg,
3994                     struct ldb_dn *basedn,
3995                     enum ldb_scope scope,
3996                     const char * const *attrs,
3997                     uint32_t dsdb_flags,
3998                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3999 {
4000         int ret;
4001         struct ldb_result *res;
4002         va_list ap;
4003         char *expression = NULL;
4004         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4005
4006         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4007
4008         res = talloc_zero(tmp_ctx, struct ldb_result);
4009         if (!res) {
4010                 talloc_free(tmp_ctx);
4011                 return ldb_oom(ldb);
4012         }
4013
4014         if (exp_fmt) {
4015                 va_start(ap, exp_fmt);
4016                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4017                 va_end(ap);
4018
4019                 if (!expression) {
4020                         talloc_free(tmp_ctx);
4021                         return ldb_oom(ldb);
4022                 }
4023                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4024                                   dsdb_flags, "%s", expression);
4025         } else {
4026                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4027                                   dsdb_flags, NULL);
4028         }
4029
4030         if (ret != LDB_SUCCESS) {
4031                 talloc_free(tmp_ctx);
4032                 return ret;
4033         }
4034
4035         *msg = talloc_steal(mem_ctx, res->msgs[0]);
4036         talloc_free(tmp_ctx);
4037
4038         return LDB_SUCCESS;
4039 }
4040
4041 /* returns back the forest DNS name */
4042 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4043 {
4044         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4045                                                           ldb_get_root_basedn(ldb));
4046         char *p;
4047
4048         if (forest_name == NULL) {
4049                 return NULL;
4050         }
4051
4052         p = strchr(forest_name, '/');
4053         if (p) {
4054                 *p = '\0';
4055         }
4056
4057         return forest_name;
4058 }
4059
4060 /* returns back the default domain DNS name */
4061 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4062 {
4063         const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4064                                                           ldb_get_default_basedn(ldb));
4065         char *p;
4066
4067         if (domain_name == NULL) {
4068                 return NULL;
4069         }
4070
4071         p = strchr(domain_name, '/');
4072         if (p) {
4073                 *p = '\0';
4074         }
4075
4076         return domain_name;
4077 }
4078
4079 /*
4080    validate that an DSA GUID belongs to the specified user sid.
4081    The user SID must be a domain controller account (either RODC or
4082    RWDC)
4083  */
4084 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4085                            const struct GUID *dsa_guid,
4086                            const struct dom_sid *sid)
4087 {
4088         /* strategy:
4089             - find DN of record with the DSA GUID in the
4090               configuration partition (objectGUID)
4091             - remove "NTDS Settings" component from DN
4092             - do a base search on that DN for serverReference with
4093               extended-dn enabled
4094             - extract objectSid from resulting serverReference
4095               attribute
4096             - check this sid matches the sid argument
4097         */
4098         struct ldb_dn *config_dn;
4099         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4100         struct ldb_message *msg;
4101         const char *attrs1[] = { NULL };
4102         const char *attrs2[] = { "serverReference", NULL };
4103         int ret;
4104         struct ldb_dn *dn, *account_dn;
4105         struct dom_sid sid2;
4106         NTSTATUS status;
4107
4108         config_dn = ldb_get_config_basedn(ldb);
4109
4110         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4111                               attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4112         if (ret != LDB_SUCCESS) {
4113                 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4114                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4115                 talloc_free(tmp_ctx);
4116                 return ldb_operr(ldb);
4117         }
4118         dn = msg->dn;
4119
4120         if (!ldb_dn_remove_child_components(dn, 1)) {
4121                 talloc_free(tmp_ctx);
4122                 return ldb_operr(ldb);
4123         }
4124
4125         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4126                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4127                               "(objectClass=server)");
4128         if (ret != LDB_SUCCESS) {
4129                 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4130                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4131                 talloc_free(tmp_ctx);
4132                 return ldb_operr(ldb);
4133         }
4134
4135         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4136         if (account_dn == NULL) {
4137                 DEBUG(1,(__location__ ": Failed to find account_dn for DSA with objectGUID %s, sid %s\n",
4138                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4139                 talloc_free(tmp_ctx);
4140                 return ldb_operr(ldb);
4141         }
4142
4143         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4144         if (!NT_STATUS_IS_OK(status)) {
4145                 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4146                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4147                 talloc_free(tmp_ctx);
4148                 return ldb_operr(ldb);
4149         }
4150
4151         if (!dom_sid_equal(sid, &sid2)) {
4152                 /* someone is trying to spoof another account */
4153                 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4154                          GUID_string(tmp_ctx, dsa_guid),
4155                          dom_sid_string(tmp_ctx, sid),
4156                          dom_sid_string(tmp_ctx, &sid2)));
4157                 talloc_free(tmp_ctx);
4158                 return ldb_operr(ldb);
4159         }
4160
4161         talloc_free(tmp_ctx);
4162         return LDB_SUCCESS;
4163 }
4164
4165 static const char * const secret_attributes[] = {
4166         DSDB_SECRET_ATTRIBUTES,
4167         NULL
4168 };
4169
4170 /*
4171   check if the attribute belongs to the RODC filtered attribute set
4172   Note that attributes that are in the filtered attribute set are the
4173   ones that _are_ always sent to a RODC
4174 */
4175 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4176 {
4177         /* they never get secret attributes */
4178         if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4179                 return false;
4180         }
4181
4182         /* they do get non-secret critical attributes */
4183         if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4184                 return true;
4185         }
4186
4187         /* they do get non-secret attributes marked as being in the FAS  */
4188         if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4189                 return true;
4190         }
4191
4192         /* other attributes are denied */
4193         return false;
4194 }
4195
4196 /* return fsmo role dn and role owner dn for a particular role*/
4197 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4198                                struct ldb_context *ldb,
4199                                uint32_t role,
4200                                struct ldb_dn **fsmo_role_dn,
4201                                struct ldb_dn **role_owner_dn)
4202 {
4203         int ret;
4204         switch (role) {
4205         case DREPL_NAMING_MASTER:
4206                 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4207                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4208                 if (ret != LDB_SUCCESS) {
4209                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4210                                  ldb_errstring(ldb)));
4211                         talloc_free(tmp_ctx);
4212                         return WERR_DS_DRA_INTERNAL_ERROR;
4213                 }
4214                 break;
4215         case DREPL_INFRASTRUCTURE_MASTER:
4216                 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4217                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4218                 if (ret != LDB_SUCCESS) {
4219                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4220                                  ldb_errstring(ldb)));
4221                         talloc_free(tmp_ctx);
4222                         return WERR_DS_DRA_INTERNAL_ERROR;
4223                 }
4224                 break;
4225         case DREPL_RID_MASTER:
4226                 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
4227                 if (ret != LDB_SUCCESS) {
4228                         DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
4229                         talloc_free(tmp_ctx);
4230                         return WERR_DS_DRA_INTERNAL_ERROR;
4231                 }
4232
4233                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4234                 if (ret != LDB_SUCCESS) {
4235                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
4236                                  ldb_errstring(ldb)));
4237                         talloc_free(tmp_ctx);
4238                         return WERR_DS_DRA_INTERNAL_ERROR;
4239                 }
4240                 break;
4241         case DREPL_SCHEMA_MASTER:
4242                 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
4243                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4244                 if (ret != LDB_SUCCESS) {
4245                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4246                                  ldb_errstring(ldb)));
4247                         talloc_free(tmp_ctx);
4248                         return WERR_DS_DRA_INTERNAL_ERROR;
4249                 }
4250                 break;
4251         case DREPL_PDC_MASTER:
4252                 *fsmo_role_dn = ldb_get_default_basedn(ldb);
4253                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4254                 if (ret != LDB_SUCCESS) {
4255                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
4256                                  ldb_errstring(ldb)));
4257                         talloc_free(tmp_ctx);
4258                         return WERR_DS_DRA_INTERNAL_ERROR;
4259                 }
4260                 break;
4261         default:
4262                 return WERR_DS_DRA_INTERNAL_ERROR;
4263         }
4264         return WERR_OK;
4265 }
4266
4267 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
4268                                     TALLOC_CTX *mem_ctx,
4269                                     struct ldb_dn *server_dn)
4270 {
4271         int ldb_ret;
4272         struct ldb_result *res = NULL;
4273         const char * const attrs[] = { "dNSHostName", NULL};
4274
4275         ldb_ret = ldb_search(ldb, mem_ctx, &res,
4276                              server_dn,
4277                              LDB_SCOPE_BASE,
4278                              attrs, NULL);
4279         if (ldb_ret != LDB_SUCCESS) {
4280                 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
4281                           ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
4282                 return NULL;
4283         }
4284
4285         return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
4286 }
4287
4288 /*
4289   returns true if an attribute is in the filter,
4290   false otherwise, provided that attribute value is provided with the expression
4291 */
4292 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
4293                              const char *attr)
4294 {
4295        unsigned int i;
4296        switch (tree->operation) {
4297        case LDB_OP_AND:
4298        case LDB_OP_OR:
4299                for (i=0;i<tree->u.list.num_elements;i++) {
4300                        if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
4301                                                        attr))
4302                                return true;
4303                }
4304                return false;
4305        case LDB_OP_NOT:
4306                return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
4307        case LDB_OP_EQUALITY:
4308        case LDB_OP_GREATER:
4309        case LDB_OP_LESS:
4310        case LDB_OP_APPROX:
4311                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
4312                        return true;
4313                }
4314                return false;
4315        case LDB_OP_SUBSTRING:
4316                if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
4317                        return true;
4318                }
4319                return false;
4320        case LDB_OP_PRESENT:
4321                /* (attrname=*) is not filtered out */
4322                return false;
4323        case LDB_OP_EXTENDED:
4324                if (tree->u.extended.attr &&
4325                    ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
4326                        return true;
4327                }
4328                return false;
4329        }
4330        return false;
4331 }
4332
4333 bool is_attr_in_list(const char * const * attrs, const char *attr)
4334 {
4335         unsigned int i;
4336
4337         for (i = 0; attrs[i]; i++) {
4338                 if (ldb_attr_cmp(attrs[i], attr) == 0)
4339                         return true;
4340         }
4341
4342         return false;
4343 }
4344
4345
4346 /*
4347   map an ldb error code to an approximate NTSTATUS code
4348  */
4349 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
4350 {
4351         switch (err) {
4352         case LDB_SUCCESS:
4353                 return NT_STATUS_OK;
4354
4355         case LDB_ERR_PROTOCOL_ERROR:
4356                 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
4357
4358         case LDB_ERR_TIME_LIMIT_EXCEEDED:
4359                 return NT_STATUS_IO_TIMEOUT;
4360
4361         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
4362                 return NT_STATUS_BUFFER_TOO_SMALL;
4363
4364         case LDB_ERR_COMPARE_FALSE:
4365         case LDB_ERR_COMPARE_TRUE:
4366                 return NT_STATUS_REVISION_MISMATCH;
4367
4368         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
4369                 return NT_STATUS_NOT_SUPPORTED;
4370
4371         case LDB_ERR_STRONG_AUTH_REQUIRED:
4372         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
4373         case LDB_ERR_SASL_BIND_IN_PROGRESS:
4374         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
4375         case LDB_ERR_INVALID_CREDENTIALS:
4376         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
4377         case LDB_ERR_UNWILLING_TO_PERFORM:
4378                 return NT_STATUS_ACCESS_DENIED;
4379
4380         case LDB_ERR_NO_SUCH_OBJECT:
4381                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4382
4383         case LDB_ERR_REFERRAL:
4384         case LDB_ERR_NO_SUCH_ATTRIBUTE:
4385                 return NT_STATUS_NOT_FOUND;
4386
4387         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
4388                 return NT_STATUS_NOT_SUPPORTED;
4389
4390         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
4391                 return NT_STATUS_BUFFER_TOO_SMALL;
4392
4393         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
4394         case LDB_ERR_INAPPROPRIATE_MATCHING:
4395         case LDB_ERR_CONSTRAINT_VIOLATION:
4396         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
4397         case LDB_ERR_INVALID_DN_SYNTAX:
4398         case LDB_ERR_NAMING_VIOLATION:
4399         case LDB_ERR_OBJECT_CLASS_VIOLATION:
4400         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
4401         case LDB_ERR_NOT_ALLOWED_ON_RDN:
4402                 return NT_STATUS_INVALID_PARAMETER;
4403
4404         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
4405         case LDB_ERR_ENTRY_ALREADY_EXISTS:
4406                 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
4407
4408         case LDB_ERR_BUSY:
4409                 return NT_STATUS_NETWORK_BUSY;
4410
4411         case LDB_ERR_ALIAS_PROBLEM:
4412         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
4413         case LDB_ERR_UNAVAILABLE:
4414         case LDB_ERR_LOOP_DETECT:
4415         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
4416         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
4417         case LDB_ERR_OTHER:
4418         case LDB_ERR_OPERATIONS_ERROR:
4419                 break;
4420         }
4421         return NT_STATUS_UNSUCCESSFUL;
4422 }
4423
4424
4425 /*
4426   create a new naming context that will hold a partial replica
4427  */
4428 int dsdb_create_partial_replica_NC(struct ldb_context *ldb,  struct ldb_dn *dn)
4429 {
4430         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4431         struct ldb_message *msg;
4432         int ret;
4433
4434         msg = ldb_msg_new(tmp_ctx);
4435         if (msg == NULL) {
4436                 talloc_free(tmp_ctx);
4437                 return ldb_oom(ldb);
4438         }
4439
4440         msg->dn = dn;
4441         ret = ldb_msg_add_string(msg, "objectClass", "top");
4442         if (ret != LDB_SUCCESS) {
4443                 talloc_free(tmp_ctx);
4444                 return ldb_oom(ldb);
4445         }
4446
4447         /* [MS-DRSR] implies that we should only add the 'top'
4448          * objectclass, but that would cause lots of problems with our
4449          * objectclass code as top is not structural, so we add
4450          * 'domainDNS' as well to keep things sane. We're expecting
4451          * this new NC to be of objectclass domainDNS after
4452          * replication anyway
4453          */
4454         ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
4455         if (ret != LDB_SUCCESS) {
4456                 talloc_free(tmp_ctx);
4457                 return ldb_oom(ldb);
4458         }
4459
4460         ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
4461                               INSTANCE_TYPE_IS_NC_HEAD|
4462                               INSTANCE_TYPE_NC_ABOVE|
4463                               INSTANCE_TYPE_UNINSTANT);
4464         if (ret != LDB_SUCCESS) {
4465                 talloc_free(tmp_ctx);
4466                 return ldb_oom(ldb);
4467         }
4468
4469         ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
4470         if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
4471                 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
4472                          ldb_dn_get_linearized(dn),
4473                          ldb_errstring(ldb), ldb_strerror(ret)));
4474                 talloc_free(tmp_ctx);
4475                 return ret;
4476         }
4477
4478         DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
4479
4480         talloc_free(tmp_ctx);
4481         return LDB_SUCCESS;
4482 }
4483
4484 /**
4485   build a GUID from a string
4486 */
4487 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
4488 {
4489         NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
4490         uint32_t time_low;
4491         uint32_t time_mid, time_hi_and_version;
4492         uint32_t clock_seq[2];
4493         uint32_t node[6];
4494         int i;
4495
4496         if (s == NULL) {
4497                 return NT_STATUS_INVALID_PARAMETER;
4498         }
4499
4500         if (11 == sscanf(s, "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
4501                          &time_low, &time_mid, &time_hi_and_version, 
4502                          &clock_seq[0], &clock_seq[1],
4503                          &node[0], &node[1], &node[2], &node[3], &node[4], &node[5])) {
4504                 status = NT_STATUS_OK;
4505         }
4506
4507         if (!NT_STATUS_IS_OK(status)) {
4508                 return status;
4509         }
4510
4511         guid->time_low = time_low;
4512         guid->time_mid = time_mid;
4513         guid->time_hi_and_version = time_hi_and_version;
4514         guid->clock_seq[0] = clock_seq[0];
4515         guid->clock_seq[1] = clock_seq[1];
4516         for (i=0;i<6;i++) {
4517                 guid->node[i] = node[i];
4518         }
4519
4520         return NT_STATUS_OK;
4521 }
4522
4523 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
4524 {
4525         return talloc_asprintf(mem_ctx, 
4526                                "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
4527                                guid->time_low, guid->time_mid,
4528                                guid->time_hi_and_version,
4529                                guid->clock_seq[0],
4530                                guid->clock_seq[1],
4531                                guid->node[0], guid->node[1],
4532                                guid->node[2], guid->node[3],
4533                                guid->node[4], guid->node[5]);
4534 }