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