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