r13679: Commiting the rm_primary_group.patch posted on samba-technical
[samba.git] / source / 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     
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
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
48 #undef DBGC_CLASS
49 #define DBGC_CLASS DBGC_PASSDB
50
51 #include <lber.h>
52 #include <ldap.h>
53
54 /*
55  * Work around versions of the LDAP client libs that don't have the OIDs
56  * defined, or have them defined under the old name.  
57  * This functionality is really a factor of the server, not the client 
58  *
59  */
60
61 #if defined(LDAP_EXOP_X_MODIFY_PASSWD) && !defined(LDAP_EXOP_MODIFY_PASSWD)
62 #define LDAP_EXOP_MODIFY_PASSWD LDAP_EXOP_X_MODIFY_PASSWD
63 #elif !defined(LDAP_EXOP_MODIFY_PASSWD)
64 #define LDAP_EXOP_MODIFY_PASSWD "1.3.6.1.4.1.4203.1.11.1"
65 #endif
66
67 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_ID) && !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
68 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID LDAP_EXOP_X_MODIFY_PASSWD_ID
69 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
70 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID        ((ber_tag_t) 0x80U)
71 #endif
72
73 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_NEW) && !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
74 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW LDAP_EXOP_X_MODIFY_PASSWD_NEW
75 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
76 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW       ((ber_tag_t) 0x82U)
77 #endif
78
79
80 #include "smbldap.h"
81
82 /**********************************************************************
83  Simple helper function to make stuff better readable
84  **********************************************************************/
85
86 static LDAP *priv2ld(struct ldapsam_privates *priv)
87 {
88         return priv->smbldap_state->ldap_struct;
89 }
90
91 /**********************************************************************
92  Get the attribute name given a user schame version.
93  **********************************************************************/
94  
95 static const char* get_userattr_key2string( int schema_ver, int key )
96 {
97         switch ( schema_ver ) {
98                 case SCHEMAVER_SAMBAACCOUNT:
99                         return get_attr_key2string( attrib_map_v22, key );
100                         
101                 case SCHEMAVER_SAMBASAMACCOUNT:
102                         return get_attr_key2string( attrib_map_v30, key );
103                         
104                 default:
105                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
106                         break;
107         }
108         return NULL;
109 }
110
111 /**********************************************************************
112  Return the list of attribute names given a user schema version.
113 **********************************************************************/
114
115 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
116 {
117         switch ( schema_ver ) {
118                 case SCHEMAVER_SAMBAACCOUNT:
119                         return get_attr_list( mem_ctx, attrib_map_v22 );
120                         
121                 case SCHEMAVER_SAMBASAMACCOUNT:
122                         return get_attr_list( mem_ctx, attrib_map_v30 );
123                 default:
124                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
125                         break;
126         }
127         
128         return NULL;
129 }
130
131 /**************************************************************************
132  Return the list of attribute names to delete given a user schema version.
133 **************************************************************************/
134
135 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
136                                               int schema_ver )
137 {
138         switch ( schema_ver ) {
139                 case SCHEMAVER_SAMBAACCOUNT:
140                         return get_attr_list( mem_ctx,
141                                               attrib_map_to_delete_v22 );
142                         
143                 case SCHEMAVER_SAMBASAMACCOUNT:
144                         return get_attr_list( mem_ctx,
145                                               attrib_map_to_delete_v30 );
146                 default:
147                         DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
148                         break;
149         }
150         
151         return NULL;
152 }
153
154
155 /*******************************************************************
156  Generate the LDAP search filter for the objectclass based on the 
157  version of the schema we are using.
158 ******************************************************************/
159
160 static const char* get_objclass_filter( int schema_ver )
161 {
162         static fstring objclass_filter;
163         
164         switch( schema_ver ) {
165                 case SCHEMAVER_SAMBAACCOUNT:
166                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
167                         break;
168                 case SCHEMAVER_SAMBASAMACCOUNT:
169                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
170                         break;
171                 default:
172                         DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
173                         break;
174         }
175         
176         return objclass_filter; 
177 }
178
179 /*****************************************************************
180  Scan a sequence number off OpenLDAP's syncrepl contextCSN
181 ******************************************************************/
182
183 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
184 {
185         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
186         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
187         LDAPMessage *msg = NULL;
188         LDAPMessage *entry = NULL;
189         TALLOC_CTX *mem_ctx;
190         char **values = NULL;
191         int rc, num_result, num_values, rid;
192         pstring suffix;
193         fstring tok;
194         const char *p;
195         const char **attrs;
196
197         /* Unfortunatly there is no proper way to detect syncrepl-support in
198          * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
199          * but do not show up in the root-DSE yet. Neither we can query the
200          * subschema-context for the syncProviderSubentry or syncConsumerSubentry
201          * objectclass. Currently we require lp_ldap_suffix() to show up as
202          * namingContext.  -  Guenther
203          */
204
205         if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
206                 return ntstatus;
207         }
208
209         if (!seq_num) {
210                 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
211                 return ntstatus;
212         }
213
214         if (!smbldap_has_naming_context(ldap_state->smbldap_state, lp_ldap_suffix())) {
215                 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
216                          "as top-level namingContext\n", lp_ldap_suffix()));
217                 return ntstatus;
218         }
219
220         mem_ctx = talloc_init("ldapsam_get_seq_num");
221
222         if (mem_ctx == NULL)
223                 return NT_STATUS_NO_MEMORY;
224
225         attrs = TALLOC_ARRAY(mem_ctx, const char *, 2);
226
227         /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
228         rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
229         if (rid > 0) {
230
231                 /* consumer syncreplCookie: */
232                 /* csn=20050126161620Z#0000001#00#00000 */
233                 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
234                 attrs[1] = NULL;
235                 pstr_sprintf( suffix, "cn=syncrepl%d,%s", rid, lp_ldap_suffix());
236
237         } else {
238
239                 /* provider contextCSN */
240                 /* 20050126161620Z#000009#00#000000 */
241                 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
242                 attrs[1] = NULL;
243                 pstr_sprintf( suffix, "cn=ldapsync,%s", lp_ldap_suffix());
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(&p, tok, "#", sizeof(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         pstring filter;
322         char *escape_user = escape_ldap_string_alloc(user);
323
324         if (!escape_user) {
325                 return LDAP_NO_MEMORY;
326         }
327
328         /*
329          * in the filter expression, replace %u with the real name
330          * so in ldap filter, %u MUST exist :-)
331          */
332         pstr_sprintf(filter, "(&%s%s)", "(uid=%u)", 
333                 get_objclass_filter(ldap_state->schema_ver));
334
335         /* 
336          * have to use this here because $ is filtered out
337            * in pstring_sub
338          */
339         
340
341         all_string_sub(filter, "%u", escape_user, sizeof(pstring));
342         SAFE_FREE(escape_user);
343
344         return smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
345 }
346
347 /*******************************************************************
348  Run the search by rid.
349 ******************************************************************/
350
351 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state, 
352                                          uint32 rid, LDAPMessage ** result, 
353                                          const char **attr)
354 {
355         pstring filter;
356         int rc;
357
358         pstr_sprintf(filter, "(&(rid=%i)%s)", rid, 
359                 get_objclass_filter(ldap_state->schema_ver));
360         
361         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
362         
363         return rc;
364 }
365
366 /*******************************************************************
367  Run the search by SID.
368 ******************************************************************/
369
370 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state, 
371                                          const DOM_SID *sid, LDAPMessage ** result, 
372                                          const char **attr)
373 {
374         pstring filter;
375         int rc;
376         fstring sid_string;
377
378         pstr_sprintf(filter, "(&(%s=%s)%s)", 
379                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
380                 sid_to_string(sid_string, sid), 
381                 get_objclass_filter(ldap_state->schema_ver));
382                 
383         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
384         
385         return rc;
386 }
387
388 /*******************************************************************
389  Delete complete object or objectclass and attrs from
390  object found in search_result depending on lp_ldap_delete_dn
391 ******************************************************************/
392
393 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
394                                 TALLOC_CTX *mem_ctx,
395                                 LDAPMessage *entry,
396                                 const char *objectclass,
397                                 const char **attrs)
398 {
399         LDAPMod **mods = NULL;
400         char *name;
401         const char *dn;
402         BerElement *ptr = NULL;
403
404         dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
405         if (dn == NULL) {
406                 return LDAP_NO_MEMORY;
407         }
408
409         if (lp_ldap_delete_dn()) {
410                 return smbldap_delete(priv->smbldap_state, dn);
411         }
412
413         /* Ok, delete only the SAM attributes */
414         
415         for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
416              name != NULL;
417              name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
418                 const char **attrib;
419
420                 /* We are only allowed to delete the attributes that
421                    really exist. */
422
423                 for (attrib = attrs; *attrib != NULL; attrib++) {
424                         if (strequal(*attrib, name)) {
425                                 DEBUG(10, ("ldapsam_delete_entry: deleting "
426                                            "attribute %s\n", name));
427                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
428                                                 NULL);
429                         }
430                 }
431                 ldap_memfree(name);
432         }
433
434         if (ptr != NULL) {
435                 ber_free(ptr, 0);
436         }
437         
438         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
439         talloc_autofree_ldapmod(mem_ctx, mods);
440         
441         return smbldap_modify(priv->smbldap_state, dn, mods);
442 }
443                   
444 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
445 {
446         pstring temp;   
447         struct tm tm;
448
449         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
450                         get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
451                         temp))
452                 return (time_t) 0;
453
454         strptime(temp, "%Y%m%d%H%M%SZ", &tm);
455         tzset();
456         return timegm(&tm);
457 }
458
459 /**********************************************************************
460  Initialize struct samu from an LDAP query.
461  (Based on init_sam_from_buffer in pdb_tdb.c)
462 *********************************************************************/
463
464 static BOOL init_sam_from_ldap(struct ldapsam_privates *ldap_state, 
465                                 struct samu * sampass,
466                                 LDAPMessage * entry)
467 {
468         time_t  logon_time,
469                         logoff_time,
470                         kickoff_time,
471                         pass_last_set_time, 
472                         pass_can_change_time, 
473                         pass_must_change_time,
474                         ldap_entry_time,
475                         bad_password_time;
476         pstring         username, 
477                         domain,
478                         nt_username,
479                         fullname,
480                         homedir,
481                         dir_drive,
482                         logon_script,
483                         profile_path,
484                         acct_desc,
485                         workstations;
486         char            munged_dial[2048];
487         uint32          user_rid; 
488         uint8           smblmpwd[LM_HASH_LEN],
489                         smbntpwd[NT_HASH_LEN];
490         BOOL            use_samba_attrs = True;
491         uint16          acct_ctrl = 0, 
492                         logon_divs;
493         uint16          bad_password_count = 0, 
494                         logon_count = 0;
495         uint32 hours_len;
496         uint8           hours[MAX_HOURS_LEN];
497         pstring temp;
498         LOGIN_CACHE     *cache_entry = NULL;
499         uint32          pwHistLen;
500         pstring         tmpstring;
501         BOOL expand_explicit = lp_passdb_expand_explicit();
502
503         /*
504          * do a little initialization
505          */
506         username[0]     = '\0';
507         domain[0]       = '\0';
508         nt_username[0]  = '\0';
509         fullname[0]     = '\0';
510         homedir[0]      = '\0';
511         dir_drive[0]    = '\0';
512         logon_script[0] = '\0';
513         profile_path[0] = '\0';
514         acct_desc[0]    = '\0';
515         munged_dial[0]  = '\0';
516         workstations[0] = '\0';
517          
518
519         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
520                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
521                 return False;
522         }
523
524         if (priv2ld(ldap_state) == NULL) {
525                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
526                           "ldap_struct is NULL!\n"));
527                 return False;
528         }
529         
530         if (!smbldap_get_single_pstring(priv2ld(ldap_state), entry, "uid",
531                                         username)) {
532                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
533                           "this user!\n"));
534                 return False;
535         }
536
537         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
538
539         pstrcpy(nt_username, username);
540
541         pstrcpy(domain, ldap_state->domain_name);
542         
543         pdb_set_username(sampass, username, PDB_SET);
544
545         pdb_set_domain(sampass, domain, PDB_DEFAULT);
546         pdb_set_nt_username(sampass, nt_username, PDB_SET);
547
548         /* deal with different attributes between the schema first */
549         
550         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
551                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
552                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), temp)) {
553                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
554                 }
555         } else {
556                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
557                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), temp)) {
558                         user_rid = (uint32)atol(temp);
559                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
560                 }
561         }
562
563         if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
564                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
565                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
566                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
567                         username));
568                 return False;
569         }
570
571         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
572                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), temp)) {
573                 /* leave as default */
574         } else {
575                 pass_last_set_time = (time_t) atol(temp);
576                 pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
577         }
578
579         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
580                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp)) {
581                 /* leave as default */
582         } else {
583                 logon_time = (time_t) atol(temp);
584                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
585         }
586
587         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
588                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp)) {
589                 /* leave as default */
590         } else {
591                 logoff_time = (time_t) atol(temp);
592                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
593         }
594
595         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
596                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp)) {
597                 /* leave as default */
598         } else {
599                 kickoff_time = (time_t) atol(temp);
600                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
601         }
602
603         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
604                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp)) {
605                 /* leave as default */
606         } else {
607                 pass_can_change_time = (time_t) atol(temp);
608                 pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
609         }
610
611         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
612                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp)) {    
613                 /* leave as default */
614         } else {
615                 pass_must_change_time = (time_t) atol(temp);
616                 pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
617         }
618
619         /* recommend that 'gecos' and 'displayName' should refer to the same
620          * attribute OID.  userFullName depreciated, only used by Samba
621          * primary rules of LDAP: don't make a new attribute when one is already defined
622          * that fits your needs; using cn then displayName rather than 'userFullName'
623          */
624
625         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
626                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), fullname)) {
627                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
628                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_CN), fullname)) {
629                         /* leave as default */
630                 } else {
631                         pdb_set_fullname(sampass, fullname, PDB_SET);
632                 }
633         } else {
634                 pdb_set_fullname(sampass, fullname, PDB_SET);
635         }
636
637         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
638                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), dir_drive)) 
639         {
640                 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
641         } else {
642                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
643         }
644
645         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
646                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), homedir)) 
647         {
648                 pdb_set_homedir( sampass, 
649                         talloc_sub_basic(sampass, username, lp_logon_home()),
650                         PDB_DEFAULT );
651         } else {
652                 pstrcpy( tmpstring, homedir );
653                 if (expand_explicit) {
654                         standard_sub_basic( username, tmpstring,
655                                             sizeof(tmpstring) );
656                 }
657                 pdb_set_homedir(sampass, tmpstring, PDB_SET);
658         }
659
660         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
661                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), logon_script)) 
662         {
663                 pdb_set_logon_script( sampass, 
664                         talloc_sub_basic(sampass, username, lp_logon_script()), 
665                         PDB_DEFAULT );
666         } else {
667                 pstrcpy( tmpstring, logon_script );
668                 if (expand_explicit) {
669                         standard_sub_basic( username, tmpstring,
670                                             sizeof(tmpstring) );
671                 }
672                 pdb_set_logon_script(sampass, tmpstring, PDB_SET);
673         }
674
675         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
676                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), profile_path)) 
677         {
678                 pdb_set_profile_path( sampass, 
679                         talloc_sub_basic( sampass, username, lp_logon_path()),
680                         PDB_DEFAULT );
681         } else {
682                 pstrcpy( tmpstring, profile_path );
683                 if (expand_explicit) {
684                         standard_sub_basic( username, tmpstring,
685                                             sizeof(tmpstring) );
686                 }
687                 pdb_set_profile_path(sampass, tmpstring, PDB_SET);
688         }
689
690         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
691                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), acct_desc)) 
692         {
693                 /* leave as default */
694         } else {
695                 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
696         }
697
698         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
699                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), workstations)) {
700                 /* leave as default */;
701         } else {
702                 pdb_set_workstations(sampass, workstations, PDB_SET);
703         }
704
705         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
706                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), munged_dial, sizeof(munged_dial))) {
707                 /* leave as default */;
708         } else {
709                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
710         }
711         
712         /* FIXME: hours stuff should be cleaner */
713         
714         logon_divs = 168;
715         hours_len = 21;
716         memset(hours, 0xff, hours_len);
717
718         if (ldap_state->is_nds_ldap) {
719                 char *user_dn;
720                 size_t pwd_len;
721                 char clear_text_pw[512];
722    
723                 /* Make call to Novell eDirectory ldap extension to get clear text password.
724                         NOTE: This will only work if we have an SSL connection to eDirectory. */
725                 user_dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
726                 if (user_dn != NULL) {
727                         DEBUG(3, ("init_sam_from_ldap: smbldap_get_dn(%s) returned '%s'\n", username, user_dn));
728
729                         pwd_len = sizeof(clear_text_pw);
730                         if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
731                                 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
732                                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
733                                         return False;
734                                 ZERO_STRUCT(smblmpwd);
735                                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
736                                         return False;
737                                 ZERO_STRUCT(smbntpwd);
738                                 use_samba_attrs = False;
739                         }
740                 } else {
741                         DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
742                 }
743         }
744
745         if (use_samba_attrs) {
746                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry, 
747                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), temp)) {
748                         /* leave as default */
749                 } else {
750                         pdb_gethexpwd(temp, smblmpwd);
751                         memset((char *)temp, '\0', strlen(temp)+1);
752                         if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
753                                 return False;
754                         ZERO_STRUCT(smblmpwd);
755                 }
756
757                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
758                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), temp)) {
759                         /* leave as default */
760                 } else {
761                         pdb_gethexpwd(temp, smbntpwd);
762                         memset((char *)temp, '\0', strlen(temp)+1);
763                         if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
764                                 return False;
765                         ZERO_STRUCT(smbntpwd);
766                 }
767         }
768
769         pwHistLen = 0;
770
771         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
772         if (pwHistLen > 0){
773                 uint8 *pwhist = NULL;
774                 int i;
775
776                 /* We can only store (sizeof(pstring)-1)/64 password history entries. */
777                 pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
778
779                 if ((pwhist = SMB_MALLOC(pwHistLen * PW_HISTORY_ENTRY_LEN)) == NULL){
780                         DEBUG(0, ("init_sam_from_ldap: malloc failed!\n"));
781                         return False;
782                 }
783                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
784
785                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry, 
786                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), temp)) {
787                         /* leave as default - zeros */
788                 } else {
789                         BOOL hex_failed = False;
790                         for (i = 0; i < pwHistLen; i++){
791                                 /* Get the 16 byte salt. */
792                                 if (!pdb_gethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
793                                         hex_failed = True;
794                                         break;
795                                 }
796                                 /* Get the 16 byte MD5 hash of salt+passwd. */
797                                 if (!pdb_gethexpwd(&temp[(i*64)+32],
798                                                 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN])) {
799                                         hex_failed = True;
800                                         break;
801                                 }
802                         }
803                         if (hex_failed) {
804                                 DEBUG(0,("init_sam_from_ldap: Failed to get password history for user %s\n",
805                                         username));
806                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
807                         }
808                 }
809                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
810                         SAFE_FREE(pwhist);
811                         return False;
812                 }
813                 SAFE_FREE(pwhist);
814         }
815
816         if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
817                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), temp)) {
818                 acct_ctrl |= ACB_NORMAL;
819         } else {
820                 acct_ctrl = pdb_decode_acct_ctrl(temp);
821
822                 if (acct_ctrl == 0)
823                         acct_ctrl |= ACB_NORMAL;
824
825                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
826         }
827
828         pdb_set_hours_len(sampass, hours_len, PDB_SET);
829         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
830
831         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
832                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_COUNT), temp)) {
833                         /* leave as default */
834         } else {
835                 bad_password_count = (uint32) atol(temp);
836                 pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
837         }
838
839         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
840                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_TIME), temp)) {
841                 /* leave as default */
842         } else {
843                 bad_password_time = (time_t) atol(temp);
844                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
845         }
846
847
848         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
849                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_COUNT), temp)) {
850                         /* leave as default */
851         } else {
852                 logon_count = (uint32) atol(temp);
853                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
854         }
855
856         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
857
858         if(!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
859                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_HOURS), temp)) {
860                         /* leave as default */
861         } else {
862                 pdb_gethexhours(temp, hours);
863                 memset((char *)temp, '\0', strlen(temp) +1);
864                 pdb_set_hours(sampass, hours, PDB_SET);
865                 ZERO_STRUCT(hours);
866         }
867
868         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
869                 if (smbldap_get_single_pstring(priv2ld(ldap_state), entry,
870                                                "uidNumber", temp)) {
871                         /* We've got a uid, feed the cache */
872                         uid_t uid = strtoul(temp, NULL, 10);
873                         store_uid_sid_cache(pdb_get_user_sid(sampass), uid);
874                 }
875         }
876
877         /* check the timestamp of the cache vs ldap entry */
878         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state, 
879                                                             entry)))
880                 return True;
881
882         /* see if we have newer updates */
883         if (!(cache_entry = login_cache_read(sampass))) {
884                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
885                            (unsigned int)pdb_get_bad_password_count(sampass),
886                            (unsigned int)pdb_get_bad_password_time(sampass)));
887                 return True;
888         }
889
890         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n", 
891                   (unsigned int)ldap_entry_time, (unsigned int)cache_entry->entry_timestamp, 
892                   (unsigned int)cache_entry->bad_password_time));
893
894         if (ldap_entry_time > cache_entry->entry_timestamp) {
895                 /* cache is older than directory , so
896                    we need to delete the entry but allow the 
897                    fields to be written out */
898                 login_cache_delentry(sampass);
899         } else {
900                 /* read cache in */
901                 pdb_set_acct_ctrl(sampass, 
902                                   pdb_get_acct_ctrl(sampass) | 
903                                   (cache_entry->acct_ctrl & ACB_AUTOLOCK),
904                                   PDB_SET);
905                 pdb_set_bad_password_count(sampass, 
906                                            cache_entry->bad_password_count, 
907                                            PDB_SET);
908                 pdb_set_bad_password_time(sampass, 
909                                           cache_entry->bad_password_time, 
910                                           PDB_SET);
911         }
912
913         SAFE_FREE(cache_entry);
914         return True;
915 }
916
917 /**********************************************************************
918  Initialize the ldap db from a struct samu. Called on update.
919  (Based on init_buffer_from_sam in pdb_tdb.c)
920 *********************************************************************/
921
922 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state, 
923                                 LDAPMessage *existing,
924                                 LDAPMod *** mods, struct samu * sampass,
925                                 BOOL (*need_update)(const struct samu *,
926                                                     enum pdb_elements))
927 {
928         pstring temp;
929         uint32 rid;
930
931         if (mods == NULL || sampass == NULL) {
932                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
933                 return False;
934         }
935
936         *mods = NULL;
937
938         /* 
939          * took out adding "objectclass: sambaAccount"
940          * do this on a per-mod basis
941          */
942         if (need_update(sampass, PDB_USERNAME))
943                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
944                               "uid", pdb_get_username(sampass));
945
946         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
947
948         /* only update the RID if we actually need to */
949         if (need_update(sampass, PDB_USERSID)) {
950                 fstring sid_string;
951                 fstring dom_sid_string;
952                 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
953                 
954                 switch ( ldap_state->schema_ver ) {
955                         case SCHEMAVER_SAMBAACCOUNT:
956                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
957                                         DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
958                                                 sid_to_string(sid_string, user_sid), 
959                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
960                                         return False;
961                                 }
962                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
963                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
964                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
965                                         temp);
966                                 break;
967                                 
968                         case SCHEMAVER_SAMBASAMACCOUNT:
969                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
970                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
971                                         sid_to_string(sid_string, user_sid));                                 
972                                 break;
973                                 
974                         default:
975                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
976                                 break;
977                 }               
978         }
979
980         /* we don't need to store the primary group RID - so leaving it
981            'free' to hang off the unix primary group makes life easier */
982
983         if (need_update(sampass, PDB_GROUPSID)) {
984                 fstring sid_string;
985                 fstring dom_sid_string;
986                 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
987                 
988                 switch ( ldap_state->schema_ver ) {
989                         case SCHEMAVER_SAMBAACCOUNT:
990                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
991                                         DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
992                                                 sid_to_string(sid_string, group_sid),
993                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
994                                         return False;
995                                 }
996
997                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
998                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
999                                         get_userattr_key2string(ldap_state->schema_ver, 
1000                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
1001                                 break;
1002                                 
1003                         case SCHEMAVER_SAMBASAMACCOUNT:
1004                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1005                                         get_userattr_key2string(ldap_state->schema_ver, 
1006                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_string(sid_string, group_sid));
1007                                 break;
1008                                 
1009                         default:
1010                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1011                                 break;
1012                 }
1013                 
1014         }
1015         
1016         /* displayName, cn, and gecos should all be the same
1017          *  most easily accomplished by giving them the same OID
1018          *  gecos isn't set here b/c it should be handled by the 
1019          *  add-user script
1020          *  We change displayName only and fall back to cn if
1021          *  it does not exist.
1022          */
1023
1024         if (need_update(sampass, PDB_FULLNAME))
1025                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1026                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
1027                         pdb_get_fullname(sampass));
1028
1029         if (need_update(sampass, PDB_ACCTDESC))
1030                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1031                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
1032                         pdb_get_acct_desc(sampass));
1033
1034         if (need_update(sampass, PDB_WORKSTATIONS))
1035                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1036                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
1037                         pdb_get_workstations(sampass));
1038         
1039         if (need_update(sampass, PDB_MUNGEDDIAL))
1040                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1041                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
1042                         pdb_get_munged_dial(sampass));
1043         
1044         if (need_update(sampass, PDB_SMBHOME))
1045                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1046                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
1047                         pdb_get_homedir(sampass));
1048                         
1049         if (need_update(sampass, PDB_DRIVE))
1050                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1051                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
1052                         pdb_get_dir_drive(sampass));
1053
1054         if (need_update(sampass, PDB_LOGONSCRIPT))
1055                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1056                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1057                         pdb_get_logon_script(sampass));
1058
1059         if (need_update(sampass, PDB_PROFILE))
1060                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1061                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1062                         pdb_get_profile_path(sampass));
1063
1064         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
1065         if (need_update(sampass, PDB_LOGONTIME))
1066                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1067                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1068
1069         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
1070         if (need_update(sampass, PDB_LOGOFFTIME))
1071                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1072                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1073
1074         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
1075         if (need_update(sampass, PDB_KICKOFFTIME))
1076                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1077                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1078
1079         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
1080         if (need_update(sampass, PDB_CANCHANGETIME))
1081                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1082                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1083
1084         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
1085         if (need_update(sampass, PDB_MUSTCHANGETIME))
1086                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1087                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1088
1089
1090         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1091                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1092
1093                 if (need_update(sampass, PDB_LMPASSWD)) {
1094                         const uchar *lm_pw =  pdb_get_lanman_passwd(sampass);
1095                         if (lm_pw) {
1096                                 pdb_sethexpwd(temp, lm_pw,
1097                                               pdb_get_acct_ctrl(sampass));
1098                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1099                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1100                                                  temp);
1101                         } else {
1102                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1103                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1104                                                  NULL);
1105                         }
1106                 }
1107                 if (need_update(sampass, PDB_NTPASSWD)) {
1108                         const uchar *nt_pw =  pdb_get_nt_passwd(sampass);
1109                         if (nt_pw) {
1110                                 pdb_sethexpwd(temp, nt_pw,
1111                                               pdb_get_acct_ctrl(sampass));
1112                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1113                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1114                                                  temp);
1115                         } else {
1116                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1117                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1118                                                  NULL);
1119                         }
1120                 }
1121
1122                 if (need_update(sampass, PDB_PWHISTORY)) {
1123                         uint32 pwHistLen = 0;
1124                         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
1125                         if (pwHistLen == 0) {
1126                                 /* Remove any password history from the LDAP store. */
1127                                 memset(temp, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1128                                 temp[64] = '\0';
1129                         } else {
1130                                 int i; 
1131                                 uint32 currHistLen = 0;
1132                                 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1133                                 if (pwhist != NULL) {
1134                                         /* We can only store (sizeof(pstring)-1)/64 password history entries. */
1135                                         pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
1136                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1137                                                 /* Store the salt. */
1138                                                 pdb_sethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1139                                                 /* Followed by the md5 hash of salt + md4 hash */
1140                                                 pdb_sethexpwd(&temp[(i*64)+32],
1141                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1142                                                 DEBUG(100, ("temp=%s\n", temp));
1143                                         }
1144                                 } 
1145                         }
1146                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1147                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1148                                          temp);
1149                 }
1150
1151                 if (need_update(sampass, PDB_PASSLASTSET)) {
1152                         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
1153                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1154                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1155                                 temp);
1156                 }
1157         }
1158
1159         if (need_update(sampass, PDB_HOURS)) {
1160                 const uint8 *hours = pdb_get_hours(sampass);
1161                 if (hours) {
1162                         pdb_sethexhours(temp, hours);
1163                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1164                                 existing,
1165                                 mods,
1166                                 get_userattr_key2string(ldap_state->schema_ver,
1167                                                 LDAP_ATTR_LOGON_HOURS),
1168                                 temp);
1169                 }
1170         }
1171
1172         if (need_update(sampass, PDB_ACCTCTRL))
1173                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1174                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1175                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1176
1177         /* password lockout cache: 
1178            - If we are now autolocking or clearing, we write to ldap
1179            - If we are clearing, we delete the cache entry
1180            - If the count is > 0, we update the cache
1181
1182            This even means when autolocking, we cache, just in case the
1183            update doesn't work, and we have to cache the autolock flag */
1184
1185         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1186             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1187                 uint16 badcount = pdb_get_bad_password_count(sampass);
1188                 time_t badtime = pdb_get_bad_password_time(sampass);
1189                 uint32 pol;
1190                 pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1191
1192                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1193                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1194
1195                 if ((badcount >= pol) || (badcount == 0)) {
1196                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1197                                 (unsigned int)badcount, (unsigned int)badtime));
1198                         slprintf (temp, sizeof (temp) - 1, "%li", (long)badcount);
1199                         smbldap_make_mod(
1200                                 ldap_state->smbldap_state->ldap_struct,
1201                                 existing, mods, 
1202                                 get_userattr_key2string(
1203                                         ldap_state->schema_ver, 
1204                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1205                                 temp);
1206
1207                         slprintf (temp, sizeof (temp) - 1, "%li", badtime);
1208                         smbldap_make_mod(
1209                                 ldap_state->smbldap_state->ldap_struct, 
1210                                 existing, mods,
1211                                 get_userattr_key2string(
1212                                         ldap_state->schema_ver, 
1213                                         LDAP_ATTR_BAD_PASSWORD_TIME), 
1214                                 temp);
1215                 }
1216                 if (badcount == 0) {
1217                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1218                         login_cache_delentry(sampass);
1219                 } else {
1220                         LOGIN_CACHE cache_entry;
1221
1222                         cache_entry.entry_timestamp = time(NULL);
1223                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1224                         cache_entry.bad_password_count = badcount;
1225                         cache_entry.bad_password_time = badtime;
1226
1227                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1228                         login_cache_write(sampass, cache_entry);
1229                 }
1230         }
1231
1232         return True;
1233 }
1234
1235 /**********************************************************************
1236  Connect to LDAP server for password enumeration.
1237 *********************************************************************/
1238
1239 static NTSTATUS ldapsam_setsampwent(struct pdb_methods *my_methods, BOOL update, uint16 acb_mask)
1240 {
1241         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1242         int rc;
1243         pstring filter, suffix;
1244         const char **attr_list;
1245         BOOL machine_mask = False, user_mask = False;
1246
1247         pstr_sprintf( filter, "(&%s%s)", "(uid=%u)", 
1248                 get_objclass_filter(ldap_state->schema_ver));
1249         all_string_sub(filter, "%u", "*", sizeof(pstring));
1250
1251         machine_mask    = ((acb_mask != 0) && (acb_mask & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)));
1252         user_mask       = ((acb_mask != 0) && (acb_mask & ACB_NORMAL));
1253
1254         if (machine_mask) {
1255                 pstrcpy(suffix, lp_ldap_machine_suffix());
1256         } else if (user_mask) {
1257                 pstrcpy(suffix, lp_ldap_user_suffix());
1258         } else {
1259                 pstrcpy(suffix, lp_ldap_suffix());
1260         }
1261
1262         DEBUG(10,("ldapsam_setsampwent: LDAP Query for acb_mask 0x%x will use suffix %s\n", 
1263                 acb_mask, suffix));
1264
1265         attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1266         rc = smbldap_search(ldap_state->smbldap_state, suffix, LDAP_SCOPE_SUBTREE, filter, 
1267                             attr_list, 0, &ldap_state->result);
1268         TALLOC_FREE( attr_list );
1269
1270         if (rc != LDAP_SUCCESS) {
1271                 DEBUG(0, ("ldapsam_setsampwent: LDAP search failed: %s\n", ldap_err2string(rc)));
1272                 DEBUG(3, ("ldapsam_setsampwent: Query was: %s, %s\n", suffix, filter));
1273                 ldap_msgfree(ldap_state->result);
1274                 ldap_state->result = NULL;
1275                 return NT_STATUS_UNSUCCESSFUL;
1276         }
1277
1278         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base %s\n",
1279                 ldap_count_entries(ldap_state->smbldap_state->ldap_struct, 
1280                 ldap_state->result), suffix));
1281
1282         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
1283                                  ldap_state->result);
1284         ldap_state->index = 0;
1285
1286         return NT_STATUS_OK;
1287 }
1288
1289 /**********************************************************************
1290  End enumeration of the LDAP password list.
1291 *********************************************************************/
1292
1293 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1294 {
1295         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1296         if (ldap_state->result) {
1297                 ldap_msgfree(ldap_state->result);
1298                 ldap_state->result = NULL;
1299         }
1300 }
1301
1302 /**********************************************************************
1303 Get the next entry in the LDAP password database.
1304 *********************************************************************/
1305
1306 static NTSTATUS ldapsam_getsampwent(struct pdb_methods *my_methods,
1307                                     struct samu *user)
1308 {
1309         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1310         struct ldapsam_privates *ldap_state =
1311                 (struct ldapsam_privates *)my_methods->private_data;
1312         BOOL bret = False;
1313
1314         while (!bret) {
1315                 if (!ldap_state->entry)
1316                         return ret;
1317                 
1318                 ldap_state->index++;
1319                 bret = init_sam_from_ldap(ldap_state, user, ldap_state->entry);
1320                 
1321                 ldap_state->entry = ldap_next_entry(priv2ld(ldap_state),
1322                                                     ldap_state->entry); 
1323         }
1324
1325         return NT_STATUS_OK;
1326 }
1327
1328 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1329                         const char *new_attr)
1330 {
1331         int i;
1332
1333         if (new_attr == NULL) {
1334                 return;
1335         }
1336
1337         for (i=0; (*attr_list)[i] != NULL; i++) {
1338                 ;
1339         }
1340
1341         (*attr_list) = TALLOC_REALLOC_ARRAY(mem_ctx, (*attr_list),
1342                                             const char *,  i+2);
1343         SMB_ASSERT((*attr_list) != NULL);
1344         (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1345         (*attr_list)[i+1] = NULL;
1346 }
1347
1348 /**********************************************************************
1349 Get struct samu entry from LDAP by username.
1350 *********************************************************************/
1351
1352 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1353 {
1354         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1355         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1356         LDAPMessage *result = NULL;
1357         LDAPMessage *entry = NULL;
1358         int count;
1359         const char ** attr_list;
1360         int rc;
1361         
1362         attr_list = get_userattr_list( user, ldap_state->schema_ver );
1363         append_attr(user, &attr_list,
1364                     get_userattr_key2string(ldap_state->schema_ver,
1365                                             LDAP_ATTR_MOD_TIMESTAMP));
1366         append_attr(user, &attr_list, "uidNumber");
1367         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1368                                            attr_list);
1369         TALLOC_FREE( attr_list );
1370
1371         if ( rc != LDAP_SUCCESS ) 
1372                 return NT_STATUS_NO_SUCH_USER;
1373         
1374         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1375         
1376         if (count < 1) {
1377                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1378                 ldap_msgfree(result);
1379                 return NT_STATUS_NO_SUCH_USER;
1380         } else if (count > 1) {
1381                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1382                 ldap_msgfree(result);
1383                 return NT_STATUS_NO_SUCH_USER;
1384         }
1385
1386         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1387         if (entry) {
1388                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1389                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1390                         ldap_msgfree(result);
1391                         return NT_STATUS_NO_SUCH_USER;
1392                 }
1393                 pdb_set_backend_private_data(user, result, NULL,
1394                                              my_methods, PDB_CHANGED);
1395                 talloc_autofree_ldapmsg(user, result);
1396                 ret = NT_STATUS_OK;
1397         } else {
1398                 ldap_msgfree(result);
1399         }
1400         return ret;
1401 }
1402
1403 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1404                                    const DOM_SID *sid, LDAPMessage **result) 
1405 {
1406         int rc = -1;
1407         const char ** attr_list;
1408         uint32 rid;
1409
1410         switch ( ldap_state->schema_ver ) {
1411                 case SCHEMAVER_SAMBASAMACCOUNT: {
1412                         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1413                         if (tmp_ctx == NULL) {
1414                                 return LDAP_NO_MEMORY;
1415                         }
1416
1417                         attr_list = get_userattr_list(tmp_ctx,
1418                                                       ldap_state->schema_ver);
1419                         append_attr(tmp_ctx, &attr_list,
1420                                     get_userattr_key2string(
1421                                             ldap_state->schema_ver,
1422                                             LDAP_ATTR_MOD_TIMESTAMP));
1423                         append_attr(tmp_ctx, &attr_list, "uidNumber");
1424                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1425                                                           result, attr_list);
1426                         TALLOC_FREE(tmp_ctx);
1427
1428                         if ( rc != LDAP_SUCCESS ) 
1429                                 return rc;
1430                         break;
1431                 }
1432                         
1433                 case SCHEMAVER_SAMBAACCOUNT:
1434                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1435                                 return rc;
1436                         }
1437                 
1438                         attr_list = get_userattr_list(NULL,
1439                                                       ldap_state->schema_ver);
1440                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1441                         TALLOC_FREE( attr_list );
1442
1443                         if ( rc != LDAP_SUCCESS ) 
1444                                 return rc;
1445                         break;
1446         }
1447         return rc;
1448 }
1449
1450 /**********************************************************************
1451  Get struct samu entry from LDAP by SID.
1452 *********************************************************************/
1453
1454 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1455 {
1456         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1457         LDAPMessage *result = NULL;
1458         LDAPMessage *entry = NULL;
1459         int count;
1460         int rc;
1461         fstring sid_string;
1462
1463         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1464                                           sid, &result); 
1465         if (rc != LDAP_SUCCESS)
1466                 return NT_STATUS_NO_SUCH_USER;
1467
1468         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1469         
1470         if (count < 1) {
1471                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] count=%d\n", sid_to_string(sid_string, sid),
1472                        count));
1473                 ldap_msgfree(result);
1474                 return NT_STATUS_NO_SUCH_USER;
1475         }  else if (count > 1) {
1476                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID [%s]. Failing. count=%d\n", sid_to_string(sid_string, sid),
1477                        count));
1478                 ldap_msgfree(result);
1479                 return NT_STATUS_NO_SUCH_USER;
1480         }
1481
1482         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1483         if (!entry) {
1484                 ldap_msgfree(result);
1485                 return NT_STATUS_NO_SUCH_USER;
1486         }
1487
1488         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1489                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1490                 ldap_msgfree(result);
1491                 return NT_STATUS_NO_SUCH_USER;
1492         }
1493
1494         pdb_set_backend_private_data(user, result, NULL,
1495                                      my_methods, PDB_CHANGED);
1496         talloc_autofree_ldapmsg(user, result);
1497         return NT_STATUS_OK;
1498 }       
1499
1500 static BOOL ldapsam_can_pwchange_exop(struct smbldap_state *ldap_state)
1501 {
1502         return smbldap_has_extension(ldap_state, LDAP_EXOP_MODIFY_PASSWD);
1503 }
1504
1505 /********************************************************************
1506  Do the actual modification - also change a plaintext passord if 
1507  it it set.
1508 **********************************************************************/
1509
1510 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1511                                      struct samu *newpwd, char *dn,
1512                                      LDAPMod **mods, int ldap_op, 
1513                                      BOOL (*need_update)(const struct samu *, enum pdb_elements))
1514 {
1515         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1516         int rc;
1517         
1518         if (!my_methods || !newpwd || !dn) {
1519                 return NT_STATUS_INVALID_PARAMETER;
1520         }
1521         
1522         if (!mods) {
1523                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1524                 /* may be password change below however */
1525         } else {
1526                 switch(ldap_op) {
1527                         case LDAP_MOD_ADD: 
1528                                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1529                                                 "objectclass", 
1530                                                 LDAP_OBJ_ACCOUNT);
1531                                 rc = smbldap_add(ldap_state->smbldap_state, 
1532                                                  dn, mods);
1533                                 break;
1534                         case LDAP_MOD_REPLACE: 
1535                                 rc = smbldap_modify(ldap_state->smbldap_state, 
1536                                                     dn ,mods);
1537                                 break;
1538                         default:        
1539                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n", 
1540                                          ldap_op));
1541                                 return NT_STATUS_INVALID_PARAMETER;
1542                 }
1543                 
1544                 if (rc!=LDAP_SUCCESS) {
1545                         return NT_STATUS_UNSUCCESSFUL;
1546                 }  
1547         }
1548         
1549         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1550                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1551                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1552                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1553                 BerElement *ber;
1554                 struct berval *bv;
1555                 char *retoid = NULL;
1556                 struct berval *retdata = NULL;
1557                 char *utf8_password;
1558                 char *utf8_dn;
1559
1560                 if (!ldap_state->is_nds_ldap) {
1561                         if (!ldapsam_can_pwchange_exop(ldap_state->smbldap_state)) {
1562                                 DEBUG(2, ("ldap password change requested, but LDAP "
1563                                           "server does not support it -- ignoring\n"));
1564                                 return NT_STATUS_OK;
1565                         }
1566                 }
1567
1568                 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1569                         return NT_STATUS_NO_MEMORY;
1570                 }
1571
1572                 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1573                         return NT_STATUS_NO_MEMORY;
1574                 }
1575
1576                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1577                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1578                         SAFE_FREE(utf8_password);
1579                         return NT_STATUS_UNSUCCESSFUL;
1580                 }
1581
1582                 ber_printf (ber, "{");
1583                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn);
1584                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password);
1585                 ber_printf (ber, "N}");
1586
1587                 if ((rc = ber_flatten (ber, &bv))<0) {
1588                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1589                         ber_free(ber,1);
1590                         SAFE_FREE(utf8_dn);
1591                         SAFE_FREE(utf8_password);
1592                         return NT_STATUS_UNSUCCESSFUL;
1593                 }
1594                 
1595                 SAFE_FREE(utf8_dn);
1596                 SAFE_FREE(utf8_password);
1597                 ber_free(ber, 1);
1598
1599                 if (!ldap_state->is_nds_ldap) {
1600                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1601                                                         LDAP_EXOP_MODIFY_PASSWD,
1602                                                         bv, NULL, NULL, &retoid, 
1603                                                         &retdata);
1604                 } else {
1605                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1606                                                         pdb_get_plaintext_passwd(newpwd));
1607                 }
1608                 if (rc != LDAP_SUCCESS) {
1609                         char *ld_error = NULL;
1610
1611                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1612                                 DEBUG(3, ("Could not set userPassword "
1613                                           "attribute due to an objectClass "
1614                                           "violation -- ignoring\n"));
1615                                 ber_bvfree(bv);
1616                                 return NT_STATUS_OK;
1617                         }
1618
1619                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1620                                         &ld_error);
1621                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1622                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1623                         SAFE_FREE(ld_error);
1624                         ber_bvfree(bv);
1625                         return NT_STATUS_UNSUCCESSFUL;
1626                 } else {
1627                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1628 #ifdef DEBUG_PASSWORD
1629                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1630 #endif    
1631                         if (retdata)
1632                                 ber_bvfree(retdata);
1633                         if (retoid)
1634                                 ldap_memfree(retoid);
1635                 }
1636                 ber_bvfree(bv);
1637         }
1638         return NT_STATUS_OK;
1639 }
1640
1641 /**********************************************************************
1642  Delete entry from LDAP for username.
1643 *********************************************************************/
1644
1645 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1646                                            struct samu * sam_acct)
1647 {
1648         struct ldapsam_privates *priv =
1649                 (struct ldapsam_privates *)my_methods->private_data;
1650         const char *sname;
1651         int rc;
1652         LDAPMessage *msg, *entry;
1653         NTSTATUS result = NT_STATUS_NO_MEMORY;
1654         const char **attr_list;
1655         TALLOC_CTX *mem_ctx;
1656
1657         if (!sam_acct) {
1658                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1659                 return NT_STATUS_INVALID_PARAMETER;
1660         }
1661
1662         sname = pdb_get_username(sam_acct);
1663
1664         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1665                   "LDAP.\n", sname));
1666
1667         mem_ctx = talloc_new(NULL);
1668         if (mem_ctx == NULL) {
1669                 DEBUG(0, ("talloc_new failed\n"));
1670                 goto done;
1671         }
1672
1673         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1674         if (attr_list == NULL) {
1675                 goto done;
1676         }
1677
1678         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1679
1680         if ((rc != LDAP_SUCCESS) ||
1681             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1682             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1683                 DEBUG(5, ("Could not find user %s\n", sname));
1684                 result = NT_STATUS_NO_SUCH_USER;
1685                 goto done;
1686         }
1687         
1688         rc = ldapsam_delete_entry(
1689                 priv, mem_ctx, entry,
1690                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1691                 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1692                 attr_list);
1693
1694         result = (rc == LDAP_SUCCESS) ?
1695                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1696
1697  done:
1698         TALLOC_FREE(mem_ctx);
1699         return result;
1700 }
1701
1702 /**********************************************************************
1703  Helper function to determine for update_sam_account whether
1704  we need LDAP modification.
1705 *********************************************************************/
1706
1707 static BOOL element_is_changed(const struct samu *sampass,
1708                                enum pdb_elements element)
1709 {
1710         return IS_SAM_CHANGED(sampass, element);
1711 }
1712
1713 /**********************************************************************
1714  Update struct samu.
1715 *********************************************************************/
1716
1717 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1718 {
1719         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1720         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1721         int rc = 0;
1722         char *dn;
1723         LDAPMessage *result = NULL;
1724         LDAPMessage *entry = NULL;
1725         LDAPMod **mods = NULL;
1726         const char **attr_list;
1727
1728         result = pdb_get_backend_private_data(newpwd, my_methods);
1729         if (!result) {
1730                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1731                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1732                 TALLOC_FREE( attr_list );
1733                 if (rc != LDAP_SUCCESS) {
1734                         return NT_STATUS_UNSUCCESSFUL;
1735                 }
1736                 pdb_set_backend_private_data(newpwd, result, NULL,
1737                                              my_methods, PDB_CHANGED);
1738                 talloc_autofree_ldapmsg(newpwd, result);
1739         }
1740
1741         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1742                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1743                 return NT_STATUS_UNSUCCESSFUL;
1744         }
1745
1746         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1747         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1748         if (!dn) {
1749                 return NT_STATUS_UNSUCCESSFUL;
1750         }
1751
1752         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1753
1754         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1755                                 element_is_changed)) {
1756                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1757                 SAFE_FREE(dn);
1758                 if (mods != NULL)
1759                         ldap_mods_free(mods,True);
1760                 return NT_STATUS_UNSUCCESSFUL;
1761         }
1762         
1763         if (mods == NULL) {
1764                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1765                          pdb_get_username(newpwd)));
1766                 SAFE_FREE(dn);
1767                 return NT_STATUS_OK;
1768         }
1769         
1770         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1771         ldap_mods_free(mods,True);
1772         SAFE_FREE(dn);
1773
1774         if (!NT_STATUS_IS_OK(ret)) {
1775                 return ret;
1776         }
1777
1778         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1779                   pdb_get_username(newpwd)));
1780         return NT_STATUS_OK;
1781 }
1782
1783 /***************************************************************************
1784  Renames a struct samu
1785  - The "rename user script" has full responsibility for changing everything
1786 ***************************************************************************/
1787
1788 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1789                                            struct samu *old_acct, 
1790                                            const char *newname)
1791 {
1792         const char *oldname;
1793         int rc;
1794         pstring rename_script;
1795
1796         if (!old_acct) {
1797                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1798                 return NT_STATUS_INVALID_PARAMETER;
1799         }
1800         if (!newname) {
1801                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1802                 return NT_STATUS_INVALID_PARAMETER;
1803         }
1804                 
1805         oldname = pdb_get_username(old_acct);
1806
1807         /* rename the posix user */
1808         pstrcpy(rename_script, lp_renameuser_script());
1809
1810         if (!(*rename_script))
1811                 return NT_STATUS_ACCESS_DENIED;
1812
1813         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n", 
1814                    oldname, newname));
1815
1816         /* we have to allow the account name to end with a '$' */
1817         string_sub2(rename_script, "%unew", newname, sizeof(pstring), 
1818                     True, False, True);
1819         string_sub2(rename_script, "%uold", oldname, sizeof(pstring), 
1820                     True, False, True);
1821         rc = smbrun(rename_script, NULL);
1822
1823         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n", 
1824                           rename_script, rc));
1825
1826         if (rc)
1827                 return NT_STATUS_UNSUCCESSFUL;
1828
1829         return NT_STATUS_OK;
1830 }
1831
1832 /**********************************************************************
1833  Helper function to determine for update_sam_account whether
1834  we need LDAP modification.
1835  *********************************************************************/
1836
1837 static BOOL element_is_set_or_changed(const struct samu *sampass,
1838                                       enum pdb_elements element)
1839 {
1840         return (IS_SAM_SET(sampass, element) ||
1841                 IS_SAM_CHANGED(sampass, element));
1842 }
1843
1844 /**********************************************************************
1845  Add struct samu to LDAP.
1846 *********************************************************************/
1847
1848 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1849 {
1850         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1851         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1852         int rc;
1853         LDAPMessage     *result = NULL;
1854         LDAPMessage     *entry  = NULL;
1855         pstring         dn;
1856         LDAPMod         **mods = NULL;
1857         int             ldap_op = LDAP_MOD_REPLACE;
1858         uint32          num_result;
1859         const char      **attr_list;
1860         char            *escape_user;
1861         const char      *username = pdb_get_username(newpwd);
1862         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
1863         pstring         filter;
1864         fstring         sid_string;
1865
1866         if (!username || !*username) {
1867                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
1868                 return NT_STATUS_INVALID_PARAMETER;
1869         }
1870
1871         /* free this list after the second search or in case we exit on failure */
1872         attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1873
1874         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
1875
1876         if (rc != LDAP_SUCCESS) {
1877                 TALLOC_FREE( attr_list );
1878                 return NT_STATUS_UNSUCCESSFUL;
1879         }
1880
1881         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1882                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
1883                          username));
1884                 ldap_msgfree(result);
1885                 TALLOC_FREE( attr_list );
1886                 return NT_STATUS_UNSUCCESSFUL;
1887         }
1888         ldap_msgfree(result);
1889         result = NULL;
1890
1891         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
1892                 rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1893                                                   sid, &result); 
1894                 if (rc == LDAP_SUCCESS) {
1895                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1896                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' already in the base, with samba attributes\n", 
1897                                          sid_to_string(sid_string, sid)));
1898                                 TALLOC_FREE( attr_list );
1899                                 ldap_msgfree(result);
1900                                 return NT_STATUS_UNSUCCESSFUL;
1901                         }
1902                         ldap_msgfree(result);
1903                 }
1904         }
1905
1906         /* does the entry already exist but without a samba attributes?
1907            we need to return the samba attributes here */
1908            
1909         escape_user = escape_ldap_string_alloc( username );
1910         pstrcpy( filter, "(uid=%u)" );
1911         all_string_sub( filter, "%u", escape_user, sizeof(filter) );
1912         SAFE_FREE( escape_user );
1913
1914         rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1915                                    filter, attr_list, &result);
1916         if ( rc != LDAP_SUCCESS ) {
1917                 TALLOC_FREE( attr_list );
1918                 return NT_STATUS_UNSUCCESSFUL;
1919         }
1920
1921         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1922         
1923         if (num_result > 1) {
1924                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1925                 TALLOC_FREE( attr_list );
1926                 ldap_msgfree(result);
1927                 return NT_STATUS_UNSUCCESSFUL;
1928         }
1929         
1930         /* Check if we need to update an existing entry */
1931         if (num_result == 1) {
1932                 char *tmp;
1933                 
1934                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1935                 ldap_op = LDAP_MOD_REPLACE;
1936                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1937                 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1938                 if (!tmp) {
1939                         TALLOC_FREE( attr_list );
1940                         ldap_msgfree(result);
1941                         return NT_STATUS_UNSUCCESSFUL;
1942                 }
1943                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1944                 SAFE_FREE(tmp);
1945
1946         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
1947
1948                 /* There might be a SID for this account already - say an idmap entry */
1949
1950                 pstr_sprintf(filter, "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))", 
1951                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1952                          sid_to_string(sid_string, sid),
1953                          LDAP_OBJ_IDMAP_ENTRY,
1954                          LDAP_OBJ_SID_ENTRY);
1955                 
1956                 /* free old result before doing a new search */
1957                 if (result != NULL) {
1958                         ldap_msgfree(result);
1959                         result = NULL;
1960                 }
1961                 rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1962                                            filter, attr_list, &result);
1963                         
1964                 if ( rc != LDAP_SUCCESS ) {
1965                         TALLOC_FREE( attr_list );
1966                         return NT_STATUS_UNSUCCESSFUL;
1967                 }
1968                 
1969                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1970                 
1971                 if (num_result > 1) {
1972                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1973                         TALLOC_FREE( attr_list );
1974                         ldap_msgfree(result);
1975                         return NT_STATUS_UNSUCCESSFUL;
1976                 }
1977                 
1978                 /* Check if we need to update an existing entry */
1979                 if (num_result == 1) {
1980                         char *tmp;
1981                         
1982                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1983                         ldap_op = LDAP_MOD_REPLACE;
1984                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1985                         tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1986                         if (!tmp) {
1987                                 TALLOC_FREE( attr_list );
1988                                 ldap_msgfree(result);
1989                                 return NT_STATUS_UNSUCCESSFUL;
1990                         }
1991                         slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1992                         SAFE_FREE(tmp);
1993                 }
1994         }
1995         
1996         TALLOC_FREE( attr_list );
1997
1998         if (num_result == 0) {
1999                 /* Check if we need to add an entry */
2000                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2001                 ldap_op = LDAP_MOD_ADD;
2002                 if (username[strlen(username)-1] == '$') {
2003                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_machine_suffix ());
2004                 } else {
2005                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_user_suffix ());
2006                 }
2007         }
2008
2009         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2010                                 element_is_set_or_changed)) {
2011                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2012                 ldap_msgfree(result);
2013                 if (mods != NULL)
2014                         ldap_mods_free(mods,True);
2015                 return NT_STATUS_UNSUCCESSFUL;          
2016         }
2017         
2018         ldap_msgfree(result);
2019
2020         if (mods == NULL) {
2021                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2022                 return NT_STATUS_UNSUCCESSFUL;
2023         }
2024         switch ( ldap_state->schema_ver ) {
2025                 case SCHEMAVER_SAMBAACCOUNT:
2026                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2027                         break;
2028                 case SCHEMAVER_SAMBASAMACCOUNT:
2029                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2030                         break;
2031                 default:
2032                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2033                         break;
2034         }
2035
2036         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2037         if (!NT_STATUS_IS_OK(ret)) {
2038                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2039                          pdb_get_username(newpwd),dn));
2040                 ldap_mods_free(mods, True);
2041                 return ret;
2042         }
2043
2044         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2045         ldap_mods_free(mods, True);
2046         
2047         return NT_STATUS_OK;
2048 }
2049
2050 /**********************************************************************
2051  *********************************************************************/
2052
2053 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2054                                      const char *filter,
2055                                      LDAPMessage ** result)
2056 {
2057         int scope = LDAP_SCOPE_SUBTREE;
2058         int rc;
2059         const char **attr_list;
2060
2061         attr_list = get_attr_list(NULL, groupmap_attr_list);
2062         rc = smbldap_search(ldap_state->smbldap_state, 
2063                             lp_ldap_group_suffix (), scope,
2064                             filter, attr_list, 0, result);
2065         TALLOC_FREE(attr_list);
2066
2067         return rc;
2068 }
2069
2070 /**********************************************************************
2071  *********************************************************************/
2072
2073 static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
2074                                  GROUP_MAP *map, LDAPMessage *entry)
2075 {
2076         pstring temp;
2077
2078         if (ldap_state == NULL || map == NULL || entry == NULL ||
2079                         ldap_state->smbldap_state->ldap_struct == NULL) {
2080                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2081                 return False;
2082         }
2083
2084         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2085                         get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER), temp)) {
2086                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2087                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2088                 return False;
2089         }
2090         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2091
2092         map->gid = (gid_t)atol(temp);
2093
2094         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2095                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID), temp)) {
2096                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2097                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2098                 return False;
2099         }
2100         
2101         if (!string_to_sid(&map->sid, temp)) {
2102                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2103                 return False;
2104         }
2105
2106         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2107                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), temp)) {
2108                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2109                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2110                 return False;
2111         }
2112         map->sid_name_use = (enum SID_NAME_USE)atol(temp);
2113
2114         if ((map->sid_name_use < SID_NAME_USER) ||
2115                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2116                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2117                 return False;
2118         }
2119
2120         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2121                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), temp)) {
2122                 temp[0] = '\0';
2123                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2124                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_CN), temp)) 
2125                 {
2126                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2127 for gidNumber(%lu)\n",(unsigned long)map->gid));
2128                         return False;
2129                 }
2130         }
2131         fstrcpy(map->nt_name, temp);
2132
2133         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2134                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), temp)) {
2135                 temp[0] = '\0';
2136         }
2137         fstrcpy(map->comment, temp);
2138
2139         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
2140                 store_gid_sid_cache(&map->sid, map->gid);
2141         }
2142
2143         return True;
2144 }
2145
2146 /**********************************************************************
2147  *********************************************************************/
2148
2149 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2150                                  const char *filter,
2151                                  GROUP_MAP *map)
2152 {
2153         struct ldapsam_privates *ldap_state =
2154                 (struct ldapsam_privates *)methods->private_data;
2155         LDAPMessage *result = NULL;
2156         LDAPMessage *entry = NULL;
2157         int count;
2158
2159         if (ldapsam_search_one_group(ldap_state, filter, &result)
2160             != LDAP_SUCCESS) {
2161                 return NT_STATUS_NO_SUCH_GROUP;
2162         }
2163
2164         count = ldap_count_entries(priv2ld(ldap_state), result);
2165
2166         if (count < 1) {
2167                 DEBUG(4, ("ldapsam_getgroup: Did not find group\n"));
2168                 ldap_msgfree(result);
2169                 return NT_STATUS_NO_SUCH_GROUP;
2170         }
2171
2172         if (count > 1) {
2173                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2174                           "count=%d\n", filter, count));
2175                 ldap_msgfree(result);
2176                 return NT_STATUS_NO_SUCH_GROUP;
2177         }
2178
2179         entry = ldap_first_entry(priv2ld(ldap_state), result);
2180
2181         if (!entry) {
2182                 ldap_msgfree(result);
2183                 return NT_STATUS_UNSUCCESSFUL;
2184         }
2185
2186         if (!init_group_from_ldap(ldap_state, map, entry)) {
2187                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2188                           "group filter %s\n", filter));
2189                 ldap_msgfree(result);
2190                 return NT_STATUS_NO_SUCH_GROUP;
2191         }
2192
2193         ldap_msgfree(result);
2194         return NT_STATUS_OK;
2195 }
2196
2197 /**********************************************************************
2198  *********************************************************************/
2199
2200 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2201                                  DOM_SID sid)
2202 {
2203         pstring filter;
2204
2205         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
2206                 LDAP_OBJ_GROUPMAP, 
2207                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2208                 sid_string_static(&sid));
2209
2210         return ldapsam_getgroup(methods, filter, map);
2211 }
2212
2213 /**********************************************************************
2214  *********************************************************************/
2215
2216 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2217                                  gid_t gid)
2218 {
2219         pstring filter;
2220
2221         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))",
2222                 LDAP_OBJ_GROUPMAP,
2223                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2224                 (unsigned long)gid);
2225
2226         return ldapsam_getgroup(methods, filter, map);
2227 }
2228
2229 /**********************************************************************
2230  *********************************************************************/
2231
2232 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2233                                  const char *name)
2234 {
2235         pstring filter;
2236         char *escape_name = escape_ldap_string_alloc(name);
2237
2238         if (!escape_name) {
2239                 return NT_STATUS_NO_MEMORY;
2240         }
2241
2242         pstr_sprintf(filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2243                 LDAP_OBJ_GROUPMAP,
2244                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2245                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN), escape_name);
2246
2247         SAFE_FREE(escape_name);
2248
2249         return ldapsam_getgroup(methods, filter, map);
2250 }
2251
2252 static void add_rid_to_array_unique(TALLOC_CTX *mem_ctx,
2253                                     uint32 rid, uint32 **pp_rids, size_t *p_num)
2254 {
2255         size_t i;
2256
2257         for (i=0; i<*p_num; i++) {
2258                 if ((*pp_rids)[i] == rid)
2259                         return;
2260         }
2261         
2262         *pp_rids = TALLOC_REALLOC_ARRAY(mem_ctx, *pp_rids, uint32, *p_num+1);
2263
2264         if (*pp_rids == NULL)
2265                 return;
2266
2267         (*pp_rids)[*p_num] = rid;
2268         *p_num += 1;
2269 }
2270
2271 static BOOL ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2272                                            LDAPMessage *entry,
2273                                            const DOM_SID *domain_sid,
2274                                            uint32 *rid)
2275 {
2276         fstring str;
2277         DOM_SID sid;
2278
2279         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2280                                           str, sizeof(str)-1)) {
2281                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2282                 return False;
2283         }
2284
2285         if (!string_to_sid(&sid, str)) {
2286                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2287                 return False;
2288         }
2289
2290         if (sid_compare_domain(&sid, domain_sid) != 0) {
2291                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2292                            str, sid_string_static(domain_sid)));
2293                 return False;
2294         }
2295
2296         if (!sid_peek_rid(&sid, rid)) {
2297                 DEBUG(10, ("Could not peek into RID\n"));
2298                 return False;
2299         }
2300
2301         return True;
2302 }
2303
2304 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2305                                            TALLOC_CTX *mem_ctx,
2306                                            const DOM_SID *group,
2307                                            uint32 **pp_member_rids,
2308                                            size_t *p_num_members)
2309 {
2310         struct ldapsam_privates *ldap_state =
2311                 (struct ldapsam_privates *)methods->private_data;
2312         struct smbldap_state *conn = ldap_state->smbldap_state;
2313         pstring filter;
2314         int rc, count;
2315         LDAPMessage *msg = NULL;
2316         LDAPMessage *entry;
2317         char **values = NULL;
2318         char **memberuid;
2319         char *sid_filter = NULL;
2320         char *tmp;
2321         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2322
2323         *pp_member_rids = NULL;
2324         *p_num_members = 0;
2325
2326         pstr_sprintf(filter,
2327                      "(&(objectClass=sambaSamAccount)"
2328                      "(sambaPrimaryGroupSid=%s))",
2329                      sid_string_static(group));
2330
2331         {
2332                 const char *attrs[] = { "sambaSID", NULL };
2333                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2334                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2335                                     &msg);
2336         }
2337
2338         if (rc != LDAP_SUCCESS)
2339                 goto done;
2340
2341         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2342              entry != NULL;
2343              entry = ldap_next_entry(conn->ldap_struct, entry))
2344         {
2345                 uint32 rid;
2346
2347                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2348                                                     entry,
2349                                                     get_global_sam_sid(),
2350                                                     &rid)) {
2351                         DEBUG(2, ("Could not find sid from ldap entry\n"));
2352                         continue;
2353                 }
2354
2355                 add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2356                                         p_num_members);
2357         }
2358
2359         if (msg != NULL)
2360                 ldap_msgfree(msg);
2361
2362         pstr_sprintf(filter,
2363                      "(&(objectClass=sambaGroupMapping)"
2364                      "(objectClass=posixGroup)"
2365                      "(sambaSID=%s))",
2366                      sid_string_static(group));
2367
2368         {
2369                 const char *attrs[] = { "memberUid", NULL };
2370                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2371                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2372                                     &msg);
2373         }
2374
2375         if (rc != LDAP_SUCCESS)
2376                 goto done;
2377
2378         count = ldap_count_entries(conn->ldap_struct, msg);
2379
2380         if (count > 1) {
2381                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2382                           sid_string_static(group)));
2383                 goto done;
2384         }
2385
2386         if (count == 0) {
2387                 result = NT_STATUS_OK;
2388                 goto done;
2389         }
2390
2391         entry = ldap_first_entry(conn->ldap_struct, msg);
2392         if (entry == NULL)
2393                 goto done;
2394
2395         values = ldap_get_values(conn->ldap_struct, msg, "memberUid");
2396         if (values == NULL) {
2397                 result = NT_STATUS_OK;
2398                 goto done;
2399         }
2400
2401         sid_filter = SMB_STRDUP("(&(objectClass=sambaSamAccount)(|");
2402         if (sid_filter == NULL) {
2403                 result = NT_STATUS_NO_MEMORY;
2404                 goto done;
2405         }
2406
2407         for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2408                 tmp = sid_filter;
2409                 asprintf(&sid_filter, "%s(uid=%s)", tmp, *memberuid);
2410                 free(tmp);
2411                 if (sid_filter == NULL) {
2412                         result = NT_STATUS_NO_MEMORY;
2413                         goto done;
2414                 }
2415         }
2416
2417         tmp = sid_filter;
2418         asprintf(&sid_filter, "%s))", sid_filter);
2419         free(tmp);
2420         if (sid_filter == NULL) {
2421                 result = NT_STATUS_NO_MEMORY;
2422                 goto done;
2423         }
2424
2425         {
2426                 const char *attrs[] = { "sambaSID", NULL };
2427                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2428                                     LDAP_SCOPE_SUBTREE, sid_filter, attrs, 0,
2429                                     &msg);
2430         }
2431
2432         if (rc != LDAP_SUCCESS)
2433                 goto done;
2434
2435         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2436              entry != NULL;
2437              entry = ldap_next_entry(conn->ldap_struct, entry))
2438         {
2439                 fstring str;
2440                 DOM_SID sid;
2441                 uint32 rid;
2442
2443                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2444                                                   entry, "sambaSID",
2445                                                   str, sizeof(str)-1))
2446                         continue;
2447
2448                 if (!string_to_sid(&sid, str))
2449                         goto done;
2450
2451                 if (!sid_check_is_in_our_domain(&sid)) {
2452                         DEBUG(1, ("Inconsistent SAM -- group member uid not "
2453                                   "in our domain\n"));
2454                         continue;
2455                 }
2456
2457                 sid_peek_rid(&sid, &rid);
2458
2459                 add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2460                                         p_num_members);
2461         }
2462
2463         result = NT_STATUS_OK;
2464         
2465  done:
2466         SAFE_FREE(sid_filter);
2467
2468         if (values != NULL)
2469                 ldap_value_free(values);
2470
2471         if (msg != NULL)
2472                 ldap_msgfree(msg);
2473
2474         return result;
2475 }
2476
2477 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2478                                                TALLOC_CTX *mem_ctx,
2479                                                struct samu *user,
2480                                                DOM_SID **pp_sids,
2481                                                gid_t **pp_gids,
2482                                                size_t *p_num_groups)
2483 {
2484         struct ldapsam_privates *ldap_state =
2485                 (struct ldapsam_privates *)methods->private_data;
2486         struct smbldap_state *conn = ldap_state->smbldap_state;
2487         pstring filter;
2488         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2489         char *escape_name;
2490         int rc;
2491         LDAPMessage *msg = NULL;
2492         LDAPMessage *entry;
2493         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2494         size_t num_sids, num_gids;
2495         gid_t primary_gid;
2496
2497         *pp_sids = NULL;
2498         num_sids = 0;
2499
2500         if (!sid_to_gid(pdb_get_group_sid(user), &primary_gid)) {
2501                 DEBUG(1, ("sid_to_gid failed for user's primary group\n"));
2502                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
2503         }
2504
2505         escape_name = escape_ldap_string_alloc(pdb_get_username(user));
2506
2507         if (escape_name == NULL)
2508                 return NT_STATUS_NO_MEMORY;
2509
2510         pstr_sprintf(filter, "(&(objectClass=posixGroup)"
2511                      "(|(memberUid=%s)(gidNumber=%d)))",
2512                      escape_name, primary_gid);
2513
2514         rc = smbldap_search(conn, lp_ldap_group_suffix(),
2515                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &msg);
2516
2517         if (rc != LDAP_SUCCESS)
2518                 goto done;
2519
2520         num_gids = 0;
2521         *pp_gids = NULL;
2522
2523         num_sids = 0;
2524         *pp_sids = NULL;
2525
2526         /* We need to add the primary group as the first gid/sid */
2527
2528         add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids);
2529
2530         /* This sid will be replaced later */
2531
2532         add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids, &num_sids);
2533
2534         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2535              entry != NULL;
2536              entry = ldap_next_entry(conn->ldap_struct, entry))
2537         {
2538                 fstring str;
2539                 DOM_SID sid;
2540                 gid_t gid;
2541                 char *end;
2542
2543                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2544                                                   entry, "sambaSID",
2545                                                   str, sizeof(str)-1))
2546                         continue;
2547
2548                 if (!string_to_sid(&sid, str))
2549                         goto done;
2550
2551                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2552                                                   entry, "gidNumber",
2553                                                   str, sizeof(str)-1))
2554                         continue;
2555
2556                 gid = strtoul(str, &end, 10);
2557
2558                 if (PTR_DIFF(end, str) != strlen(str))
2559                         goto done;
2560
2561                 if (gid == primary_gid) {
2562                         sid_copy(&(*pp_sids)[0], &sid);
2563                 } else {
2564                         add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2565                                                 &num_gids);
2566                         add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2567                                                 &num_sids);
2568                 }
2569         }
2570
2571         if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2572                 DEBUG(3, ("primary group of [%s] not found\n",
2573                           pdb_get_username(user)));
2574                 goto done;
2575         }
2576
2577         *p_num_groups = num_sids;
2578
2579         result = NT_STATUS_OK;
2580
2581  done:
2582
2583         SAFE_FREE(escape_name);
2584         if (msg != NULL)
2585                 ldap_msgfree(msg);
2586
2587         return result;
2588 }
2589
2590 /**********************************************************************
2591  * Augment a posixGroup object with a sambaGroupMapping domgroup
2592  *********************************************************************/
2593
2594 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2595                                        struct ldapsam_privates *ldap_state,
2596                                        GROUP_MAP *map)
2597 {
2598         const char *filter, *dn;
2599         LDAPMessage *msg, *entry;
2600         LDAPMod **mods;
2601         int rc;
2602
2603         filter = talloc_asprintf(mem_ctx,
2604                                  "(&(objectClass=posixGroup)(gidNumber=%u))",
2605                                  map->gid);
2606         if (filter == NULL) {
2607                 return NT_STATUS_NO_MEMORY;
2608         }
2609
2610         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2611                                    get_attr_list(mem_ctx, groupmap_attr_list),
2612                                    &msg);
2613         talloc_autofree_ldapmsg(mem_ctx, msg);
2614
2615         if ((rc != LDAP_SUCCESS) ||
2616             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2617             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2618                 return NT_STATUS_NO_SUCH_GROUP;
2619         }
2620
2621         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2622         if (dn == NULL) {
2623                 return NT_STATUS_NO_MEMORY;
2624         }
2625
2626         mods = NULL;
2627         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
2628                         "sambaGroupMapping");
2629         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
2630                          sid_string_static(&map->sid));
2631         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
2632                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2633         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2634                          map->nt_name);
2635         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2636                          map->comment);
2637         talloc_autofree_ldapmod(mem_ctx, mods);
2638
2639         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2640         if (rc != LDAP_SUCCESS) {
2641                 return NT_STATUS_ACCESS_DENIED;
2642         }
2643
2644         return NT_STATUS_OK;
2645 }
2646
2647 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
2648                                                 GROUP_MAP *map)
2649 {
2650         struct ldapsam_privates *ldap_state =
2651                 (struct ldapsam_privates *)methods->private_data;
2652         LDAPMessage *msg = NULL;
2653         LDAPMod **mods = NULL;
2654         const char *attrs[] = { NULL };
2655         char *filter;
2656
2657         char *dn;
2658         TALLOC_CTX *mem_ctx;
2659         NTSTATUS result;
2660
2661         DOM_SID sid;
2662
2663         int rc;
2664
2665         mem_ctx = talloc_new(NULL);
2666         if (mem_ctx == NULL) {
2667                 DEBUG(0, ("talloc_new failed\n"));
2668                 return NT_STATUS_NO_MEMORY;
2669         }
2670
2671         filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
2672                                  sid_string_static(&map->sid));
2673         if (filter == NULL) {
2674                 result = NT_STATUS_NO_MEMORY;
2675                 goto done;
2676         }
2677
2678         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
2679                             LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
2680         talloc_autofree_ldapmsg(mem_ctx, msg);
2681
2682         if ((rc == LDAP_SUCCESS) &&
2683             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
2684
2685                 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
2686                           "group mapping entry\n",
2687                           sid_string_static(&map->sid)));
2688                 result = NT_STATUS_GROUP_EXISTS;
2689                 goto done;
2690         }
2691
2692         switch (map->sid_name_use) {
2693
2694         case SID_NAME_DOM_GRP:
2695                 /* To map a domain group we need to have a posix group
2696                    to attach to. */
2697                 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
2698                 goto done;
2699                 break;
2700
2701         case SID_NAME_ALIAS:
2702                 if (!sid_check_is_in_our_domain(&map->sid)) {
2703                         DEBUG(3, ("Refusing to map sid %s as an alias, not "
2704                                   "in our domain\n",
2705                                   sid_string_static(&map->sid)));
2706                         result = NT_STATUS_INVALID_PARAMETER;
2707                         goto done;
2708                 }
2709                 break;
2710
2711         case SID_NAME_WKN_GRP:
2712                 if (!sid_check_is_in_builtin(&map->sid)) {
2713                         DEBUG(3, ("Refusing to map sid %s as an alias, not "
2714                                   "in builtin domain\n",
2715                                   sid_string_static(&map->sid)));
2716                         result = NT_STATUS_INVALID_PARAMETER;
2717                         goto done;
2718                 }
2719                 break;
2720
2721         default:
2722                 DEBUG(3, ("Got invalid use '%s' for mapping\n",
2723                           sid_type_lookup(map->sid_name_use)));
2724                 result = NT_STATUS_INVALID_PARAMETER;
2725                 goto done;
2726         }
2727
2728         /* Domain groups have been mapped in a separate routine, we have to
2729          * create an alias now */
2730
2731         if (map->gid == -1) {
2732                 DEBUG(10, ("Refusing to map gid==-1\n"));
2733                 result = NT_STATUS_INVALID_PARAMETER;
2734                 goto done;
2735         }
2736
2737         if (pdb_gid_to_sid(map->gid, &sid)) {
2738                 DEBUG(3, ("Gid %d is already mapped to SID %s, refusing to "
2739                           "add\n", map->gid, sid_string_static(&sid)));
2740                 result = NT_STATUS_GROUP_EXISTS;
2741                 goto done;
2742         }
2743
2744         /* Ok, enough checks done. It's still racy to go ahead now, but that's
2745          * the best we can get out of LDAP. */
2746
2747         dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
2748                              sid_string_static(&map->sid),
2749                              lp_ldap_group_suffix());
2750         if (dn == NULL) {
2751                 result = NT_STATUS_NO_MEMORY;
2752                 goto done;
2753         }
2754
2755         mods = NULL;
2756
2757         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
2758                          "sambaSidEntry");
2759         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
2760                          "sambaGroupMapping");
2761
2762         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
2763                          sid_string_static(&map->sid));
2764         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
2765                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2766         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
2767                          map->nt_name);
2768         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
2769                          map->comment);
2770         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
2771                          talloc_asprintf(mem_ctx, "%u", map->gid));
2772         talloc_autofree_ldapmod(mem_ctx, mods);
2773
2774         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
2775
2776         result = (rc == LDAP_SUCCESS) ?
2777                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
2778
2779  done:
2780         TALLOC_FREE(mem_ctx);
2781         return result;
2782 }
2783
2784 /**********************************************************************
2785  * Update a group mapping entry. We're quite strict about what can be changed:
2786  * Only the description and displayname may be changed. It simply does not
2787  * make any sense to change the SID, gid or the type in a mapping.
2788  *********************************************************************/
2789
2790 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
2791                                                    GROUP_MAP *map)
2792 {
2793         struct ldapsam_privates *ldap_state =
2794                 (struct ldapsam_privates *)methods->private_data;
2795         int rc;
2796         const char *filter, *dn;
2797         LDAPMessage *msg = NULL;
2798         LDAPMessage *entry = NULL;
2799         LDAPMod **mods = NULL;
2800         TALLOC_CTX *mem_ctx;
2801         NTSTATUS result;
2802
2803         mem_ctx = talloc_new(NULL);
2804         if (mem_ctx == NULL) {
2805                 DEBUG(0, ("talloc_new failed\n"));
2806                 return NT_STATUS_NO_MEMORY;
2807         }
2808
2809         /* Make 100% sure that sid, gid and type are not changed by looking up
2810          * exactly the values we're given in LDAP. */
2811
2812         filter = talloc_asprintf(mem_ctx, "(&(objectClass=sambaGroupMapping)"
2813                                  "(sambaSid=%s)(gidNumber=%u)"
2814                                  "(sambaGroupType=%d))",
2815                                  sid_string_static(&map->sid), map->gid,
2816                                  map->sid_name_use);
2817         if (filter == NULL) {
2818                 result = NT_STATUS_NO_MEMORY;
2819                 goto done;
2820         }
2821
2822         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2823                                    get_attr_list(mem_ctx, groupmap_attr_list),
2824                                    &msg);
2825         talloc_autofree_ldapmsg(mem_ctx, msg);
2826
2827         if ((rc != LDAP_SUCCESS) ||
2828             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2829             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2830                 result = NT_STATUS_NO_SUCH_GROUP;
2831                 goto done;
2832         }
2833
2834         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2835
2836         if (dn == NULL) {
2837                 result = NT_STATUS_NO_MEMORY;
2838                 goto done;
2839         }
2840
2841         mods = NULL;
2842         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2843                          map->nt_name);
2844         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2845                          map->comment);
2846         talloc_autofree_ldapmod(mem_ctx, mods);
2847
2848         if (mods == NULL) {
2849                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
2850                           "nothing to do\n"));
2851                 result = NT_STATUS_OK;
2852                 goto done;
2853         }
2854
2855         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2856
2857         if (rc != LDAP_SUCCESS) {
2858                 result = NT_STATUS_ACCESS_DENIED;
2859                 goto done;
2860         }
2861
2862         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
2863                   "group %lu in LDAP\n", (unsigned long)map->gid));
2864
2865         result = NT_STATUS_OK;
2866
2867  done:
2868         TALLOC_FREE(mem_ctx);
2869         return result;
2870 }
2871
2872 /**********************************************************************
2873  *********************************************************************/
2874
2875 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
2876                                                    DOM_SID sid)
2877 {
2878         struct ldapsam_privates *priv =
2879                 (struct ldapsam_privates *)methods->private_data;
2880         LDAPMessage *msg, *entry;
2881         int rc;
2882         NTSTATUS result;
2883         TALLOC_CTX *mem_ctx;
2884         char *filter;
2885
2886         mem_ctx = talloc_new(NULL);
2887         if (mem_ctx == NULL) {
2888                 DEBUG(0, ("talloc_new failed\n"));
2889                 return NT_STATUS_NO_MEMORY;
2890         }
2891
2892         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
2893                                  LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
2894                                  sid_string_static(&sid));
2895         if (filter == NULL) {
2896                 result = NT_STATUS_NO_MEMORY;
2897                 goto done;
2898         }
2899         rc = smbldap_search_suffix(priv->smbldap_state, filter,
2900                                    get_attr_list(mem_ctx, groupmap_attr_list),
2901                                    &msg);
2902         talloc_autofree_ldapmsg(mem_ctx, msg);
2903
2904         if ((rc != LDAP_SUCCESS) ||
2905             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
2906             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
2907                 result = NT_STATUS_NO_SUCH_GROUP;
2908                 goto done;
2909         }
2910
2911         rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
2912                                   get_attr_list(mem_ctx,
2913                                                 groupmap_attr_list_to_delete));
2914  
2915         if ((rc == LDAP_NAMING_VIOLATION) ||
2916             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
2917                 const char *attrs[] = { "sambaGroupType", "description",
2918                                         "displayName", "sambaSIDList",
2919                                         NULL };
2920
2921                 /* Second try. Don't delete the sambaSID attribute, this is
2922                    for "old" entries that are tacked on a winbind
2923                    sambaIdmapEntry. */
2924
2925                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
2926                                           LDAP_OBJ_GROUPMAP, attrs);
2927         }
2928
2929         if ((rc == LDAP_NAMING_VIOLATION) ||
2930             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
2931                 const char *attrs[] = { "sambaGroupType", "description",
2932                                         "displayName", "sambaSIDList",
2933                                         "gidNumber", NULL };
2934
2935                 /* Third try. This is a post-3.0.21 alias (containing only
2936                  * sambaSidEntry and sambaGroupMapping classes), we also have
2937                  * to delete the gidNumber attribute, only the sambaSidEntry
2938                  * remains */
2939
2940                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
2941                                           LDAP_OBJ_GROUPMAP, attrs);
2942         }
2943
2944         result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
2945
2946  done:
2947         TALLOC_FREE(mem_ctx);
2948         return result;
2949  }
2950
2951 /**********************************************************************
2952  *********************************************************************/
2953
2954 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
2955                                     BOOL update)
2956 {
2957         struct ldapsam_privates *ldap_state =
2958                 (struct ldapsam_privates *)my_methods->private_data;
2959         fstring filter;
2960         int rc;
2961         const char **attr_list;
2962
2963         pstr_sprintf( filter, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
2964         attr_list = get_attr_list( NULL, groupmap_attr_list );
2965         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
2966                             LDAP_SCOPE_SUBTREE, filter,
2967                             attr_list, 0, &ldap_state->result);
2968         TALLOC_FREE(attr_list);
2969
2970         if (rc != LDAP_SUCCESS) {
2971                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
2972                           ldap_err2string(rc)));
2973                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
2974                           lp_ldap_group_suffix(), filter));
2975                 ldap_msgfree(ldap_state->result);
2976                 ldap_state->result = NULL;
2977                 return NT_STATUS_UNSUCCESSFUL;
2978         }
2979
2980         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
2981                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2982                                      ldap_state->result)));
2983
2984         ldap_state->entry =
2985                 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
2986                                  ldap_state->result);
2987         ldap_state->index = 0;
2988
2989         return NT_STATUS_OK;
2990 }
2991
2992 /**********************************************************************
2993  *********************************************************************/
2994
2995 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
2996 {
2997         ldapsam_endsampwent(my_methods);
2998 }
2999
3000 /**********************************************************************
3001  *********************************************************************/
3002
3003 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3004                                     GROUP_MAP *map)
3005 {
3006         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3007         struct ldapsam_privates *ldap_state =
3008                 (struct ldapsam_privates *)my_methods->private_data;
3009         BOOL bret = False;
3010
3011         while (!bret) {
3012                 if (!ldap_state->entry)
3013                         return ret;
3014                 
3015                 ldap_state->index++;
3016                 bret = init_group_from_ldap(ldap_state, map,
3017                                             ldap_state->entry);
3018                 
3019                 ldap_state->entry =
3020                         ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3021                                         ldap_state->entry);     
3022         }
3023
3024         return NT_STATUS_OK;
3025 }
3026
3027 /**********************************************************************
3028  *********************************************************************/
3029
3030 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3031                                            enum SID_NAME_USE sid_name_use,
3032                                            GROUP_MAP **pp_rmap,
3033                                            size_t *p_num_entries,
3034                                            BOOL unix_only)
3035 {
3036         GROUP_MAP map;
3037         GROUP_MAP *mapt;
3038         size_t entries = 0;
3039
3040         *p_num_entries = 0;
3041         *pp_rmap = NULL;
3042
3043         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3044                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3045                           "passdb\n"));
3046                 return NT_STATUS_ACCESS_DENIED;
3047         }
3048
3049         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3050                 if (sid_name_use != SID_NAME_UNKNOWN &&
3051                     sid_name_use != map.sid_name_use) {
3052                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3053                                   "not of the requested type\n", map.nt_name));
3054                         continue;
3055                 }
3056                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3057                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3058                                   "non mapped\n", map.nt_name));
3059                         continue;
3060                 }
3061
3062                 mapt=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3063                 if (!mapt) {
3064                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3065                                  "enlarge group map!\n"));
3066                         SAFE_FREE(*pp_rmap);
3067                         return NT_STATUS_UNSUCCESSFUL;
3068                 }
3069                 else
3070                         (*pp_rmap) = mapt;
3071
3072                 mapt[entries] = map;
3073
3074                 entries += 1;
3075
3076         }
3077         ldapsam_endsamgrent(methods);
3078
3079         *p_num_entries = entries;
3080
3081         return NT_STATUS_OK;
3082 }
3083
3084 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3085                                         const DOM_SID *alias,
3086                                         const DOM_SID *member,
3087                                         int modop)
3088 {
3089         struct ldapsam_privates *ldap_state =
3090                 (struct ldapsam_privates *)methods->private_data;
3091         char *dn;
3092         LDAPMessage *result = NULL;
3093         LDAPMessage *entry = NULL;
3094         int count;
3095         LDAPMod **mods = NULL;
3096         int rc;
3097         enum SID_NAME_USE type = SID_NAME_USE_NONE;
3098
3099         pstring filter;
3100
3101         if (sid_check_is_in_builtin(alias)) {
3102                 type = SID_NAME_WKN_GRP;
3103         }
3104
3105         if (sid_check_is_in_our_domain(alias)) {
3106                 type = SID_NAME_ALIAS;
3107         }
3108
3109         if (type == SID_NAME_USE_NONE) {
3110                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3111                           sid_string_static(alias)));
3112                 return NT_STATUS_NO_SUCH_ALIAS;
3113         }
3114
3115         pstr_sprintf(filter,
3116                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3117                      LDAP_OBJ_GROUPMAP, sid_string_static(alias),
3118                      type);
3119
3120         if (ldapsam_search_one_group(ldap_state, filter,
3121                                      &result) != LDAP_SUCCESS)
3122                 return NT_STATUS_NO_SUCH_ALIAS;
3123
3124         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3125                                    result);
3126
3127         if (count < 1) {
3128                 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3129                 ldap_msgfree(result);
3130                 return NT_STATUS_NO_SUCH_ALIAS;
3131         }
3132
3133         if (count > 1) {
3134                 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3135                           "filter %s: count=%d\n", filter, count));
3136                 ldap_msgfree(result);
3137                 return NT_STATUS_NO_SUCH_ALIAS;
3138         }
3139
3140         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3141                                  result);
3142
3143         if (!entry) {
3144                 ldap_msgfree(result);
3145                 return NT_STATUS_UNSUCCESSFUL;
3146         }
3147
3148         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
3149         if (!dn) {
3150                 ldap_msgfree(result);
3151                 return NT_STATUS_UNSUCCESSFUL;
3152         }
3153
3154         smbldap_set_mod(&mods, modop,
3155                         get_attr_key2string(groupmap_attr_list,
3156                                             LDAP_ATTR_SID_LIST),
3157                         sid_string_static(member));
3158
3159         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3160
3161         ldap_mods_free(mods, True);
3162         ldap_msgfree(result);
3163         SAFE_FREE(dn);
3164
3165         if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3166                 return NT_STATUS_MEMBER_IN_ALIAS;
3167         }
3168
3169         if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3170                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3171         }
3172
3173         if (rc != LDAP_SUCCESS) {
3174                 return NT_STATUS_UNSUCCESSFUL;
3175         }
3176
3177         return NT_STATUS_OK;
3178 }
3179
3180 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3181                                      const DOM_SID *alias,
3182                                      const DOM_SID *member)
3183 {
3184         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3185 }
3186
3187 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3188                                      const DOM_SID *alias,
3189                                      const DOM_SID *member)
3190 {
3191         return ldapsam_modify_aliasmem(methods, alias, member,
3192                                        LDAP_MOD_DELETE);
3193 }
3194
3195 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3196                                       const DOM_SID *alias,
3197                                       DOM_SID **pp_members,
3198                                       size_t *p_num_members)
3199 {
3200         struct ldapsam_privates *ldap_state =
3201                 (struct ldapsam_privates *)methods->private_data;
3202         LDAPMessage *result = NULL;
3203         LDAPMessage *entry = NULL;
3204         int count;
3205         char **values;
3206         int i;
3207         pstring filter;
3208         size_t num_members = 0;
3209         enum SID_NAME_USE type = SID_NAME_USE_NONE;
3210
3211         *pp_members = NULL;
3212         *p_num_members = 0;
3213
3214         if (sid_check_is_in_builtin(alias)) {
3215                 type = SID_NAME_WKN_GRP;
3216         }
3217
3218         if (sid_check_is_in_our_domain(alias)) {
3219                 type = SID_NAME_ALIAS;
3220         }
3221
3222         if (type == SID_NAME_USE_NONE) {
3223                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3224                           sid_string_static(alias)));
3225                 return NT_STATUS_NO_SUCH_ALIAS;
3226         }
3227
3228         pstr_sprintf(filter,
3229                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3230                      LDAP_OBJ_GROUPMAP, sid_string_static(alias),
3231                      type);
3232
3233         if (ldapsam_search_one_group(ldap_state, filter,
3234                                      &result) != LDAP_SUCCESS)
3235                 return NT_STATUS_NO_SUCH_ALIAS;
3236
3237         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3238                                    result);
3239
3240         if (count < 1) {
3241                 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3242                 ldap_msgfree(result);
3243                 return NT_STATUS_NO_SUCH_ALIAS;
3244         }
3245
3246         if (count > 1) {
3247                 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3248                           "filter %s: count=%d\n", filter, count));
3249                 ldap_msgfree(result);
3250                 return NT_STATUS_NO_SUCH_ALIAS;
3251         }
3252
3253         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3254                                  result);
3255
3256         if (!entry) {
3257                 ldap_msgfree(result);
3258                 return NT_STATUS_UNSUCCESSFUL;
3259         }
3260
3261         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3262                                  entry,
3263                                  get_attr_key2string(groupmap_attr_list,
3264                                                      LDAP_ATTR_SID_LIST));
3265
3266         if (values == NULL) {
3267                 ldap_msgfree(result);
3268                 return NT_STATUS_OK;
3269         }
3270
3271         count = ldap_count_values(values);
3272
3273         for (i=0; i<count; i++) {
3274                 DOM_SID member;
3275
3276                 if (!string_to_sid(&member, values[i]))
3277                         continue;
3278
3279                 add_sid_to_array(NULL, &member, pp_members, &num_members);
3280         }
3281
3282         *p_num_members = num_members;
3283         ldap_value_free(values);
3284         ldap_msgfree(result);
3285
3286         return NT_STATUS_OK;
3287 }
3288
3289 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3290                                           TALLOC_CTX *mem_ctx,
3291                                           const DOM_SID *domain_sid,
3292                                           const DOM_SID *members,
3293                                           size_t num_members,
3294                                           uint32 **pp_alias_rids,
3295                                           size_t *p_num_alias_rids)
3296 {
3297         struct ldapsam_privates *ldap_state =
3298                 (struct ldapsam_privates *)methods->private_data;
3299         LDAP *ldap_struct;
3300
3301         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3302
3303         LDAPMessage *result = NULL;
3304         LDAPMessage *entry = NULL;
3305         int i;
3306         int rc;
3307         char *filter;
3308         enum SID_NAME_USE type = SID_NAME_USE_NONE;
3309
3310         if (sid_check_is_builtin(domain_sid)) {
3311                 type = SID_NAME_WKN_GRP;
3312         }
3313
3314         if (sid_check_is_domain(domain_sid)) {
3315                 type = SID_NAME_ALIAS;
3316         }
3317
3318         if (type == SID_NAME_USE_NONE) {
3319                 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3320                           sid_string_static(domain_sid)));
3321                 return NT_STATUS_UNSUCCESSFUL;
3322         }
3323
3324         filter = talloc_asprintf(mem_ctx,
3325                                  "(&(|(objectclass=%s)(sambaGroupType=%d))(|",
3326                                  LDAP_OBJ_GROUPMAP, type);
3327
3328         for (i=0; i<num_members; i++)
3329                 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3330                                          filter,
3331                                          sid_string_static(&members[i]));
3332
3333         filter = talloc_asprintf(mem_ctx, "%s))", filter);
3334
3335         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3336                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3337
3338         if (rc != LDAP_SUCCESS)
3339                 return NT_STATUS_UNSUCCESSFUL;
3340
3341         ldap_struct = ldap_state->smbldap_state->ldap_struct;
3342
3343         for (entry = ldap_first_entry(ldap_struct, result);
3344              entry != NULL;
3345              entry = ldap_next_entry(ldap_struct, entry))
3346         {
3347                 fstring sid_str;
3348                 DOM_SID sid;
3349                 uint32 rid;
3350
3351                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3352                                                   LDAP_ATTRIBUTE_SID,
3353                                                   sid_str,
3354                                                   sizeof(sid_str)-1))
3355                         continue;
3356
3357                 if (!string_to_sid(&sid, sid_str))
3358                         continue;
3359
3360                 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3361                         continue;
3362
3363                 add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3364                                         p_num_alias_rids);
3365         }
3366
3367         ldap_msgfree(result);
3368         return NT_STATUS_OK;
3369 }
3370
3371 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3372                                                    int policy_index,
3373                                                    uint32 value)
3374 {
3375         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3376         int rc;
3377         LDAPMod **mods = NULL;
3378         fstring value_string;
3379         const char *policy_attr = NULL;
3380
3381         struct ldapsam_privates *ldap_state =
3382                 (struct ldapsam_privates *)methods->private_data;
3383
3384         const char *attrs[2];
3385
3386         DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3387
3388         if (!ldap_state->domain_dn) {
3389                 return NT_STATUS_INVALID_PARAMETER;
3390         }
3391
3392         policy_attr = get_account_policy_attr(policy_index);
3393         if (policy_attr == NULL) {
3394                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3395                          "policy\n"));
3396                 return ntstatus;
3397         }
3398
3399         attrs[0] = policy_attr;
3400         attrs[1] = NULL;
3401
3402         slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3403
3404         smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3405
3406         rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3407                             mods);
3408
3409         ldap_mods_free(mods, True);
3410
3411         if (rc != LDAP_SUCCESS) {
3412                 return ntstatus;
3413         }
3414
3415         if (!cache_account_policy_set(policy_index, value)) {
3416                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3417                          "update local tdb cache\n"));
3418                 return ntstatus;
3419         }
3420
3421         return NT_STATUS_OK;
3422 }
3423
3424 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3425                                            int policy_index, uint32 value)
3426 {
3427         if (!account_policy_migrated(False)) {
3428                 return (account_policy_set(policy_index, value)) ?
3429                         NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3430         }
3431
3432         return ldapsam_set_account_policy_in_ldap(methods, policy_index,
3433                                                   value);
3434 }
3435
3436 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3437                                                      int policy_index,
3438                                                      uint32 *value)
3439 {
3440         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3441         LDAPMessage *result = NULL;
3442         LDAPMessage *entry = NULL;
3443         int count;
3444         int rc;
3445         char **vals = NULL;
3446         const char *policy_attr = NULL;
3447
3448         struct ldapsam_privates *ldap_state =
3449                 (struct ldapsam_privates *)methods->private_data;
3450
3451         const char *attrs[2];
3452
3453         DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3454
3455         if (!ldap_state->domain_dn) {
3456                 return NT_STATUS_INVALID_PARAMETER;
3457         }
3458
3459         policy_attr = get_account_policy_attr(policy_index);
3460         if (!policy_attr) {
3461                 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3462                          "policy index: %d\n", policy_index));
3463                 return ntstatus;
3464         }
3465
3466         attrs[0] = policy_attr;
3467         attrs[1] = NULL;
3468
3469         rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3470                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0,
3471                             &result);
3472
3473         if (rc != LDAP_SUCCESS) {
3474                 return ntstatus;
3475         }
3476
3477         count = ldap_count_entries(priv2ld(ldap_state), result);
3478         if (count < 1) {
3479                 goto out;
3480         }
3481
3482         entry = ldap_first_entry(priv2ld(ldap_state), result);
3483         if (entry == NULL) {
3484                 goto out;
3485         }
3486
3487         vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3488         if (vals == NULL) {
3489                 goto out;
3490         }
3491
3492         *value = (uint32)atol(vals[0]);
3493         
3494         ntstatus = NT_STATUS_OK;
3495
3496 out:
3497         if (vals)
3498                 ldap_value_free(vals);
3499         ldap_msgfree(result);
3500
3501         return ntstatus;
3502 }
3503
3504 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache 
3505
3506    - if user hasn't decided to use account policies inside LDAP just reuse the
3507      old tdb values
3508    
3509    - if there is a valid cache entry, return that
3510    - if there is an LDAP entry, update cache and return 
3511    - otherwise set to default, update cache and return
3512
3513    Guenther
3514 */
3515 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3516                                            int policy_index, uint32 *value)
3517 {
3518         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3519
3520         if (!account_policy_migrated(False)) {
3521                 return (account_policy_get(policy_index, value))
3522                         ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3523         }
3524
3525         if (cache_account_policy_get(policy_index, value)) {
3526                 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3527                           "cache\n"));
3528                 return NT_STATUS_OK;
3529         }
3530
3531         ntstatus = ldapsam_get_account_policy_from_ldap(methods, policy_index,
3532                                                         value);
3533         if (NT_STATUS_IS_OK(ntstatus)) {
3534                 goto update_cache;
3535         }
3536
3537         DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3538                   "ldap\n"));
3539
3540 #if 0
3541         /* should we automagically migrate old tdb value here ? */
3542         if (account_policy_get(policy_index, value))
3543                 goto update_ldap;
3544
3545         DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3546                   "default\n", policy_index));
3547 #endif
3548
3549         if (!account_policy_get_default(policy_index, value)) {
3550                 return ntstatus;
3551         }
3552         
3553 /* update_ldap: */
3554  
3555         ntstatus = ldapsam_set_account_policy(methods, policy_index, *value);
3556         if (!NT_STATUS_IS_OK(ntstatus)) {
3557                 return ntstatus;
3558         }
3559                 
3560  update_cache:
3561  
3562         if (!cache_account_policy_set(policy_index, *value)) {
3563                 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3564                          "tdb as a cache\n"));
3565                 return NT_STATUS_UNSUCCESSFUL;
3566         }
3567
3568         return NT_STATUS_OK;
3569 }
3570
3571 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3572                                     const DOM_SID *domain_sid,
3573                                     int num_rids,
3574                                     uint32 *rids,
3575                                     const char **names,
3576                                     uint32 *attrs)
3577 {
3578         struct ldapsam_privates *ldap_state =
3579                 (struct ldapsam_privates *)methods->private_data;
3580         LDAPMessage *msg = NULL;
3581         LDAPMessage *entry;
3582         char *allsids = NULL;
3583         int i, rc, num_mapped;
3584         NTSTATUS result = NT_STATUS_NO_MEMORY;
3585         TALLOC_CTX *mem_ctx;
3586         LDAP *ld;
3587         BOOL is_builtin;
3588
3589         mem_ctx = talloc_new(NULL);
3590         if (mem_ctx == NULL) {
3591                 DEBUG(0, ("talloc_new failed\n"));
3592                 goto done;
3593         }
3594
3595         if (!sid_check_is_builtin(domain_sid) &&
3596             !sid_check_is_domain(domain_sid)) {
3597                 result = NT_STATUS_INVALID_PARAMETER;
3598                 goto done;
3599         }
3600
3601         for (i=0; i<num_rids; i++)
3602                 attrs[i] = SID_NAME_UNKNOWN;
3603
3604         allsids = talloc_strdup(mem_ctx, "");
3605         if (allsids == NULL) {
3606                 goto done;
3607         }
3608
3609         for (i=0; i<num_rids; i++) {
3610                 DOM_SID sid;
3611                 sid_copy(&sid, domain_sid);
3612                 sid_append_rid(&sid, rids[i]);
3613                 allsids = talloc_asprintf_append(allsids, "(sambaSid=%s)",
3614                                                  sid_string_static(&sid));
3615                 if (allsids == NULL) {
3616                         goto done;
3617                 }
3618         }
3619
3620         /* First look for users */
3621
3622         {
3623                 char *filter;
3624                 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
3625
3626                 filter = talloc_asprintf(
3627                         mem_ctx, ("(&(objectClass=sambaSamAccount)(|%s))"),
3628                         allsids);
3629
3630                 if (filter == NULL) {
3631                         goto done;
3632                 }
3633
3634                 rc = smbldap_search(ldap_state->smbldap_state,
3635                                     lp_ldap_user_suffix(),
3636                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3637                                     &msg);
3638                 talloc_autofree_ldapmsg(mem_ctx, msg);
3639         }
3640
3641         if (rc != LDAP_SUCCESS)
3642                 goto done;
3643
3644         ld = ldap_state->smbldap_state->ldap_struct;
3645         num_mapped = 0;
3646
3647         for (entry = ldap_first_entry(ld, msg);
3648              entry != NULL;
3649              entry = ldap_next_entry(ld, entry)) {
3650                 uint32 rid;
3651                 int rid_index;
3652                 const char *name;
3653
3654                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
3655                                                     &rid)) {
3656                         DEBUG(2, ("Could not find sid from ldap entry\n"));
3657                         continue;
3658                 }
3659
3660                 name = smbldap_talloc_single_attribute(ld, entry, "uid",
3661                                                        names);
3662                 if (name == NULL) {
3663                         DEBUG(2, ("Could not retrieve uid attribute\n"));
3664                         continue;
3665                 }
3666
3667                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3668                         if (rid == rids[rid_index])
3669                                 break;
3670                 }
3671
3672                 if (rid_index == num_rids) {
3673                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3674                         continue;
3675                 }
3676
3677                 attrs[rid_index] = SID_NAME_USER;
3678                 names[rid_index] = name;
3679                 num_mapped += 1;
3680         }
3681
3682         if (num_mapped == num_rids) {
3683                 /* No need to look for groups anymore -- we're done */
3684                 result = NT_STATUS_OK;
3685                 goto done;
3686         }
3687
3688         /* Same game for groups */
3689
3690         {
3691                 char *filter;
3692                 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
3693                                              "sambaGroupType", NULL };
3694
3695                 filter = talloc_asprintf(
3696                         mem_ctx, "(&(objectClass=sambaGroupMapping)(|%s))",
3697                         allsids);
3698                 if (filter == NULL) {
3699                         goto done;
3700                 }
3701
3702                 rc = smbldap_search(ldap_state->smbldap_state,
3703                                     lp_ldap_group_suffix(),
3704                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3705                                     &msg);
3706                 talloc_autofree_ldapmsg(mem_ctx, msg);
3707         }
3708
3709         if (rc != LDAP_SUCCESS)
3710                 goto done;
3711
3712         /* ldap_struct might have changed due to a reconnect */
3713
3714         ld = ldap_state->smbldap_state->ldap_struct;
3715
3716         /* For consistency checks, we already checked we're only domain or builtin */
3717
3718         is_builtin = sid_check_is_builtin(domain_sid);
3719
3720         for (entry = ldap_first_entry(ld, msg);
3721              entry != NULL;
3722              entry = ldap_next_entry(ld, entry))
3723         {
3724                 uint32 rid;
3725                 int rid_index;
3726                 const char *attr;
3727                 enum SID_NAME_USE type;
3728                 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
3729
3730                 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
3731                                                        mem_ctx);
3732                 if (attr == NULL) {
3733                         DEBUG(2, ("Could not extract type from ldap entry %s\n",
3734                                   dn));
3735                         continue;
3736                 }
3737
3738                 type = atol(attr);
3739
3740                 /* Consistency checks */
3741                 if ((is_builtin && (type != SID_NAME_WKN_GRP)) ||
3742                     (!is_builtin && ((type != SID_NAME_ALIAS) &&
3743                                      (type != SID_NAME_DOM_GRP)))) {
3744                         DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
3745                 }
3746
3747                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
3748                                                     &rid)) {
3749                         DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
3750                         continue;
3751                 }
3752
3753                 attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
3754
3755                 if (attr == NULL) {
3756                         DEBUG(10, ("Could not retrieve 'cn' attribute from %s\n",
3757                                    dn));
3758                         attr = smbldap_talloc_single_attribute(
3759                                 ld, entry, "displayName", names);
3760                 }
3761
3762                 if (attr == NULL) {
3763                         DEBUG(2, ("Could not retrieve naming attribute from %s\n",
3764                                   dn));
3765                         continue;
3766                 }
3767
3768                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3769                         if (rid == rids[rid_index])
3770                                 break;
3771                 }
3772
3773                 if (rid_index == num_rids) {
3774                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3775                         continue;
3776                 }
3777
3778                 attrs[rid_index] = type;
3779                 names[rid_index] = attr;
3780                 num_mapped += 1;
3781         }
3782
3783         result = NT_STATUS_NONE_MAPPED;
3784
3785         if (num_mapped > 0)
3786                 result = (num_mapped == num_rids) ?
3787                         NT_STATUS_OK : STATUS_SOME_UNMAPPED;
3788  done:
3789         TALLOC_FREE(mem_ctx);
3790         return result;
3791 }
3792
3793 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
3794 {
3795         char *filter = NULL;
3796         char *escaped = NULL;
3797         char *result = NULL;
3798
3799         asprintf(&filter, "(&%s(objectclass=sambaSamAccount))",
3800                  "(uid=%u)");
3801         if (filter == NULL) goto done;
3802
3803         escaped = escape_ldap_string_alloc(username);
3804         if (escaped == NULL) goto done;
3805
3806         result = talloc_string_sub(mem_ctx, filter, "%u", username);
3807
3808  done:
3809         SAFE_FREE(filter);
3810         SAFE_FREE(escaped);
3811
3812         return result;
3813 }
3814
3815 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
3816 {
3817         int i, num = 0;
3818         va_list ap;
3819         const char **result;
3820
3821         va_start(ap, mem_ctx);
3822         while (va_arg(ap, const char *) != NULL)
3823                 num += 1;
3824         va_end(ap);
3825
3826         result = TALLOC_ARRAY(mem_ctx, const char *, num+1);
3827
3828         va_start(ap, mem_ctx);
3829         for (i=0; i<num; i++)
3830                 result[i] = talloc_strdup(mem_ctx, va_arg(ap, const char*));
3831         va_end(ap);
3832
3833         result[num] = NULL;
3834         return result;
3835 }
3836
3837 struct ldap_search_state {
3838         struct smbldap_state *connection;
3839
3840         uint16 acct_flags;
3841         uint16 group_type;
3842
3843         const char *base;
3844         int scope;
3845         const char *filter;
3846         const char **attrs;
3847         int attrsonly;
3848         void *pagedresults_cookie;
3849
3850         LDAPMessage *entries, *current_entry;
3851         BOOL (*ldap2displayentry)(struct ldap_search_state *state,
3852                                   TALLOC_CTX *mem_ctx,
3853                                   LDAP *ld, LDAPMessage *entry,
3854                                   struct samr_displayentry *result);
3855 };
3856
3857 static BOOL ldapsam_search_firstpage(struct pdb_search *search)
3858 {
3859         struct ldap_search_state *state = search->private_data;
3860         LDAP *ld;
3861         int rc = LDAP_OPERATIONS_ERROR;
3862
3863         state->entries = NULL;
3864
3865         if (state->connection->paged_results) {
3866                 rc = smbldap_search_paged(state->connection, state->base,
3867                                           state->scope, state->filter,
3868                                           state->attrs, state->attrsonly,
3869                                           lp_ldap_page_size(), &state->entries,
3870                                           &state->pagedresults_cookie);
3871         }
3872
3873         if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
3874
3875                 if (state->entries != NULL) {
3876                         /* Left over from unsuccessful paged attempt */
3877                         ldap_msgfree(state->entries);
3878                         state->entries = NULL;
3879                 }
3880
3881                 rc = smbldap_search(state->connection, state->base,
3882                                     state->scope, state->filter, state->attrs,
3883                                     state->attrsonly, &state->entries);
3884
3885                 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
3886                         return False;
3887
3888                 /* Ok, the server was lying. It told us it could do paged
3889                  * searches when it could not. */
3890                 state->connection->paged_results = False;
3891         }
3892
3893         ld = state->connection->ldap_struct;
3894         if ( ld == NULL) {
3895                 DEBUG(5, ("Don't have an LDAP connection right after a "
3896                           "search\n"));
3897                 return False;
3898         }
3899         state->current_entry = ldap_first_entry(ld, state->entries);
3900
3901         if (state->current_entry == NULL) {
3902                 ldap_msgfree(state->entries);
3903                 state->entries = NULL;
3904         }
3905
3906         return True;
3907 }
3908
3909 static BOOL ldapsam_search_nextpage(struct pdb_search *search)
3910 {
3911         struct ldap_search_state *state = search->private_data;
3912         int rc;
3913
3914         if (!state->connection->paged_results) {
3915                 /* There is no next page when there are no paged results */
3916                 return False;
3917         }
3918
3919         rc = smbldap_search_paged(state->connection, state->base,
3920                                   state->scope, state->filter, state->attrs,
3921                                   state->attrsonly, lp_ldap_page_size(),
3922                                   &state->entries,
3923                                   &state->pagedresults_cookie);
3924
3925         if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
3926                 return False;
3927
3928         state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
3929
3930         if (state->current_entry == NULL) {
3931                 ldap_msgfree(state->entries);
3932                 state->entries = NULL;
3933         }
3934
3935         return True;
3936 }
3937
3938 static BOOL ldapsam_search_next_entry(struct pdb_search *search,
3939                                       struct samr_displayentry *entry)
3940 {
3941         struct ldap_search_state *state = search->private_data;
3942         BOOL result;
3943
3944  retry:
3945         if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
3946                 return False;
3947
3948         if ((state->entries == NULL) &&
3949             !ldapsam_search_nextpage(search))
3950                     return False;
3951
3952         result = state->ldap2displayentry(state, search->mem_ctx, state->connection->ldap_struct,
3953                                           state->current_entry, entry);
3954
3955         if (!result) {
3956                 char *dn;
3957                 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
3958                 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
3959                 if (dn != NULL) ldap_memfree(dn);
3960         }
3961
3962         state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
3963
3964         if (state->current_entry == NULL) {
3965                 ldap_msgfree(state->entries);
3966                 state->entries = NULL;
3967         }
3968
3969         if (!result) goto retry;
3970
3971         return True;
3972 }
3973
3974 static void ldapsam_search_end(struct pdb_search *search)
3975 {
3976         struct ldap_search_state *state = search->private_data;
3977         int rc;
3978
3979         if (state->pagedresults_cookie == NULL)
3980                 return;
3981
3982         if (state->entries != NULL)
3983                 ldap_msgfree(state->entries);
3984
3985         state->entries = NULL;
3986         state->current_entry = NULL;
3987
3988         if (!state->connection->paged_results)
3989                 return;
3990
3991         /* Tell the LDAP server we're not interested in the rest anymore. */
3992
3993         rc = smbldap_search_paged(state->connection, state->base, state->scope,
3994                                   state->filter, state->attrs,
3995                                   state->attrsonly, 0, &state->entries,
3996                                   &state->pagedresults_cookie);
3997
3998         if (rc != LDAP_SUCCESS)
3999                 DEBUG(5, ("Could not end search properly\n"));
4000
4001         return;
4002 }
4003
4004 static BOOL ldapuser2displayentry(struct ldap_search_state *state,
4005                                   TALLOC_CTX *mem_ctx,
4006                                   LDAP *ld, LDAPMessage *entry,
4007                                   struct samr_displayentry *result)
4008 {
4009         char **vals;
4010         DOM_SID sid;
4011         uint16 acct_flags;
4012
4013         vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4014         if ((vals == NULL) || (vals[0] == NULL)) {
4015                 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4016                 return False;
4017         }
4018         acct_flags = pdb_decode_acct_ctrl(vals[0]);
4019         ldap_value_free(vals);
4020
4021         if ((state->acct_flags != 0) &&
4022             ((state->acct_flags & acct_flags) == 0))
4023                 return False;           
4024
4025         result->acct_flags = acct_flags;
4026         result->account_name = "";
4027         result->fullname = "";
4028         result->description = "";
4029
4030         vals = ldap_get_values(ld, entry, "uid");
4031         if ((vals == NULL) || (vals[0] == NULL)) {
4032                 DEBUG(5, ("\"uid\" not found\n"));
4033                 return False;
4034         }
4035         pull_utf8_talloc(mem_ctx,
4036                          CONST_DISCARD(char **, &result->account_name),
4037                          vals[0]);
4038         ldap_value_free(vals);
4039
4040         vals = ldap_get_values(ld, entry, "displayName");
4041         if ((vals == NULL) || (vals[0] == NULL))
4042                 DEBUG(8, ("\"displayName\" not found\n"));
4043         else
4044                 pull_utf8_talloc(mem_ctx,
4045                                  CONST_DISCARD(char **, &result->fullname),
4046                                  vals[0]);
4047         ldap_value_free(vals);
4048
4049         vals = ldap_get_values(ld, entry, "description");
4050         if ((vals == NULL) || (vals[0] == NULL))
4051                 DEBUG(8, ("\"description\" not found\n"));
4052         else
4053                 pull_utf8_talloc(mem_ctx,
4054                                  CONST_DISCARD(char **, &result->description),
4055                                  vals[0]);
4056         ldap_value_free(vals);
4057
4058         if ((result->account_name == NULL) ||
4059             (result->fullname == NULL) ||
4060             (result->description == NULL)) {
4061                 DEBUG(0, ("talloc failed\n"));
4062                 return False;
4063         }
4064         
4065         vals = ldap_get_values(ld, entry, "sambaSid");
4066         if ((vals == NULL) || (vals[0] == NULL)) {
4067                 DEBUG(0, ("\"objectSid\" not found\n"));
4068                 return False;
4069         }
4070
4071         if (!string_to_sid(&sid, vals[0])) {
4072                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4073                 ldap_value_free(vals);
4074                 return False;
4075         }
4076         ldap_value_free(vals);
4077
4078         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4079                 DEBUG(0, ("sid %s does not belong to our domain\n",
4080                           sid_string_static(&sid)));
4081                 return False;
4082         }
4083
4084         return True;
4085 }
4086
4087
4088 static BOOL ldapsam_search_users(struct pdb_methods *methods,
4089                                  struct pdb_search *search,
4090                                  uint16 acct_flags)
4091 {
4092         struct ldapsam_privates *ldap_state = methods->private_data;
4093         struct ldap_search_state *state;
4094
4095         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4096         if (state == NULL) {
4097                 DEBUG(0, ("talloc failed\n"));
4098                 return False;
4099         }
4100
4101         state->connection = ldap_state->smbldap_state;
4102
4103         if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4104                 state->base = lp_ldap_user_suffix();
4105         else if ((acct_flags != 0) &&
4106                  ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4107                 state->base = lp_ldap_machine_suffix();
4108         else
4109                 state->base = lp_ldap_suffix();
4110
4111         state->acct_flags = acct_flags;
4112         state->base = talloc_strdup(search->mem_ctx, state->base);
4113         state->scope = LDAP_SCOPE_SUBTREE;
4114         state->filter = get_ldap_filter(search->mem_ctx, "*");
4115         state->attrs = talloc_attrs(search->mem_ctx, "uid", "sambaSid",
4116                                     "displayName", "description",
4117                                     "sambaAcctFlags", NULL);
4118         state->attrsonly = 0;
4119         state->pagedresults_cookie = NULL;
4120         state->entries = NULL;
4121         state->ldap2displayentry = ldapuser2displayentry;
4122
4123         if ((state->filter == NULL) || (state->attrs == NULL)) {
4124                 DEBUG(0, ("talloc failed\n"));
4125                 return False;
4126         }
4127
4128         search->private_data = state;
4129         search->next_entry = ldapsam_search_next_entry;
4130         search->search_end = ldapsam_search_end;
4131
4132         return ldapsam_search_firstpage(search);
4133 }
4134
4135 static BOOL ldapgroup2displayentry(struct ldap_search_state *state,
4136                                    TALLOC_CTX *mem_ctx,
4137                                    LDAP *ld, LDAPMessage *entry,
4138                                    struct samr_displayentry *result)
4139 {
4140         char **vals;
4141         DOM_SID sid;
4142         uint16 group_type;
4143
4144         result->account_name = "";
4145         result->fullname = "";
4146         result->description = "";
4147
4148
4149         vals = ldap_get_values(ld, entry, "sambaGroupType");
4150         if ((vals == NULL) || (vals[0] == NULL)) {
4151                 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4152                 if (vals != NULL) {
4153                         ldap_value_free(vals);
4154                 }
4155                 return False;
4156         }
4157
4158         group_type = atoi(vals[0]);
4159
4160         if ((state->group_type != 0) &&
4161             ((state->group_type != group_type))) {
4162                 ldap_value_free(vals);
4163                 return False;
4164         }
4165
4166         ldap_value_free(vals);
4167
4168         /* display name is the NT group name */
4169
4170         vals = ldap_get_values(ld, entry, "displayName");
4171         if ((vals == NULL) || (vals[0] == NULL)) {
4172                 DEBUG(8, ("\"displayName\" not found\n"));
4173
4174                 /* fallback to the 'cn' attribute */
4175                 vals = ldap_get_values(ld, entry, "cn");
4176                 if ((vals == NULL) || (vals[0] == NULL)) {
4177                         DEBUG(5, ("\"cn\" not found\n"));
4178                         return False;
4179                 }
4180                 pull_utf8_talloc(mem_ctx,
4181                                  CONST_DISCARD(char **, &result->account_name),
4182                                  vals[0]);
4183         }
4184         else {
4185                 pull_utf8_talloc(mem_ctx,
4186                                  CONST_DISCARD(char **, &result->account_name),
4187                                  vals[0]);
4188         }
4189
4190         ldap_value_free(vals);
4191
4192         vals = ldap_get_values(ld, entry, "description");
4193         if ((vals == NULL) || (vals[0] == NULL))
4194                 DEBUG(8, ("\"description\" not found\n"));
4195         else
4196                 pull_utf8_talloc(mem_ctx,
4197                                  CONST_DISCARD(char **, &result->description),
4198                                  vals[0]);
4199         ldap_value_free(vals);
4200
4201         if ((result->account_name == NULL) ||
4202             (result->fullname == NULL) ||
4203             (result->description == NULL)) {
4204                 DEBUG(0, ("talloc failed\n"));
4205                 return False;
4206         }
4207         
4208         vals = ldap_get_values(ld, entry, "sambaSid");
4209         if ((vals == NULL) || (vals[0] == NULL)) {
4210                 DEBUG(0, ("\"objectSid\" not found\n"));
4211                 if (vals != NULL) {
4212                         ldap_value_free(vals);
4213                 }
4214                 return False;
4215         }
4216
4217         if (!string_to_sid(&sid, vals[0])) {
4218                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4219                 return False;
4220         }
4221
4222         ldap_value_free(vals);
4223
4224         switch (group_type) {
4225                 case SID_NAME_DOM_GRP:
4226                 case SID_NAME_ALIAS:
4227
4228                         if (!sid_peek_check_rid(get_global_sam_sid(), &sid,
4229                                                 &result->rid)) {
4230                                 DEBUG(0, ("%s is not in our domain\n",
4231                                           sid_string_static(&sid)));
4232                                 return False;
4233                         }
4234                         break;
4235         
4236                 case SID_NAME_WKN_GRP:
4237
4238                         if (!sid_peek_check_rid(&global_sid_Builtin, &sid,
4239                                                 &result->rid)) {
4240
4241                                 DEBUG(0, ("%s is not in builtin sid\n",
4242                                           sid_string_static(&sid)));
4243                                 return False;
4244                         }
4245                         break;
4246
4247                 default:
4248                         DEBUG(0,("unkown group type: %d\n", group_type));
4249                         return False;
4250         }
4251         
4252         return True;
4253 }
4254
4255 static BOOL ldapsam_search_grouptype(struct pdb_methods *methods,
4256                                      struct pdb_search *search,
4257                                      enum SID_NAME_USE type)
4258 {
4259         struct ldapsam_privates *ldap_state = methods->private_data;
4260         struct ldap_search_state *state;
4261
4262         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4263         if (state == NULL) {
4264                 DEBUG(0, ("talloc failed\n"));
4265                 return False;
4266         }
4267
4268         state->connection = ldap_state->smbldap_state;
4269
4270         state->base = talloc_strdup(search->mem_ctx, lp_ldap_group_suffix());
4271         state->connection = ldap_state->smbldap_state;
4272         state->scope = LDAP_SCOPE_SUBTREE;
4273         state->filter = talloc_asprintf(search->mem_ctx,
4274                                         "(&(objectclass=sambaGroupMapping)"
4275                                         "(sambaGroupType=%d))", type);
4276         state->attrs = talloc_attrs(search->mem_ctx, "cn", "sambaSid",
4277                                     "displayName", "description",
4278                                     "sambaGroupType", NULL);
4279         state->attrsonly = 0;
4280         state->pagedresults_cookie = NULL;
4281         state->entries = NULL;
4282         state->group_type = type;
4283         state->ldap2displayentry = ldapgroup2displayentry;
4284
4285         if ((state->filter == NULL) || (state->attrs == NULL)) {
4286                 DEBUG(0, ("talloc failed\n"));
4287                 return False;
4288         }
4289
4290         search->private_data = state;
4291         search->next_entry = ldapsam_search_next_entry;
4292         search->search_end = ldapsam_search_end;
4293
4294         return ldapsam_search_firstpage(search);
4295 }
4296
4297 static BOOL ldapsam_search_groups(struct pdb_methods *methods,
4298                                   struct pdb_search *search)
4299 {
4300         return ldapsam_search_grouptype(methods, search, SID_NAME_DOM_GRP);
4301 }
4302
4303 static BOOL ldapsam_search_aliases(struct pdb_methods *methods,
4304                                    struct pdb_search *search,
4305                                    const DOM_SID *sid)
4306 {
4307         if (sid_check_is_domain(sid))
4308                 return ldapsam_search_grouptype(methods, search,
4309                                                 SID_NAME_ALIAS);
4310
4311         if (sid_check_is_builtin(sid))
4312                 return ldapsam_search_grouptype(methods, search,
4313                                                 SID_NAME_WKN_GRP);
4314
4315         DEBUG(5, ("Don't know SID %s\n", sid_string_static(sid)));
4316         return False;
4317 }
4318
4319 static BOOL ldapsam_rid_algorithm(struct pdb_methods *methods)
4320 {
4321         return False;
4322 }
4323
4324 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4325                                     uint32 *rid)
4326 {
4327         struct smbldap_state *smbldap_state = priv->smbldap_state;
4328
4329         LDAPMessage *result = NULL;
4330         LDAPMessage *entry = NULL;
4331         LDAPMod **mods = NULL;
4332         NTSTATUS status;
4333         char *value;
4334         int rc;
4335         uint32 nextRid = 0;
4336
4337         TALLOC_CTX *mem_ctx;
4338
4339         mem_ctx = talloc_new(NULL);
4340         if (mem_ctx == NULL) {
4341                 DEBUG(0, ("talloc_new failed\n"));
4342                 return NT_STATUS_NO_MEMORY;
4343         }
4344
4345         status = smbldap_search_domain_info(smbldap_state, &result,
4346                                             get_global_sam_name(), False);
4347         if (!NT_STATUS_IS_OK(status)) {
4348                 DEBUG(3, ("Could not get domain info: %s\n",
4349                           nt_errstr(status)));
4350                 goto done;
4351         }
4352
4353         talloc_autofree_ldapmsg(mem_ctx, result);
4354
4355         entry = ldap_first_entry(priv2ld(priv), result);
4356         if (entry == NULL) {
4357                 DEBUG(0, ("Could not get domain info entry\n"));
4358                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4359                 goto done;
4360         }
4361
4362         /* Find the largest of the three attributes "sambaNextRid",
4363            "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4364            concept of differentiating between user and group rids, and will
4365            use only "sambaNextRid" in the future. But for compatibility
4366            reasons I look if others have chosen different strategies -- VL */
4367
4368         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4369                                                 "sambaNextRid", mem_ctx);
4370         if (value != NULL) {
4371                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4372                 nextRid = MAX(nextRid, tmp);
4373         }
4374
4375         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4376                                                 "sambaNextUserRid", mem_ctx);
4377         if (value != NULL) {
4378                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4379                 nextRid = MAX(nextRid, tmp);
4380         }
4381
4382         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4383                                                 "sambaNextGroupRid", mem_ctx);
4384         if (value != NULL) {
4385                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4386                 nextRid = MAX(nextRid, tmp);
4387         }
4388
4389         if (nextRid == 0) {
4390                 nextRid = BASE_RID-1;
4391         }
4392
4393         nextRid += 1;
4394
4395         smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4396                          talloc_asprintf(mem_ctx, "%d", nextRid));
4397         talloc_autofree_ldapmod(mem_ctx, mods);
4398
4399         rc = smbldap_modify(smbldap_state,
4400                             smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry),
4401                             mods);
4402
4403         /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4404          * please retry" */
4405
4406         status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4407
4408  done:
4409         if (NT_STATUS_IS_OK(status)) {
4410                 *rid = nextRid;
4411         }
4412
4413         TALLOC_FREE(mem_ctx);
4414         return status;
4415 }
4416
4417 static BOOL ldapsam_new_rid(struct pdb_methods *methods, uint32 *rid)
4418 {
4419         int i;
4420
4421         for (i=0; i<10; i++) {
4422                 NTSTATUS result = ldapsam_get_new_rid(methods->private_data,
4423                                                       rid);
4424                 if (NT_STATUS_IS_OK(result)) {
4425                         return True;
4426                 }
4427
4428                 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4429                         return False;
4430                 }
4431
4432                 /* The ldap update failed (maybe a race condition), retry */
4433         }
4434
4435         /* Tried 10 times, fail. */
4436         return False;
4437 }
4438
4439 static BOOL ldapsam_sid_to_id(struct pdb_methods *methods,
4440                               const DOM_SID *sid,
4441                               union unid_t *id, enum SID_NAME_USE *type)
4442 {
4443         struct ldapsam_privates *priv = methods->private_data;
4444         char *filter;
4445         const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4446                                 NULL };
4447         LDAPMessage *result = NULL;
4448         LDAPMessage *entry = NULL;
4449         BOOL ret = False;
4450         char *value;
4451         int rc;
4452
4453         TALLOC_CTX *mem_ctx;
4454
4455         mem_ctx = talloc_new(NULL);
4456         if (mem_ctx == NULL) {
4457                 DEBUG(0, ("talloc_new failed\n"));
4458                 return False;
4459         }
4460
4461         filter = talloc_asprintf(mem_ctx,
4462                                  "(&(sambaSid=%s)"
4463                                  "(|(objectClass=sambaGroupMapping)"
4464                                  "(objectClass=sambaSamAccount)))",
4465                                  sid_string_static(sid));
4466         if (filter == NULL) {
4467                 DEBUG(5, ("talloc_asprintf failed\n"));
4468                 goto done;
4469         }
4470
4471         rc = smbldap_search_suffix(priv->smbldap_state, filter,
4472                                    attrs, &result);
4473         if (rc != LDAP_SUCCESS) {
4474                 goto done;
4475         }
4476         talloc_autofree_ldapmsg(mem_ctx, result);
4477
4478         if (ldap_count_entries(priv2ld(priv), result) != 1) {
4479                 DEBUG(10, ("Got %d entries, expected one\n",
4480                            ldap_count_entries(priv2ld(priv), result)));
4481                 goto done;
4482         }
4483
4484         entry = ldap_first_entry(priv2ld(priv), result);
4485
4486         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4487                                                 "sambaGroupType", mem_ctx);
4488
4489         if (value != NULL) {
4490                 const char *gid_str;
4491                 /* It's a group */
4492
4493                 gid_str = smbldap_talloc_single_attribute(
4494                         priv2ld(priv), entry, "gidNumber", mem_ctx);
4495                 if (gid_str == NULL) {
4496                         DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4497                                   smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4498                                                     entry)));
4499                         goto done;
4500                 }
4501
4502                 id->gid = strtoul(gid_str, NULL, 10);
4503                 *type = strtoul(value, NULL, 10);
4504                 ret = True;
4505                 goto done;
4506         }
4507
4508         /* It must be a user */
4509
4510         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4511                                                 "uidNumber", mem_ctx);
4512         if (value == NULL) {
4513                 DEBUG(1, ("Could not find uidNumber in %s\n",
4514                           smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4515                 goto done;
4516         }
4517
4518         id->uid = strtoul(value, NULL, 10);
4519         *type = SID_NAME_USER;
4520
4521         ret = True;
4522  done:
4523         TALLOC_FREE(mem_ctx);
4524         return ret;
4525 }
4526
4527 /**********************************************************************
4528  Housekeeping
4529  *********************************************************************/
4530
4531 static void free_private_data(void **vp) 
4532 {
4533         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
4534
4535         smbldap_free_struct(&(*ldap_state)->smbldap_state);
4536
4537         if ((*ldap_state)->result != NULL) {
4538                 ldap_msgfree((*ldap_state)->result);
4539                 (*ldap_state)->result = NULL;
4540         }
4541         if ((*ldap_state)->domain_dn != NULL) {
4542                 SAFE_FREE((*ldap_state)->domain_dn);
4543         }
4544
4545         *ldap_state = NULL;
4546
4547         /* No need to free any further, as it is talloc()ed */
4548 }
4549
4550 /*********************************************************************
4551  Intitalise the parts of the pdb_methods structure that are common to 
4552  all pdb_ldap modes
4553 *********************************************************************/
4554
4555 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
4556 {
4557         NTSTATUS nt_status;
4558         struct ldapsam_privates *ldap_state;
4559
4560         if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
4561                 return nt_status;
4562         }
4563
4564         (*pdb_method)->name = "ldapsam";
4565
4566         (*pdb_method)->setsampwent = ldapsam_setsampwent;
4567         (*pdb_method)->endsampwent = ldapsam_endsampwent;
4568         (*pdb_method)->getsampwent = ldapsam_getsampwent;
4569         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
4570         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
4571         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
4572         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
4573         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
4574         (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
4575
4576         (*pdb_method)->getgrsid = ldapsam_getgrsid;
4577         (*pdb_method)->getgrgid = ldapsam_getgrgid;
4578         (*pdb_method)->getgrnam = ldapsam_getgrnam;
4579         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
4580         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
4581         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
4582         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
4583
4584         (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
4585         (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
4586
4587         (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
4588
4589         (*pdb_method)->rid_algorithm = ldapsam_rid_algorithm;
4590         (*pdb_method)->new_rid = ldapsam_new_rid;
4591
4592         /* TODO: Setup private data and free */
4593
4594         if ( !(ldap_state = TALLOC_ZERO_P(*pdb_method, struct ldapsam_privates)) ) {
4595                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
4596                 return NT_STATUS_NO_MEMORY;
4597         }
4598
4599         nt_status = smbldap_init(*pdb_method, location, &ldap_state->smbldap_state);
4600
4601         if ( !NT_STATUS_IS_OK(nt_status) ) {
4602                 return nt_status;
4603         }
4604
4605         if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
4606                 return NT_STATUS_NO_MEMORY;
4607         }
4608
4609         (*pdb_method)->private_data = ldap_state;
4610
4611         (*pdb_method)->free_private_data = free_private_data;
4612
4613         return NT_STATUS_OK;
4614 }
4615
4616 /**********************************************************************
4617  Initialise the 'compat' mode for pdb_ldap
4618  *********************************************************************/
4619
4620 NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
4621 {
4622         NTSTATUS nt_status;
4623         struct ldapsam_privates *ldap_state;
4624         char *uri = talloc_strdup( NULL, location );
4625
4626 #ifdef WITH_LDAP_SAMCONFIG
4627         if (!uri) {
4628                 int ldap_port = lp_ldap_port();
4629                         
4630                 /* remap default port if not using SSL (ie clear or TLS) */
4631                 if ( (lp_ldap_ssl() != LDAP_SSL_ON) && (ldap_port == 636) ) {
4632                         ldap_port = 389;
4633                 }
4634
4635                 uri = talloc_asprintf(NULL, "%s://%s:%d", lp_ldap_ssl() == LDAP_SSL_ON ? "ldaps" : "ldap", lp_ldap_server(), ldap_port);
4636                 if (!uri) {
4637                         return NT_STATUS_NO_MEMORY;
4638                 }
4639                 location = uri;
4640         }
4641 #endif
4642
4643         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common( pdb_method, uri ))) {
4644                 return nt_status;
4645         }
4646
4647         /* the module itself stores a copy of the location so throw this one away */
4648
4649         if ( uri )
4650                 TALLOC_FREE( uri );
4651
4652         (*pdb_method)->name = "ldapsam_compat";
4653
4654         ldap_state = (*pdb_method)->private_data;
4655         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
4656
4657         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
4658
4659         return NT_STATUS_OK;
4660 }
4661
4662 /**********************************************************************
4663  Initialise the normal mode for pdb_ldap
4664  *********************************************************************/
4665
4666 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
4667 {
4668         NTSTATUS nt_status;
4669         struct ldapsam_privates *ldap_state;
4670         uint32 alg_rid_base;
4671         pstring alg_rid_base_string;
4672         LDAPMessage *result = NULL;
4673         LDAPMessage *entry = NULL;
4674         DOM_SID ldap_domain_sid;
4675         DOM_SID secrets_domain_sid;
4676         pstring domain_sid_string;
4677         char *dn;
4678
4679         nt_status = pdb_init_ldapsam_common(pdb_method, location);
4680         if (!NT_STATUS_IS_OK(nt_status)) {
4681                 return nt_status;
4682         }
4683
4684         (*pdb_method)->name = "ldapsam";
4685
4686         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
4687         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
4688         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
4689         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
4690         (*pdb_method)->search_users = ldapsam_search_users;
4691         (*pdb_method)->search_groups = ldapsam_search_groups;
4692         (*pdb_method)->search_aliases = ldapsam_search_aliases;
4693
4694         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
4695                 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
4696                 (*pdb_method)->enum_group_memberships =
4697                         ldapsam_enum_group_memberships;
4698                 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
4699                 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
4700         }
4701
4702         ldap_state = (*pdb_method)->private_data;
4703         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
4704
4705         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
4706         
4707         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
4708                                                &result, 
4709                                                ldap_state->domain_name, True);
4710         
4711         if ( !NT_STATUS_IS_OK(nt_status) ) {
4712                 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain "
4713                           "info, nor add one to the domain\n"));
4714                 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, "
4715                              "will be unable to allocate new users/groups, "
4716                              "and will risk BDCs having inconsistant SIDs\n"));
4717                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
4718                 return NT_STATUS_OK;
4719         }
4720
4721         /* Given that the above might fail, everything below this must be
4722          * optional */
4723         
4724         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
4725                                  result);
4726         if (!entry) {
4727                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
4728                           "entry\n"));
4729                 ldap_msgfree(result);
4730                 return NT_STATUS_UNSUCCESSFUL;
4731         }
4732
4733         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
4734         if (!dn) {
4735                 return NT_STATUS_UNSUCCESSFUL;
4736         }
4737
4738         ldap_state->domain_dn = smb_xstrdup(dn);
4739         ldap_memfree(dn);
4740
4741         if (smbldap_get_single_pstring(
4742                     ldap_state->smbldap_state->ldap_struct,
4743                     entry, 
4744                     get_userattr_key2string(ldap_state->schema_ver,
4745                                             LDAP_ATTR_USER_SID), 
4746                     domain_sid_string)) {
4747                 BOOL found_sid;
4748                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
4749                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
4750                                   "read as a valid SID\n", domain_sid_string));
4751                         return NT_STATUS_INVALID_PARAMETER;
4752                 }
4753                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
4754                                                      &secrets_domain_sid);
4755                 if (!found_sid || !sid_equal(&secrets_domain_sid,
4756                                              &ldap_domain_sid)) {
4757                         fstring new_sid_str, old_sid_str;
4758                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
4759                                   "%s based on pdb_ldap results %s -> %s\n",
4760                                   ldap_state->domain_name,
4761                                   sid_to_string(old_sid_str,
4762                                                 &secrets_domain_sid),
4763                                   sid_to_string(new_sid_str,
4764                                                 &ldap_domain_sid)));
4765                         
4766                         /* reset secrets.tdb sid */
4767                         secrets_store_domain_sid(ldap_state->domain_name,
4768                                                  &ldap_domain_sid);
4769                         DEBUG(1, ("New global sam SID: %s\n",
4770                                   sid_to_string(new_sid_str,
4771                                                 get_global_sam_sid())));
4772                 }
4773                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
4774         }
4775
4776         if (smbldap_get_single_pstring(
4777                     ldap_state->smbldap_state->ldap_struct,
4778                     entry, 
4779                     get_attr_key2string( dominfo_attr_list,
4780                                          LDAP_ATTR_ALGORITHMIC_RID_BASE ),
4781                     alg_rid_base_string)) {
4782                 alg_rid_base = (uint32)atol(alg_rid_base_string);
4783                 if (alg_rid_base != algorithmic_rid_base()) {
4784                         DEBUG(0, ("The value of 'algorithmic RID base' has "
4785                                   "changed since the LDAP\n"
4786                                   "database was initialised.  Aborting. \n"));
4787                         ldap_msgfree(result);
4788                         return NT_STATUS_UNSUCCESSFUL;
4789                 }
4790         }
4791         ldap_msgfree(result);
4792
4793         return NT_STATUS_OK;
4794 }
4795
4796 NTSTATUS pdb_ldap_init(void)
4797 {
4798         NTSTATUS nt_status;
4799         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
4800                 return nt_status;
4801
4802         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
4803                 return nt_status;
4804
4805         /* Let pdb_nds register backends */
4806         pdb_nds_init();
4807
4808         return NT_STATUS_OK;
4809 }