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