Merge branch 'master' of ctdb into 'master' of samba
[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, TALLOC_CTX *mem_ctx)
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 ldb_dn_copy(mem_ctx, settings_dn);
1256         }
1257
1258         tmp_ctx = talloc_new(mem_ctx);
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(mem_ctx, 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                 SMB_ASSERT(!GUID_all_zero(invocation_id));
1306                 return invocation_id;
1307         }
1308
1309         tmp_ctx = talloc_new(ldb);
1310         if (tmp_ctx == NULL) {
1311                 goto failed;
1312         }
1313
1314         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1315         if (ret) {
1316                 goto failed;
1317         }
1318
1319         if (res->count != 1) {
1320                 goto failed;
1321         }
1322
1323         invocation_id = talloc(tmp_ctx, struct GUID);
1324         if (!invocation_id) {
1325                 goto failed;
1326         }
1327
1328         *invocation_id = samdb_result_guid(res->msgs[0], "invocationId");
1329         if (GUID_all_zero(invocation_id)) {
1330                 if (ldb_msg_find_ldb_val(res->msgs[0], "invocationId")) {
1331                         DEBUG(0, ("Failed to find our own NTDS Settings invocationId in the ldb!\n"));  
1332                 } else {
1333                         DEBUG(0, ("Failed to find parse own NTDS Settings invocationId from the ldb!\n"));
1334                 }
1335                 goto failed;
1336         }
1337
1338         /* cache the domain_sid in the ldb */
1339         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id) != LDB_SUCCESS) {
1340                 goto failed;
1341         }
1342
1343         talloc_steal(ldb, invocation_id);
1344         talloc_free(tmp_ctx);
1345
1346         return invocation_id;
1347
1348 failed:
1349         DEBUG(1,("Failed to find our own NTDS Settings invocationId in the ldb!\n"));
1350         talloc_free(tmp_ctx);
1351         return NULL;
1352 }
1353
1354 bool samdb_set_ntds_invocation_id(struct ldb_context *ldb, const struct GUID *invocation_id_in)
1355 {
1356         TALLOC_CTX *tmp_ctx;
1357         struct GUID *invocation_id_new;
1358         struct GUID *invocation_id_old;
1359
1360         /* see if we have a cached copy */
1361         invocation_id_old = (struct GUID *)ldb_get_opaque(ldb, 
1362                                                          "cache.invocation_id");
1363
1364         tmp_ctx = talloc_new(ldb);
1365         if (tmp_ctx == NULL) {
1366                 goto failed;
1367         }
1368
1369         invocation_id_new = talloc(tmp_ctx, struct GUID);
1370         if (!invocation_id_new) {
1371                 goto failed;
1372         }
1373
1374         SMB_ASSERT(!GUID_all_zero(invocation_id_in));
1375         *invocation_id_new = *invocation_id_in;
1376
1377         /* cache the domain_sid in the ldb */
1378         if (ldb_set_opaque(ldb, "cache.invocation_id", invocation_id_new) != LDB_SUCCESS) {
1379                 goto failed;
1380         }
1381
1382         talloc_steal(ldb, invocation_id_new);
1383         talloc_free(tmp_ctx);
1384         talloc_free(invocation_id_old);
1385
1386         return true;
1387
1388 failed:
1389         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1390         talloc_free(tmp_ctx);
1391         return false;
1392 }
1393
1394 /*
1395   work out the ntds settings objectGUID for the current open ldb
1396 */
1397 const struct GUID *samdb_ntds_objectGUID(struct ldb_context *ldb)
1398 {
1399         TALLOC_CTX *tmp_ctx;
1400         const char *attrs[] = { "objectGUID", NULL };
1401         int ret;
1402         struct ldb_result *res;
1403         struct GUID *ntds_guid;
1404
1405         /* see if we have a cached copy */
1406         ntds_guid = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1407         if (ntds_guid) {
1408                 return ntds_guid;
1409         }
1410
1411         tmp_ctx = talloc_new(ldb);
1412         if (tmp_ctx == NULL) {
1413                 goto failed;
1414         }
1415
1416         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
1417         if (ret) {
1418                 goto failed;
1419         }
1420
1421         if (res->count != 1) {
1422                 goto failed;
1423         }
1424
1425         ntds_guid = talloc(tmp_ctx, struct GUID);
1426         if (!ntds_guid) {
1427                 goto failed;
1428         }
1429
1430         *ntds_guid = samdb_result_guid(res->msgs[0], "objectGUID");
1431
1432         /* cache the domain_sid in the ldb */
1433         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid) != LDB_SUCCESS) {
1434                 goto failed;
1435         }
1436
1437         talloc_steal(ldb, ntds_guid);
1438         talloc_free(tmp_ctx);
1439
1440         return ntds_guid;
1441
1442 failed:
1443         DEBUG(1,("Failed to find our own NTDS Settings objectGUID in the ldb!\n"));
1444         talloc_free(tmp_ctx);
1445         return NULL;
1446 }
1447
1448 bool samdb_set_ntds_objectGUID(struct ldb_context *ldb, const struct GUID *ntds_guid_in)
1449 {
1450         TALLOC_CTX *tmp_ctx;
1451         struct GUID *ntds_guid_new;
1452         struct GUID *ntds_guid_old;
1453
1454         /* see if we have a cached copy */
1455         ntds_guid_old = (struct GUID *)ldb_get_opaque(ldb, "cache.ntds_guid");
1456
1457         tmp_ctx = talloc_new(ldb);
1458         if (tmp_ctx == NULL) {
1459                 goto failed;
1460         }
1461
1462         ntds_guid_new = talloc(tmp_ctx, struct GUID);
1463         if (!ntds_guid_new) {
1464                 goto failed;
1465         }
1466
1467         *ntds_guid_new = *ntds_guid_in;
1468
1469         /* cache the domain_sid in the ldb */
1470         if (ldb_set_opaque(ldb, "cache.ntds_guid", ntds_guid_new) != LDB_SUCCESS) {
1471                 goto failed;
1472         }
1473
1474         talloc_steal(ldb, ntds_guid_new);
1475         talloc_free(tmp_ctx);
1476         talloc_free(ntds_guid_old);
1477
1478         return true;
1479
1480 failed:
1481         DEBUG(1,("Failed to set our own cached invocationId in the ldb!\n"));
1482         talloc_free(tmp_ctx);
1483         return false;
1484 }
1485
1486 /*
1487   work out the server dn for the current open ldb
1488 */
1489 struct ldb_dn *samdb_server_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1490 {
1491         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
1492         struct ldb_dn *dn;
1493         if (!tmp_ctx) {
1494                 return NULL;
1495         }
1496         dn = ldb_dn_get_parent(mem_ctx, samdb_ntds_settings_dn(ldb, tmp_ctx));
1497         talloc_free(tmp_ctx);
1498         return dn;
1499         
1500 }
1501
1502 /*
1503   work out the server dn for the current open ldb
1504 */
1505 struct ldb_dn *samdb_server_site_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1506 {
1507         struct ldb_dn *server_dn;
1508         struct ldb_dn *servers_dn;
1509         struct ldb_dn *server_site_dn;
1510
1511         /* TODO: there must be a saner way to do this!! */
1512         server_dn = samdb_server_dn(ldb, mem_ctx);
1513         if (!server_dn) return NULL;
1514
1515         servers_dn = ldb_dn_get_parent(mem_ctx, server_dn);
1516         talloc_free(server_dn);
1517         if (!servers_dn) return NULL;
1518
1519         server_site_dn = ldb_dn_get_parent(mem_ctx, servers_dn);
1520         talloc_free(servers_dn);
1521
1522         return server_site_dn;
1523 }
1524
1525 /*
1526   find the site name from a computers DN record
1527  */
1528 int samdb_find_site_for_computer(struct ldb_context *ldb,
1529                                  TALLOC_CTX *mem_ctx, struct ldb_dn *computer_dn,
1530                                  const char **site_name)
1531 {
1532         int ret;
1533         struct ldb_dn *dn;
1534         const struct ldb_val *rdn_val;
1535
1536         *site_name = NULL;
1537
1538         ret = samdb_reference_dn(ldb, mem_ctx, computer_dn, "serverReferenceBL", &dn);
1539         if (ret != LDB_SUCCESS) {
1540                 return ret;
1541         }
1542
1543         if (!ldb_dn_remove_child_components(dn, 2)) {
1544                 talloc_free(dn);
1545                 return LDB_ERR_INVALID_DN_SYNTAX;
1546         }
1547
1548         rdn_val = ldb_dn_get_rdn_val(dn);
1549         if (rdn_val == NULL) {
1550                 return LDB_ERR_OPERATIONS_ERROR;
1551         }
1552
1553         (*site_name) = talloc_strndup(mem_ctx, (const char *)rdn_val->data, rdn_val->length);
1554         talloc_free(dn);
1555         if (!*site_name) {
1556                 return LDB_ERR_OPERATIONS_ERROR;
1557         }
1558         return LDB_SUCCESS;
1559 }
1560
1561 /*
1562   find the NTDS GUID from a computers DN record
1563  */
1564 int samdb_find_ntdsguid_for_computer(struct ldb_context *ldb, struct ldb_dn *computer_dn,
1565                                      struct GUID *ntds_guid)
1566 {
1567         int ret;
1568         struct ldb_dn *dn;
1569
1570         *ntds_guid = GUID_zero();
1571
1572         ret = samdb_reference_dn(ldb, ldb, computer_dn, "serverReferenceBL", &dn);
1573         if (ret != LDB_SUCCESS) {
1574                 return ret;
1575         }
1576
1577         if (!ldb_dn_add_child_fmt(dn, "CN=NTDS Settings")) {
1578                 talloc_free(dn);
1579                 return LDB_ERR_OPERATIONS_ERROR;
1580         }
1581
1582         ret = dsdb_find_guid_by_dn(ldb, dn, ntds_guid);
1583         talloc_free(dn);
1584         return ret;
1585 }
1586
1587 /*
1588   find a 'reference' DN that points at another object
1589   (eg. serverReference, rIDManagerReference etc)
1590  */
1591 int samdb_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *base,
1592                        const char *attribute, struct ldb_dn **dn)
1593 {
1594         const char *attrs[2];
1595         struct ldb_result *res;
1596         int ret;
1597
1598         attrs[0] = attribute;
1599         attrs[1] = NULL;
1600
1601         ret = dsdb_search(ldb, mem_ctx, &res, base, LDB_SCOPE_BASE, attrs, DSDB_SEARCH_ONE_ONLY|DSDB_SEARCH_SHOW_EXTENDED_DN, NULL);
1602         if (ret != LDB_SUCCESS) {
1603                 ldb_asprintf_errstring(ldb, "Cannot find DN %s to get attribute %s for reference dn: %s",
1604                                        ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb));
1605                 return ret;
1606         }
1607
1608         *dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx, res->msgs[0], attribute);
1609         if (!*dn) {
1610                 if (!ldb_msg_find_element(res->msgs[0], attribute)) {
1611                         ldb_asprintf_errstring(ldb, "Cannot find attribute %s of %s to calculate reference dn", attribute,
1612                                                ldb_dn_get_linearized(base));
1613                 } else {
1614                         ldb_asprintf_errstring(ldb, "Cannot interpret attribute %s of %s as a dn", attribute,
1615                                                ldb_dn_get_linearized(base));
1616                 }
1617                 talloc_free(res);
1618                 return LDB_ERR_NO_SUCH_ATTRIBUTE;
1619         }
1620
1621         talloc_free(res);
1622         return LDB_SUCCESS;
1623 }
1624
1625 /*
1626   find if a DN (must have GUID component!) is our ntdsDsa
1627  */
1628 int samdb_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *dn, bool *is_ntdsa)
1629 {
1630         NTSTATUS status;
1631         struct GUID dn_guid;
1632         const struct GUID *our_ntds_guid;
1633         status = dsdb_get_extended_dn_guid(dn, &dn_guid, "GUID");
1634         if (!NT_STATUS_IS_OK(status)) {
1635                 return LDB_ERR_OPERATIONS_ERROR;
1636         }
1637
1638         our_ntds_guid = samdb_ntds_objectGUID(ldb);
1639         if (!our_ntds_guid) {
1640                 DEBUG(0, ("Failed to find our NTDS Settings GUID for comparison with %s - %s\n", ldb_dn_get_linearized(dn), ldb_errstring(ldb)));
1641                 return LDB_ERR_OPERATIONS_ERROR;
1642         }
1643
1644         *is_ntdsa = GUID_equal(&dn_guid, our_ntds_guid);
1645         return LDB_SUCCESS;
1646 }
1647
1648 /*
1649   find a 'reference' DN that points at another object and indicate if it is our ntdsDsa
1650  */
1651 int samdb_reference_dn_is_our_ntdsa(struct ldb_context *ldb, struct ldb_dn *base,
1652                                     const char *attribute, bool *is_ntdsa)
1653 {
1654         int ret;
1655         struct ldb_dn *referenced_dn;
1656         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
1657         if (tmp_ctx == NULL) {
1658                 return LDB_ERR_OPERATIONS_ERROR;
1659         }
1660         ret = samdb_reference_dn(ldb, tmp_ctx, base, attribute, &referenced_dn);
1661         if (ret != LDB_SUCCESS) {
1662                 DEBUG(0, ("Failed to find object %s for attribute %s - %s\n", ldb_dn_get_linearized(base), attribute, ldb_errstring(ldb)));
1663                 return ret;
1664         }
1665
1666         ret = samdb_dn_is_our_ntdsa(ldb, referenced_dn, is_ntdsa);
1667         
1668         talloc_free(tmp_ctx);
1669         return ret;
1670 }
1671
1672 /*
1673   find our machine account via the serverReference attribute in the
1674   server DN
1675  */
1676 int samdb_server_reference_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1677 {
1678         struct ldb_dn *server_dn;
1679         int ret;
1680
1681         server_dn = samdb_server_dn(ldb, mem_ctx);
1682         if (server_dn == NULL) {
1683                 return LDB_ERR_NO_SUCH_OBJECT;
1684         }
1685
1686         ret = samdb_reference_dn(ldb, mem_ctx, server_dn, "serverReference", dn);
1687         talloc_free(server_dn);
1688
1689         return ret;
1690 }
1691
1692 /*
1693   find the RID Manager$ DN via the rIDManagerReference attribute in the
1694   base DN
1695  */
1696 int samdb_rid_manager_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1697 {
1698         return samdb_reference_dn(ldb, mem_ctx, ldb_get_default_basedn(ldb),
1699                                   "rIDManagerReference", dn);
1700 }
1701
1702 /*
1703   find the RID Set DN via the rIDSetReferences attribute in our
1704   machine account DN
1705  */
1706 int samdb_rid_set_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn **dn)
1707 {
1708         struct ldb_dn *server_ref_dn;
1709         int ret;
1710
1711         ret = samdb_server_reference_dn(ldb, mem_ctx, &server_ref_dn);
1712         if (ret != LDB_SUCCESS) {
1713                 return ret;
1714         }
1715         ret = samdb_reference_dn(ldb, mem_ctx, server_ref_dn, "rIDSetReferences", dn);
1716         talloc_free(server_ref_dn);
1717         return ret;
1718 }
1719
1720 const char *samdb_server_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
1721 {
1722         const struct ldb_val *val = ldb_dn_get_rdn_val(samdb_server_site_dn(ldb,
1723                                                                             mem_ctx));
1724
1725         if (val == NULL) {
1726                 return NULL;
1727         }
1728
1729         return (const char *) val->data;
1730 }
1731
1732 /*
1733  * Finds the client site by using the client's IP address.
1734  * The "subnet_name" returns the name of the subnet if parameter != NULL
1735  */
1736 const char *samdb_client_site_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1737                                    const char *ip_address, char **subnet_name)
1738 {
1739         const char *attrs[] = { "cn", "siteObject", NULL };
1740         struct ldb_dn *sites_container_dn, *subnets_dn, *sites_dn;
1741         struct ldb_result *res;
1742         const struct ldb_val *val;
1743         const char *site_name = NULL, *l_subnet_name = NULL;
1744         const char *allow_list[2] = { NULL, NULL };
1745         unsigned int i, count;
1746         int cnt, ret;
1747
1748         /*
1749          * if we don't have a client ip e.g. ncalrpc
1750          * the server site is the client site
1751          */
1752         if (ip_address == NULL) {
1753                 return samdb_server_site_name(ldb, mem_ctx);
1754         }
1755
1756         sites_container_dn = samdb_sites_dn(ldb, mem_ctx);
1757         if (sites_container_dn == NULL) {
1758                 return NULL;
1759         }
1760
1761         subnets_dn = ldb_dn_copy(mem_ctx, sites_container_dn);
1762         if ( ! ldb_dn_add_child_fmt(subnets_dn, "CN=Subnets")) {
1763                 talloc_free(sites_container_dn);
1764                 talloc_free(subnets_dn);
1765                 return NULL;
1766         }
1767
1768         ret = ldb_search(ldb, mem_ctx, &res, subnets_dn, LDB_SCOPE_ONELEVEL,
1769                          attrs, NULL);
1770         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1771                 count = 0;
1772         } else if (ret != LDB_SUCCESS) {
1773                 talloc_free(sites_container_dn);
1774                 talloc_free(subnets_dn);
1775                 return NULL;
1776         } else {
1777                 count = res->count;
1778         }
1779
1780         for (i = 0; i < count; i++) {
1781                 l_subnet_name = ldb_msg_find_attr_as_string(res->msgs[i], "cn",
1782                                                             NULL);
1783
1784                 allow_list[0] = l_subnet_name;
1785
1786                 if (socket_allow_access(mem_ctx, NULL, allow_list, "", ip_address)) {
1787                         sites_dn = ldb_msg_find_attr_as_dn(ldb, mem_ctx,
1788                                                            res->msgs[i],
1789                                                            "siteObject");
1790                         if (sites_dn == NULL) {
1791                                 /* No reference, maybe another subnet matches */
1792                                 continue;
1793                         }
1794
1795                         /* "val" cannot be NULL here since "sites_dn" != NULL */
1796                         val = ldb_dn_get_rdn_val(sites_dn);
1797                         site_name = talloc_strdup(mem_ctx,
1798                                                   (const char *) val->data);
1799
1800                         talloc_free(sites_dn);
1801
1802                         break;
1803                 }
1804         }
1805
1806         if (site_name == NULL) {
1807                 /* This is the Windows Server fallback rule: when no subnet
1808                  * exists and we have only one site available then use it (it
1809                  * is for sure the same as our server site). If more sites do
1810                  * exist then we don't know which one to use and set the site
1811                  * name to "". */
1812                 cnt = samdb_search_count(ldb, mem_ctx, sites_container_dn,
1813                                          "(objectClass=site)");
1814                 if (cnt == 1) {
1815                         site_name = samdb_server_site_name(ldb, mem_ctx);
1816                 } else {
1817                         site_name = talloc_strdup(mem_ctx, "");
1818                 }
1819                 l_subnet_name = NULL;
1820         }
1821
1822         if (subnet_name != NULL) {
1823                 *subnet_name = talloc_strdup(mem_ctx, l_subnet_name);
1824         }
1825
1826         talloc_free(sites_container_dn);
1827         talloc_free(subnets_dn);
1828         talloc_free(res);
1829
1830         return site_name;
1831 }
1832
1833 /*
1834   work out if we are the PDC for the domain of the current open ldb
1835 */
1836 bool samdb_is_pdc(struct ldb_context *ldb)
1837 {
1838         int ret;
1839         bool is_pdc;
1840
1841         ret = samdb_reference_dn_is_our_ntdsa(ldb, ldb_get_default_basedn(ldb), "fsmoRoleOwner", 
1842                                               &is_pdc);
1843         if (ret != LDB_SUCCESS) {
1844                 DEBUG(1,("Failed to find if we are the PDC for this ldb: Searching for fSMORoleOwner in %s failed: %s\n", 
1845                          ldb_dn_get_linearized(ldb_get_default_basedn(ldb)), 
1846                          ldb_errstring(ldb)));
1847                 return false;
1848         }
1849
1850         return is_pdc;
1851 }
1852
1853 /*
1854   work out if we are a Global Catalog server for the domain of the current open ldb
1855 */
1856 bool samdb_is_gc(struct ldb_context *ldb)
1857 {
1858         uint32_t options;
1859         if (samdb_ntds_options(ldb, &options) != LDB_SUCCESS) {
1860                 return false;
1861         }
1862         return (options & DS_NTDSDSA_OPT_IS_GC) != 0;
1863 }
1864
1865 /* Find a domain object in the parents of a particular DN.  */
1866 int samdb_search_for_parent_domain(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
1867                                    struct ldb_dn **parent_dn, const char **errstring)
1868 {
1869         TALLOC_CTX *local_ctx;
1870         struct ldb_dn *sdn = dn;
1871         struct ldb_result *res = NULL;
1872         int ret = LDB_SUCCESS;
1873         const char *attrs[] = { NULL };
1874
1875         local_ctx = talloc_new(mem_ctx);
1876         if (local_ctx == NULL) return ldb_oom(ldb);
1877
1878         while ((sdn = ldb_dn_get_parent(local_ctx, sdn))) {
1879                 ret = ldb_search(ldb, local_ctx, &res, sdn, LDB_SCOPE_BASE, attrs,
1880                                  "(|(objectClass=domain)(objectClass=builtinDomain))");
1881                 if (ret == LDB_SUCCESS) {
1882                         if (res->count == 1) {
1883                                 break;
1884                         }
1885                 } else {
1886                         break;
1887                 }
1888         }
1889
1890         if (ret != LDB_SUCCESS) {
1891                 *errstring = talloc_asprintf(mem_ctx, "Error searching for parent domain of %s, failed searching for %s: %s",
1892                                              ldb_dn_get_linearized(dn),
1893                                              ldb_dn_get_linearized(sdn),
1894                                              ldb_errstring(ldb));
1895                 talloc_free(local_ctx);
1896                 return ret;
1897         }
1898         if (res->count != 1) {
1899                 *errstring = talloc_asprintf(mem_ctx, "Invalid dn (%s), not child of a domain object",
1900                                              ldb_dn_get_linearized(dn));
1901                 DEBUG(0,(__location__ ": %s\n", *errstring));
1902                 talloc_free(local_ctx);
1903                 return LDB_ERR_CONSTRAINT_VIOLATION;
1904         }
1905
1906         *parent_dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
1907         talloc_free(local_ctx);
1908         return ret;
1909 }
1910
1911
1912 /*
1913  * Performs checks on a user password (plaintext UNIX format - attribute
1914  * "password"). The remaining parameters have to be extracted from the domain
1915  * object in the AD.
1916  *
1917  * Result codes from "enum samr_ValidationStatus" (consider "samr.idl")
1918  */
1919 enum samr_ValidationStatus samdb_check_password(const DATA_BLOB *utf8_blob,
1920                                                 const uint32_t pwdProperties,
1921                                                 const uint32_t minPwdLength)
1922 {
1923         const char *utf8_pw = (const char *)utf8_blob->data;
1924         size_t utf8_len = strlen_m(utf8_pw);
1925
1926         /* checks if the "minPwdLength" property is satisfied */
1927         if (minPwdLength > utf8_len) {
1928                 return SAMR_VALIDATION_STATUS_PWD_TOO_SHORT;
1929         }
1930
1931         /* checks the password complexity */
1932         if (!(pwdProperties & DOMAIN_PASSWORD_COMPLEX)) {
1933                 return SAMR_VALIDATION_STATUS_SUCCESS;
1934         }
1935
1936         if (utf8_len == 0) {
1937                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1938         }
1939
1940         if (!check_password_quality(utf8_pw)) {
1941                 return SAMR_VALIDATION_STATUS_NOT_COMPLEX_ENOUGH;
1942         }
1943
1944         return SAMR_VALIDATION_STATUS_SUCCESS;
1945 }
1946
1947 /*
1948  * Callback for "samdb_set_password" password change
1949  */
1950 int samdb_set_password_callback(struct ldb_request *req, struct ldb_reply *ares)
1951 {
1952         int ret;
1953
1954         if (!ares) {
1955                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1956         }
1957
1958         if (ares->error != LDB_SUCCESS) {
1959                 ret = ares->error;
1960                 req->context = talloc_steal(req,
1961                                             ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1962                 talloc_free(ares);
1963                 return ldb_request_done(req, ret);
1964         }
1965
1966         if (ares->type != LDB_REPLY_DONE) {
1967                 talloc_free(ares);
1968                 return ldb_request_done(req, LDB_ERR_OPERATIONS_ERROR);
1969         }
1970
1971         req->context = talloc_steal(req,
1972                                     ldb_reply_get_control(ares, DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID));
1973         talloc_free(ares);
1974         return ldb_request_done(req, LDB_SUCCESS);
1975 }
1976
1977 /*
1978  * Sets the user password using plaintext UTF16 (attribute "new_password") or
1979  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
1980  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
1981  * user change or not. The "rejectReason" gives some more information if the
1982  * change failed.
1983  *
1984  * Results: NT_STATUS_OK, NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
1985  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION
1986  */
1987 NTSTATUS samdb_set_password(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
1988                             struct ldb_dn *user_dn, struct ldb_dn *domain_dn,
1989                             const DATA_BLOB *new_password,
1990                             const struct samr_Password *lmNewHash,
1991                             const struct samr_Password *ntNewHash,
1992                             const struct samr_Password *lmOldHash,
1993                             const struct samr_Password *ntOldHash,
1994                             enum samPwdChangeReason *reject_reason,
1995                             struct samr_DomInfo1 **_dominfo)
1996 {
1997         struct ldb_message *msg;
1998         struct ldb_message_element *el;
1999         struct ldb_request *req;
2000         struct dsdb_control_password_change_status *pwd_stat = NULL;
2001         int ret;
2002         bool hash_values = false;
2003         NTSTATUS status = NT_STATUS_OK;
2004
2005 #define CHECK_RET(x) \
2006         if (x != LDB_SUCCESS) { \
2007                 talloc_free(msg); \
2008                 return NT_STATUS_NO_MEMORY; \
2009         }
2010
2011         msg = ldb_msg_new(mem_ctx);
2012         if (msg == NULL) {
2013                 return NT_STATUS_NO_MEMORY;
2014         }
2015         msg->dn = user_dn;
2016         if ((new_password != NULL)
2017                         && ((lmNewHash == NULL) && (ntNewHash == NULL))) {
2018                 /* we have the password as plaintext UTF16 */
2019                 CHECK_RET(ldb_msg_add_value(msg, "clearTextPassword",
2020                                             new_password, NULL));
2021                 el = ldb_msg_find_element(msg, "clearTextPassword");
2022                 el->flags = LDB_FLAG_MOD_REPLACE;
2023         } else if ((new_password == NULL)
2024                         && ((lmNewHash != NULL) || (ntNewHash != NULL))) {
2025                 /* we have a password as LM and/or NT hash */
2026                 if (lmNewHash != NULL) {
2027                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2028                                 "dBCSPwd", lmNewHash));
2029                         el = ldb_msg_find_element(msg, "dBCSPwd");
2030                         el->flags = LDB_FLAG_MOD_REPLACE;
2031                 }
2032                 if (ntNewHash != NULL) {
2033                         CHECK_RET(samdb_msg_add_hash(ldb, mem_ctx, msg,
2034                                 "unicodePwd", ntNewHash));
2035                         el = ldb_msg_find_element(msg, "unicodePwd");
2036                         el->flags = LDB_FLAG_MOD_REPLACE;
2037                 }
2038                 hash_values = true;
2039         } else {
2040                 /* the password wasn't specified correctly */
2041                 talloc_free(msg);
2042                 return NT_STATUS_INVALID_PARAMETER;
2043         }
2044
2045         /* build modify request */
2046         ret = ldb_build_mod_req(&req, ldb, mem_ctx, msg, NULL, NULL,
2047                                 samdb_set_password_callback, NULL);
2048         if (ret != LDB_SUCCESS) {
2049                 talloc_free(msg);
2050                 return NT_STATUS_NO_MEMORY;
2051         }
2052
2053         /* A password change operation */
2054         if ((ntOldHash != NULL) || (lmOldHash != NULL)) {
2055                 struct dsdb_control_password_change *change;
2056
2057                 change = talloc(req, struct dsdb_control_password_change);
2058                 if (change == NULL) {
2059                         talloc_free(req);
2060                         talloc_free(msg);
2061                         return NT_STATUS_NO_MEMORY;
2062                 }
2063
2064                 change->old_nt_pwd_hash = ntOldHash;
2065                 change->old_lm_pwd_hash = lmOldHash;
2066
2067                 ret = ldb_request_add_control(req,
2068                                               DSDB_CONTROL_PASSWORD_CHANGE_OID,
2069                                               true, change);
2070                 if (ret != LDB_SUCCESS) {
2071                         talloc_free(req);
2072                         talloc_free(msg);
2073                         return NT_STATUS_NO_MEMORY;
2074                 }
2075         }
2076         if (hash_values) {
2077                 ret = ldb_request_add_control(req,
2078                                               DSDB_CONTROL_PASSWORD_HASH_VALUES_OID,
2079                                               true, NULL);
2080                 if (ret != LDB_SUCCESS) {
2081                         talloc_free(req);
2082                         talloc_free(msg);
2083                         return NT_STATUS_NO_MEMORY;
2084                 }
2085         }
2086         ret = ldb_request_add_control(req,
2087                                       DSDB_CONTROL_PASSWORD_CHANGE_STATUS_OID,
2088                                       true, NULL);
2089         if (ret != LDB_SUCCESS) {
2090                 talloc_free(req);
2091                 talloc_free(msg);
2092                 return NT_STATUS_NO_MEMORY;
2093         }
2094
2095         ret = dsdb_autotransaction_request(ldb, req);
2096
2097         if (req->context != NULL) {
2098                 pwd_stat = talloc_steal(mem_ctx,
2099                                         ((struct ldb_control *)req->context)->data);
2100         }
2101
2102         talloc_free(req);
2103         talloc_free(msg);
2104
2105         /* Sets the domain info (if requested) */
2106         if (_dominfo != NULL) {
2107                 struct samr_DomInfo1 *dominfo;
2108
2109                 dominfo = talloc_zero(mem_ctx, struct samr_DomInfo1);
2110                 if (dominfo == NULL) {
2111                         return NT_STATUS_NO_MEMORY;
2112                 }
2113
2114                 if (pwd_stat != NULL) {
2115                         dominfo->min_password_length     = pwd_stat->domain_data.minPwdLength;
2116                         dominfo->password_properties     = pwd_stat->domain_data.pwdProperties;
2117                         dominfo->password_history_length = pwd_stat->domain_data.pwdHistoryLength;
2118                         dominfo->max_password_age        = pwd_stat->domain_data.maxPwdAge;
2119                         dominfo->min_password_age        = pwd_stat->domain_data.minPwdAge;
2120                 }
2121
2122                 *_dominfo = dominfo;
2123         }
2124
2125         if (reject_reason != NULL) {
2126                 if (pwd_stat != NULL) {
2127                         *reject_reason = pwd_stat->reject_reason;
2128                 } else {
2129                         *reject_reason = SAM_PWD_CHANGE_NO_ERROR;
2130                 }
2131         }
2132
2133         if (pwd_stat != NULL) {
2134                 talloc_free(pwd_stat);
2135         }
2136
2137         if (ret == LDB_ERR_CONSTRAINT_VIOLATION) {
2138                 const char *errmsg = ldb_errstring(ldb);
2139                 char *endptr = NULL;
2140                 WERROR werr = WERR_GENERAL_FAILURE;
2141                 status = NT_STATUS_UNSUCCESSFUL;
2142                 if (errmsg != NULL) {
2143                         werr = W_ERROR(strtol(errmsg, &endptr, 16));
2144                 }
2145                 if (endptr != errmsg) {
2146                         if (W_ERROR_EQUAL(werr, WERR_INVALID_PASSWORD)) {
2147                                 status = NT_STATUS_WRONG_PASSWORD;
2148                         }
2149                         if (W_ERROR_EQUAL(werr, WERR_PASSWORD_RESTRICTION)) {
2150                                 status = NT_STATUS_PASSWORD_RESTRICTION;
2151                         }
2152                 }
2153         } else if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2154                 /* don't let the caller know if an account doesn't exist */
2155                 status = NT_STATUS_WRONG_PASSWORD;
2156         } else if (ret != LDB_SUCCESS) {
2157                 status = NT_STATUS_UNSUCCESSFUL;
2158         }
2159
2160         return status;
2161 }
2162
2163 /*
2164  * Sets the user password using plaintext UTF16 (attribute "new_password") or
2165  * LM (attribute "lmNewHash") or NT (attribute "ntNewHash") hash. Also pass
2166  * the old LM and/or NT hash (attributes "lmOldHash"/"ntOldHash") if it is a
2167  * user change or not. The "rejectReason" gives some more information if the
2168  * change failed.
2169  *
2170  * This wrapper function for "samdb_set_password" takes a SID as input rather
2171  * than a user DN.
2172  *
2173  * This call encapsulates a new LDB transaction for changing the password;
2174  * therefore the user hasn't to start a new one.
2175  *
2176  * Results: NT_STATUS_OK, NT_STATUS_INTERNAL_DB_CORRUPTION,
2177  *   NT_STATUS_INVALID_PARAMETER, NT_STATUS_UNSUCCESSFUL,
2178  *   NT_STATUS_WRONG_PASSWORD, NT_STATUS_PASSWORD_RESTRICTION,
2179  *   NT_STATUS_TRANSACTION_ABORTED, NT_STATUS_NO_SUCH_USER
2180  */
2181 NTSTATUS samdb_set_password_sid(struct ldb_context *ldb, TALLOC_CTX *mem_ctx,
2182                                 const struct dom_sid *user_sid,
2183                                 const DATA_BLOB *new_password,
2184                                 const struct samr_Password *lmNewHash,
2185                                 const struct samr_Password *ntNewHash,
2186                                 const struct samr_Password *lmOldHash,
2187                                 const struct samr_Password *ntOldHash,
2188                                 enum samPwdChangeReason *reject_reason,
2189                                 struct samr_DomInfo1 **_dominfo) 
2190 {
2191         NTSTATUS nt_status;
2192         struct ldb_dn *user_dn;
2193         int ret;
2194
2195         ret = ldb_transaction_start(ldb);
2196         if (ret != LDB_SUCCESS) {
2197                 DEBUG(1, ("Failed to start transaction: %s\n", ldb_errstring(ldb)));
2198                 return NT_STATUS_TRANSACTION_ABORTED;
2199         }
2200
2201         user_dn = samdb_search_dn(ldb, mem_ctx, NULL,
2202                                   "(&(objectSid=%s)(objectClass=user))", 
2203                                   ldap_encode_ndr_dom_sid(mem_ctx, user_sid));
2204         if (!user_dn) {
2205                 ldb_transaction_cancel(ldb);
2206                 DEBUG(3, ("samdb_set_password_sid: SID %s not found in samdb, returning NO_SUCH_USER\n",
2207                           dom_sid_string(mem_ctx, user_sid)));
2208                 return NT_STATUS_NO_SUCH_USER;
2209         }
2210
2211         nt_status = samdb_set_password(ldb, mem_ctx,
2212                                        user_dn, NULL,
2213                                        new_password,
2214                                        lmNewHash, ntNewHash,
2215                                        lmOldHash, ntOldHash,
2216                                        reject_reason, _dominfo);
2217         if (!NT_STATUS_IS_OK(nt_status)) {
2218                 ldb_transaction_cancel(ldb);
2219                 talloc_free(user_dn);
2220                 return nt_status;
2221         }
2222
2223         ret = ldb_transaction_commit(ldb);
2224         if (ret != LDB_SUCCESS) {
2225                 DEBUG(0,("Failed to commit transaction to change password on %s: %s\n",
2226                          ldb_dn_get_linearized(user_dn),
2227                          ldb_errstring(ldb)));
2228                 talloc_free(user_dn);
2229                 return NT_STATUS_TRANSACTION_ABORTED;
2230         }
2231
2232         talloc_free(user_dn);
2233         return NT_STATUS_OK;
2234 }
2235
2236
2237 NTSTATUS samdb_create_foreign_security_principal(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, 
2238                                                  struct dom_sid *sid, struct ldb_dn **ret_dn) 
2239 {
2240         struct ldb_message *msg;
2241         struct ldb_dn *basedn;
2242         char *sidstr;
2243         int ret;
2244
2245         sidstr = dom_sid_string(mem_ctx, sid);
2246         NT_STATUS_HAVE_NO_MEMORY(sidstr);
2247
2248         /* We might have to create a ForeignSecurityPrincipal, even if this user
2249          * is in our own domain */
2250
2251         msg = ldb_msg_new(sidstr);
2252         if (msg == NULL) {
2253                 talloc_free(sidstr);
2254                 return NT_STATUS_NO_MEMORY;
2255         }
2256
2257         ret = dsdb_wellknown_dn(sam_ctx, sidstr,
2258                                 ldb_get_default_basedn(sam_ctx),
2259                                 DS_GUID_FOREIGNSECURITYPRINCIPALS_CONTAINER,
2260                                 &basedn);
2261         if (ret != LDB_SUCCESS) {
2262                 DEBUG(0, ("Failed to find DN for "
2263                           "ForeignSecurityPrincipal container - %s\n", ldb_errstring(sam_ctx)));
2264                 talloc_free(sidstr);
2265                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2266         }
2267
2268         /* add core elements to the ldb_message for the alias */
2269         msg->dn = basedn;
2270         if ( ! ldb_dn_add_child_fmt(msg->dn, "CN=%s", sidstr)) {
2271                 talloc_free(sidstr);
2272                 return NT_STATUS_NO_MEMORY;
2273         }
2274
2275         ret = ldb_msg_add_string(msg, "objectClass",
2276                                  "foreignSecurityPrincipal");
2277         if (ret != LDB_SUCCESS) {
2278                 talloc_free(sidstr);
2279                 return NT_STATUS_NO_MEMORY;
2280         }
2281
2282         /* create the alias */
2283         ret = ldb_add(sam_ctx, msg);
2284         if (ret != LDB_SUCCESS) {
2285                 DEBUG(0,("Failed to create foreignSecurityPrincipal "
2286                          "record %s: %s\n", 
2287                          ldb_dn_get_linearized(msg->dn),
2288                          ldb_errstring(sam_ctx)));
2289                 talloc_free(sidstr);
2290                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2291         }
2292
2293         *ret_dn = talloc_steal(mem_ctx, msg->dn);
2294         talloc_free(sidstr);
2295
2296         return NT_STATUS_OK;
2297 }
2298
2299
2300 /*
2301   Find the DN of a domain, assuming it to be a dotted.dns name
2302 */
2303
2304 struct ldb_dn *samdb_dns_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, const char *dns_domain) 
2305 {
2306         unsigned int i;
2307         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2308         const char *binary_encoded;
2309         const char * const *split_realm;
2310         struct ldb_dn *dn;
2311
2312         if (!tmp_ctx) {
2313                 return NULL;
2314         }
2315
2316         split_realm = (const char * const *)str_list_make(tmp_ctx, dns_domain, ".");
2317         if (!split_realm) {
2318                 talloc_free(tmp_ctx);
2319                 return NULL;
2320         }
2321         dn = ldb_dn_new(mem_ctx, ldb, NULL);
2322         for (i=0; split_realm[i]; i++) {
2323                 binary_encoded = ldb_binary_encode_string(tmp_ctx, split_realm[i]);
2324                 if (!ldb_dn_add_base_fmt(dn, "dc=%s", binary_encoded)) {
2325                         DEBUG(2, ("Failed to add dc=%s element to DN %s\n",
2326                                   binary_encoded, ldb_dn_get_linearized(dn)));
2327                         talloc_free(tmp_ctx);
2328                         return NULL;
2329                 }
2330         }
2331         if (!ldb_dn_validate(dn)) {
2332                 DEBUG(2, ("Failed to validated DN %s\n",
2333                           ldb_dn_get_linearized(dn)));
2334                 talloc_free(tmp_ctx);
2335                 return NULL;
2336         }
2337         talloc_free(tmp_ctx);
2338         return dn;
2339 }
2340
2341
2342 /*
2343   Find the DNS equivalent of a DN, in dotted DNS form
2344 */
2345 char *samdb_dn_to_dns_domain(TALLOC_CTX *mem_ctx, struct ldb_dn *dn)
2346 {
2347         int i, num_components = ldb_dn_get_comp_num(dn);
2348         char *dns_name = talloc_strdup(mem_ctx, "");
2349         if (dns_name == NULL) {
2350                 return NULL;
2351         }
2352
2353         for (i=0; i<num_components; i++) {
2354                 const struct ldb_val *v = ldb_dn_get_component_val(dn, i);
2355                 char *s;
2356                 if (v == NULL) {
2357                         talloc_free(dns_name);
2358                         return NULL;
2359                 }
2360                 s = talloc_asprintf_append_buffer(dns_name, "%*.*s.",
2361                                                   (int)v->length, (int)v->length, (char *)v->data);
2362                 if (s == NULL) {
2363                         talloc_free(dns_name);
2364                         return NULL;
2365                 }
2366                 dns_name = s;
2367         }
2368
2369         /* remove the last '.' */
2370         if (dns_name[0] != 0) {
2371                 dns_name[strlen(dns_name)-1] = 0;
2372         }
2373
2374         return dns_name;
2375 }
2376
2377 /*
2378   Find the DNS _msdcs name for a given NTDS GUID. The resulting DNS
2379   name is based on the forest DNS name
2380 */
2381 char *samdb_ntds_msdcs_dns_name(struct ldb_context *samdb,
2382                                 TALLOC_CTX *mem_ctx,
2383                                 const struct GUID *ntds_guid)
2384 {
2385         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2386         const char *guid_str;
2387         struct ldb_dn *forest_dn;
2388         const char *dnsforest;
2389         char *ret;
2390
2391         guid_str = GUID_string(tmp_ctx, ntds_guid);
2392         if (guid_str == NULL) {
2393                 talloc_free(tmp_ctx);
2394                 return NULL;
2395         }
2396         forest_dn = ldb_get_root_basedn(samdb);
2397         if (forest_dn == NULL) {
2398                 talloc_free(tmp_ctx);
2399                 return NULL;
2400         }
2401         dnsforest = samdb_dn_to_dns_domain(tmp_ctx, forest_dn);
2402         if (dnsforest == NULL) {
2403                 talloc_free(tmp_ctx);
2404                 return NULL;
2405         }
2406         ret = talloc_asprintf(mem_ctx, "%s._msdcs.%s", guid_str, dnsforest);
2407         talloc_free(tmp_ctx);
2408         return ret;
2409 }
2410
2411
2412 /*
2413   Find the DN of a domain, be it the netbios or DNS name 
2414 */
2415 struct ldb_dn *samdb_domain_to_dn(struct ldb_context *ldb, TALLOC_CTX *mem_ctx, 
2416                                   const char *domain_name) 
2417 {
2418         const char * const domain_ref_attrs[] = {
2419                 "ncName", NULL
2420         };
2421         const char * const domain_ref2_attrs[] = {
2422                 NULL
2423         };
2424         struct ldb_result *res_domain_ref;
2425         char *escaped_domain = ldb_binary_encode_string(mem_ctx, domain_name);
2426         /* find the domain's DN */
2427         int ret_domain = ldb_search(ldb, mem_ctx,
2428                                             &res_domain_ref, 
2429                                             samdb_partitions_dn(ldb, mem_ctx), 
2430                                             LDB_SCOPE_ONELEVEL, 
2431                                             domain_ref_attrs,
2432                                             "(&(nETBIOSName=%s)(objectclass=crossRef))", 
2433                                             escaped_domain);
2434         if (ret_domain != LDB_SUCCESS) {
2435                 return NULL;
2436         }
2437
2438         if (res_domain_ref->count == 0) {
2439                 ret_domain = ldb_search(ldb, mem_ctx,
2440                                                 &res_domain_ref, 
2441                                                 samdb_dns_domain_to_dn(ldb, mem_ctx, domain_name),
2442                                                 LDB_SCOPE_BASE,
2443                                                 domain_ref2_attrs,
2444                                                 "(objectclass=domain)");
2445                 if (ret_domain != LDB_SUCCESS) {
2446                         return NULL;
2447                 }
2448
2449                 if (res_domain_ref->count == 1) {
2450                         return res_domain_ref->msgs[0]->dn;
2451                 }
2452                 return NULL;
2453         }
2454
2455         if (res_domain_ref->count > 1) {
2456                 DEBUG(0,("Found %d records matching domain [%s]\n", 
2457                          ret_domain, domain_name));
2458                 return NULL;
2459         }
2460
2461         return samdb_result_dn(ldb, mem_ctx, res_domain_ref->msgs[0], "nCName", NULL);
2462
2463 }
2464
2465
2466 /*
2467   use a GUID to find a DN
2468  */
2469 int dsdb_find_dn_by_guid(struct ldb_context *ldb, 
2470                          TALLOC_CTX *mem_ctx,
2471                          const struct GUID *guid,
2472                          uint32_t dsdb_flags,
2473                          struct ldb_dn **dn)
2474 {
2475         int ret;
2476         struct ldb_result *res;
2477         const char *attrs[] = { NULL };
2478         char *guid_str = GUID_string(mem_ctx, guid);
2479
2480         if (!guid_str) {
2481                 return ldb_operr(ldb);
2482         }
2483
2484         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2485                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2486                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2487                           DSDB_SEARCH_ONE_ONLY | dsdb_flags,
2488                           "objectGUID=%s", guid_str);
2489         talloc_free(guid_str);
2490         if (ret != LDB_SUCCESS) {
2491                 return ret;
2492         }
2493
2494         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2495         talloc_free(res);
2496
2497         return LDB_SUCCESS;
2498 }
2499
2500 /*
2501   use a DN to find a GUID with a given attribute name
2502  */
2503 int dsdb_find_guid_attr_by_dn(struct ldb_context *ldb,
2504                               struct ldb_dn *dn, const char *attribute,
2505                               struct GUID *guid)
2506 {
2507         int ret;
2508         struct ldb_result *res;
2509         const char *attrs[2];
2510         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2511
2512         attrs[0] = attribute;
2513         attrs[1] = NULL;
2514
2515         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2516                              DSDB_SEARCH_SHOW_DELETED |
2517                              DSDB_SEARCH_SHOW_RECYCLED);
2518         if (ret != LDB_SUCCESS) {
2519                 talloc_free(tmp_ctx);
2520                 return ret;
2521         }
2522         if (res->count < 1) {
2523                 talloc_free(tmp_ctx);
2524                 return LDB_ERR_NO_SUCH_OBJECT;
2525         }
2526         *guid = samdb_result_guid(res->msgs[0], attribute);
2527         talloc_free(tmp_ctx);
2528         return LDB_SUCCESS;
2529 }
2530
2531 /*
2532   use a DN to find a GUID
2533  */
2534 int dsdb_find_guid_by_dn(struct ldb_context *ldb,
2535                          struct ldb_dn *dn, struct GUID *guid)
2536 {
2537         return dsdb_find_guid_attr_by_dn(ldb, dn, "objectGUID", guid);
2538 }
2539
2540
2541
2542 /*
2543  adds the given GUID to the given ldb_message. This value is added
2544  for the given attr_name (may be either "objectGUID" or "parentGUID").
2545  */
2546 int dsdb_msg_add_guid(struct ldb_message *msg,
2547                 struct GUID *guid,
2548                 const char *attr_name)
2549 {
2550         int ret;
2551         struct ldb_val v;
2552         NTSTATUS status;
2553         TALLOC_CTX *tmp_ctx =  talloc_init("dsdb_msg_add_guid");
2554
2555         status = GUID_to_ndr_blob(guid, tmp_ctx, &v);
2556         if (!NT_STATUS_IS_OK(status)) {
2557                 ret = LDB_ERR_OPERATIONS_ERROR;
2558                 goto done;
2559         }
2560
2561         ret = ldb_msg_add_steal_value(msg, attr_name, &v);
2562         if (ret != LDB_SUCCESS) {
2563                 DEBUG(4,(__location__ ": Failed to add %s to the message\n",
2564                                          attr_name));
2565                 goto done;
2566         }
2567
2568         ret = LDB_SUCCESS;
2569
2570 done:
2571         talloc_free(tmp_ctx);
2572         return ret;
2573
2574 }
2575
2576
2577 /*
2578   use a DN to find a SID
2579  */
2580 int dsdb_find_sid_by_dn(struct ldb_context *ldb, 
2581                         struct ldb_dn *dn, struct dom_sid *sid)
2582 {
2583         int ret;
2584         struct ldb_result *res;
2585         const char *attrs[] = { "objectSid", NULL };
2586         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2587         struct dom_sid *s;
2588
2589         ZERO_STRUCTP(sid);
2590
2591         ret = dsdb_search_dn(ldb, tmp_ctx, &res, dn, attrs,
2592                              DSDB_SEARCH_SHOW_DELETED |
2593                              DSDB_SEARCH_SHOW_RECYCLED);
2594         if (ret != LDB_SUCCESS) {
2595                 talloc_free(tmp_ctx);
2596                 return ret;
2597         }
2598         if (res->count < 1) {
2599                 talloc_free(tmp_ctx);
2600                 return LDB_ERR_NO_SUCH_OBJECT;
2601         }
2602         s = samdb_result_dom_sid(tmp_ctx, res->msgs[0], "objectSid");
2603         if (s == NULL) {
2604                 talloc_free(tmp_ctx);
2605                 return LDB_ERR_NO_SUCH_OBJECT;
2606         }
2607         *sid = *s;
2608         talloc_free(tmp_ctx);
2609         return LDB_SUCCESS;
2610 }
2611
2612 /*
2613   use a SID to find a DN
2614  */
2615 int dsdb_find_dn_by_sid(struct ldb_context *ldb,
2616                         TALLOC_CTX *mem_ctx,
2617                         struct dom_sid *sid, struct ldb_dn **dn)
2618 {
2619         int ret;
2620         struct ldb_result *res;
2621         const char *attrs[] = { NULL };
2622         char *sid_str = ldap_encode_ndr_dom_sid(mem_ctx, sid);
2623
2624         if (!sid_str) {
2625                 return ldb_operr(ldb);
2626         }
2627
2628         ret = dsdb_search(ldb, mem_ctx, &res, NULL, LDB_SCOPE_SUBTREE, attrs,
2629                           DSDB_SEARCH_SEARCH_ALL_PARTITIONS |
2630                           DSDB_SEARCH_SHOW_EXTENDED_DN |
2631                           DSDB_SEARCH_ONE_ONLY,
2632                           "objectSid=%s", sid_str);
2633         talloc_free(sid_str);
2634         if (ret != LDB_SUCCESS) {
2635                 return ret;
2636         }
2637
2638         *dn = talloc_steal(mem_ctx, res->msgs[0]->dn);
2639         talloc_free(res);
2640
2641         return LDB_SUCCESS;
2642 }
2643
2644 /*
2645   load a repsFromTo blob list for a given partition GUID
2646   attr must be "repsFrom" or "repsTo"
2647  */
2648 WERROR dsdb_loadreps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2649                      const char *attr, struct repsFromToBlob **r, uint32_t *count)
2650 {
2651         const char *attrs[] = { attr, NULL };
2652         struct ldb_result *res = NULL;
2653         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2654         unsigned int i;
2655         struct ldb_message_element *el;
2656         int ret;
2657
2658         *r = NULL;
2659         *count = 0;
2660
2661         ret = dsdb_search_dn(sam_ctx, tmp_ctx, &res, dn, attrs, 0);
2662         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2663                 /* partition hasn't been replicated yet */
2664                 return WERR_OK;
2665         }
2666         if (ret != LDB_SUCCESS) {
2667                 DEBUG(0,("dsdb_loadreps: failed to read partition object: %s\n", ldb_errstring(sam_ctx)));
2668                 talloc_free(tmp_ctx);
2669                 return WERR_DS_DRA_INTERNAL_ERROR;
2670         }
2671
2672         el = ldb_msg_find_element(res->msgs[0], attr);
2673         if (el == NULL) {
2674                 /* it's OK to be empty */
2675                 talloc_free(tmp_ctx);
2676                 return WERR_OK;
2677         }
2678
2679         *count = el->num_values;
2680         *r = talloc_array(mem_ctx, struct repsFromToBlob, *count);
2681         if (*r == NULL) {
2682                 talloc_free(tmp_ctx);
2683                 return WERR_DS_DRA_INTERNAL_ERROR;
2684         }
2685
2686         for (i=0; i<(*count); i++) {
2687                 enum ndr_err_code ndr_err;
2688                 ndr_err = ndr_pull_struct_blob(&el->values[i], 
2689                                                mem_ctx, 
2690                                                &(*r)[i], 
2691                                                (ndr_pull_flags_fn_t)ndr_pull_repsFromToBlob);
2692                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2693                         talloc_free(tmp_ctx);
2694                         return WERR_DS_DRA_INTERNAL_ERROR;
2695                 }
2696         }
2697
2698         talloc_free(tmp_ctx);
2699         
2700         return WERR_OK;
2701 }
2702
2703 /*
2704   save the repsFromTo blob list for a given partition GUID
2705   attr must be "repsFrom" or "repsTo"
2706  */
2707 WERROR dsdb_savereps(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
2708                      const char *attr, struct repsFromToBlob *r, uint32_t count)
2709 {
2710         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
2711         struct ldb_message *msg;
2712         struct ldb_message_element *el;
2713         unsigned int i;
2714
2715         msg = ldb_msg_new(tmp_ctx);
2716         msg->dn = dn;
2717         if (ldb_msg_add_empty(msg, attr, LDB_FLAG_MOD_REPLACE, &el) != LDB_SUCCESS) {
2718                 goto failed;
2719         }
2720
2721         el->values = talloc_array(msg, struct ldb_val, count);
2722         if (!el->values) {
2723                 goto failed;
2724         }
2725
2726         for (i=0; i<count; i++) {
2727                 struct ldb_val v;
2728                 enum ndr_err_code ndr_err;
2729
2730                 ndr_err = ndr_push_struct_blob(&v, tmp_ctx, 
2731                                                &r[i], 
2732                                                (ndr_push_flags_fn_t)ndr_push_repsFromToBlob);
2733                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2734                         goto failed;
2735                 }
2736
2737                 el->num_values++;
2738                 el->values[i] = v;
2739         }
2740
2741         if (dsdb_modify(sam_ctx, msg, 0) != LDB_SUCCESS) {
2742                 DEBUG(0,("Failed to store %s - %s\n", attr, ldb_errstring(sam_ctx)));
2743                 goto failed;
2744         }
2745
2746         talloc_free(tmp_ctx);
2747         
2748         return WERR_OK;
2749
2750 failed:
2751         talloc_free(tmp_ctx);
2752         return WERR_DS_DRA_INTERNAL_ERROR;
2753 }
2754
2755
2756 /*
2757   load the uSNHighest and the uSNUrgent attributes from the @REPLCHANGED
2758   object for a partition
2759  */
2760 int dsdb_load_partition_usn(struct ldb_context *ldb, struct ldb_dn *dn,
2761                                 uint64_t *uSN, uint64_t *urgent_uSN)
2762 {
2763         struct ldb_request *req;
2764         int ret;
2765         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
2766         struct dsdb_control_current_partition *p_ctrl;
2767         struct ldb_result *res;
2768
2769         res = talloc_zero(tmp_ctx, struct ldb_result);
2770         if (!res) {
2771                 talloc_free(tmp_ctx);
2772                 return ldb_oom(ldb);
2773         }
2774
2775         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
2776                                    ldb_dn_new(tmp_ctx, ldb, "@REPLCHANGED"),
2777                                    LDB_SCOPE_BASE,
2778                                    NULL, NULL,
2779                                    NULL,
2780                                    res, ldb_search_default_callback,
2781                                    NULL);
2782         if (ret != LDB_SUCCESS) {
2783                 talloc_free(tmp_ctx);
2784                 return ret;
2785         }
2786
2787         p_ctrl = talloc(req, struct dsdb_control_current_partition);
2788         if (p_ctrl == NULL) {
2789                 talloc_free(tmp_ctx);
2790                 return ldb_oom(ldb);
2791         }
2792         p_ctrl->version = DSDB_CONTROL_CURRENT_PARTITION_VERSION;
2793         p_ctrl->dn = dn;
2794         
2795         ret = ldb_request_add_control(req,
2796                                       DSDB_CONTROL_CURRENT_PARTITION_OID,
2797                                       false, p_ctrl);
2798         if (ret != LDB_SUCCESS) {
2799                 talloc_free(tmp_ctx);
2800                 return ret;
2801         }
2802         
2803         /* Run the new request */
2804         ret = ldb_request(ldb, req);
2805         
2806         if (ret == LDB_SUCCESS) {
2807                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
2808         }
2809
2810         if (ret == LDB_ERR_NO_SUCH_OBJECT || ret == LDB_ERR_INVALID_DN_SYNTAX) {
2811                 /* it hasn't been created yet, which means
2812                    an implicit value of zero */
2813                 *uSN = 0;
2814                 talloc_free(tmp_ctx);
2815                 return LDB_SUCCESS;
2816         }
2817
2818         if (ret != LDB_SUCCESS) {
2819                 talloc_free(tmp_ctx);
2820                 return ret;
2821         }
2822
2823         if (res->count < 1) {
2824                 *uSN = 0;
2825                 if (urgent_uSN) {
2826                         *urgent_uSN = 0;
2827                 }
2828         } else {
2829                 *uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNHighest", 0);
2830                 if (urgent_uSN) {
2831                         *urgent_uSN = ldb_msg_find_attr_as_uint64(res->msgs[0], "uSNUrgent", 0);
2832                 }
2833         }
2834
2835         talloc_free(tmp_ctx);
2836
2837         return LDB_SUCCESS;     
2838 }
2839
2840 int drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
2841                                                    const struct drsuapi_DsReplicaCursor2 *c2)
2842 {
2843         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2844 }
2845
2846 int drsuapi_DsReplicaCursor_compare(const struct drsuapi_DsReplicaCursor *c1,
2847                                     const struct drsuapi_DsReplicaCursor *c2)
2848 {
2849         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
2850 }
2851
2852
2853 /*
2854   see if a computer identified by its invocationId is a RODC
2855 */
2856 int samdb_is_rodc(struct ldb_context *sam_ctx, const struct GUID *objectGUID, bool *is_rodc)
2857 {
2858         /* 1) find the DN for this servers NTDSDSA object
2859            2) search for the msDS-isRODC attribute
2860            3) if not present then not a RODC
2861            4) if present and TRUE then is a RODC
2862         */
2863         struct ldb_dn *config_dn;
2864         const char *attrs[] = { "msDS-isRODC", NULL };
2865         int ret;
2866         struct ldb_result *res;
2867         TALLOC_CTX *tmp_ctx = talloc_new(sam_ctx);
2868
2869         config_dn = ldb_get_config_basedn(sam_ctx);
2870         if (!config_dn) {
2871                 talloc_free(tmp_ctx);
2872                 return ldb_operr(sam_ctx);
2873         }
2874
2875         ret = dsdb_search(sam_ctx, tmp_ctx, &res, config_dn, LDB_SCOPE_SUBTREE, attrs,
2876                           DSDB_SEARCH_ONE_ONLY, "objectGUID=%s", GUID_string(tmp_ctx, objectGUID));
2877
2878         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
2879                 *is_rodc = false;
2880                 talloc_free(tmp_ctx);
2881                 return LDB_SUCCESS;
2882         }
2883
2884         if (ret != LDB_SUCCESS) {
2885                 DEBUG(1,(("Failed to find our own NTDS Settings object by objectGUID=%s!\n"),
2886                          GUID_string(tmp_ctx, objectGUID)));
2887                 *is_rodc = false;
2888                 talloc_free(tmp_ctx);
2889                 return ret;
2890         }
2891
2892         ret = ldb_msg_find_attr_as_bool(res->msgs[0], "msDS-isRODC", 0);
2893         *is_rodc = (ret == 1);
2894
2895         talloc_free(tmp_ctx);
2896         return LDB_SUCCESS;
2897 }
2898
2899
2900 /*
2901   see if we are a RODC
2902 */
2903 int samdb_rodc(struct ldb_context *sam_ctx, bool *am_rodc)
2904 {
2905         const struct GUID *objectGUID;
2906         int ret;
2907         bool *cached;
2908
2909         /* see if we have a cached copy */
2910         cached = (bool *)ldb_get_opaque(sam_ctx, "cache.am_rodc");
2911         if (cached) {
2912                 *am_rodc = *cached;
2913                 return LDB_SUCCESS;
2914         }
2915
2916         objectGUID = samdb_ntds_objectGUID(sam_ctx);
2917         if (!objectGUID) {
2918                 return ldb_operr(sam_ctx);
2919         }
2920
2921         ret = samdb_is_rodc(sam_ctx, objectGUID, am_rodc);
2922         if (ret != LDB_SUCCESS) {
2923                 return ret;
2924         }
2925
2926         cached = talloc(sam_ctx, bool);
2927         if (cached == NULL) {
2928                 return ldb_oom(sam_ctx);
2929         }
2930         *cached = *am_rodc;
2931
2932         ret = ldb_set_opaque(sam_ctx, "cache.am_rodc", cached);
2933         if (ret != LDB_SUCCESS) {
2934                 talloc_free(cached);
2935                 return ldb_operr(sam_ctx);
2936         }
2937
2938         return LDB_SUCCESS;
2939 }
2940
2941 bool samdb_set_am_rodc(struct ldb_context *ldb, bool am_rodc)
2942 {
2943         TALLOC_CTX *tmp_ctx;
2944         bool *cached;
2945
2946         tmp_ctx = talloc_new(ldb);
2947         if (tmp_ctx == NULL) {
2948                 goto failed;
2949         }
2950
2951         cached = talloc(tmp_ctx, bool);
2952         if (!cached) {
2953                 goto failed;
2954         }
2955
2956         *cached = am_rodc;
2957         if (ldb_set_opaque(ldb, "cache.am_rodc", cached) != LDB_SUCCESS) {
2958                 goto failed;
2959         }
2960
2961         talloc_steal(ldb, cached);
2962         talloc_free(tmp_ctx);
2963         return true;
2964
2965 failed:
2966         DEBUG(1,("Failed to set our own cached am_rodc in the ldb!\n"));
2967         talloc_free(tmp_ctx);
2968         return false;
2969 }
2970
2971
2972 /*
2973  * return NTDSSiteSettings options. See MS-ADTS 7.1.1.2.2.1.1
2974  * flags are DS_NTDSSETTINGS_OPT_*
2975  */
2976 int samdb_ntds_site_settings_options(struct ldb_context *ldb_ctx,
2977                                         uint32_t *options)
2978 {
2979         int rc;
2980         TALLOC_CTX *tmp_ctx;
2981         struct ldb_result *res;
2982         struct ldb_dn *site_dn;
2983         const char *attrs[] = { "options", NULL };
2984
2985         tmp_ctx = talloc_new(ldb_ctx);
2986         if (tmp_ctx == NULL)
2987                 goto failed;
2988
2989         /* Retrieve the site dn for the ldb that we
2990          * have open.  This is our local site.
2991          */
2992         site_dn = samdb_server_site_dn(ldb_ctx, tmp_ctx);
2993         if (site_dn == NULL)
2994                 goto failed;
2995
2996         /* Perform a one level (child) search from the local
2997          * site distinguided name.   We're looking for the
2998          * "options" attribute within the nTDSSiteSettings
2999          * object
3000          */
3001         rc = ldb_search(ldb_ctx, tmp_ctx, &res, site_dn,
3002                         LDB_SCOPE_ONELEVEL, attrs,
3003                         "objectClass=nTDSSiteSettings");
3004
3005         if (rc != LDB_SUCCESS || res->count != 1)
3006                 goto failed;
3007
3008         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3009
3010         talloc_free(tmp_ctx);
3011
3012         return LDB_SUCCESS;
3013
3014 failed:
3015         DEBUG(1,("Failed to find our NTDS Site Settings options in ldb!\n"));
3016         talloc_free(tmp_ctx);
3017         return LDB_ERR_NO_SUCH_OBJECT;
3018 }
3019
3020 /*
3021   return NTDS options flags. See MS-ADTS 7.1.1.2.2.1.2.1.1 
3022
3023   flags are DS_NTDS_OPTION_*
3024 */
3025 int samdb_ntds_options(struct ldb_context *ldb, uint32_t *options)
3026 {
3027         TALLOC_CTX *tmp_ctx;
3028         const char *attrs[] = { "options", NULL };
3029         int ret;
3030         struct ldb_result *res;
3031
3032         tmp_ctx = talloc_new(ldb);
3033         if (tmp_ctx == NULL) {
3034                 goto failed;
3035         }
3036
3037         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3038         if (ret != LDB_SUCCESS) {
3039                 goto failed;
3040         }
3041
3042         if (res->count != 1) {
3043                 goto failed;
3044         }
3045
3046         *options = ldb_msg_find_attr_as_uint(res->msgs[0], "options", 0);
3047
3048         talloc_free(tmp_ctx);
3049
3050         return LDB_SUCCESS;
3051
3052 failed:
3053         DEBUG(1,("Failed to find our own NTDS Settings options in the ldb!\n"));
3054         talloc_free(tmp_ctx);
3055         return LDB_ERR_NO_SUCH_OBJECT;
3056 }
3057
3058 const char* samdb_ntds_object_category(TALLOC_CTX *tmp_ctx, struct ldb_context *ldb)
3059 {
3060         const char *attrs[] = { "objectCategory", NULL };
3061         int ret;
3062         struct ldb_result *res;
3063
3064         ret = ldb_search(ldb, tmp_ctx, &res, samdb_ntds_settings_dn(ldb, tmp_ctx), LDB_SCOPE_BASE, attrs, NULL);
3065         if (ret != LDB_SUCCESS) {
3066                 goto failed;
3067         }
3068
3069         if (res->count != 1) {
3070                 goto failed;
3071         }
3072
3073         return ldb_msg_find_attr_as_string(res->msgs[0], "objectCategory", NULL);
3074
3075 failed:
3076         DEBUG(1,("Failed to find our own NTDS Settings objectCategory in the ldb!\n"));
3077         return NULL;
3078 }
3079
3080 /*
3081  * Function which generates a "lDAPDisplayName" attribute from a "CN" one.
3082  * Algorithm implemented according to MS-ADTS 3.1.1.2.3.4
3083  */
3084 const char *samdb_cn_to_lDAPDisplayName(TALLOC_CTX *mem_ctx, const char *cn)
3085 {
3086         char **tokens, *ret;
3087         size_t i;
3088
3089         tokens = str_list_make(mem_ctx, cn, " -_");
3090         if (tokens == NULL)
3091                 return NULL;
3092
3093         /* "tolower()" and "toupper()" should also work properly on 0x00 */
3094         tokens[0][0] = tolower(tokens[0][0]);
3095         for (i = 1; i < str_list_length((const char * const *)tokens); i++)
3096                 tokens[i][0] = toupper(tokens[i][0]);
3097
3098         ret = talloc_strdup(mem_ctx, tokens[0]);
3099         for (i = 1; i < str_list_length((const char * const *)tokens); i++)
3100                 ret = talloc_asprintf_append_buffer(ret, "%s", tokens[i]);
3101
3102         talloc_free(tokens);
3103
3104         return ret;
3105 }
3106
3107 /*
3108  * This detects and returns the domain functional level (DS_DOMAIN_FUNCTION_*)
3109  */
3110 int dsdb_functional_level(struct ldb_context *ldb)
3111 {
3112         int *domainFunctionality =
3113                 talloc_get_type(ldb_get_opaque(ldb, "domainFunctionality"), int);
3114         if (!domainFunctionality) {
3115                 /* this is expected during initial provision */
3116                 DEBUG(4,(__location__ ": WARNING: domainFunctionality not setup\n"));
3117                 return DS_DOMAIN_FUNCTION_2000;
3118         }
3119         return *domainFunctionality;
3120 }
3121
3122 /*
3123  * This detects and returns the forest functional level (DS_DOMAIN_FUNCTION_*)
3124  */
3125 int dsdb_forest_functional_level(struct ldb_context *ldb)
3126 {
3127         int *forestFunctionality =
3128                 talloc_get_type(ldb_get_opaque(ldb, "forestFunctionality"), int);
3129         if (!forestFunctionality) {
3130                 DEBUG(0,(__location__ ": WARNING: forestFunctionality not setup\n"));
3131                 return DS_DOMAIN_FUNCTION_2000;
3132         }
3133         return *forestFunctionality;
3134 }
3135
3136 /*
3137   set a GUID in an extended DN structure
3138  */
3139 int dsdb_set_extended_dn_guid(struct ldb_dn *dn, const struct GUID *guid, const char *component_name)
3140 {
3141         struct ldb_val v;
3142         NTSTATUS status;
3143         int ret;
3144
3145         status = GUID_to_ndr_blob(guid, dn, &v);
3146         if (!NT_STATUS_IS_OK(status)) {
3147                 return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3148         }
3149
3150         ret = ldb_dn_set_extended_component(dn, component_name, &v);
3151         data_blob_free(&v);
3152         return ret;
3153 }
3154
3155 /*
3156   return a GUID from a extended DN structure
3157  */
3158 NTSTATUS dsdb_get_extended_dn_guid(struct ldb_dn *dn, struct GUID *guid, const char *component_name)
3159 {
3160         const struct ldb_val *v;
3161
3162         v = ldb_dn_get_extended_component(dn, component_name);
3163         if (v == NULL) {
3164                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3165         }
3166
3167         return GUID_from_ndr_blob(v, guid);
3168 }
3169
3170 /*
3171   return a uint64_t from a extended DN structure
3172  */
3173 NTSTATUS dsdb_get_extended_dn_uint64(struct ldb_dn *dn, uint64_t *val, const char *component_name)
3174 {
3175         const struct ldb_val *v;
3176         char *s;
3177
3178         v = ldb_dn_get_extended_component(dn, component_name);
3179         if (v == NULL) {
3180                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3181         }
3182         s = talloc_strndup(dn, (const char *)v->data, v->length);
3183         NT_STATUS_HAVE_NO_MEMORY(s);
3184
3185         *val = strtoull(s, NULL, 0);
3186
3187         talloc_free(s);
3188         return NT_STATUS_OK;
3189 }
3190
3191 /*
3192   return a NTTIME from a extended DN structure
3193  */
3194 NTSTATUS dsdb_get_extended_dn_nttime(struct ldb_dn *dn, NTTIME *nttime, const char *component_name)
3195 {
3196         return dsdb_get_extended_dn_uint64(dn, nttime, component_name);
3197 }
3198
3199 /*
3200   return a uint32_t from a extended DN structure
3201  */
3202 NTSTATUS dsdb_get_extended_dn_uint32(struct ldb_dn *dn, uint32_t *val, const char *component_name)
3203 {
3204         const struct ldb_val *v;
3205         char *s;
3206
3207         v = ldb_dn_get_extended_component(dn, component_name);
3208         if (v == NULL) {
3209                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3210         }
3211
3212         s = talloc_strndup(dn, (const char *)v->data, v->length);
3213         NT_STATUS_HAVE_NO_MEMORY(s);
3214
3215         *val = strtoul(s, NULL, 0);
3216
3217         talloc_free(s);
3218         return NT_STATUS_OK;
3219 }
3220
3221 /*
3222   return a dom_sid from a extended DN structure
3223  */
3224 NTSTATUS dsdb_get_extended_dn_sid(struct ldb_dn *dn, struct dom_sid *sid, const char *component_name)
3225 {
3226         const struct ldb_val *sid_blob;
3227         struct TALLOC_CTX *tmp_ctx;
3228         enum ndr_err_code ndr_err;
3229
3230         sid_blob = ldb_dn_get_extended_component(dn, component_name);
3231         if (!sid_blob) {
3232                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
3233         }
3234
3235         tmp_ctx = talloc_new(NULL);
3236
3237         ndr_err = ndr_pull_struct_blob_all(sid_blob, tmp_ctx, sid,
3238                                            (ndr_pull_flags_fn_t)ndr_pull_dom_sid);
3239         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3240                 NTSTATUS status = ndr_map_error2ntstatus(ndr_err);
3241                 talloc_free(tmp_ctx);
3242                 return status;
3243         }
3244
3245         talloc_free(tmp_ctx);
3246         return NT_STATUS_OK;
3247 }
3248
3249
3250 /*
3251   return RMD_FLAGS directly from a ldb_dn
3252   returns 0 if not found
3253  */
3254 uint32_t dsdb_dn_rmd_flags(struct ldb_dn *dn)
3255 {
3256         const struct ldb_val *v;
3257         char buf[32];
3258         v = ldb_dn_get_extended_component(dn, "RMD_FLAGS");
3259         if (!v || v->length > sizeof(buf)-1) return 0;
3260         strncpy(buf, (const char *)v->data, v->length);
3261         buf[v->length] = 0;
3262         return strtoul(buf, NULL, 10);
3263 }
3264
3265 /*
3266   return RMD_FLAGS directly from a ldb_val for a DN
3267   returns 0 if RMD_FLAGS is not found
3268  */
3269 uint32_t dsdb_dn_val_rmd_flags(const struct ldb_val *val)
3270 {
3271         const char *p;
3272         uint32_t flags;
3273         char *end;
3274
3275         if (val->length < 13) {
3276                 return 0;
3277         }
3278         p = memmem(val->data, val->length, "<RMD_FLAGS=", 11);
3279         if (!p) {
3280                 return 0;
3281         }
3282         flags = strtoul(p+11, &end, 10);
3283         if (!end || *end != '>') {
3284                 /* it must end in a > */
3285                 return 0;
3286         }
3287         return flags;
3288 }
3289
3290 /*
3291   return true if a ldb_val containing a DN in storage form is deleted
3292  */
3293 bool dsdb_dn_is_deleted_val(const struct ldb_val *val)
3294 {
3295         return (dsdb_dn_val_rmd_flags(val) & DSDB_RMD_FLAG_DELETED) != 0;
3296 }
3297
3298 /*
3299   return true if a ldb_val containing a DN in storage form is
3300   in the upgraded w2k3 linked attribute format
3301  */
3302 bool dsdb_dn_is_upgraded_link_val(struct ldb_val *val)
3303 {
3304         return memmem(val->data, val->length, "<RMD_VERSION=", 13) != NULL;
3305 }
3306
3307 /*
3308   return a DN for a wellknown GUID
3309  */
3310 int dsdb_wellknown_dn(struct ldb_context *samdb, TALLOC_CTX *mem_ctx,
3311                       struct ldb_dn *nc_root, const char *wk_guid,
3312                       struct ldb_dn **wkguid_dn)
3313 {
3314         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3315         const char *attrs[] = { NULL };
3316         int ret;
3317         struct ldb_dn *dn;
3318         struct ldb_result *res;
3319
3320         /* construct the magic WKGUID DN */
3321         dn = ldb_dn_new_fmt(tmp_ctx, samdb, "<WKGUID=%s,%s>",
3322                             wk_guid, ldb_dn_get_linearized(nc_root));
3323         if (!wkguid_dn) {
3324                 talloc_free(tmp_ctx);
3325                 return ldb_operr(samdb);
3326         }
3327
3328         ret = dsdb_search_dn(samdb, tmp_ctx, &res, dn, attrs,
3329                              DSDB_SEARCH_SHOW_DELETED |
3330                              DSDB_SEARCH_SHOW_RECYCLED);
3331         if (ret != LDB_SUCCESS) {
3332                 talloc_free(tmp_ctx);
3333                 return ret;
3334         }
3335
3336         (*wkguid_dn) = talloc_steal(mem_ctx, res->msgs[0]->dn);
3337         talloc_free(tmp_ctx);
3338         return LDB_SUCCESS;
3339 }
3340
3341
3342 static int dsdb_dn_compare_ptrs(struct ldb_dn **dn1, struct ldb_dn **dn2)
3343 {
3344         return ldb_dn_compare(*dn1, *dn2);
3345 }
3346
3347 /*
3348   find a NC root given a DN within the NC
3349  */
3350 int dsdb_find_nc_root(struct ldb_context *samdb, TALLOC_CTX *mem_ctx, struct ldb_dn *dn,
3351                       struct ldb_dn **nc_root)
3352 {
3353         const char *root_attrs[] = { "namingContexts", NULL };
3354         TALLOC_CTX *tmp_ctx;
3355         int ret;
3356         struct ldb_message_element *el;
3357         struct ldb_result *root_res;
3358         unsigned int i;
3359         struct ldb_dn **nc_dns;
3360
3361         tmp_ctx = talloc_new(samdb);
3362         if (tmp_ctx == NULL) {
3363                 return ldb_oom(samdb);
3364         }
3365
3366         ret = ldb_search(samdb, tmp_ctx, &root_res,
3367                          ldb_dn_new(tmp_ctx, samdb, ""), LDB_SCOPE_BASE, root_attrs, NULL);
3368         if (ret != LDB_SUCCESS) {
3369                 DEBUG(1,("Searching for namingContexts in rootDSE failed: %s\n", ldb_errstring(samdb)));
3370                 talloc_free(tmp_ctx);
3371                 return ret;
3372         }
3373
3374         el = ldb_msg_find_element(root_res->msgs[0], "namingContexts");
3375         if ((el == NULL) || (el->num_values < 3)) {
3376                 struct ldb_message *tmp_msg;
3377
3378                 DEBUG(5,("dsdb_find_nc_root: Finding a valid 'namingContexts' element in the RootDSE failed. Using a temporary list."));
3379
3380                 /* This generates a temporary list of NCs in order to let the
3381                  * provisioning work. */
3382                 tmp_msg = ldb_msg_new(tmp_ctx);
3383                 if (tmp_msg == NULL) {
3384                         talloc_free(tmp_ctx);
3385                         return ldb_oom(samdb);
3386                 }
3387                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3388                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_schema_basedn(samdb)));
3389                 if (ret != LDB_SUCCESS) {
3390                         talloc_free(tmp_ctx);
3391                         return ret;
3392                 }
3393                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3394                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_config_basedn(samdb)));
3395                 if (ret != LDB_SUCCESS) {
3396                         talloc_free(tmp_ctx);
3397                         return ret;
3398                 }
3399                 ret = ldb_msg_add_steal_string(tmp_msg, "namingContexts",
3400                                                ldb_dn_alloc_linearized(tmp_msg, ldb_get_default_basedn(samdb)));
3401                 if (ret != LDB_SUCCESS) {
3402                         talloc_free(tmp_ctx);
3403                         return ret;
3404                 }
3405                 el = &tmp_msg->elements[0];
3406         }
3407
3408        nc_dns = talloc_array(tmp_ctx, struct ldb_dn *, el->num_values);
3409        if (!nc_dns) {
3410                talloc_free(tmp_ctx);
3411                return ldb_oom(samdb);
3412        }
3413
3414        for (i=0; i<el->num_values; i++) {
3415                nc_dns[i] = ldb_dn_from_ldb_val(nc_dns, samdb, &el->values[i]);
3416                if (nc_dns[i] == NULL) {
3417                        talloc_free(tmp_ctx);
3418                        return ldb_operr(samdb);
3419                }
3420        }
3421
3422        TYPESAFE_QSORT(nc_dns, el->num_values, dsdb_dn_compare_ptrs);
3423
3424        for (i=0; i<el->num_values; i++) {
3425                if (ldb_dn_compare_base(nc_dns[i], dn) == 0) {
3426                        (*nc_root) = talloc_steal(mem_ctx, nc_dns[i]);
3427                        talloc_free(tmp_ctx);
3428                        return LDB_SUCCESS;
3429                }
3430        }
3431
3432        talloc_free(tmp_ctx);
3433        return LDB_ERR_NO_SUCH_OBJECT;
3434 }
3435
3436
3437 /*
3438   find the deleted objects DN for any object, by looking for the NC
3439   root, then looking up the wellknown GUID
3440  */
3441 int dsdb_get_deleted_objects_dn(struct ldb_context *ldb,
3442                                 TALLOC_CTX *mem_ctx, struct ldb_dn *obj_dn,
3443                                 struct ldb_dn **do_dn)
3444 {
3445         struct ldb_dn *nc_root;
3446         int ret;
3447
3448         ret = dsdb_find_nc_root(ldb, mem_ctx, obj_dn, &nc_root);
3449         if (ret != LDB_SUCCESS) {
3450                 return ret;
3451         }
3452
3453         ret = dsdb_wellknown_dn(ldb, mem_ctx, nc_root, DS_GUID_DELETED_OBJECTS_CONTAINER, do_dn);
3454         talloc_free(nc_root);
3455         return ret;
3456 }
3457
3458 /*
3459   return the tombstoneLifetime, in days
3460  */
3461 int dsdb_tombstone_lifetime(struct ldb_context *ldb, uint32_t *lifetime)
3462 {
3463         struct ldb_dn *dn;
3464         dn = ldb_get_config_basedn(ldb);
3465         if (!dn) {
3466                 return LDB_ERR_NO_SUCH_OBJECT;
3467         }
3468         dn = ldb_dn_copy(ldb, dn);
3469         if (!dn) {
3470                 return ldb_operr(ldb);
3471         }
3472         /* see MS-ADTS section 7.1.1.2.4.1.1. There doesn't appear to
3473          be a wellknown GUID for this */
3474         if (!ldb_dn_add_child_fmt(dn, "CN=Directory Service,CN=Windows NT,CN=Services")) {
3475                 talloc_free(dn);
3476                 return ldb_operr(ldb);
3477         }
3478
3479         *lifetime = samdb_search_uint(ldb, dn, 180, dn, "tombstoneLifetime", "objectClass=nTDSService");
3480         talloc_free(dn);
3481         return LDB_SUCCESS;
3482 }
3483
3484 /*
3485   compare a ldb_val to a string case insensitively
3486  */
3487 int samdb_ldb_val_case_cmp(const char *s, struct ldb_val *v)
3488 {
3489         size_t len = strlen(s);
3490         int ret;
3491         if (len > v->length) return 1;
3492         ret = strncasecmp(s, (const char *)v->data, v->length);
3493         if (ret != 0) return ret;
3494         if (v->length > len && v->data[len] != 0) {
3495                 return -1;
3496         }
3497         return 0;
3498 }
3499
3500
3501 /*
3502   load the UDV for a partition in v2 format
3503   The list is returned sorted, and with our local cursor added
3504  */
3505 int dsdb_load_udv_v2(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3506                      struct drsuapi_DsReplicaCursor2 **cursors, uint32_t *count)
3507 {
3508         static const char *attrs[] = { "replUpToDateVector", NULL };
3509         struct ldb_result *r;
3510         const struct ldb_val *ouv_value;
3511         unsigned int i;
3512         int ret;
3513         uint64_t highest_usn = 0;
3514         const struct GUID *our_invocation_id;
3515         static const struct timeval tv1970;
3516         NTTIME nt1970 = timeval_to_nttime(&tv1970);
3517
3518         ret = ldb_search(samdb, mem_ctx, &r, dn, LDB_SCOPE_BASE, attrs, NULL);
3519         if (ret != LDB_SUCCESS) {
3520                 return ret;
3521         }
3522
3523         ouv_value = ldb_msg_find_ldb_val(r->msgs[0], "replUpToDateVector");
3524         if (ouv_value) {
3525                 enum ndr_err_code ndr_err;
3526                 struct replUpToDateVectorBlob ouv;
3527
3528                 ndr_err = ndr_pull_struct_blob(ouv_value, r, &ouv,
3529                                                (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
3530                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
3531                         talloc_free(r);
3532                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3533                 }
3534                 if (ouv.version != 2) {
3535                         /* we always store as version 2, and
3536                          * replUpToDateVector is not replicated
3537                          */
3538                         return LDB_ERR_INVALID_ATTRIBUTE_SYNTAX;
3539                 }
3540
3541                 *count = ouv.ctr.ctr2.count;
3542                 *cursors = talloc_steal(mem_ctx, ouv.ctr.ctr2.cursors);
3543         } else {
3544                 *count = 0;
3545                 *cursors = NULL;
3546         }
3547
3548         talloc_free(r);
3549
3550         our_invocation_id = samdb_ntds_invocation_id(samdb);
3551         if (!our_invocation_id) {
3552                 DEBUG(0,(__location__ ": No invocationID on samdb - %s\n", ldb_errstring(samdb)));
3553                 talloc_free(*cursors);
3554                 return ldb_operr(samdb);
3555         }
3556
3557         ret = ldb_sequence_number(samdb, LDB_SEQ_HIGHEST_SEQ, &highest_usn);
3558         if (ret != LDB_SUCCESS) {
3559                 /* nothing to add - this can happen after a vampire */
3560                 TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3561                 return LDB_SUCCESS;
3562         }
3563
3564         for (i=0; i<*count; i++) {
3565                 if (GUID_equal(our_invocation_id, &(*cursors)[i].source_dsa_invocation_id)) {
3566                         (*cursors)[i].highest_usn = highest_usn;
3567                         (*cursors)[i].last_sync_success = nt1970;
3568                         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3569                         return LDB_SUCCESS;
3570                 }
3571         }
3572
3573         (*cursors) = talloc_realloc(mem_ctx, *cursors, struct drsuapi_DsReplicaCursor2, (*count)+1);
3574         if (! *cursors) {
3575                 return ldb_oom(samdb);
3576         }
3577
3578         (*cursors)[*count].source_dsa_invocation_id = *our_invocation_id;
3579         (*cursors)[*count].highest_usn = highest_usn;
3580         (*cursors)[*count].last_sync_success = nt1970;
3581         (*count)++;
3582
3583         TYPESAFE_QSORT(*cursors, *count, drsuapi_DsReplicaCursor2_compare);
3584
3585         return LDB_SUCCESS;
3586 }
3587
3588 /*
3589   load the UDV for a partition in version 1 format
3590   The list is returned sorted, and with our local cursor added
3591  */
3592 int dsdb_load_udv_v1(struct ldb_context *samdb, struct ldb_dn *dn, TALLOC_CTX *mem_ctx,
3593                      struct drsuapi_DsReplicaCursor **cursors, uint32_t *count)
3594 {
3595         struct drsuapi_DsReplicaCursor2 *v2;
3596         uint32_t i;
3597         int ret;
3598
3599         ret = dsdb_load_udv_v2(samdb, dn, mem_ctx, &v2, count);
3600         if (ret != LDB_SUCCESS) {
3601                 return ret;
3602         }
3603
3604         if (*count == 0) {
3605                 talloc_free(v2);
3606                 *cursors = NULL;
3607                 return LDB_SUCCESS;
3608         }
3609
3610         *cursors = talloc_array(mem_ctx, struct drsuapi_DsReplicaCursor, *count);
3611         if (*cursors == NULL) {
3612                 talloc_free(v2);
3613                 return ldb_oom(samdb);
3614         }
3615
3616         for (i=0; i<*count; i++) {
3617                 (*cursors)[i].source_dsa_invocation_id = v2[i].source_dsa_invocation_id;
3618                 (*cursors)[i].highest_usn = v2[i].highest_usn;
3619         }
3620         talloc_free(v2);
3621         return LDB_SUCCESS;
3622 }
3623
3624 /*
3625   add a set of controls to a ldb_request structure based on a set of
3626   flags. See util.h for a list of available flags
3627  */
3628 int dsdb_request_add_controls(struct ldb_request *req, uint32_t dsdb_flags)
3629 {
3630         int ret;
3631         if (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) {
3632                 struct ldb_search_options_control *options;
3633                 /* Using the phantom root control allows us to search all partitions */
3634                 options = talloc(req, struct ldb_search_options_control);
3635                 if (options == NULL) {
3636                         return LDB_ERR_OPERATIONS_ERROR;
3637                 }
3638                 options->search_options = LDB_SEARCH_OPTION_PHANTOM_ROOT;
3639
3640                 ret = ldb_request_add_control(req,
3641                                               LDB_CONTROL_SEARCH_OPTIONS_OID,
3642                                               true, options);
3643                 if (ret != LDB_SUCCESS) {
3644                         return ret;
3645                 }
3646         }
3647
3648         if (dsdb_flags & DSDB_SEARCH_NO_GLOBAL_CATALOG) {
3649                 ret = ldb_request_add_control(req,
3650                                               DSDB_CONTROL_NO_GLOBAL_CATALOG,
3651                                               false, NULL);
3652                 if (ret != LDB_SUCCESS) {
3653                         return ret;
3654                 }
3655         }
3656
3657         if (dsdb_flags & DSDB_SEARCH_SHOW_DELETED) {
3658                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_DELETED_OID, true, NULL);
3659                 if (ret != LDB_SUCCESS) {
3660                         return ret;
3661                 }
3662         }
3663
3664         if (dsdb_flags & DSDB_SEARCH_SHOW_RECYCLED) {
3665                 ret = ldb_request_add_control(req, LDB_CONTROL_SHOW_RECYCLED_OID, false, NULL);
3666                 if (ret != LDB_SUCCESS) {
3667                         return ret;
3668                 }
3669         }
3670
3671         if (dsdb_flags & DSDB_SEARCH_SHOW_DN_IN_STORAGE_FORMAT) {
3672                 ret = ldb_request_add_control(req, DSDB_CONTROL_DN_STORAGE_FORMAT_OID, false, NULL);
3673                 if (ret != LDB_SUCCESS) {
3674                         return ret;
3675                 }
3676         }
3677
3678         if (dsdb_flags & DSDB_SEARCH_SHOW_EXTENDED_DN) {
3679                 struct ldb_extended_dn_control *extended_ctrl = talloc(req, struct ldb_extended_dn_control);
3680                 if (!extended_ctrl) {
3681                         return LDB_ERR_OPERATIONS_ERROR;
3682                 }
3683                 extended_ctrl->type = 1;
3684
3685                 ret = ldb_request_add_control(req, LDB_CONTROL_EXTENDED_DN_OID, true, extended_ctrl);
3686                 if (ret != LDB_SUCCESS) {
3687                         return ret;
3688                 }
3689         }
3690
3691         if (dsdb_flags & DSDB_SEARCH_REVEAL_INTERNALS) {
3692                 ret = ldb_request_add_control(req, LDB_CONTROL_REVEAL_INTERNALS, false, NULL);
3693                 if (ret != LDB_SUCCESS) {
3694                         return ret;
3695                 }
3696         }
3697
3698         if (dsdb_flags & DSDB_MODIFY_RELAX) {
3699                 ret = ldb_request_add_control(req, LDB_CONTROL_RELAX_OID, false, NULL);
3700                 if (ret != LDB_SUCCESS) {
3701                         return ret;
3702                 }
3703         }
3704
3705         if (dsdb_flags & DSDB_MODIFY_PERMISSIVE) {
3706                 ret = ldb_request_add_control(req, LDB_CONTROL_PERMISSIVE_MODIFY_OID, false, NULL);
3707                 if (ret != LDB_SUCCESS) {
3708                         return ret;
3709                 }
3710         }
3711
3712         if (dsdb_flags & DSDB_FLAG_AS_SYSTEM) {
3713                 ret = ldb_request_add_control(req, LDB_CONTROL_AS_SYSTEM_OID, false, NULL);
3714                 if (ret != LDB_SUCCESS) {
3715                         return ret;
3716                 }
3717         }
3718
3719         if (dsdb_flags & DSDB_TREE_DELETE) {
3720                 ret = ldb_request_add_control(req, LDB_CONTROL_TREE_DELETE_OID, false, NULL);
3721                 if (ret != LDB_SUCCESS) {
3722                         return ret;
3723                 }
3724         }
3725
3726         if (dsdb_flags & DSDB_PROVISION) {
3727                 ret = ldb_request_add_control(req, LDB_CONTROL_PROVISION_OID, false, NULL);
3728                 if (ret != LDB_SUCCESS) {
3729                         return ret;
3730                 }
3731         }
3732
3733         /* This is a special control to bypass the password_hash module for use in pdb_samba4 for Samba3 upgrades */
3734         if (dsdb_flags & DSDB_BYPASS_PASSWORD_HASH) {
3735                 ret = ldb_request_add_control(req, DSDB_CONTROL_BYPASS_PASSWORD_HASH_OID, true, NULL);
3736                 if (ret != LDB_SUCCESS) {
3737                         return ret;
3738                 }
3739         }
3740
3741         if (dsdb_flags & DSDB_PASSWORD_BYPASS_LAST_SET) {
3742                 /* 
3743                  * This must not be critical, as it will only be
3744                  * handled (and need to be handled) if the other
3745                  * attributes in the request bring password_hash into
3746                  * action
3747                  */
3748                 ret = ldb_request_add_control(req, DSDB_CONTROL_PASSWORD_BYPASS_LAST_SET_OID, false, NULL);
3749                 if (ret != LDB_SUCCESS) {
3750                         return ret;
3751                 }
3752         }
3753
3754         if (dsdb_flags & DSDB_MODIFY_PARTIAL_REPLICA) {
3755                 ret = ldb_request_add_control(req, DSDB_CONTROL_PARTIAL_REPLICA, false, NULL);
3756                 if (ret != LDB_SUCCESS) {
3757                         return ret;
3758                 }
3759         }
3760
3761         return LDB_SUCCESS;
3762 }
3763
3764 /*
3765   an add with a set of controls
3766 */
3767 int dsdb_add(struct ldb_context *ldb, const struct ldb_message *message,
3768              uint32_t dsdb_flags)
3769 {
3770         struct ldb_request *req;
3771         int ret;
3772
3773         ret = ldb_build_add_req(&req, ldb, ldb,
3774                                 message,
3775                                 NULL,
3776                                 NULL,
3777                                 ldb_op_default_callback,
3778                                 NULL);
3779
3780         if (ret != LDB_SUCCESS) return ret;
3781
3782         ret = dsdb_request_add_controls(req, dsdb_flags);
3783         if (ret != LDB_SUCCESS) {
3784                 talloc_free(req);
3785                 return ret;
3786         }
3787
3788         ret = dsdb_autotransaction_request(ldb, req);
3789
3790         talloc_free(req);
3791         return ret;
3792 }
3793
3794 /*
3795   a modify with a set of controls
3796 */
3797 int dsdb_modify(struct ldb_context *ldb, const struct ldb_message *message,
3798                 uint32_t dsdb_flags)
3799 {
3800         struct ldb_request *req;
3801         int ret;
3802
3803         ret = ldb_build_mod_req(&req, ldb, ldb,
3804                                 message,
3805                                 NULL,
3806                                 NULL,
3807                                 ldb_op_default_callback,
3808                                 NULL);
3809
3810         if (ret != LDB_SUCCESS) return ret;
3811
3812         ret = dsdb_request_add_controls(req, dsdb_flags);
3813         if (ret != LDB_SUCCESS) {
3814                 talloc_free(req);
3815                 return ret;
3816         }
3817
3818         ret = dsdb_autotransaction_request(ldb, req);
3819
3820         talloc_free(req);
3821         return ret;
3822 }
3823
3824 /*
3825   a delete with a set of flags
3826 */
3827 int dsdb_delete(struct ldb_context *ldb, struct ldb_dn *dn,
3828                 uint32_t dsdb_flags)
3829 {
3830         struct ldb_request *req;
3831         int ret;
3832
3833         ret = ldb_build_del_req(&req, ldb, ldb,
3834                                 dn,
3835                                 NULL,
3836                                 NULL,
3837                                 ldb_op_default_callback,
3838                                 NULL);
3839
3840         if (ret != LDB_SUCCESS) return ret;
3841
3842         ret = dsdb_request_add_controls(req, dsdb_flags);
3843         if (ret != LDB_SUCCESS) {
3844                 talloc_free(req);
3845                 return ret;
3846         }
3847
3848         ret = dsdb_autotransaction_request(ldb, req);
3849
3850         talloc_free(req);
3851         return ret;
3852 }
3853
3854 /*
3855   like dsdb_modify() but set all the element flags to
3856   LDB_FLAG_MOD_REPLACE
3857  */
3858 int dsdb_replace(struct ldb_context *ldb, struct ldb_message *msg, uint32_t dsdb_flags)
3859 {
3860         unsigned int i;
3861
3862         /* mark all the message elements as LDB_FLAG_MOD_REPLACE */
3863         for (i=0;i<msg->num_elements;i++) {
3864                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
3865         }
3866
3867         return dsdb_modify(ldb, msg, dsdb_flags);
3868 }
3869
3870
3871 /*
3872   search for attrs on one DN, allowing for dsdb_flags controls
3873  */
3874 int dsdb_search_dn(struct ldb_context *ldb,
3875                    TALLOC_CTX *mem_ctx,
3876                    struct ldb_result **_result,
3877                    struct ldb_dn *basedn,
3878                    const char * const *attrs,
3879                    uint32_t dsdb_flags)
3880 {
3881         int ret;
3882         struct ldb_request *req;
3883         struct ldb_result *res;
3884
3885         res = talloc_zero(mem_ctx, struct ldb_result);
3886         if (!res) {
3887                 return ldb_oom(ldb);
3888         }
3889
3890         ret = ldb_build_search_req(&req, ldb, res,
3891                                    basedn,
3892                                    LDB_SCOPE_BASE,
3893                                    NULL,
3894                                    attrs,
3895                                    NULL,
3896                                    res,
3897                                    ldb_search_default_callback,
3898                                    NULL);
3899         if (ret != LDB_SUCCESS) {
3900                 talloc_free(res);
3901                 return ret;
3902         }
3903
3904         ret = dsdb_request_add_controls(req, dsdb_flags);
3905         if (ret != LDB_SUCCESS) {
3906                 talloc_free(res);
3907                 return ret;
3908         }
3909
3910         ret = ldb_request(ldb, req);
3911         if (ret == LDB_SUCCESS) {
3912                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
3913         }
3914
3915         talloc_free(req);
3916         if (ret != LDB_SUCCESS) {
3917                 talloc_free(res);
3918                 return ret;
3919         }
3920
3921         *_result = res;
3922         return LDB_SUCCESS;
3923 }
3924
3925 /*
3926   search for attrs on one DN, by the GUID of the DN, allowing for
3927   dsdb_flags controls
3928  */
3929 int dsdb_search_by_dn_guid(struct ldb_context *ldb,
3930                            TALLOC_CTX *mem_ctx,
3931                            struct ldb_result **_result,
3932                            const struct GUID *guid,
3933                            const char * const *attrs,
3934                            uint32_t dsdb_flags)
3935 {
3936         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3937         struct ldb_dn *dn;
3938         int ret;
3939
3940         dn = ldb_dn_new_fmt(tmp_ctx, ldb, "<GUID=%s>", GUID_string(tmp_ctx, guid));
3941         if (dn == NULL) {
3942                 talloc_free(tmp_ctx);
3943                 return ldb_oom(ldb);
3944         }
3945
3946         ret = dsdb_search_dn(ldb, mem_ctx, _result, dn, attrs, dsdb_flags);
3947         talloc_free(tmp_ctx);
3948         return ret;
3949 }
3950
3951 /*
3952   general search with dsdb_flags for controls
3953  */
3954 int dsdb_search(struct ldb_context *ldb,
3955                 TALLOC_CTX *mem_ctx,
3956                 struct ldb_result **_result,
3957                 struct ldb_dn *basedn,
3958                 enum ldb_scope scope,
3959                 const char * const *attrs,
3960                 uint32_t dsdb_flags,
3961                 const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
3962 {
3963         int ret;
3964         struct ldb_request *req;
3965         struct ldb_result *res;
3966         va_list ap;
3967         char *expression = NULL;
3968         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
3969
3970         /* cross-partitions searches with a basedn break multi-domain support */
3971         SMB_ASSERT(basedn == NULL || (dsdb_flags & DSDB_SEARCH_SEARCH_ALL_PARTITIONS) == 0);
3972
3973         res = talloc_zero(tmp_ctx, struct ldb_result);
3974         if (!res) {
3975                 talloc_free(tmp_ctx);
3976                 return ldb_oom(ldb);
3977         }
3978
3979         if (exp_fmt) {
3980                 va_start(ap, exp_fmt);
3981                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
3982                 va_end(ap);
3983
3984                 if (!expression) {
3985                         talloc_free(tmp_ctx);
3986                         return ldb_oom(ldb);
3987                 }
3988         }
3989
3990         ret = ldb_build_search_req(&req, ldb, tmp_ctx,
3991                                    basedn,
3992                                    scope,
3993                                    expression,
3994                                    attrs,
3995                                    NULL,
3996                                    res,
3997                                    ldb_search_default_callback,
3998                                    NULL);
3999         if (ret != LDB_SUCCESS) {
4000                 talloc_free(tmp_ctx);
4001                 return ret;
4002         }
4003
4004         ret = dsdb_request_add_controls(req, dsdb_flags);
4005         if (ret != LDB_SUCCESS) {
4006                 talloc_free(tmp_ctx);
4007                 ldb_reset_err_string(ldb);
4008                 return ret;
4009         }
4010
4011         ret = ldb_request(ldb, req);
4012         if (ret == LDB_SUCCESS) {
4013                 ret = ldb_wait(req->handle, LDB_WAIT_ALL);
4014         }
4015
4016         if (ret != LDB_SUCCESS) {
4017                 talloc_free(tmp_ctx);
4018                 return ret;
4019         }
4020
4021         if (dsdb_flags & DSDB_SEARCH_ONE_ONLY) {
4022                 if (res->count == 0) {
4023                         talloc_free(tmp_ctx);
4024                         ldb_reset_err_string(ldb);
4025                         return LDB_ERR_NO_SUCH_OBJECT;
4026                 }
4027                 if (res->count != 1) {
4028                         talloc_free(tmp_ctx);
4029                         ldb_reset_err_string(ldb);
4030                         return LDB_ERR_CONSTRAINT_VIOLATION;
4031                 }
4032         }
4033
4034         *_result = talloc_steal(mem_ctx, res);
4035         talloc_free(tmp_ctx);
4036
4037         return LDB_SUCCESS;
4038 }
4039
4040
4041 /*
4042   general search with dsdb_flags for controls
4043   returns exactly 1 record or an error
4044  */
4045 int dsdb_search_one(struct ldb_context *ldb,
4046                     TALLOC_CTX *mem_ctx,
4047                     struct ldb_message **msg,
4048                     struct ldb_dn *basedn,
4049                     enum ldb_scope scope,
4050                     const char * const *attrs,
4051                     uint32_t dsdb_flags,
4052                     const char *exp_fmt, ...) _PRINTF_ATTRIBUTE(8, 9)
4053 {
4054         int ret;
4055         struct ldb_result *res;
4056         va_list ap;
4057         char *expression = NULL;
4058         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
4059
4060         dsdb_flags |= DSDB_SEARCH_ONE_ONLY;
4061
4062         res = talloc_zero(tmp_ctx, struct ldb_result);
4063         if (!res) {
4064                 talloc_free(tmp_ctx);
4065                 return ldb_oom(ldb);
4066         }
4067
4068         if (exp_fmt) {
4069                 va_start(ap, exp_fmt);
4070                 expression = talloc_vasprintf(tmp_ctx, exp_fmt, ap);
4071                 va_end(ap);
4072
4073                 if (!expression) {
4074                         talloc_free(tmp_ctx);
4075                         return ldb_oom(ldb);
4076                 }
4077                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4078                                   dsdb_flags, "%s", expression);
4079         } else {
4080                 ret = dsdb_search(ldb, tmp_ctx, &res, basedn, scope, attrs,
4081                                   dsdb_flags, NULL);
4082         }
4083
4084         if (ret != LDB_SUCCESS) {
4085                 talloc_free(tmp_ctx);
4086                 return ret;
4087         }
4088
4089         *msg = talloc_steal(mem_ctx, res->msgs[0]);
4090         talloc_free(tmp_ctx);
4091
4092         return LDB_SUCCESS;
4093 }
4094
4095 /* returns back the forest DNS name */
4096 const char *samdb_forest_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4097 {
4098         const char *forest_name = ldb_dn_canonical_string(mem_ctx,
4099                                                           ldb_get_root_basedn(ldb));
4100         char *p;
4101
4102         if (forest_name == NULL) {
4103                 return NULL;
4104         }
4105
4106         p = strchr(forest_name, '/');
4107         if (p) {
4108                 *p = '\0';
4109         }
4110
4111         return forest_name;
4112 }
4113
4114 /* returns back the default domain DNS name */
4115 const char *samdb_default_domain_name(struct ldb_context *ldb, TALLOC_CTX *mem_ctx)
4116 {
4117         const char *domain_name = ldb_dn_canonical_string(mem_ctx,
4118                                                           ldb_get_default_basedn(ldb));
4119         char *p;
4120
4121         if (domain_name == NULL) {
4122                 return NULL;
4123         }
4124
4125         p = strchr(domain_name, '/');
4126         if (p) {
4127                 *p = '\0';
4128         }
4129
4130         return domain_name;
4131 }
4132
4133 /*
4134    validate that an DSA GUID belongs to the specified user sid.
4135    The user SID must be a domain controller account (either RODC or
4136    RWDC)
4137  */
4138 int dsdb_validate_dsa_guid(struct ldb_context *ldb,
4139                            const struct GUID *dsa_guid,
4140                            const struct dom_sid *sid)
4141 {
4142         /* strategy:
4143             - find DN of record with the DSA GUID in the
4144               configuration partition (objectGUID)
4145             - remove "NTDS Settings" component from DN
4146             - do a base search on that DN for serverReference with
4147               extended-dn enabled
4148             - extract objectSid from resulting serverReference
4149               attribute
4150             - check this sid matches the sid argument
4151         */
4152         struct ldb_dn *config_dn;
4153         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4154         struct ldb_message *msg;
4155         const char *attrs1[] = { NULL };
4156         const char *attrs2[] = { "serverReference", NULL };
4157         int ret;
4158         struct ldb_dn *dn, *account_dn;
4159         struct dom_sid sid2;
4160         NTSTATUS status;
4161
4162         config_dn = ldb_get_config_basedn(ldb);
4163
4164         ret = dsdb_search_one(ldb, tmp_ctx, &msg, config_dn, LDB_SCOPE_SUBTREE,
4165                               attrs1, 0, "(&(objectGUID=%s)(objectClass=nTDSDSA))", GUID_string(tmp_ctx, dsa_guid));
4166         if (ret != LDB_SUCCESS) {
4167                 DEBUG(1,(__location__ ": Failed to find DSA objectGUID %s for sid %s\n",
4168                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4169                 talloc_free(tmp_ctx);
4170                 return ldb_operr(ldb);
4171         }
4172         dn = msg->dn;
4173
4174         if (!ldb_dn_remove_child_components(dn, 1)) {
4175                 talloc_free(tmp_ctx);
4176                 return ldb_operr(ldb);
4177         }
4178
4179         ret = dsdb_search_one(ldb, tmp_ctx, &msg, dn, LDB_SCOPE_BASE,
4180                               attrs2, DSDB_SEARCH_SHOW_EXTENDED_DN,
4181                               "(objectClass=server)");
4182         if (ret != LDB_SUCCESS) {
4183                 DEBUG(1,(__location__ ": Failed to find server record for DSA with objectGUID %s, sid %s\n",
4184                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4185                 talloc_free(tmp_ctx);
4186                 return ldb_operr(ldb);
4187         }
4188
4189         account_dn = ldb_msg_find_attr_as_dn(ldb, tmp_ctx, msg, "serverReference");
4190         if (account_dn == NULL) {
4191                 DEBUG(1,(__location__ ": Failed to find account_dn for DSA with objectGUID %s, sid %s\n",
4192                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4193                 talloc_free(tmp_ctx);
4194                 return ldb_operr(ldb);
4195         }
4196
4197         status = dsdb_get_extended_dn_sid(account_dn, &sid2, "SID");
4198         if (!NT_STATUS_IS_OK(status)) {
4199                 DEBUG(1,(__location__ ": Failed to find SID for DSA with objectGUID %s, sid %s\n",
4200                          GUID_string(tmp_ctx, dsa_guid), dom_sid_string(tmp_ctx, sid)));
4201                 talloc_free(tmp_ctx);
4202                 return ldb_operr(ldb);
4203         }
4204
4205         if (!dom_sid_equal(sid, &sid2)) {
4206                 /* someone is trying to spoof another account */
4207                 DEBUG(0,(__location__ ": Bad DSA objectGUID %s for sid %s - expected sid %s\n",
4208                          GUID_string(tmp_ctx, dsa_guid),
4209                          dom_sid_string(tmp_ctx, sid),
4210                          dom_sid_string(tmp_ctx, &sid2)));
4211                 talloc_free(tmp_ctx);
4212                 return ldb_operr(ldb);
4213         }
4214
4215         talloc_free(tmp_ctx);
4216         return LDB_SUCCESS;
4217 }
4218
4219 static const char * const secret_attributes[] = {
4220         DSDB_SECRET_ATTRIBUTES,
4221         NULL
4222 };
4223
4224 /*
4225   check if the attribute belongs to the RODC filtered attribute set
4226   Note that attributes that are in the filtered attribute set are the
4227   ones that _are_ always sent to a RODC
4228 */
4229 bool dsdb_attr_in_rodc_fas(const struct dsdb_attribute *sa)
4230 {
4231         /* they never get secret attributes */
4232         if (is_attr_in_list(secret_attributes, sa->lDAPDisplayName)) {
4233                 return false;
4234         }
4235
4236         /* they do get non-secret critical attributes */
4237         if (sa->schemaFlagsEx & SCHEMA_FLAG_ATTR_IS_CRITICAL) {
4238                 return true;
4239         }
4240
4241         /* they do get non-secret attributes marked as being in the FAS  */
4242         if (sa->searchFlags & SEARCH_FLAG_RODC_ATTRIBUTE) {
4243                 return true;
4244         }
4245
4246         /* other attributes are denied */
4247         return false;
4248 }
4249
4250 /* return fsmo role dn and role owner dn for a particular role*/
4251 WERROR dsdb_get_fsmo_role_info(TALLOC_CTX *tmp_ctx,
4252                                struct ldb_context *ldb,
4253                                uint32_t role,
4254                                struct ldb_dn **fsmo_role_dn,
4255                                struct ldb_dn **role_owner_dn)
4256 {
4257         int ret;
4258         switch (role) {
4259         case DREPL_NAMING_MASTER:
4260                 *fsmo_role_dn = samdb_partitions_dn(ldb, tmp_ctx);
4261                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4262                 if (ret != LDB_SUCCESS) {
4263                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Naming Master object - %s",
4264                                  ldb_errstring(ldb)));
4265                         talloc_free(tmp_ctx);
4266                         return WERR_DS_DRA_INTERNAL_ERROR;
4267                 }
4268                 break;
4269         case DREPL_INFRASTRUCTURE_MASTER:
4270                 *fsmo_role_dn = samdb_infrastructure_dn(ldb, tmp_ctx);
4271                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4272                 if (ret != LDB_SUCCESS) {
4273                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4274                                  ldb_errstring(ldb)));
4275                         talloc_free(tmp_ctx);
4276                         return WERR_DS_DRA_INTERNAL_ERROR;
4277                 }
4278                 break;
4279         case DREPL_RID_MASTER:
4280                 ret = samdb_rid_manager_dn(ldb, tmp_ctx, fsmo_role_dn);
4281                 if (ret != LDB_SUCCESS) {
4282                         DEBUG(0, (__location__ ": Failed to find RID Manager object - %s", ldb_errstring(ldb)));
4283                         talloc_free(tmp_ctx);
4284                         return WERR_DS_DRA_INTERNAL_ERROR;
4285                 }
4286
4287                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4288                 if (ret != LDB_SUCCESS) {
4289                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in RID Manager object - %s",
4290                                  ldb_errstring(ldb)));
4291                         talloc_free(tmp_ctx);
4292                         return WERR_DS_DRA_INTERNAL_ERROR;
4293                 }
4294                 break;
4295         case DREPL_SCHEMA_MASTER:
4296                 *fsmo_role_dn = ldb_get_schema_basedn(ldb);
4297                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4298                 if (ret != LDB_SUCCESS) {
4299                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Schema Master object - %s",
4300                                  ldb_errstring(ldb)));
4301                         talloc_free(tmp_ctx);
4302                         return WERR_DS_DRA_INTERNAL_ERROR;
4303                 }
4304                 break;
4305         case DREPL_PDC_MASTER:
4306                 *fsmo_role_dn = ldb_get_default_basedn(ldb);
4307                 ret = samdb_reference_dn(ldb, tmp_ctx, *fsmo_role_dn, "fSMORoleOwner", role_owner_dn);
4308                 if (ret != LDB_SUCCESS) {
4309                         DEBUG(0,(__location__ ": Failed to find fSMORoleOwner in Pd Master object - %s",
4310                                  ldb_errstring(ldb)));
4311                         talloc_free(tmp_ctx);
4312                         return WERR_DS_DRA_INTERNAL_ERROR;
4313                 }
4314                 break;
4315         default:
4316                 return WERR_DS_DRA_INTERNAL_ERROR;
4317         }
4318         return WERR_OK;
4319 }
4320
4321 const char *samdb_dn_to_dnshostname(struct ldb_context *ldb,
4322                                     TALLOC_CTX *mem_ctx,
4323                                     struct ldb_dn *server_dn)
4324 {
4325         int ldb_ret;
4326         struct ldb_result *res = NULL;
4327         const char * const attrs[] = { "dNSHostName", NULL};
4328
4329         ldb_ret = ldb_search(ldb, mem_ctx, &res,
4330                              server_dn,
4331                              LDB_SCOPE_BASE,
4332                              attrs, NULL);
4333         if (ldb_ret != LDB_SUCCESS) {
4334                 DEBUG(4, ("Failed to find dNSHostName for dn %s, ldb error: %s",
4335                           ldb_dn_get_linearized(server_dn), ldb_errstring(ldb)));
4336                 return NULL;
4337         }
4338
4339         return ldb_msg_find_attr_as_string(res->msgs[0], "dNSHostName", NULL);
4340 }
4341
4342 /*
4343   returns true if an attribute is in the filter,
4344   false otherwise, provided that attribute value is provided with the expression
4345 */
4346 bool dsdb_attr_in_parse_tree(struct ldb_parse_tree *tree,
4347                              const char *attr)
4348 {
4349        unsigned int i;
4350        switch (tree->operation) {
4351        case LDB_OP_AND:
4352        case LDB_OP_OR:
4353                for (i=0;i<tree->u.list.num_elements;i++) {
4354                        if (dsdb_attr_in_parse_tree(tree->u.list.elements[i],
4355                                                        attr))
4356                                return true;
4357                }
4358                return false;
4359        case LDB_OP_NOT:
4360                return dsdb_attr_in_parse_tree(tree->u.isnot.child, attr);
4361        case LDB_OP_EQUALITY:
4362        case LDB_OP_GREATER:
4363        case LDB_OP_LESS:
4364        case LDB_OP_APPROX:
4365                if (ldb_attr_cmp(tree->u.equality.attr, attr) == 0) {
4366                        return true;
4367                }
4368                return false;
4369        case LDB_OP_SUBSTRING:
4370                if (ldb_attr_cmp(tree->u.substring.attr, attr) == 0) {
4371                        return true;
4372                }
4373                return false;
4374        case LDB_OP_PRESENT:
4375                /* (attrname=*) is not filtered out */
4376                return false;
4377        case LDB_OP_EXTENDED:
4378                if (tree->u.extended.attr &&
4379                    ldb_attr_cmp(tree->u.extended.attr, attr) == 0) {
4380                        return true;
4381                }
4382                return false;
4383        }
4384        return false;
4385 }
4386
4387 bool is_attr_in_list(const char * const * attrs, const char *attr)
4388 {
4389         unsigned int i;
4390
4391         for (i = 0; attrs[i]; i++) {
4392                 if (ldb_attr_cmp(attrs[i], attr) == 0)
4393                         return true;
4394         }
4395
4396         return false;
4397 }
4398
4399
4400 /*
4401   map an ldb error code to an approximate NTSTATUS code
4402  */
4403 NTSTATUS dsdb_ldb_err_to_ntstatus(int err)
4404 {
4405         switch (err) {
4406         case LDB_SUCCESS:
4407                 return NT_STATUS_OK;
4408
4409         case LDB_ERR_PROTOCOL_ERROR:
4410                 return NT_STATUS_DEVICE_PROTOCOL_ERROR;
4411
4412         case LDB_ERR_TIME_LIMIT_EXCEEDED:
4413                 return NT_STATUS_IO_TIMEOUT;
4414
4415         case LDB_ERR_SIZE_LIMIT_EXCEEDED:
4416                 return NT_STATUS_BUFFER_TOO_SMALL;
4417
4418         case LDB_ERR_COMPARE_FALSE:
4419         case LDB_ERR_COMPARE_TRUE:
4420                 return NT_STATUS_REVISION_MISMATCH;
4421
4422         case LDB_ERR_AUTH_METHOD_NOT_SUPPORTED:
4423                 return NT_STATUS_NOT_SUPPORTED;
4424
4425         case LDB_ERR_STRONG_AUTH_REQUIRED:
4426         case LDB_ERR_CONFIDENTIALITY_REQUIRED:
4427         case LDB_ERR_SASL_BIND_IN_PROGRESS:
4428         case LDB_ERR_INAPPROPRIATE_AUTHENTICATION:
4429         case LDB_ERR_INVALID_CREDENTIALS:
4430         case LDB_ERR_INSUFFICIENT_ACCESS_RIGHTS:
4431         case LDB_ERR_UNWILLING_TO_PERFORM:
4432                 return NT_STATUS_ACCESS_DENIED;
4433
4434         case LDB_ERR_NO_SUCH_OBJECT:
4435                 return NT_STATUS_OBJECT_NAME_NOT_FOUND;
4436
4437         case LDB_ERR_REFERRAL:
4438         case LDB_ERR_NO_SUCH_ATTRIBUTE:
4439                 return NT_STATUS_NOT_FOUND;
4440
4441         case LDB_ERR_UNSUPPORTED_CRITICAL_EXTENSION:
4442                 return NT_STATUS_NOT_SUPPORTED;
4443
4444         case LDB_ERR_ADMIN_LIMIT_EXCEEDED:
4445                 return NT_STATUS_BUFFER_TOO_SMALL;
4446
4447         case LDB_ERR_UNDEFINED_ATTRIBUTE_TYPE:
4448         case LDB_ERR_INAPPROPRIATE_MATCHING:
4449         case LDB_ERR_CONSTRAINT_VIOLATION:
4450         case LDB_ERR_INVALID_ATTRIBUTE_SYNTAX:
4451         case LDB_ERR_INVALID_DN_SYNTAX:
4452         case LDB_ERR_NAMING_VIOLATION:
4453         case LDB_ERR_OBJECT_CLASS_VIOLATION:
4454         case LDB_ERR_NOT_ALLOWED_ON_NON_LEAF:
4455         case LDB_ERR_NOT_ALLOWED_ON_RDN:
4456                 return NT_STATUS_INVALID_PARAMETER;
4457
4458         case LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS:
4459         case LDB_ERR_ENTRY_ALREADY_EXISTS:
4460                 return NT_STATUS_ERROR_DS_OBJ_STRING_NAME_EXISTS;
4461
4462         case LDB_ERR_BUSY:
4463                 return NT_STATUS_NETWORK_BUSY;
4464
4465         case LDB_ERR_ALIAS_PROBLEM:
4466         case LDB_ERR_ALIAS_DEREFERENCING_PROBLEM:
4467         case LDB_ERR_UNAVAILABLE:
4468         case LDB_ERR_LOOP_DETECT:
4469         case LDB_ERR_OBJECT_CLASS_MODS_PROHIBITED:
4470         case LDB_ERR_AFFECTS_MULTIPLE_DSAS:
4471         case LDB_ERR_OTHER:
4472         case LDB_ERR_OPERATIONS_ERROR:
4473                 break;
4474         }
4475         return NT_STATUS_UNSUCCESSFUL;
4476 }
4477
4478
4479 /*
4480   create a new naming context that will hold a partial replica
4481  */
4482 int dsdb_create_partial_replica_NC(struct ldb_context *ldb,  struct ldb_dn *dn)
4483 {
4484         TALLOC_CTX *tmp_ctx = talloc_new(ldb);
4485         struct ldb_message *msg;
4486         int ret;
4487
4488         msg = ldb_msg_new(tmp_ctx);
4489         if (msg == NULL) {
4490                 talloc_free(tmp_ctx);
4491                 return ldb_oom(ldb);
4492         }
4493
4494         msg->dn = dn;
4495         ret = ldb_msg_add_string(msg, "objectClass", "top");
4496         if (ret != LDB_SUCCESS) {
4497                 talloc_free(tmp_ctx);
4498                 return ldb_oom(ldb);
4499         }
4500
4501         /* [MS-DRSR] implies that we should only add the 'top'
4502          * objectclass, but that would cause lots of problems with our
4503          * objectclass code as top is not structural, so we add
4504          * 'domainDNS' as well to keep things sane. We're expecting
4505          * this new NC to be of objectclass domainDNS after
4506          * replication anyway
4507          */
4508         ret = ldb_msg_add_string(msg, "objectClass", "domainDNS");
4509         if (ret != LDB_SUCCESS) {
4510                 talloc_free(tmp_ctx);
4511                 return ldb_oom(ldb);
4512         }
4513
4514         ret = ldb_msg_add_fmt(msg, "instanceType", "%u",
4515                               INSTANCE_TYPE_IS_NC_HEAD|
4516                               INSTANCE_TYPE_NC_ABOVE|
4517                               INSTANCE_TYPE_UNINSTANT);
4518         if (ret != LDB_SUCCESS) {
4519                 talloc_free(tmp_ctx);
4520                 return ldb_oom(ldb);
4521         }
4522
4523         ret = dsdb_add(ldb, msg, DSDB_MODIFY_PARTIAL_REPLICA);
4524         if (ret != LDB_SUCCESS && ret != LDB_ERR_ENTRY_ALREADY_EXISTS) {
4525                 DEBUG(0,("Failed to create new NC for %s - %s (%s)\n",
4526                          ldb_dn_get_linearized(dn),
4527                          ldb_errstring(ldb), ldb_strerror(ret)));
4528                 talloc_free(tmp_ctx);
4529                 return ret;
4530         }
4531
4532         DEBUG(1,("Created new NC for %s\n", ldb_dn_get_linearized(dn)));
4533
4534         talloc_free(tmp_ctx);
4535         return LDB_SUCCESS;
4536 }
4537
4538 /**
4539   build a GUID from a string
4540 */
4541 _PUBLIC_ NTSTATUS NS_GUID_from_string(const char *s, struct GUID *guid)
4542 {
4543         NTSTATUS status = NT_STATUS_INVALID_PARAMETER;
4544         uint32_t time_low;
4545         uint32_t time_mid, time_hi_and_version;
4546         uint32_t clock_seq[2];
4547         uint32_t node[6];
4548         int i;
4549
4550         if (s == NULL) {
4551                 return NT_STATUS_INVALID_PARAMETER;
4552         }
4553
4554         if (11 == sscanf(s, "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
4555                          &time_low, &time_mid, &time_hi_and_version, 
4556                          &clock_seq[0], &clock_seq[1],
4557                          &node[0], &node[1], &node[2], &node[3], &node[4], &node[5])) {
4558                 status = NT_STATUS_OK;
4559         }
4560
4561         if (!NT_STATUS_IS_OK(status)) {
4562                 return status;
4563         }
4564
4565         guid->time_low = time_low;
4566         guid->time_mid = time_mid;
4567         guid->time_hi_and_version = time_hi_and_version;
4568         guid->clock_seq[0] = clock_seq[0];
4569         guid->clock_seq[1] = clock_seq[1];
4570         for (i=0;i<6;i++) {
4571                 guid->node[i] = node[i];
4572         }
4573
4574         return NT_STATUS_OK;
4575 }
4576
4577 _PUBLIC_ char *NS_GUID_string(TALLOC_CTX *mem_ctx, const struct GUID *guid)
4578 {
4579         return talloc_asprintf(mem_ctx, 
4580                                "%08x-%04x%04x-%02x%02x%02x%02x-%02x%02x%02x%02x",
4581                                guid->time_low, guid->time_mid,
4582                                guid->time_hi_and_version,
4583                                guid->clock_seq[0],
4584                                guid->clock_seq[1],
4585                                guid->node[0], guid->node[1],
4586                                guid->node[2], guid->node[3],
4587                                guid->node[4], guid->node[5]);
4588 }