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