s3-passdb: split out passdb/pdb_nds.h.
[bbaumbach/samba-autobuild/.git] / source3 / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/CIFS implementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Jean François Micouleau        1998
5    Copyright (C) Gerald Carter                  2001-2003
6    Copyright (C) Shahms King                    2001
7    Copyright (C) Andrew Bartlett                2002-2003
8    Copyright (C) Stefan (metze) Metzmacher      2002-2003
9    Copyright (C) Simo Sorce                     2006
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
24 */
25
26 /* TODO:
27 *  persistent connections: if using NSS LDAP, many connections are made
28 *      however, using only one within Samba would be nice
29 *  
30 *  Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
31 *
32 *  Other LDAP based login attributes: accountExpires, etc.
33 *  (should be the domain of Samba proper, but the sam_password/struct samu
34 *  structures don't have fields for some of these attributes)
35 *
36 *  SSL is done, but can't get the certificate based authentication to work
37 *  against on my test platform (Linux 2.4, OpenLDAP 2.x)
38 */
39
40 /* NOTE: this will NOT work against an Active Directory server
41 *  due to the fact that the two password fields cannot be retrieved
42 *  from a server; recommend using security = domain in this situation
43 *  and/or winbind
44 */
45
46 #include "includes.h"
47 #include "passdb.h"
48 #include "../libcli/auth/libcli_auth.h"
49 #include "secrets.h"
50 #include "idmap_cache.h"
51 #include "../libcli/security/security.h"
52 #include "../lib/util/util_pw.h"
53 #include "lib/winbind_util.h"
54
55 #undef DBGC_CLASS
56 #define DBGC_CLASS DBGC_PASSDB
57
58 #include <lber.h>
59 #include <ldap.h>
60
61
62 #include "smbldap.h"
63 #include "passdb/pdb_ldap.h"
64 #include "passdb/pdb_nds.h"
65
66 /**********************************************************************
67  Simple helper function to make stuff better readable
68  **********************************************************************/
69
70 LDAP *priv2ld(struct ldapsam_privates *priv)
71 {
72         return priv->smbldap_state->ldap_struct;
73 }
74
75 /**********************************************************************
76  Get the attribute name given a user schame version.
77  **********************************************************************/
78  
79 static const char* get_userattr_key2string( int schema_ver, int key )
80 {
81         switch ( schema_ver ) {
82                 case SCHEMAVER_SAMBAACCOUNT:
83                         return get_attr_key2string( attrib_map_v22, key );
84
85                 case SCHEMAVER_SAMBASAMACCOUNT:
86                         return get_attr_key2string( attrib_map_v30, key );
87
88                 default:
89                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
90                         break;
91         }
92         return NULL;
93 }
94
95 /**********************************************************************
96  Return the list of attribute names given a user schema version.
97 **********************************************************************/
98
99 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
100 {
101         switch ( schema_ver ) {
102                 case SCHEMAVER_SAMBAACCOUNT:
103                         return get_attr_list( mem_ctx, attrib_map_v22 );
104
105                 case SCHEMAVER_SAMBASAMACCOUNT:
106                         return get_attr_list( mem_ctx, attrib_map_v30 );
107                 default:
108                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
109                         break;
110         }
111
112         return NULL;
113 }
114
115 /**************************************************************************
116  Return the list of attribute names to delete given a user schema version.
117 **************************************************************************/
118
119 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
120                                               int schema_ver )
121 {
122         switch ( schema_ver ) {
123                 case SCHEMAVER_SAMBAACCOUNT:
124                         return get_attr_list( mem_ctx,
125                                               attrib_map_to_delete_v22 );
126
127                 case SCHEMAVER_SAMBASAMACCOUNT:
128                         return get_attr_list( mem_ctx,
129                                               attrib_map_to_delete_v30 );
130                 default:
131                         DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
132                         break;
133         }
134
135         return NULL;
136 }
137
138
139 /*******************************************************************
140  Generate the LDAP search filter for the objectclass based on the 
141  version of the schema we are using.
142 ******************************************************************/
143
144 static const char* get_objclass_filter( int schema_ver )
145 {
146         fstring objclass_filter;
147         char *result;
148
149         switch( schema_ver ) {
150                 case SCHEMAVER_SAMBAACCOUNT:
151                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
152                         break;
153                 case SCHEMAVER_SAMBASAMACCOUNT:
154                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
155                         break;
156                 default:
157                         DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
158                         objclass_filter[0] = '\0';
159                         break;
160         }
161
162         result = talloc_strdup(talloc_tos(), objclass_filter);
163         SMB_ASSERT(result != NULL);
164         return result;
165 }
166
167 /*****************************************************************
168  Scan a sequence number off OpenLDAP's syncrepl contextCSN
169 ******************************************************************/
170
171 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
172 {
173         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
174         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
175         LDAPMessage *msg = NULL;
176         LDAPMessage *entry = NULL;
177         TALLOC_CTX *mem_ctx;
178         char **values = NULL;
179         int rc, num_result, num_values, rid;
180         char *suffix = NULL;
181         char *tok;
182         const char *p;
183         const char **attrs;
184
185         /* Unfortunatly there is no proper way to detect syncrepl-support in
186          * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
187          * but do not show up in the root-DSE yet. Neither we can query the
188          * subschema-context for the syncProviderSubentry or syncConsumerSubentry
189          * objectclass. Currently we require lp_ldap_suffix() to show up as
190          * namingContext.  -  Guenther
191          */
192
193         if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
194                 return ntstatus;
195         }
196
197         if (!seq_num) {
198                 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
199                 return ntstatus;
200         }
201
202         if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix())) {
203                 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
204                          "as top-level namingContext\n", lp_ldap_suffix()));
205                 return ntstatus;
206         }
207
208         mem_ctx = talloc_init("ldapsam_get_seq_num");
209
210         if (mem_ctx == NULL)
211                 return NT_STATUS_NO_MEMORY;
212
213         if ((attrs = talloc_array(mem_ctx, const char *, 2)) == NULL) {
214                 ntstatus = NT_STATUS_NO_MEMORY;
215                 goto done;
216         }
217
218         /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
219         rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
220         if (rid > 0) {
221
222                 /* consumer syncreplCookie: */
223                 /* csn=20050126161620Z#0000001#00#00000 */
224                 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
225                 attrs[1] = NULL;
226                 suffix = talloc_asprintf(mem_ctx,
227                                 "cn=syncrepl%d,%s", rid, lp_ldap_suffix());
228                 if (!suffix) {
229                         ntstatus = NT_STATUS_NO_MEMORY;
230                         goto done;
231                 }
232         } else {
233
234                 /* provider contextCSN */
235                 /* 20050126161620Z#000009#00#000000 */
236                 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
237                 attrs[1] = NULL;
238                 suffix = talloc_asprintf(mem_ctx,
239                                 "cn=ldapsync,%s", lp_ldap_suffix());
240
241                 if (!suffix) {
242                         ntstatus = NT_STATUS_NO_MEMORY;
243                         goto done;
244                 }
245         }
246
247         rc = smbldap_search(ldap_state->smbldap_state, suffix,
248                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
249
250         if (rc != LDAP_SUCCESS) {
251                 goto done;
252         }
253
254         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
255         if (num_result != 1) {
256                 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
257                 goto done;
258         }
259
260         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
261         if (entry == NULL) {
262                 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
263                 goto done;
264         }
265
266         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
267         if (values == NULL) {
268                 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
269                 goto done;
270         }
271
272         num_values = ldap_count_values(values);
273         if (num_values == 0) {
274                 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
275                 goto done;
276         }
277
278         p = values[0];
279         if (!next_token_talloc(mem_ctx, &p, &tok, "#")) {
280                 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
281                 goto done;
282         }
283
284         p = tok;
285         if (!strncmp(p, "csn=", strlen("csn=")))
286                 p += strlen("csn=");
287
288         DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
289
290         *seq_num = generalized_to_unix_time(p);
291
292         /* very basic sanity check */
293         if (*seq_num <= 0) {
294                 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n", 
295                         (int)*seq_num));
296                 goto done;
297         }
298
299         ntstatus = NT_STATUS_OK;
300
301  done:
302         if (values != NULL)
303                 ldap_value_free(values);
304         if (msg != NULL)
305                 ldap_msgfree(msg);
306         if (mem_ctx)
307                 talloc_destroy(mem_ctx);
308
309         return ntstatus;
310 }
311
312 /*******************************************************************
313  Run the search by name.
314 ******************************************************************/
315
316 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state,
317                                           const char *user,
318                                           LDAPMessage ** result,
319                                           const char **attr)
320 {
321         char *filter = NULL;
322         char *escape_user = escape_ldap_string(talloc_tos(), user);
323         int ret = -1;
324
325         if (!escape_user) {
326                 return LDAP_NO_MEMORY;
327         }
328
329         /*
330          * in the filter expression, replace %u with the real name
331          * so in ldap filter, %u MUST exist :-)
332          */
333         filter = talloc_asprintf(talloc_tos(), "(&%s%s)", "(uid=%u)",
334                 get_objclass_filter(ldap_state->schema_ver));
335         if (!filter) {
336                 TALLOC_FREE(escape_user);
337                 return LDAP_NO_MEMORY;
338         }
339         /*
340          * have to use this here because $ is filtered out
341          * in string_sub
342          */
343
344         filter = talloc_all_string_sub(talloc_tos(),
345                                 filter, "%u", escape_user);
346         TALLOC_FREE(escape_user);
347         if (!filter) {
348                 return LDAP_NO_MEMORY;
349         }
350
351         ret = smbldap_search_suffix(ldap_state->smbldap_state,
352                         filter, attr, result);
353         TALLOC_FREE(filter);
354         return ret;
355 }
356
357 /*******************************************************************
358  Run the search by rid.
359 ******************************************************************/
360
361 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state,
362                                          uint32_t rid, LDAPMessage ** result,
363                                          const char **attr)
364 {
365         char *filter = NULL;
366         int rc;
367
368         filter = talloc_asprintf(talloc_tos(), "(&(rid=%i)%s)", rid,
369                 get_objclass_filter(ldap_state->schema_ver));
370         if (!filter) {
371                 return LDAP_NO_MEMORY;
372         }
373
374         rc = smbldap_search_suffix(ldap_state->smbldap_state,
375                         filter, attr, result);
376         TALLOC_FREE(filter);
377         return rc;
378 }
379
380 /*******************************************************************
381  Run the search by SID.
382 ******************************************************************/
383
384 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state,
385                                  const struct dom_sid *sid, LDAPMessage ** result,
386                                  const char **attr)
387 {
388         char *filter = NULL;
389         int rc;
390         fstring sid_string;
391
392         filter = talloc_asprintf(talloc_tos(), "(&(%s=%s)%s)",
393                 get_userattr_key2string(ldap_state->schema_ver,
394                         LDAP_ATTR_USER_SID),
395                 sid_to_fstring(sid_string, sid),
396                 get_objclass_filter(ldap_state->schema_ver));
397         if (!filter) {
398                 return LDAP_NO_MEMORY;
399         }
400
401         rc = smbldap_search_suffix(ldap_state->smbldap_state,
402                         filter, attr, result);
403
404         TALLOC_FREE(filter);
405         return rc;
406 }
407
408 /*******************************************************************
409  Delete complete object or objectclass and attrs from
410  object found in search_result depending on lp_ldap_delete_dn
411 ******************************************************************/
412
413 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
414                                 TALLOC_CTX *mem_ctx,
415                                 LDAPMessage *entry,
416                                 const char *objectclass,
417                                 const char **attrs)
418 {
419         LDAPMod **mods = NULL;
420         char *name;
421         const char *dn;
422         BerElement *ptr = NULL;
423
424         dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
425         if (dn == NULL) {
426                 return LDAP_NO_MEMORY;
427         }
428
429         if (lp_ldap_delete_dn()) {
430                 return smbldap_delete(priv->smbldap_state, dn);
431         }
432
433         /* Ok, delete only the SAM attributes */
434
435         for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
436              name != NULL;
437              name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
438                 const char **attrib;
439
440                 /* We are only allowed to delete the attributes that
441                    really exist. */
442
443                 for (attrib = attrs; *attrib != NULL; attrib++) {
444                         if (strequal(*attrib, name)) {
445                                 DEBUG(10, ("ldapsam_delete_entry: deleting "
446                                            "attribute %s\n", name));
447                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
448                                                 NULL);
449                         }
450                 }
451                 ldap_memfree(name);
452         }
453
454         if (ptr != NULL) {
455                 ber_free(ptr, 0);
456         }
457
458         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
459         talloc_autofree_ldapmod(mem_ctx, mods);
460
461         return smbldap_modify(priv->smbldap_state, dn, mods);
462 }
463
464 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
465 {
466         char *temp;
467         struct tm tm;
468
469         temp = smbldap_talloc_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
470                         get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
471                         talloc_tos());
472         if (!temp) {
473                 return (time_t) 0;
474         }
475
476         if ( !strptime(temp, "%Y%m%d%H%M%SZ", &tm)) {
477                 DEBUG(2,("ldapsam_get_entry_timestamp: strptime failed on: %s\n",
478                         (char*)temp));
479                 TALLOC_FREE(temp);
480                 return (time_t) 0;
481         }
482         TALLOC_FREE(temp);
483         tzset();
484         return timegm(&tm);
485 }
486
487 /**********************************************************************
488  Initialize struct samu from an LDAP query.
489  (Based on init_sam_from_buffer in pdb_tdb.c)
490 *********************************************************************/
491
492 static bool init_sam_from_ldap(struct ldapsam_privates *ldap_state,
493                                 struct samu * sampass,
494                                 LDAPMessage * entry)
495 {
496         time_t  logon_time,
497                         logoff_time,
498                         kickoff_time,
499                         pass_last_set_time,
500                         pass_can_change_time,
501                         pass_must_change_time,
502                         ldap_entry_time,
503                         bad_password_time;
504         char *username = NULL,
505                         *domain = NULL,
506                         *nt_username = NULL,
507                         *fullname = NULL,
508                         *homedir = NULL,
509                         *dir_drive = NULL,
510                         *logon_script = NULL,
511                         *profile_path = NULL,
512                         *acct_desc = NULL,
513                         *workstations = NULL,
514                         *munged_dial = NULL;
515         uint32_t                user_rid;
516         uint8           smblmpwd[LM_HASH_LEN],
517                         smbntpwd[NT_HASH_LEN];
518         bool            use_samba_attrs = True;
519         uint32_t                acct_ctrl = 0;
520         uint16_t                logon_divs;
521         uint16_t                bad_password_count = 0,
522                         logon_count = 0;
523         uint32_t hours_len;
524         uint8           hours[MAX_HOURS_LEN];
525         char *temp = NULL;
526         struct login_cache cache_entry;
527         uint32_t                pwHistLen;
528         bool expand_explicit = lp_passdb_expand_explicit();
529         bool ret = false;
530         TALLOC_CTX *ctx = talloc_init("init_sam_from_ldap");
531
532         if (!ctx) {
533                 return false;
534         }
535         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
536                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
537                 goto fn_exit;
538         }
539
540         if (priv2ld(ldap_state) == NULL) {
541                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
542                           "ldap_struct is NULL!\n"));
543                 goto fn_exit;
544         }
545
546         if (!(username = smbldap_talloc_first_attribute(priv2ld(ldap_state),
547                                         entry,
548                                         "uid",
549                                         ctx))) {
550                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
551                           "this user!\n"));
552                 goto fn_exit;
553         }
554
555         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
556
557         nt_username = talloc_strdup(ctx, username);
558         if (!nt_username) {
559                 goto fn_exit;
560         }
561
562         domain = talloc_strdup(ctx, ldap_state->domain_name);
563         if (!domain) {
564                 goto fn_exit;
565         }
566
567         pdb_set_username(sampass, username, PDB_SET);
568
569         pdb_set_domain(sampass, domain, PDB_DEFAULT);
570         pdb_set_nt_username(sampass, nt_username, PDB_SET);
571
572         /* deal with different attributes between the schema first */
573
574         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
575                 if ((temp = smbldap_talloc_single_attribute(
576                                 ldap_state->smbldap_state->ldap_struct,
577                                 entry,
578                                 get_userattr_key2string(ldap_state->schema_ver,
579                                         LDAP_ATTR_USER_SID),
580                                 ctx))!=NULL) {
581                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
582                 }
583         } else {
584                 if ((temp = smbldap_talloc_single_attribute(
585                                 ldap_state->smbldap_state->ldap_struct,
586                                 entry,
587                                 get_userattr_key2string(ldap_state->schema_ver,
588                                         LDAP_ATTR_USER_RID),
589                                 ctx))!=NULL) {
590                         user_rid = (uint32_t)atol(temp);
591                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
592                 }
593         }
594
595         if (IS_SAM_DEFAULT(sampass, PDB_USERSID)) {
596                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
597                         get_userattr_key2string(ldap_state->schema_ver,
598                                 LDAP_ATTR_USER_SID),
599                         get_userattr_key2string(ldap_state->schema_ver,
600                                 LDAP_ATTR_USER_RID),
601                         username));
602                 return False;
603         }
604
605         temp = smbldap_talloc_single_attribute(
606                         ldap_state->smbldap_state->ldap_struct,
607                         entry,
608                         get_userattr_key2string(ldap_state->schema_ver,
609                                 LDAP_ATTR_PWD_LAST_SET),
610                         ctx);
611         if (temp) {
612                 pass_last_set_time = (time_t) atol(temp);
613                 pdb_set_pass_last_set_time(sampass,
614                                 pass_last_set_time, PDB_SET);
615         }
616
617         temp = smbldap_talloc_single_attribute(
618                         ldap_state->smbldap_state->ldap_struct,
619                         entry,
620                         get_userattr_key2string(ldap_state->schema_ver,
621                                 LDAP_ATTR_LOGON_TIME),
622                         ctx);
623         if (temp) {
624                 logon_time = (time_t) atol(temp);
625                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
626         }
627
628         temp = smbldap_talloc_single_attribute(
629                         ldap_state->smbldap_state->ldap_struct,
630                         entry,
631                         get_userattr_key2string(ldap_state->schema_ver,
632                                 LDAP_ATTR_LOGOFF_TIME),
633                         ctx);
634         if (temp) {
635                 logoff_time = (time_t) atol(temp);
636                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
637         }
638
639         temp = smbldap_talloc_single_attribute(
640                         ldap_state->smbldap_state->ldap_struct,
641                         entry,
642                         get_userattr_key2string(ldap_state->schema_ver,
643                                 LDAP_ATTR_KICKOFF_TIME),
644                         ctx);
645         if (temp) {
646                 kickoff_time = (time_t) atol(temp);
647                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
648         }
649
650         temp = smbldap_talloc_single_attribute(
651                         ldap_state->smbldap_state->ldap_struct,
652                         entry,
653                         get_userattr_key2string(ldap_state->schema_ver,
654                                 LDAP_ATTR_PWD_CAN_CHANGE),
655                         ctx);
656         if (temp) {
657                 pass_can_change_time = (time_t) atol(temp);
658                 pdb_set_pass_can_change_time(sampass,
659                                 pass_can_change_time, PDB_SET);
660         }
661
662         temp = smbldap_talloc_single_attribute(
663                         ldap_state->smbldap_state->ldap_struct,
664                         entry,
665                         get_userattr_key2string(ldap_state->schema_ver,
666                                 LDAP_ATTR_PWD_MUST_CHANGE),
667                         ctx);
668         if (temp) {
669                 pass_must_change_time = (time_t) atol(temp);
670                 pdb_set_pass_must_change_time(sampass,
671                                 pass_must_change_time, PDB_SET);
672         }
673
674         /* recommend that 'gecos' and 'displayName' should refer to the same
675          * attribute OID.  userFullName depreciated, only used by Samba
676          * primary rules of LDAP: don't make a new attribute when one is already defined
677          * that fits your needs; using cn then displayName rather than 'userFullName'
678          */
679
680         fullname = smbldap_talloc_single_attribute(
681                         ldap_state->smbldap_state->ldap_struct,
682                         entry,
683                         get_userattr_key2string(ldap_state->schema_ver,
684                                 LDAP_ATTR_DISPLAY_NAME),
685                         ctx);
686         if (fullname) {
687                 pdb_set_fullname(sampass, fullname, PDB_SET);
688         } else {
689                 fullname = smbldap_talloc_single_attribute(
690                                 ldap_state->smbldap_state->ldap_struct,
691                                 entry,
692                                 get_userattr_key2string(ldap_state->schema_ver,
693                                         LDAP_ATTR_CN),
694                                 ctx);
695                 if (fullname) {
696                         pdb_set_fullname(sampass, fullname, PDB_SET);
697                 }
698         }
699
700         dir_drive = smbldap_talloc_single_attribute(
701                         ldap_state->smbldap_state->ldap_struct,
702                         entry,
703                         get_userattr_key2string(ldap_state->schema_ver,
704                                 LDAP_ATTR_HOME_DRIVE),
705                         ctx);
706         if (dir_drive) {
707                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
708         } else {
709                 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
710         }
711
712         homedir = smbldap_talloc_single_attribute(
713                         ldap_state->smbldap_state->ldap_struct,
714                         entry,
715                         get_userattr_key2string(ldap_state->schema_ver,
716                                 LDAP_ATTR_HOME_PATH),
717                         ctx);
718         if (homedir) {
719                 if (expand_explicit) {
720                         homedir = talloc_sub_basic(ctx,
721                                                 username,
722                                                 domain,
723                                                 homedir);
724                         if (!homedir) {
725                                 goto fn_exit;
726                         }
727                 }
728                 pdb_set_homedir(sampass, homedir, PDB_SET);
729         } else {
730                 pdb_set_homedir(sampass,
731                         talloc_sub_basic(ctx, username, domain,
732                                          lp_logon_home()),
733                         PDB_DEFAULT);
734         }
735
736         logon_script = smbldap_talloc_single_attribute(
737                         ldap_state->smbldap_state->ldap_struct,
738                         entry,
739                         get_userattr_key2string(ldap_state->schema_ver,
740                                 LDAP_ATTR_LOGON_SCRIPT),
741                         ctx);
742         if (logon_script) {
743                 if (expand_explicit) {
744                         logon_script = talloc_sub_basic(ctx,
745                                                 username,
746                                                 domain,
747                                                 logon_script);
748                         if (!logon_script) {
749                                 goto fn_exit;
750                         }
751                 }
752                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
753         } else {
754                 pdb_set_logon_script(sampass,
755                         talloc_sub_basic(ctx, username, domain,
756                                          lp_logon_script()),
757                         PDB_DEFAULT );
758         }
759
760         profile_path = smbldap_talloc_single_attribute(
761                         ldap_state->smbldap_state->ldap_struct,
762                         entry,
763                         get_userattr_key2string(ldap_state->schema_ver,
764                                 LDAP_ATTR_PROFILE_PATH),
765                         ctx);
766         if (profile_path) {
767                 if (expand_explicit) {
768                         profile_path = talloc_sub_basic(ctx,
769                                                 username,
770                                                 domain,
771                                                 profile_path);
772                         if (!profile_path) {
773                                 goto fn_exit;
774                         }
775                 }
776                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
777         } else {
778                 pdb_set_profile_path(sampass,
779                         talloc_sub_basic(ctx, username, domain,
780                                           lp_logon_path()),
781                         PDB_DEFAULT );
782         }
783
784         acct_desc = smbldap_talloc_single_attribute(
785                         ldap_state->smbldap_state->ldap_struct,
786                         entry,
787                         get_userattr_key2string(ldap_state->schema_ver,
788                                 LDAP_ATTR_DESC),
789                         ctx);
790         if (acct_desc) {
791                 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
792         }
793
794         workstations = smbldap_talloc_single_attribute(
795                         ldap_state->smbldap_state->ldap_struct,
796                         entry,
797                         get_userattr_key2string(ldap_state->schema_ver,
798                                 LDAP_ATTR_USER_WKS),
799                         ctx);
800         if (workstations) {
801                 pdb_set_workstations(sampass, workstations, PDB_SET);
802         }
803
804         munged_dial = smbldap_talloc_single_attribute(
805                         ldap_state->smbldap_state->ldap_struct,
806                         entry,
807                         get_userattr_key2string(ldap_state->schema_ver,
808                                 LDAP_ATTR_MUNGED_DIAL),
809                         ctx);
810         if (munged_dial) {
811                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
812         }
813
814         /* FIXME: hours stuff should be cleaner */
815
816         logon_divs = 168;
817         hours_len = 21;
818         memset(hours, 0xff, hours_len);
819
820         if (ldap_state->is_nds_ldap) {
821                 char *user_dn;
822                 size_t pwd_len;
823                 char clear_text_pw[512];
824
825                 /* Make call to Novell eDirectory ldap extension to get clear text password.
826                         NOTE: This will only work if we have an SSL connection to eDirectory. */
827                 user_dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
828                 if (user_dn != NULL) {
829                         DEBUG(3, ("init_sam_from_ldap: smbldap_talloc_dn(ctx, %s) returned '%s'\n", username, user_dn));
830
831                         pwd_len = sizeof(clear_text_pw);
832                         if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
833                                 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
834                                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
835                                         TALLOC_FREE(user_dn);
836                                         return False;
837                                 }
838                                 ZERO_STRUCT(smblmpwd);
839                                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
840                                         TALLOC_FREE(user_dn);
841                                         return False;
842                                 }
843                                 ZERO_STRUCT(smbntpwd);
844                                 use_samba_attrs = False;
845                         }
846
847                         TALLOC_FREE(user_dn);
848
849                 } else {
850                         DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
851                 }
852         }
853
854         if (use_samba_attrs) {
855                 temp = smbldap_talloc_single_attribute(
856                                 ldap_state->smbldap_state->ldap_struct,
857                                 entry,
858                                 get_userattr_key2string(ldap_state->schema_ver,
859                                         LDAP_ATTR_LMPW),
860                                 ctx);
861                 if (temp) {
862                         pdb_gethexpwd(temp, smblmpwd);
863                         memset((char *)temp, '\0', strlen(temp)+1);
864                         if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
865                                 goto fn_exit;
866                         }
867                         ZERO_STRUCT(smblmpwd);
868                 }
869
870                 temp = smbldap_talloc_single_attribute(
871                                 ldap_state->smbldap_state->ldap_struct,
872                                 entry,
873                                 get_userattr_key2string(ldap_state->schema_ver,
874                                         LDAP_ATTR_NTPW),
875                                 ctx);
876                 if (temp) {
877                         pdb_gethexpwd(temp, smbntpwd);
878                         memset((char *)temp, '\0', strlen(temp)+1);
879                         if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
880                                 goto fn_exit;
881                         }
882                         ZERO_STRUCT(smbntpwd);
883                 }
884         }
885
886         pwHistLen = 0;
887
888         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
889         if (pwHistLen > 0){
890                 uint8 *pwhist = NULL;
891                 int i;
892                 char *history_string = talloc_array(ctx, char,
893                                                 MAX_PW_HISTORY_LEN*64);
894
895                 if (!history_string) {
896                         goto fn_exit;
897                 }
898
899                 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
900
901                 pwhist = talloc_array(ctx, uint8,
902                                       pwHistLen * PW_HISTORY_ENTRY_LEN);
903                 if (pwhist == NULL) {
904                         DEBUG(0, ("init_sam_from_ldap: talloc failed!\n"));
905                         goto fn_exit;
906                 }
907                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
908
909                 if (smbldap_get_single_attribute(
910                                 ldap_state->smbldap_state->ldap_struct,
911                                 entry,
912                                 get_userattr_key2string(ldap_state->schema_ver,
913                                         LDAP_ATTR_PWD_HISTORY),
914                                 history_string,
915                                 MAX_PW_HISTORY_LEN*64)) {
916                         bool hex_failed = false;
917                         for (i = 0; i < pwHistLen; i++){
918                                 /* Get the 16 byte salt. */
919                                 if (!pdb_gethexpwd(&history_string[i*64],
920                                         &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
921                                         hex_failed = true;
922                                         break;
923                                 }
924                                 /* Get the 16 byte MD5 hash of salt+passwd. */
925                                 if (!pdb_gethexpwd(&history_string[(i*64)+32],
926                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+
927                                                 PW_HISTORY_SALT_LEN])) {
928                                         hex_failed = True;
929                                         break;
930                                 }
931                         }
932                         if (hex_failed) {
933                                 DEBUG(2,("init_sam_from_ldap: Failed to get password history for user %s\n",
934                                         username));
935                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
936                         }
937                 }
938                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
939                         goto fn_exit;
940                 }
941         }
942
943         temp = smbldap_talloc_single_attribute(
944                         ldap_state->smbldap_state->ldap_struct,
945                         entry,
946                         get_userattr_key2string(ldap_state->schema_ver,
947                                 LDAP_ATTR_ACB_INFO),
948                         ctx);
949         if (temp) {
950                 acct_ctrl = pdb_decode_acct_ctrl(temp);
951
952                 if (acct_ctrl == 0) {
953                         acct_ctrl |= ACB_NORMAL;
954                 }
955
956                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
957         } else {
958                 acct_ctrl |= ACB_NORMAL;
959         }
960
961         pdb_set_hours_len(sampass, hours_len, PDB_SET);
962         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
963
964         temp = smbldap_talloc_single_attribute(
965                         ldap_state->smbldap_state->ldap_struct,
966                         entry,
967                         get_userattr_key2string(ldap_state->schema_ver,
968                                 LDAP_ATTR_BAD_PASSWORD_COUNT),
969                         ctx);
970         if (temp) {
971                 bad_password_count = (uint32_t) atol(temp);
972                 pdb_set_bad_password_count(sampass,
973                                 bad_password_count, PDB_SET);
974         }
975
976         temp = smbldap_talloc_single_attribute(
977                         ldap_state->smbldap_state->ldap_struct,
978                         entry,
979                         get_userattr_key2string(ldap_state->schema_ver,
980                                 LDAP_ATTR_BAD_PASSWORD_TIME),
981                         ctx);
982         if (temp) {
983                 bad_password_time = (time_t) atol(temp);
984                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
985         }
986
987
988         temp = smbldap_talloc_single_attribute(
989                         ldap_state->smbldap_state->ldap_struct,
990                         entry,
991                         get_userattr_key2string(ldap_state->schema_ver,
992                                 LDAP_ATTR_LOGON_COUNT),
993                         ctx);
994         if (temp) {
995                 logon_count = (uint32_t) atol(temp);
996                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
997         }
998
999         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
1000
1001         temp = smbldap_talloc_single_attribute(
1002                         ldap_state->smbldap_state->ldap_struct,
1003                         entry,
1004                         get_userattr_key2string(ldap_state->schema_ver,
1005                                 LDAP_ATTR_LOGON_HOURS),
1006                         ctx);
1007         if (temp) {
1008                 pdb_gethexhours(temp, hours);
1009                 memset((char *)temp, '\0', strlen(temp) +1);
1010                 pdb_set_hours(sampass, hours, hours_len, PDB_SET);
1011                 ZERO_STRUCT(hours);
1012         }
1013
1014         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
1015                 struct passwd unix_pw;
1016                 bool have_uid = false;
1017                 bool have_gid = false;
1018                 struct dom_sid mapped_gsid;
1019                 const struct dom_sid *primary_gsid;
1020
1021                 ZERO_STRUCT(unix_pw);
1022
1023                 unix_pw.pw_name = username;
1024                 unix_pw.pw_passwd = discard_const_p(char, "x");
1025
1026                 temp = smbldap_talloc_single_attribute(
1027                                 priv2ld(ldap_state),
1028                                 entry,
1029                                 "uidNumber",
1030                                 ctx);
1031                 if (temp) {
1032                         /* We've got a uid, feed the cache */
1033                         unix_pw.pw_uid = strtoul(temp, NULL, 10);
1034                         have_uid = true;
1035                 }
1036                 temp = smbldap_talloc_single_attribute(
1037                                 priv2ld(ldap_state),
1038                                 entry,
1039                                 "gidNumber",
1040                                 ctx);
1041                 if (temp) {
1042                         /* We've got a uid, feed the cache */
1043                         unix_pw.pw_gid = strtoul(temp, NULL, 10);
1044                         have_gid = true;
1045                 }
1046                 unix_pw.pw_gecos = smbldap_talloc_single_attribute(
1047                                 priv2ld(ldap_state),
1048                                 entry,
1049                                 "gecos",
1050                                 ctx);
1051                 if (unix_pw.pw_gecos) {
1052                         unix_pw.pw_gecos = fullname;
1053                 }
1054                 unix_pw.pw_dir = smbldap_talloc_single_attribute(
1055                                 priv2ld(ldap_state),
1056                                 entry,
1057                                 "homeDirectory",
1058                                 ctx);
1059                 if (unix_pw.pw_dir) {
1060                         unix_pw.pw_dir = discard_const_p(char, "");
1061                 }
1062                 unix_pw.pw_shell = smbldap_talloc_single_attribute(
1063                                 priv2ld(ldap_state),
1064                                 entry,
1065                                 "loginShell",
1066                                 ctx);
1067                 if (unix_pw.pw_shell) {
1068                         unix_pw.pw_shell = discard_const_p(char, "");
1069                 }
1070
1071                 if (have_uid && have_gid) {
1072                         sampass->unix_pw = tcopy_passwd(sampass, &unix_pw);
1073                 } else {
1074                         sampass->unix_pw = Get_Pwnam_alloc(sampass, unix_pw.pw_name);
1075                 }
1076
1077                 if (sampass->unix_pw == NULL) {
1078                         DEBUG(0,("init_sam_from_ldap: Failed to find Unix account for %s\n",
1079                                  pdb_get_username(sampass)));
1080                         goto fn_exit;
1081                 }
1082
1083                 store_uid_sid_cache(pdb_get_user_sid(sampass),
1084                                     sampass->unix_pw->pw_uid);
1085                 idmap_cache_set_sid2uid(pdb_get_user_sid(sampass),
1086                                         sampass->unix_pw->pw_uid);
1087
1088                 gid_to_sid(&mapped_gsid, sampass->unix_pw->pw_gid);
1089                 primary_gsid = pdb_get_group_sid(sampass);
1090                 if (primary_gsid && dom_sid_equal(primary_gsid, &mapped_gsid)) {
1091                         store_gid_sid_cache(primary_gsid,
1092                                             sampass->unix_pw->pw_gid);
1093                         idmap_cache_set_sid2gid(primary_gsid,
1094                                                 sampass->unix_pw->pw_gid);
1095                 }
1096         }
1097
1098         /* check the timestamp of the cache vs ldap entry */
1099         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state,
1100                                                             entry))) {
1101                 ret = true;
1102                 goto fn_exit;
1103         }
1104
1105         /* see if we have newer updates */
1106         if (!login_cache_read(sampass, &cache_entry)) {
1107                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
1108                            (unsigned int)pdb_get_bad_password_count(sampass),
1109                            (unsigned int)pdb_get_bad_password_time(sampass)));
1110                 ret = true;
1111                 goto fn_exit;
1112         }
1113
1114         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n",
1115                   (unsigned int)ldap_entry_time,
1116                   (unsigned int)cache_entry.entry_timestamp,
1117                   (unsigned int)cache_entry.bad_password_time));
1118
1119         if (ldap_entry_time > cache_entry.entry_timestamp) {
1120                 /* cache is older than directory , so
1121                    we need to delete the entry but allow the
1122                    fields to be written out */
1123                 login_cache_delentry(sampass);
1124         } else {
1125                 /* read cache in */
1126                 pdb_set_acct_ctrl(sampass,
1127                                   pdb_get_acct_ctrl(sampass) |
1128                                   (cache_entry.acct_ctrl & ACB_AUTOLOCK),
1129                                   PDB_SET);
1130                 pdb_set_bad_password_count(sampass,
1131                                            cache_entry.bad_password_count,
1132                                            PDB_SET);
1133                 pdb_set_bad_password_time(sampass,
1134                                           cache_entry.bad_password_time,
1135                                           PDB_SET);
1136         }
1137
1138         ret = true;
1139
1140   fn_exit:
1141
1142         TALLOC_FREE(ctx);
1143         return ret;
1144 }
1145
1146 /**********************************************************************
1147  Initialize the ldap db from a struct samu. Called on update.
1148  (Based on init_buffer_from_sam in pdb_tdb.c)
1149 *********************************************************************/
1150
1151 static bool init_ldap_from_sam (struct ldapsam_privates *ldap_state,
1152                                 LDAPMessage *existing,
1153                                 LDAPMod *** mods, struct samu * sampass,
1154                                 bool (*need_update)(const struct samu *,
1155                                                     enum pdb_elements))
1156 {
1157         char *temp = NULL;
1158         uint32_t rid;
1159
1160         if (mods == NULL || sampass == NULL) {
1161                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
1162                 return False;
1163         }
1164
1165         *mods = NULL;
1166
1167         /*
1168          * took out adding "objectclass: sambaAccount"
1169          * do this on a per-mod basis
1170          */
1171         if (need_update(sampass, PDB_USERNAME)) {
1172                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1173                               "uid", pdb_get_username(sampass));
1174                 if (ldap_state->is_nds_ldap) {
1175                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1176                                       "cn", pdb_get_username(sampass));
1177                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
1178                                       "sn", pdb_get_username(sampass));
1179                 }
1180         }
1181
1182         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
1183
1184         /* only update the RID if we actually need to */
1185         if (need_update(sampass, PDB_USERSID)) {
1186                 fstring sid_string;
1187                 const struct dom_sid *user_sid = pdb_get_user_sid(sampass);
1188
1189                 switch ( ldap_state->schema_ver ) {
1190                         case SCHEMAVER_SAMBAACCOUNT:
1191                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
1192                                         DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
1193                                                   sid_string_dbg(user_sid),
1194                                                   sid_string_dbg(
1195                                                           &ldap_state->domain_sid)));
1196                                         return False;
1197                                 }
1198                                 if (asprintf(&temp, "%i", rid) < 0) {
1199                                         return false;
1200                                 }
1201                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1202                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
1203                                         temp);
1204                                 SAFE_FREE(temp);
1205                                 break;
1206
1207                         case SCHEMAVER_SAMBASAMACCOUNT:
1208                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1209                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
1210                                         sid_to_fstring(sid_string, user_sid));
1211                                 break;
1212
1213                         default:
1214                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1215                                 break;
1216                 }
1217         }
1218
1219         /* we don't need to store the primary group RID - so leaving it
1220            'free' to hang off the unix primary group makes life easier */
1221
1222         if (need_update(sampass, PDB_GROUPSID)) {
1223                 fstring sid_string;
1224                 const struct dom_sid *group_sid = pdb_get_group_sid(sampass);
1225
1226                 switch ( ldap_state->schema_ver ) {
1227                         case SCHEMAVER_SAMBAACCOUNT:
1228                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
1229                                         DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1230                                                   sid_string_dbg(group_sid),
1231                                                   sid_string_dbg(
1232                                                           &ldap_state->domain_sid)));
1233                                         return False;
1234                                 }
1235
1236                                 if (asprintf(&temp, "%i", rid) < 0) {
1237                                         return false;
1238                                 }
1239                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1240                                         get_userattr_key2string(ldap_state->schema_ver, 
1241                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
1242                                 SAFE_FREE(temp);
1243                                 break;
1244
1245                         case SCHEMAVER_SAMBASAMACCOUNT:
1246                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1247                                         get_userattr_key2string(ldap_state->schema_ver, 
1248                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_fstring(sid_string, group_sid));
1249                                 break;
1250
1251                         default:
1252                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1253                                 break;
1254                 }
1255
1256         }
1257
1258         /* displayName, cn, and gecos should all be the same
1259          *  most easily accomplished by giving them the same OID
1260          *  gecos isn't set here b/c it should be handled by the
1261          *  add-user script
1262          *  We change displayName only and fall back to cn if
1263          *  it does not exist.
1264          */
1265
1266         if (need_update(sampass, PDB_FULLNAME))
1267                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1268                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
1269                         pdb_get_fullname(sampass));
1270
1271         if (need_update(sampass, PDB_ACCTDESC))
1272                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1273                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
1274                         pdb_get_acct_desc(sampass));
1275
1276         if (need_update(sampass, PDB_WORKSTATIONS))
1277                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1278                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
1279                         pdb_get_workstations(sampass));
1280
1281         if (need_update(sampass, PDB_MUNGEDDIAL))
1282                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1283                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
1284                         pdb_get_munged_dial(sampass));
1285
1286         if (need_update(sampass, PDB_SMBHOME))
1287                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1288                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
1289                         pdb_get_homedir(sampass));
1290
1291         if (need_update(sampass, PDB_DRIVE))
1292                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1293                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
1294                         pdb_get_dir_drive(sampass));
1295
1296         if (need_update(sampass, PDB_LOGONSCRIPT))
1297                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1298                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1299                         pdb_get_logon_script(sampass));
1300
1301         if (need_update(sampass, PDB_PROFILE))
1302                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1303                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1304                         pdb_get_profile_path(sampass));
1305
1306         if (asprintf(&temp, "%li", (long int)pdb_get_logon_time(sampass)) < 0) {
1307                 return false;
1308         }
1309         if (need_update(sampass, PDB_LOGONTIME))
1310                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1311                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1312         SAFE_FREE(temp);
1313
1314         if (asprintf(&temp, "%li", (long int)pdb_get_logoff_time(sampass)) < 0) {
1315                 return false;
1316         }
1317         if (need_update(sampass, PDB_LOGOFFTIME))
1318                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1319                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1320         SAFE_FREE(temp);
1321
1322         if (asprintf(&temp, "%li", (long int)pdb_get_kickoff_time(sampass)) < 0) {
1323                 return false;
1324         }
1325         if (need_update(sampass, PDB_KICKOFFTIME))
1326                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1327                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1328         SAFE_FREE(temp);
1329
1330         if (asprintf(&temp, "%li", (long int)pdb_get_pass_can_change_time_noncalc(sampass)) < 0) {
1331                 return false;
1332         }
1333         if (need_update(sampass, PDB_CANCHANGETIME))
1334                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1335                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1336         SAFE_FREE(temp);
1337
1338         if (asprintf(&temp, "%li", (long int)pdb_get_pass_must_change_time(sampass)) < 0) {
1339                 return false;
1340         }
1341         if (need_update(sampass, PDB_MUSTCHANGETIME))
1342                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1343                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1344         SAFE_FREE(temp);
1345
1346         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1347                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1348
1349                 if (need_update(sampass, PDB_LMPASSWD)) {
1350                         const uchar *lm_pw = pdb_get_lanman_passwd(sampass);
1351                         if (lm_pw) {
1352                                 char pwstr[34];
1353                                 pdb_sethexpwd(pwstr, lm_pw,
1354                                               pdb_get_acct_ctrl(sampass));
1355                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1356                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1357                                                  pwstr);
1358                         } else {
1359                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1360                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1361                                                  NULL);
1362                         }
1363                 }
1364                 if (need_update(sampass, PDB_NTPASSWD)) {
1365                         const uchar *nt_pw = pdb_get_nt_passwd(sampass);
1366                         if (nt_pw) {
1367                                 char pwstr[34];
1368                                 pdb_sethexpwd(pwstr, nt_pw,
1369                                               pdb_get_acct_ctrl(sampass));
1370                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1371                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1372                                                  pwstr);
1373                         } else {
1374                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1375                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1376                                                  NULL);
1377                         }
1378                 }
1379
1380                 if (need_update(sampass, PDB_PWHISTORY)) {
1381                         char *pwstr = NULL;
1382                         uint32_t pwHistLen = 0;
1383                         pdb_get_account_policy(PDB_POLICY_PASSWORD_HISTORY, &pwHistLen);
1384
1385                         pwstr = SMB_MALLOC_ARRAY(char, 1024);
1386                         if (!pwstr) {
1387                                 return false;
1388                         }
1389                         if (pwHistLen == 0) {
1390                                 /* Remove any password history from the LDAP store. */
1391                                 memset(pwstr, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1392                                 pwstr[64] = '\0';
1393                         } else {
1394                                 int i;
1395                                 uint32_t currHistLen = 0;
1396                                 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1397                                 if (pwhist != NULL) {
1398                                         /* We can only store (1024-1/64 password history entries. */
1399                                         pwHistLen = MIN(pwHistLen, ((1024-1)/64));
1400                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1401                                                 /* Store the salt. */
1402                                                 pdb_sethexpwd(&pwstr[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1403                                                 /* Followed by the md5 hash of salt + md4 hash */
1404                                                 pdb_sethexpwd(&pwstr[(i*64)+32],
1405                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1406                                                 DEBUG(100, ("pwstr=%s\n", pwstr));
1407                                         }
1408                                 }
1409                         }
1410                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1411                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1412                                          pwstr);
1413                         SAFE_FREE(pwstr);
1414                 }
1415
1416                 if (need_update(sampass, PDB_PASSLASTSET)) {
1417                         if (asprintf(&temp, "%li",
1418                                 (long int)pdb_get_pass_last_set_time(sampass)) < 0) {
1419                                 return false;
1420                         }
1421                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1422                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1423                                 temp);
1424                         SAFE_FREE(temp);
1425                 }
1426         }
1427
1428         if (need_update(sampass, PDB_HOURS)) {
1429                 const uint8 *hours = pdb_get_hours(sampass);
1430                 if (hours) {
1431                         char hourstr[44];
1432                         pdb_sethexhours(hourstr, hours);
1433                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1434                                 existing,
1435                                 mods,
1436                                 get_userattr_key2string(ldap_state->schema_ver,
1437                                                 LDAP_ATTR_LOGON_HOURS),
1438                                 hourstr);
1439                 }
1440         }
1441
1442         if (need_update(sampass, PDB_ACCTCTRL))
1443                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1444                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1445                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1446
1447         /* password lockout cache:
1448            - If we are now autolocking or clearing, we write to ldap
1449            - If we are clearing, we delete the cache entry
1450            - If the count is > 0, we update the cache
1451
1452            This even means when autolocking, we cache, just in case the
1453            update doesn't work, and we have to cache the autolock flag */
1454
1455         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1456             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1457                 uint16_t badcount = pdb_get_bad_password_count(sampass);
1458                 time_t badtime = pdb_get_bad_password_time(sampass);
1459                 uint32_t pol;
1460                 pdb_get_account_policy(PDB_POLICY_BAD_ATTEMPT_LOCKOUT, &pol);
1461
1462                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1463                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1464
1465                 if ((badcount >= pol) || (badcount == 0)) {
1466                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1467                                 (unsigned int)badcount, (unsigned int)badtime));
1468                         if (asprintf(&temp, "%li", (long)badcount) < 0) {
1469                                 return false;
1470                         }
1471                         smbldap_make_mod(
1472                                 ldap_state->smbldap_state->ldap_struct,
1473                                 existing, mods,
1474                                 get_userattr_key2string(
1475                                         ldap_state->schema_ver,
1476                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1477                                 temp);
1478                         SAFE_FREE(temp);
1479
1480                         if (asprintf(&temp, "%li", (long int)badtime) < 0) {
1481                                 return false;
1482                         }
1483                         smbldap_make_mod(
1484                                 ldap_state->smbldap_state->ldap_struct,
1485                                 existing, mods,
1486                                 get_userattr_key2string(
1487                                         ldap_state->schema_ver,
1488                                         LDAP_ATTR_BAD_PASSWORD_TIME),
1489                                 temp);
1490                         SAFE_FREE(temp);
1491                 }
1492                 if (badcount == 0) {
1493                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1494                         login_cache_delentry(sampass);
1495                 } else {
1496                         struct login_cache cache_entry;
1497
1498                         cache_entry.entry_timestamp = time(NULL);
1499                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1500                         cache_entry.bad_password_count = badcount;
1501                         cache_entry.bad_password_time = badtime;
1502
1503                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1504                         login_cache_write(sampass, &cache_entry);
1505                 }
1506         }
1507
1508         return True;
1509 }
1510
1511 /**********************************************************************
1512  End enumeration of the LDAP password list.
1513 *********************************************************************/
1514
1515 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1516 {
1517         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1518         if (ldap_state->result) {
1519                 ldap_msgfree(ldap_state->result);
1520                 ldap_state->result = NULL;
1521         }
1522 }
1523
1524 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1525                         const char *new_attr)
1526 {
1527         int i;
1528
1529         if (new_attr == NULL) {
1530                 return;
1531         }
1532
1533         for (i=0; (*attr_list)[i] != NULL; i++) {
1534                 ;
1535         }
1536
1537         (*attr_list) = talloc_realloc(mem_ctx, (*attr_list),
1538                                             const char *,  i+2);
1539         SMB_ASSERT((*attr_list) != NULL);
1540         (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1541         (*attr_list)[i+1] = NULL;
1542 }
1543
1544 static void ldapsam_add_unix_attributes(TALLOC_CTX *mem_ctx,
1545                                         const char ***attr_list)
1546 {
1547         append_attr(mem_ctx, attr_list, "uidNumber");
1548         append_attr(mem_ctx, attr_list, "gidNumber");
1549         append_attr(mem_ctx, attr_list, "homeDirectory");
1550         append_attr(mem_ctx, attr_list, "loginShell");
1551         append_attr(mem_ctx, attr_list, "gecos");
1552 }
1553
1554 /**********************************************************************
1555 Get struct samu entry from LDAP by username.
1556 *********************************************************************/
1557
1558 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1559 {
1560         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1561         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1562         LDAPMessage *result = NULL;
1563         LDAPMessage *entry = NULL;
1564         int count;
1565         const char ** attr_list;
1566         int rc;
1567
1568         attr_list = get_userattr_list( user, ldap_state->schema_ver );
1569         append_attr(user, &attr_list,
1570                     get_userattr_key2string(ldap_state->schema_ver,
1571                                             LDAP_ATTR_MOD_TIMESTAMP));
1572         ldapsam_add_unix_attributes(user, &attr_list);
1573         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1574                                            attr_list);
1575         TALLOC_FREE( attr_list );
1576
1577         if ( rc != LDAP_SUCCESS ) 
1578                 return NT_STATUS_NO_SUCH_USER;
1579
1580         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1581
1582         if (count < 1) {
1583                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1584                 ldap_msgfree(result);
1585                 return NT_STATUS_NO_SUCH_USER;
1586         } else if (count > 1) {
1587                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1588                 ldap_msgfree(result);
1589                 return NT_STATUS_NO_SUCH_USER;
1590         }
1591
1592         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1593         if (entry) {
1594                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1595                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1596                         ldap_msgfree(result);
1597                         return NT_STATUS_NO_SUCH_USER;
1598                 }
1599                 pdb_set_backend_private_data(user, result, NULL,
1600                                              my_methods, PDB_CHANGED);
1601                 talloc_autofree_ldapmsg(user, result);
1602                 ret = NT_STATUS_OK;
1603         } else {
1604                 ldap_msgfree(result);
1605         }
1606         return ret;
1607 }
1608
1609 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1610                                    const struct dom_sid *sid, LDAPMessage **result)
1611 {
1612         int rc = -1;
1613         const char ** attr_list;
1614         uint32_t rid;
1615
1616         switch ( ldap_state->schema_ver ) {
1617                 case SCHEMAVER_SAMBASAMACCOUNT: {
1618                         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1619                         if (tmp_ctx == NULL) {
1620                                 return LDAP_NO_MEMORY;
1621                         }
1622
1623                         attr_list = get_userattr_list(tmp_ctx,
1624                                                       ldap_state->schema_ver);
1625                         append_attr(tmp_ctx, &attr_list,
1626                                     get_userattr_key2string(
1627                                             ldap_state->schema_ver,
1628                                             LDAP_ATTR_MOD_TIMESTAMP));
1629                         ldapsam_add_unix_attributes(tmp_ctx, &attr_list);
1630                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1631                                                           result, attr_list);
1632                         TALLOC_FREE(tmp_ctx);
1633
1634                         if ( rc != LDAP_SUCCESS ) 
1635                                 return rc;
1636                         break;
1637                 }
1638
1639                 case SCHEMAVER_SAMBAACCOUNT:
1640                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1641                                 return rc;
1642                         }
1643
1644                         attr_list = get_userattr_list(NULL,
1645                                                       ldap_state->schema_ver);
1646                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1647                         TALLOC_FREE( attr_list );
1648
1649                         if ( rc != LDAP_SUCCESS ) 
1650                                 return rc;
1651                         break;
1652         }
1653         return rc;
1654 }
1655
1656 /**********************************************************************
1657  Get struct samu entry from LDAP by SID.
1658 *********************************************************************/
1659
1660 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const struct dom_sid *sid)
1661 {
1662         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1663         LDAPMessage *result = NULL;
1664         LDAPMessage *entry = NULL;
1665         int count;
1666         int rc;
1667
1668         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1669                                           sid, &result); 
1670         if (rc != LDAP_SUCCESS)
1671                 return NT_STATUS_NO_SUCH_USER;
1672
1673         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1674
1675         if (count < 1) {
1676                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] "
1677                           "count=%d\n", sid_string_dbg(sid), count));
1678                 ldap_msgfree(result);
1679                 return NT_STATUS_NO_SUCH_USER;
1680         }  else if (count > 1) {
1681                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID "
1682                           "[%s]. Failing. count=%d\n", sid_string_dbg(sid),
1683                           count));
1684                 ldap_msgfree(result);
1685                 return NT_STATUS_NO_SUCH_USER;
1686         }
1687
1688         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1689         if (!entry) {
1690                 ldap_msgfree(result);
1691                 return NT_STATUS_NO_SUCH_USER;
1692         }
1693
1694         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1695                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1696                 ldap_msgfree(result);
1697                 return NT_STATUS_NO_SUCH_USER;
1698         }
1699
1700         pdb_set_backend_private_data(user, result, NULL,
1701                                      my_methods, PDB_CHANGED);
1702         talloc_autofree_ldapmsg(user, result);
1703         return NT_STATUS_OK;
1704 }       
1705
1706 /********************************************************************
1707  Do the actual modification - also change a plaintext passord if 
1708  it it set.
1709 **********************************************************************/
1710
1711 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1712                                      struct samu *newpwd, char *dn,
1713                                      LDAPMod **mods, int ldap_op, 
1714                                      bool (*need_update)(const struct samu *, enum pdb_elements))
1715 {
1716         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1717         int rc;
1718
1719         if (!newpwd || !dn) {
1720                 return NT_STATUS_INVALID_PARAMETER;
1721         }
1722
1723         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1724                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1725                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1726                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1727                 BerElement *ber;
1728                 struct berval *bv;
1729                 char *retoid = NULL;
1730                 struct berval *retdata = NULL;
1731                 char *utf8_password;
1732                 char *utf8_dn;
1733                 size_t converted_size;
1734                 int ret;
1735
1736                 if (!ldap_state->is_nds_ldap) {
1737
1738                         if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct, 
1739                                                    LDAP_EXOP_MODIFY_PASSWD)) {
1740                                 DEBUG(2, ("ldap password change requested, but LDAP "
1741                                           "server does not support it -- ignoring\n"));
1742                                 return NT_STATUS_OK;
1743                         }
1744                 }
1745
1746                 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1747                                         pdb_get_plaintext_passwd(newpwd),
1748                                         &converted_size))
1749                 {
1750                         return NT_STATUS_NO_MEMORY;
1751                 }
1752
1753                 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1754                         TALLOC_FREE(utf8_password);
1755                         return NT_STATUS_NO_MEMORY;
1756                 }
1757
1758                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1759                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1760                         TALLOC_FREE(utf8_password);
1761                         TALLOC_FREE(utf8_dn);
1762                         return NT_STATUS_UNSUCCESSFUL;
1763                 }
1764
1765                 if ((ber_printf (ber, "{") < 0) ||
1766                     (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1767                                  utf8_dn) < 0)) {
1768                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1769                                  "value <0\n"));
1770                         ber_free(ber,1);
1771                         TALLOC_FREE(utf8_dn);
1772                         TALLOC_FREE(utf8_password);
1773                         return NT_STATUS_UNSUCCESSFUL;
1774                 }
1775
1776                 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1777                         ret = ber_printf(ber, "ts}",
1778                                          LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1779                                          utf8_password);
1780                 } else {
1781                         ret = ber_printf(ber, "}");
1782                 }
1783
1784                 if (ret < 0) {
1785                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1786                                  "value <0\n"));
1787                         ber_free(ber,1);
1788                         TALLOC_FREE(utf8_dn);
1789                         TALLOC_FREE(utf8_password);
1790                         return NT_STATUS_UNSUCCESSFUL;
1791                 }
1792
1793                 if ((rc = ber_flatten (ber, &bv))<0) {
1794                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1795                         ber_free(ber,1);
1796                         TALLOC_FREE(utf8_dn);
1797                         TALLOC_FREE(utf8_password);
1798                         return NT_STATUS_UNSUCCESSFUL;
1799                 }
1800
1801                 TALLOC_FREE(utf8_dn);
1802                 TALLOC_FREE(utf8_password);
1803                 ber_free(ber, 1);
1804
1805                 if (!ldap_state->is_nds_ldap) {
1806                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1807                                                         LDAP_EXOP_MODIFY_PASSWD,
1808                                                         bv, NULL, NULL, &retoid, 
1809                                                         &retdata);
1810                 } else {
1811                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1812                                                         pdb_get_plaintext_passwd(newpwd));
1813                 }
1814                 if (rc != LDAP_SUCCESS) {
1815                         char *ld_error = NULL;
1816
1817                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1818                                 DEBUG(3, ("Could not set userPassword "
1819                                           "attribute due to an objectClass "
1820                                           "violation -- ignoring\n"));
1821                                 ber_bvfree(bv);
1822                                 return NT_STATUS_OK;
1823                         }
1824
1825                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1826                                         &ld_error);
1827                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1828                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1829                         SAFE_FREE(ld_error);
1830                         ber_bvfree(bv);
1831 #if defined(LDAP_CONSTRAINT_VIOLATION)
1832                         if (rc == LDAP_CONSTRAINT_VIOLATION)
1833                                 return NT_STATUS_PASSWORD_RESTRICTION;
1834 #endif
1835                         return NT_STATUS_UNSUCCESSFUL;
1836                 } else {
1837                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1838 #ifdef DEBUG_PASSWORD
1839                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1840 #endif    
1841                         if (retdata)
1842                                 ber_bvfree(retdata);
1843                         if (retoid)
1844                                 ldap_memfree(retoid);
1845                 }
1846                 ber_bvfree(bv);
1847         }
1848
1849         if (!mods) {
1850                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1851                 /* may be password change below however */
1852         } else {
1853                 switch(ldap_op) {
1854                         case LDAP_MOD_ADD:
1855                                 if (ldap_state->is_nds_ldap) {
1856                                         smbldap_set_mod(&mods, LDAP_MOD_ADD,
1857                                                         "objectclass",
1858                                                         "inetOrgPerson");
1859                                 } else {
1860                                         smbldap_set_mod(&mods, LDAP_MOD_ADD,
1861                                                         "objectclass",
1862                                                         LDAP_OBJ_ACCOUNT);
1863                                 }
1864                                 rc = smbldap_add(ldap_state->smbldap_state,
1865                                                  dn, mods);
1866                                 break;
1867                         case LDAP_MOD_REPLACE:
1868                                 rc = smbldap_modify(ldap_state->smbldap_state,
1869                                                     dn ,mods);
1870                                 break;
1871                         default:
1872                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n",
1873                                          ldap_op));
1874                                 return NT_STATUS_INVALID_PARAMETER;
1875                 }
1876
1877                 if (rc!=LDAP_SUCCESS) {
1878                         return NT_STATUS_UNSUCCESSFUL;
1879                 }
1880         }
1881
1882         return NT_STATUS_OK;
1883 }
1884
1885 /**********************************************************************
1886  Delete entry from LDAP for username.
1887 *********************************************************************/
1888
1889 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1890                                            struct samu * sam_acct)
1891 {
1892         struct ldapsam_privates *priv =
1893                 (struct ldapsam_privates *)my_methods->private_data;
1894         const char *sname;
1895         int rc;
1896         LDAPMessage *msg, *entry;
1897         NTSTATUS result = NT_STATUS_NO_MEMORY;
1898         const char **attr_list;
1899         TALLOC_CTX *mem_ctx;
1900
1901         if (!sam_acct) {
1902                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1903                 return NT_STATUS_INVALID_PARAMETER;
1904         }
1905
1906         sname = pdb_get_username(sam_acct);
1907
1908         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1909                   "LDAP.\n", sname));
1910
1911         mem_ctx = talloc_new(NULL);
1912         if (mem_ctx == NULL) {
1913                 DEBUG(0, ("talloc_new failed\n"));
1914                 goto done;
1915         }
1916
1917         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1918         if (attr_list == NULL) {
1919                 goto done;
1920         }
1921
1922         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1923
1924         if ((rc != LDAP_SUCCESS) ||
1925             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1926             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1927                 DEBUG(5, ("Could not find user %s\n", sname));
1928                 result = NT_STATUS_NO_SUCH_USER;
1929                 goto done;
1930         }
1931
1932         rc = ldapsam_delete_entry(
1933                 priv, mem_ctx, entry,
1934                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1935                 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1936                 attr_list);
1937
1938         result = (rc == LDAP_SUCCESS) ?
1939                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1940
1941  done:
1942         TALLOC_FREE(mem_ctx);
1943         return result;
1944 }
1945
1946 /**********************************************************************
1947  Update struct samu.
1948 *********************************************************************/
1949
1950 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1951 {
1952         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1953         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1954         int rc = 0;
1955         char *dn;
1956         LDAPMessage *result = NULL;
1957         LDAPMessage *entry = NULL;
1958         LDAPMod **mods = NULL;
1959         const char **attr_list;
1960
1961         result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1962         if (!result) {
1963                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1964                 if (pdb_get_username(newpwd) == NULL) {
1965                         return NT_STATUS_INVALID_PARAMETER;
1966                 }
1967                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1968                 TALLOC_FREE( attr_list );
1969                 if (rc != LDAP_SUCCESS) {
1970                         return NT_STATUS_UNSUCCESSFUL;
1971                 }
1972                 pdb_set_backend_private_data(newpwd, result, NULL,
1973                                              my_methods, PDB_CHANGED);
1974                 talloc_autofree_ldapmsg(newpwd, result);
1975         }
1976
1977         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1978                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1979                 return NT_STATUS_UNSUCCESSFUL;
1980         }
1981
1982         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1983         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1984         if (!dn) {
1985                 return NT_STATUS_UNSUCCESSFUL;
1986         }
1987
1988         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1989
1990         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1991                                 pdb_element_is_changed)) {
1992                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1993                 TALLOC_FREE(dn);
1994                 if (mods != NULL)
1995                         ldap_mods_free(mods,True);
1996                 return NT_STATUS_UNSUCCESSFUL;
1997         }
1998
1999         if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
2000             && (mods == NULL)) {
2001                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
2002                          pdb_get_username(newpwd)));
2003                 TALLOC_FREE(dn);
2004                 return NT_STATUS_OK;
2005         }
2006
2007         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, pdb_element_is_changed);
2008
2009         if (mods != NULL) {
2010                 ldap_mods_free(mods,True);
2011         }
2012
2013         TALLOC_FREE(dn);
2014
2015         /*
2016          * We need to set the backend private data to NULL here. For example
2017          * setuserinfo level 25 does a pdb_update_sam_account twice on the
2018          * same one, and with the explicit delete / add logic for attribute
2019          * values the second time we would use the wrong "old" value which
2020          * does not exist in LDAP anymore. Thus the LDAP server would refuse
2021          * the update.
2022          * The existing LDAPMessage is still being auto-freed by the
2023          * destructor.
2024          */
2025         pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
2026                                      PDB_CHANGED);
2027
2028         if (!NT_STATUS_IS_OK(ret)) {
2029                 return ret;
2030         }
2031
2032         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
2033                   pdb_get_username(newpwd)));
2034         return NT_STATUS_OK;
2035 }
2036
2037 /***************************************************************************
2038  Renames a struct samu
2039  - The "rename user script" has full responsibility for changing everything
2040 ***************************************************************************/
2041
2042 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
2043                                      TALLOC_CTX *tmp_ctx,
2044                                      uint32_t group_rid,
2045                                      uint32_t member_rid);
2046
2047 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2048                                                TALLOC_CTX *mem_ctx,
2049                                                struct samu *user,
2050                                                struct dom_sid **pp_sids,
2051                                                gid_t **pp_gids,
2052                                                uint32_t *p_num_groups);
2053
2054 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
2055                                            struct samu *old_acct,
2056                                            const char *newname)
2057 {
2058         const char *oldname;
2059         int rc;
2060         char *rename_script = NULL;
2061         fstring oldname_lower, newname_lower;
2062
2063         if (!old_acct) {
2064                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
2065                 return NT_STATUS_INVALID_PARAMETER;
2066         }
2067         if (!newname) {
2068                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
2069                 return NT_STATUS_INVALID_PARAMETER;
2070         }
2071
2072         oldname = pdb_get_username(old_acct);
2073
2074         /* rename the posix user */
2075         rename_script = SMB_STRDUP(lp_renameuser_script());
2076         if (rename_script == NULL) {
2077                 return NT_STATUS_NO_MEMORY;
2078         }
2079
2080         if (!(*rename_script)) {
2081                 SAFE_FREE(rename_script);
2082                 return NT_STATUS_ACCESS_DENIED;
2083         }
2084
2085         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
2086                    oldname, newname));
2087
2088         /* We have to allow the account name to end with a '$'.
2089            Also, follow the semantics in _samr_create_user() and lower case the
2090            posix name but preserve the case in passdb */
2091
2092         fstrcpy( oldname_lower, oldname );
2093         strlower_m( oldname_lower );
2094         fstrcpy( newname_lower, newname );
2095         strlower_m( newname_lower );
2096         rename_script = realloc_string_sub2(rename_script,
2097                                         "%unew",
2098                                         newname_lower,
2099                                         true,
2100                                         true);
2101         if (!rename_script) {
2102                 return NT_STATUS_NO_MEMORY;
2103         }
2104         rename_script = realloc_string_sub2(rename_script,
2105                                         "%uold",
2106                                         oldname_lower,
2107                                         true,
2108                                         true);
2109         rc = smbrun(rename_script, NULL);
2110
2111         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2112                           rename_script, rc));
2113
2114         SAFE_FREE(rename_script);
2115
2116         if (rc == 0) {
2117                 smb_nscd_flush_user_cache();
2118         }
2119
2120         if (rc)
2121                 return NT_STATUS_UNSUCCESSFUL;
2122
2123         return NT_STATUS_OK;
2124 }
2125
2126 /**********************************************************************
2127  Add struct samu to LDAP.
2128 *********************************************************************/
2129
2130 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2131 {
2132         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2133         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2134         int rc;
2135         LDAPMessage     *result = NULL;
2136         LDAPMessage     *entry  = NULL;
2137         LDAPMod         **mods = NULL;
2138         int             ldap_op = LDAP_MOD_REPLACE;
2139         uint32_t                num_result;
2140         const char      **attr_list;
2141         char *escape_user = NULL;
2142         const char      *username = pdb_get_username(newpwd);
2143         const struct dom_sid    *sid = pdb_get_user_sid(newpwd);
2144         char *filter = NULL;
2145         char *dn = NULL;
2146         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2147         TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2148
2149         if (!ctx) {
2150                 return NT_STATUS_NO_MEMORY;
2151         }
2152
2153         if (!username || !*username) {
2154                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2155                 status = NT_STATUS_INVALID_PARAMETER;
2156                 goto fn_exit;
2157         }
2158
2159         /* free this list after the second search or in case we exit on failure */
2160         attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2161
2162         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2163
2164         if (rc != LDAP_SUCCESS) {
2165                 goto fn_exit;
2166         }
2167
2168         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2169                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
2170                          username));
2171                 goto fn_exit;
2172         }
2173         ldap_msgfree(result);
2174         result = NULL;
2175
2176         if (pdb_element_is_set_or_changed(newpwd, PDB_USERSID)) {
2177                 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2178                                                   sid, &result);
2179                 if (rc == LDAP_SUCCESS) {
2180                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2181                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2182                                          "already in the base, with samba "
2183                                          "attributes\n", sid_string_dbg(sid)));
2184                                 goto fn_exit;
2185                         }
2186                         ldap_msgfree(result);
2187                         result = NULL;
2188                 }
2189         }
2190
2191         /* does the entry already exist but without a samba attributes?
2192            we need to return the samba attributes here */
2193
2194         escape_user = escape_ldap_string(talloc_tos(), username);
2195         filter = talloc_strdup(attr_list, "(uid=%u)");
2196         if (!filter) {
2197                 status = NT_STATUS_NO_MEMORY;
2198                 goto fn_exit;
2199         }
2200         filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2201         TALLOC_FREE(escape_user);
2202         if (!filter) {
2203                 status = NT_STATUS_NO_MEMORY;
2204                 goto fn_exit;
2205         }
2206
2207         rc = smbldap_search_suffix(ldap_state->smbldap_state,
2208                                    filter, attr_list, &result);
2209         if ( rc != LDAP_SUCCESS ) {
2210                 goto fn_exit;
2211         }
2212
2213         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2214
2215         if (num_result > 1) {
2216                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2217                 goto fn_exit;
2218         }
2219
2220         /* Check if we need to update an existing entry */
2221         if (num_result == 1) {
2222                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2223                 ldap_op = LDAP_MOD_REPLACE;
2224                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2225                 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2226                 if (!dn) {
2227                         status = NT_STATUS_NO_MEMORY;
2228                         goto fn_exit;
2229                 }
2230
2231         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2232
2233                 /* There might be a SID for this account already - say an idmap entry */
2234
2235                 filter = talloc_asprintf(ctx,
2236                                 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2237                                  get_userattr_key2string(ldap_state->schema_ver,
2238                                          LDAP_ATTR_USER_SID),
2239                                  sid_string_talloc(ctx, sid),
2240                                  LDAP_OBJ_IDMAP_ENTRY,
2241                                  LDAP_OBJ_SID_ENTRY);
2242                 if (!filter) {
2243                         status = NT_STATUS_NO_MEMORY;
2244                         goto fn_exit;
2245                 }
2246
2247                 /* free old result before doing a new search */
2248                 if (result != NULL) {
2249                         ldap_msgfree(result);
2250                         result = NULL;
2251                 }
2252                 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2253                                            filter, attr_list, &result);
2254
2255                 if ( rc != LDAP_SUCCESS ) {
2256                         goto fn_exit;
2257                 }
2258
2259                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2260
2261                 if (num_result > 1) {
2262                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2263                         goto fn_exit;
2264                 }
2265
2266                 /* Check if we need to update an existing entry */
2267                 if (num_result == 1) {
2268
2269                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2270                         ldap_op = LDAP_MOD_REPLACE;
2271                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2272                         dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2273                         if (!dn) {
2274                                 status = NT_STATUS_NO_MEMORY;
2275                                 goto fn_exit;
2276                         }
2277                 }
2278         }
2279
2280         if (num_result == 0) {
2281                 char *escape_username;
2282                 /* Check if we need to add an entry */
2283                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2284                 ldap_op = LDAP_MOD_ADD;
2285
2286                 escape_username = escape_rdn_val_string_alloc(username);
2287                 if (!escape_username) {
2288                         status = NT_STATUS_NO_MEMORY;
2289                         goto fn_exit;
2290                 }
2291
2292                 if (username[strlen(username)-1] == '$') {
2293                         dn = talloc_asprintf(ctx,
2294                                         "uid=%s,%s",
2295                                         escape_username,
2296                                         lp_ldap_machine_suffix());
2297                 } else {
2298                         dn = talloc_asprintf(ctx,
2299                                         "uid=%s,%s",
2300                                         escape_username,
2301                                         lp_ldap_user_suffix());
2302                 }
2303
2304                 SAFE_FREE(escape_username);
2305                 if (!dn) {
2306                         status = NT_STATUS_NO_MEMORY;
2307                         goto fn_exit;
2308                 }
2309         }
2310
2311         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2312                                 pdb_element_is_set_or_changed)) {
2313                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2314                 if (mods != NULL) {
2315                         ldap_mods_free(mods, true);
2316                 }
2317                 goto fn_exit;
2318         }
2319
2320         if (mods == NULL) {
2321                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2322                 goto fn_exit;
2323         }
2324         switch ( ldap_state->schema_ver ) {
2325                 case SCHEMAVER_SAMBAACCOUNT:
2326                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2327                         break;
2328                 case SCHEMAVER_SAMBASAMACCOUNT:
2329                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2330                         break;
2331                 default:
2332                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2333                         break;
2334         }
2335
2336         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, pdb_element_is_set_or_changed);
2337         if (!NT_STATUS_IS_OK(ret)) {
2338                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2339                          pdb_get_username(newpwd),dn));
2340                 ldap_mods_free(mods, true);
2341                 goto fn_exit;
2342         }
2343
2344         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2345         ldap_mods_free(mods, true);
2346
2347         status = NT_STATUS_OK;
2348
2349   fn_exit:
2350
2351         TALLOC_FREE(ctx);
2352         if (result) {
2353                 ldap_msgfree(result);
2354         }
2355         return status;
2356 }
2357
2358 /**********************************************************************
2359  *********************************************************************/
2360
2361 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2362                                      const char *filter,
2363                                      LDAPMessage ** result)
2364 {
2365         int scope = LDAP_SCOPE_SUBTREE;
2366         int rc;
2367         const char **attr_list;
2368
2369         attr_list = get_attr_list(NULL, groupmap_attr_list);
2370         rc = smbldap_search(ldap_state->smbldap_state,
2371                             lp_ldap_suffix (), scope,
2372                             filter, attr_list, 0, result);
2373         TALLOC_FREE(attr_list);
2374
2375         return rc;
2376 }
2377
2378 /**********************************************************************
2379  *********************************************************************/
2380
2381 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2382                                  GROUP_MAP *map, LDAPMessage *entry)
2383 {
2384         char *temp = NULL;
2385         TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2386
2387         if (ldap_state == NULL || map == NULL || entry == NULL ||
2388                         ldap_state->smbldap_state->ldap_struct == NULL) {
2389                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2390                 TALLOC_FREE(ctx);
2391                 return false;
2392         }
2393
2394         temp = smbldap_talloc_single_attribute(
2395                         ldap_state->smbldap_state->ldap_struct,
2396                         entry,
2397                         get_attr_key2string(groupmap_attr_list,
2398                                 LDAP_ATTR_GIDNUMBER),
2399                         ctx);
2400         if (!temp) {
2401                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2402                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2403                 TALLOC_FREE(ctx);
2404                 return false;
2405         }
2406         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2407
2408         map->gid = (gid_t)atol(temp);
2409
2410         TALLOC_FREE(temp);
2411         temp = smbldap_talloc_single_attribute(
2412                         ldap_state->smbldap_state->ldap_struct,
2413                         entry,
2414                         get_attr_key2string(groupmap_attr_list,
2415                                 LDAP_ATTR_GROUP_SID),
2416                         ctx);
2417         if (!temp) {
2418                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2419                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2420                 TALLOC_FREE(ctx);
2421                 return false;
2422         }
2423
2424         if (!string_to_sid(&map->sid, temp)) {
2425                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2426                 TALLOC_FREE(ctx);
2427                 return false;
2428         }
2429
2430         TALLOC_FREE(temp);
2431         temp = smbldap_talloc_single_attribute(
2432                         ldap_state->smbldap_state->ldap_struct,
2433                         entry,
2434                         get_attr_key2string(groupmap_attr_list,
2435                                 LDAP_ATTR_GROUP_TYPE),
2436                         ctx);
2437         if (!temp) {
2438                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2439                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2440                 TALLOC_FREE(ctx);
2441                 return false;
2442         }
2443         map->sid_name_use = (enum lsa_SidType)atol(temp);
2444
2445         if ((map->sid_name_use < SID_NAME_USER) ||
2446                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2447                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2448                 TALLOC_FREE(ctx);
2449                 return false;
2450         }
2451
2452         TALLOC_FREE(temp);
2453         temp = smbldap_talloc_single_attribute(
2454                         ldap_state->smbldap_state->ldap_struct,
2455                         entry,
2456                         get_attr_key2string(groupmap_attr_list,
2457                                 LDAP_ATTR_DISPLAY_NAME),
2458                         ctx);
2459         if (!temp) {
2460                 temp = smbldap_talloc_single_attribute(
2461                                 ldap_state->smbldap_state->ldap_struct,
2462                                 entry,
2463                                 get_attr_key2string(groupmap_attr_list,
2464                                         LDAP_ATTR_CN),
2465                                 ctx);
2466                 if (!temp) {
2467                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2468 for gidNumber(%lu)\n",(unsigned long)map->gid));
2469                         TALLOC_FREE(ctx);
2470                         return false;
2471                 }
2472         }
2473         fstrcpy(map->nt_name, temp);
2474
2475         TALLOC_FREE(temp);
2476         temp = smbldap_talloc_single_attribute(
2477                         ldap_state->smbldap_state->ldap_struct,
2478                         entry,
2479                         get_attr_key2string(groupmap_attr_list,
2480                                 LDAP_ATTR_DESC),
2481                         ctx);
2482         if (!temp) {
2483                 temp = talloc_strdup(ctx, "");
2484                 if (!temp) {
2485                         TALLOC_FREE(ctx);
2486                         return false;
2487                 }
2488         }
2489         fstrcpy(map->comment, temp);
2490
2491         if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2492                 store_gid_sid_cache(&map->sid, map->gid);
2493                 idmap_cache_set_sid2gid(&map->sid, map->gid);
2494         }
2495
2496         TALLOC_FREE(ctx);
2497         return true;
2498 }
2499
2500 /**********************************************************************
2501  *********************************************************************/
2502
2503 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2504                                  const char *filter,
2505                                  GROUP_MAP *map)
2506 {
2507         struct ldapsam_privates *ldap_state =
2508                 (struct ldapsam_privates *)methods->private_data;
2509         LDAPMessage *result = NULL;
2510         LDAPMessage *entry = NULL;
2511         int count;
2512
2513         if (ldapsam_search_one_group(ldap_state, filter, &result)
2514             != LDAP_SUCCESS) {
2515                 return NT_STATUS_NO_SUCH_GROUP;
2516         }
2517
2518         count = ldap_count_entries(priv2ld(ldap_state), result);
2519
2520         if (count < 1) {
2521                 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2522                           "%s\n", filter));
2523                 ldap_msgfree(result);
2524                 return NT_STATUS_NO_SUCH_GROUP;
2525         }
2526
2527         if (count > 1) {
2528                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2529                           "count=%d\n", filter, count));
2530                 ldap_msgfree(result);
2531                 return NT_STATUS_NO_SUCH_GROUP;
2532         }
2533
2534         entry = ldap_first_entry(priv2ld(ldap_state), result);
2535
2536         if (!entry) {
2537                 ldap_msgfree(result);
2538                 return NT_STATUS_UNSUCCESSFUL;
2539         }
2540
2541         if (!init_group_from_ldap(ldap_state, map, entry)) {
2542                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2543                           "group filter %s\n", filter));
2544                 ldap_msgfree(result);
2545                 return NT_STATUS_NO_SUCH_GROUP;
2546         }
2547
2548         ldap_msgfree(result);
2549         return NT_STATUS_OK;
2550 }
2551
2552 /**********************************************************************
2553  *********************************************************************/
2554
2555 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2556                                  struct dom_sid sid)
2557 {
2558         char *filter = NULL;
2559         NTSTATUS status;
2560         fstring tmp;
2561
2562         if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2563                 LDAP_OBJ_GROUPMAP,
2564                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2565                 sid_to_fstring(tmp, &sid)) < 0) {
2566                 return NT_STATUS_NO_MEMORY;
2567         }
2568
2569         status = ldapsam_getgroup(methods, filter, map);
2570         SAFE_FREE(filter);
2571         return status;
2572 }
2573
2574 /**********************************************************************
2575  *********************************************************************/
2576
2577 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2578                                  gid_t gid)
2579 {
2580         char *filter = NULL;
2581         NTSTATUS status;
2582
2583         if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2584                 LDAP_OBJ_GROUPMAP,
2585                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2586                 (unsigned long)gid) < 0) {
2587                 return NT_STATUS_NO_MEMORY;
2588         }
2589
2590         status = ldapsam_getgroup(methods, filter, map);
2591         SAFE_FREE(filter);
2592         return status;
2593 }
2594
2595 /**********************************************************************
2596  *********************************************************************/
2597
2598 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2599                                  const char *name)
2600 {
2601         char *filter = NULL;
2602         char *escape_name = escape_ldap_string(talloc_tos(), name);
2603         NTSTATUS status;
2604
2605         if (!escape_name) {
2606                 return NT_STATUS_NO_MEMORY;
2607         }
2608
2609         if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2610                 LDAP_OBJ_GROUPMAP,
2611                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2612                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2613                 escape_name) < 0) {
2614                 TALLOC_FREE(escape_name);
2615                 return NT_STATUS_NO_MEMORY;
2616         }
2617
2618         TALLOC_FREE(escape_name);
2619         status = ldapsam_getgroup(methods, filter, map);
2620         SAFE_FREE(filter);
2621         return status;
2622 }
2623
2624 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2625                                            LDAPMessage *entry,
2626                                            const struct dom_sid *domain_sid,
2627                                            uint32_t *rid)
2628 {
2629         fstring str;
2630         struct dom_sid sid;
2631
2632         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2633                                           str, sizeof(str)-1)) {
2634                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2635                 return False;
2636         }
2637
2638         if (!string_to_sid(&sid, str)) {
2639                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2640                 return False;
2641         }
2642
2643         if (dom_sid_compare_domain(&sid, domain_sid) != 0) {
2644                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2645                            str, sid_string_dbg(domain_sid)));
2646                 return False;
2647         }
2648
2649         if (!sid_peek_rid(&sid, rid)) {
2650                 DEBUG(10, ("Could not peek into RID\n"));
2651                 return False;
2652         }
2653
2654         return True;
2655 }
2656
2657 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2658                                            TALLOC_CTX *mem_ctx,
2659                                            const struct dom_sid *group,
2660                                            uint32_t **pp_member_rids,
2661                                            size_t *p_num_members)
2662 {
2663         struct ldapsam_privates *ldap_state =
2664                 (struct ldapsam_privates *)methods->private_data;
2665         struct smbldap_state *conn = ldap_state->smbldap_state;
2666         const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2667         const char *sid_attrs[] = { "sambaSID", NULL };
2668         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2669         LDAPMessage *result = NULL;
2670         LDAPMessage *entry;
2671         char *filter;
2672         char **values = NULL;
2673         char **memberuid;
2674         char *gidstr;
2675         int rc, count;
2676
2677         *pp_member_rids = NULL;
2678         *p_num_members = 0;
2679
2680         filter = talloc_asprintf(mem_ctx,
2681                                  "(&(objectClass=%s)"
2682                                  "(objectClass=%s)"
2683                                  "(sambaSID=%s))",
2684                                  LDAP_OBJ_POSIXGROUP,
2685                                  LDAP_OBJ_GROUPMAP,
2686                                  sid_string_talloc(mem_ctx, group));
2687         if (filter == NULL) {
2688                 ret = NT_STATUS_NO_MEMORY;
2689                 goto done;
2690         }
2691
2692         rc = smbldap_search(conn, lp_ldap_suffix(),
2693                             LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2694                             &result);
2695
2696         if (rc != LDAP_SUCCESS)
2697                 goto done;
2698
2699         talloc_autofree_ldapmsg(mem_ctx, result);
2700
2701         count = ldap_count_entries(conn->ldap_struct, result);
2702
2703         if (count > 1) {
2704                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2705                           sid_string_dbg(group)));
2706                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2707                 goto done;
2708         }
2709
2710         if (count == 0) {
2711                 ret = NT_STATUS_NO_SUCH_GROUP;
2712                 goto done;
2713         }
2714
2715         entry = ldap_first_entry(conn->ldap_struct, result);
2716         if (entry == NULL)
2717                 goto done;
2718
2719         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2720         if (!gidstr) {
2721                 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2722                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2723                 goto done;
2724         }
2725
2726         values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2727
2728         if ((values != NULL) && (values[0] != NULL)) {
2729
2730                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2731                 if (filter == NULL) {
2732                         ret = NT_STATUS_NO_MEMORY;
2733                         goto done;
2734                 }
2735
2736                 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2737                         char *escape_memberuid;
2738
2739                         escape_memberuid = escape_ldap_string(talloc_tos(),
2740                                                               *memberuid);
2741                         if (escape_memberuid == NULL) {
2742                                 ret = NT_STATUS_NO_MEMORY;
2743                                 goto done;
2744                         }
2745
2746                         filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2747                         TALLOC_FREE(escape_memberuid);
2748                         if (filter == NULL) {
2749                                 ret = NT_STATUS_NO_MEMORY;
2750                                 goto done;
2751                         }
2752                 }
2753
2754                 filter = talloc_asprintf_append_buffer(filter, "))");
2755                 if (filter == NULL) {
2756                         ret = NT_STATUS_NO_MEMORY;
2757                         goto done;
2758                 }
2759
2760                 rc = smbldap_search(conn, lp_ldap_suffix(),
2761                                     LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2762                                     &result);
2763
2764                 if (rc != LDAP_SUCCESS)
2765                         goto done;
2766
2767                 count = ldap_count_entries(conn->ldap_struct, result);
2768                 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2769
2770                 talloc_autofree_ldapmsg(mem_ctx, result);
2771
2772                 for (entry = ldap_first_entry(conn->ldap_struct, result);
2773                      entry != NULL;
2774                      entry = ldap_next_entry(conn->ldap_struct, entry))
2775                 {
2776                         char *sidstr;
2777                         struct dom_sid sid;
2778                         uint32_t rid;
2779
2780                         sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2781                                                                  entry, "sambaSID",
2782                                                                  mem_ctx);
2783                         if (!sidstr) {
2784                                 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2785                                           "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2786                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2787                                 goto done;
2788                         }
2789
2790                         if (!string_to_sid(&sid, sidstr))
2791                                 goto done;
2792
2793                         if (!sid_check_is_in_our_domain(&sid)) {
2794                                 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2795                                           "in our domain\n"));
2796                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2797                                 goto done;
2798                         }
2799
2800                         sid_peek_rid(&sid, &rid);
2801
2802                         if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2803                                                 p_num_members)) {
2804                                 ret = NT_STATUS_NO_MEMORY;
2805                                 goto done;
2806                         }
2807                 }
2808         }
2809
2810         filter = talloc_asprintf(mem_ctx,
2811                                  "(&(objectClass=%s)"
2812                                  "(gidNumber=%s))",
2813                                  LDAP_OBJ_SAMBASAMACCOUNT,
2814                                  gidstr);
2815
2816         rc = smbldap_search(conn, lp_ldap_suffix(),
2817                             LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2818                             &result);
2819
2820         if (rc != LDAP_SUCCESS)
2821                 goto done;
2822
2823         talloc_autofree_ldapmsg(mem_ctx, result);
2824
2825         for (entry = ldap_first_entry(conn->ldap_struct, result);
2826              entry != NULL;
2827              entry = ldap_next_entry(conn->ldap_struct, entry))
2828         {
2829                 uint32_t rid;
2830
2831                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2832                                                     entry,
2833                                                     get_global_sam_sid(),
2834                                                     &rid)) {
2835                         DEBUG(0, ("Severe DB error, %s can't miss the samba SID"                                                                "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2836                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2837                         goto done;
2838                 }
2839
2840                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2841                                         p_num_members)) {
2842                         ret = NT_STATUS_NO_MEMORY;
2843                         goto done;
2844                 }
2845         }
2846
2847         ret = NT_STATUS_OK;
2848
2849  done:
2850
2851         if (values)
2852                 ldap_value_free(values);
2853
2854         return ret;
2855 }
2856
2857 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2858                                                TALLOC_CTX *mem_ctx,
2859                                                struct samu *user,
2860                                                struct dom_sid **pp_sids,
2861                                                gid_t **pp_gids,
2862                                                uint32_t *p_num_groups)
2863 {
2864         struct ldapsam_privates *ldap_state =
2865                 (struct ldapsam_privates *)methods->private_data;
2866         struct smbldap_state *conn = ldap_state->smbldap_state;
2867         char *filter;
2868         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2869         char *escape_name;
2870         int rc, count;
2871         LDAPMessage *result = NULL;
2872         LDAPMessage *entry;
2873         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2874         uint32_t num_sids;
2875         uint32_t num_gids;
2876         char *gidstr;
2877         gid_t primary_gid = -1;
2878
2879         *pp_sids = NULL;
2880         num_sids = 0;
2881
2882         if (pdb_get_username(user) == NULL) {
2883                 return NT_STATUS_INVALID_PARAMETER;
2884         }
2885
2886         escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2887         if (escape_name == NULL)
2888                 return NT_STATUS_NO_MEMORY;
2889
2890         if (user->unix_pw) {
2891                 primary_gid = user->unix_pw->pw_gid;
2892         } else {
2893                 /* retrieve the users primary gid */
2894                 filter = talloc_asprintf(mem_ctx,
2895                                          "(&(objectClass=%s)(uid=%s))",
2896                                          LDAP_OBJ_SAMBASAMACCOUNT,
2897                                          escape_name);
2898                 if (filter == NULL) {
2899                         ret = NT_STATUS_NO_MEMORY;
2900                         goto done;
2901                 }
2902
2903                 rc = smbldap_search(conn, lp_ldap_suffix(),
2904                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2905
2906                 if (rc != LDAP_SUCCESS)
2907                         goto done;
2908
2909                 talloc_autofree_ldapmsg(mem_ctx, result);
2910
2911                 count = ldap_count_entries(priv2ld(ldap_state), result);
2912
2913                 switch (count) {
2914                 case 0:
2915                         DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2916                         ret = NT_STATUS_NO_SUCH_USER;
2917                         goto done;
2918                 case 1:
2919                         entry = ldap_first_entry(priv2ld(ldap_state), result);
2920
2921                         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2922                         if (!gidstr) {
2923                                 DEBUG (1, ("Unable to find the member's gid!\n"));
2924                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2925                                 goto done;
2926                         }
2927                         primary_gid = strtoul(gidstr, NULL, 10);
2928                         break;
2929                 default:
2930                         DEBUG(1, ("found more than one account with the same user name ?!\n"));
2931                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2932                         goto done;
2933                 }
2934         }
2935
2936         filter = talloc_asprintf(mem_ctx,
2937                                  "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2938                                  LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2939         if (filter == NULL) {
2940                 ret = NT_STATUS_NO_MEMORY;
2941                 goto done;
2942         }
2943
2944         rc = smbldap_search(conn, lp_ldap_suffix(),
2945                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2946
2947         if (rc != LDAP_SUCCESS)
2948                 goto done;
2949
2950         talloc_autofree_ldapmsg(mem_ctx, result);
2951
2952         num_gids = 0;
2953         *pp_gids = NULL;
2954
2955         num_sids = 0;
2956         *pp_sids = NULL;
2957
2958         /* We need to add the primary group as the first gid/sid */
2959
2960         if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2961                 ret = NT_STATUS_NO_MEMORY;
2962                 goto done;
2963         }
2964
2965         /* This sid will be replaced later */
2966
2967         ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2968                                       &num_sids);
2969         if (!NT_STATUS_IS_OK(ret)) {
2970                 goto done;
2971         }
2972
2973         for (entry = ldap_first_entry(conn->ldap_struct, result);
2974              entry != NULL;
2975              entry = ldap_next_entry(conn->ldap_struct, entry))
2976         {
2977                 fstring str;
2978                 struct dom_sid sid;
2979                 gid_t gid;
2980                 char *end;
2981
2982                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2983                                                   entry, "sambaSID",
2984                                                   str, sizeof(str)-1))
2985                         continue;
2986
2987                 if (!string_to_sid(&sid, str))
2988                         goto done;
2989
2990                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2991                                                   entry, "gidNumber",
2992                                                   str, sizeof(str)-1))
2993                         continue;
2994
2995                 gid = strtoul(str, &end, 10);
2996
2997                 if (PTR_DIFF(end, str) != strlen(str))
2998                         goto done;
2999
3000                 if (gid == primary_gid) {
3001                         sid_copy(&(*pp_sids)[0], &sid);
3002                 } else {
3003                         if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
3004                                                 &num_gids)) {
3005                                 ret = NT_STATUS_NO_MEMORY;
3006                                 goto done;
3007                         }
3008                         ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
3009                                                       &num_sids);
3010                         if (!NT_STATUS_IS_OK(ret)) {
3011                                 goto done;
3012                         }
3013                 }
3014         }
3015
3016         if (dom_sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
3017                 DEBUG(3, ("primary group of [%s] not found\n",
3018                           pdb_get_username(user)));
3019                 goto done;
3020         }
3021
3022         *p_num_groups = num_sids;
3023
3024         ret = NT_STATUS_OK;
3025
3026  done:
3027
3028         TALLOC_FREE(escape_name);
3029         return ret;
3030 }
3031
3032 /**********************************************************************
3033  * Augment a posixGroup object with a sambaGroupMapping domgroup
3034  *********************************************************************/
3035
3036 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
3037                                        struct ldapsam_privates *ldap_state,
3038                                        GROUP_MAP *map)
3039 {
3040         const char *filter, *dn;
3041         LDAPMessage *msg, *entry;
3042         LDAPMod **mods;
3043         int rc;
3044
3045         filter = talloc_asprintf(mem_ctx,
3046                                  "(&(objectClass=%s)(gidNumber=%u))",
3047                                  LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
3048         if (filter == NULL) {
3049                 return NT_STATUS_NO_MEMORY;
3050         }
3051
3052         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3053                                    get_attr_list(mem_ctx, groupmap_attr_list),
3054                                    &msg);
3055         talloc_autofree_ldapmsg(mem_ctx, msg);
3056
3057         if ((rc != LDAP_SUCCESS) ||
3058             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3059             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3060                 return NT_STATUS_NO_SUCH_GROUP;
3061         }
3062
3063         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3064         if (dn == NULL) {
3065                 return NT_STATUS_NO_MEMORY;
3066         }
3067
3068         mods = NULL;
3069         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3070                         LDAP_OBJ_GROUPMAP);
3071         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3072                          sid_string_talloc(mem_ctx, &map->sid));
3073         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3074                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3075         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3076                          map->nt_name);
3077         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3078                          map->comment);
3079         talloc_autofree_ldapmod(mem_ctx, mods);
3080
3081         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3082         if (rc != LDAP_SUCCESS) {
3083                 return NT_STATUS_ACCESS_DENIED;
3084         }
3085
3086         return NT_STATUS_OK;
3087 }
3088
3089 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3090                                                 GROUP_MAP *map)
3091 {
3092         struct ldapsam_privates *ldap_state =
3093                 (struct ldapsam_privates *)methods->private_data;
3094         LDAPMessage *msg = NULL;
3095         LDAPMod **mods = NULL;
3096         const char *attrs[] = { NULL };
3097         char *filter;
3098
3099         char *dn;
3100         TALLOC_CTX *mem_ctx;
3101         NTSTATUS result;
3102
3103         struct dom_sid sid;
3104
3105         int rc;
3106
3107         mem_ctx = talloc_new(NULL);
3108         if (mem_ctx == NULL) {
3109                 DEBUG(0, ("talloc_new failed\n"));
3110                 return NT_STATUS_NO_MEMORY;
3111         }
3112
3113         filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3114                                  sid_string_talloc(mem_ctx, &map->sid));
3115         if (filter == NULL) {
3116                 result = NT_STATUS_NO_MEMORY;
3117                 goto done;
3118         }
3119
3120         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3121                             LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3122         talloc_autofree_ldapmsg(mem_ctx, msg);
3123
3124         if ((rc == LDAP_SUCCESS) &&
3125             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3126
3127                 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3128                           "group mapping entry\n", sid_string_dbg(&map->sid)));
3129                 result = NT_STATUS_GROUP_EXISTS;
3130                 goto done;
3131         }
3132
3133         switch (map->sid_name_use) {
3134
3135         case SID_NAME_DOM_GRP:
3136                 /* To map a domain group we need to have a posix group
3137                    to attach to. */
3138                 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3139                 goto done;
3140                 break;
3141
3142         case SID_NAME_ALIAS:
3143                 if (!sid_check_is_in_our_domain(&map->sid) 
3144                         && !sid_check_is_in_builtin(&map->sid) ) 
3145                 {
3146                         DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3147                                   sid_string_dbg(&map->sid)));
3148                         result = NT_STATUS_INVALID_PARAMETER;
3149                         goto done;
3150                 }
3151                 break;
3152
3153         default:
3154                 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3155                           sid_type_lookup(map->sid_name_use)));
3156                 result = NT_STATUS_INVALID_PARAMETER;
3157                 goto done;
3158         }
3159
3160         /* Domain groups have been mapped in a separate routine, we have to
3161          * create an alias now */
3162
3163         if (map->gid == -1) {
3164                 DEBUG(10, ("Refusing to map gid==-1\n"));
3165                 result = NT_STATUS_INVALID_PARAMETER;
3166                 goto done;
3167         }
3168
3169         if (pdb_gid_to_sid(map->gid, &sid)) {
3170                 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3171                           "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3172                 result = NT_STATUS_GROUP_EXISTS;
3173                 goto done;
3174         }
3175
3176         /* Ok, enough checks done. It's still racy to go ahead now, but that's
3177          * the best we can get out of LDAP. */
3178
3179         dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3180                              sid_string_talloc(mem_ctx, &map->sid),
3181                              lp_ldap_group_suffix());
3182         if (dn == NULL) {
3183                 result = NT_STATUS_NO_MEMORY;
3184                 goto done;
3185         }
3186
3187         mods = NULL;
3188
3189         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3190                          LDAP_OBJ_SID_ENTRY);
3191         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3192                          LDAP_OBJ_GROUPMAP);
3193         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3194                          sid_string_talloc(mem_ctx, &map->sid));
3195         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3196                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3197         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3198                          map->nt_name);
3199         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3200                          map->comment);
3201         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3202                          talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3203         talloc_autofree_ldapmod(mem_ctx, mods);
3204
3205         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3206
3207         result = (rc == LDAP_SUCCESS) ?
3208                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3209
3210  done:
3211         TALLOC_FREE(mem_ctx);
3212         return result;
3213 }
3214
3215 /**********************************************************************
3216  * Update a group mapping entry. We're quite strict about what can be changed:
3217  * Only the description and displayname may be changed. It simply does not
3218  * make any sense to change the SID, gid or the type in a mapping.
3219  *********************************************************************/
3220
3221 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3222                                                    GROUP_MAP *map)
3223 {
3224         struct ldapsam_privates *ldap_state =
3225                 (struct ldapsam_privates *)methods->private_data;
3226         int rc;
3227         const char *filter, *dn;
3228         LDAPMessage *msg = NULL;
3229         LDAPMessage *entry = NULL;
3230         LDAPMod **mods = NULL;
3231         TALLOC_CTX *mem_ctx;
3232         NTSTATUS result;
3233
3234         mem_ctx = talloc_new(NULL);
3235         if (mem_ctx == NULL) {
3236                 DEBUG(0, ("talloc_new failed\n"));
3237                 return NT_STATUS_NO_MEMORY;
3238         }
3239
3240         /* Make 100% sure that sid, gid and type are not changed by looking up
3241          * exactly the values we're given in LDAP. */
3242
3243         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3244                                  "(sambaSid=%s)(gidNumber=%u)"
3245                                  "(sambaGroupType=%d))",
3246                                  LDAP_OBJ_GROUPMAP,
3247                                  sid_string_talloc(mem_ctx, &map->sid),
3248                                  (unsigned int)map->gid, map->sid_name_use);
3249         if (filter == NULL) {
3250                 result = NT_STATUS_NO_MEMORY;
3251                 goto done;
3252         }
3253
3254         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3255                                    get_attr_list(mem_ctx, groupmap_attr_list),
3256                                    &msg);
3257         talloc_autofree_ldapmsg(mem_ctx, msg);
3258
3259         if ((rc != LDAP_SUCCESS) ||
3260             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3261             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3262                 result = NT_STATUS_NO_SUCH_GROUP;
3263                 goto done;
3264         }
3265
3266         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3267
3268         if (dn == NULL) {
3269                 result = NT_STATUS_NO_MEMORY;
3270                 goto done;
3271         }
3272
3273         mods = NULL;
3274         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3275                          map->nt_name);
3276         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3277                          map->comment);
3278         talloc_autofree_ldapmod(mem_ctx, mods);
3279
3280         if (mods == NULL) {
3281                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3282                           "nothing to do\n"));
3283                 result = NT_STATUS_OK;
3284                 goto done;
3285         }
3286
3287         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3288
3289         if (rc != LDAP_SUCCESS) {
3290                 result = NT_STATUS_ACCESS_DENIED;
3291                 goto done;
3292         }
3293
3294         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3295                   "group %lu in LDAP\n", (unsigned long)map->gid));
3296
3297         result = NT_STATUS_OK;
3298
3299  done:
3300         TALLOC_FREE(mem_ctx);
3301         return result;
3302 }
3303
3304 /**********************************************************************
3305  *********************************************************************/
3306
3307 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3308                                                    struct dom_sid sid)
3309 {
3310         struct ldapsam_privates *priv =
3311                 (struct ldapsam_privates *)methods->private_data;
3312         LDAPMessage *msg, *entry;
3313         int rc;
3314         NTSTATUS result;
3315         TALLOC_CTX *mem_ctx;
3316         char *filter;
3317
3318         mem_ctx = talloc_new(NULL);
3319         if (mem_ctx == NULL) {
3320                 DEBUG(0, ("talloc_new failed\n"));
3321                 return NT_STATUS_NO_MEMORY;
3322         }
3323
3324         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3325                                  LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3326                                  sid_string_talloc(mem_ctx, &sid));
3327         if (filter == NULL) {
3328                 result = NT_STATUS_NO_MEMORY;
3329                 goto done;
3330         }
3331         rc = smbldap_search_suffix(priv->smbldap_state, filter,
3332                                    get_attr_list(mem_ctx, groupmap_attr_list),
3333                                    &msg);
3334         talloc_autofree_ldapmsg(mem_ctx, msg);
3335
3336         if ((rc != LDAP_SUCCESS) ||
3337             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3338             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3339                 result = NT_STATUS_NO_SUCH_GROUP;
3340                 goto done;
3341         }
3342
3343         rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3344                                   get_attr_list(mem_ctx,
3345                                                 groupmap_attr_list_to_delete));
3346
3347         if ((rc == LDAP_NAMING_VIOLATION) ||
3348             (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3349             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3350                 const char *attrs[] = { "sambaGroupType", "description",
3351                                         "displayName", "sambaSIDList",
3352                                         NULL };
3353
3354                 /* Second try. Don't delete the sambaSID attribute, this is
3355                    for "old" entries that are tacked on a winbind
3356                    sambaIdmapEntry. */
3357
3358                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3359                                           LDAP_OBJ_GROUPMAP, attrs);
3360         }
3361
3362         if ((rc == LDAP_NAMING_VIOLATION) ||
3363             (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3364             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3365                 const char *attrs[] = { "sambaGroupType", "description",
3366                                         "displayName", "sambaSIDList",
3367                                         "gidNumber", NULL };
3368
3369                 /* Third try. This is a post-3.0.21 alias (containing only
3370                  * sambaSidEntry and sambaGroupMapping classes), we also have
3371                  * to delete the gidNumber attribute, only the sambaSidEntry
3372                  * remains */
3373
3374                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3375                                           LDAP_OBJ_GROUPMAP, attrs);
3376         }
3377
3378         result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3379
3380  done:
3381         TALLOC_FREE(mem_ctx);
3382         return result;
3383  }
3384
3385 /**********************************************************************
3386  *********************************************************************/
3387
3388 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3389                                     bool update)
3390 {
3391         struct ldapsam_privates *ldap_state =
3392                 (struct ldapsam_privates *)my_methods->private_data;
3393         char *filter = NULL;
3394         int rc;
3395         const char **attr_list;
3396
3397         filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3398         if (!filter) {
3399                 return NT_STATUS_NO_MEMORY;
3400         }
3401         attr_list = get_attr_list( NULL, groupmap_attr_list );
3402         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3403                             LDAP_SCOPE_SUBTREE, filter,
3404                             attr_list, 0, &ldap_state->result);
3405         TALLOC_FREE(attr_list);
3406
3407         if (rc != LDAP_SUCCESS) {
3408                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3409                           ldap_err2string(rc)));
3410                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3411                           lp_ldap_suffix(), filter));
3412                 ldap_msgfree(ldap_state->result);
3413                 ldap_state->result = NULL;
3414                 TALLOC_FREE(filter);
3415                 return NT_STATUS_UNSUCCESSFUL;
3416         }
3417
3418         TALLOC_FREE(filter);
3419
3420         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3421                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3422                                      ldap_state->result)));
3423
3424         ldap_state->entry =
3425                 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3426                                  ldap_state->result);
3427         ldap_state->index = 0;
3428
3429         return NT_STATUS_OK;
3430 }
3431
3432 /**********************************************************************
3433  *********************************************************************/
3434
3435 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3436 {
3437         ldapsam_endsampwent(my_methods);
3438 }
3439
3440 /**********************************************************************
3441  *********************************************************************/
3442
3443 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3444                                     GROUP_MAP *map)
3445 {
3446         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3447         struct ldapsam_privates *ldap_state =
3448                 (struct ldapsam_privates *)my_methods->private_data;
3449         bool bret = False;
3450
3451         while (!bret) {
3452                 if (!ldap_state->entry)
3453                         return ret;
3454
3455                 ldap_state->index++;
3456                 bret = init_group_from_ldap(ldap_state, map,
3457                                             ldap_state->entry);
3458
3459                 ldap_state->entry =
3460                         ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3461                                         ldap_state->entry);     
3462         }
3463
3464         return NT_STATUS_OK;
3465 }
3466
3467 /**********************************************************************
3468  *********************************************************************/
3469
3470 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3471                                            const struct dom_sid *domsid, enum lsa_SidType sid_name_use,
3472                                            GROUP_MAP **pp_rmap,
3473                                            size_t *p_num_entries,
3474                                            bool unix_only)
3475 {
3476         GROUP_MAP map = { 0, };
3477         size_t entries = 0;
3478
3479         *p_num_entries = 0;
3480         *pp_rmap = NULL;
3481
3482         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3483                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3484                           "passdb\n"));
3485                 return NT_STATUS_ACCESS_DENIED;
3486         }
3487
3488         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3489                 if (sid_name_use != SID_NAME_UNKNOWN &&
3490                     sid_name_use != map.sid_name_use) {
3491                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3492                                   "not of the requested type\n", map.nt_name));
3493                         continue;
3494                 }
3495                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3496                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3497                                   "non mapped\n", map.nt_name));
3498                         continue;
3499                 }
3500
3501                 (*pp_rmap)=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3502                 if (!(*pp_rmap)) {
3503                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3504                                  "enlarge group map!\n"));
3505                         return NT_STATUS_UNSUCCESSFUL;
3506                 }
3507
3508                 (*pp_rmap)[entries] = map;
3509
3510                 entries += 1;
3511
3512         }
3513         ldapsam_endsamgrent(methods);
3514
3515         *p_num_entries = entries;
3516
3517         return NT_STATUS_OK;
3518 }
3519
3520 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3521                                         const struct dom_sid *alias,
3522                                         const struct dom_sid *member,
3523                                         int modop)
3524 {
3525         struct ldapsam_privates *ldap_state =
3526                 (struct ldapsam_privates *)methods->private_data;
3527         char *dn = NULL;
3528         LDAPMessage *result = NULL;
3529         LDAPMessage *entry = NULL;
3530         int count;
3531         LDAPMod **mods = NULL;
3532         int rc;
3533         enum lsa_SidType type = SID_NAME_USE_NONE;
3534         fstring tmp;
3535
3536         char *filter = NULL;
3537
3538         if (sid_check_is_in_builtin(alias)) {
3539                 type = SID_NAME_ALIAS;
3540         }
3541
3542         if (sid_check_is_in_our_domain(alias)) {
3543                 type = SID_NAME_ALIAS;
3544         }
3545
3546         if (type == SID_NAME_USE_NONE) {
3547                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3548                           sid_string_dbg(alias)));
3549                 return NT_STATUS_NO_SUCH_ALIAS;
3550         }
3551
3552         if (asprintf(&filter,
3553                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3554                      LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3555                      type) < 0) {
3556                 return NT_STATUS_NO_MEMORY;
3557         }
3558
3559         if (ldapsam_search_one_group(ldap_state, filter,
3560                                      &result) != LDAP_SUCCESS) {
3561                 SAFE_FREE(filter);
3562                 return NT_STATUS_NO_SUCH_ALIAS;
3563         }
3564
3565         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3566                                    result);
3567
3568         if (count < 1) {
3569                 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3570                 ldap_msgfree(result);
3571                 SAFE_FREE(filter);
3572                 return NT_STATUS_NO_SUCH_ALIAS;
3573         }
3574
3575         if (count > 1) {
3576                 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3577                           "filter %s: count=%d\n", filter, count));
3578                 ldap_msgfree(result);
3579                 SAFE_FREE(filter);
3580                 return NT_STATUS_NO_SUCH_ALIAS;
3581         }
3582
3583         SAFE_FREE(filter);
3584
3585         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3586                                  result);
3587
3588         if (!entry) {
3589                 ldap_msgfree(result);
3590                 return NT_STATUS_UNSUCCESSFUL;
3591         }
3592
3593         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3594         if (!dn) {
3595                 ldap_msgfree(result);
3596                 return NT_STATUS_UNSUCCESSFUL;
3597         }
3598
3599         smbldap_set_mod(&mods, modop,
3600                         get_attr_key2string(groupmap_attr_list,
3601                                             LDAP_ATTR_SID_LIST),
3602                         sid_to_fstring(tmp, member));
3603
3604         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3605
3606         ldap_mods_free(mods, True);
3607         ldap_msgfree(result);
3608         TALLOC_FREE(dn);
3609
3610         if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3611                 return NT_STATUS_MEMBER_IN_ALIAS;
3612         }
3613
3614         if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3615                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3616         }
3617
3618         if (rc != LDAP_SUCCESS) {
3619                 return NT_STATUS_UNSUCCESSFUL;
3620         }
3621
3622         return NT_STATUS_OK;
3623 }
3624
3625 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3626                                      const struct dom_sid *alias,
3627                                      const struct dom_sid *member)
3628 {
3629         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3630 }
3631
3632 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3633                                      const struct dom_sid *alias,
3634                                      const struct dom_sid *member)
3635 {
3636         return ldapsam_modify_aliasmem(methods, alias, member,
3637                                        LDAP_MOD_DELETE);
3638 }
3639
3640 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3641                                       const struct dom_sid *alias,
3642                                       TALLOC_CTX *mem_ctx,
3643                                       struct dom_sid **pp_members,
3644                                       size_t *p_num_members)
3645 {
3646         struct ldapsam_privates *ldap_state =
3647                 (struct ldapsam_privates *)methods->private_data;
3648         LDAPMessage *result = NULL;
3649         LDAPMessage *entry = NULL;
3650         int count;
3651         char **values = NULL;
3652         int i;
3653         char *filter = NULL;
3654         uint32_t num_members = 0;
3655         enum lsa_SidType type = SID_NAME_USE_NONE;
3656         fstring tmp;
3657
3658         *pp_members = NULL;
3659         *p_num_members = 0;
3660
3661         if (sid_check_is_in_builtin(alias)) {
3662                 type = SID_NAME_ALIAS;
3663         }
3664
3665         if (sid_check_is_in_our_domain(alias)) {
3666                 type = SID_NAME_ALIAS;
3667         }
3668
3669         if (type == SID_NAME_USE_NONE) {
3670                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3671                           sid_string_dbg(alias)));
3672                 return NT_STATUS_NO_SUCH_ALIAS;
3673         }
3674
3675         if (asprintf(&filter,
3676                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3677                      LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3678                      type) < 0) {
3679                 return NT_STATUS_NO_MEMORY;
3680         }
3681
3682         if (ldapsam_search_one_group(ldap_state, filter,
3683                                      &result) != LDAP_SUCCESS) {
3684                 SAFE_FREE(filter);
3685                 return NT_STATUS_NO_SUCH_ALIAS;
3686         }
3687
3688         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3689                                    result);
3690
3691         if (count < 1) {
3692                 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3693                 ldap_msgfree(result);
3694                 SAFE_FREE(filter);
3695                 return NT_STATUS_NO_SUCH_ALIAS;
3696         }
3697
3698         if (count > 1) {
3699                 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3700                           "filter %s: count=%d\n", filter, count));
3701                 ldap_msgfree(result);
3702                 SAFE_FREE(filter);
3703                 return NT_STATUS_NO_SUCH_ALIAS;
3704         }
3705
3706         SAFE_FREE(filter);
3707
3708         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3709                                  result);
3710
3711         if (!entry) {
3712                 ldap_msgfree(result);
3713                 return NT_STATUS_UNSUCCESSFUL;
3714         }
3715
3716         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3717                                  entry,
3718                                  get_attr_key2string(groupmap_attr_list,
3719                                                      LDAP_ATTR_SID_LIST));
3720
3721         if (values == NULL) {
3722                 ldap_msgfree(result);
3723                 return NT_STATUS_OK;
3724         }
3725
3726         count = ldap_count_values(values);
3727
3728         for (i=0; i<count; i++) {
3729                 struct dom_sid member;
3730                 NTSTATUS status;
3731
3732                 if (!string_to_sid(&member, values[i]))
3733                         continue;
3734
3735                 status = add_sid_to_array(mem_ctx, &member, pp_members,
3736                                           &num_members);
3737                 if (!NT_STATUS_IS_OK(status)) {
3738                         ldap_value_free(values);
3739                         ldap_msgfree(result);
3740                         return status;
3741                 }
3742         }
3743
3744         *p_num_members = num_members;
3745         ldap_value_free(values);
3746         ldap_msgfree(result);
3747
3748         return NT_STATUS_OK;
3749 }
3750
3751 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3752                                           TALLOC_CTX *mem_ctx,
3753                                           const struct dom_sid *domain_sid,
3754                                           const struct dom_sid *members,
3755                                           size_t num_members,
3756                                           uint32_t **pp_alias_rids,
3757                                           size_t *p_num_alias_rids)
3758 {
3759         struct ldapsam_privates *ldap_state =
3760                 (struct ldapsam_privates *)methods->private_data;
3761         LDAP *ldap_struct;
3762
3763         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3764
3765         LDAPMessage *result = NULL;
3766         LDAPMessage *entry = NULL;
3767         int i;
3768         int rc;
3769         char *filter;
3770         enum lsa_SidType type = SID_NAME_USE_NONE;
3771         bool is_builtin = false;
3772         bool sid_added = false;
3773
3774         *pp_alias_rids = NULL;
3775         *p_num_alias_rids = 0;
3776
3777         if (sid_check_is_builtin(domain_sid)) {
3778                 is_builtin = true;
3779                 type = SID_NAME_ALIAS;
3780         }
3781
3782         if (sid_check_is_domain(domain_sid)) {
3783                 type = SID_NAME_ALIAS;
3784         }
3785
3786         if (type == SID_NAME_USE_NONE) {
3787                 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3788                           sid_string_dbg(domain_sid)));
3789                 return NT_STATUS_UNSUCCESSFUL;
3790         }
3791
3792         if (num_members == 0) {
3793                 return NT_STATUS_OK;
3794         }
3795
3796         filter = talloc_asprintf(mem_ctx,
3797                                  "(&(objectclass=%s)(sambaGroupType=%d)(|",
3798                                  LDAP_OBJ_GROUPMAP, type);
3799
3800         for (i=0; i<num_members; i++)
3801                 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3802                                          filter,
3803                                          sid_string_talloc(mem_ctx,
3804                                                            &members[i]));
3805
3806         filter = talloc_asprintf(mem_ctx, "%s))", filter);
3807
3808         if (filter == NULL) {
3809                 return NT_STATUS_NO_MEMORY;
3810         }
3811
3812         if (is_builtin &&
3813             ldap_state->search_cache.filter &&
3814             strcmp(ldap_state->search_cache.filter, filter) == 0) {
3815                 filter = talloc_move(filter, &ldap_state->search_cache.filter);
3816                 result = ldap_state->search_cache.result;
3817                 ldap_state->search_cache.result = NULL;
3818         } else {
3819                 rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3820                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3821                 if (rc != LDAP_SUCCESS) {
3822                         return NT_STATUS_UNSUCCESSFUL;
3823                 }
3824                 talloc_autofree_ldapmsg(filter, result);
3825         }
3826
3827         ldap_struct = ldap_state->smbldap_state->ldap_struct;
3828
3829         for (entry = ldap_first_entry(ldap_struct, result);
3830              entry != NULL;
3831              entry = ldap_next_entry(ldap_struct, entry))
3832         {
3833                 fstring sid_str;
3834                 struct dom_sid sid;
3835                 uint32_t rid;
3836
3837                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3838                                                   LDAP_ATTRIBUTE_SID,
3839                                                   sid_str,
3840                                                   sizeof(sid_str)-1))
3841                         continue;
3842
3843                 if (!string_to_sid(&sid, sid_str))
3844                         continue;
3845
3846                 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3847                         continue;
3848
3849                 sid_added = true;
3850
3851                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3852                                         p_num_alias_rids)) {
3853                         return NT_STATUS_NO_MEMORY;
3854                 }
3855         }
3856
3857         if (!is_builtin && !sid_added) {
3858                 TALLOC_FREE(ldap_state->search_cache.filter);
3859                 /*
3860                  * Note: result is a talloc child of filter because of the
3861                  * talloc_autofree_ldapmsg() usage
3862                  */
3863                 ldap_state->search_cache.filter = talloc_move(ldap_state, &filter);
3864                 ldap_state->search_cache.result = result;
3865         }
3866
3867         return NT_STATUS_OK;
3868 }
3869
3870 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3871                                                    enum pdb_policy_type type,
3872                                                    uint32_t value)
3873 {
3874         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3875         int rc;
3876         LDAPMod **mods = NULL;
3877         fstring value_string;
3878         const char *policy_attr = NULL;
3879
3880         struct ldapsam_privates *ldap_state =
3881                 (struct ldapsam_privates *)methods->private_data;
3882
3883         DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3884
3885         if (!ldap_state->domain_dn) {
3886                 return NT_STATUS_INVALID_PARAMETER;
3887         }
3888
3889         policy_attr = get_account_policy_attr(type);
3890         if (policy_attr == NULL) {
3891                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3892                          "policy\n"));
3893                 return ntstatus;
3894         }
3895
3896         slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3897
3898         smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3899
3900         rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3901                             mods);
3902
3903         ldap_mods_free(mods, True);
3904
3905         if (rc != LDAP_SUCCESS) {
3906                 return ntstatus;
3907         }
3908
3909         if (!cache_account_policy_set(type, value)) {
3910                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3911                          "update local tdb cache\n"));
3912                 return ntstatus;
3913         }
3914
3915         return NT_STATUS_OK;
3916 }
3917
3918 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3919                                            enum pdb_policy_type type,
3920                                            uint32_t value)
3921 {
3922         return ldapsam_set_account_policy_in_ldap(methods, type,
3923                                                   value);
3924 }
3925
3926 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3927                                                      enum pdb_policy_type type,
3928                                                      uint32_t *value)
3929 {
3930         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3931         LDAPMessage *result = NULL;
3932         LDAPMessage *entry = NULL;
3933         int count;
3934         int rc;
3935         char **vals = NULL;
3936         char *filter;
3937         const char *policy_attr = NULL;
3938
3939         struct ldapsam_privates *ldap_state =
3940                 (struct ldapsam_privates *)methods->private_data;
3941
3942         const char *attrs[2];
3943
3944         DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3945
3946         if (!ldap_state->domain_dn) {
3947                 return NT_STATUS_INVALID_PARAMETER;
3948         }
3949
3950         policy_attr = get_account_policy_attr(type);
3951         if (!policy_attr) {
3952                 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3953                          "policy index: %d\n", type));
3954                 return ntstatus;
3955         }
3956
3957         attrs[0] = policy_attr;
3958         attrs[1] = NULL;
3959
3960         filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)", LDAP_OBJ_DOMINFO);
3961         if (filter == NULL) {
3962                 return NT_STATUS_NO_MEMORY;
3963         }
3964         rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3965                             LDAP_SCOPE_BASE, filter, attrs, 0,
3966                             &result);
3967         TALLOC_FREE(filter);
3968         if (rc != LDAP_SUCCESS) {
3969                 return ntstatus;
3970         }
3971
3972         count = ldap_count_entries(priv2ld(ldap_state), result);
3973         if (count < 1) {
3974                 goto out;
3975         }
3976
3977         entry = ldap_first_entry(priv2ld(ldap_state), result);
3978         if (entry == NULL) {
3979                 goto out;
3980         }
3981
3982         vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3983         if (vals == NULL) {
3984                 goto out;
3985         }
3986
3987         *value = (uint32_t)atol(vals[0]);
3988
3989         ntstatus = NT_STATUS_OK;
3990
3991 out:
3992         if (vals)
3993                 ldap_value_free(vals);
3994         ldap_msgfree(result);
3995
3996         return ntstatus;
3997 }
3998
3999 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache 
4000
4001    - if user hasn't decided to use account policies inside LDAP just reuse the
4002      old tdb values
4003
4004    - if there is a valid cache entry, return that
4005    - if there is an LDAP entry, update cache and return 
4006    - otherwise set to default, update cache and return
4007
4008    Guenther
4009 */
4010 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
4011                                            enum pdb_policy_type type,
4012                                            uint32_t *value)
4013 {
4014         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
4015
4016         if (cache_account_policy_get(type, value)) {
4017                 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
4018                           "cache\n"));
4019                 return NT_STATUS_OK;
4020         }
4021
4022         ntstatus = ldapsam_get_account_policy_from_ldap(methods, type,
4023                                                         value);
4024         if (NT_STATUS_IS_OK(ntstatus)) {
4025                 goto update_cache;
4026         }
4027
4028         DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
4029                   "ldap\n"));
4030
4031 #if 0
4032         /* should we automagically migrate old tdb value here ? */
4033         if (account_policy_get(type, value))
4034                 goto update_ldap;
4035
4036         DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
4037                   "default\n", type));
4038 #endif
4039
4040         if (!account_policy_get_default(type, value)) {
4041                 return ntstatus;
4042         }
4043
4044 /* update_ldap: */
4045
4046         ntstatus = ldapsam_set_account_policy(methods, type, *value);
4047         if (!NT_STATUS_IS_OK(ntstatus)) {
4048                 return ntstatus;
4049         }
4050
4051  update_cache:
4052
4053         if (!cache_account_policy_set(type, *value)) {
4054                 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
4055                          "tdb as a cache\n"));
4056                 return NT_STATUS_UNSUCCESSFUL;
4057         }
4058
4059         return NT_STATUS_OK;
4060 }
4061
4062 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
4063                                     const struct dom_sid *domain_sid,
4064                                     int num_rids,
4065                                     uint32_t *rids,
4066                                     const char **names,
4067                                     enum lsa_SidType *attrs)
4068 {
4069         struct ldapsam_privates *ldap_state =
4070                 (struct ldapsam_privates *)methods->private_data;
4071         LDAPMessage *msg = NULL;
4072         LDAPMessage *entry;
4073         char *allsids = NULL;
4074         int i, rc, num_mapped;
4075         NTSTATUS result = NT_STATUS_NO_MEMORY;
4076         TALLOC_CTX *mem_ctx;
4077         LDAP *ld;
4078         bool is_builtin;
4079
4080         mem_ctx = talloc_new(NULL);
4081         if (mem_ctx == NULL) {
4082                 DEBUG(0, ("talloc_new failed\n"));
4083                 goto done;
4084         }
4085
4086         if (!sid_check_is_builtin(domain_sid) &&
4087             !sid_check_is_domain(domain_sid)) {
4088                 result = NT_STATUS_INVALID_PARAMETER;
4089                 goto done;
4090         }
4091
4092         if (num_rids == 0) {
4093                 result = NT_STATUS_NONE_MAPPED;
4094                 goto done;
4095         }
4096
4097         for (i=0; i<num_rids; i++)
4098                 attrs[i] = SID_NAME_UNKNOWN;
4099
4100         allsids = talloc_strdup(mem_ctx, "");
4101         if (allsids == NULL) {
4102                 goto done;
4103         }
4104
4105         for (i=0; i<num_rids; i++) {
4106                 struct dom_sid sid;
4107                 sid_compose(&sid, domain_sid, rids[i]);
4108                 allsids = talloc_asprintf_append_buffer(
4109                         allsids, "(sambaSid=%s)",
4110                         sid_string_talloc(mem_ctx, &sid));
4111                 if (allsids == NULL) {
4112                         goto done;
4113                 }
4114         }
4115
4116         /* First look for users */
4117
4118         {
4119                 char *filter;
4120                 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4121
4122                 filter = talloc_asprintf(
4123                         mem_ctx, ("(&(objectClass=%s)(|%s))"),
4124                         LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4125
4126                 if (filter == NULL) {
4127                         goto done;
4128                 }
4129
4130                 rc = smbldap_search(ldap_state->smbldap_state,
4131                                     lp_ldap_user_suffix(),
4132                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4133                                     &msg);
4134                 talloc_autofree_ldapmsg(mem_ctx, msg);
4135         }
4136
4137         if (rc != LDAP_SUCCESS)
4138                 goto done;
4139
4140         ld = ldap_state->smbldap_state->ldap_struct;
4141         num_mapped = 0;
4142
4143         for (entry = ldap_first_entry(ld, msg);
4144              entry != NULL;
4145              entry = ldap_next_entry(ld, entry)) {
4146                 uint32_t rid;
4147                 int rid_index;
4148                 const char *name;
4149
4150                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4151                                                     &rid)) {
4152                         DEBUG(2, ("Could not find sid from ldap entry\n"));
4153                         continue;
4154                 }
4155
4156                 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4157                                                        names);
4158                 if (name == NULL) {
4159                         DEBUG(2, ("Could not retrieve uid attribute\n"));
4160                         continue;
4161                 }
4162
4163                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4164                         if (rid == rids[rid_index])
4165                                 break;
4166                 }
4167
4168                 if (rid_index == num_rids) {
4169                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4170                         continue;
4171                 }
4172
4173                 attrs[rid_index] = SID_NAME_USER;
4174                 names[rid_index] = name;
4175                 num_mapped += 1;
4176         }
4177
4178         if (num_mapped == num_rids) {
4179                 /* No need to look for groups anymore -- we're done */
4180                 result = NT_STATUS_OK;
4181                 goto done;
4182         }
4183
4184         /* Same game for groups */
4185
4186         {
4187                 char *filter;
4188                 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4189                                              "sambaGroupType", NULL };
4190
4191                 filter = talloc_asprintf(
4192                         mem_ctx, "(&(objectClass=%s)(|%s))",
4193                         LDAP_OBJ_GROUPMAP, allsids);
4194                 if (filter == NULL) {
4195                         goto done;
4196                 }
4197
4198                 rc = smbldap_search(ldap_state->smbldap_state,
4199                                     lp_ldap_suffix(),
4200                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4201                                     &msg);
4202                 talloc_autofree_ldapmsg(mem_ctx, msg);
4203         }
4204
4205         if (rc != LDAP_SUCCESS)
4206                 goto done;
4207
4208         /* ldap_struct might have changed due to a reconnect */
4209
4210         ld = ldap_state->smbldap_state->ldap_struct;
4211
4212         /* For consistency checks, we already checked we're only domain or builtin */
4213
4214         is_builtin = sid_check_is_builtin(domain_sid);
4215
4216         for (entry = ldap_first_entry(ld, msg);
4217              entry != NULL;
4218              entry = ldap_next_entry(ld, entry))
4219         {
4220                 uint32_t rid;
4221                 int rid_index;
4222                 const char *attr;
4223                 enum lsa_SidType type;
4224                 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4225
4226                 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4227                                                        mem_ctx);
4228                 if (attr == NULL) {
4229                         DEBUG(2, ("Could not extract type from ldap entry %s\n",
4230                                   dn));
4231                         continue;
4232                 }
4233
4234                 type = (enum lsa_SidType)atol(attr);
4235
4236                 /* Consistency checks */
4237                 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4238                     (!is_builtin && ((type != SID_NAME_ALIAS) &&
4239                                      (type != SID_NAME_DOM_GRP)))) {
4240                         DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4241                 }
4242
4243                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4244                                                     &rid)) {
4245                         DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4246                         continue;
4247                 }
4248
4249                 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4250
4251                 if (attr == NULL) {
4252                         DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4253                                    dn));
4254                         attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4255                 }
4256
4257                 if (attr == NULL) {
4258                         DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4259                                   dn));
4260                         continue;
4261                 }
4262
4263                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4264                         if (rid == rids[rid_index])
4265                                 break;
4266                 }
4267
4268                 if (rid_index == num_rids) {
4269                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4270                         continue;
4271                 }
4272
4273                 attrs[rid_index] = type;
4274                 names[rid_index] = attr;
4275                 num_mapped += 1;
4276         }
4277
4278         result = NT_STATUS_NONE_MAPPED;
4279
4280         if (num_mapped > 0)
4281                 result = (num_mapped == num_rids) ?
4282                         NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4283  done:
4284         TALLOC_FREE(mem_ctx);
4285         return result;
4286 }
4287
4288 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4289 {
4290         char *filter = NULL;
4291         char *escaped = NULL;
4292         char *result = NULL;
4293
4294         if (asprintf(&filter, "(&%s(objectclass=%s))",
4295                           "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4296                 goto done;
4297         }
4298
4299         escaped = escape_ldap_string(talloc_tos(), username);
4300         if (escaped == NULL) goto done;
4301
4302         result = talloc_string_sub(mem_ctx, filter, "%u", username);
4303
4304  done:
4305         SAFE_FREE(filter);
4306         TALLOC_FREE(escaped);
4307
4308         return result;
4309 }
4310
4311 static const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4312 {
4313         int i, num = 0;
4314         va_list ap;
4315         const char **result;
4316
4317         va_start(ap, mem_ctx);
4318         while (va_arg(ap, const char *) != NULL)
4319                 num += 1;
4320         va_end(ap);
4321
4322         if ((result = talloc_array(mem_ctx, const char *, num+1)) == NULL) {
4323                 return NULL;
4324         }
4325
4326         va_start(ap, mem_ctx);
4327         for (i=0; i<num; i++) {
4328                 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4329                 if (result[i] == NULL) {
4330                         talloc_free(result);
4331                         va_end(ap);
4332                         return NULL;
4333                 }
4334         }
4335         va_end(ap);
4336
4337         result[num] = NULL;
4338         return result;
4339 }
4340
4341 struct ldap_search_state {
4342         struct smbldap_state *connection;
4343
4344         uint32_t acct_flags;
4345         uint16_t group_type;
4346
4347         const char *base;
4348         int scope;
4349         const char *filter;
4350         const char **attrs;
4351         int attrsonly;
4352         void *pagedresults_cookie;
4353
4354         LDAPMessage *entries, *current_entry;
4355         bool (*ldap2displayentry)(struct ldap_search_state *state,
4356                                   TALLOC_CTX *mem_ctx,
4357                                   LDAP *ld, LDAPMessage *entry,
4358                                   struct samr_displayentry *result);
4359 };
4360
4361 static bool ldapsam_search_firstpage(struct pdb_search *search)
4362 {
4363         struct ldap_search_state *state =
4364                 (struct ldap_search_state *)search->private_data;
4365         LDAP *ld;
4366         int rc = LDAP_OPERATIONS_ERROR;
4367
4368         state->entries = NULL;
4369
4370         if (state->connection->paged_results) {
4371                 rc = smbldap_search_paged(state->connection, state->base,
4372                                           state->scope, state->filter,
4373                                           state->attrs, state->attrsonly,
4374                                           lp_ldap_page_size(), &state->entries,
4375                                           &state->pagedresults_cookie);
4376         }
4377
4378         if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4379
4380                 if (state->entries != NULL) {
4381                         /* Left over from unsuccessful paged attempt */
4382                         ldap_msgfree(state->entries);
4383                         state->entries = NULL;
4384                 }
4385
4386                 rc = smbldap_search(state->connection, state->base,
4387                                     state->scope, state->filter, state->attrs,
4388                                     state->attrsonly, &state->entries);
4389
4390                 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4391                         return False;
4392
4393                 /* Ok, the server was lying. It told us it could do paged
4394                  * searches when it could not. */
4395                 state->connection->paged_results = False;
4396         }
4397
4398         ld = state->connection->ldap_struct;
4399         if ( ld == NULL) {
4400                 DEBUG(5, ("Don't have an LDAP connection right after a "
4401                           "search\n"));
4402                 return False;
4403         }
4404         state->current_entry = ldap_first_entry(ld, state->entries);
4405
4406         return True;
4407 }
4408
4409 static bool ldapsam_search_nextpage(struct pdb_search *search)
4410 {
4411         struct ldap_search_state *state =
4412                 (struct ldap_search_state *)search->private_data;
4413         int rc;
4414
4415         if (!state->connection->paged_results) {
4416                 /* There is no next page when there are no paged results */
4417                 return False;
4418         }
4419
4420         rc = smbldap_search_paged(state->connection, state->base,
4421                                   state->scope, state->filter, state->attrs,
4422                                   state->attrsonly, lp_ldap_page_size(),
4423                                   &state->entries,
4424                                   &state->pagedresults_cookie);
4425
4426         if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4427                 return False;
4428
4429         state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4430
4431         if (state->current_entry == NULL) {
4432                 ldap_msgfree(state->entries);
4433                 state->entries = NULL;
4434                 return false;
4435         }
4436
4437         return True;
4438 }
4439
4440 static bool ldapsam_search_next_entry(struct pdb_search *search,
4441                                       struct samr_displayentry *entry)
4442 {
4443         struct ldap_search_state *state =
4444                 (struct ldap_search_state *)search->private_data;
4445         bool result;
4446
4447  retry:
4448         if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4449                 return False;
4450
4451         if ((state->entries == NULL) &&
4452             !ldapsam_search_nextpage(search))
4453                     return False;
4454
4455         if (state->current_entry == NULL) {
4456                 return false;
4457         }
4458
4459         result = state->ldap2displayentry(state, search,
4460                                           state->connection->ldap_struct,
4461                                           state->current_entry, entry);
4462
4463         if (!result) {
4464                 char *dn;
4465                 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4466                 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4467                 if (dn != NULL) ldap_memfree(dn);
4468         }
4469
4470         state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4471
4472         if (state->current_entry == NULL) {
4473                 ldap_msgfree(state->entries);
4474                 state->entries = NULL;
4475         }
4476
4477         if (!result) goto retry;
4478
4479         return True;
4480 }
4481
4482 static void ldapsam_search_end(struct pdb_search *search)
4483 {
4484         struct ldap_search_state *state =
4485                 (struct ldap_search_state *)search->private_data;
4486         int rc;
4487
4488         if (state->pagedresults_cookie == NULL)
4489                 return;
4490
4491         if (state->entries != NULL)
4492                 ldap_msgfree(state->entries);
4493
4494         state->entries = NULL;
4495         state->current_entry = NULL;
4496
4497         if (!state->connection->paged_results)
4498                 return;
4499
4500         /* Tell the LDAP server we're not interested in the rest anymore. */
4501
4502         rc = smbldap_search_paged(state->connection, state->base, state->scope,
4503                                   state->filter, state->attrs,
4504                                   state->attrsonly, 0, &state->entries,
4505                                   &state->pagedresults_cookie);
4506
4507         if (rc != LDAP_SUCCESS)
4508                 DEBUG(5, ("Could not end search properly\n"));
4509
4510         return;
4511 }
4512
4513 static bool ldapuser2displayentry(struct ldap_search_state *state,
4514                                   TALLOC_CTX *mem_ctx,
4515                                   LDAP *ld, LDAPMessage *entry,
4516                                   struct samr_displayentry *result)
4517 {
4518         char **vals;
4519         size_t converted_size;
4520         struct dom_sid sid;
4521         uint32_t acct_flags;
4522
4523         vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4524         if ((vals == NULL) || (vals[0] == NULL)) {
4525                 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4526                 return False;
4527         }
4528         acct_flags = pdb_decode_acct_ctrl(vals[0]);
4529         ldap_value_free(vals);
4530
4531         if ((state->acct_flags != 0) &&
4532             ((state->acct_flags & acct_flags) == 0))
4533                 return False;           
4534
4535         result->acct_flags = acct_flags;
4536         result->account_name = "";
4537         result->fullname = "";
4538         result->description = "";
4539
4540         vals = ldap_get_values(ld, entry, "uid");
4541         if ((vals == NULL) || (vals[0] == NULL)) {
4542                 DEBUG(5, ("\"uid\" not found\n"));
4543                 return False;
4544         }
4545         if (!pull_utf8_talloc(mem_ctx,
4546                               discard_const_p(char *, &result->account_name),
4547                               vals[0], &converted_size))
4548         {
4549                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4550                          strerror(errno)));
4551         }
4552
4553         ldap_value_free(vals);
4554
4555         vals = ldap_get_values(ld, entry, "displayName");
4556         if ((vals == NULL) || (vals[0] == NULL))
4557                 DEBUG(8, ("\"displayName\" not found\n"));
4558         else if (!pull_utf8_talloc(mem_ctx,
4559                                    discard_const_p(char *, &result->fullname),
4560                                    vals[0], &converted_size))
4561         {
4562                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4563                          strerror(errno)));
4564         }
4565
4566         ldap_value_free(vals);
4567
4568         vals = ldap_get_values(ld, entry, "description");
4569         if ((vals == NULL) || (vals[0] == NULL))
4570                 DEBUG(8, ("\"description\" not found\n"));
4571         else if (!pull_utf8_talloc(mem_ctx,
4572                                    discard_const_p(char *, &result->description),
4573                                    vals[0], &converted_size))
4574         {
4575                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4576                          strerror(errno)));
4577         }
4578
4579         ldap_value_free(vals);
4580
4581         if ((result->account_name == NULL) ||
4582             (result->fullname == NULL) ||
4583             (result->description == NULL)) {
4584                 DEBUG(0, ("talloc failed\n"));
4585                 return False;
4586         }
4587
4588         vals = ldap_get_values(ld, entry, "sambaSid");
4589         if ((vals == NULL) || (vals[0] == NULL)) {
4590                 DEBUG(0, ("\"objectSid\" not found\n"));
4591                 return False;
4592         }
4593
4594         if (!string_to_sid(&sid, vals[0])) {
4595                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4596                 ldap_value_free(vals);
4597                 return False;
4598         }
4599         ldap_value_free(vals);
4600
4601         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4602                 DEBUG(0, ("sid %s does not belong to our domain\n",
4603                           sid_string_dbg(&sid)));
4604                 return False;
4605         }
4606
4607         return True;
4608 }
4609
4610
4611 static bool ldapsam_search_users(struct pdb_methods *methods,
4612                                  struct pdb_search *search,
4613                                  uint32_t acct_flags)
4614 {
4615         struct ldapsam_privates *ldap_state =
4616                 (struct ldapsam_privates *)methods->private_data;
4617         struct ldap_search_state *state;
4618
4619         state = talloc(search, struct ldap_search_state);
4620         if (state == NULL) {
4621                 DEBUG(0, ("talloc failed\n"));
4622                 return False;
4623         }
4624
4625         state->connection = ldap_state->smbldap_state;
4626
4627         if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4628                 state->base = lp_ldap_user_suffix();
4629         else if ((acct_flags != 0) &&
4630                  ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4631                 state->base = lp_ldap_machine_suffix();
4632         else
4633                 state->base = lp_ldap_suffix();
4634
4635         state->acct_flags = acct_flags;
4636         state->base = talloc_strdup(search, state->base);
4637         state->scope = LDAP_SCOPE_SUBTREE;
4638         state->filter = get_ldap_filter(search, "*");
4639         state->attrs = talloc_attrs(search, "uid", "sambaSid",
4640                                     "displayName", "description",
4641                                     "sambaAcctFlags", NULL);
4642         state->attrsonly = 0;
4643         state->pagedresults_cookie = NULL;
4644         state->entries = NULL;
4645         state->ldap2displayentry = ldapuser2displayentry;
4646
4647         if ((state->filter == NULL) || (state->attrs == NULL)) {
4648                 DEBUG(0, ("talloc failed\n"));
4649                 return False;
4650         }
4651
4652         search->private_data = state;
4653         search->next_entry = ldapsam_search_next_entry;
4654         search->search_end = ldapsam_search_end;
4655
4656         return ldapsam_search_firstpage(search);
4657 }
4658
4659 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4660                                    TALLOC_CTX *mem_ctx,
4661                                    LDAP *ld, LDAPMessage *entry,
4662                                    struct samr_displayentry *result)
4663 {
4664         char **vals;
4665         size_t converted_size;
4666         struct dom_sid sid;
4667         uint16_t group_type;
4668
4669         result->account_name = "";
4670         result->fullname = "";
4671         result->description = "";
4672
4673
4674         vals = ldap_get_values(ld, entry, "sambaGroupType");
4675         if ((vals == NULL) || (vals[0] == NULL)) {
4676                 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4677                 if (vals != NULL) {
4678                         ldap_value_free(vals);
4679                 }
4680                 return False;
4681         }
4682
4683         group_type = atoi(vals[0]);
4684
4685         if ((state->group_type != 0) &&
4686             ((state->group_type != group_type))) {
4687                 ldap_value_free(vals);
4688                 return False;
4689         }
4690
4691         ldap_value_free(vals);
4692
4693         /* display name is the NT group name */
4694
4695         vals = ldap_get_values(ld, entry, "displayName");
4696         if ((vals == NULL) || (vals[0] == NULL)) {
4697                 DEBUG(8, ("\"displayName\" not found\n"));
4698
4699                 /* fallback to the 'cn' attribute */
4700                 vals = ldap_get_values(ld, entry, "cn");
4701                 if ((vals == NULL) || (vals[0] == NULL)) {
4702                         DEBUG(5, ("\"cn\" not found\n"));
4703                         return False;
4704                 }
4705                 if (!pull_utf8_talloc(mem_ctx,
4706                                       discard_const_p(char *,
4707                                                     &result->account_name),
4708                                       vals[0], &converted_size))
4709                 {
4710                         DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4711                                   "failed: %s", strerror(errno)));
4712                 }
4713         }
4714         else if (!pull_utf8_talloc(mem_ctx,
4715                                    discard_const_p(char *,
4716                                                  &result->account_name),
4717                                    vals[0], &converted_size))
4718         {
4719                 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4720                           strerror(errno)));
4721         }
4722
4723         ldap_value_free(vals);
4724
4725         vals = ldap_get_values(ld, entry, "description");
4726         if ((vals == NULL) || (vals[0] == NULL))
4727                 DEBUG(8, ("\"description\" not found\n"));
4728         else if (!pull_utf8_talloc(mem_ctx,
4729                                    discard_const_p(char *, &result->description),
4730                                    vals[0], &converted_size))
4731         {
4732                 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4733                           strerror(errno)));
4734         }
4735         ldap_value_free(vals);
4736
4737         if ((result->account_name == NULL) ||
4738             (result->fullname == NULL) ||
4739             (result->description == NULL)) {
4740                 DEBUG(0, ("talloc failed\n"));
4741                 return False;
4742         }
4743
4744         vals = ldap_get_values(ld, entry, "sambaSid");
4745         if ((vals == NULL) || (vals[0] == NULL)) {
4746                 DEBUG(0, ("\"objectSid\" not found\n"));
4747                 if (vals != NULL) {
4748                         ldap_value_free(vals);
4749                 }
4750                 return False;
4751         }
4752
4753         if (!string_to_sid(&sid, vals[0])) {
4754                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4755                 return False;
4756         }
4757
4758         ldap_value_free(vals);
4759
4760         switch (group_type) {
4761                 case SID_NAME_DOM_GRP:
4762                 case SID_NAME_ALIAS:
4763
4764                         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid) 
4765                                 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid)) 
4766                         {
4767                                 DEBUG(0, ("%s is not in our domain\n",
4768                                           sid_string_dbg(&sid)));
4769                                 return False;
4770                         }
4771                         break;
4772
4773                 default:
4774                         DEBUG(0,("unknown group type: %d\n", group_type));
4775                         return False;
4776         }
4777
4778         result->acct_flags = 0;
4779
4780         return True;
4781 }
4782
4783 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4784                                      struct pdb_search *search,
4785                                      const struct dom_sid *sid,
4786                                      enum lsa_SidType type)
4787 {
4788         struct ldapsam_privates *ldap_state =
4789                 (struct ldapsam_privates *)methods->private_data;
4790         struct ldap_search_state *state;
4791         fstring tmp;
4792
4793         state = talloc(search, struct ldap_search_state);
4794         if (state == NULL) {
4795                 DEBUG(0, ("talloc failed\n"));
4796                 return False;
4797         }
4798
4799         state->connection = ldap_state->smbldap_state;
4800
4801         state->base = talloc_strdup(search, lp_ldap_suffix());
4802         state->connection = ldap_state->smbldap_state;
4803         state->scope = LDAP_SCOPE_SUBTREE;
4804         state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4805                                         "(sambaGroupType=%d)(sambaSID=%s*))",
4806                                          LDAP_OBJ_GROUPMAP,
4807                                          type, sid_to_fstring(tmp, sid));
4808         state->attrs = talloc_attrs(search, "cn", "sambaSid",
4809                                     "displayName", "description",
4810                                     "sambaGroupType", NULL);
4811         state->attrsonly = 0;
4812         state->pagedresults_cookie = NULL;
4813         state->entries = NULL;
4814         state->group_type = type;
4815         state->ldap2displayentry = ldapgroup2displayentry;
4816
4817         if ((state->filter == NULL) || (state->attrs == NULL)) {
4818                 DEBUG(0, ("talloc failed\n"));
4819                 return False;
4820         }
4821
4822         search->private_data = state;
4823         search->next_entry = ldapsam_search_next_entry;
4824         search->search_end = ldapsam_search_end;
4825
4826         return ldapsam_search_firstpage(search);
4827 }
4828
4829 static bool ldapsam_search_groups(struct pdb_methods *methods,
4830                                   struct pdb_search *search)
4831 {
4832         return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4833 }
4834
4835 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4836                                    struct pdb_search *search,
4837                                    const struct dom_sid *sid)
4838 {
4839         return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4840 }
4841
4842 static uint32_t ldapsam_capabilities(struct pdb_methods *methods)
4843 {
4844         return PDB_CAP_STORE_RIDS;
4845 }
4846
4847 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4848                                     uint32_t *rid)
4849 {
4850         struct smbldap_state *smbldap_state = priv->smbldap_state;
4851
4852         LDAPMessage *result = NULL;
4853         LDAPMessage *entry = NULL;
4854         LDAPMod **mods = NULL;
4855         NTSTATUS status;
4856         char *value;
4857         int rc;
4858         uint32_t nextRid = 0;
4859         const char *dn;
4860
4861         TALLOC_CTX *mem_ctx;
4862
4863         mem_ctx = talloc_new(NULL);
4864         if (mem_ctx == NULL) {
4865                 DEBUG(0, ("talloc_new failed\n"));
4866                 return NT_STATUS_NO_MEMORY;
4867         }
4868
4869         status = smbldap_search_domain_info(smbldap_state, &result,
4870                                             get_global_sam_name(), False);
4871         if (!NT_STATUS_IS_OK(status)) {
4872                 DEBUG(3, ("Could not get domain info: %s\n",
4873                           nt_errstr(status)));
4874                 goto done;
4875         }
4876
4877         talloc_autofree_ldapmsg(mem_ctx, result);
4878
4879         entry = ldap_first_entry(priv2ld(priv), result);
4880         if (entry == NULL) {
4881                 DEBUG(0, ("Could not get domain info entry\n"));
4882                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4883                 goto done;
4884         }
4885
4886         /* Find the largest of the three attributes "sambaNextRid",
4887            "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4888            concept of differentiating between user and group rids, and will
4889            use only "sambaNextRid" in the future. But for compatibility
4890            reasons I look if others have chosen different strategies -- VL */
4891
4892         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4893                                                 "sambaNextRid", mem_ctx);
4894         if (value != NULL) {
4895                 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4896                 nextRid = MAX(nextRid, tmp);
4897         }
4898
4899         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4900                                                 "sambaNextUserRid", mem_ctx);
4901         if (value != NULL) {
4902                 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4903                 nextRid = MAX(nextRid, tmp);
4904         }
4905
4906         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4907                                                 "sambaNextGroupRid", mem_ctx);
4908         if (value != NULL) {
4909                 uint32_t tmp = (uint32_t)strtoul(value, NULL, 10);
4910                 nextRid = MAX(nextRid, tmp);
4911         }
4912
4913         if (nextRid == 0) {
4914                 nextRid = BASE_RID-1;
4915         }
4916
4917         nextRid += 1;
4918
4919         smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4920                          talloc_asprintf(mem_ctx, "%d", nextRid));
4921         talloc_autofree_ldapmod(mem_ctx, mods);
4922
4923         if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4924                 status = NT_STATUS_NO_MEMORY;
4925                 goto done;
4926         }
4927
4928         rc = smbldap_modify(smbldap_state, dn, mods);
4929
4930         /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4931          * please retry" */
4932
4933         status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4934
4935  done:
4936         if (NT_STATUS_IS_OK(status)) {
4937                 *rid = nextRid;
4938         }
4939
4940         TALLOC_FREE(mem_ctx);
4941         return status;
4942 }
4943
4944 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32_t *rid)
4945 {
4946         int i;
4947
4948         for (i=0; i<10; i++) {
4949                 NTSTATUS result = ldapsam_get_new_rid(
4950                         (struct ldapsam_privates *)methods->private_data, rid);
4951                 if (NT_STATUS_IS_OK(result)) {
4952                         return result;
4953                 }
4954
4955                 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4956                         return result;
4957                 }
4958
4959                 /* The ldap update failed (maybe a race condition), retry */
4960         }
4961
4962         /* Tried 10 times, fail. */
4963         return NT_STATUS_ACCESS_DENIED;
4964 }
4965
4966 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32_t *rid)
4967 {
4968         NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4969         return NT_STATUS_IS_OK(result) ? True : False;
4970 }
4971
4972 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4973                               const struct dom_sid *sid,
4974                               union unid_t *id, enum lsa_SidType *type)
4975 {
4976         struct ldapsam_privates *priv =
4977                 (struct ldapsam_privates *)methods->private_data;
4978         char *filter;
4979         const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4980                                 NULL };
4981         LDAPMessage *result = NULL;
4982         LDAPMessage *entry = NULL;
4983         bool ret = False;
4984         char *value;
4985         int rc;
4986
4987         TALLOC_CTX *mem_ctx;
4988
4989         mem_ctx = talloc_new(NULL);
4990         if (mem_ctx == NULL) {
4991                 DEBUG(0, ("talloc_new failed\n"));
4992                 return False;
4993         }
4994
4995         filter = talloc_asprintf(mem_ctx,
4996                                  "(&(sambaSid=%s)"
4997                                  "(|(objectClass=%s)(objectClass=%s)))",
4998                                  sid_string_talloc(mem_ctx, sid),
4999                                  LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
5000         if (filter == NULL) {
5001                 DEBUG(5, ("talloc_asprintf failed\n"));
5002                 goto done;
5003         }
5004
5005         rc = smbldap_search_suffix(priv->smbldap_state, filter,
5006                                    attrs, &result);
5007         if (rc != LDAP_SUCCESS) {
5008                 goto done;
5009         }
5010         talloc_autofree_ldapmsg(mem_ctx, result);
5011
5012         if (ldap_count_entries(priv2ld(priv), result) != 1) {
5013                 DEBUG(10, ("Got %d entries, expected one\n",
5014                            ldap_count_entries(priv2ld(priv), result)));
5015                 goto done;
5016         }
5017
5018         entry = ldap_first_entry(priv2ld(priv), result);
5019
5020         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5021                                                 "sambaGroupType", mem_ctx);
5022
5023         if (value != NULL) {
5024                 const char *gid_str;
5025                 /* It's a group */
5026
5027                 gid_str = smbldap_talloc_single_attribute(
5028                         priv2ld(priv), entry, "gidNumber", mem_ctx);
5029                 if (gid_str == NULL) {
5030                         DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
5031                                   smbldap_talloc_dn(mem_ctx, priv2ld(priv),
5032                                                     entry)));
5033                         goto done;
5034                 }
5035
5036                 id->gid = strtoul(gid_str, NULL, 10);
5037                 *type = (enum lsa_SidType)strtoul(value, NULL, 10);
5038                 store_gid_sid_cache(sid, id->gid);
5039                 idmap_cache_set_sid2gid(sid, id->gid);
5040                 ret = True;
5041                 goto done;
5042         }
5043
5044         /* It must be a user */
5045
5046         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5047                                                 "uidNumber", mem_ctx);
5048         if (value == NULL) {
5049                 DEBUG(1, ("Could not find uidNumber in %s\n",
5050                           smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
5051                 goto done;
5052         }
5053
5054         id->uid = strtoul(value, NULL, 10);
5055         *type = SID_NAME_USER;
5056         store_uid_sid_cache(sid, id->uid);
5057         idmap_cache_set_sid2uid(sid, id->uid);
5058
5059         ret = True;
5060  done:
5061         TALLOC_FREE(mem_ctx);
5062         return ret;
5063 }
5064
5065 /**
5066  * Find the SID for a uid.
5067  * This is shortcut is only used if ldapsam:trusted is set to true.
5068  */
5069 static bool ldapsam_uid_to_sid(struct pdb_methods *methods, uid_t uid,
5070                                struct dom_sid *sid)
5071 {
5072         struct ldapsam_privates *priv =
5073                 (struct ldapsam_privates *)methods->private_data;
5074         char *filter;
5075         const char *attrs[] = { "sambaSID", NULL };
5076         LDAPMessage *result = NULL;
5077         LDAPMessage *entry = NULL;
5078         bool ret = false;
5079         char *user_sid_string;
5080         struct dom_sid user_sid;
5081         int rc;
5082         TALLOC_CTX *tmp_ctx = talloc_stackframe();
5083
5084         filter = talloc_asprintf(tmp_ctx,
5085                                  "(&(uidNumber=%u)"
5086                                  "(objectClass=%s)"
5087                                  "(objectClass=%s))",
5088                                  (unsigned int)uid,
5089                                  LDAP_OBJ_POSIXACCOUNT,
5090                                  LDAP_OBJ_SAMBASAMACCOUNT);
5091         if (filter == NULL) {
5092                 DEBUG(3, ("talloc_asprintf failed\n"));
5093                 goto done;
5094         }
5095
5096         rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5097         if (rc != LDAP_SUCCESS) {
5098                 goto done;
5099         }
5100         talloc_autofree_ldapmsg(tmp_ctx, result);
5101
5102         if (ldap_count_entries(priv2ld(priv), result) != 1) {
5103                 DEBUG(3, ("ERROR: Got %d entries for uid %u, expected one\n",
5104                            ldap_count_entries(priv2ld(priv), result),
5105                            (unsigned int)uid));
5106                 goto done;
5107         }
5108
5109         entry = ldap_first_entry(priv2ld(priv), result);
5110
5111         user_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5112                                                           "sambaSID", tmp_ctx);
5113         if (user_sid_string == NULL) {
5114                 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5115                           smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5116                 goto done;
5117         }
5118
5119         if (!string_to_sid(&user_sid, user_sid_string)) {
5120                 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5121                           user_sid_string));
5122                 goto done;
5123         }
5124
5125         sid_copy(sid, &user_sid);
5126
5127         store_uid_sid_cache(sid, uid);
5128         idmap_cache_set_sid2uid(sid, uid);
5129
5130         ret = true;
5131
5132  done:
5133         TALLOC_FREE(tmp_ctx);
5134         return ret;
5135 }
5136
5137 /**
5138  * Find the SID for a gid.
5139  * This is shortcut is only used if ldapsam:trusted is set to true.
5140  */
5141 static bool ldapsam_gid_to_sid(struct pdb_methods *methods, gid_t gid,
5142                                struct dom_sid *sid)
5143 {
5144         struct ldapsam_privates *priv =
5145                 (struct ldapsam_privates *)methods->private_data;
5146         char *filter;
5147         const char *attrs[] = { "sambaSID", NULL };
5148         LDAPMessage *result = NULL;
5149         LDAPMessage *entry = NULL;
5150         bool ret = false;
5151         char *group_sid_string;
5152         struct dom_sid group_sid;
5153         int rc;
5154         TALLOC_CTX *tmp_ctx = talloc_stackframe();
5155
5156         filter = talloc_asprintf(tmp_ctx,
5157                                  "(&(gidNumber=%u)"
5158                                  "(objectClass=%s))",
5159                                  (unsigned int)gid,
5160                                  LDAP_OBJ_GROUPMAP);
5161         if (filter == NULL) {
5162                 DEBUG(3, ("talloc_asprintf failed\n"));
5163                 goto done;
5164         }
5165
5166         rc = smbldap_search_suffix(priv->smbldap_state, filter, attrs, &result);
5167         if (rc != LDAP_SUCCESS) {
5168                 goto done;
5169         }
5170         talloc_autofree_ldapmsg(tmp_ctx, result);
5171
5172         if (ldap_count_entries(priv2ld(priv), result) != 1) {
5173                 DEBUG(3, ("ERROR: Got %d entries for gid %u, expected one\n",
5174                            ldap_count_entries(priv2ld(priv), result),
5175                            (unsigned int)gid));
5176                 goto done;
5177         }
5178
5179         entry = ldap_first_entry(priv2ld(priv), result);
5180
5181         group_sid_string = smbldap_talloc_single_attribute(priv2ld(priv), entry,
5182                                                           "sambaSID", tmp_ctx);
5183         if (group_sid_string == NULL) {
5184                 DEBUG(1, ("Could not find sambaSID in object '%s'\n",
5185                           smbldap_talloc_dn(tmp_ctx, priv2ld(priv), entry)));
5186                 goto done;
5187         }
5188
5189         if (!string_to_sid(&group_sid, group_sid_string)) {
5190                 DEBUG(3, ("Error calling sid_string_talloc for sid '%s'\n",
5191                           group_sid_string));
5192                 goto done;
5193         }
5194
5195         sid_copy(sid, &group_sid);
5196
5197         store_gid_sid_cache(sid, gid);
5198         idmap_cache_set_sid2gid(sid, gid);
5199
5200         ret = true;
5201
5202  done:
5203         TALLOC_FREE(tmp_ctx);
5204         return ret;
5205 }
5206
5207
5208 /*
5209  * The following functions are called only if
5210  * ldapsam:trusted and ldapsam:editposix are
5211  * set to true
5212  */
5213
5214 /*
5215  * ldapsam_create_user creates a new
5216  * posixAccount and sambaSamAccount object
5217  * in the ldap users subtree
5218  *
5219  * The uid is allocated by winbindd.
5220  */
5221
5222 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
5223                                     TALLOC_CTX *tmp_ctx, const char *name,
5224                                     uint32_t acb_info, uint32_t *rid)
5225 {
5226         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5227         LDAPMessage *entry = NULL;
5228         LDAPMessage *result = NULL;
5229         uint32_t num_result;
5230         bool is_machine = False;
5231         bool add_posix = False;
5232         LDAPMod **mods = NULL;
5233         struct samu *user;
5234         char *filter;
5235         char *username;
5236         char *homedir;
5237         char *gidstr;
5238         char *uidstr;
5239         char *shell;
5240         const char *dn = NULL;
5241         struct dom_sid group_sid;
5242         struct dom_sid user_sid;
5243         gid_t gid = -1;
5244         uid_t uid = -1;
5245         NTSTATUS ret;
5246         int rc;
5247
5248         if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5249               acb_info & ACB_WSTRUST ||
5250               acb_info & ACB_SVRTRUST ||
5251               acb_info & ACB_DOMTRUST) {
5252                 is_machine = True;
5253         }
5254
5255         username = escape_ldap_string(talloc_tos(), name);
5256         filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5257                                  username, LDAP_OBJ_POSIXACCOUNT);
5258         TALLOC_FREE(username);
5259
5260         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5261         if (rc != LDAP_SUCCESS) {
5262                 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5263                 return NT_STATUS_ACCESS_DENIED;
5264         }
5265         talloc_autofree_ldapmsg(tmp_ctx, result);
5266
5267         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5268
5269         if (num_result > 1) {
5270                 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5271                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5272         }
5273
5274         if (num_result == 1) {
5275                 char *tmp;
5276                 /* check if it is just a posix account.
5277                  * or if there is a sid attached to this entry
5278                  */
5279
5280                 entry = ldap_first_entry(priv2ld(ldap_state), result);
5281                 if (!entry) {
5282                         return NT_STATUS_UNSUCCESSFUL;
5283                 }
5284
5285                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5286                 if (tmp) {
5287                         DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5288                         return NT_STATUS_USER_EXISTS;
5289                 }
5290
5291                 /* it is just a posix account, retrieve the dn for later use */
5292                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5293                 if (!dn) {
5294                         DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5295                         return NT_STATUS_NO_MEMORY;
5296                 }
5297         }
5298
5299         if (num_result == 0) {
5300                 add_posix = True;
5301         }
5302
5303         /* Create the basic samu structure and generate the mods for the ldap commit */
5304         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5305                 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5306                 return ret;
5307         }
5308
5309         sid_compose(&user_sid, get_global_sam_sid(), *rid);
5310
5311         user = samu_new(tmp_ctx);
5312         if (!user) {
5313                 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5314                 return NT_STATUS_NO_MEMORY;
5315         }
5316
5317         if (!pdb_set_username(user, name, PDB_SET)) {
5318                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5319                 return NT_STATUS_UNSUCCESSFUL;
5320         }
5321         if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5322                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5323                 return NT_STATUS_UNSUCCESSFUL;
5324         }
5325         if (is_machine) {
5326                 if (acb_info & ACB_NORMAL) {
5327                         if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5328                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5329                                 return NT_STATUS_UNSUCCESSFUL;
5330                         }
5331                 } else {
5332                         if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5333                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5334                                 return NT_STATUS_UNSUCCESSFUL;
5335                         }
5336                 }
5337         } else {
5338                 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5339                         DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5340                         return NT_STATUS_UNSUCCESSFUL;
5341                 }
5342         }
5343
5344         if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5345                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5346                 return NT_STATUS_UNSUCCESSFUL;
5347         }
5348
5349         if (!init_ldap_from_sam(ldap_state, entry, &mods, user, pdb_element_is_set_or_changed)) {
5350                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5351                 return NT_STATUS_UNSUCCESSFUL;
5352         }
5353
5354         if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5355                 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5356         }
5357         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5358
5359         if (add_posix) {
5360                 char *escape_name;
5361
5362                 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5363
5364                 /* retrieve the Domain Users group gid */
5365                 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_RID_USERS) ||
5366                     !sid_to_gid(&group_sid, &gid)) {
5367                         DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5368                         return NT_STATUS_INVALID_PRIMARY_GROUP;
5369                 }
5370
5371                 /* lets allocate a new userid for this user */
5372                 if (!winbind_allocate_uid(&uid)) {
5373                         DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5374                         return NT_STATUS_UNSUCCESSFUL;
5375                 }
5376
5377
5378                 if (is_machine) {
5379                         /* TODO: choose a more appropriate default for machines */
5380                         homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
5381                         shell = talloc_strdup(tmp_ctx, "/bin/false");
5382                 } else {
5383                         homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
5384                         shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
5385                 }
5386                 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5387                 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5388
5389                 escape_name = escape_rdn_val_string_alloc(name);
5390                 if (!escape_name) {
5391                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5392                         return NT_STATUS_NO_MEMORY;
5393                 }
5394
5395                 if (is_machine) {
5396                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix ());
5397                 } else {
5398                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix ());
5399                 }
5400
5401                 SAFE_FREE(escape_name);
5402
5403                 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5404                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5405                         return NT_STATUS_NO_MEMORY;
5406                 }
5407
5408                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5409                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5410                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5411                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5412                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5413                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5414                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5415         }
5416
5417         talloc_autofree_ldapmod(tmp_ctx, mods);
5418
5419         if (add_posix) {        
5420                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5421         } else {
5422                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5423         }       
5424
5425         if (rc != LDAP_SUCCESS) {
5426                 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5427                 return NT_STATUS_UNSUCCESSFUL;
5428         }
5429
5430         DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5431
5432         flush_pwnam_cache();
5433
5434         return NT_STATUS_OK;
5435 }
5436
5437 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5438 {
5439         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5440         LDAPMessage *result = NULL;
5441         LDAPMessage *entry = NULL;
5442         int num_result;
5443         const char *dn;
5444         char *filter;
5445         int rc;
5446
5447         DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5448
5449         filter = talloc_asprintf(tmp_ctx,
5450                                  "(&(uid=%s)"
5451                                  "(objectClass=%s)"
5452                                  "(objectClass=%s))",
5453                                  pdb_get_username(sam_acct),
5454                                  LDAP_OBJ_POSIXACCOUNT,
5455                                  LDAP_OBJ_SAMBASAMACCOUNT);
5456         if (filter == NULL) {
5457                 return NT_STATUS_NO_MEMORY;
5458         }
5459
5460         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5461         if (rc != LDAP_SUCCESS) {
5462                 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5463                 return NT_STATUS_UNSUCCESSFUL;
5464         }
5465         talloc_autofree_ldapmsg(tmp_ctx, result);
5466
5467         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5468
5469         if (num_result == 0) {
5470                 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5471                 return NT_STATUS_NO_SUCH_USER;
5472         }
5473
5474         if (num_result > 1) {
5475                 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5476                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5477         }
5478
5479         entry = ldap_first_entry(priv2ld(ldap_state), result);
5480         if (!entry) {
5481                 return NT_STATUS_UNSUCCESSFUL;
5482         }
5483
5484         /* it is just a posix account, retrieve the dn for later use */
5485         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5486         if (!dn) {
5487                 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5488                 return NT_STATUS_NO_MEMORY;
5489         }
5490
5491         /* try to remove memberships first */
5492         {
5493                 NTSTATUS status;
5494                 struct dom_sid *sids = NULL;
5495                 gid_t *gids = NULL;
5496                 uint32_t num_groups = 0;
5497                 int i;
5498                 uint32_t user_rid = pdb_get_user_rid(sam_acct);
5499
5500                 status = ldapsam_enum_group_memberships(my_methods,
5501                                                         tmp_ctx,
5502                                                         sam_acct,
5503                                                         &sids,
5504                                                         &gids,
5505                                                         &num_groups);
5506                 if (!NT_STATUS_IS_OK(status)) {
5507                         goto delete_dn;
5508                 }
5509
5510                 for (i=0; i < num_groups; i++) {
5511
5512                         uint32_t group_rid;
5513
5514                         sid_peek_rid(&sids[i], &group_rid);
5515
5516                         ldapsam_del_groupmem(my_methods,
5517                                              tmp_ctx,
5518                                              group_rid,
5519                                              user_rid);
5520                 }
5521         }
5522
5523  delete_dn:
5524
5525         rc = smbldap_delete(ldap_state->smbldap_state, dn);
5526         if (rc != LDAP_SUCCESS) {
5527                 return NT_STATUS_UNSUCCESSFUL;
5528         }
5529
5530         flush_pwnam_cache();
5531
5532         return NT_STATUS_OK;
5533 }
5534
5535 /*
5536  * ldapsam_create_group creates a new
5537  * posixGroup and sambaGroupMapping object
5538  * in the ldap groups subtree
5539  *
5540  * The gid is allocated by winbindd.
5541  */
5542
5543 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5544                                          TALLOC_CTX *tmp_ctx,
5545                                          const char *name,
5546                                          uint32_t *rid)
5547 {
5548         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5549         NTSTATUS ret;
5550         LDAPMessage *entry = NULL;
5551         LDAPMessage *result = NULL;
5552         uint32_t num_result;
5553         bool is_new_entry = False;
5554         LDAPMod **mods = NULL;
5555         char *filter;
5556         char *groupsidstr;
5557         char *groupname;
5558         char *grouptype;
5559         char *gidstr;
5560         const char *dn = NULL;
5561         struct dom_sid group_sid;
5562         gid_t gid = -1;
5563         int rc;
5564
5565         groupname = escape_ldap_string(talloc_tos(), name);
5566         filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5567                                  groupname, LDAP_OBJ_POSIXGROUP);
5568         TALLOC_FREE(groupname);
5569
5570         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5571         if (rc != LDAP_SUCCESS) {
5572                 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5573                 return NT_STATUS_UNSUCCESSFUL;
5574         }
5575         talloc_autofree_ldapmsg(tmp_ctx, result);
5576
5577         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5578
5579         if (num_result > 1) {
5580                 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5581                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5582         }
5583
5584         if (num_result == 1) {
5585                 char *tmp;
5586                 /* check if it is just a posix group.
5587                  * or if there is a sid attached to this entry
5588                  */
5589
5590                 entry = ldap_first_entry(priv2ld(ldap_state), result);
5591                 if (!entry) {
5592                         return NT_STATUS_UNSUCCESSFUL;
5593                 }
5594
5595                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5596                 if (tmp) {
5597                         DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5598                         return NT_STATUS_GROUP_EXISTS;
5599                 }
5600
5601                 /* it is just a posix group, retrieve the gid and the dn for later use */
5602                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5603                 if (!tmp) {
5604                         DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5605                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5606                 }
5607
5608                 gid = strtoul(tmp, NULL, 10);
5609
5610                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5611                 if (!dn) {
5612                         DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5613                         return NT_STATUS_NO_MEMORY;
5614                 }
5615         }
5616
5617         if (num_result == 0) {
5618                 is_new_entry = true;
5619         }
5620
5621         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5622                 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5623                 return ret;
5624         }
5625
5626         sid_compose(&group_sid, get_global_sam_sid(), *rid);
5627
5628         groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5629                                                                &group_sid));
5630         grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5631
5632         if (!groupsidstr || !grouptype) {
5633                 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5634                 return NT_STATUS_NO_MEMORY;
5635         }
5636
5637         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5638         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5639         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5640         smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5641
5642         if (is_new_entry) {
5643                 char *escape_name;
5644
5645                 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5646
5647                 /* lets allocate a new groupid for this group */
5648                 if (!winbind_allocate_gid(&gid)) {
5649                         DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5650                         return NT_STATUS_UNSUCCESSFUL;
5651                 }
5652
5653                 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5654
5655                 escape_name = escape_rdn_val_string_alloc(name);
5656                 if (!escape_name) {
5657                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5658                         return NT_STATUS_NO_MEMORY;
5659                 }
5660
5661                 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix());
5662
5663                 SAFE_FREE(escape_name);
5664
5665                 if (!gidstr || !dn) {
5666                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5667                         return NT_STATUS_NO_MEMORY;
5668                 }
5669
5670                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5671                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5672                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5673         }
5674
5675         talloc_autofree_ldapmod(tmp_ctx, mods);
5676
5677         if (is_new_entry) {     
5678                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5679 #if 0
5680                 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5681                         /* This call may fail with rfc2307bis schema */
5682                         /* Retry adding a structural class */
5683                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5684                         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5685                 }
5686 #endif
5687         } else {
5688                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5689         }       
5690
5691         if (rc != LDAP_SUCCESS) {
5692                 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5693                 return NT_STATUS_UNSUCCESSFUL;
5694         }
5695
5696         DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5697
5698         return NT_STATUS_OK;
5699 }
5700
5701 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32_t rid)
5702 {
5703         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5704         LDAPMessage *result = NULL;
5705         LDAPMessage *entry = NULL;
5706         int num_result;
5707         const char *dn;
5708         char *gidstr;
5709         char *filter;
5710         struct dom_sid group_sid;
5711         int rc;
5712
5713         /* get the group sid */
5714         sid_compose(&group_sid, get_global_sam_sid(), rid);
5715
5716         filter = talloc_asprintf(tmp_ctx,
5717                                  "(&(sambaSID=%s)"
5718                                  "(objectClass=%s)"
5719                                  "(objectClass=%s))",
5720                                  sid_string_talloc(tmp_ctx, &group_sid),
5721                                  LDAP_OBJ_POSIXGROUP,
5722                                  LDAP_OBJ_GROUPMAP);
5723         if (filter == NULL) {
5724                 return NT_STATUS_NO_MEMORY;
5725         }
5726
5727         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5728         if (rc != LDAP_SUCCESS) {
5729                 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5730                 return NT_STATUS_UNSUCCESSFUL;
5731         }
5732         talloc_autofree_ldapmsg(tmp_ctx, result);
5733
5734         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5735
5736         if (num_result == 0) {
5737                 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5738                 return NT_STATUS_NO_SUCH_GROUP;
5739         }
5740
5741         if (num_result > 1) {
5742                 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5743                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5744         }
5745
5746         entry = ldap_first_entry(priv2ld(ldap_state), result);
5747         if (!entry) {
5748                 return NT_STATUS_UNSUCCESSFUL;
5749         }
5750
5751         /* here it is, retrieve the dn for later use */
5752         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5753         if (!dn) {
5754                 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5755                 return NT_STATUS_NO_MEMORY;
5756         }
5757
5758         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5759         if (!gidstr) {
5760                 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5761                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5762         }
5763
5764         /* check no user have this group marked as primary group */
5765         filter = talloc_asprintf(tmp_ctx,
5766                                  "(&(gidNumber=%s)"
5767                                  "(objectClass=%s)"
5768                                  "(objectClass=%s))",
5769                                  gidstr,
5770                                  LDAP_OBJ_POSIXACCOUNT,
5771                                  LDAP_OBJ_SAMBASAMACCOUNT);
5772
5773         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5774         if (rc != LDAP_SUCCESS) {
5775                 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5776                 return NT_STATUS_UNSUCCESSFUL;
5777         }
5778         talloc_autofree_ldapmsg(tmp_ctx, result);
5779
5780         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5781
5782         if (num_result != 0) {
5783                 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5784                 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5785         }
5786
5787         rc = smbldap_delete(ldap_state->smbldap_state, dn);
5788         if (rc != LDAP_SUCCESS) {
5789                 return NT_STATUS_UNSUCCESSFUL;
5790         }
5791
5792         return NT_STATUS_OK;
5793 }
5794
5795 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5796                                         TALLOC_CTX *tmp_ctx,
5797                                         uint32_t group_rid,
5798                                         uint32_t member_rid,
5799                                         int modop)
5800 {
5801         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5802         LDAPMessage *entry = NULL;
5803         LDAPMessage *result = NULL;
5804         uint32_t num_result;
5805         LDAPMod **mods = NULL;
5806         char *filter;
5807         char *uidstr;
5808         const char *dn = NULL;
5809         struct dom_sid group_sid;
5810         struct dom_sid member_sid;
5811         int rc;
5812
5813         switch (modop) {
5814         case LDAP_MOD_ADD:
5815                 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5816                 break;
5817         case LDAP_MOD_DELETE:
5818                 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5819                 break;
5820         default:
5821                 return NT_STATUS_UNSUCCESSFUL;
5822         }
5823
5824         /* get member sid  */
5825         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5826
5827         /* get the group sid */
5828         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5829
5830         filter = talloc_asprintf(tmp_ctx,
5831                                  "(&(sambaSID=%s)"
5832                                  "(objectClass=%s)"
5833                                  "(objectClass=%s))",
5834                                  sid_string_talloc(tmp_ctx, &member_sid),
5835                                  LDAP_OBJ_POSIXACCOUNT,
5836                                  LDAP_OBJ_SAMBASAMACCOUNT);
5837         if (filter == NULL) {
5838                 return NT_STATUS_NO_MEMORY;
5839         }
5840
5841         /* get the member uid */
5842         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5843         if (rc != LDAP_SUCCESS) {
5844                 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5845                 return NT_STATUS_UNSUCCESSFUL;
5846         }
5847         talloc_autofree_ldapmsg(tmp_ctx, result);
5848
5849         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5850
5851         if (num_result == 0) {
5852                 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5853                 return NT_STATUS_NO_SUCH_MEMBER;
5854         }
5855
5856         if (num_result > 1) {
5857                 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5858                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5859         }
5860
5861         entry = ldap_first_entry(priv2ld(ldap_state), result);
5862         if (!entry) {
5863                 return NT_STATUS_UNSUCCESSFUL;
5864         }
5865
5866         if (modop == LDAP_MOD_DELETE) {
5867                 /* check if we are trying to remove the member from his primary group */
5868                 char *gidstr;
5869                 gid_t user_gid, group_gid;
5870
5871                 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5872                 if (!gidstr) {
5873                         DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5874                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5875                 }
5876
5877                 user_gid = strtoul(gidstr, NULL, 10);
5878
5879                 if (!sid_to_gid(&group_sid, &group_gid)) {
5880                         DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5881                         return NT_STATUS_UNSUCCESSFUL;
5882                 }
5883
5884                 if (user_gid == group_gid) {
5885                         DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5886                         return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5887                 }
5888         }
5889
5890         /* here it is, retrieve the uid for later use */
5891         uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5892         if (!uidstr) {
5893                 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5894                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5895         }
5896
5897         filter = talloc_asprintf(tmp_ctx,
5898                                  "(&(sambaSID=%s)"
5899                                  "(objectClass=%s)"
5900                                  "(objectClass=%s))",
5901                                  sid_string_talloc(tmp_ctx, &group_sid),
5902                                  LDAP_OBJ_POSIXGROUP,
5903                                  LDAP_OBJ_GROUPMAP);
5904
5905         /* get the group */
5906         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5907         if (rc != LDAP_SUCCESS) {
5908                 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5909                 return NT_STATUS_UNSUCCESSFUL;
5910         }
5911         talloc_autofree_ldapmsg(tmp_ctx, result);
5912
5913         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5914
5915         if (num_result == 0) {
5916                 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5917                 return NT_STATUS_NO_SUCH_GROUP;
5918         }
5919
5920         if (num_result > 1) {
5921                 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5922                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5923         }
5924
5925         entry = ldap_first_entry(priv2ld(ldap_state), result);
5926         if (!entry) {
5927                 return NT_STATUS_UNSUCCESSFUL;
5928         }
5929
5930         /* here it is, retrieve the dn for later use */
5931         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5932         if (!dn) {
5933                 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5934                 return NT_STATUS_NO_MEMORY;
5935         }
5936
5937         smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5938
5939         talloc_autofree_ldapmod(tmp_ctx, mods);
5940
5941         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5942         if (rc != LDAP_SUCCESS) {
5943                 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5944                         DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5945                         return NT_STATUS_MEMBER_IN_GROUP;
5946                 }
5947                 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5948                         DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5949                         return NT_STATUS_MEMBER_NOT_IN_GROUP;
5950                 }
5951                 return NT_STATUS_UNSUCCESSFUL;
5952         }
5953
5954         return NT_STATUS_OK;
5955 }
5956
5957 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5958                                      TALLOC_CTX *tmp_ctx,
5959                                      uint32_t group_rid,
5960                                      uint32_t member_rid)
5961 {
5962         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5963 }
5964 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5965                                      TALLOC_CTX *tmp_ctx,
5966                                      uint32_t group_rid,
5967                                      uint32_t member_rid)
5968 {
5969         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5970 }
5971
5972 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5973                                           TALLOC_CTX *mem_ctx,
5974                                           struct samu *sampass)
5975 {
5976         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5977         LDAPMessage *entry = NULL;
5978         LDAPMessage *result = NULL;
5979         uint32_t num_result;
5980         LDAPMod **mods = NULL;
5981         char *filter;
5982         char *escape_username;
5983         char *gidstr;
5984         const char *dn = NULL;
5985         gid_t gid;
5986         int rc;
5987
5988         DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5989
5990         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5991                 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5992                 return NT_STATUS_UNSUCCESSFUL;
5993         }
5994         gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5995         if (!gidstr) {
5996                 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5997                 return NT_STATUS_NO_MEMORY;
5998         }
5999
6000         escape_username = escape_ldap_string(talloc_tos(),
6001                                              pdb_get_username(sampass));
6002         if (escape_username== NULL) {
6003                 return NT_STATUS_NO_MEMORY;
6004         }
6005
6006         filter = talloc_asprintf(mem_ctx,
6007                                  "(&(uid=%s)"
6008                                  "(objectClass=%s)"
6009                                  "(objectClass=%s))",
6010                                  escape_username,
6011                                  LDAP_OBJ_POSIXACCOUNT,
6012                                  LDAP_OBJ_SAMBASAMACCOUNT);
6013
6014         TALLOC_FREE(escape_username);
6015
6016         if (filter == NULL) {
6017                 return NT_STATUS_NO_MEMORY;
6018         }
6019
6020         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
6021         if (rc != LDAP_SUCCESS) {
6022                 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
6023                 return NT_STATUS_UNSUCCESSFUL;
6024         }
6025         talloc_autofree_ldapmsg(mem_ctx, result);
6026
6027         num_result = ldap_count_entries(priv2ld(ldap_state), result);
6028
6029         if (num_result == 0) {
6030                 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
6031                 return NT_STATUS_NO_SUCH_USER;
6032         }
6033
6034         if (num_result > 1) {
6035                 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
6036                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
6037         }
6038
6039         entry = ldap_first_entry(priv2ld(ldap_state), result);
6040         if (!entry) {
6041                 return NT_STATUS_UNSUCCESSFUL;
6042         }
6043
6044         /* retrieve the dn for later use */
6045         dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
6046         if (!dn) {
6047                 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
6048                 return NT_STATUS_NO_MEMORY;
6049         }
6050
6051         /* remove the old one, and add the new one, this way we do not risk races */
6052         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
6053
6054         if (mods == NULL) {
6055                 return NT_STATUS_OK;
6056         }
6057
6058         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
6059
6060         if (rc != LDAP_SUCCESS) {
6061                 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
6062                          pdb_get_username(sampass), gidstr));
6063                 return NT_STATUS_UNSUCCESSFUL;
6064         }
6065
6066         flush_pwnam_cache();
6067
6068         return NT_STATUS_OK;
6069 }
6070
6071
6072 /**********************************************************************
6073  trusted domains functions
6074  *********************************************************************/
6075
6076 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
6077                            const char *domain)
6078 {
6079         return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
6080                                ldap_state->domain_dn);
6081 }
6082
6083 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
6084                                   TALLOC_CTX *mem_ctx,
6085                                   const char *domain, LDAPMessage **entry)
6086 {
6087         int rc;
6088         char *filter;
6089         int scope = LDAP_SCOPE_SUBTREE;
6090         const char **attrs = NULL; /* NULL: get all attrs */
6091         int attrsonly = 0; /* 0: return values too */
6092         LDAPMessage *result = NULL;
6093         char *trusted_dn;
6094         uint32_t num_result;
6095
6096         filter = talloc_asprintf(talloc_tos(),
6097                                  "(&(objectClass=%s)(sambaDomainName=%s))",
6098                                  LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
6099
6100         trusted_dn = trusteddom_dn(ldap_state, domain);
6101         if (trusted_dn == NULL) {
6102                 return False;
6103         }
6104         rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
6105                             filter, attrs, attrsonly, &result);
6106
6107         if (result != NULL) {
6108                 talloc_autofree_ldapmsg(mem_ctx, result);
6109         }
6110
6111         if (rc == LDAP_NO_SUCH_OBJECT) {
6112                 *entry = NULL;
6113                 return True;
6114         }
6115
6116         if (rc != LDAP_SUCCESS) {
6117                 return False;
6118         }
6119
6120         num_result = ldap_count_entries(priv2ld(ldap_state), result);
6121
6122         if (num_result > 1) {
6123                 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
6124                           "%s object for domain '%s'?!\n",
6125                           LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6126                 return False;
6127         }
6128
6129         if (num_result == 0) {
6130                 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
6131                           "%s object for domain %s.\n",
6132                           LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
6133                 *entry = NULL;
6134         } else {
6135                 *entry = ldap_first_entry(priv2ld(ldap_state), result);
6136         }
6137
6138         return True;
6139 }
6140
6141 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
6142                                       const char *domain,
6143                                       char** pwd,
6144                                       struct dom_sid *sid,
6145                                       time_t *pass_last_set_time)
6146 {
6147         struct ldapsam_privates *ldap_state =
6148                 (struct ldapsam_privates *)methods->private_data;
6149         LDAPMessage *entry = NULL;
6150
6151         DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
6152
6153         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
6154             (entry == NULL))
6155         {
6156                 return False;
6157         }
6158
6159         /* password */
6160         if (pwd != NULL) {
6161                 char *pwd_str;
6162                 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6163                                 entry, "sambaClearTextPassword", talloc_tos());
6164                 if (pwd_str == NULL) {
6165                         return False;
6166                 }
6167                 /* trusteddom_pw routines do not use talloc yet... */
6168                 *pwd = SMB_STRDUP(pwd_str);
6169                 if (*pwd == NULL) {
6170                         return False;
6171                 }
6172         }
6173
6174         /* last change time */
6175         if (pass_last_set_time != NULL) {
6176                 char *time_str;
6177                 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6178                                 entry, "sambaPwdLastSet", talloc_tos());
6179                 if (time_str == NULL) {
6180                         return False;
6181                 }
6182                 *pass_last_set_time = (time_t)atol(time_str);
6183         }
6184
6185         /* domain sid */
6186         if (sid != NULL) {
6187                 char *sid_str;
6188                 struct dom_sid dom_sid;
6189                 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6190                                                           entry, "sambaSID",
6191                                                           talloc_tos());
6192                 if (sid_str == NULL) {
6193                         return False;
6194                 }
6195                 if (!string_to_sid(&dom_sid, sid_str)) {
6196                         return False;
6197                 }
6198                 sid_copy(sid, &dom_sid);
6199         }
6200
6201         return True;
6202 }
6203
6204 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
6205                                       const char* domain,
6206                                       const char* pwd,
6207                                       const struct dom_sid *sid)
6208 {
6209         struct ldapsam_privates *ldap_state =
6210                 (struct ldapsam_privates *)methods->private_data;
6211         LDAPMessage *entry = NULL;
6212         LDAPMod **mods = NULL;
6213         char *prev_pwd = NULL;
6214         char *trusted_dn = NULL;
6215         int rc;
6216
6217         DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
6218
6219         /*
6220          * get the current entry (if there is one) in order to put the
6221          * current password into the previous password attribute
6222          */
6223         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6224                 return False;
6225         }
6226
6227         mods = NULL;
6228         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
6229                          LDAP_OBJ_TRUSTDOM_PASSWORD);
6230         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
6231                          domain);
6232         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
6233                          sid_string_tos(sid));
6234         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
6235                          talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
6236         smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6237                          "sambaClearTextPassword", pwd);
6238
6239         if (entry != NULL) {
6240                 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6241                                 entry, "sambaClearTextPassword", talloc_tos());
6242                 if (prev_pwd != NULL) {
6243                         smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
6244                                          "sambaPreviousClearTextPassword",
6245                                          prev_pwd);
6246                 }
6247         }
6248
6249         talloc_autofree_ldapmod(talloc_tos(), mods);
6250
6251         trusted_dn = trusteddom_dn(ldap_state, domain);
6252         if (trusted_dn == NULL) {
6253                 return False;
6254         }
6255         if (entry == NULL) {
6256                 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
6257         } else {
6258                 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
6259         }
6260
6261         if (rc != LDAP_SUCCESS) {
6262                 DEBUG(1, ("error writing trusted domain password!\n"));
6263                 return False;
6264         }
6265
6266         return True;
6267 }
6268
6269 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
6270                                       const char *domain)
6271 {
6272         int rc;
6273         struct ldapsam_privates *ldap_state =
6274                 (struct ldapsam_privates *)methods->private_data;
6275         LDAPMessage *entry = NULL;
6276         const char *trusted_dn;
6277
6278         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6279                 return False;
6280         }
6281
6282         if (entry == NULL) {
6283                 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6284                           "%s\n", domain));
6285                 return True;
6286         }
6287
6288         trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6289                                        entry);
6290         if (trusted_dn == NULL) {
6291                 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6292                 return False;
6293         }
6294
6295         rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6296         if (rc != LDAP_SUCCESS) {
6297                 return False;
6298         }
6299
6300         return True;
6301 }
6302
6303 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
6304                                          TALLOC_CTX *mem_ctx,
6305                                          uint32_t *num_domains,
6306                                          struct trustdom_info ***domains)
6307 {
6308         int rc;
6309         struct ldapsam_privates *ldap_state =
6310                 (struct ldapsam_privates *)methods->private_data;
6311         char *filter;
6312         int scope = LDAP_SCOPE_SUBTREE;
6313         const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6314         int attrsonly = 0; /* 0: return values too */
6315         LDAPMessage *result = NULL;
6316         LDAPMessage *entry = NULL;
6317
6318         filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6319                                  LDAP_OBJ_TRUSTDOM_PASSWORD);
6320
6321         rc = smbldap_search(ldap_state->smbldap_state,
6322                             ldap_state->domain_dn,
6323                             scope,
6324                             filter,
6325                             attrs,
6326                             attrsonly,
6327                             &result);
6328
6329         if (result != NULL) {
6330                 talloc_autofree_ldapmsg(mem_ctx, result);
6331         }
6332
6333         if (rc != LDAP_SUCCESS) {
6334                 return NT_STATUS_UNSUCCESSFUL;
6335         }
6336
6337         *num_domains = 0;
6338         if (!(*domains = talloc_array(mem_ctx, struct trustdom_info *, 1))) {
6339                 DEBUG(1, ("talloc failed\n"));
6340                 return NT_STATUS_NO_MEMORY;
6341         }
6342
6343         for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6344              entry != NULL;
6345              entry = ldap_next_entry(priv2ld(ldap_state), entry))
6346         {
6347                 char *dom_name, *dom_sid_str;
6348                 struct trustdom_info *dom_info;
6349
6350                 dom_info = talloc(*domains, struct trustdom_info);
6351                 if (dom_info == NULL) {
6352                         DEBUG(1, ("talloc failed\n"));
6353                         return NT_STATUS_NO_MEMORY;
6354                 }
6355
6356                 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6357                                                            entry,
6358                                                            "sambaDomainName",
6359                                                            talloc_tos());
6360                 if (dom_name == NULL) {
6361                         DEBUG(1, ("talloc failed\n"));
6362                         return NT_STATUS_NO_MEMORY;
6363                 }
6364                 dom_info->name = dom_name;
6365
6366                 dom_sid_str = smbldap_talloc_single_attribute(
6367                                         priv2ld(ldap_state), entry, "sambaSID",
6368                                         talloc_tos());
6369                 if (dom_sid_str == NULL) {
6370                         DEBUG(1, ("talloc failed\n"));
6371                         return NT_STATUS_NO_MEMORY;
6372                 }
6373                 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6374                         DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6375                                   dom_sid_str));
6376                         return NT_STATUS_UNSUCCESSFUL;
6377                 }
6378
6379                 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6380                              domains, num_domains);
6381
6382                 if (*domains == NULL) {
6383                         DEBUG(1, ("talloc failed\n"));
6384                         return NT_STATUS_NO_MEMORY;
6385                 }
6386         }
6387
6388         DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6389         return NT_STATUS_OK;
6390 }
6391
6392
6393 /**********************************************************************
6394  Housekeeping
6395  *********************************************************************/
6396
6397 static void free_private_data(void **vp) 
6398 {
6399         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6400
6401         smbldap_free_struct(&(*ldap_state)->smbldap_state);
6402
6403         if ((*ldap_state)->result != NULL) {
6404                 ldap_msgfree((*ldap_state)->result);
6405                 (*ldap_state)->result = NULL;
6406         }
6407         if ((*ldap_state)->domain_dn != NULL) {
6408                 SAFE_FREE((*ldap_state)->domain_dn);
6409         }
6410
6411         *ldap_state = NULL;
6412
6413         /* No need to free any further, as it is talloc()ed */
6414 }
6415
6416 /*********************************************************************
6417  Intitalise the parts of the pdb_methods structure that are common to 
6418  all pdb_ldap modes
6419 *********************************************************************/
6420
6421 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6422 {
6423         NTSTATUS nt_status;
6424         struct ldapsam_privates *ldap_state;
6425
6426         if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6427                 return nt_status;
6428         }
6429
6430         (*pdb_method)->name = "ldapsam";
6431
6432         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6433         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6434         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6435         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6436         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6437         (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6438
6439         (*pdb_method)->getgrsid = ldapsam_getgrsid;
6440         (*pdb_method)->getgrgid = ldapsam_getgrgid;
6441         (*pdb_method)->getgrnam = ldapsam_getgrnam;
6442         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6443         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6444         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6445         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6446
6447         (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6448         (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6449
6450         (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6451
6452         (*pdb_method)->capabilities = ldapsam_capabilities;
6453         (*pdb_method)->new_rid = ldapsam_new_rid;
6454
6455         (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6456         (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6457         (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6458         (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6459
6460         /* TODO: Setup private data and free */
6461
6462         if ( !(ldap_state = talloc_zero(*pdb_method, struct ldapsam_privates)) ) {
6463                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6464                 return NT_STATUS_NO_MEMORY;
6465         }
6466
6467         nt_status = smbldap_init(*pdb_method, pdb_get_event_context(),
6468                                  location, &ldap_state->smbldap_state);
6469
6470         if ( !NT_STATUS_IS_OK(nt_status) ) {
6471                 return nt_status;
6472         }
6473
6474         if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6475                 return NT_STATUS_NO_MEMORY;
6476         }
6477
6478         (*pdb_method)->private_data = ldap_state;
6479
6480         (*pdb_method)->free_private_data = free_private_data;
6481
6482         return NT_STATUS_OK;
6483 }
6484
6485 /**********************************************************************
6486  Initialise the 'compat' mode for pdb_ldap
6487  *********************************************************************/
6488
6489 NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
6490 {
6491         NTSTATUS nt_status;
6492         struct ldapsam_privates *ldap_state;
6493         char *uri = talloc_strdup( NULL, location );
6494
6495         trim_char( uri, '\"', '\"' );
6496         nt_status = pdb_init_ldapsam_common( pdb_method, uri );
6497         if ( uri )
6498                 TALLOC_FREE( uri );
6499
6500         if ( !NT_STATUS_IS_OK(nt_status) ) {
6501                 return nt_status;
6502         }
6503
6504         (*pdb_method)->name = "ldapsam_compat";
6505
6506         ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6507         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
6508
6509         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
6510
6511         return NT_STATUS_OK;
6512 }
6513
6514 /**********************************************************************
6515  Initialise the normal mode for pdb_ldap
6516  *********************************************************************/
6517
6518 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
6519 {
6520         NTSTATUS nt_status;
6521         struct ldapsam_privates *ldap_state = NULL;
6522         uint32_t alg_rid_base;
6523         char *alg_rid_base_string = NULL;
6524         LDAPMessage *result = NULL;
6525         LDAPMessage *entry = NULL;
6526         struct dom_sid ldap_domain_sid;
6527         struct dom_sid secrets_domain_sid;
6528         char *domain_sid_string = NULL;
6529         char *dn = NULL;
6530         char *uri = talloc_strdup( NULL, location );
6531
6532         trim_char( uri, '\"', '\"' );
6533         nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6534
6535         TALLOC_FREE(uri);
6536
6537         if (!NT_STATUS_IS_OK(nt_status)) {
6538                 return nt_status;
6539         }
6540
6541         (*pdb_method)->name = "ldapsam";
6542
6543         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6544         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6545         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6546         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6547         (*pdb_method)->search_users = ldapsam_search_users;
6548         (*pdb_method)->search_groups = ldapsam_search_groups;
6549         (*pdb_method)->search_aliases = ldapsam_search_aliases;
6550
6551         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6552                 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6553                 (*pdb_method)->enum_group_memberships =
6554                         ldapsam_enum_group_memberships;
6555                 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6556                 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6557                 (*pdb_method)->uid_to_sid = ldapsam_uid_to_sid;
6558                 (*pdb_method)->gid_to_sid = ldapsam_gid_to_sid;
6559
6560                 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6561                         (*pdb_method)->create_user = ldapsam_create_user;
6562                         (*pdb_method)->delete_user = ldapsam_delete_user;
6563                         (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6564                         (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6565                         (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6566                         (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6567                         (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6568                 }
6569         }
6570
6571         ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6572         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6573
6574         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6575
6576         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6577                                                &result,
6578                                                ldap_state->domain_name, True);
6579
6580         if ( !NT_STATUS_IS_OK(nt_status) ) {
6581                 DEBUG(0, ("pdb_init_ldapsam: WARNING: Could not get domain "
6582                           "info, nor add one to the domain. "
6583                           "We cannot work reliably without it.\n"));
6584                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
6585         }
6586
6587         /* Given that the above might fail, everything below this must be
6588          * optional */
6589
6590         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6591                                  result);
6592         if (!entry) {
6593                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6594                           "entry\n"));
6595                 ldap_msgfree(result);
6596                 return NT_STATUS_UNSUCCESSFUL;
6597         }
6598
6599         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6600         if (!dn) {
6601                 ldap_msgfree(result);
6602                 return NT_STATUS_UNSUCCESSFUL;
6603         }
6604
6605         ldap_state->domain_dn = smb_xstrdup(dn);
6606         TALLOC_FREE(dn);
6607
6608         domain_sid_string = smbldap_talloc_single_attribute(
6609                     ldap_state->smbldap_state->ldap_struct,
6610                     entry,
6611                     get_userattr_key2string(ldap_state->schema_ver,
6612                                             LDAP_ATTR_USER_SID),
6613                     talloc_tos());
6614
6615         if (domain_sid_string) {
6616                 bool found_sid;
6617                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6618                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6619                                   "read as a valid SID\n", domain_sid_string));
6620                         ldap_msgfree(result);
6621                         TALLOC_FREE(domain_sid_string);
6622                         return NT_STATUS_INVALID_PARAMETER;
6623                 }
6624                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
6625                                                      &secrets_domain_sid);
6626                 if (!found_sid || !dom_sid_equal(&secrets_domain_sid,
6627                                              &ldap_domain_sid)) {
6628                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6629                                   "%s based on pdb_ldap results %s -> %s\n",
6630                                   ldap_state->domain_name,
6631                                   sid_string_dbg(&secrets_domain_sid),
6632                                   sid_string_dbg(&ldap_domain_sid)));
6633
6634                         /* reset secrets.tdb sid */
6635                         secrets_store_domain_sid(ldap_state->domain_name,
6636                                                  &ldap_domain_sid);
6637                         DEBUG(1, ("New global sam SID: %s\n",
6638                                   sid_string_dbg(get_global_sam_sid())));
6639                 }
6640                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6641                 TALLOC_FREE(domain_sid_string);
6642         }
6643
6644         alg_rid_base_string = smbldap_talloc_single_attribute(
6645                     ldap_state->smbldap_state->ldap_struct,
6646                     entry,
6647                     get_attr_key2string( dominfo_attr_list,
6648                                          LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6649                     talloc_tos());
6650         if (alg_rid_base_string) {
6651                 alg_rid_base = (uint32_t)atol(alg_rid_base_string);
6652                 if (alg_rid_base != algorithmic_rid_base()) {
6653                         DEBUG(0, ("The value of 'algorithmic RID base' has "
6654                                   "changed since the LDAP\n"
6655                                   "database was initialised.  Aborting. \n"));
6656                         ldap_msgfree(result);
6657                         TALLOC_FREE(alg_rid_base_string);
6658                         return NT_STATUS_UNSUCCESSFUL;
6659                 }
6660                 TALLOC_FREE(alg_rid_base_string);
6661         }
6662         ldap_msgfree(result);
6663
6664         return NT_STATUS_OK;
6665 }
6666
6667 NTSTATUS pdb_ldap_init(void)
6668 {
6669         NTSTATUS nt_status;
6670         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
6671                 return nt_status;
6672
6673         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
6674                 return nt_status;
6675
6676         /* Let pdb_nds register backends */
6677         pdb_nds_init();
6678
6679         pdb_ipa_init();
6680
6681         return NT_STATUS_OK;
6682 }