r2619: Only issue the ldap extended password change operation if the ldap server
[ira/wip.git] / source / 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                 if ((pwhist = malloc(pwHistLen * PW_HISTORY_ENTRY_LEN)) == NULL){
731                         DEBUG(0, ("init_sam_from_ldap: malloc failed!\n"));
732                         return False;
733                 }
734                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
735
736                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry, 
737                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), temp)) {
738                         /* leave as default - zeros */
739                 } else {
740                         BOOL hex_failed = False;
741                         for (i = 0; i < pwHistLen; i++){
742                                 /* Get the 16 byte salt. */
743                                 if (!pdb_gethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
744                                         hex_failed = True;
745                                         break;
746                                 }
747                                 /* Get the 16 byte MD5 hash of salt+passwd. */
748                                 if (!pdb_gethexpwd(&temp[(i*64)+32],
749                                                 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN])) {
750                                         hex_failed = True;
751                                         break;
752                                 }
753                         }
754                         if (hex_failed) {
755                                 DEBUG(0,("init_sam_from_ldap: Failed to get password history for user %s\n",
756                                         username));
757                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
758                         }
759                 }
760                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
761                         SAFE_FREE(pwhist);
762                         return False;
763                 }
764                 SAFE_FREE(pwhist);
765         }
766
767         if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
768                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), temp)) {
769                 acct_ctrl |= ACB_NORMAL;
770         } else {
771                 acct_ctrl = pdb_decode_acct_ctrl(temp);
772
773                 if (acct_ctrl == 0)
774                         acct_ctrl |= ACB_NORMAL;
775
776                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
777         }
778
779         pdb_set_hours_len(sampass, hours_len, PDB_SET);
780         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
781
782 /*      pdb_set_munged_dial(sampass, munged_dial, PDB_SET); */
783         
784         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
785                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_COUNT), temp)) {
786                         /* leave as default */
787         } else {
788                 bad_password_count = (uint32) atol(temp);
789                 pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
790         }
791
792         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
793                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_TIME), temp)) {
794                 /* leave as default */
795         } else {
796                 bad_password_time = (time_t) atol(temp);
797                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
798         }
799
800
801         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
802                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_COUNT), temp)) {
803                         /* leave as default */
804         } else {
805                 logon_count = (uint32) atol(temp);
806                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
807         }
808
809         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
810
811         if(!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
812                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_HOURS), temp)) {
813                         /* leave as default */
814         } else {
815                 pdb_gethexhours(temp, hours);
816                 memset((char *)temp, '\0', strlen(temp) +1);
817                 pdb_set_hours(sampass, hours, PDB_SET);
818                 ZERO_STRUCT(hours);
819         }
820
821         /* check the timestamp of the cache vs ldap entry */
822         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state, 
823                                                             entry)))
824                 return True;
825
826         /* see if we have newer updates */
827         if (!(cache_entry = login_cache_read(sampass))) {
828                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
829                            (unsigned int)pdb_get_bad_password_count(sampass),
830                            (unsigned int)pdb_get_bad_password_time(sampass)));
831                 return True;
832         }
833
834         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n", 
835                   (unsigned int)ldap_entry_time, (unsigned int)cache_entry->entry_timestamp, 
836                   (unsigned int)cache_entry->bad_password_time));
837
838         if (ldap_entry_time > cache_entry->entry_timestamp) {
839                 /* cache is older than directory , so
840                    we need to delete the entry but allow the 
841                    fields to be written out */
842                 login_cache_delentry(sampass);
843         } else {
844                 /* read cache in */
845                 pdb_set_acct_ctrl(sampass, 
846                                   pdb_get_acct_ctrl(sampass) | 
847                                   (cache_entry->acct_ctrl & ACB_AUTOLOCK),
848                                   PDB_SET);
849                 pdb_set_bad_password_count(sampass, 
850                                            cache_entry->bad_password_count, 
851                                            PDB_SET);
852                 pdb_set_bad_password_time(sampass, 
853                                           cache_entry->bad_password_time, 
854                                           PDB_SET);
855         }
856
857         SAFE_FREE(cache_entry);
858         return True;
859 }
860
861 /**********************************************************************
862  Initialize the ldap db from a SAM_ACCOUNT. Called on update.
863  (Based on init_buffer_from_sam in pdb_tdb.c)
864 *********************************************************************/
865
866 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state, 
867                                 LDAPMessage *existing,
868                                 LDAPMod *** mods, SAM_ACCOUNT * sampass,
869                                 BOOL (*need_update)(const SAM_ACCOUNT *,
870                                                     enum pdb_elements))
871 {
872         pstring temp;
873         uint32 rid;
874
875         if (mods == NULL || sampass == NULL) {
876                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
877                 return False;
878         }
879
880         *mods = NULL;
881
882         /* 
883          * took out adding "objectclass: sambaAccount"
884          * do this on a per-mod basis
885          */
886         if (need_update(sampass, PDB_USERNAME))
887                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
888                               "uid", pdb_get_username(sampass));
889
890         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
891
892         /* only update the RID if we actually need to */
893         if (need_update(sampass, PDB_USERSID)) {
894                 fstring sid_string;
895                 fstring dom_sid_string;
896                 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
897                 
898                 switch ( ldap_state->schema_ver ) {
899                         case SCHEMAVER_SAMBAACCOUNT:
900                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
901                                         DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
902                                                 sid_to_string(sid_string, user_sid), 
903                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
904                                         return False;
905                                 }
906                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
907                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
908                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
909                                         temp);
910                                 break;
911                                 
912                         case SCHEMAVER_SAMBASAMACCOUNT:
913                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
914                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
915                                         sid_to_string(sid_string, user_sid));                                 
916                                 break;
917                                 
918                         default:
919                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
920                                 break;
921                 }               
922         }
923
924         /* we don't need to store the primary group RID - so leaving it
925            'free' to hang off the unix primary group makes life easier */
926
927         if (need_update(sampass, PDB_GROUPSID)) {
928                 fstring sid_string;
929                 fstring dom_sid_string;
930                 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
931                 
932                 switch ( ldap_state->schema_ver ) {
933                         case SCHEMAVER_SAMBAACCOUNT:
934                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
935                                         DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
936                                                 sid_to_string(sid_string, group_sid),
937                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
938                                         return False;
939                                 }
940
941                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
942                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
943                                         get_userattr_key2string(ldap_state->schema_ver, 
944                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
945                                 break;
946                                 
947                         case SCHEMAVER_SAMBASAMACCOUNT:
948                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
949                                         get_userattr_key2string(ldap_state->schema_ver, 
950                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_string(sid_string, group_sid));
951                                 break;
952                                 
953                         default:
954                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
955                                 break;
956                 }
957                 
958         }
959         
960         /* displayName, cn, and gecos should all be the same
961          *  most easily accomplished by giving them the same OID
962          *  gecos isn't set here b/c it should be handled by the 
963          *  add-user script
964          *  We change displayName only and fall back to cn if
965          *  it does not exist.
966          */
967
968         if (need_update(sampass, PDB_FULLNAME))
969                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
970                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
971                         pdb_get_fullname(sampass));
972
973         if (need_update(sampass, PDB_ACCTDESC))
974                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
975                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
976                         pdb_get_acct_desc(sampass));
977
978         if (need_update(sampass, PDB_WORKSTATIONS))
979                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
980                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
981                         pdb_get_workstations(sampass));
982         
983         if (need_update(sampass, PDB_MUNGEDDIAL))
984                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
985                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
986                         pdb_get_munged_dial(sampass));
987         
988         if (need_update(sampass, PDB_SMBHOME))
989                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
990                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
991                         pdb_get_homedir(sampass));
992                         
993         if (need_update(sampass, PDB_DRIVE))
994                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
995                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
996                         pdb_get_dir_drive(sampass));
997
998         if (need_update(sampass, PDB_LOGONSCRIPT))
999                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1000                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1001                         pdb_get_logon_script(sampass));
1002
1003         if (need_update(sampass, PDB_PROFILE))
1004                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1005                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1006                         pdb_get_profile_path(sampass));
1007
1008         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
1009         if (need_update(sampass, PDB_LOGONTIME))
1010                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1011                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1012
1013         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
1014         if (need_update(sampass, PDB_LOGOFFTIME))
1015                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1016                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1017
1018         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
1019         if (need_update(sampass, PDB_KICKOFFTIME))
1020                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1021                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1022
1023         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
1024         if (need_update(sampass, PDB_CANCHANGETIME))
1025                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1026                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1027
1028         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
1029         if (need_update(sampass, PDB_MUSTCHANGETIME))
1030                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1031                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1032
1033
1034         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1035                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1036
1037                 if (need_update(sampass, PDB_LMPASSWD)) {
1038                         const uchar *lm_pw =  pdb_get_lanman_passwd(sampass);
1039                         if (lm_pw) {
1040                                 pdb_sethexpwd(temp, lm_pw,
1041                                               pdb_get_acct_ctrl(sampass));
1042                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1043                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1044                                                  temp);
1045                         } else {
1046                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1047                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1048                                                  NULL);
1049                         }
1050                 }
1051                 if (need_update(sampass, PDB_NTPASSWD)) {
1052                         const uchar *nt_pw =  pdb_get_nt_passwd(sampass);
1053                         if (nt_pw) {
1054                                 pdb_sethexpwd(temp, nt_pw,
1055                                               pdb_get_acct_ctrl(sampass));
1056                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1057                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1058                                                  temp);
1059                         } else {
1060                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1061                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1062                                                  NULL);
1063                         }
1064                 }
1065
1066                 if (need_update(sampass, PDB_PWHISTORY)) {
1067                         int pwHistLen = 0;
1068                         account_policy_get(AP_PASSWORD_HISTORY, &pwHistLen);
1069                         if (pwHistLen == 0) {
1070                                 /* Remove any password history from the LDAP store. */
1071                                 memset(temp, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1072                                 temp[64] = '\0';
1073                         } else {
1074                                 int i, currHistLen = 0;
1075                                 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1076                                 if (pwhist != NULL) {
1077                                         /* We can only store (sizeof(pstring)-1)/64 password history entries. */
1078                                         pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
1079                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1080                                                 /* Store the salt. */
1081                                                 pdb_sethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1082                                                 /* Followed by the md5 hash of salt + md4 hash */
1083                                                 pdb_sethexpwd(&temp[(i*64)+32],
1084                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1085                                                 DEBUG(100, ("temp=%s\n", temp));
1086                                         }
1087                                 } 
1088                         }
1089                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1090                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1091                                          temp);
1092                 }
1093
1094                 if (need_update(sampass, PDB_PASSLASTSET)) {
1095                         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
1096                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1097                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1098                                 temp);
1099                 }
1100         }
1101
1102         if (need_update(sampass, PDB_HOURS)) {
1103                 const char *hours = pdb_get_hours(sampass);
1104                 if (hours) {
1105                         pdb_sethexhours(temp, hours);
1106                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1107                                 existing,
1108                                 mods,
1109                                 get_userattr_key2string(ldap_state->schema_ver,
1110                                                 LDAP_ATTR_LOGON_HOURS),
1111                                 temp);
1112                 }
1113         }
1114
1115         if (need_update(sampass, PDB_ACCTCTRL))
1116                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1117                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1118                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1119
1120         /* password lockout cache: 
1121            - If we are now autolocking or clearing, we write to ldap
1122            - If we are clearing, we delete the cache entry
1123            - If the count is > 0, we update the cache
1124
1125            This even means when autolocking, we cache, just in case the
1126            update doesn't work, and we have to cache the autolock flag */
1127
1128         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1129             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1130                 uint16 badcount = pdb_get_bad_password_count(sampass);
1131                 time_t badtime = pdb_get_bad_password_time(sampass);
1132                 uint32 pol;
1133                 account_policy_get(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1134
1135                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1136                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1137
1138                 if ((badcount >= pol) || (badcount == 0)) {
1139                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1140                                 (unsigned int)badcount, (unsigned int)badtime));
1141                         slprintf (temp, sizeof (temp) - 1, "%li", (long)badcount);
1142                         smbldap_make_mod(
1143                                 ldap_state->smbldap_state->ldap_struct,
1144                                 existing, mods, 
1145                                 get_userattr_key2string(
1146                                         ldap_state->schema_ver, 
1147                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1148                                 temp);
1149
1150                         slprintf (temp, sizeof (temp) - 1, "%li", badtime);
1151                         smbldap_make_mod(
1152                                 ldap_state->smbldap_state->ldap_struct, 
1153                                 existing, mods,
1154                                 get_userattr_key2string(
1155                                         ldap_state->schema_ver, 
1156                                         LDAP_ATTR_BAD_PASSWORD_TIME), 
1157                                 temp);
1158                 }
1159                 if (badcount == 0) {
1160                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1161                         login_cache_delentry(sampass);
1162                 } else {
1163                         LOGIN_CACHE cache_entry;
1164
1165                         cache_entry.entry_timestamp = time(NULL);
1166                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1167                         cache_entry.bad_password_count = badcount;
1168                         cache_entry.bad_password_time = badtime;
1169
1170                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1171                         login_cache_write(sampass, cache_entry);
1172                 }
1173         }
1174
1175         return True;
1176 }
1177
1178 /**********************************************************************
1179  Connect to LDAP server for password enumeration.
1180 *********************************************************************/
1181
1182 static NTSTATUS ldapsam_setsampwent(struct pdb_methods *my_methods, BOOL update)
1183 {
1184         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1185         int rc;
1186         pstring filter;
1187         char **attr_list;
1188
1189         pstr_sprintf( filter, "(&%s%s)", lp_ldap_filter(), 
1190                 get_objclass_filter(ldap_state->schema_ver));
1191         all_string_sub(filter, "%u", "*", sizeof(pstring));
1192
1193         attr_list = get_userattr_list(ldap_state->schema_ver);
1194         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, 
1195                                    attr_list, &ldap_state->result);
1196         free_attr_list( attr_list );
1197
1198         if (rc != LDAP_SUCCESS) {
1199                 DEBUG(0, ("ldapsam_setsampwent: LDAP search failed: %s\n", ldap_err2string(rc)));
1200                 DEBUG(3, ("ldapsam_setsampwent: Query was: %s, %s\n", lp_ldap_suffix(), filter));
1201                 ldap_msgfree(ldap_state->result);
1202                 ldap_state->result = NULL;
1203                 return NT_STATUS_UNSUCCESSFUL;
1204         }
1205
1206         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base!\n",
1207                 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
1208                 ldap_state->result)));
1209
1210         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
1211                                  ldap_state->result);
1212         ldap_state->index = 0;
1213
1214         return NT_STATUS_OK;
1215 }
1216
1217 /**********************************************************************
1218  End enumeration of the LDAP password list.
1219 *********************************************************************/
1220
1221 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1222 {
1223         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1224         if (ldap_state->result) {
1225                 ldap_msgfree(ldap_state->result);
1226                 ldap_state->result = NULL;
1227         }
1228 }
1229
1230 /**********************************************************************
1231 Get the next entry in the LDAP password database.
1232 *********************************************************************/
1233
1234 static NTSTATUS ldapsam_getsampwent(struct pdb_methods *my_methods, SAM_ACCOUNT *user)
1235 {
1236         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1237         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1238         BOOL bret = False;
1239
1240         while (!bret) {
1241                 if (!ldap_state->entry)
1242                         return ret;
1243                 
1244                 ldap_state->index++;
1245                 bret = init_sam_from_ldap(ldap_state, user, ldap_state->entry);
1246                 
1247                 ldap_state->entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
1248                                             ldap_state->entry); 
1249         }
1250
1251         return NT_STATUS_OK;
1252 }
1253
1254 static void append_attr(char ***attr_list, const char *new_attr)
1255 {
1256         int i;
1257
1258         if (new_attr == NULL) {
1259                 return;
1260         }
1261
1262         for (i=0; (*attr_list)[i] != NULL; i++) {
1263                 ;
1264         }
1265
1266         (*attr_list) = Realloc((*attr_list), sizeof(**attr_list) * (i+2));
1267         SMB_ASSERT((*attr_list) != NULL);
1268         (*attr_list)[i] = strdup(new_attr);
1269         (*attr_list)[i+1] = NULL;
1270 }
1271
1272 /**********************************************************************
1273 Get SAM_ACCOUNT entry from LDAP by username.
1274 *********************************************************************/
1275
1276 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, SAM_ACCOUNT *user, const char *sname)
1277 {
1278         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1279         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1280         LDAPMessage *result = NULL;
1281         LDAPMessage *entry = NULL;
1282         int count;
1283         char ** attr_list;
1284         int rc;
1285         
1286         attr_list = get_userattr_list( ldap_state->schema_ver );
1287         append_attr(&attr_list, get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP));
1288         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result, attr_list);
1289         free_attr_list( attr_list );
1290
1291         if ( rc != LDAP_SUCCESS ) 
1292                 return NT_STATUS_NO_SUCH_USER;
1293         
1294         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1295         
1296         if (count < 1) {
1297                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1298                 ldap_msgfree(result);
1299                 return NT_STATUS_NO_SUCH_USER;
1300         } else if (count > 1) {
1301                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1302                 ldap_msgfree(result);
1303                 return NT_STATUS_NO_SUCH_USER;
1304         }
1305
1306         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1307         if (entry) {
1308                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1309                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1310                         ldap_msgfree(result);
1311                         return NT_STATUS_NO_SUCH_USER;
1312                 }
1313                 pdb_set_backend_private_data(user, result, 
1314                                              private_data_free_fn, 
1315                                              my_methods, PDB_CHANGED);
1316                 ret = NT_STATUS_OK;
1317         } else {
1318                 ldap_msgfree(result);
1319         }
1320         return ret;
1321 }
1322
1323 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1324                                    const DOM_SID *sid, LDAPMessage **result) 
1325 {
1326         int rc = -1;
1327         char ** attr_list;
1328         uint32 rid;
1329
1330         switch ( ldap_state->schema_ver ) {
1331                 case SCHEMAVER_SAMBASAMACCOUNT:
1332                         attr_list = get_userattr_list(ldap_state->schema_ver);
1333                         append_attr(&attr_list, get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP));
1334                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid, result, attr_list);
1335                         free_attr_list( attr_list );
1336
1337                         if ( rc != LDAP_SUCCESS ) 
1338                                 return rc;
1339                         break;
1340                         
1341                 case SCHEMAVER_SAMBAACCOUNT:
1342                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1343                                 return rc;
1344                         }
1345                 
1346                         attr_list = get_userattr_list(ldap_state->schema_ver);
1347                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1348                         free_attr_list( attr_list );
1349
1350                         if ( rc != LDAP_SUCCESS ) 
1351                                 return rc;
1352                         break;
1353         }
1354         return rc;
1355 }
1356
1357 /**********************************************************************
1358  Get SAM_ACCOUNT entry from LDAP by SID.
1359 *********************************************************************/
1360
1361 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, SAM_ACCOUNT * user, const DOM_SID *sid)
1362 {
1363         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1364         LDAPMessage *result = NULL;
1365         LDAPMessage *entry = NULL;
1366         int count;
1367         int rc;
1368         fstring sid_string;
1369
1370         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1371                                           sid, &result); 
1372         if (rc != LDAP_SUCCESS)
1373                 return NT_STATUS_NO_SUCH_USER;
1374
1375         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1376         
1377         if (count < 1) {
1378                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] count=%d\n", sid_to_string(sid_string, sid),
1379                        count));
1380                 ldap_msgfree(result);
1381                 return NT_STATUS_NO_SUCH_USER;
1382         }  else if (count > 1) {
1383                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID [%s]. Failing. count=%d\n", sid_to_string(sid_string, sid),
1384                        count));
1385                 ldap_msgfree(result);
1386                 return NT_STATUS_NO_SUCH_USER;
1387         }
1388
1389         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1390         if (!entry) {
1391                 ldap_msgfree(result);
1392                 return NT_STATUS_NO_SUCH_USER;
1393         }
1394
1395         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1396                 DEBUG(1,("ldapsam_getsampwrid: init_sam_from_ldap failed!\n"));
1397                 ldap_msgfree(result);
1398                 return NT_STATUS_NO_SUCH_USER;
1399         }
1400
1401         pdb_set_backend_private_data(user, result, 
1402                                      private_data_free_fn, 
1403                                      my_methods, PDB_CHANGED);
1404         return NT_STATUS_OK;
1405 }       
1406
1407 static BOOL ldapsam_can_pwchange_exop(struct smbldap_state *ldap_state)
1408 {
1409         LDAPMessage *msg = NULL;
1410         LDAPMessage *entry = NULL;
1411         char **values = NULL;
1412         char *attrs[] = { "supportedExtension", NULL };
1413         int rc, num_result, num_values, i;
1414         BOOL result = False;
1415
1416         rc = smbldap_search(ldap_state, "", LDAP_SCOPE_BASE, "(objectclass=*)",
1417                             attrs, 0, &msg);
1418
1419         if (rc != LDAP_SUCCESS) {
1420                 DEBUG(3, ("Could not search rootDSE\n"));
1421                 return False;
1422         }
1423
1424         num_result = ldap_count_entries(ldap_state->ldap_struct, msg);
1425
1426         if (num_result != 1) {
1427                 DEBUG(3, ("Expected one rootDSE, got %d\n", num_result));
1428                 goto done;
1429         }
1430
1431         entry = ldap_first_entry(ldap_state->ldap_struct, msg);
1432
1433         if (entry == NULL) {
1434                 DEBUG(3, ("Could not retrieve rootDSE\n"));
1435                 goto done;
1436         }
1437
1438         values = ldap_get_values(ldap_state->ldap_struct, entry,
1439                                  "supportedExtension");
1440
1441         if (values == NULL) {
1442                 DEBUG(9, ("LDAP Server does not support any extensions\n"));
1443                 goto done;
1444         }
1445
1446         num_values = ldap_count_values(values);
1447
1448         if (num_values == 0) {
1449                 DEBUG(9, ("LDAP Server does not support any extensions\n"));
1450                 goto done;
1451         }
1452
1453         for (i=0; i<num_values; i++) {
1454                 if (strcmp(values[i], LDAP_EXOP_MODIFY_PASSWD) == 0)
1455                         result = True;
1456         }
1457
1458  done:
1459         if (values != NULL)
1460                 ldap_value_free(values);
1461         if (msg != NULL)
1462                 ldap_msgfree(msg);
1463
1464         return result;
1465 }
1466
1467 /********************************************************************
1468  Do the actual modification - also change a plaintext passord if 
1469  it it set.
1470 **********************************************************************/
1471
1472 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1473                                      SAM_ACCOUNT *newpwd, char *dn,
1474                                      LDAPMod **mods, int ldap_op, 
1475                                      BOOL (*need_update)(const SAM_ACCOUNT *, enum pdb_elements))
1476 {
1477         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1478         int rc;
1479         
1480         if (!my_methods || !newpwd || !dn) {
1481                 return NT_STATUS_INVALID_PARAMETER;
1482         }
1483         
1484         if (!mods) {
1485                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1486                 /* may be password change below however */
1487         } else {
1488                 switch(ldap_op) {
1489                         case LDAP_MOD_ADD: 
1490                                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1491                                                 "objectclass", 
1492                                                 LDAP_OBJ_ACCOUNT);
1493                                 rc = smbldap_add(ldap_state->smbldap_state, 
1494                                                  dn, mods);
1495                                 break;
1496                         case LDAP_MOD_REPLACE: 
1497                                 rc = smbldap_modify(ldap_state->smbldap_state, 
1498                                                     dn ,mods);
1499                                 break;
1500                         default:        
1501                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n", 
1502                                          ldap_op));
1503                                 return NT_STATUS_INVALID_PARAMETER;
1504                 }
1505                 
1506                 if (rc!=LDAP_SUCCESS) {
1507                         char *ld_error = NULL;
1508                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1509                                         &ld_error);
1510                         DEBUG(1, ("ldapsam_modify_entry: Failed to %s user dn= %s with: %s\n\t%s\n",
1511                                ldap_op == LDAP_MOD_ADD ? "add" : "modify",
1512                                dn, ldap_err2string(rc),
1513                                ld_error?ld_error:"unknown"));
1514                         SAFE_FREE(ld_error);
1515                         return NT_STATUS_UNSUCCESSFUL;
1516                 }  
1517         }
1518         
1519         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1520                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1521                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1522                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1523                 BerElement *ber;
1524                 struct berval *bv;
1525                 char *retoid;
1526                 struct berval *retdata;
1527                 char *utf8_password;
1528                 char *utf8_dn;
1529
1530                 if (!ldapsam_can_pwchange_exop(ldap_state->smbldap_state)) {
1531                         DEBUG(2, ("ldap password change requested, but LDAP "
1532                                   "server does not support it -- ignoring\n"));
1533                         return NT_STATUS_OK;
1534                 }
1535
1536                 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1537                         return NT_STATUS_NO_MEMORY;
1538                 }
1539
1540                 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1541                         return NT_STATUS_NO_MEMORY;
1542                 }
1543
1544                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1545                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1546                         SAFE_FREE(utf8_password);
1547                         return NT_STATUS_UNSUCCESSFUL;
1548                 }
1549
1550                 ber_printf (ber, "{");
1551                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn);
1552                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password);
1553                 ber_printf (ber, "N}");
1554
1555                 if ((rc = ber_flatten (ber, &bv))<0) {
1556                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1557                         ber_free(ber,1);
1558                         SAFE_FREE(utf8_dn);
1559                         SAFE_FREE(utf8_password);
1560                         return NT_STATUS_UNSUCCESSFUL;
1561                 }
1562                 
1563                 SAFE_FREE(utf8_dn);
1564                 SAFE_FREE(utf8_password);
1565                 ber_free(ber, 1);
1566
1567                 if ((rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1568                                                      LDAP_EXOP_MODIFY_PASSWD,
1569                                                      bv, NULL, NULL, &retoid, 
1570                                                      &retdata)) != LDAP_SUCCESS) {
1571                         char *ld_error = NULL;
1572
1573                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1574                                 DEBUG(3, ("Could not set userPassword "
1575                                           "attribute due to an objectClass "
1576                                           "violation -- ignoring\n"));
1577                                 ber_bvfree(bv);
1578                                 return NT_STATUS_OK;
1579                         }
1580
1581                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1582                                         &ld_error);
1583                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1584                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1585                         SAFE_FREE(ld_error);
1586                         ber_bvfree(bv);
1587                         return NT_STATUS_UNSUCCESSFUL;
1588                 } else {
1589                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1590 #ifdef DEBUG_PASSWORD
1591                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1592 #endif    
1593                         ber_bvfree(retdata);
1594                         ber_memfree(retoid);
1595                 }
1596                 ber_bvfree(bv);
1597         }
1598         return NT_STATUS_OK;
1599 }
1600
1601 /**********************************************************************
1602  Delete entry from LDAP for username.
1603 *********************************************************************/
1604
1605 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * sam_acct)
1606 {
1607         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1608         const char *sname;
1609         int rc;
1610         LDAPMessage *result = NULL;
1611         NTSTATUS ret;
1612         char **attr_list;
1613         fstring objclass;
1614
1615         if (!sam_acct) {
1616                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1617                 return NT_STATUS_INVALID_PARAMETER;
1618         }
1619
1620         sname = pdb_get_username(sam_acct);
1621
1622         DEBUG (3, ("ldapsam_delete_sam_account: Deleting user %s from LDAP.\n", sname));
1623
1624         attr_list= get_userattr_delete_list( ldap_state->schema_ver );
1625         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result, attr_list);
1626
1627         if (rc != LDAP_SUCCESS)  {
1628                 free_attr_list( attr_list );
1629                 return NT_STATUS_NO_SUCH_USER;
1630         }
1631         
1632         switch ( ldap_state->schema_ver ) {
1633                 case SCHEMAVER_SAMBASAMACCOUNT:
1634                         fstrcpy( objclass, LDAP_OBJ_SAMBASAMACCOUNT );
1635                         break;
1636                         
1637                 case SCHEMAVER_SAMBAACCOUNT:
1638                         fstrcpy( objclass, LDAP_OBJ_SAMBAACCOUNT );
1639                         break;
1640                 default:
1641                         fstrcpy( objclass, "UNKNOWN" );
1642                         DEBUG(0,("ldapsam_delete_sam_account: Unknown schema version specified!\n"));
1643                                 break;
1644         }
1645
1646         ret = ldapsam_delete_entry(ldap_state, result, objclass, attr_list );
1647         ldap_msgfree(result);
1648         free_attr_list( attr_list );
1649
1650         return ret;
1651 }
1652
1653 /**********************************************************************
1654  Helper function to determine for update_sam_account whether
1655  we need LDAP modification.
1656 *********************************************************************/
1657
1658 static BOOL element_is_changed(const SAM_ACCOUNT *sampass,
1659                                enum pdb_elements element)
1660 {
1661         return IS_SAM_CHANGED(sampass, element);
1662 }
1663
1664 /**********************************************************************
1665  Update SAM_ACCOUNT.
1666 *********************************************************************/
1667
1668 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * newpwd)
1669 {
1670         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1671         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1672         int rc = 0;
1673         char *dn;
1674         LDAPMessage *result = NULL;
1675         LDAPMessage *entry = NULL;
1676         LDAPMod **mods = NULL;
1677         char **attr_list;
1678
1679         result = pdb_get_backend_private_data(newpwd, my_methods);
1680         if (!result) {
1681                 attr_list = get_userattr_list(ldap_state->schema_ver);
1682                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1683                 free_attr_list( attr_list );
1684                 if (rc != LDAP_SUCCESS) {
1685                         return NT_STATUS_UNSUCCESSFUL;
1686                 }
1687                 pdb_set_backend_private_data(newpwd, result, private_data_free_fn, my_methods, PDB_CHANGED);
1688         }
1689
1690         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1691                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1692                 return NT_STATUS_UNSUCCESSFUL;
1693         }
1694
1695         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1696         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1697         if (!dn) {
1698                 return NT_STATUS_UNSUCCESSFUL;
1699         }
1700
1701         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1702
1703         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1704                                 element_is_changed)) {
1705                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1706                 SAFE_FREE(dn);
1707                 if (mods != NULL)
1708                         ldap_mods_free(mods,True);
1709                 return NT_STATUS_UNSUCCESSFUL;
1710         }
1711         
1712         if (mods == NULL) {
1713                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1714                          pdb_get_username(newpwd)));
1715                 SAFE_FREE(dn);
1716                 return NT_STATUS_OK;
1717         }
1718         
1719         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1720         ldap_mods_free(mods,True);
1721         SAFE_FREE(dn);
1722
1723         if (!NT_STATUS_IS_OK(ret)) {
1724                 char *ld_error = NULL;
1725                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1726                                 &ld_error);
1727                 DEBUG(0,("ldapsam_update_sam_account: failed to modify user with uid = %s, error: %s (%s)\n",
1728                          pdb_get_username(newpwd), ld_error?ld_error:"(unknwon)", ldap_err2string(rc)));
1729                 SAFE_FREE(ld_error);
1730                 return ret;
1731         }
1732
1733         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1734                   pdb_get_username(newpwd)));
1735         return NT_STATUS_OK;
1736 }
1737
1738 /**********************************************************************
1739  Helper function to determine for update_sam_account whether
1740  we need LDAP modification.
1741  *********************************************************************/
1742
1743 static BOOL element_is_set_or_changed(const SAM_ACCOUNT *sampass,
1744                                       enum pdb_elements element)
1745 {
1746         return (IS_SAM_SET(sampass, element) ||
1747                 IS_SAM_CHANGED(sampass, element));
1748 }
1749
1750 /**********************************************************************
1751  Add SAM_ACCOUNT to LDAP.
1752 *********************************************************************/
1753
1754 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * newpwd)
1755 {
1756         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1757         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1758         int rc;
1759         LDAPMessage     *result = NULL;
1760         LDAPMessage     *entry  = NULL;
1761         pstring         dn;
1762         LDAPMod         **mods = NULL;
1763         int             ldap_op = LDAP_MOD_REPLACE;
1764         uint32          num_result;
1765         char            **attr_list;
1766         char            *escape_user;
1767         const char      *username = pdb_get_username(newpwd);
1768         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
1769         pstring         filter;
1770         fstring         sid_string;
1771
1772         if (!username || !*username) {
1773                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
1774                 return NT_STATUS_INVALID_PARAMETER;
1775         }
1776
1777         /* free this list after the second search or in case we exit on failure */
1778         attr_list = get_userattr_list(ldap_state->schema_ver);
1779
1780         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
1781
1782         if (rc != LDAP_SUCCESS) {
1783                 free_attr_list( attr_list );
1784                 return NT_STATUS_UNSUCCESSFUL;
1785         }
1786
1787         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1788                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
1789                          username));
1790                 ldap_msgfree(result);
1791                 free_attr_list( attr_list );
1792                 return NT_STATUS_UNSUCCESSFUL;
1793         }
1794         ldap_msgfree(result);
1795         result = NULL;
1796
1797         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
1798                 rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1799                                                   sid, &result); 
1800                 if (rc == LDAP_SUCCESS) {
1801                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1802                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' already in the base, with samba attributes\n", 
1803                                          sid_to_string(sid_string, sid)));
1804                                 free_attr_list( attr_list );
1805                                 ldap_msgfree(result);
1806                                 return NT_STATUS_UNSUCCESSFUL;
1807                         }
1808                         ldap_msgfree(result);
1809                 }
1810         }
1811
1812         /* does the entry already exist but without a samba attributes?
1813            we need to return the samba attributes here */
1814            
1815         escape_user = escape_ldap_string_alloc( username );
1816         pstrcpy( filter, lp_ldap_filter() );
1817         all_string_sub( filter, "%u", escape_user, sizeof(filter) );
1818         SAFE_FREE( escape_user );
1819
1820         rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1821                                    filter, attr_list, &result);
1822         if ( rc != LDAP_SUCCESS ) {
1823                 free_attr_list( attr_list );
1824                 return NT_STATUS_UNSUCCESSFUL;
1825         }
1826
1827         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1828         
1829         if (num_result > 1) {
1830                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1831                 free_attr_list( attr_list );
1832                 ldap_msgfree(result);
1833                 return NT_STATUS_UNSUCCESSFUL;
1834         }
1835         
1836         /* Check if we need to update an existing entry */
1837         if (num_result == 1) {
1838                 char *tmp;
1839                 
1840                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1841                 ldap_op = LDAP_MOD_REPLACE;
1842                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1843                 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1844                 if (!tmp) {
1845                         free_attr_list( attr_list );
1846                         ldap_msgfree(result);
1847                         return NT_STATUS_UNSUCCESSFUL;
1848                 }
1849                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1850                 SAFE_FREE(tmp);
1851
1852         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
1853
1854                 /* There might be a SID for this account already - say an idmap entry */
1855
1856                 pstr_sprintf(filter, "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))", 
1857                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1858                          sid_to_string(sid_string, sid),
1859                          LDAP_OBJ_IDMAP_ENTRY,
1860                          LDAP_OBJ_SID_ENTRY);
1861                 
1862                 /* free old result before doing a new search */
1863                 if (result != NULL) {
1864                         ldap_msgfree(result);
1865                         result = NULL;
1866                 }
1867                 rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1868                                            filter, attr_list, &result);
1869                         
1870                 if ( rc != LDAP_SUCCESS ) {
1871                         free_attr_list( attr_list );
1872                         return NT_STATUS_UNSUCCESSFUL;
1873                 }
1874                 
1875                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1876                 
1877                 if (num_result > 1) {
1878                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1879                         free_attr_list( attr_list );
1880                         ldap_msgfree(result);
1881                         return NT_STATUS_UNSUCCESSFUL;
1882                 }
1883                 
1884                 /* Check if we need to update an existing entry */
1885                 if (num_result == 1) {
1886                         char *tmp;
1887                         
1888                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1889                         ldap_op = LDAP_MOD_REPLACE;
1890                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1891                         tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1892                         if (!tmp) {
1893                                 free_attr_list( attr_list );
1894                                 ldap_msgfree(result);
1895                                 return NT_STATUS_UNSUCCESSFUL;
1896                         }
1897                         slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1898                         SAFE_FREE(tmp);
1899                 }
1900         }
1901         
1902         free_attr_list( attr_list );
1903
1904         if (num_result == 0) {
1905                 /* Check if we need to add an entry */
1906                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
1907                 ldap_op = LDAP_MOD_ADD;
1908                 if (username[strlen(username)-1] == '$') {
1909                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_machine_suffix ());
1910                 } else {
1911                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_user_suffix ());
1912                 }
1913         }
1914
1915         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1916                                 element_is_set_or_changed)) {
1917                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
1918                 ldap_msgfree(result);
1919                 if (mods != NULL)
1920                         ldap_mods_free(mods,True);
1921                 return NT_STATUS_UNSUCCESSFUL;          
1922         }
1923         
1924         ldap_msgfree(result);
1925
1926         if (mods == NULL) {
1927                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
1928                 return NT_STATUS_UNSUCCESSFUL;
1929         }
1930         switch ( ldap_state->schema_ver ) {
1931                 case SCHEMAVER_SAMBAACCOUNT:
1932                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
1933                         break;
1934                 case SCHEMAVER_SAMBASAMACCOUNT:
1935                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
1936                         break;
1937                 default:
1938                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
1939                         break;
1940         }
1941
1942         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
1943         if (!NT_STATUS_IS_OK(ret)) {
1944                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
1945                          pdb_get_username(newpwd),dn));
1946                 ldap_mods_free(mods, True);
1947                 return ret;
1948         }
1949
1950         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
1951         ldap_mods_free(mods, True);
1952         
1953         return NT_STATUS_OK;
1954 }
1955
1956 /**********************************************************************
1957  *********************************************************************/
1958
1959 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
1960                                      const char *filter,
1961                                      LDAPMessage ** result)
1962 {
1963         int scope = LDAP_SCOPE_SUBTREE;
1964         int rc;
1965         char **attr_list;
1966
1967         attr_list = get_attr_list(groupmap_attr_list);
1968         rc = smbldap_search(ldap_state->smbldap_state, 
1969                             lp_ldap_group_suffix (), scope,
1970                             filter, attr_list, 0, result);
1971         free_attr_list( attr_list );
1972
1973         if (rc != LDAP_SUCCESS) {
1974                 char *ld_error = NULL;
1975                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1976                                 &ld_error);
1977                 DEBUG(0, ("ldapsam_search_one_group: "
1978                           "Problem during the LDAP search: LDAP error: %s (%s)\n",
1979                           ld_error?ld_error:"(unknown)", ldap_err2string(rc)));
1980                 DEBUGADD(3, ("ldapsam_search_one_group: Query was: %s, %s\n",
1981                           lp_ldap_group_suffix(), filter));
1982                 SAFE_FREE(ld_error);
1983         }
1984
1985         return rc;
1986 }
1987
1988 /**********************************************************************
1989  *********************************************************************/
1990
1991 static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
1992                                  GROUP_MAP *map, LDAPMessage *entry)
1993 {
1994         pstring temp;
1995
1996         if (ldap_state == NULL || map == NULL || entry == NULL ||
1997                         ldap_state->smbldap_state->ldap_struct == NULL) {
1998                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
1999                 return False;
2000         }
2001
2002         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2003                         get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER), temp)) {
2004                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2005                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2006                 return False;
2007         }
2008         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2009
2010         map->gid = (gid_t)atol(temp);
2011
2012         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2013                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID), temp)) {
2014                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2015                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2016                 return False;
2017         }
2018         
2019         if (!string_to_sid(&map->sid, temp)) {
2020                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2021                 return False;
2022         }
2023
2024         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2025                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), temp)) {
2026                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2027                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2028                 return False;
2029         }
2030         map->sid_name_use = (enum SID_NAME_USE)atol(temp);
2031
2032         if ((map->sid_name_use < SID_NAME_USER) ||
2033                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2034                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2035                 return False;
2036         }
2037
2038         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2039                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), temp)) {
2040                 temp[0] = '\0';
2041                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2042                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_CN), temp)) 
2043                 {
2044                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2045 for gidNumber(%lu)\n",(unsigned long)map->gid));
2046                         return False;
2047                 }
2048         }
2049         fstrcpy(map->nt_name, temp);
2050
2051         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2052                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), temp)) {
2053                 temp[0] = '\0';
2054         }
2055         fstrcpy(map->comment, temp);
2056
2057         return True;
2058 }
2059
2060 /**********************************************************************
2061  *********************************************************************/
2062
2063 static BOOL init_ldap_from_group(LDAP *ldap_struct,
2064                                  LDAPMessage *existing,
2065                                  LDAPMod ***mods,
2066                                  const GROUP_MAP *map)
2067 {
2068         pstring tmp;
2069
2070         if (mods == NULL || map == NULL) {
2071                 DEBUG(0, ("init_ldap_from_group: NULL parameters found!\n"));
2072                 return False;
2073         }
2074
2075         *mods = NULL;
2076
2077         sid_to_string(tmp, &map->sid);
2078
2079         smbldap_make_mod(ldap_struct, existing, mods, 
2080                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID), tmp);
2081         pstr_sprintf(tmp, "%i", map->sid_name_use);
2082         smbldap_make_mod(ldap_struct, existing, mods, 
2083                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), tmp);
2084
2085         smbldap_make_mod(ldap_struct, existing, mods, 
2086                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), map->nt_name);
2087         smbldap_make_mod(ldap_struct, existing, mods, 
2088                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), map->comment);
2089
2090         return True;
2091 }
2092
2093 /**********************************************************************
2094  *********************************************************************/
2095
2096 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2097                                  const char *filter,
2098                                  GROUP_MAP *map)
2099 {
2100         struct ldapsam_privates *ldap_state =
2101                 (struct ldapsam_privates *)methods->private_data;
2102         LDAPMessage *result = NULL;
2103         LDAPMessage *entry = NULL;
2104         int count;
2105
2106         if (ldapsam_search_one_group(ldap_state, filter, &result)
2107             != LDAP_SUCCESS) {
2108                 return NT_STATUS_NO_SUCH_GROUP;
2109         }
2110
2111         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2112
2113         if (count < 1) {
2114                 DEBUG(4, ("ldapsam_getgroup: Did not find group\n"));
2115                 ldap_msgfree(result);
2116                 return NT_STATUS_NO_SUCH_GROUP;
2117         }
2118
2119         if (count > 1) {
2120                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: count=%d\n",
2121                           filter, count));
2122                 ldap_msgfree(result);
2123                 return NT_STATUS_NO_SUCH_GROUP;
2124         }
2125
2126         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2127
2128         if (!entry) {
2129                 ldap_msgfree(result);
2130                 return NT_STATUS_UNSUCCESSFUL;
2131         }
2132
2133         if (!init_group_from_ldap(ldap_state, map, entry)) {
2134                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for group filter %s\n",
2135                           filter));
2136                 ldap_msgfree(result);
2137                 return NT_STATUS_NO_SUCH_GROUP;
2138         }
2139
2140         ldap_msgfree(result);
2141         return NT_STATUS_OK;
2142 }
2143
2144 /**********************************************************************
2145  *********************************************************************/
2146
2147 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2148                                  DOM_SID sid)
2149 {
2150         pstring filter;
2151
2152         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
2153                 LDAP_OBJ_GROUPMAP, 
2154                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2155                 sid_string_static(&sid));
2156
2157         return ldapsam_getgroup(methods, filter, map);
2158 }
2159
2160 /**********************************************************************
2161  *********************************************************************/
2162
2163 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2164                                  gid_t gid)
2165 {
2166         pstring filter;
2167
2168         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))",
2169                 LDAP_OBJ_GROUPMAP,
2170                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2171                 (unsigned long)gid);
2172
2173         return ldapsam_getgroup(methods, filter, map);
2174 }
2175
2176 /**********************************************************************
2177  *********************************************************************/
2178
2179 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2180                                  const char *name)
2181 {
2182         pstring filter;
2183         char *escape_name = escape_ldap_string_alloc(name);
2184
2185         if (!escape_name) {
2186                 return NT_STATUS_NO_MEMORY;
2187         }
2188
2189         pstr_sprintf(filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2190                 LDAP_OBJ_GROUPMAP,
2191                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2192                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN), escape_name);
2193
2194         SAFE_FREE(escape_name);
2195
2196         return ldapsam_getgroup(methods, filter, map);
2197 }
2198
2199 /**********************************************************************
2200  *********************************************************************/
2201
2202 static int ldapsam_search_one_group_by_gid(struct ldapsam_privates *ldap_state,
2203                                            gid_t gid,
2204                                            LDAPMessage **result)
2205 {
2206         pstring filter;
2207
2208         pstr_sprintf(filter, "(&(|(objectClass=%s)(objectclass=%s))(%s=%lu))", 
2209                 LDAP_OBJ_POSIXGROUP, LDAP_OBJ_IDMAP_ENTRY,
2210                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2211                 (unsigned long)gid);
2212
2213         return ldapsam_search_one_group(ldap_state, filter, result);
2214 }
2215
2216 /**********************************************************************
2217  *********************************************************************/
2218
2219 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
2220                                                 GROUP_MAP *map)
2221 {
2222         struct ldapsam_privates *ldap_state =
2223                 (struct ldapsam_privates *)methods->private_data;
2224         LDAPMessage *result = NULL;
2225         LDAPMod **mods = NULL;
2226         int count;
2227
2228         char *tmp;
2229         pstring dn;
2230         LDAPMessage *entry;
2231
2232         GROUP_MAP dummy;
2233
2234         int rc;
2235
2236         if (NT_STATUS_IS_OK(ldapsam_getgrgid(methods, &dummy,
2237                                              map->gid))) {
2238                 DEBUG(0, ("ldapsam_add_group_mapping_entry: Group %ld already exists in LDAP\n", (unsigned long)map->gid));
2239                 return NT_STATUS_UNSUCCESSFUL;
2240         }
2241
2242         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
2243         if (rc != LDAP_SUCCESS) {
2244                 ldap_msgfree(result);
2245                 return NT_STATUS_UNSUCCESSFUL;
2246         }
2247
2248         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2249
2250         if ( count == 0 ) {
2251                 /* There's no posixGroup account, let's try to find an
2252                  * appropriate idmap entry for aliases */
2253
2254                 pstring suffix;
2255                 pstring filter;
2256                 char **attr_list;
2257
2258                 ldap_msgfree(result);
2259
2260                 pstrcpy( suffix, lp_ldap_idmap_suffix() );
2261                 pstr_sprintf(filter, "(&(objectClass=%s)(%s=%u))",
2262                              LDAP_OBJ_IDMAP_ENTRY, LDAP_ATTRIBUTE_GIDNUMBER,
2263                              map->gid);
2264                 
2265                 attr_list = get_attr_list( sidmap_attr_list );
2266                 rc = smbldap_search(ldap_state->smbldap_state, suffix,
2267                                     LDAP_SCOPE_SUBTREE, filter, attr_list,
2268                                     0, &result);
2269
2270                 free_attr_list(attr_list);
2271
2272                 if (rc != LDAP_SUCCESS) {
2273                         DEBUG(3,("Failure looking up entry (%s)\n",
2274                                  ldap_err2string(rc) ));
2275                         ldap_msgfree(result);
2276                         return NT_STATUS_UNSUCCESSFUL;
2277                 }
2278         }
2279                            
2280         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2281         if ( count == 0 ) {
2282                 ldap_msgfree(result);
2283                 return NT_STATUS_UNSUCCESSFUL;
2284         }
2285
2286         if (count > 1) {
2287                 DEBUG(2, ("ldapsam_add_group_mapping_entry: Group %lu must exist exactly once in LDAP\n",
2288                           (unsigned long)map->gid));
2289                 ldap_msgfree(result);
2290                 return NT_STATUS_UNSUCCESSFUL;
2291         }
2292
2293         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2294         tmp = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2295         if (!tmp) {
2296                 ldap_msgfree(result);
2297                 return NT_STATUS_UNSUCCESSFUL;
2298         }
2299         pstrcpy(dn, tmp);
2300         SAFE_FREE(tmp);
2301
2302         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
2303                                   result, &mods, map)) {
2304                 DEBUG(0, ("ldapsam_add_group_mapping_entry: init_ldap_from_group failed!\n"));
2305                 ldap_mods_free(mods, True);
2306                 ldap_msgfree(result);
2307                 return NT_STATUS_UNSUCCESSFUL;
2308         }
2309
2310         ldap_msgfree(result);
2311
2312         if (mods == NULL) {
2313                 DEBUG(0, ("ldapsam_add_group_mapping_entry: mods is empty\n"));
2314                 return NT_STATUS_UNSUCCESSFUL;
2315         }
2316
2317         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP );
2318
2319         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2320         ldap_mods_free(mods, True);
2321
2322         if (rc != LDAP_SUCCESS) {
2323                 char *ld_error = NULL;
2324                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2325                                 &ld_error);
2326                 DEBUG(0, ("ldapsam_add_group_mapping_entry: failed to add group %lu error: %s (%s)\n", (unsigned long)map->gid, 
2327                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
2328                 SAFE_FREE(ld_error);
2329                 return NT_STATUS_UNSUCCESSFUL;
2330         }
2331
2332         DEBUG(2, ("ldapsam_add_group_mapping_entry: successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
2333         return NT_STATUS_OK;
2334 }
2335
2336 /**********************************************************************
2337  *********************************************************************/
2338
2339 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
2340                                                    GROUP_MAP *map)
2341 {
2342         struct ldapsam_privates *ldap_state =
2343                 (struct ldapsam_privates *)methods->private_data;
2344         int rc;
2345         char *dn = NULL;
2346         LDAPMessage *result = NULL;
2347         LDAPMessage *entry = NULL;
2348         LDAPMod **mods = NULL;
2349
2350         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
2351
2352         if (rc != LDAP_SUCCESS) {
2353                 return NT_STATUS_UNSUCCESSFUL;
2354         }
2355
2356         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
2357                 DEBUG(0, ("ldapsam_update_group_mapping_entry: No group to modify!\n"));
2358                 ldap_msgfree(result);
2359                 return NT_STATUS_UNSUCCESSFUL;
2360         }
2361
2362         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2363
2364         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
2365                                   result, &mods, map)) {
2366                 DEBUG(0, ("ldapsam_update_group_mapping_entry: init_ldap_from_group failed\n"));
2367                 ldap_msgfree(result);
2368                 if (mods != NULL)
2369                         ldap_mods_free(mods,True);
2370                 return NT_STATUS_UNSUCCESSFUL;
2371         }
2372
2373         if (mods == NULL) {
2374                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: nothing to do\n"));
2375                 ldap_msgfree(result);
2376                 return NT_STATUS_OK;
2377         }
2378
2379         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2380         if (!dn) {
2381                 ldap_msgfree(result);
2382                 return NT_STATUS_UNSUCCESSFUL;
2383         }
2384         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2385         SAFE_FREE(dn);
2386
2387         ldap_mods_free(mods, True);
2388         ldap_msgfree(result);
2389
2390         if (rc != LDAP_SUCCESS) {
2391                 char *ld_error = NULL;
2392                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2393                                 &ld_error);
2394                 DEBUG(0, ("ldapsam_update_group_mapping_entry: failed to modify group %lu error: %s (%s)\n", (unsigned long)map->gid, 
2395                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
2396                 SAFE_FREE(ld_error);
2397                 return NT_STATUS_UNSUCCESSFUL;
2398         }
2399
2400         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
2401         return NT_STATUS_OK;
2402 }
2403
2404 /**********************************************************************
2405  *********************************************************************/
2406
2407 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
2408                                                    DOM_SID sid)
2409 {
2410         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)methods->private_data;
2411         pstring sidstring, filter;
2412         LDAPMessage *result = NULL;
2413         int rc;
2414         NTSTATUS ret;
2415         char **attr_list;
2416
2417         sid_to_string(sidstring, &sid);
2418         
2419         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))", 
2420                 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID, sidstring);
2421
2422         rc = ldapsam_search_one_group(ldap_state, filter, &result);
2423
2424         if (rc != LDAP_SUCCESS) {
2425                 return NT_STATUS_NO_SUCH_GROUP;
2426         }
2427
2428         attr_list = get_attr_list( groupmap_attr_list_to_delete );
2429         ret = ldapsam_delete_entry(ldap_state, result, LDAP_OBJ_GROUPMAP, attr_list);
2430         free_attr_list ( attr_list );
2431
2432         ldap_msgfree(result);
2433
2434         return ret;
2435 }
2436
2437 /**********************************************************************
2438  *********************************************************************/
2439
2440 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods, BOOL update)
2441 {
2442         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2443         fstring filter;
2444         int rc;
2445         char **attr_list;
2446
2447         pstr_sprintf( filter, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
2448         attr_list = get_attr_list( groupmap_attr_list );
2449         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
2450                             LDAP_SCOPE_SUBTREE, filter,
2451                             attr_list, 0, &ldap_state->result);
2452         free_attr_list( attr_list );
2453
2454         if (rc != LDAP_SUCCESS) {
2455                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n", ldap_err2string(rc)));
2456                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n", lp_ldap_group_suffix(), filter));
2457                 ldap_msgfree(ldap_state->result);
2458                 ldap_state->result = NULL;
2459                 return NT_STATUS_UNSUCCESSFUL;
2460         }
2461
2462         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base!\n",
2463                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2464                                      ldap_state->result)));
2465
2466         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, ldap_state->result);
2467         ldap_state->index = 0;
2468
2469         return NT_STATUS_OK;
2470 }
2471
2472 /**********************************************************************
2473  *********************************************************************/
2474
2475 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
2476 {
2477         ldapsam_endsampwent(my_methods);
2478 }
2479
2480 /**********************************************************************
2481  *********************************************************************/
2482
2483 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
2484                                     GROUP_MAP *map)
2485 {
2486         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2487         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2488         BOOL bret = False;
2489
2490         while (!bret) {
2491                 if (!ldap_state->entry)
2492                         return ret;
2493                 
2494                 ldap_state->index++;
2495                 bret = init_group_from_ldap(ldap_state, map, ldap_state->entry);
2496                 
2497                 ldap_state->entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
2498                                             ldap_state->entry); 
2499         }
2500
2501         return NT_STATUS_OK;
2502 }
2503
2504 /**********************************************************************
2505  *********************************************************************/
2506
2507 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
2508                                            enum SID_NAME_USE sid_name_use,
2509                                            GROUP_MAP **rmap, int *num_entries,
2510                                            BOOL unix_only)
2511 {
2512         GROUP_MAP map;
2513         GROUP_MAP *mapt;
2514         int entries = 0;
2515
2516         *num_entries = 0;
2517         *rmap = NULL;
2518
2519         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
2520                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open passdb\n"));
2521                 return NT_STATUS_ACCESS_DENIED;
2522         }
2523
2524         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
2525                 if (sid_name_use != SID_NAME_UNKNOWN &&
2526                     sid_name_use != map.sid_name_use) {
2527                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is not of the requested type\n", map.nt_name));
2528                         continue;
2529                 }
2530                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
2531                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is non mapped\n", map.nt_name));
2532                         continue;
2533                 }
2534
2535                 mapt=(GROUP_MAP *)Realloc((*rmap), (entries+1)*sizeof(GROUP_MAP));
2536                 if (!mapt) {
2537                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to enlarge group map!\n"));
2538                         SAFE_FREE(*rmap);
2539                         return NT_STATUS_UNSUCCESSFUL;
2540                 }
2541                 else
2542                         (*rmap) = mapt;
2543
2544                 mapt[entries] = map;
2545
2546                 entries += 1;
2547
2548         }
2549         ldapsam_endsamgrent(methods);
2550
2551         *num_entries = entries;
2552
2553         return NT_STATUS_OK;
2554 }
2555
2556 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
2557                                         const DOM_SID *alias,
2558                                         const DOM_SID *member,
2559                                         int modop)
2560 {
2561         struct ldapsam_privates *ldap_state =
2562                 (struct ldapsam_privates *)methods->private_data;
2563         char *dn;
2564         LDAPMessage *result = NULL;
2565         LDAPMessage *entry = NULL;
2566         int count;
2567         LDAPMod **mods = NULL;
2568         int rc;
2569
2570         pstring filter;
2571
2572         pstr_sprintf(filter, "(&(|(objectClass=%s)(objectclass=%s))(%s=%s))",
2573                      LDAP_OBJ_GROUPMAP, LDAP_OBJ_IDMAP_ENTRY,
2574                      get_attr_key2string(groupmap_attr_list,
2575                                          LDAP_ATTR_GROUP_SID),
2576                      sid_string_static(alias));
2577
2578         if (ldapsam_search_one_group(ldap_state, filter,
2579                                      &result) != LDAP_SUCCESS)
2580                 return NT_STATUS_NO_SUCH_ALIAS;
2581
2582         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2583                                    result);
2584
2585         if (count < 1) {
2586                 DEBUG(4, ("ldapsam_add_aliasmem: Did not find alias\n"));
2587                 ldap_msgfree(result);
2588                 return NT_STATUS_NO_SUCH_ALIAS;
2589         }
2590
2591         if (count > 1) {
2592                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2593                           "count=%d\n", filter, count));
2594                 ldap_msgfree(result);
2595                 return NT_STATUS_NO_SUCH_ALIAS;
2596         }
2597
2598         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
2599                                  result);
2600
2601         if (!entry) {
2602                 ldap_msgfree(result);
2603                 return NT_STATUS_UNSUCCESSFUL;
2604         }
2605
2606         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2607         if (!dn) {
2608                 ldap_msgfree(result);
2609                 return NT_STATUS_UNSUCCESSFUL;
2610         }
2611
2612         smbldap_set_mod(&mods, modop,
2613                         get_attr_key2string(groupmap_attr_list,
2614                                             LDAP_ATTR_SID_LIST),
2615                         sid_string_static(member));
2616
2617         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2618
2619         ldap_mods_free(mods, True);
2620         ldap_msgfree(result);
2621
2622         if (rc != LDAP_SUCCESS) {
2623                 char *ld_error = NULL;
2624                 ldap_get_option(ldap_state->smbldap_state->ldap_struct,
2625                                 LDAP_OPT_ERROR_STRING,&ld_error);
2626                 
2627                 DEBUG(0, ("ldapsam_delete_entry: Could not delete attributes "
2628                           "for %s, error: %s (%s)\n", dn, ldap_err2string(rc),
2629                           ld_error?ld_error:"unknown"));
2630                 SAFE_FREE(ld_error);
2631                 SAFE_FREE(dn);
2632                 return NT_STATUS_UNSUCCESSFUL;
2633         }
2634
2635         SAFE_FREE(dn);
2636
2637         return NT_STATUS_OK;
2638 }
2639
2640 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
2641                                      const DOM_SID *alias,
2642                                      const DOM_SID *member)
2643 {
2644         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
2645 }
2646
2647 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
2648                                      const DOM_SID *alias,
2649                                      const DOM_SID *member)
2650 {
2651         return ldapsam_modify_aliasmem(methods, alias, member,
2652                                        LDAP_MOD_DELETE);
2653 }
2654
2655 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
2656                                       const DOM_SID *alias, DOM_SID **members,
2657                                       int *num_members)
2658 {
2659         struct ldapsam_privates *ldap_state =
2660                 (struct ldapsam_privates *)methods->private_data;
2661         LDAPMessage *result = NULL;
2662         LDAPMessage *entry = NULL;
2663         int count;
2664         char **values;
2665         int i;
2666         pstring filter;
2667
2668         *members = NULL;
2669         *num_members = 0;
2670
2671         pstr_sprintf(filter, "(&(|(objectClass=%s)(objectclass=%s))(%s=%s))",
2672                      LDAP_OBJ_GROUPMAP, LDAP_OBJ_IDMAP_ENTRY,
2673                      get_attr_key2string(groupmap_attr_list,
2674                                          LDAP_ATTR_GROUP_SID),
2675                      sid_string_static(alias));
2676
2677         if (ldapsam_search_one_group(ldap_state, filter,
2678                                      &result) != LDAP_SUCCESS)
2679                 return NT_STATUS_NO_SUCH_ALIAS;
2680
2681         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2682                                    result);
2683
2684         if (count < 1) {
2685                 DEBUG(4, ("ldapsam_add_aliasmem: Did not find alias\n"));
2686                 ldap_msgfree(result);
2687                 return NT_STATUS_NO_SUCH_ALIAS;
2688         }
2689
2690         if (count > 1) {
2691                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2692                           "count=%d\n", filter, count));
2693                 ldap_msgfree(result);
2694                 return NT_STATUS_NO_SUCH_ALIAS;
2695         }
2696
2697         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
2698                                  result);
2699
2700         if (!entry) {
2701                 ldap_msgfree(result);
2702                 return NT_STATUS_UNSUCCESSFUL;
2703         }
2704
2705         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
2706                                  entry,
2707                                  get_attr_key2string(groupmap_attr_list,
2708                                                      LDAP_ATTR_SID_LIST));
2709
2710         if (values == NULL) {
2711                 ldap_msgfree(result);
2712                 return NT_STATUS_OK;
2713         }
2714
2715         count = ldap_count_values(values);
2716
2717         for (i=0; i<count; i++) {
2718                 DOM_SID member;
2719
2720                 if (!string_to_sid(&member, values[i]))
2721                         continue;
2722
2723                 add_sid_to_array(&member, members, num_members);
2724         }
2725
2726         ldap_value_free(values);
2727         ldap_msgfree(result);
2728
2729         return NT_STATUS_OK;
2730 }
2731
2732 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
2733                                           const DOM_SID *sid,
2734                                           DOM_SID **aliases, int *num)
2735 {
2736         struct ldapsam_privates *ldap_state =
2737                 (struct ldapsam_privates *)methods->private_data;
2738
2739         fstring sid_string;
2740         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
2741
2742         LDAPMessage *result = NULL;
2743         LDAPMessage *entry = NULL;
2744         int count;
2745         int rc;
2746         pstring filter;
2747
2748         sid_to_string(sid_string, sid);
2749         pstr_sprintf(filter, "(&(|(objectclass=%s)(objectclass=%s))(%s=%s))",
2750                      LDAP_OBJ_GROUPMAP, LDAP_OBJ_IDMAP_ENTRY,
2751                      get_attr_key2string(groupmap_attr_list,
2752                                          LDAP_ATTR_SID_LIST), sid_string);
2753
2754         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
2755                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2756
2757         if (rc != LDAP_SUCCESS)
2758                 return NT_STATUS_UNSUCCESSFUL;
2759
2760         *aliases = NULL;
2761         *num = 0;
2762
2763         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2764                                    result);
2765
2766         if (count < 1) {
2767                 ldap_msgfree(result);
2768                 return NT_STATUS_OK;
2769         }
2770
2771
2772         for (entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
2773                                       result);
2774              entry != NULL;
2775              entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
2776                                      entry))
2777         {
2778                 DOM_SID alias;
2779                 char **vals;
2780                 vals = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
2781                                        entry, LDAP_ATTRIBUTE_SID);
2782
2783                 if (vals == NULL)
2784                         continue;
2785
2786                 if (vals[0] == NULL) {
2787                         ldap_value_free(vals);
2788                         continue;
2789                 }
2790
2791                 if (!string_to_sid(&alias, vals[0])) {
2792                         ldap_value_free(vals);
2793                         continue;
2794                 }
2795
2796                 add_sid_to_array(&alias, aliases, num);
2797                 ldap_value_free(vals);
2798         }
2799
2800         ldap_msgfree(result);
2801         return NT_STATUS_OK;
2802 }
2803
2804 /**********************************************************************
2805  Housekeeping
2806  *********************************************************************/
2807
2808 static void free_private_data(void **vp) 
2809 {
2810         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
2811
2812         smbldap_free_struct(&(*ldap_state)->smbldap_state);
2813
2814         if ((*ldap_state)->result != NULL) {
2815                 ldap_msgfree((*ldap_state)->result);
2816                 (*ldap_state)->result = NULL;
2817         }
2818
2819         *ldap_state = NULL;
2820
2821         /* No need to free any further, as it is talloc()ed */
2822 }
2823
2824 /**********************************************************************
2825  Intitalise the parts of the pdb_context that are common to all pdb_ldap modes
2826  *********************************************************************/
2827
2828 static NTSTATUS pdb_init_ldapsam_common(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, 
2829                                         const char *location)
2830 {
2831         NTSTATUS nt_status;
2832         struct ldapsam_privates *ldap_state;
2833
2834         if (!NT_STATUS_IS_OK(nt_status = make_pdb_methods(pdb_context->mem_ctx, pdb_method))) {
2835                 return nt_status;
2836         }
2837
2838         (*pdb_method)->name = "ldapsam";
2839
2840         (*pdb_method)->setsampwent = ldapsam_setsampwent;
2841         (*pdb_method)->endsampwent = ldapsam_endsampwent;
2842         (*pdb_method)->getsampwent = ldapsam_getsampwent;
2843         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
2844         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
2845         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
2846         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
2847         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
2848
2849         (*pdb_method)->getgrsid = ldapsam_getgrsid;
2850         (*pdb_method)->getgrgid = ldapsam_getgrgid;
2851         (*pdb_method)->getgrnam = ldapsam_getgrnam;
2852         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
2853         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
2854         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
2855         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
2856
2857         /* TODO: Setup private data and free */
2858
2859         ldap_state = talloc_zero(pdb_context->mem_ctx, sizeof(*ldap_state));
2860         if (!ldap_state) {
2861                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
2862                 return NT_STATUS_NO_MEMORY;
2863         }
2864
2865         if (!NT_STATUS_IS_OK(nt_status = 
2866                              smbldap_init(pdb_context->mem_ctx, location, 
2867                                           &ldap_state->smbldap_state)));
2868
2869         ldap_state->domain_name = talloc_strdup(pdb_context->mem_ctx, get_global_sam_name());
2870         if (!ldap_state->domain_name) {
2871                 return NT_STATUS_NO_MEMORY;
2872         }
2873
2874         (*pdb_method)->private_data = ldap_state;
2875
2876         (*pdb_method)->free_private_data = free_private_data;
2877
2878         return NT_STATUS_OK;
2879 }
2880
2881 /**********************************************************************
2882  Initialise the 'compat' mode for pdb_ldap
2883  *********************************************************************/
2884
2885 static NTSTATUS pdb_init_ldapsam_compat(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
2886 {
2887         NTSTATUS nt_status;
2888         struct ldapsam_privates *ldap_state;
2889
2890 #ifdef WITH_LDAP_SAMCONFIG
2891         if (!location) {
2892                 int ldap_port = lp_ldap_port();
2893                         
2894                 /* remap default port if not using SSL (ie clear or TLS) */
2895                 if ( (lp_ldap_ssl() != LDAP_SSL_ON) && (ldap_port == 636) ) {
2896                         ldap_port = 389;
2897                 }
2898
2899                 location = talloc_asprintf(pdb_context->mem_ctx, "%s://%s:%d", lp_ldap_ssl() == LDAP_SSL_ON ? "ldaps" : "ldap", lp_ldap_server(), ldap_port);
2900                 if (!location) {
2901                         return NT_STATUS_NO_MEMORY;
2902                 }
2903         }
2904 #endif
2905
2906         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
2907                 return nt_status;
2908         }
2909
2910         (*pdb_method)->name = "ldapsam_compat";
2911
2912         ldap_state = (*pdb_method)->private_data;
2913         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
2914
2915         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
2916
2917         return NT_STATUS_OK;
2918 }
2919
2920 /**********************************************************************
2921  Initialise the normal mode for pdb_ldap
2922  *********************************************************************/
2923
2924 static NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
2925 {
2926         NTSTATUS nt_status;
2927         struct ldapsam_privates *ldap_state;
2928         uint32 alg_rid_base;
2929         pstring alg_rid_base_string;
2930         LDAPMessage *result = NULL;
2931         LDAPMessage *entry = NULL;
2932         DOM_SID ldap_domain_sid;
2933         DOM_SID secrets_domain_sid;
2934         pstring domain_sid_string;
2935
2936         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
2937                 return nt_status;
2938         }
2939
2940         (*pdb_method)->name = "ldapsam";
2941
2942         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
2943         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
2944         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
2945         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
2946
2947         ldap_state = (*pdb_method)->private_data;
2948         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
2949
2950         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
2951         
2952         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state, &result, 
2953                                                ldap_state->domain_name, True);
2954         
2955         if ( !NT_STATUS_IS_OK(nt_status) ) {
2956                 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain info, nor add one to the domain\n"));
2957                 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, will be unable to allocate new users/groups, \
2958 and will risk BDCs having inconsistant SIDs\n"));
2959                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
2960                 return NT_STATUS_OK;
2961         }
2962
2963         /* Given that the above might fail, everything below this must be optional */
2964         
2965         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2966         if (!entry) {
2967                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info entry\n"));
2968                 ldap_msgfree(result);
2969                 return NT_STATUS_UNSUCCESSFUL;
2970         }
2971
2972         if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2973                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
2974                                  domain_sid_string)) {
2975                 BOOL found_sid;
2976                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
2977                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be read as a valid SID\n", domain_sid_string));
2978                         return NT_STATUS_INVALID_PARAMETER;
2979                 }
2980                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name, &secrets_domain_sid);
2981                 if (!found_sid || !sid_equal(&secrets_domain_sid, &ldap_domain_sid)) {
2982                         fstring new_sid_str, old_sid_str;
2983                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain %s based on pdb_ldap results %s -> %s\n",
2984                                   ldap_state->domain_name, 
2985                                   sid_to_string(old_sid_str, &secrets_domain_sid),
2986                                   sid_to_string(new_sid_str, &ldap_domain_sid)));
2987                         
2988                         /* reset secrets.tdb sid */
2989                         secrets_store_domain_sid(ldap_state->domain_name, &ldap_domain_sid);
2990                         DEBUG(1, ("New global sam SID: %s\n", sid_to_string(new_sid_str, get_global_sam_sid())));
2991                 }
2992                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
2993         }
2994
2995         if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2996                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ALGORITHMIC_RID_BASE), 
2997                                  alg_rid_base_string)) {
2998                 alg_rid_base = (uint32)atol(alg_rid_base_string);
2999                 if (alg_rid_base != algorithmic_rid_base()) {
3000                         DEBUG(0, ("The value of 'algorithmic RID base' has changed since the LDAP\n"
3001                                   "database was initialised.  Aborting. \n"));
3002                         ldap_msgfree(result);
3003                         return NT_STATUS_UNSUCCESSFUL;
3004                 }
3005         }
3006         ldap_msgfree(result);
3007
3008         return NT_STATUS_OK;
3009 }
3010
3011 NTSTATUS pdb_ldap_init(void)
3012 {
3013         NTSTATUS nt_status;
3014         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
3015                 return nt_status;
3016
3017         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
3018                 return nt_status;
3019
3020         return NT_STATUS_OK;
3021 }