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