r8787: Make enumeration of builtin-aliases work again.
[ira/wip.git] / source3 / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/CIFS implementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Jean François Micouleau        1998
5    Copyright (C) Gerald Carter                  2001-2003
6    Copyright (C) Shahms King                    2001
7    Copyright (C) Andrew Bartlett                2002-2003
8    Copyright (C) Stefan (metze) Metzmacher      2002-2003
9     
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/SAM_ACCOUNT
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 #ifndef SAM_ACCOUNT
81 #define SAM_ACCOUNT struct sam_passwd
82 #endif
83
84 #include "smbldap.h"
85
86 /**********************************************************************
87  Free a LDAPMessage (one is stored on the SAM_ACCOUNT).
88  **********************************************************************/
89  
90 void private_data_free_fn(void **result) 
91 {
92         ldap_msgfree(*result);
93         *result = NULL;
94 }
95
96 /**********************************************************************
97  Get the attribute name given a user schame version.
98  **********************************************************************/
99  
100 static const char* get_userattr_key2string( int schema_ver, int key )
101 {
102         switch ( schema_ver ) {
103                 case SCHEMAVER_SAMBAACCOUNT:
104                         return get_attr_key2string( attrib_map_v22, key );
105                         
106                 case SCHEMAVER_SAMBASAMACCOUNT:
107                         return get_attr_key2string( attrib_map_v30, key );
108                         
109                 default:
110                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
111                         break;
112         }
113         return NULL;
114 }
115
116 /**********************************************************************
117  Return the list of attribute names given a user schema version.
118 **********************************************************************/
119
120 const char** get_userattr_list( int schema_ver )
121 {
122         switch ( schema_ver ) {
123                 case SCHEMAVER_SAMBAACCOUNT:
124                         return get_attr_list( attrib_map_v22 );
125                         
126                 case SCHEMAVER_SAMBASAMACCOUNT:
127                         return get_attr_list( attrib_map_v30 );
128                 default:
129                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
130                         break;
131         }
132         
133         return NULL;
134 }
135
136 /**************************************************************************
137  Return the list of attribute names to delete given a user schema version.
138 **************************************************************************/
139
140 static const char** get_userattr_delete_list( int schema_ver )
141 {
142         switch ( schema_ver ) {
143                 case SCHEMAVER_SAMBAACCOUNT:
144                         return get_attr_list( attrib_map_to_delete_v22 );
145                         
146                 case SCHEMAVER_SAMBASAMACCOUNT:
147                         return get_attr_list( attrib_map_to_delete_v30 );
148                 default:
149                         DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
150                         break;
151         }
152         
153         return NULL;
154 }
155
156
157 /*******************************************************************
158  Generate the LDAP search filter for the objectclass based on the 
159  version of the schema we are using.
160 ******************************************************************/
161
162 static const char* get_objclass_filter( int schema_ver )
163 {
164         static fstring objclass_filter;
165         
166         switch( schema_ver ) {
167                 case SCHEMAVER_SAMBAACCOUNT:
168                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
169                         break;
170                 case SCHEMAVER_SAMBASAMACCOUNT:
171                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
172                         break;
173                 default:
174                         DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
175                         break;
176         }
177         
178         return objclass_filter; 
179 }
180
181 /*******************************************************************
182  Run the search by name.
183 ******************************************************************/
184
185 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state, 
186                                           const char *user,
187                                           LDAPMessage ** result,
188                                           const char **attr)
189 {
190         pstring filter;
191         char *escape_user = escape_ldap_string_alloc(user);
192
193         if (!escape_user) {
194                 return LDAP_NO_MEMORY;
195         }
196
197         /*
198          * in the filter expression, replace %u with the real name
199          * so in ldap filter, %u MUST exist :-)
200          */
201         pstr_sprintf(filter, "(&%s%s)", "(uid=%u)", 
202                 get_objclass_filter(ldap_state->schema_ver));
203
204         /* 
205          * have to use this here because $ is filtered out
206            * in pstring_sub
207          */
208         
209
210         all_string_sub(filter, "%u", escape_user, sizeof(pstring));
211         SAFE_FREE(escape_user);
212
213         return smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
214 }
215
216 /*******************************************************************
217  Run the search by rid.
218 ******************************************************************/
219
220 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state, 
221                                          uint32 rid, LDAPMessage ** result, 
222                                          const char **attr)
223 {
224         pstring filter;
225         int rc;
226
227         pstr_sprintf(filter, "(&(rid=%i)%s)", rid, 
228                 get_objclass_filter(ldap_state->schema_ver));
229         
230         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
231         
232         return rc;
233 }
234
235 /*******************************************************************
236  Run the search by SID.
237 ******************************************************************/
238
239 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state, 
240                                          const DOM_SID *sid, LDAPMessage ** result, 
241                                          const char **attr)
242 {
243         pstring filter;
244         int rc;
245         fstring sid_string;
246
247         pstr_sprintf(filter, "(&(%s=%s)%s)", 
248                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
249                 sid_to_string(sid_string, sid), 
250                 get_objclass_filter(ldap_state->schema_ver));
251                 
252         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
253         
254         return rc;
255 }
256
257 /*******************************************************************
258  Delete complete object or objectclass and attrs from
259  object found in search_result depending on lp_ldap_delete_dn
260 ******************************************************************/
261
262 static NTSTATUS ldapsam_delete_entry(struct ldapsam_privates *ldap_state,
263                                      LDAPMessage *result,
264                                      const char *objectclass,
265                                      const char **attrs)
266 {
267         int rc;
268         LDAPMessage *entry = NULL;
269         LDAPMod **mods = NULL;
270         char *name, *dn;
271         BerElement *ptr = NULL;
272
273         rc = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
274
275         if (rc != 1) {
276                 DEBUG(0, ("ldapsam_delete_entry: Entry must exist exactly once!\n"));
277                 return NT_STATUS_UNSUCCESSFUL;
278         }
279
280         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
281         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
282         if (!dn) {
283                 return NT_STATUS_UNSUCCESSFUL;
284         }
285
286         if (lp_ldap_delete_dn()) {
287                 NTSTATUS ret = NT_STATUS_OK;
288                 rc = smbldap_delete(ldap_state->smbldap_state, dn);
289
290                 if (rc != LDAP_SUCCESS) {
291                         DEBUG(0, ("ldapsam_delete_entry: Could not delete object %s\n", dn));
292                         ret = NT_STATUS_UNSUCCESSFUL;
293                 }
294                 SAFE_FREE(dn);
295                 return ret;
296         }
297
298         /* Ok, delete only the SAM attributes */
299         
300         for (name = ldap_first_attribute(ldap_state->smbldap_state->ldap_struct, entry, &ptr);
301              name != NULL;
302              name = ldap_next_attribute(ldap_state->smbldap_state->ldap_struct, entry, ptr)) {
303                 const char **attrib;
304
305                 /* We are only allowed to delete the attributes that
306                    really exist. */
307
308                 for (attrib = attrs; *attrib != NULL; attrib++) {
309                         /* Don't delete LDAP_ATTR_MOD_TIMESTAMP attribute. */
310                         if (strequal(*attrib, get_userattr_key2string(ldap_state->schema_ver,
311                                                 LDAP_ATTR_MOD_TIMESTAMP))) {
312                                 continue;
313                         }
314                         if (strequal(*attrib, name)) {
315                                 DEBUG(10, ("ldapsam_delete_entry: deleting "
316                                            "attribute %s\n", name));
317                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
318                                                 NULL);
319                         }
320                 }
321
322                 ldap_memfree(name);
323         }
324         
325         if (ptr != NULL) {
326                 ber_free(ptr, 0);
327         }
328         
329         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
330
331         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
332         ldap_mods_free(mods, True);
333
334         if (rc != LDAP_SUCCESS) {
335                 char *ld_error = NULL;
336                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
337                                 &ld_error);
338                 
339                 DEBUG(0, ("ldapsam_delete_entry: Could not delete attributes for %s, error: %s (%s)\n",
340                           dn, ldap_err2string(rc), ld_error?ld_error:"unknown"));
341                 SAFE_FREE(ld_error);
342                 SAFE_FREE(dn);
343                 return NT_STATUS_UNSUCCESSFUL;
344         }
345
346         SAFE_FREE(dn);
347         return NT_STATUS_OK;
348 }
349                   
350 /* New Interface is being implemented here */
351
352 #if 0   /* JERRY - not uesed anymore */
353
354 /**********************************************************************
355 Initialize SAM_ACCOUNT from an LDAP query (unix attributes only)
356 *********************************************************************/
357 static BOOL get_unix_attributes (struct ldapsam_privates *ldap_state, 
358                                 SAM_ACCOUNT * sampass,
359                                 LDAPMessage * entry,
360                                 gid_t *gid)
361 {
362         pstring  homedir;
363         pstring  temp;
364         char **ldap_values;
365         char **values;
366
367         if ((ldap_values = ldap_get_values (ldap_state->smbldap_state->ldap_struct, entry, "objectClass")) == NULL) {
368                 DEBUG (1, ("get_unix_attributes: no objectClass! \n"));
369                 return False;
370         }
371
372         for (values=ldap_values;*values;values++) {
373                 if (strequal(*values, LDAP_OBJ_POSIXACCOUNT )) {
374                         break;
375                 }
376         }
377         
378         if (!*values) { /*end of array, no posixAccount */
379                 DEBUG(10, ("user does not have %s attributes\n", LDAP_OBJ_POSIXACCOUNT));
380                 ldap_value_free(ldap_values);
381                 return False;
382         }
383         ldap_value_free(ldap_values);
384
385         if ( !smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
386                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_UNIX_HOME), homedir) ) 
387         {
388                 return False;
389         }
390         
391         if ( !smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
392                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_GIDNUMBER), temp) )
393         {
394                 return False;
395         }
396         
397         *gid = (gid_t)atol(temp);
398
399         pdb_set_unix_homedir(sampass, homedir, PDB_SET);
400         
401         DEBUG(10, ("user has %s attributes\n", LDAP_OBJ_POSIXACCOUNT));
402         
403         return True;
404 }
405
406 #endif
407
408 static time_t ldapsam_get_entry_timestamp(
409         struct ldapsam_privates *ldap_state,
410         LDAPMessage * entry)
411 {
412         pstring temp;   
413         struct tm tm;
414
415         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
416                         get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
417                         temp))
418                 return (time_t) 0;
419
420         strptime(temp, "%Y%m%d%H%M%SZ", &tm);
421         tzset();
422         return timegm(&tm);
423 }
424
425 /**********************************************************************
426  Initialize SAM_ACCOUNT from an LDAP query.
427  (Based on init_sam_from_buffer in pdb_tdb.c)
428 *********************************************************************/
429
430 static BOOL init_sam_from_ldap(struct ldapsam_privates *ldap_state, 
431                                 SAM_ACCOUNT * sampass,
432                                 LDAPMessage * entry)
433 {
434         time_t  logon_time,
435                         logoff_time,
436                         kickoff_time,
437                         pass_last_set_time, 
438                         pass_can_change_time, 
439                         pass_must_change_time,
440                         ldap_entry_time,
441                         bad_password_time;
442         pstring         username, 
443                         domain,
444                         nt_username,
445                         fullname,
446                         homedir,
447                         dir_drive,
448                         logon_script,
449                         profile_path,
450                         acct_desc,
451                         workstations;
452         char            munged_dial[2048];
453         uint32          user_rid; 
454         uint8           smblmpwd[LM_HASH_LEN],
455                         smbntpwd[NT_HASH_LEN];
456         BOOL            use_samba_attrs = True;
457         uint16          acct_ctrl = 0, 
458                         logon_divs;
459         uint16          bad_password_count = 0, 
460                         logon_count = 0;
461         uint32 hours_len;
462         uint8           hours[MAX_HOURS_LEN];
463         pstring temp;
464         LOGIN_CACHE     *cache_entry = NULL;
465         uint32          pwHistLen;
466         pstring         tmpstring;
467
468         /*
469          * do a little initialization
470          */
471         username[0]     = '\0';
472         domain[0]       = '\0';
473         nt_username[0]  = '\0';
474         fullname[0]     = '\0';
475         homedir[0]      = '\0';
476         dir_drive[0]    = '\0';
477         logon_script[0] = '\0';
478         profile_path[0] = '\0';
479         acct_desc[0]    = '\0';
480         munged_dial[0]  = '\0';
481         workstations[0] = '\0';
482          
483
484         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
485                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
486                 return False;
487         }
488
489         if (ldap_state->smbldap_state->ldap_struct == NULL) {
490                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->ldap_struct is NULL!\n"));
491                 return False;
492         }
493         
494         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, "uid", username)) {
495                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for this user!\n"));
496                 return False;
497         }
498
499         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
500
501         pstrcpy(nt_username, username);
502
503         pstrcpy(domain, ldap_state->domain_name);
504         
505         pdb_set_username(sampass, username, PDB_SET);
506
507         pdb_set_domain(sampass, domain, PDB_DEFAULT);
508         pdb_set_nt_username(sampass, nt_username, PDB_SET);
509
510         /* deal with different attributes between the schema first */
511         
512         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
513                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
514                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), temp)) {
515                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
516                 }
517                 
518                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
519                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_SID), temp)) {
520                         pdb_set_group_sid_from_string(sampass, temp, PDB_SET);                  
521                 } else {
522                         pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
523                 }
524         } else {
525                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
526                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), temp)) {
527                         user_rid = (uint32)atol(temp);
528                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
529                 }
530                 
531                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
532                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_RID), temp)) {
533                         pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
534                 } else {
535                         uint32 group_rid;
536                         
537                         group_rid = (uint32)atol(temp);
538                         
539                         /* for some reason, we often have 0 as a primary group RID.
540                            Make sure that we treat this just as a 'default' value */
541                            
542                         if ( group_rid > 0 )
543                                 pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
544                         else
545                                 pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
546                 }
547         }
548
549         if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
550                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
551                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
552                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
553                         username));
554                 return False;
555         }
556
557         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
558                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), temp)) {
559                 /* leave as default */
560         } else {
561                 pass_last_set_time = (time_t) atol(temp);
562                 pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
563         }
564
565         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
566                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp)) {
567                 /* leave as default */
568         } else {
569                 logon_time = (time_t) atol(temp);
570                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
571         }
572
573         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
574                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp)) {
575                 /* leave as default */
576         } else {
577                 logoff_time = (time_t) atol(temp);
578                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
579         }
580
581         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
582                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp)) {
583                 /* leave as default */
584         } else {
585                 kickoff_time = (time_t) atol(temp);
586                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
587         }
588
589         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
590                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp)) {
591                 /* leave as default */
592         } else {
593                 pass_can_change_time = (time_t) atol(temp);
594                 pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
595         }
596
597         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
598                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp)) {    
599                 /* leave as default */
600         } else {
601                 pass_must_change_time = (time_t) atol(temp);
602                 pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
603         }
604
605         /* recommend that 'gecos' and 'displayName' should refer to the same
606          * attribute OID.  userFullName depreciated, only used by Samba
607          * primary rules of LDAP: don't make a new attribute when one is already defined
608          * that fits your needs; using cn then displayName rather than 'userFullName'
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_DISPLAY_NAME), fullname)) {
613                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
614                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_CN), fullname)) {
615                         /* leave as default */
616                 } else {
617                         pdb_set_fullname(sampass, fullname, PDB_SET);
618                 }
619         } else {
620                 pdb_set_fullname(sampass, fullname, PDB_SET);
621         }
622
623         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
624                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), dir_drive)) 
625         {
626                 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
627         } else {
628                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
629         }
630
631         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
632                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), homedir)) 
633         {
634                 pdb_set_homedir( sampass, 
635                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_home()),
636                         PDB_DEFAULT );
637         } else {
638                 pstrcpy( tmpstring, homedir );
639                 standard_sub_basic( username, tmpstring, sizeof(tmpstring) );
640                 pdb_set_homedir(sampass, tmpstring, PDB_SET);
641         }
642
643         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
644                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), logon_script)) 
645         {
646                 pdb_set_logon_script( sampass, 
647                         talloc_sub_basic(sampass->mem_ctx, username, lp_logon_script()), 
648                         PDB_DEFAULT );
649         } else {
650                 pstrcpy( tmpstring, logon_script );
651                 standard_sub_basic( username, tmpstring, sizeof(tmpstring) );
652                 pdb_set_logon_script(sampass, tmpstring, PDB_SET);
653         }
654
655         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
656                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), profile_path)) 
657         {
658                 pdb_set_profile_path( sampass, 
659                         talloc_sub_basic( sampass->mem_ctx, username, lp_logon_path()),
660                         PDB_DEFAULT );
661         } else {
662                 pstrcpy( tmpstring, profile_path );
663                 standard_sub_basic( username, tmpstring, sizeof(tmpstring) );
664                 pdb_set_profile_path(sampass, tmpstring, PDB_SET);
665         }
666
667         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
668                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), acct_desc)) 
669         {
670                 /* leave as default */
671         } else {
672                 pdb_set_acct_desc(sampass, acct_desc, 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_USER_WKS), workstations)) {
677                 /* leave as default */;
678         } else {
679                 pdb_set_workstations(sampass, workstations, PDB_SET);
680         }
681
682         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
683                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), munged_dial, sizeof(munged_dial))) {
684                 /* leave as default */;
685         } else {
686                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
687         }
688         
689         /* FIXME: hours stuff should be cleaner */
690         
691         logon_divs = 168;
692         hours_len = 21;
693         memset(hours, 0xff, hours_len);
694
695         if (ldap_state->is_nds_ldap) {
696                 char *user_dn;
697                 int pwd_len;
698                 char clear_text_pw[512];
699
700                 /* Make call to Novell eDirectory ldap extension to get clear text password.
701                         NOTE: This will only work if we have an SSL connection to eDirectory. */
702                 user_dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
703                 if (user_dn != NULL) {
704                         DEBUG(3, ("init_sam_from_ldap: smbldap_get_dn(%s) returned '%s'\n", username, user_dn));
705
706                         pwd_len = sizeof(clear_text_pw);
707                         if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
708                                 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
709                                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
710                                         return False;
711                                 ZERO_STRUCT(smblmpwd);
712                                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
713                                         return False;
714                                 ZERO_STRUCT(smbntpwd);
715                                 use_samba_attrs = False;
716                         }
717                 } else {
718                         DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
719                 }
720         }
721
722         if (use_samba_attrs) {
723                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry, 
724                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), temp)) {
725                         /* leave as default */
726                 } else {
727                         pdb_gethexpwd(temp, smblmpwd);
728                         memset((char *)temp, '\0', strlen(temp)+1);
729                         if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
730                                 return False;
731                         ZERO_STRUCT(smblmpwd);
732                 }
733
734                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
735                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), temp)) {
736                         /* leave as default */
737                 } else {
738                         pdb_gethexpwd(temp, smbntpwd);
739                         memset((char *)temp, '\0', strlen(temp)+1);
740                         if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
741                                 return False;
742                         ZERO_STRUCT(smbntpwd);
743                 }
744         }
745
746         account_policy_get(AP_PASSWORD_HISTORY, &pwHistLen);
747         if (pwHistLen > 0){
748                 uint8 *pwhist = NULL;
749                 int i;
750
751                 /* We can only store (sizeof(pstring)-1)/64 password history entries. */
752                 pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
753
754                 if ((pwhist = SMB_MALLOC(pwHistLen * PW_HISTORY_ENTRY_LEN)) == NULL){
755                         DEBUG(0, ("init_sam_from_ldap: malloc failed!\n"));
756                         return False;
757                 }
758                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
759
760                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry, 
761                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), temp)) {
762                         /* leave as default - zeros */
763                 } else {
764                         BOOL hex_failed = False;
765                         for (i = 0; i < pwHistLen; i++){
766                                 /* Get the 16 byte salt. */
767                                 if (!pdb_gethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
768                                         hex_failed = True;
769                                         break;
770                                 }
771                                 /* Get the 16 byte MD5 hash of salt+passwd. */
772                                 if (!pdb_gethexpwd(&temp[(i*64)+32],
773                                                 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN])) {
774                                         hex_failed = True;
775                                         break;
776                                 }
777                         }
778                         if (hex_failed) {
779                                 DEBUG(0,("init_sam_from_ldap: Failed to get password history for user %s\n",
780                                         username));
781                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
782                         }
783                 }
784                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
785                         SAFE_FREE(pwhist);
786                         return False;
787                 }
788                 SAFE_FREE(pwhist);
789         }
790
791         if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
792                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), temp)) {
793                 acct_ctrl |= ACB_NORMAL;
794         } else {
795                 acct_ctrl = pdb_decode_acct_ctrl(temp);
796
797                 if (acct_ctrl == 0)
798                         acct_ctrl |= ACB_NORMAL;
799
800                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
801         }
802
803         pdb_set_hours_len(sampass, hours_len, PDB_SET);
804         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
805
806         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
807                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_COUNT), temp)) {
808                         /* leave as default */
809         } else {
810                 bad_password_count = (uint32) atol(temp);
811                 pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
812         }
813
814         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
815                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_TIME), temp)) {
816                 /* leave as default */
817         } else {
818                 bad_password_time = (time_t) atol(temp);
819                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
820         }
821
822
823         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
824                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_COUNT), temp)) {
825                         /* leave as default */
826         } else {
827                 logon_count = (uint32) atol(temp);
828                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
829         }
830
831         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
832
833         if(!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
834                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_HOURS), temp)) {
835                         /* leave as default */
836         } else {
837                 pdb_gethexhours(temp, hours);
838                 memset((char *)temp, '\0', strlen(temp) +1);
839                 pdb_set_hours(sampass, hours, PDB_SET);
840                 ZERO_STRUCT(hours);
841         }
842
843         /* check the timestamp of the cache vs ldap entry */
844         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state, 
845                                                             entry)))
846                 return True;
847
848         /* see if we have newer updates */
849         if (!(cache_entry = login_cache_read(sampass))) {
850                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
851                            (unsigned int)pdb_get_bad_password_count(sampass),
852                            (unsigned int)pdb_get_bad_password_time(sampass)));
853                 return True;
854         }
855
856         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n", 
857                   (unsigned int)ldap_entry_time, (unsigned int)cache_entry->entry_timestamp, 
858                   (unsigned int)cache_entry->bad_password_time));
859
860         if (ldap_entry_time > cache_entry->entry_timestamp) {
861                 /* cache is older than directory , so
862                    we need to delete the entry but allow the 
863                    fields to be written out */
864                 login_cache_delentry(sampass);
865         } else {
866                 /* read cache in */
867                 pdb_set_acct_ctrl(sampass, 
868                                   pdb_get_acct_ctrl(sampass) | 
869                                   (cache_entry->acct_ctrl & ACB_AUTOLOCK),
870                                   PDB_SET);
871                 pdb_set_bad_password_count(sampass, 
872                                            cache_entry->bad_password_count, 
873                                            PDB_SET);
874                 pdb_set_bad_password_time(sampass, 
875                                           cache_entry->bad_password_time, 
876                                           PDB_SET);
877         }
878
879         SAFE_FREE(cache_entry);
880         return True;
881 }
882
883 /**********************************************************************
884  Initialize the ldap db from a SAM_ACCOUNT. Called on update.
885  (Based on init_buffer_from_sam in pdb_tdb.c)
886 *********************************************************************/
887
888 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state, 
889                                 LDAPMessage *existing,
890                                 LDAPMod *** mods, SAM_ACCOUNT * sampass,
891                                 BOOL (*need_update)(const SAM_ACCOUNT *,
892                                                     enum pdb_elements))
893 {
894         pstring temp;
895         uint32 rid;
896
897         if (mods == NULL || sampass == NULL) {
898                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
899                 return False;
900         }
901
902         *mods = NULL;
903
904         /* 
905          * took out adding "objectclass: sambaAccount"
906          * do this on a per-mod basis
907          */
908         if (need_update(sampass, PDB_USERNAME))
909                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
910                               "uid", pdb_get_username(sampass));
911
912         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
913
914         /* only update the RID if we actually need to */
915         if (need_update(sampass, PDB_USERSID)) {
916                 fstring sid_string;
917                 fstring dom_sid_string;
918                 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
919                 
920                 switch ( ldap_state->schema_ver ) {
921                         case SCHEMAVER_SAMBAACCOUNT:
922                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
923                                         DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
924                                                 sid_to_string(sid_string, user_sid), 
925                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
926                                         return False;
927                                 }
928                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
929                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
930                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
931                                         temp);
932                                 break;
933                                 
934                         case SCHEMAVER_SAMBASAMACCOUNT:
935                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
936                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
937                                         sid_to_string(sid_string, user_sid));                                 
938                                 break;
939                                 
940                         default:
941                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
942                                 break;
943                 }               
944         }
945
946         /* we don't need to store the primary group RID - so leaving it
947            'free' to hang off the unix primary group makes life easier */
948
949         if (need_update(sampass, PDB_GROUPSID)) {
950                 fstring sid_string;
951                 fstring dom_sid_string;
952                 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
953                 
954                 switch ( ldap_state->schema_ver ) {
955                         case SCHEMAVER_SAMBAACCOUNT:
956                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
957                                         DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
958                                                 sid_to_string(sid_string, group_sid),
959                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
960                                         return False;
961                                 }
962
963                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
964                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
965                                         get_userattr_key2string(ldap_state->schema_ver, 
966                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
967                                 break;
968                                 
969                         case SCHEMAVER_SAMBASAMACCOUNT:
970                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
971                                         get_userattr_key2string(ldap_state->schema_ver, 
972                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_string(sid_string, group_sid));
973                                 break;
974                                 
975                         default:
976                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
977                                 break;
978                 }
979                 
980         }
981         
982         /* displayName, cn, and gecos should all be the same
983          *  most easily accomplished by giving them the same OID
984          *  gecos isn't set here b/c it should be handled by the 
985          *  add-user script
986          *  We change displayName only and fall back to cn if
987          *  it does not exist.
988          */
989
990         if (need_update(sampass, PDB_FULLNAME))
991                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
992                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
993                         pdb_get_fullname(sampass));
994
995         if (need_update(sampass, PDB_ACCTDESC))
996                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
997                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
998                         pdb_get_acct_desc(sampass));
999
1000         if (need_update(sampass, PDB_WORKSTATIONS))
1001                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1002                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
1003                         pdb_get_workstations(sampass));
1004         
1005         if (need_update(sampass, PDB_MUNGEDDIAL))
1006                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1007                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
1008                         pdb_get_munged_dial(sampass));
1009         
1010         if (need_update(sampass, PDB_SMBHOME))
1011                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1012                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
1013                         pdb_get_homedir(sampass));
1014                         
1015         if (need_update(sampass, PDB_DRIVE))
1016                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1017                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
1018                         pdb_get_dir_drive(sampass));
1019
1020         if (need_update(sampass, PDB_LOGONSCRIPT))
1021                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1022                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1023                         pdb_get_logon_script(sampass));
1024
1025         if (need_update(sampass, PDB_PROFILE))
1026                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1027                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1028                         pdb_get_profile_path(sampass));
1029
1030         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
1031         if (need_update(sampass, PDB_LOGONTIME))
1032                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1033                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1034
1035         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
1036         if (need_update(sampass, PDB_LOGOFFTIME))
1037                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1038                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1039
1040         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
1041         if (need_update(sampass, PDB_KICKOFFTIME))
1042                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1043                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1044
1045         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
1046         if (need_update(sampass, PDB_CANCHANGETIME))
1047                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1048                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1049
1050         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
1051         if (need_update(sampass, PDB_MUSTCHANGETIME))
1052                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1053                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1054
1055
1056         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1057                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1058
1059                 if (need_update(sampass, PDB_LMPASSWD)) {
1060                         const uchar *lm_pw =  pdb_get_lanman_passwd(sampass);
1061                         if (lm_pw) {
1062                                 pdb_sethexpwd(temp, lm_pw,
1063                                               pdb_get_acct_ctrl(sampass));
1064                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1065                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1066                                                  temp);
1067                         } else {
1068                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1069                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1070                                                  NULL);
1071                         }
1072                 }
1073                 if (need_update(sampass, PDB_NTPASSWD)) {
1074                         const uchar *nt_pw =  pdb_get_nt_passwd(sampass);
1075                         if (nt_pw) {
1076                                 pdb_sethexpwd(temp, nt_pw,
1077                                               pdb_get_acct_ctrl(sampass));
1078                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1079                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1080                                                  temp);
1081                         } else {
1082                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1083                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1084                                                  NULL);
1085                         }
1086                 }
1087
1088                 if (need_update(sampass, PDB_PWHISTORY)) {
1089                         uint32 pwHistLen = 0;
1090                         account_policy_get(AP_PASSWORD_HISTORY, &pwHistLen);
1091                         if (pwHistLen == 0) {
1092                                 /* Remove any password history from the LDAP store. */
1093                                 memset(temp, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1094                                 temp[64] = '\0';
1095                         } else {
1096                                 int i; 
1097                                 uint32 currHistLen = 0;
1098                                 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1099                                 if (pwhist != NULL) {
1100                                         /* We can only store (sizeof(pstring)-1)/64 password history entries. */
1101                                         pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
1102                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1103                                                 /* Store the salt. */
1104                                                 pdb_sethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1105                                                 /* Followed by the md5 hash of salt + md4 hash */
1106                                                 pdb_sethexpwd(&temp[(i*64)+32],
1107                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1108                                                 DEBUG(100, ("temp=%s\n", temp));
1109                                         }
1110                                 } 
1111                         }
1112                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1113                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1114                                          temp);
1115                 }
1116
1117                 if (need_update(sampass, PDB_PASSLASTSET)) {
1118                         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
1119                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1120                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1121                                 temp);
1122                 }
1123         }
1124
1125         if (need_update(sampass, PDB_HOURS)) {
1126                 const uint8 *hours = pdb_get_hours(sampass);
1127                 if (hours) {
1128                         pdb_sethexhours(temp, hours);
1129                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1130                                 existing,
1131                                 mods,
1132                                 get_userattr_key2string(ldap_state->schema_ver,
1133                                                 LDAP_ATTR_LOGON_HOURS),
1134                                 temp);
1135                 }
1136         }
1137
1138         if (need_update(sampass, PDB_ACCTCTRL))
1139                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1140                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1141                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1142
1143         /* password lockout cache: 
1144            - If we are now autolocking or clearing, we write to ldap
1145            - If we are clearing, we delete the cache entry
1146            - If the count is > 0, we update the cache
1147
1148            This even means when autolocking, we cache, just in case the
1149            update doesn't work, and we have to cache the autolock flag */
1150
1151         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1152             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1153                 uint16 badcount = pdb_get_bad_password_count(sampass);
1154                 time_t badtime = pdb_get_bad_password_time(sampass);
1155                 uint32 pol;
1156                 account_policy_get(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1157
1158                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1159                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1160
1161                 if ((badcount >= pol) || (badcount == 0)) {
1162                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1163                                 (unsigned int)badcount, (unsigned int)badtime));
1164                         slprintf (temp, sizeof (temp) - 1, "%li", (long)badcount);
1165                         smbldap_make_mod(
1166                                 ldap_state->smbldap_state->ldap_struct,
1167                                 existing, mods, 
1168                                 get_userattr_key2string(
1169                                         ldap_state->schema_ver, 
1170                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1171                                 temp);
1172
1173                         slprintf (temp, sizeof (temp) - 1, "%li", badtime);
1174                         smbldap_make_mod(
1175                                 ldap_state->smbldap_state->ldap_struct, 
1176                                 existing, mods,
1177                                 get_userattr_key2string(
1178                                         ldap_state->schema_ver, 
1179                                         LDAP_ATTR_BAD_PASSWORD_TIME), 
1180                                 temp);
1181                 }
1182                 if (badcount == 0) {
1183                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1184                         login_cache_delentry(sampass);
1185                 } else {
1186                         LOGIN_CACHE cache_entry;
1187
1188                         cache_entry.entry_timestamp = time(NULL);
1189                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1190                         cache_entry.bad_password_count = badcount;
1191                         cache_entry.bad_password_time = badtime;
1192
1193                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1194                         login_cache_write(sampass, cache_entry);
1195                 }
1196         }
1197
1198         return True;
1199 }
1200
1201 /**********************************************************************
1202  Connect to LDAP server for password enumeration.
1203 *********************************************************************/
1204
1205 static NTSTATUS ldapsam_setsampwent(struct pdb_methods *my_methods, BOOL update, uint16 acb_mask)
1206 {
1207         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1208         int rc;
1209         pstring filter, suffix;
1210         const char **attr_list;
1211         BOOL machine_mask = False, user_mask = False;
1212
1213         pstr_sprintf( filter, "(&%s%s)", "(uid=%u)", 
1214                 get_objclass_filter(ldap_state->schema_ver));
1215         all_string_sub(filter, "%u", "*", sizeof(pstring));
1216
1217         machine_mask    = ((acb_mask != 0) && (acb_mask & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)));
1218         user_mask       = ((acb_mask != 0) && (acb_mask & ACB_NORMAL));
1219
1220         if (machine_mask) {
1221                 pstrcpy(suffix, lp_ldap_machine_suffix());
1222         } else if (user_mask) {
1223                 pstrcpy(suffix, lp_ldap_user_suffix());
1224         } else {
1225                 pstrcpy(suffix, lp_ldap_suffix());
1226         }
1227
1228         DEBUG(10,("ldapsam_setsampwent: LDAP Query for acb_mask 0x%x will use suffix %s\n", 
1229                 acb_mask, suffix));
1230
1231         attr_list = get_userattr_list(ldap_state->schema_ver);
1232         rc = smbldap_search(ldap_state->smbldap_state, suffix, LDAP_SCOPE_SUBTREE, filter, 
1233                             attr_list, 0, &ldap_state->result);
1234         free_attr_list( attr_list );
1235
1236         if (rc != LDAP_SUCCESS) {
1237                 DEBUG(0, ("ldapsam_setsampwent: LDAP search failed: %s\n", ldap_err2string(rc)));
1238                 DEBUG(3, ("ldapsam_setsampwent: Query was: %s, %s\n", suffix, filter));
1239                 ldap_msgfree(ldap_state->result);
1240                 ldap_state->result = NULL;
1241                 return NT_STATUS_UNSUCCESSFUL;
1242         }
1243
1244         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base %s\n",
1245                 ldap_count_entries(ldap_state->smbldap_state->ldap_struct, 
1246                 ldap_state->result), suffix));
1247
1248         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
1249                                  ldap_state->result);
1250         ldap_state->index = 0;
1251
1252         return NT_STATUS_OK;
1253 }
1254
1255 /**********************************************************************
1256  End enumeration of the LDAP password list.
1257 *********************************************************************/
1258
1259 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1260 {
1261         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1262         if (ldap_state->result) {
1263                 ldap_msgfree(ldap_state->result);
1264                 ldap_state->result = NULL;
1265         }
1266 }
1267
1268 /**********************************************************************
1269 Get the next entry in the LDAP password database.
1270 *********************************************************************/
1271
1272 static NTSTATUS ldapsam_getsampwent(struct pdb_methods *my_methods, SAM_ACCOUNT *user)
1273 {
1274         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1275         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1276         BOOL bret = False;
1277
1278         while (!bret) {
1279                 if (!ldap_state->entry)
1280                         return ret;
1281                 
1282                 ldap_state->index++;
1283                 bret = init_sam_from_ldap(ldap_state, user, ldap_state->entry);
1284                 
1285                 ldap_state->entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
1286                                             ldap_state->entry); 
1287         }
1288
1289         return NT_STATUS_OK;
1290 }
1291
1292 static void append_attr(const char ***attr_list, const char *new_attr)
1293 {
1294         int i;
1295
1296         if (new_attr == NULL) {
1297                 return;
1298         }
1299
1300         for (i=0; (*attr_list)[i] != NULL; i++) {
1301                 ;
1302         }
1303
1304         (*attr_list) = SMB_REALLOC_ARRAY((*attr_list), const char *,  i+2);
1305         SMB_ASSERT((*attr_list) != NULL);
1306         (*attr_list)[i] = SMB_STRDUP(new_attr);
1307         (*attr_list)[i+1] = NULL;
1308 }
1309
1310 /**********************************************************************
1311 Get SAM_ACCOUNT entry from LDAP by username.
1312 *********************************************************************/
1313
1314 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, SAM_ACCOUNT *user, const char *sname)
1315 {
1316         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1317         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1318         LDAPMessage *result = NULL;
1319         LDAPMessage *entry = NULL;
1320         int count;
1321         const char ** attr_list;
1322         int rc;
1323         
1324         attr_list = get_userattr_list( ldap_state->schema_ver );
1325         append_attr(&attr_list, get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP));
1326         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result, attr_list);
1327         free_attr_list( attr_list );
1328
1329         if ( rc != LDAP_SUCCESS ) 
1330                 return NT_STATUS_NO_SUCH_USER;
1331         
1332         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1333         
1334         if (count < 1) {
1335                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1336                 ldap_msgfree(result);
1337                 return NT_STATUS_NO_SUCH_USER;
1338         } else if (count > 1) {
1339                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1340                 ldap_msgfree(result);
1341                 return NT_STATUS_NO_SUCH_USER;
1342         }
1343
1344         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1345         if (entry) {
1346                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1347                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1348                         ldap_msgfree(result);
1349                         return NT_STATUS_NO_SUCH_USER;
1350                 }
1351                 pdb_set_backend_private_data(user, result, 
1352                                              private_data_free_fn, 
1353                                              my_methods, PDB_CHANGED);
1354                 ret = NT_STATUS_OK;
1355         } else {
1356                 ldap_msgfree(result);
1357         }
1358         return ret;
1359 }
1360
1361 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1362                                    const DOM_SID *sid, LDAPMessage **result) 
1363 {
1364         int rc = -1;
1365         const char ** attr_list;
1366         uint32 rid;
1367
1368         switch ( ldap_state->schema_ver ) {
1369                 case SCHEMAVER_SAMBASAMACCOUNT:
1370                         attr_list = get_userattr_list(ldap_state->schema_ver);
1371                         append_attr(&attr_list, get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP));
1372                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid, result, attr_list);
1373                         free_attr_list( attr_list );
1374
1375                         if ( rc != LDAP_SUCCESS ) 
1376                                 return rc;
1377                         break;
1378                         
1379                 case SCHEMAVER_SAMBAACCOUNT:
1380                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1381                                 return rc;
1382                         }
1383                 
1384                         attr_list = get_userattr_list(ldap_state->schema_ver);
1385                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1386                         free_attr_list( attr_list );
1387
1388                         if ( rc != LDAP_SUCCESS ) 
1389                                 return rc;
1390                         break;
1391         }
1392         return rc;
1393 }
1394
1395 /**********************************************************************
1396  Get SAM_ACCOUNT entry from LDAP by SID.
1397 *********************************************************************/
1398
1399 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, SAM_ACCOUNT * user, const DOM_SID *sid)
1400 {
1401         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1402         LDAPMessage *result = NULL;
1403         LDAPMessage *entry = NULL;
1404         int count;
1405         int rc;
1406         fstring sid_string;
1407
1408         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1409                                           sid, &result); 
1410         if (rc != LDAP_SUCCESS)
1411                 return NT_STATUS_NO_SUCH_USER;
1412
1413         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1414         
1415         if (count < 1) {
1416                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] count=%d\n", sid_to_string(sid_string, sid),
1417                        count));
1418                 ldap_msgfree(result);
1419                 return NT_STATUS_NO_SUCH_USER;
1420         }  else if (count > 1) {
1421                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID [%s]. Failing. count=%d\n", sid_to_string(sid_string, sid),
1422                        count));
1423                 ldap_msgfree(result);
1424                 return NT_STATUS_NO_SUCH_USER;
1425         }
1426
1427         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1428         if (!entry) {
1429                 ldap_msgfree(result);
1430                 return NT_STATUS_NO_SUCH_USER;
1431         }
1432
1433         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1434                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1435                 ldap_msgfree(result);
1436                 return NT_STATUS_NO_SUCH_USER;
1437         }
1438
1439         pdb_set_backend_private_data(user, result, 
1440                                      private_data_free_fn, 
1441                                      my_methods, PDB_CHANGED);
1442         return NT_STATUS_OK;
1443 }       
1444
1445 static BOOL ldapsam_can_pwchange_exop(struct smbldap_state *ldap_state)
1446 {
1447         return smbldap_has_extension(ldap_state, LDAP_EXOP_MODIFY_PASSWD);
1448 }
1449
1450 /********************************************************************
1451  Do the actual modification - also change a plaintext passord if 
1452  it it set.
1453 **********************************************************************/
1454
1455 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1456                                      SAM_ACCOUNT *newpwd, char *dn,
1457                                      LDAPMod **mods, int ldap_op, 
1458                                      BOOL (*need_update)(const SAM_ACCOUNT *, enum pdb_elements))
1459 {
1460         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1461         int rc;
1462         
1463         if (!my_methods || !newpwd || !dn) {
1464                 return NT_STATUS_INVALID_PARAMETER;
1465         }
1466         
1467         if (!mods) {
1468                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1469                 /* may be password change below however */
1470         } else {
1471                 switch(ldap_op) {
1472                         case LDAP_MOD_ADD: 
1473                                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1474                                                 "objectclass", 
1475                                                 LDAP_OBJ_ACCOUNT);
1476                                 rc = smbldap_add(ldap_state->smbldap_state, 
1477                                                  dn, mods);
1478                                 break;
1479                         case LDAP_MOD_REPLACE: 
1480                                 rc = smbldap_modify(ldap_state->smbldap_state, 
1481                                                     dn ,mods);
1482                                 break;
1483                         default:        
1484                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n", 
1485                                          ldap_op));
1486                                 return NT_STATUS_INVALID_PARAMETER;
1487                 }
1488                 
1489                 if (rc!=LDAP_SUCCESS) {
1490                         char *ld_error = NULL;
1491                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1492                                         &ld_error);
1493                         DEBUG(1, ("ldapsam_modify_entry: Failed to %s user dn= %s with: %s\n\t%s\n",
1494                                ldap_op == LDAP_MOD_ADD ? "add" : "modify",
1495                                dn, ldap_err2string(rc),
1496                                ld_error?ld_error:"unknown"));
1497                         SAFE_FREE(ld_error);
1498                         return NT_STATUS_UNSUCCESSFUL;
1499                 }  
1500         }
1501         
1502         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1503                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1504                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1505                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1506                 BerElement *ber;
1507                 struct berval *bv;
1508                 char *retoid = NULL;
1509                 struct berval *retdata = NULL;
1510                 char *utf8_password;
1511                 char *utf8_dn;
1512
1513                 if (!ldap_state->is_nds_ldap) {
1514                         if (!ldapsam_can_pwchange_exop(ldap_state->smbldap_state)) {
1515                                 DEBUG(2, ("ldap password change requested, but LDAP "
1516                                           "server does not support it -- ignoring\n"));
1517                                 return NT_STATUS_OK;
1518                         }
1519                 }
1520
1521                 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1522                         return NT_STATUS_NO_MEMORY;
1523                 }
1524
1525                 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1526                         return NT_STATUS_NO_MEMORY;
1527                 }
1528
1529                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1530                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1531                         SAFE_FREE(utf8_password);
1532                         return NT_STATUS_UNSUCCESSFUL;
1533                 }
1534
1535                 ber_printf (ber, "{");
1536                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn);
1537                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password);
1538                 ber_printf (ber, "N}");
1539
1540                 if ((rc = ber_flatten (ber, &bv))<0) {
1541                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1542                         ber_free(ber,1);
1543                         SAFE_FREE(utf8_dn);
1544                         SAFE_FREE(utf8_password);
1545                         return NT_STATUS_UNSUCCESSFUL;
1546                 }
1547                 
1548                 SAFE_FREE(utf8_dn);
1549                 SAFE_FREE(utf8_password);
1550                 ber_free(ber, 1);
1551
1552                 if (!ldap_state->is_nds_ldap) {
1553                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1554                                                         LDAP_EXOP_MODIFY_PASSWD,
1555                                                         bv, NULL, NULL, &retoid, 
1556                                                         &retdata);
1557                 } else {
1558                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1559                                                         pdb_get_plaintext_passwd(newpwd));
1560                 }
1561                 if (rc != LDAP_SUCCESS) {
1562                         char *ld_error = NULL;
1563
1564                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1565                                 DEBUG(3, ("Could not set userPassword "
1566                                           "attribute due to an objectClass "
1567                                           "violation -- ignoring\n"));
1568                                 ber_bvfree(bv);
1569                                 return NT_STATUS_OK;
1570                         }
1571
1572                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1573                                         &ld_error);
1574                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1575                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1576                         SAFE_FREE(ld_error);
1577                         ber_bvfree(bv);
1578                         return NT_STATUS_UNSUCCESSFUL;
1579                 } else {
1580                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1581 #ifdef DEBUG_PASSWORD
1582                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1583 #endif    
1584                         if (retdata)
1585                                 ber_bvfree(retdata);
1586                         if (retoid)
1587                                 ber_memfree(retoid);
1588                 }
1589                 ber_bvfree(bv);
1590         }
1591         return NT_STATUS_OK;
1592 }
1593
1594 /**********************************************************************
1595  Delete entry from LDAP for username.
1596 *********************************************************************/
1597
1598 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * sam_acct)
1599 {
1600         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1601         const char *sname;
1602         int rc;
1603         LDAPMessage *result = NULL;
1604         NTSTATUS ret;
1605         const char **attr_list;
1606         fstring objclass;
1607
1608         if (!sam_acct) {
1609                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1610                 return NT_STATUS_INVALID_PARAMETER;
1611         }
1612
1613         sname = pdb_get_username(sam_acct);
1614
1615         DEBUG (3, ("ldapsam_delete_sam_account: Deleting user %s from LDAP.\n", sname));
1616
1617         attr_list= get_userattr_delete_list( ldap_state->schema_ver );
1618         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result, attr_list);
1619
1620         if (rc != LDAP_SUCCESS)  {
1621                 free_attr_list( attr_list );
1622                 return NT_STATUS_NO_SUCH_USER;
1623         }
1624         
1625         switch ( ldap_state->schema_ver ) {
1626                 case SCHEMAVER_SAMBASAMACCOUNT:
1627                         fstrcpy( objclass, LDAP_OBJ_SAMBASAMACCOUNT );
1628                         break;
1629                         
1630                 case SCHEMAVER_SAMBAACCOUNT:
1631                         fstrcpy( objclass, LDAP_OBJ_SAMBAACCOUNT );
1632                         break;
1633                 default:
1634                         fstrcpy( objclass, "UNKNOWN" );
1635                         DEBUG(0,("ldapsam_delete_sam_account: Unknown schema version specified!\n"));
1636                                 break;
1637         }
1638
1639         ret = ldapsam_delete_entry(ldap_state, result, objclass, attr_list );
1640         ldap_msgfree(result);
1641         free_attr_list( attr_list );
1642
1643         return ret;
1644 }
1645
1646 /**********************************************************************
1647  Helper function to determine for update_sam_account whether
1648  we need LDAP modification.
1649 *********************************************************************/
1650
1651 static BOOL element_is_changed(const SAM_ACCOUNT *sampass,
1652                                enum pdb_elements element)
1653 {
1654         return IS_SAM_CHANGED(sampass, element);
1655 }
1656
1657 /**********************************************************************
1658  Update SAM_ACCOUNT.
1659 *********************************************************************/
1660
1661 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * newpwd)
1662 {
1663         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1664         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1665         int rc = 0;
1666         char *dn;
1667         LDAPMessage *result = NULL;
1668         LDAPMessage *entry = NULL;
1669         LDAPMod **mods = NULL;
1670         const char **attr_list;
1671
1672         result = pdb_get_backend_private_data(newpwd, my_methods);
1673         if (!result) {
1674                 attr_list = get_userattr_list(ldap_state->schema_ver);
1675                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1676                 free_attr_list( attr_list );
1677                 if (rc != LDAP_SUCCESS) {
1678                         return NT_STATUS_UNSUCCESSFUL;
1679                 }
1680                 pdb_set_backend_private_data(newpwd, result, private_data_free_fn, my_methods, PDB_CHANGED);
1681         }
1682
1683         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1684                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1685                 return NT_STATUS_UNSUCCESSFUL;
1686         }
1687
1688         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1689         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1690         if (!dn) {
1691                 return NT_STATUS_UNSUCCESSFUL;
1692         }
1693
1694         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1695
1696         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1697                                 element_is_changed)) {
1698                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1699                 SAFE_FREE(dn);
1700                 if (mods != NULL)
1701                         ldap_mods_free(mods,True);
1702                 return NT_STATUS_UNSUCCESSFUL;
1703         }
1704         
1705         if (mods == NULL) {
1706                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1707                          pdb_get_username(newpwd)));
1708                 SAFE_FREE(dn);
1709                 return NT_STATUS_OK;
1710         }
1711         
1712         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1713         ldap_mods_free(mods,True);
1714         SAFE_FREE(dn);
1715
1716         if (!NT_STATUS_IS_OK(ret)) {
1717                 char *ld_error = NULL;
1718                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1719                                 &ld_error);
1720                 DEBUG(0,("ldapsam_update_sam_account: failed to modify user with uid = %s, error: %s (%s)\n",
1721                          pdb_get_username(newpwd), ld_error?ld_error:"(unknwon)", ldap_err2string(rc)));
1722                 SAFE_FREE(ld_error);
1723                 return ret;
1724         }
1725
1726         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1727                   pdb_get_username(newpwd)));
1728         return NT_STATUS_OK;
1729 }
1730
1731 /**********************************************************************
1732  Helper function to determine for update_sam_account whether
1733  we need LDAP modification.
1734  *********************************************************************/
1735
1736 static BOOL element_is_set_or_changed(const SAM_ACCOUNT *sampass,
1737                                       enum pdb_elements element)
1738 {
1739         return (IS_SAM_SET(sampass, element) ||
1740                 IS_SAM_CHANGED(sampass, element));
1741 }
1742
1743 /**********************************************************************
1744  Add SAM_ACCOUNT to LDAP.
1745 *********************************************************************/
1746
1747 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * newpwd)
1748 {
1749         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1750         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1751         int rc;
1752         LDAPMessage     *result = NULL;
1753         LDAPMessage     *entry  = NULL;
1754         pstring         dn;
1755         LDAPMod         **mods = NULL;
1756         int             ldap_op = LDAP_MOD_REPLACE;
1757         uint32          num_result;
1758         const char      **attr_list;
1759         char            *escape_user;
1760         const char      *username = pdb_get_username(newpwd);
1761         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
1762         pstring         filter;
1763         fstring         sid_string;
1764
1765         if (!username || !*username) {
1766                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
1767                 return NT_STATUS_INVALID_PARAMETER;
1768         }
1769
1770         /* free this list after the second search or in case we exit on failure */
1771         attr_list = get_userattr_list(ldap_state->schema_ver);
1772
1773         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
1774
1775         if (rc != LDAP_SUCCESS) {
1776                 free_attr_list( attr_list );
1777                 return NT_STATUS_UNSUCCESSFUL;
1778         }
1779
1780         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1781                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
1782                          username));
1783                 ldap_msgfree(result);
1784                 free_attr_list( attr_list );
1785                 return NT_STATUS_UNSUCCESSFUL;
1786         }
1787         ldap_msgfree(result);
1788         result = NULL;
1789
1790         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
1791                 rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1792                                                   sid, &result); 
1793                 if (rc == LDAP_SUCCESS) {
1794                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1795                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' already in the base, with samba attributes\n", 
1796                                          sid_to_string(sid_string, sid)));
1797                                 free_attr_list( attr_list );
1798                                 ldap_msgfree(result);
1799                                 return NT_STATUS_UNSUCCESSFUL;
1800                         }
1801                         ldap_msgfree(result);
1802                 }
1803         }
1804
1805         /* does the entry already exist but without a samba attributes?
1806            we need to return the samba attributes here */
1807            
1808         escape_user = escape_ldap_string_alloc( username );
1809         pstrcpy( filter, "(uid=%u)" );
1810         all_string_sub( filter, "%u", escape_user, sizeof(filter) );
1811         SAFE_FREE( escape_user );
1812
1813         rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1814                                    filter, attr_list, &result);
1815         if ( rc != LDAP_SUCCESS ) {
1816                 free_attr_list( attr_list );
1817                 return NT_STATUS_UNSUCCESSFUL;
1818         }
1819
1820         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1821         
1822         if (num_result > 1) {
1823                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1824                 free_attr_list( attr_list );
1825                 ldap_msgfree(result);
1826                 return NT_STATUS_UNSUCCESSFUL;
1827         }
1828         
1829         /* Check if we need to update an existing entry */
1830         if (num_result == 1) {
1831                 char *tmp;
1832                 
1833                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1834                 ldap_op = LDAP_MOD_REPLACE;
1835                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1836                 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1837                 if (!tmp) {
1838                         free_attr_list( attr_list );
1839                         ldap_msgfree(result);
1840                         return NT_STATUS_UNSUCCESSFUL;
1841                 }
1842                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1843                 SAFE_FREE(tmp);
1844
1845         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
1846
1847                 /* There might be a SID for this account already - say an idmap entry */
1848
1849                 pstr_sprintf(filter, "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))", 
1850                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1851                          sid_to_string(sid_string, sid),
1852                          LDAP_OBJ_IDMAP_ENTRY,
1853                          LDAP_OBJ_SID_ENTRY);
1854                 
1855                 /* free old result before doing a new search */
1856                 if (result != NULL) {
1857                         ldap_msgfree(result);
1858                         result = NULL;
1859                 }
1860                 rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1861                                            filter, attr_list, &result);
1862                         
1863                 if ( rc != LDAP_SUCCESS ) {
1864                         free_attr_list( attr_list );
1865                         return NT_STATUS_UNSUCCESSFUL;
1866                 }
1867                 
1868                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1869                 
1870                 if (num_result > 1) {
1871                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1872                         free_attr_list( attr_list );
1873                         ldap_msgfree(result);
1874                         return NT_STATUS_UNSUCCESSFUL;
1875                 }
1876                 
1877                 /* Check if we need to update an existing entry */
1878                 if (num_result == 1) {
1879                         char *tmp;
1880                         
1881                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1882                         ldap_op = LDAP_MOD_REPLACE;
1883                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1884                         tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1885                         if (!tmp) {
1886                                 free_attr_list( attr_list );
1887                                 ldap_msgfree(result);
1888                                 return NT_STATUS_UNSUCCESSFUL;
1889                         }
1890                         slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1891                         SAFE_FREE(tmp);
1892                 }
1893         }
1894         
1895         free_attr_list( attr_list );
1896
1897         if (num_result == 0) {
1898                 /* Check if we need to add an entry */
1899                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
1900                 ldap_op = LDAP_MOD_ADD;
1901                 if (username[strlen(username)-1] == '$') {
1902                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_machine_suffix ());
1903                 } else {
1904                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_user_suffix ());
1905                 }
1906         }
1907
1908         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1909                                 element_is_set_or_changed)) {
1910                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
1911                 ldap_msgfree(result);
1912                 if (mods != NULL)
1913                         ldap_mods_free(mods,True);
1914                 return NT_STATUS_UNSUCCESSFUL;          
1915         }
1916         
1917         ldap_msgfree(result);
1918
1919         if (mods == NULL) {
1920                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
1921                 return NT_STATUS_UNSUCCESSFUL;
1922         }
1923         switch ( ldap_state->schema_ver ) {
1924                 case SCHEMAVER_SAMBAACCOUNT:
1925                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
1926                         break;
1927                 case SCHEMAVER_SAMBASAMACCOUNT:
1928                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
1929                         break;
1930                 default:
1931                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
1932                         break;
1933         }
1934
1935         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
1936         if (!NT_STATUS_IS_OK(ret)) {
1937                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
1938                          pdb_get_username(newpwd),dn));
1939                 ldap_mods_free(mods, True);
1940                 return ret;
1941         }
1942
1943         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
1944         ldap_mods_free(mods, True);
1945         
1946         return NT_STATUS_OK;
1947 }
1948
1949 /**********************************************************************
1950  *********************************************************************/
1951
1952 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
1953                                      const char *filter,
1954                                      LDAPMessage ** result)
1955 {
1956         int scope = LDAP_SCOPE_SUBTREE;
1957         int rc;
1958         const char **attr_list;
1959
1960         attr_list = get_attr_list(groupmap_attr_list);
1961         rc = smbldap_search(ldap_state->smbldap_state, 
1962                             lp_ldap_group_suffix (), scope,
1963                             filter, attr_list, 0, result);
1964         free_attr_list( attr_list );
1965
1966         if (rc != LDAP_SUCCESS) {
1967                 char *ld_error = NULL;
1968                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1969                                 &ld_error);
1970                 DEBUG(0, ("ldapsam_search_one_group: "
1971                           "Problem during the LDAP search: LDAP error: %s (%s)\n",
1972                           ld_error?ld_error:"(unknown)", ldap_err2string(rc)));
1973                 DEBUGADD(3, ("ldapsam_search_one_group: Query was: %s, %s\n",
1974                           lp_ldap_group_suffix(), filter));
1975                 SAFE_FREE(ld_error);
1976         }
1977
1978         return rc;
1979 }
1980
1981 /**********************************************************************
1982  *********************************************************************/
1983
1984 static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
1985                                  GROUP_MAP *map, LDAPMessage *entry)
1986 {
1987         pstring temp;
1988
1989         if (ldap_state == NULL || map == NULL || entry == NULL ||
1990                         ldap_state->smbldap_state->ldap_struct == NULL) {
1991                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
1992                 return False;
1993         }
1994
1995         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
1996                         get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER), temp)) {
1997                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
1998                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
1999                 return False;
2000         }
2001         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2002
2003         map->gid = (gid_t)atol(temp);
2004
2005         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2006                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID), temp)) {
2007                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2008                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2009                 return False;
2010         }
2011         
2012         if (!string_to_sid(&map->sid, temp)) {
2013                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2014                 return False;
2015         }
2016
2017         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2018                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), temp)) {
2019                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2020                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2021                 return False;
2022         }
2023         map->sid_name_use = (enum SID_NAME_USE)atol(temp);
2024
2025         if ((map->sid_name_use < SID_NAME_USER) ||
2026                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2027                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2028                 return False;
2029         }
2030
2031         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2032                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), temp)) {
2033                 temp[0] = '\0';
2034                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2035                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_CN), temp)) 
2036                 {
2037                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2038 for gidNumber(%lu)\n",(unsigned long)map->gid));
2039                         return False;
2040                 }
2041         }
2042         fstrcpy(map->nt_name, temp);
2043
2044         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2045                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), temp)) {
2046                 temp[0] = '\0';
2047         }
2048         fstrcpy(map->comment, temp);
2049
2050         return True;
2051 }
2052
2053 /**********************************************************************
2054  *********************************************************************/
2055
2056 static BOOL init_ldap_from_group(LDAP *ldap_struct,
2057                                  LDAPMessage *existing,
2058                                  LDAPMod ***mods,
2059                                  const GROUP_MAP *map)
2060 {
2061         pstring tmp;
2062
2063         if (mods == NULL || map == NULL) {
2064                 DEBUG(0, ("init_ldap_from_group: NULL parameters found!\n"));
2065                 return False;
2066         }
2067
2068         *mods = NULL;
2069
2070         sid_to_string(tmp, &map->sid);
2071
2072         smbldap_make_mod(ldap_struct, existing, mods, 
2073                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID), tmp);
2074         pstr_sprintf(tmp, "%i", map->sid_name_use);
2075         smbldap_make_mod(ldap_struct, existing, mods, 
2076                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), tmp);
2077
2078         smbldap_make_mod(ldap_struct, existing, mods, 
2079                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), map->nt_name);
2080         smbldap_make_mod(ldap_struct, existing, mods, 
2081                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), map->comment);
2082
2083         return True;
2084 }
2085
2086 /**********************************************************************
2087  *********************************************************************/
2088
2089 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2090                                  const char *filter,
2091                                  GROUP_MAP *map)
2092 {
2093         struct ldapsam_privates *ldap_state =
2094                 (struct ldapsam_privates *)methods->private_data;
2095         LDAPMessage *result = NULL;
2096         LDAPMessage *entry = NULL;
2097         int count;
2098
2099         if (ldapsam_search_one_group(ldap_state, filter, &result)
2100             != LDAP_SUCCESS) {
2101                 return NT_STATUS_NO_SUCH_GROUP;
2102         }
2103
2104         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2105
2106         if (count < 1) {
2107                 DEBUG(4, ("ldapsam_getgroup: Did not find group\n"));
2108                 ldap_msgfree(result);
2109                 return NT_STATUS_NO_SUCH_GROUP;
2110         }
2111
2112         if (count > 1) {
2113                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: count=%d\n",
2114                           filter, count));
2115                 ldap_msgfree(result);
2116                 return NT_STATUS_NO_SUCH_GROUP;
2117         }
2118
2119         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2120
2121         if (!entry) {
2122                 ldap_msgfree(result);
2123                 return NT_STATUS_UNSUCCESSFUL;
2124         }
2125
2126         if (!init_group_from_ldap(ldap_state, map, entry)) {
2127                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for group filter %s\n",
2128                           filter));
2129                 ldap_msgfree(result);
2130                 return NT_STATUS_NO_SUCH_GROUP;
2131         }
2132
2133         ldap_msgfree(result);
2134         return NT_STATUS_OK;
2135 }
2136
2137 /**********************************************************************
2138  *********************************************************************/
2139
2140 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2141                                  DOM_SID sid)
2142 {
2143         pstring filter;
2144
2145         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
2146                 LDAP_OBJ_GROUPMAP, 
2147                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2148                 sid_string_static(&sid));
2149
2150         return ldapsam_getgroup(methods, filter, map);
2151 }
2152
2153 /**********************************************************************
2154  *********************************************************************/
2155
2156 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2157                                  gid_t gid)
2158 {
2159         pstring filter;
2160
2161         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%d))",
2162                 LDAP_OBJ_GROUPMAP,
2163                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2164                 gid);
2165
2166         return ldapsam_getgroup(methods, filter, map);
2167 }
2168
2169 /**********************************************************************
2170  *********************************************************************/
2171
2172 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2173                                  const char *name)
2174 {
2175         pstring filter;
2176         char *escape_name = escape_ldap_string_alloc(name);
2177
2178         if (!escape_name) {
2179                 return NT_STATUS_NO_MEMORY;
2180         }
2181
2182         pstr_sprintf(filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2183                 LDAP_OBJ_GROUPMAP,
2184                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2185                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN), escape_name);
2186
2187         SAFE_FREE(escape_name);
2188
2189         return ldapsam_getgroup(methods, filter, map);
2190 }
2191
2192 static void add_rid_to_array_unique(TALLOC_CTX *mem_ctx,
2193                                     uint32 rid, uint32 **rids, int *num)
2194 {
2195         int i;
2196
2197         for (i=0; i<*num; i++) {
2198                 if ((*rids)[i] == rid)
2199                         return;
2200         }
2201         
2202         *rids = TALLOC_REALLOC_ARRAY(mem_ctx, *rids, uint32, *num+1);
2203
2204         if (*rids == NULL)
2205                 return;
2206
2207         (*rids)[*num] = rid;
2208         *num += 1;
2209 }
2210
2211 static BOOL ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2212                                            LDAPMessage *entry,
2213                                            const DOM_SID *domain_sid,
2214                                            uint32 *rid)
2215 {
2216         fstring str;
2217         DOM_SID sid;
2218
2219         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2220                                           str, sizeof(str)-1)) {
2221                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2222                 return False;
2223         }
2224
2225         if (!string_to_sid(&sid, str)) {
2226                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2227                 return False;
2228         }
2229
2230         if (sid_compare_domain(&sid, domain_sid) != 0) {
2231                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2232                            str, sid_string_static(domain_sid)));
2233                 return False;
2234         }
2235
2236         if (!sid_peek_rid(&sid, rid)) {
2237                 DEBUG(10, ("Could not peek into RID\n"));
2238                 return False;
2239         }
2240
2241         return True;
2242 }
2243
2244 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2245                                            TALLOC_CTX *mem_ctx,
2246                                            const DOM_SID *group,
2247                                            uint32 **member_rids,
2248                                            int *num_members)
2249 {
2250         struct ldapsam_privates *ldap_state =
2251                 (struct ldapsam_privates *)methods->private_data;
2252         struct smbldap_state *conn = ldap_state->smbldap_state;
2253         pstring filter;
2254         int rc, count;
2255         LDAPMessage *msg = NULL;
2256         LDAPMessage *entry;
2257         char **values = NULL;
2258         char **memberuid;
2259         char *sid_filter = NULL;
2260         char *tmp;
2261         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2262
2263         if (!lp_parm_bool(-1, "ldapsam", "trusted", False))
2264                 return pdb_default_enum_group_members(methods, mem_ctx, group,
2265                                                       member_rids,
2266                                                       num_members);
2267
2268         *member_rids = NULL;
2269         *num_members = 0;
2270
2271         pstr_sprintf(filter,
2272                      "(&(objectClass=sambaSamAccount)"
2273                      "(sambaPrimaryGroupSid=%s))",
2274                      sid_string_static(group));
2275
2276         {
2277                 const char *attrs[] = { "sambaSID", NULL };
2278                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2279                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2280                                     &msg);
2281         }
2282
2283         if (rc != LDAP_SUCCESS)
2284                 goto done;
2285
2286         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2287              entry != NULL;
2288              entry = ldap_next_entry(conn->ldap_struct, entry))
2289         {
2290                 uint32 rid;
2291
2292                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2293                                                     entry,
2294                                                     get_global_sam_sid(),
2295                                                     &rid)) {
2296                         DEBUG(2, ("Could not find sid from ldap entry\n"));
2297                         continue;
2298                 }
2299
2300                 add_rid_to_array_unique(mem_ctx, rid, member_rids,
2301                                         num_members);
2302         }
2303
2304         if (msg != NULL)
2305                 ldap_msgfree(msg);
2306
2307         pstr_sprintf(filter,
2308                      "(&(objectClass=sambaGroupMapping)"
2309                      "(objectClass=posixGroup)"
2310                      "(sambaSID=%s))",
2311                      sid_string_static(group));
2312
2313         {
2314                 const char *attrs[] = { "memberUid", NULL };
2315                 rc = smbldap_search(conn, lp_ldap_group_suffix(),
2316                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2317                                     &msg);
2318         }
2319
2320         if (rc != LDAP_SUCCESS)
2321                 goto done;
2322
2323         count = ldap_count_entries(conn->ldap_struct, msg);
2324
2325         if (count > 1) {
2326                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2327                           sid_string_static(group)));
2328                 goto done;
2329         }
2330
2331         if (count == 0) {
2332                 result = NT_STATUS_OK;
2333                 goto done;
2334         }
2335
2336         entry = ldap_first_entry(conn->ldap_struct, msg);
2337         if (entry == NULL)
2338                 goto done;
2339
2340         values = ldap_get_values(conn->ldap_struct, msg, "memberUid");
2341         if (values == NULL) {
2342                 result = NT_STATUS_OK;
2343                 goto done;
2344         }
2345
2346         sid_filter = SMB_STRDUP("(&(objectClass=sambaSamAccount)(|");
2347         if (sid_filter == NULL) {
2348                 result = NT_STATUS_NO_MEMORY;
2349                 goto done;
2350         }
2351
2352         for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2353                 tmp = sid_filter;
2354                 asprintf(&sid_filter, "%s(uid=%s)", tmp, *memberuid);
2355                 free(tmp);
2356                 if (sid_filter == NULL) {
2357                         result = NT_STATUS_NO_MEMORY;
2358                         goto done;
2359                 }
2360         }
2361
2362         tmp = sid_filter;
2363         asprintf(&sid_filter, "%s))", sid_filter);
2364         free(tmp);
2365         if (sid_filter == NULL) {
2366                 result = NT_STATUS_NO_MEMORY;
2367                 goto done;
2368         }
2369
2370         {
2371                 const char *attrs[] = { "sambaSID", NULL };
2372                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2373                                     LDAP_SCOPE_SUBTREE, sid_filter, attrs, 0,
2374                                     &msg);
2375         }
2376
2377         if (rc != LDAP_SUCCESS)
2378                 goto done;
2379
2380         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2381              entry != NULL;
2382              entry = ldap_next_entry(conn->ldap_struct, entry))
2383         {
2384                 fstring str;
2385                 DOM_SID sid;
2386                 uint32 rid;
2387
2388                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2389                                                   entry, "sambaSID",
2390                                                   str, sizeof(str)-1))
2391                         continue;
2392
2393                 if (!string_to_sid(&sid, str))
2394                         goto done;
2395
2396                 if (!sid_check_is_in_our_domain(&sid)) {
2397                         DEBUG(1, ("Inconsistent SAM -- group member uid not "
2398                                   "in our domain\n"));
2399                         continue;
2400                 }
2401
2402                 sid_peek_rid(&sid, &rid);
2403
2404                 add_rid_to_array_unique(mem_ctx, rid, member_rids,
2405                                         num_members);
2406         }
2407
2408         result = NT_STATUS_OK;
2409         
2410  done:
2411         SAFE_FREE(sid_filter);
2412
2413         if (values != NULL)
2414                 ldap_value_free(values);
2415
2416         if (msg != NULL)
2417                 ldap_msgfree(msg);
2418
2419         return result;
2420 }
2421
2422 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2423                                                const char *username,
2424                                                gid_t primary_gid,
2425                                                DOM_SID **sids, gid_t **gids,
2426                                                int *num_groups)
2427 {
2428         struct ldapsam_privates *ldap_state =
2429                 (struct ldapsam_privates *)methods->private_data;
2430         struct smbldap_state *conn = ldap_state->smbldap_state;
2431         pstring filter;
2432         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2433         char *escape_name;
2434         int rc;
2435         LDAPMessage *msg = NULL;
2436         LDAPMessage *entry;
2437         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2438         int num_sids, num_gids;
2439
2440         if (!lp_parm_bool(-1, "ldapsam", "trusted", False))
2441                 return pdb_default_enum_group_memberships(methods, username,
2442                                                           primary_gid, sids,
2443                                                           gids, num_groups);
2444
2445         *sids = NULL;
2446         num_sids = 0;
2447
2448         escape_name = escape_ldap_string_alloc(username);
2449
2450         if (escape_name == NULL)
2451                 return NT_STATUS_NO_MEMORY;
2452
2453         pstr_sprintf(filter, "(&(objectClass=posixGroup)"
2454                      "(|(memberUid=%s)(gidNumber=%d)))",
2455                      username, primary_gid);
2456
2457         rc = smbldap_search(conn, lp_ldap_group_suffix(),
2458                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &msg);
2459
2460         if (rc != LDAP_SUCCESS)
2461                 goto done;
2462
2463         num_gids = 0;
2464         *gids = NULL;
2465
2466         num_sids = 0;
2467         *sids = NULL;
2468
2469         /* We need to add the primary group as the first gid/sid */
2470
2471         add_gid_to_array_unique(NULL, primary_gid, gids, &num_gids);
2472
2473         /* This sid will be replaced later */
2474
2475         add_sid_to_array_unique(NULL, &global_sid_NULL, sids, &num_sids);
2476
2477         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2478              entry != NULL;
2479              entry = ldap_next_entry(conn->ldap_struct, entry))
2480         {
2481                 fstring str;
2482                 DOM_SID sid;
2483                 gid_t gid;
2484                 char *end;
2485
2486                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2487                                                   entry, "sambaSID",
2488                                                   str, sizeof(str)-1))
2489                         continue;
2490
2491                 if (!string_to_sid(&sid, str))
2492                         goto done;
2493
2494                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2495                                                   entry, "gidNumber",
2496                                                   str, sizeof(str)-1))
2497                         continue;
2498
2499                 gid = strtoul(str, &end, 10);
2500
2501                 if (PTR_DIFF(end, str) != strlen(str))
2502                         goto done;
2503
2504                 if (gid == primary_gid) {
2505                         sid_copy(&(*sids)[0], &sid);
2506                 } else {
2507                         add_gid_to_array_unique(NULL, gid, gids, &num_gids);
2508                         add_sid_to_array_unique(NULL, &sid, sids, &num_sids);
2509                 }
2510         }
2511
2512         if (sid_compare(&global_sid_NULL, &(*sids)[0]) == 0) {
2513                 DEBUG(3, ("primary group of [%s] not found\n", username));
2514                 goto done;
2515         }
2516
2517         *num_groups = num_sids;
2518
2519         result = NT_STATUS_OK;
2520
2521  done:
2522
2523         SAFE_FREE(escape_name);
2524         if (msg != NULL)
2525                 ldap_msgfree(msg);
2526
2527         return result;
2528 }
2529
2530 /**********************************************************************
2531  *********************************************************************/
2532
2533 static int ldapsam_search_one_group_by_gid(struct ldapsam_privates *ldap_state,
2534                                            gid_t gid,
2535                                            LDAPMessage **result)
2536 {
2537         pstring filter;
2538
2539         pstr_sprintf(filter, "(&(|(objectClass=%s)(objectclass=%s))(%s=%d))", 
2540                 LDAP_OBJ_POSIXGROUP, LDAP_OBJ_IDMAP_ENTRY,
2541                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2542                 gid);
2543
2544         return ldapsam_search_one_group(ldap_state, filter, result);
2545 }
2546
2547 /**********************************************************************
2548  *********************************************************************/
2549
2550 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
2551                                                 GROUP_MAP *map)
2552 {
2553         struct ldapsam_privates *ldap_state =
2554                 (struct ldapsam_privates *)methods->private_data;
2555         LDAPMessage *result = NULL;
2556         LDAPMod **mods = NULL;
2557         int count;
2558
2559         char *tmp;
2560         pstring dn;
2561         LDAPMessage *entry;
2562
2563         GROUP_MAP dummy;
2564
2565         int rc;
2566
2567         if (NT_STATUS_IS_OK(ldapsam_getgrgid(methods, &dummy,
2568                                              map->gid))) {
2569                 DEBUG(0, ("ldapsam_add_group_mapping_entry: Group %ld already exists in LDAP\n", (unsigned long)map->gid));
2570                 return NT_STATUS_UNSUCCESSFUL;
2571         }
2572
2573         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
2574         if (rc != LDAP_SUCCESS) {
2575                 ldap_msgfree(result);
2576                 return NT_STATUS_UNSUCCESSFUL;
2577         }
2578
2579         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2580
2581         if ( count == 0 ) {
2582                 /* There's no posixGroup account, let's try to find an
2583                  * appropriate idmap entry for aliases */
2584
2585                 pstring suffix;
2586                 pstring filter;
2587                 const char **attr_list;
2588
2589                 ldap_msgfree(result);
2590
2591                 pstrcpy( suffix, lp_ldap_idmap_suffix() );
2592                 pstr_sprintf(filter, "(&(objectClass=%s)(%s=%d))",
2593                              LDAP_OBJ_IDMAP_ENTRY, LDAP_ATTRIBUTE_GIDNUMBER,
2594                              map->gid);
2595                 
2596                 attr_list = get_attr_list( sidmap_attr_list );
2597                 rc = smbldap_search(ldap_state->smbldap_state, suffix,
2598                                     LDAP_SCOPE_SUBTREE, filter, attr_list,
2599                                     0, &result);
2600
2601                 free_attr_list(attr_list);
2602
2603                 if (rc != LDAP_SUCCESS) {
2604                         DEBUG(3,("Failure looking up entry (%s)\n",
2605                                  ldap_err2string(rc) ));
2606                         ldap_msgfree(result);
2607                         return NT_STATUS_UNSUCCESSFUL;
2608                 }
2609         }
2610                            
2611         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2612         if ( count == 0 ) {
2613                 ldap_msgfree(result);
2614                 return NT_STATUS_UNSUCCESSFUL;
2615         }
2616
2617         if (count > 1) {
2618                 DEBUG(2, ("ldapsam_add_group_mapping_entry: Group %lu must exist exactly once in LDAP\n",
2619                           (unsigned long)map->gid));
2620                 ldap_msgfree(result);
2621                 return NT_STATUS_UNSUCCESSFUL;
2622         }
2623
2624         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2625         tmp = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2626         if (!tmp) {
2627                 ldap_msgfree(result);
2628                 return NT_STATUS_UNSUCCESSFUL;
2629         }
2630         pstrcpy(dn, tmp);
2631         SAFE_FREE(tmp);
2632
2633         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
2634                                   result, &mods, map)) {
2635                 DEBUG(0, ("ldapsam_add_group_mapping_entry: init_ldap_from_group failed!\n"));
2636                 ldap_mods_free(mods, True);
2637                 ldap_msgfree(result);
2638                 return NT_STATUS_UNSUCCESSFUL;
2639         }
2640
2641         ldap_msgfree(result);
2642
2643         if (mods == NULL) {
2644                 DEBUG(0, ("ldapsam_add_group_mapping_entry: mods is empty\n"));
2645                 return NT_STATUS_UNSUCCESSFUL;
2646         }
2647
2648         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP );
2649
2650         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2651         ldap_mods_free(mods, True);
2652
2653         if (rc != LDAP_SUCCESS) {
2654                 char *ld_error = NULL;
2655                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2656                                 &ld_error);
2657                 DEBUG(0, ("ldapsam_add_group_mapping_entry: failed to add group %lu error: %s (%s)\n", (unsigned long)map->gid, 
2658                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
2659                 SAFE_FREE(ld_error);
2660                 return NT_STATUS_UNSUCCESSFUL;
2661         }
2662
2663         DEBUG(2, ("ldapsam_add_group_mapping_entry: successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
2664         return NT_STATUS_OK;
2665 }
2666
2667 /**********************************************************************
2668  *********************************************************************/
2669
2670 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
2671                                                    GROUP_MAP *map)
2672 {
2673         struct ldapsam_privates *ldap_state =
2674                 (struct ldapsam_privates *)methods->private_data;
2675         int rc;
2676         char *dn = NULL;
2677         LDAPMessage *result = NULL;
2678         LDAPMessage *entry = NULL;
2679         LDAPMod **mods = NULL;
2680
2681         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
2682
2683         if (rc != LDAP_SUCCESS) {
2684                 return NT_STATUS_UNSUCCESSFUL;
2685         }
2686
2687         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
2688                 DEBUG(0, ("ldapsam_update_group_mapping_entry: No group to modify!\n"));
2689                 ldap_msgfree(result);
2690                 return NT_STATUS_UNSUCCESSFUL;
2691         }
2692
2693         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2694
2695         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
2696                                   result, &mods, map)) {
2697                 DEBUG(0, ("ldapsam_update_group_mapping_entry: init_ldap_from_group failed\n"));
2698                 ldap_msgfree(result);
2699                 if (mods != NULL)
2700                         ldap_mods_free(mods,True);
2701                 return NT_STATUS_UNSUCCESSFUL;
2702         }
2703
2704         if (mods == NULL) {
2705                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: nothing to do\n"));
2706                 ldap_msgfree(result);
2707                 return NT_STATUS_OK;
2708         }
2709
2710         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2711         if (!dn) {
2712                 ldap_msgfree(result);
2713                 return NT_STATUS_UNSUCCESSFUL;
2714         }
2715         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2716         SAFE_FREE(dn);
2717
2718         ldap_mods_free(mods, True);
2719         ldap_msgfree(result);
2720
2721         if (rc != LDAP_SUCCESS) {
2722                 char *ld_error = NULL;
2723                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2724                                 &ld_error);
2725                 DEBUG(0, ("ldapsam_update_group_mapping_entry: failed to modify group %lu error: %s (%s)\n", (unsigned long)map->gid, 
2726                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
2727                 SAFE_FREE(ld_error);
2728                 return NT_STATUS_UNSUCCESSFUL;
2729         }
2730
2731         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
2732         return NT_STATUS_OK;
2733 }
2734
2735 /**********************************************************************
2736  *********************************************************************/
2737
2738 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
2739                                                    DOM_SID sid)
2740 {
2741         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)methods->private_data;
2742         pstring sidstring, filter;
2743         LDAPMessage *result = NULL;
2744         int rc;
2745         NTSTATUS ret;
2746         const char **attr_list;
2747
2748         sid_to_string(sidstring, &sid);
2749         
2750         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))", 
2751                 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID, sidstring);
2752
2753         rc = ldapsam_search_one_group(ldap_state, filter, &result);
2754
2755         if (rc != LDAP_SUCCESS) {
2756                 return NT_STATUS_NO_SUCH_GROUP;
2757         }
2758
2759         attr_list = get_attr_list( groupmap_attr_list_to_delete );
2760         ret = ldapsam_delete_entry(ldap_state, result, LDAP_OBJ_GROUPMAP, attr_list);
2761         free_attr_list ( attr_list );
2762
2763         ldap_msgfree(result);
2764
2765         return ret;
2766 }
2767
2768 /**********************************************************************
2769  *********************************************************************/
2770
2771 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods, BOOL update)
2772 {
2773         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2774         fstring filter;
2775         int rc;
2776         const char **attr_list;
2777
2778         pstr_sprintf( filter, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
2779         attr_list = get_attr_list( groupmap_attr_list );
2780         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
2781                             LDAP_SCOPE_SUBTREE, filter,
2782                             attr_list, 0, &ldap_state->result);
2783         free_attr_list( attr_list );
2784
2785         if (rc != LDAP_SUCCESS) {
2786                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n", ldap_err2string(rc)));
2787                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n", lp_ldap_group_suffix(), filter));
2788                 ldap_msgfree(ldap_state->result);
2789                 ldap_state->result = NULL;
2790                 return NT_STATUS_UNSUCCESSFUL;
2791         }
2792
2793         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
2794                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2795                                      ldap_state->result)));
2796
2797         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, ldap_state->result);
2798         ldap_state->index = 0;
2799
2800         return NT_STATUS_OK;
2801 }
2802
2803 /**********************************************************************
2804  *********************************************************************/
2805
2806 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
2807 {
2808         ldapsam_endsampwent(my_methods);
2809 }
2810
2811 /**********************************************************************
2812  *********************************************************************/
2813
2814 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
2815                                     GROUP_MAP *map)
2816 {
2817         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2818         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2819         BOOL bret = False;
2820
2821         while (!bret) {
2822                 if (!ldap_state->entry)
2823                         return ret;
2824                 
2825                 ldap_state->index++;
2826                 bret = init_group_from_ldap(ldap_state, map, ldap_state->entry);
2827                 
2828                 ldap_state->entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
2829                                             ldap_state->entry); 
2830         }
2831
2832         return NT_STATUS_OK;
2833 }
2834
2835 /**********************************************************************
2836  *********************************************************************/
2837
2838 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
2839                                            enum SID_NAME_USE sid_name_use,
2840                                            GROUP_MAP **rmap, int *num_entries,
2841                                            BOOL unix_only)
2842 {
2843         GROUP_MAP map;
2844         GROUP_MAP *mapt;
2845         int entries = 0;
2846
2847         *num_entries = 0;
2848         *rmap = NULL;
2849
2850         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
2851                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open passdb\n"));
2852                 return NT_STATUS_ACCESS_DENIED;
2853         }
2854
2855         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
2856                 if (sid_name_use != SID_NAME_UNKNOWN &&
2857                     sid_name_use != map.sid_name_use) {
2858                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is not of the requested type\n", map.nt_name));
2859                         continue;
2860                 }
2861                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
2862                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is non mapped\n", map.nt_name));
2863                         continue;
2864                 }
2865
2866                 mapt=SMB_REALLOC_ARRAY((*rmap), GROUP_MAP, entries+1);
2867                 if (!mapt) {
2868                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to enlarge group map!\n"));
2869                         SAFE_FREE(*rmap);
2870                         return NT_STATUS_UNSUCCESSFUL;
2871                 }
2872                 else
2873                         (*rmap) = mapt;
2874
2875                 mapt[entries] = map;
2876
2877                 entries += 1;
2878
2879         }
2880         ldapsam_endsamgrent(methods);
2881
2882         *num_entries = entries;
2883
2884         return NT_STATUS_OK;
2885 }
2886
2887 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
2888                                         const DOM_SID *alias,
2889                                         const DOM_SID *member,
2890                                         int modop)
2891 {
2892         struct ldapsam_privates *ldap_state =
2893                 (struct ldapsam_privates *)methods->private_data;
2894         char *dn;
2895         LDAPMessage *result = NULL;
2896         LDAPMessage *entry = NULL;
2897         int count;
2898         LDAPMod **mods = NULL;
2899         int rc;
2900
2901         pstring filter;
2902
2903         pstr_sprintf(filter, "(&(|(objectClass=%s)(objectclass=%s))(%s=%s))",
2904                      LDAP_OBJ_GROUPMAP, LDAP_OBJ_IDMAP_ENTRY,
2905                      get_attr_key2string(groupmap_attr_list,
2906                                          LDAP_ATTR_GROUP_SID),
2907                      sid_string_static(alias));
2908
2909         if (ldapsam_search_one_group(ldap_state, filter,
2910                                      &result) != LDAP_SUCCESS)
2911                 return NT_STATUS_NO_SUCH_ALIAS;
2912
2913         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2914                                    result);
2915
2916         if (count < 1) {
2917                 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
2918                 ldap_msgfree(result);
2919                 return NT_STATUS_NO_SUCH_ALIAS;
2920         }
2921
2922         if (count > 1) {
2923                 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for filter %s: "
2924                           "count=%d\n", filter, count));
2925                 ldap_msgfree(result);
2926                 return NT_STATUS_NO_SUCH_ALIAS;
2927         }
2928
2929         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
2930                                  result);
2931
2932         if (!entry) {
2933                 ldap_msgfree(result);
2934                 return NT_STATUS_UNSUCCESSFUL;
2935         }
2936
2937         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2938         if (!dn) {
2939                 ldap_msgfree(result);
2940                 return NT_STATUS_UNSUCCESSFUL;
2941         }
2942
2943         smbldap_set_mod(&mods, modop,
2944                         get_attr_key2string(groupmap_attr_list,
2945                                             LDAP_ATTR_SID_LIST),
2946                         sid_string_static(member));
2947
2948         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2949
2950         ldap_mods_free(mods, True);
2951         ldap_msgfree(result);
2952
2953         if (rc != LDAP_SUCCESS) {
2954                 char *ld_error = NULL;
2955                 ldap_get_option(ldap_state->smbldap_state->ldap_struct,
2956                                 LDAP_OPT_ERROR_STRING,&ld_error);
2957                 
2958                 DEBUG(0, ("ldapsam_modify_aliasmem: Could not modify alias "
2959                           "for %s, error: %s (%s)\n", dn, ldap_err2string(rc),
2960                           ld_error?ld_error:"unknown"));
2961                 SAFE_FREE(ld_error);
2962                 SAFE_FREE(dn);
2963                 return NT_STATUS_UNSUCCESSFUL;
2964         }
2965
2966         SAFE_FREE(dn);
2967
2968         return NT_STATUS_OK;
2969 }
2970
2971 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
2972                                      const DOM_SID *alias,
2973                                      const DOM_SID *member)
2974 {
2975         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
2976 }
2977
2978 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
2979                                      const DOM_SID *alias,
2980                                      const DOM_SID *member)
2981 {
2982         return ldapsam_modify_aliasmem(methods, alias, member,
2983                                        LDAP_MOD_DELETE);
2984 }
2985
2986 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
2987                                       const DOM_SID *alias, DOM_SID **members,
2988                                       int *num_members)
2989 {
2990         struct ldapsam_privates *ldap_state =
2991                 (struct ldapsam_privates *)methods->private_data;
2992         LDAPMessage *result = NULL;
2993         LDAPMessage *entry = NULL;
2994         int count;
2995         char **values;
2996         int i;
2997         pstring filter;
2998
2999         *members = NULL;
3000         *num_members = 0;
3001
3002         pstr_sprintf(filter, "(&(|(objectClass=%s)(objectclass=%s))(%s=%s))",
3003                      LDAP_OBJ_GROUPMAP, LDAP_OBJ_IDMAP_ENTRY,
3004                      get_attr_key2string(groupmap_attr_list,
3005                                          LDAP_ATTR_GROUP_SID),
3006                      sid_string_static(alias));
3007
3008         if (ldapsam_search_one_group(ldap_state, filter,
3009                                      &result) != LDAP_SUCCESS)
3010                 return NT_STATUS_NO_SUCH_ALIAS;
3011
3012         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3013                                    result);
3014
3015         if (count < 1) {
3016                 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3017                 ldap_msgfree(result);
3018                 return NT_STATUS_NO_SUCH_ALIAS;
3019         }
3020
3021         if (count > 1) {
3022                 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for filter %s: "
3023                           "count=%d\n", filter, count));
3024                 ldap_msgfree(result);
3025                 return NT_STATUS_NO_SUCH_ALIAS;
3026         }
3027
3028         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3029                                  result);
3030
3031         if (!entry) {
3032                 ldap_msgfree(result);
3033                 return NT_STATUS_UNSUCCESSFUL;
3034         }
3035
3036         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3037                                  entry,
3038                                  get_attr_key2string(groupmap_attr_list,
3039                                                      LDAP_ATTR_SID_LIST));
3040
3041         if (values == NULL) {
3042                 ldap_msgfree(result);
3043                 return NT_STATUS_OK;
3044         }
3045
3046         count = ldap_count_values(values);
3047
3048         for (i=0; i<count; i++) {
3049                 DOM_SID member;
3050
3051                 if (!string_to_sid(&member, values[i]))
3052                         continue;
3053
3054                 add_sid_to_array(NULL, &member, members, num_members);
3055         }
3056
3057         ldap_value_free(values);
3058         ldap_msgfree(result);
3059
3060         return NT_STATUS_OK;
3061 }
3062
3063 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3064                                           TALLOC_CTX *mem_ctx,
3065                                           const DOM_SID *domain_sid,
3066                                           const DOM_SID *members,
3067                                           int num_members,
3068                                           uint32 **alias_rids,
3069                                           int *num_alias_rids)
3070 {
3071         struct ldapsam_privates *ldap_state =
3072                 (struct ldapsam_privates *)methods->private_data;
3073         LDAP *ldap_struct;
3074
3075         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3076
3077         LDAPMessage *result = NULL;
3078         LDAPMessage *entry = NULL;
3079         int i;
3080         int rc;
3081         char *filter;
3082
3083         /* This query could be further optimized by adding a
3084            (&(sambaSID=<domain-sid>*)) so that only those aliases that are
3085            asked for in the getuseraliases are returned. */        
3086
3087         filter = talloc_asprintf(mem_ctx,
3088                                  "(&(|(objectclass=%s)(objectclass=%s))(|",
3089                                  LDAP_OBJ_GROUPMAP, LDAP_OBJ_IDMAP_ENTRY);
3090
3091         for (i=0; i<num_members; i++)
3092                 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3093                                          filter,
3094                                          sid_string_static(&members[i]));
3095
3096         filter = talloc_asprintf(mem_ctx, "%s))", filter);
3097
3098         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3099                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3100
3101         if (rc != LDAP_SUCCESS)
3102                 return NT_STATUS_UNSUCCESSFUL;
3103
3104         ldap_struct = ldap_state->smbldap_state->ldap_struct;
3105
3106         for (entry = ldap_first_entry(ldap_struct, result);
3107              entry != NULL;
3108              entry = ldap_next_entry(ldap_struct, entry))
3109         {
3110                 fstring sid_str;
3111                 DOM_SID sid;
3112                 uint32 rid;
3113
3114                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3115                                                   LDAP_ATTRIBUTE_SID,
3116                                                   sid_str,
3117                                                   sizeof(sid_str)-1))
3118                         continue;
3119
3120                 if (!string_to_sid(&sid, sid_str))
3121                         continue;
3122
3123                 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3124                         continue;
3125
3126                 add_rid_to_array_unique(mem_ctx, rid, alias_rids,
3127                                         num_alias_rids);
3128         }
3129
3130         ldap_msgfree(result);
3131         return NT_STATUS_OK;
3132 }
3133
3134 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3135                                     TALLOC_CTX *mem_ctx,
3136                                     const DOM_SID *domain_sid,
3137                                     int num_rids,
3138                                     uint32 *rids,
3139                                     const char ***names,
3140                                     uint32 **attrs)
3141 {
3142         struct ldapsam_privates *ldap_state =
3143                 (struct ldapsam_privates *)methods->private_data;
3144         LDAP *ldap_struct = ldap_state->smbldap_state->ldap_struct;
3145         LDAPMessage *msg = NULL;
3146         LDAPMessage *entry;
3147         char *allsids = NULL;
3148         char *tmp;
3149         int i, rc, num_mapped;
3150         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
3151
3152         if (!lp_parm_bool(-1, "ldapsam", "trusted", False))
3153                 return pdb_default_lookup_rids(methods, mem_ctx, domain_sid,
3154                                                num_rids, rids, names, attrs);
3155
3156         if (!sid_equal(domain_sid, get_global_sam_sid())) {
3157                 /* TODO: Sooner or later we need to look up BUILTIN rids as
3158                  * well. -- vl */
3159                 goto done;
3160         }
3161
3162         (*names) = TALLOC_ZERO_ARRAY(mem_ctx, const char *, num_rids);
3163         (*attrs) = TALLOC_ARRAY(mem_ctx, uint32, num_rids);
3164
3165         if ((num_rids != 0) && (((*names) == NULL) || ((*attrs) == NULL)))
3166                 return NT_STATUS_NO_MEMORY;
3167
3168         for (i=0; i<num_rids; i++)
3169                 (*attrs)[i] = SID_NAME_UNKNOWN;
3170
3171         allsids = SMB_STRDUP("");
3172         if (allsids == NULL) return NT_STATUS_NO_MEMORY;
3173
3174         for (i=0; i<num_rids; i++) {
3175                 DOM_SID sid;
3176                 sid_copy(&sid, domain_sid);
3177                 sid_append_rid(&sid, rids[i]);
3178                 tmp = allsids;
3179                 asprintf(&allsids, "%s(sambaSid=%s)", allsids,
3180                          sid_string_static(&sid));
3181                 if (allsids == NULL) return NT_STATUS_NO_MEMORY;
3182                 free(tmp);
3183         }
3184
3185         /* First look for users */
3186
3187         {
3188                 char *filter;
3189                 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
3190
3191                 asprintf(&filter, ("(&(objectClass=sambaSamAccount)(|%s))"),
3192                          allsids);
3193                 if (filter == NULL) return NT_STATUS_NO_MEMORY;
3194
3195                 rc = smbldap_search(ldap_state->smbldap_state,
3196                                     lp_ldap_user_suffix(),
3197                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3198                                     &msg);
3199
3200                 SAFE_FREE(filter);
3201         }
3202
3203         if (rc != LDAP_SUCCESS)
3204                 goto done;
3205
3206         num_mapped = 0;
3207
3208         for (entry = ldap_first_entry(ldap_struct, msg);
3209              entry != NULL;
3210              entry = ldap_next_entry(ldap_struct, entry))
3211         {
3212                 uint32 rid;
3213                 int rid_index;
3214                 fstring str;
3215
3216                 if (!ldapsam_extract_rid_from_entry(ldap_struct, entry,
3217                                                     get_global_sam_sid(),
3218                                                     &rid)) {
3219                         DEBUG(2, ("Could not find sid from ldap entry\n"));
3220                         continue;
3221                 }
3222
3223                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3224                                                   "uid", str, sizeof(str)-1)) {
3225                         DEBUG(2, ("Could not retrieve uid attribute\n"));
3226                         continue;
3227                 }
3228
3229                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3230                         if (rid == rids[rid_index])
3231                                 break;
3232                 }
3233
3234                 if (rid_index == num_rids) {
3235                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3236                         continue;
3237                 }
3238
3239                 (*attrs)[rid_index] = SID_NAME_USER;
3240                 (*names)[rid_index] = talloc_strdup(mem_ctx, str);
3241                 if ((*names)[rid_index] == NULL) return NT_STATUS_NO_MEMORY;
3242
3243                 num_mapped += 1;
3244         }
3245
3246         if (num_mapped == num_rids) {
3247                 /* No need to look for groups anymore -- we're done */
3248                 result = NT_STATUS_OK;
3249                 goto done;
3250         }
3251
3252         /* Same game for groups */
3253
3254         {
3255                 char *filter;
3256                 const char *ldap_attrs[] = { "cn", "sambaSid", NULL };
3257
3258                 asprintf(&filter, ("(&(objectClass=sambaGroupMapping)(|%s))"),
3259                          allsids);
3260                 if (filter == NULL) return NT_STATUS_NO_MEMORY;
3261
3262                 rc = smbldap_search(ldap_state->smbldap_state,
3263                                     lp_ldap_group_suffix(),
3264                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3265                                     &msg);
3266
3267                 SAFE_FREE(filter);
3268         }
3269
3270         if (rc != LDAP_SUCCESS)
3271                 goto done;
3272
3273         for (entry = ldap_first_entry(ldap_struct, msg);
3274              entry != NULL;
3275              entry = ldap_next_entry(ldap_struct, entry))
3276         {
3277                 uint32 rid;
3278                 int rid_index;
3279                 fstring str;
3280
3281                 if (!ldapsam_extract_rid_from_entry(ldap_struct, entry,
3282                                                     get_global_sam_sid(),
3283                                                     &rid)) {
3284                         DEBUG(2, ("Could not find sid from ldap entry\n"));
3285                         continue;
3286                 }
3287
3288                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3289                                                   "cn", str, sizeof(str)-1)) {
3290                         DEBUG(2, ("Could not retrieve cn attribute\n"));
3291                         continue;
3292                 }
3293
3294                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3295                         if (rid == rids[rid_index])
3296                                 break;
3297                 }
3298
3299                 if (rid_index == num_rids) {
3300                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3301                         continue;
3302                 }
3303
3304                 (*attrs)[rid_index] = SID_NAME_DOM_GRP;
3305                 (*names)[rid_index] = talloc_strdup(mem_ctx, str);
3306                 if ((*names)[rid_index] == NULL) return NT_STATUS_NO_MEMORY;
3307                 num_mapped += 1;
3308         }
3309
3310         result = NT_STATUS_NONE_MAPPED;
3311
3312         if (num_mapped > 0)
3313                 result = (num_mapped == num_rids) ?
3314                         NT_STATUS_OK : STATUS_SOME_UNMAPPED;
3315  done:
3316         SAFE_FREE(allsids);
3317
3318         if (msg != NULL)
3319                 ldap_msgfree(msg);
3320
3321         return result;
3322 }
3323
3324 char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
3325 {
3326         char *filter = NULL;
3327         char *escaped = NULL;
3328         char *result = NULL;
3329
3330         asprintf(&filter, "(&%s(objectclass=sambaSamAccount))",
3331                  "(uid=%u)");
3332         if (filter == NULL) goto done;
3333
3334         escaped = escape_ldap_string_alloc(username);
3335         if (escaped == NULL) goto done;
3336
3337         filter = realloc_string_sub(filter, "%u", username);
3338         result = talloc_strdup(mem_ctx, filter);
3339
3340  done:
3341         SAFE_FREE(filter);
3342         SAFE_FREE(escaped);
3343
3344         return result;
3345 }
3346
3347 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
3348 {
3349         int i, num = 0;
3350         va_list ap;
3351         const char **result;
3352
3353         va_start(ap, mem_ctx);
3354         while (va_arg(ap, const char *) != NULL)
3355                 num += 1;
3356         va_end(ap);
3357
3358         result = TALLOC_ARRAY(mem_ctx, const char *, num+1);
3359
3360         va_start(ap, mem_ctx);
3361         for (i=0; i<num; i++)
3362                 result[i] = talloc_strdup(mem_ctx, va_arg(ap, const char*));
3363         va_end(ap);
3364
3365         result[num] = NULL;
3366         return result;
3367 }
3368
3369 struct ldap_search_state {
3370         struct smbldap_state *connection;
3371
3372         uint16 acct_flags;
3373         uint16 group_type;
3374
3375         const char *base;
3376         int scope;
3377         const char *filter;
3378         const char **attrs;
3379         int attrsonly;
3380         void *pagedresults_cookie;
3381
3382         LDAPMessage *entries, *current_entry;
3383         BOOL (*ldap2displayentry)(struct ldap_search_state *state,
3384                                   TALLOC_CTX *mem_ctx,
3385                                   LDAP *ld, LDAPMessage *entry,
3386                                   struct samr_displayentry *result);
3387 };
3388
3389 static BOOL ldapsam_search_firstpage(struct pdb_search *search)
3390 {
3391         struct ldap_search_state *state = search->private_data;
3392         LDAP *ld;
3393         int rc = LDAP_OPERATIONS_ERROR;
3394
3395         state->entries = NULL;
3396
3397         if (state->connection->paged_results) {
3398                 rc = smbldap_search_paged(state->connection, state->base,
3399                                           state->scope, state->filter,
3400                                           state->attrs, state->attrsonly,
3401                                           lp_ldap_page_size(), &state->entries,
3402                                           &state->pagedresults_cookie);
3403         }
3404
3405         if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
3406
3407                 if (state->entries != NULL) {
3408                         /* Left over from unsuccessful paged attempt */
3409                         ldap_msgfree(state->entries);
3410                         state->entries = NULL;
3411                 }
3412
3413                 rc = smbldap_search(state->connection, state->base,
3414                                     state->scope, state->filter, state->attrs,
3415                                     state->attrsonly, &state->entries);
3416
3417                 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
3418                         return False;
3419
3420                 /* Ok, the server was lying. It told us it could do paged
3421                  * searches when it could not. */
3422                 state->connection->paged_results = False;
3423         }
3424
3425         ld = state->connection->ldap_struct;
3426         if ( ld == NULL) {
3427                 DEBUG(5, ("Don't have an LDAP connection right after a "
3428                           "search\n"));
3429                 return False;
3430         }
3431         state->current_entry = ldap_first_entry(ld, state->entries);
3432
3433         if (state->current_entry == NULL) {
3434                 ldap_msgfree(state->entries);
3435                 state->entries = NULL;
3436         }
3437
3438         return True;
3439 }
3440
3441 static BOOL ldapsam_search_nextpage(struct pdb_search *search)
3442 {
3443         struct ldap_search_state *state = search->private_data;
3444         LDAP *ld = state->connection->ldap_struct;
3445         int rc;
3446
3447         if (!state->connection->paged_results) {
3448                 /* There is no next page when there are no paged results */
3449                 return False;
3450         }
3451
3452         rc = smbldap_search_paged(state->connection, state->base,
3453                                   state->scope, state->filter, state->attrs,
3454                                   state->attrsonly, lp_ldap_page_size(),
3455                                   &state->entries,
3456                                   &state->pagedresults_cookie);
3457
3458         if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
3459                 return False;
3460
3461         state->current_entry = ldap_first_entry(ld, state->entries);
3462
3463         if (state->current_entry == NULL) {
3464                 ldap_msgfree(state->entries);
3465                 state->entries = NULL;
3466         }
3467
3468         return True;
3469 }
3470
3471 static BOOL ldapsam_search_next_entry(struct pdb_search *search,
3472                                       struct samr_displayentry *entry)
3473 {
3474         struct ldap_search_state *state = search->private_data;
3475         LDAP *ld = state->connection->ldap_struct;
3476         BOOL result;
3477
3478  retry:
3479         if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
3480                 return False;
3481
3482         if ((state->entries == NULL) &&
3483             !ldapsam_search_nextpage(search))
3484                     return False;
3485
3486         result = state->ldap2displayentry(state, search->mem_ctx, ld,
3487                                           state->current_entry, entry);
3488
3489         if (!result) {
3490                 char *dn;
3491                 dn = ldap_get_dn(ld, state->current_entry);
3492                 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
3493                 if (dn != NULL) ldap_memfree(dn);
3494         }
3495
3496         state->current_entry = ldap_next_entry(ld, state->current_entry);
3497
3498         if (state->current_entry == NULL) {
3499                 ldap_msgfree(state->entries);
3500                 state->entries = NULL;
3501         }
3502
3503         if (!result) goto retry;
3504
3505         return True;
3506 }
3507
3508 static void ldapsam_search_end(struct pdb_search *search)
3509 {
3510         struct ldap_search_state *state = search->private_data;
3511         int rc;
3512
3513         if (state->pagedresults_cookie == NULL)
3514                 return;
3515
3516         if (state->entries != NULL)
3517                 ldap_msgfree(state->entries);
3518
3519         state->entries = NULL;
3520         state->current_entry = NULL;
3521
3522         if (!state->connection->paged_results)
3523                 return;
3524
3525         /* Tell the LDAP server we're not interested in the rest anymore. */
3526
3527         rc = smbldap_search_paged(state->connection, state->base, state->scope,
3528                                   state->filter, state->attrs,
3529                                   state->attrsonly, 0, &state->entries,
3530                                   &state->pagedresults_cookie);
3531
3532         if (rc != LDAP_SUCCESS)
3533                 DEBUG(5, ("Could not end search properly\n"));
3534
3535         return;
3536 }
3537
3538 static BOOL ldapuser2displayentry(struct ldap_search_state *state,
3539                                   TALLOC_CTX *mem_ctx,
3540                                   LDAP *ld, LDAPMessage *entry,
3541                                   struct samr_displayentry *result)
3542 {
3543         char **vals;
3544         DOM_SID sid;
3545         uint16 acct_flags;
3546
3547         vals = ldap_get_values(ld, entry, "sambaAcctFlags");
3548         if ((vals == NULL) || (vals[0] == NULL)) {
3549                 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
3550                 return False;
3551         }
3552         acct_flags = pdb_decode_acct_ctrl(vals[0]);
3553         ldap_value_free(vals);
3554
3555         if ((state->acct_flags != 0) &&
3556             ((state->acct_flags & acct_flags) == 0))
3557                 return False;           
3558
3559         result->acct_flags = acct_flags;
3560         result->account_name = "";
3561         result->fullname = "";
3562         result->description = "";
3563
3564         vals = ldap_get_values(ld, entry, "uid");
3565         if ((vals == NULL) || (vals[0] == NULL)) {
3566                 DEBUG(5, ("\"uid\" not found\n"));
3567                 return False;
3568         }
3569         pull_utf8_talloc(mem_ctx,
3570                          CONST_DISCARD(char **, &result->account_name),
3571                          vals[0]);
3572         ldap_value_free(vals);
3573
3574         vals = ldap_get_values(ld, entry, "displayName");
3575         if ((vals == NULL) || (vals[0] == NULL))
3576                 DEBUG(8, ("\"displayName\" not found\n"));
3577         else
3578                 pull_utf8_talloc(mem_ctx,
3579                                  CONST_DISCARD(char **, &result->fullname),
3580                                  vals[0]);
3581         ldap_value_free(vals);
3582
3583         vals = ldap_get_values(ld, entry, "description");
3584         if ((vals == NULL) || (vals[0] == NULL))
3585                 DEBUG(8, ("\"description\" not found\n"));
3586         else
3587                 pull_utf8_talloc(mem_ctx,
3588                                  CONST_DISCARD(char **, &result->description),
3589                                  vals[0]);
3590         ldap_value_free(vals);
3591
3592         if ((result->account_name == NULL) ||
3593             (result->fullname == NULL) ||
3594             (result->description == NULL)) {
3595                 DEBUG(0, ("talloc failed\n"));
3596                 return False;
3597         }
3598         
3599         vals = ldap_get_values(ld, entry, "sambaSid");
3600         if ((vals == NULL) || (vals[0] == NULL)) {
3601                 DEBUG(0, ("\"objectSid\" not found\n"));
3602                 return False;
3603         }
3604
3605         if (!string_to_sid(&sid, vals[0])) {
3606                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
3607                 ldap_value_free(vals);
3608                 return False;
3609         }
3610         ldap_value_free(vals);
3611
3612         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
3613                 DEBUG(0, ("sid %s does not belong to our domain\n", sid_string_static(&sid)));
3614                 return False;
3615         }
3616
3617         return True;
3618 }
3619
3620
3621 static BOOL ldapsam_search_users(struct pdb_methods *methods,
3622                                  struct pdb_search *search,
3623                                  uint16 acct_flags)
3624 {
3625         struct ldapsam_privates *ldap_state = methods->private_data;
3626         struct ldap_search_state *state;
3627
3628         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
3629         if (state == NULL) {
3630                 DEBUG(0, ("talloc failed\n"));
3631                 return False;
3632         }
3633
3634         state->connection = ldap_state->smbldap_state;
3635
3636         if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
3637                 state->base = lp_ldap_user_suffix();
3638         else if ((acct_flags != 0) &&
3639                  ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
3640                 state->base = lp_ldap_machine_suffix();
3641         else
3642                 state->base = lp_ldap_suffix();
3643
3644         state->acct_flags = acct_flags;
3645         state->base = talloc_strdup(search->mem_ctx, state->base);
3646         state->scope = LDAP_SCOPE_SUBTREE;
3647         state->filter = get_ldap_filter(search->mem_ctx, "*");
3648         state->attrs = talloc_attrs(search->mem_ctx, "uid", "sambaSid",
3649                                     "displayName", "description",
3650                                     "sambaAcctFlags", NULL);
3651         state->attrsonly = 0;
3652         state->pagedresults_cookie = NULL;
3653         state->entries = NULL;
3654         state->ldap2displayentry = ldapuser2displayentry;
3655
3656         if ((state->filter == NULL) || (state->attrs == NULL)) {
3657                 DEBUG(0, ("talloc failed\n"));
3658                 return False;
3659         }
3660
3661         search->private_data = state;
3662         search->next_entry = ldapsam_search_next_entry;
3663         search->search_end = ldapsam_search_end;
3664
3665         return ldapsam_search_firstpage(search);
3666 }
3667
3668 static BOOL ldapgroup2displayentry(struct ldap_search_state *state,
3669                                    TALLOC_CTX *mem_ctx,
3670                                    LDAP *ld, LDAPMessage *entry,
3671                                    struct samr_displayentry *result)
3672 {
3673         char **vals;
3674         DOM_SID sid;
3675         uint16 group_type;
3676
3677         result->account_name = "";
3678         result->fullname = "";
3679         result->description = "";
3680
3681
3682         vals = ldap_get_values(ld, entry, "sambaGroupType");
3683         if ((vals == NULL) || (vals[0] == NULL)) {
3684                 DEBUG(5, ("\"sambaGroupType\" not found\n"));
3685                 return False;
3686         }
3687
3688         group_type = atoi(vals[0]);
3689
3690         if ((state->group_type != 0) &&
3691             ((state->group_type != group_type))) {
3692                 return False;
3693         }
3694
3695         vals = ldap_get_values(ld, entry, "cn");
3696         if ((vals == NULL) || (vals[0] == NULL)) {
3697                 DEBUG(5, ("\"cn\" not found\n"));
3698                 return False;
3699         }
3700         pull_utf8_talloc(mem_ctx,
3701                          CONST_DISCARD(char **, &result->account_name),
3702                          vals[0]);
3703         ldap_value_free(vals);
3704
3705         vals = ldap_get_values(ld, entry, "displayName");
3706         if ((vals == NULL) || (vals[0] == NULL))
3707                 DEBUG(8, ("\"displayName\" not found\n"));
3708         else
3709                 pull_utf8_talloc(mem_ctx,
3710                                  CONST_DISCARD(char **, &result->fullname),
3711                                  vals[0]);
3712         ldap_value_free(vals);
3713
3714         vals = ldap_get_values(ld, entry, "description");
3715         if ((vals == NULL) || (vals[0] == NULL))
3716                 DEBUG(8, ("\"description\" not found\n"));
3717         else
3718                 pull_utf8_talloc(mem_ctx,
3719                                  CONST_DISCARD(char **, &result->description),
3720                                  vals[0]);
3721         ldap_value_free(vals);
3722
3723         if ((result->account_name == NULL) ||
3724             (result->fullname == NULL) ||
3725             (result->description == NULL)) {
3726                 DEBUG(0, ("talloc failed\n"));
3727                 return False;
3728         }
3729         
3730         vals = ldap_get_values(ld, entry, "sambaSid");
3731         if ((vals == NULL) || (vals[0] == NULL)) {
3732                 DEBUG(0, ("\"objectSid\" not found\n"));
3733                 return False;
3734         }
3735
3736         if (!string_to_sid(&sid, vals[0])) {
3737                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
3738                 return False;
3739         }
3740
3741         ldap_value_free(vals);
3742
3743         switch (group_type) {
3744                 case SID_NAME_DOM_GRP:
3745                 case SID_NAME_ALIAS:
3746
3747                         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
3748                                 DEBUG(0, ("%s is not in our domain\n", sid_string_static(&sid)));
3749                                 return False;
3750                         }
3751                         break;
3752         
3753                 case SID_NAME_WKN_GRP:
3754
3755                         if (!sid_check_is_in_builtin(&sid)) {
3756                                 DEBUG(0, ("%s is not in builtin sid\n", sid_string_static(&sid)));
3757                                 return False;
3758                         }
3759                         break;
3760
3761                 default:
3762                         DEBUG(0,("unkown group type: %d\n", group_type));
3763                         return False;
3764         }
3765         
3766         return True;
3767 }
3768
3769 static BOOL ldapsam_search_grouptype(struct pdb_methods *methods,
3770                                      struct pdb_search *search,
3771                                      enum SID_NAME_USE type)
3772 {
3773         struct ldapsam_privates *ldap_state = methods->private_data;
3774         struct ldap_search_state *state;
3775
3776         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
3777         if (state == NULL) {
3778                 DEBUG(0, ("talloc failed\n"));
3779                 return False;
3780         }
3781
3782         state->connection = ldap_state->smbldap_state;
3783
3784         state->base = talloc_strdup(search->mem_ctx, lp_ldap_group_suffix());
3785         state->connection = ldap_state->smbldap_state;
3786         state->scope = LDAP_SCOPE_SUBTREE;
3787         state->filter = talloc_asprintf(search->mem_ctx,
3788                                         "(&(objectclass=sambaGroupMapping)"
3789                                         "(sambaGroupType=%d))", type);
3790         state->attrs = talloc_attrs(search->mem_ctx, "cn", "sambaSid",
3791                                     "displayName", "description", "sambaGroupType", NULL);
3792         state->attrsonly = 0;
3793         state->pagedresults_cookie = NULL;
3794         state->entries = NULL;
3795         state->group_type = type;
3796         state->ldap2displayentry = ldapgroup2displayentry;
3797
3798         if ((state->filter == NULL) || (state->attrs == NULL)) {
3799                 DEBUG(0, ("talloc failed\n"));
3800                 return False;
3801         }
3802
3803         search->private_data = state;
3804         search->next_entry = ldapsam_search_next_entry;
3805         search->search_end = ldapsam_search_end;
3806
3807         return ldapsam_search_firstpage(search);
3808 }
3809
3810 static BOOL ldapsam_search_groups(struct pdb_methods *methods,
3811                                   struct pdb_search *search)
3812 {
3813         return ldapsam_search_grouptype(methods, search, SID_NAME_DOM_GRP);
3814 }
3815
3816 static BOOL ldapsam_search_aliases(struct pdb_methods *methods,
3817                                    struct pdb_search *search,
3818                                    const DOM_SID *sid)
3819 {
3820         if (sid_check_is_domain(sid))
3821                 return ldapsam_search_grouptype(methods, search,
3822                                                 SID_NAME_ALIAS);
3823
3824         if (sid_check_is_builtin(sid))
3825                 return ldapsam_search_grouptype(methods, search,
3826                                                 SID_NAME_WKN_GRP);
3827
3828         DEBUG(5, ("Don't know SID %s\n", sid_string_static(sid)));
3829         return False;
3830 }
3831
3832 /**********************************************************************
3833  Housekeeping
3834  *********************************************************************/
3835
3836 static void free_private_data(void **vp) 
3837 {
3838         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
3839
3840         smbldap_free_struct(&(*ldap_state)->smbldap_state);
3841
3842         if ((*ldap_state)->result != NULL) {
3843                 ldap_msgfree((*ldap_state)->result);
3844                 (*ldap_state)->result = NULL;
3845         }
3846         if ((*ldap_state)->domain_dn != NULL) {
3847                 SAFE_FREE((*ldap_state)->domain_dn);
3848         }
3849
3850         *ldap_state = NULL;
3851
3852         /* No need to free any further, as it is talloc()ed */
3853 }
3854
3855 /**********************************************************************
3856  Intitalise the parts of the pdb_context that are common to all pdb_ldap modes
3857  *********************************************************************/
3858
3859 static NTSTATUS pdb_init_ldapsam_common(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, 
3860                                         const char *location)
3861 {
3862         NTSTATUS nt_status;
3863         struct ldapsam_privates *ldap_state;
3864
3865         if (!NT_STATUS_IS_OK(nt_status = make_pdb_methods(pdb_context->mem_ctx, pdb_method))) {
3866                 return nt_status;
3867         }
3868
3869         (*pdb_method)->name = "ldapsam";
3870
3871         (*pdb_method)->setsampwent = ldapsam_setsampwent;
3872         (*pdb_method)->endsampwent = ldapsam_endsampwent;
3873         (*pdb_method)->getsampwent = ldapsam_getsampwent;
3874         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
3875         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
3876         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
3877         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
3878         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
3879
3880         (*pdb_method)->getgrsid = ldapsam_getgrsid;
3881         (*pdb_method)->getgrgid = ldapsam_getgrgid;
3882         (*pdb_method)->getgrnam = ldapsam_getgrnam;
3883         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
3884         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
3885         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
3886         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
3887         (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
3888         (*pdb_method)->enum_group_memberships = ldapsam_enum_group_memberships;
3889         (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
3890
3891         /* TODO: Setup private data and free */
3892
3893         ldap_state = TALLOC_ZERO_P(pdb_context->mem_ctx, struct ldapsam_privates);
3894         if (!ldap_state) {
3895                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
3896                 return NT_STATUS_NO_MEMORY;
3897         }
3898
3899         if (!NT_STATUS_IS_OK(nt_status = 
3900                              smbldap_init(pdb_context->mem_ctx, location, 
3901                                           &ldap_state->smbldap_state)));
3902
3903         ldap_state->domain_name = talloc_strdup(pdb_context->mem_ctx, get_global_sam_name());
3904         if (!ldap_state->domain_name) {
3905                 return NT_STATUS_NO_MEMORY;
3906         }
3907
3908         (*pdb_method)->private_data = ldap_state;
3909
3910         (*pdb_method)->free_private_data = free_private_data;
3911
3912         return NT_STATUS_OK;
3913 }
3914
3915 /**********************************************************************
3916  Initialise the 'compat' mode for pdb_ldap
3917  *********************************************************************/
3918
3919 NTSTATUS pdb_init_ldapsam_compat(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
3920 {
3921         NTSTATUS nt_status;
3922         struct ldapsam_privates *ldap_state;
3923
3924 #ifdef WITH_LDAP_SAMCONFIG
3925         if (!location) {
3926                 int ldap_port = lp_ldap_port();
3927                         
3928                 /* remap default port if not using SSL (ie clear or TLS) */
3929                 if ( (lp_ldap_ssl() != LDAP_SSL_ON) && (ldap_port == 636) ) {
3930                         ldap_port = 389;
3931                 }
3932
3933                 location = talloc_asprintf(pdb_context->mem_ctx, "%s://%s:%d", lp_ldap_ssl() == LDAP_SSL_ON ? "ldaps" : "ldap", lp_ldap_server(), ldap_port);
3934                 if (!location) {
3935                         return NT_STATUS_NO_MEMORY;
3936                 }
3937         }
3938 #endif
3939
3940         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
3941                 return nt_status;
3942         }
3943
3944         (*pdb_method)->name = "ldapsam_compat";
3945
3946         ldap_state = (*pdb_method)->private_data;
3947         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
3948
3949         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
3950
3951         return NT_STATUS_OK;
3952 }
3953
3954 /**********************************************************************
3955  Initialise the normal mode for pdb_ldap
3956  *********************************************************************/
3957
3958 NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
3959 {
3960         NTSTATUS nt_status;
3961         struct ldapsam_privates *ldap_state;
3962         uint32 alg_rid_base;
3963         pstring alg_rid_base_string;
3964         LDAPMessage *result = NULL;
3965         LDAPMessage *entry = NULL;
3966         DOM_SID ldap_domain_sid;
3967         DOM_SID secrets_domain_sid;
3968         pstring domain_sid_string;
3969         char *dn;
3970
3971         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
3972                 return nt_status;
3973         }
3974
3975         (*pdb_method)->name = "ldapsam";
3976
3977         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
3978         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
3979         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
3980         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
3981         (*pdb_method)->search_users = ldapsam_search_users;
3982         (*pdb_method)->search_groups = ldapsam_search_groups;
3983         (*pdb_method)->search_aliases = ldapsam_search_aliases;
3984
3985         ldap_state = (*pdb_method)->private_data;
3986         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
3987
3988         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
3989         
3990         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state, &result, 
3991                                                ldap_state->domain_name, True);
3992         
3993         if ( !NT_STATUS_IS_OK(nt_status) ) {
3994                 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain info, nor add one to the domain\n"));
3995                 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, will be unable to allocate new users/groups, \
3996 and will risk BDCs having inconsistant SIDs\n"));
3997                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
3998                 return NT_STATUS_OK;
3999         }
4000
4001         /* Given that the above might fail, everything below this must be optional */
4002         
4003         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
4004         if (!entry) {
4005                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info entry\n"));
4006                 ldap_msgfree(result);
4007                 return NT_STATUS_UNSUCCESSFUL;
4008         }
4009
4010         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
4011         if (!dn) {
4012                 return NT_STATUS_UNSUCCESSFUL;
4013         }
4014
4015         ldap_state->domain_dn = smb_xstrdup(dn);
4016         ldap_memfree(dn);
4017
4018         if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
4019                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
4020                                  domain_sid_string)) {
4021                 BOOL found_sid;
4022                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
4023                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be read as a valid SID\n", domain_sid_string));
4024                         return NT_STATUS_INVALID_PARAMETER;
4025                 }
4026                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name, &secrets_domain_sid);
4027                 if (!found_sid || !sid_equal(&secrets_domain_sid, &ldap_domain_sid)) {
4028                         fstring new_sid_str, old_sid_str;
4029                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain %s based on pdb_ldap results %s -> %s\n",
4030                                   ldap_state->domain_name, 
4031                                   sid_to_string(old_sid_str, &secrets_domain_sid),
4032                                   sid_to_string(new_sid_str, &ldap_domain_sid)));
4033                         
4034                         /* reset secrets.tdb sid */
4035                         secrets_store_domain_sid(ldap_state->domain_name, &ldap_domain_sid);
4036                         DEBUG(1, ("New global sam SID: %s\n", sid_to_string(new_sid_str, get_global_sam_sid())));
4037                 }
4038                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
4039         }
4040
4041         if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
4042                                  get_attr_key2string( dominfo_attr_list, LDAP_ATTR_ALGORITHMIC_RID_BASE ),
4043                                  alg_rid_base_string)) {
4044                 alg_rid_base = (uint32)atol(alg_rid_base_string);
4045                 if (alg_rid_base != algorithmic_rid_base()) {
4046                         DEBUG(0, ("The value of 'algorithmic RID base' has changed since the LDAP\n"
4047                                   "database was initialised.  Aborting. \n"));
4048                         ldap_msgfree(result);
4049                         return NT_STATUS_UNSUCCESSFUL;
4050                 }
4051         }
4052         ldap_msgfree(result);
4053
4054         return NT_STATUS_OK;
4055 }
4056
4057 NTSTATUS pdb_ldap_init(void)
4058 {
4059         NTSTATUS nt_status;
4060         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
4061                 return nt_status;
4062
4063         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
4064                 return nt_status;
4065
4066         /* Let pdb_nds register backends */
4067         pdb_nds_init();
4068
4069         return NT_STATUS_OK;
4070 }