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