r11137: Compile with only 2 warnings (I'm still working on that code) on a gcc4
[ira/wip.git] / source3 / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/CIFS implementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Jean François Micouleau        1998
5    Copyright (C) Gerald Carter                  2001-2003
6    Copyright (C) Shahms King                    2001
7    Copyright (C) Andrew Bartlett                2002-2003
8    Copyright (C) Stefan (metze) Metzmacher      2002-2003
9     
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23    
24 */
25
26 /* TODO:
27 *  persistent connections: if using NSS LDAP, many connections are made
28 *      however, using only one within Samba would be nice
29 *  
30 *  Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
31 *
32 *  Other LDAP based login attributes: accountExpires, etc.
33 *  (should be the domain of Samba proper, but the sam_password/SAM_ACCOUNT
34 *  structures don't have fields for some of these attributes)
35 *
36 *  SSL is done, but can't get the certificate based authentication to work
37 *  against on my test platform (Linux 2.4, OpenLDAP 2.x)
38 */
39
40 /* NOTE: this will NOT work against an Active Directory server
41 *  due to the fact that the two password fields cannot be retrieved
42 *  from a server; recommend using security = domain in this situation
43 *  and/or winbind
44 */
45
46 #include "includes.h"
47
48 #undef DBGC_CLASS
49 #define DBGC_CLASS DBGC_PASSDB
50
51 #include <lber.h>
52 #include <ldap.h>
53
54 /*
55  * Work around versions of the LDAP client libs that don't have the OIDs
56  * defined, or have them defined under the old name.  
57  * This functionality is really a factor of the server, not the client 
58  *
59  */
60
61 #if defined(LDAP_EXOP_X_MODIFY_PASSWD) && !defined(LDAP_EXOP_MODIFY_PASSWD)
62 #define LDAP_EXOP_MODIFY_PASSWD LDAP_EXOP_X_MODIFY_PASSWD
63 #elif !defined(LDAP_EXOP_MODIFY_PASSWD)
64 #define LDAP_EXOP_MODIFY_PASSWD "1.3.6.1.4.1.4203.1.11.1"
65 #endif
66
67 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_ID) && !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
68 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID LDAP_EXOP_X_MODIFY_PASSWD_ID
69 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
70 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID        ((ber_tag_t) 0x80U)
71 #endif
72
73 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_NEW) && !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
74 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW LDAP_EXOP_X_MODIFY_PASSWD_NEW
75 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
76 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW       ((ber_tag_t) 0x82U)
77 #endif
78
79
80 #ifndef SAM_ACCOUNT
81 #define SAM_ACCOUNT struct sam_passwd
82 #endif
83
84 #include "smbldap.h"
85
86 /**********************************************************************
87  Free a LDAPMessage (one is stored on the SAM_ACCOUNT).
88  **********************************************************************/
89  
90 void private_data_free_fn(void **result) 
91 {
92         ldap_msgfree(*result);
93         *result = NULL;
94 }
95
96 /**********************************************************************
97  Get the attribute name given a user schame version.
98  **********************************************************************/
99  
100 static const char* get_userattr_key2string( int schema_ver, int key )
101 {
102         switch ( schema_ver ) {
103                 case SCHEMAVER_SAMBAACCOUNT:
104                         return get_attr_key2string( attrib_map_v22, key );
105                         
106                 case SCHEMAVER_SAMBASAMACCOUNT:
107                         return get_attr_key2string( attrib_map_v30, key );
108                         
109                 default:
110                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
111                         break;
112         }
113         return NULL;
114 }
115
116 /**********************************************************************
117  Return the list of attribute names given a user schema version.
118 **********************************************************************/
119
120 const char** get_userattr_list( int schema_ver )
121 {
122         switch ( schema_ver ) {
123                 case SCHEMAVER_SAMBAACCOUNT:
124                         return get_attr_list( attrib_map_v22 );
125                         
126                 case SCHEMAVER_SAMBASAMACCOUNT:
127                         return get_attr_list( attrib_map_v30 );
128                 default:
129                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
130                         break;
131         }
132         
133         return NULL;
134 }
135
136 /**************************************************************************
137  Return the list of attribute names to delete given a user schema version.
138 **************************************************************************/
139
140 static const char** get_userattr_delete_list( int schema_ver )
141 {
142         switch ( schema_ver ) {
143                 case SCHEMAVER_SAMBAACCOUNT:
144                         return get_attr_list( attrib_map_to_delete_v22 );
145                         
146                 case SCHEMAVER_SAMBASAMACCOUNT:
147                         return get_attr_list( attrib_map_to_delete_v30 );
148                 default:
149                         DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
150                         break;
151         }
152         
153         return NULL;
154 }
155
156
157 /*******************************************************************
158  Generate the LDAP search filter for the objectclass based on the 
159  version of the schema we are using.
160 ******************************************************************/
161
162 static const char* get_objclass_filter( int schema_ver )
163 {
164         static fstring objclass_filter;
165         
166         switch( schema_ver ) {
167                 case SCHEMAVER_SAMBAACCOUNT:
168                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
169                         break;
170                 case SCHEMAVER_SAMBASAMACCOUNT:
171                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
172                         break;
173                 default:
174                         DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
175                         break;
176         }
177         
178         return objclass_filter; 
179 }
180
181 /*****************************************************************
182  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  Helper function to determine for update_sam_account whether
1875  we need LDAP modification.
1876  *********************************************************************/
1877
1878 static BOOL element_is_set_or_changed(const SAM_ACCOUNT *sampass,
1879                                       enum pdb_elements element)
1880 {
1881         return (IS_SAM_SET(sampass, element) ||
1882                 IS_SAM_CHANGED(sampass, element));
1883 }
1884
1885 /**********************************************************************
1886  Add SAM_ACCOUNT to LDAP.
1887 *********************************************************************/
1888
1889 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * newpwd)
1890 {
1891         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1892         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1893         int rc;
1894         LDAPMessage     *result = NULL;
1895         LDAPMessage     *entry  = NULL;
1896         pstring         dn;
1897         LDAPMod         **mods = NULL;
1898         int             ldap_op = LDAP_MOD_REPLACE;
1899         uint32          num_result;
1900         const char      **attr_list;
1901         char            *escape_user;
1902         const char      *username = pdb_get_username(newpwd);
1903         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
1904         pstring         filter;
1905         fstring         sid_string;
1906
1907         if (!username || !*username) {
1908                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
1909                 return NT_STATUS_INVALID_PARAMETER;
1910         }
1911
1912         /* free this list after the second search or in case we exit on failure */
1913         attr_list = get_userattr_list(ldap_state->schema_ver);
1914
1915         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
1916
1917         if (rc != LDAP_SUCCESS) {
1918                 free_attr_list( attr_list );
1919                 return NT_STATUS_UNSUCCESSFUL;
1920         }
1921
1922         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1923                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
1924                          username));
1925                 ldap_msgfree(result);
1926                 free_attr_list( attr_list );
1927                 return NT_STATUS_UNSUCCESSFUL;
1928         }
1929         ldap_msgfree(result);
1930         result = NULL;
1931
1932         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
1933                 rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1934                                                   sid, &result); 
1935                 if (rc == LDAP_SUCCESS) {
1936                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1937                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' already in the base, with samba attributes\n", 
1938                                          sid_to_string(sid_string, sid)));
1939                                 free_attr_list( attr_list );
1940                                 ldap_msgfree(result);
1941                                 return NT_STATUS_UNSUCCESSFUL;
1942                         }
1943                         ldap_msgfree(result);
1944                 }
1945         }
1946
1947         /* does the entry already exist but without a samba attributes?
1948            we need to return the samba attributes here */
1949            
1950         escape_user = escape_ldap_string_alloc( username );
1951         pstrcpy( filter, "(uid=%u)" );
1952         all_string_sub( filter, "%u", escape_user, sizeof(filter) );
1953         SAFE_FREE( escape_user );
1954
1955         rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1956                                    filter, attr_list, &result);
1957         if ( rc != LDAP_SUCCESS ) {
1958                 free_attr_list( attr_list );
1959                 return NT_STATUS_UNSUCCESSFUL;
1960         }
1961
1962         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1963         
1964         if (num_result > 1) {
1965                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1966                 free_attr_list( attr_list );
1967                 ldap_msgfree(result);
1968                 return NT_STATUS_UNSUCCESSFUL;
1969         }
1970         
1971         /* Check if we need to update an existing entry */
1972         if (num_result == 1) {
1973                 char *tmp;
1974                 
1975                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1976                 ldap_op = LDAP_MOD_REPLACE;
1977                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1978                 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1979                 if (!tmp) {
1980                         free_attr_list( attr_list );
1981                         ldap_msgfree(result);
1982                         return NT_STATUS_UNSUCCESSFUL;
1983                 }
1984                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1985                 SAFE_FREE(tmp);
1986
1987         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
1988
1989                 /* There might be a SID for this account already - say an idmap entry */
1990
1991                 pstr_sprintf(filter, "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))", 
1992                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1993                          sid_to_string(sid_string, sid),
1994                          LDAP_OBJ_IDMAP_ENTRY,
1995                          LDAP_OBJ_SID_ENTRY);
1996                 
1997                 /* free old result before doing a new search */
1998                 if (result != NULL) {
1999                         ldap_msgfree(result);
2000                         result = NULL;
2001                 }
2002                 rc = smbldap_search_suffix(ldap_state->smbldap_state, 
2003                                            filter, attr_list, &result);
2004                         
2005                 if ( rc != LDAP_SUCCESS ) {
2006                         free_attr_list( attr_list );
2007                         return NT_STATUS_UNSUCCESSFUL;
2008                 }
2009                 
2010                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2011                 
2012                 if (num_result > 1) {
2013                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2014                         free_attr_list( attr_list );
2015                         ldap_msgfree(result);
2016                         return NT_STATUS_UNSUCCESSFUL;
2017                 }
2018                 
2019                 /* Check if we need to update an existing entry */
2020                 if (num_result == 1) {
2021                         char *tmp;
2022                         
2023                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2024                         ldap_op = LDAP_MOD_REPLACE;
2025                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2026                         tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
2027                         if (!tmp) {
2028                                 free_attr_list( attr_list );
2029                                 ldap_msgfree(result);
2030                                 return NT_STATUS_UNSUCCESSFUL;
2031                         }
2032                         slprintf (dn, sizeof (dn) - 1, "%s", tmp);
2033                         SAFE_FREE(tmp);
2034                 }
2035         }
2036         
2037         free_attr_list( attr_list );
2038
2039         if (num_result == 0) {
2040                 /* Check if we need to add an entry */
2041                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2042                 ldap_op = LDAP_MOD_ADD;
2043                 if (username[strlen(username)-1] == '$') {
2044                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_machine_suffix ());
2045                 } else {
2046                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_user_suffix ());
2047                 }
2048         }
2049
2050         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2051                                 element_is_set_or_changed)) {
2052                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2053                 ldap_msgfree(result);
2054                 if (mods != NULL)
2055                         ldap_mods_free(mods,True);
2056                 return NT_STATUS_UNSUCCESSFUL;          
2057         }
2058         
2059         ldap_msgfree(result);
2060
2061         if (mods == NULL) {
2062                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2063                 return NT_STATUS_UNSUCCESSFUL;
2064         }
2065         switch ( ldap_state->schema_ver ) {
2066                 case SCHEMAVER_SAMBAACCOUNT:
2067                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2068                         break;
2069                 case SCHEMAVER_SAMBASAMACCOUNT:
2070                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2071                         break;
2072                 default:
2073                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2074                         break;
2075         }
2076
2077         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2078         if (!NT_STATUS_IS_OK(ret)) {
2079                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2080                          pdb_get_username(newpwd),dn));
2081                 ldap_mods_free(mods, True);
2082                 return ret;
2083         }
2084
2085         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2086         ldap_mods_free(mods, True);
2087         
2088         return NT_STATUS_OK;
2089 }
2090
2091 /**********************************************************************
2092  *********************************************************************/
2093
2094 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2095                                      const char *filter,
2096                                      LDAPMessage ** result)
2097 {
2098         int scope = LDAP_SCOPE_SUBTREE;
2099         int rc;
2100         const char **attr_list;
2101
2102         attr_list = get_attr_list(groupmap_attr_list);
2103         rc = smbldap_search(ldap_state->smbldap_state, 
2104                             lp_ldap_group_suffix (), scope,
2105                             filter, attr_list, 0, result);
2106         free_attr_list( attr_list );
2107
2108         if (rc != LDAP_SUCCESS) {
2109                 char *ld_error = NULL;
2110                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2111                                 &ld_error);
2112                 DEBUG(0, ("ldapsam_search_one_group: "
2113                           "Problem during the LDAP search: LDAP error: %s (%s)\n",
2114                           ld_error?ld_error:"(unknown)", ldap_err2string(rc)));
2115                 DEBUGADD(3, ("ldapsam_search_one_group: Query was: %s, %s\n",
2116                           lp_ldap_group_suffix(), filter));
2117                 SAFE_FREE(ld_error);
2118         }
2119
2120         return rc;
2121 }
2122
2123 /**********************************************************************
2124  *********************************************************************/
2125
2126 static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
2127                                  GROUP_MAP *map, LDAPMessage *entry)
2128 {
2129         pstring temp;
2130
2131         if (ldap_state == NULL || map == NULL || entry == NULL ||
2132                         ldap_state->smbldap_state->ldap_struct == NULL) {
2133                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2134                 return False;
2135         }
2136
2137         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2138                         get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER), temp)) {
2139                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2140                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2141                 return False;
2142         }
2143         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2144
2145         map->gid = (gid_t)atol(temp);
2146
2147         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2148                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID), temp)) {
2149                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2150                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2151                 return False;
2152         }
2153         
2154         if (!string_to_sid(&map->sid, temp)) {
2155                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2156                 return False;
2157         }
2158
2159         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2160                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), temp)) {
2161                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2162                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2163                 return False;
2164         }
2165         map->sid_name_use = (enum SID_NAME_USE)atol(temp);
2166
2167         if ((map->sid_name_use < SID_NAME_USER) ||
2168                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2169                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2170                 return False;
2171         }
2172
2173         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2174                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), temp)) {
2175                 temp[0] = '\0';
2176                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2177                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_CN), temp)) 
2178                 {
2179                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2180 for gidNumber(%lu)\n",(unsigned long)map->gid));
2181                         return False;
2182                 }
2183         }
2184         fstrcpy(map->nt_name, temp);
2185
2186         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2187                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), temp)) {
2188                 temp[0] = '\0';
2189         }
2190         fstrcpy(map->comment, temp);
2191
2192         return True;
2193 }
2194
2195 /**********************************************************************
2196  *********************************************************************/
2197
2198 static BOOL init_ldap_from_group(LDAP *ldap_struct,
2199                                  LDAPMessage *existing,
2200                                  LDAPMod ***mods,
2201                                  const GROUP_MAP *map)
2202 {
2203         pstring tmp;
2204
2205         if (mods == NULL || map == NULL) {
2206                 DEBUG(0, ("init_ldap_from_group: NULL parameters found!\n"));
2207                 return False;
2208         }
2209
2210         *mods = NULL;
2211
2212         sid_to_string(tmp, &map->sid);
2213
2214         smbldap_make_mod(ldap_struct, existing, mods, 
2215                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID), tmp);
2216         pstr_sprintf(tmp, "%i", map->sid_name_use);
2217         smbldap_make_mod(ldap_struct, existing, mods, 
2218                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), tmp);
2219
2220         smbldap_make_mod(ldap_struct, existing, mods, 
2221                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), map->nt_name);
2222         smbldap_make_mod(ldap_struct, existing, mods, 
2223                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), map->comment);
2224
2225         return True;
2226 }
2227
2228 /**********************************************************************
2229  *********************************************************************/
2230
2231 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2232                                  const char *filter,
2233                                  GROUP_MAP *map)
2234 {
2235         struct ldapsam_privates *ldap_state =
2236                 (struct ldapsam_privates *)methods->private_data;
2237         LDAPMessage *result = NULL;
2238         LDAPMessage *entry = NULL;
2239         int count;
2240
2241         if (ldapsam_search_one_group(ldap_state, filter, &result)
2242             != LDAP_SUCCESS) {
2243                 return NT_STATUS_NO_SUCH_GROUP;
2244         }
2245
2246         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2247
2248         if (count < 1) {
2249                 DEBUG(4, ("ldapsam_getgroup: Did not find group\n"));
2250                 ldap_msgfree(result);
2251                 return NT_STATUS_NO_SUCH_GROUP;
2252         }
2253
2254         if (count > 1) {
2255                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: count=%d\n",
2256                           filter, count));
2257                 ldap_msgfree(result);
2258                 return NT_STATUS_NO_SUCH_GROUP;
2259         }
2260
2261         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2262
2263         if (!entry) {
2264                 ldap_msgfree(result);
2265                 return NT_STATUS_UNSUCCESSFUL;
2266         }
2267
2268         if (!init_group_from_ldap(ldap_state, map, entry)) {
2269                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for group filter %s\n",
2270                           filter));
2271                 ldap_msgfree(result);
2272                 return NT_STATUS_NO_SUCH_GROUP;
2273         }
2274
2275         ldap_msgfree(result);
2276         return NT_STATUS_OK;
2277 }
2278
2279 /**********************************************************************
2280  *********************************************************************/
2281
2282 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2283                                  DOM_SID sid)
2284 {
2285         pstring filter;
2286
2287         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
2288                 LDAP_OBJ_GROUPMAP, 
2289                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2290                 sid_string_static(&sid));
2291
2292         return ldapsam_getgroup(methods, filter, map);
2293 }
2294
2295 /**********************************************************************
2296  *********************************************************************/
2297
2298 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2299                                  gid_t gid)
2300 {
2301         pstring filter;
2302
2303         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))",
2304                 LDAP_OBJ_GROUPMAP,
2305                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2306                 (unsigned long)gid);
2307
2308         return ldapsam_getgroup(methods, filter, map);
2309 }
2310
2311 /**********************************************************************
2312  *********************************************************************/
2313
2314 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2315                                  const char *name)
2316 {
2317         pstring filter;
2318         char *escape_name = escape_ldap_string_alloc(name);
2319
2320         if (!escape_name) {
2321                 return NT_STATUS_NO_MEMORY;
2322         }
2323
2324         pstr_sprintf(filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2325                 LDAP_OBJ_GROUPMAP,
2326                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2327                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN), escape_name);
2328
2329         SAFE_FREE(escape_name);
2330
2331         return ldapsam_getgroup(methods, filter, map);
2332 }
2333
2334 static void add_rid_to_array_unique(TALLOC_CTX *mem_ctx,
2335                                     uint32 rid, uint32 **pp_rids, size_t *p_num)
2336 {
2337         size_t i;
2338
2339         for (i=0; i<*p_num; i++) {
2340                 if ((*pp_rids)[i] == rid)
2341                         return;
2342         }
2343         
2344         *pp_rids = TALLOC_REALLOC_ARRAY(mem_ctx, *pp_rids, uint32, *p_num+1);
2345
2346         if (*pp_rids == NULL)
2347                 return;
2348
2349         (*pp_rids)[*p_num] = rid;
2350         *p_num += 1;
2351 }
2352
2353 static BOOL ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2354                                            LDAPMessage *entry,
2355                                            const DOM_SID *domain_sid,
2356                                            uint32 *rid)
2357 {
2358         fstring str;
2359         DOM_SID sid;
2360
2361         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2362                                           str, sizeof(str)-1)) {
2363                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2364                 return False;
2365         }
2366
2367         if (!string_to_sid(&sid, str)) {
2368                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2369                 return False;
2370         }
2371
2372         if (sid_compare_domain(&sid, domain_sid) != 0) {
2373                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2374                            str, sid_string_static(domain_sid)));
2375                 return False;
2376         }
2377
2378         if (!sid_peek_rid(&sid, rid)) {
2379                 DEBUG(10, ("Could not peek into RID\n"));
2380                 return False;
2381         }
2382
2383         return True;
2384 }
2385
2386 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2387                                            TALLOC_CTX *mem_ctx,
2388                                            const DOM_SID *group,
2389                                            uint32 **pp_member_rids,
2390                                            size_t *p_num_members)
2391 {
2392         struct ldapsam_privates *ldap_state =
2393                 (struct ldapsam_privates *)methods->private_data;
2394         struct smbldap_state *conn = ldap_state->smbldap_state;
2395         pstring filter;
2396         int rc, count;
2397         LDAPMessage *msg = NULL;
2398         LDAPMessage *entry;
2399         char **values = NULL;
2400         char **memberuid;
2401         char *sid_filter = NULL;
2402         char *tmp;
2403         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2404
2405         if (!lp_parm_bool(-1, "ldapsam", "trusted", False))
2406                 return pdb_default_enum_group_members(methods, mem_ctx, group,
2407                                                       pp_member_rids,
2408                                                       p_num_members);
2409
2410         *pp_member_rids = NULL;
2411         *p_num_members = 0;
2412
2413         pstr_sprintf(filter,
2414                      "(&(objectClass=sambaSamAccount)"
2415                      "(sambaPrimaryGroupSid=%s))",
2416                      sid_string_static(group));
2417
2418         {
2419                 const char *attrs[] = { "sambaSID", NULL };
2420                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2421                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2422                                     &msg);
2423         }
2424
2425         if (rc != LDAP_SUCCESS)
2426                 goto done;
2427
2428         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2429              entry != NULL;
2430              entry = ldap_next_entry(conn->ldap_struct, entry))
2431         {
2432                 uint32 rid;
2433
2434                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2435                                                     entry,
2436                                                     get_global_sam_sid(),
2437                                                     &rid)) {
2438                         DEBUG(2, ("Could not find sid from ldap entry\n"));
2439                         continue;
2440                 }
2441
2442                 add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2443                                         p_num_members);
2444         }
2445
2446         if (msg != NULL)
2447                 ldap_msgfree(msg);
2448
2449         pstr_sprintf(filter,
2450                      "(&(objectClass=sambaGroupMapping)"
2451                      "(objectClass=posixGroup)"
2452                      "(sambaSID=%s))",
2453                      sid_string_static(group));
2454
2455         {
2456                 const char *attrs[] = { "memberUid", NULL };
2457                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2458                                     LDAP_SCOPE_SUBTREE, filter, attrs, 0,
2459                                     &msg);
2460         }
2461
2462         if (rc != LDAP_SUCCESS)
2463                 goto done;
2464
2465         count = ldap_count_entries(conn->ldap_struct, msg);
2466
2467         if (count > 1) {
2468                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2469                           sid_string_static(group)));
2470                 goto done;
2471         }
2472
2473         if (count == 0) {
2474                 result = NT_STATUS_OK;
2475                 goto done;
2476         }
2477
2478         entry = ldap_first_entry(conn->ldap_struct, msg);
2479         if (entry == NULL)
2480                 goto done;
2481
2482         values = ldap_get_values(conn->ldap_struct, msg, "memberUid");
2483         if (values == NULL) {
2484                 result = NT_STATUS_OK;
2485                 goto done;
2486         }
2487
2488         sid_filter = SMB_STRDUP("(&(objectClass=sambaSamAccount)(|");
2489         if (sid_filter == NULL) {
2490                 result = NT_STATUS_NO_MEMORY;
2491                 goto done;
2492         }
2493
2494         for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2495                 tmp = sid_filter;
2496                 asprintf(&sid_filter, "%s(uid=%s)", tmp, *memberuid);
2497                 free(tmp);
2498                 if (sid_filter == NULL) {
2499                         result = NT_STATUS_NO_MEMORY;
2500                         goto done;
2501                 }
2502         }
2503
2504         tmp = sid_filter;
2505         asprintf(&sid_filter, "%s))", sid_filter);
2506         free(tmp);
2507         if (sid_filter == NULL) {
2508                 result = NT_STATUS_NO_MEMORY;
2509                 goto done;
2510         }
2511
2512         {
2513                 const char *attrs[] = { "sambaSID", NULL };
2514                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2515                                     LDAP_SCOPE_SUBTREE, sid_filter, attrs, 0,
2516                                     &msg);
2517         }
2518
2519         if (rc != LDAP_SUCCESS)
2520                 goto done;
2521
2522         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2523              entry != NULL;
2524              entry = ldap_next_entry(conn->ldap_struct, entry))
2525         {
2526                 fstring str;
2527                 DOM_SID sid;
2528                 uint32 rid;
2529
2530                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2531                                                   entry, "sambaSID",
2532                                                   str, sizeof(str)-1))
2533                         continue;
2534
2535                 if (!string_to_sid(&sid, str))
2536                         goto done;
2537
2538                 if (!sid_check_is_in_our_domain(&sid)) {
2539                         DEBUG(1, ("Inconsistent SAM -- group member uid not "
2540                                   "in our domain\n"));
2541                         continue;
2542                 }
2543
2544                 sid_peek_rid(&sid, &rid);
2545
2546                 add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2547                                         p_num_members);
2548         }
2549
2550         result = NT_STATUS_OK;
2551         
2552  done:
2553         SAFE_FREE(sid_filter);
2554
2555         if (values != NULL)
2556                 ldap_value_free(values);
2557
2558         if (msg != NULL)
2559                 ldap_msgfree(msg);
2560
2561         return result;
2562 }
2563
2564 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2565                                                const char *username,
2566                                                gid_t primary_gid,
2567                                                DOM_SID **pp_sids, gid_t **pp_gids,
2568                                                size_t *p_num_groups)
2569 {
2570         struct ldapsam_privates *ldap_state =
2571                 (struct ldapsam_privates *)methods->private_data;
2572         struct smbldap_state *conn = ldap_state->smbldap_state;
2573         pstring filter;
2574         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2575         char *escape_name;
2576         int rc;
2577         LDAPMessage *msg = NULL;
2578         LDAPMessage *entry;
2579         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
2580         size_t num_sids, num_gids;
2581
2582         if (!lp_parm_bool(-1, "ldapsam", "trusted", False))
2583                 return pdb_default_enum_group_memberships(methods, username,
2584                                                           primary_gid, pp_sids,
2585                                                           pp_gids, p_num_groups);
2586
2587         *pp_sids = NULL;
2588         num_sids = 0;
2589
2590         escape_name = escape_ldap_string_alloc(username);
2591
2592         if (escape_name == NULL)
2593                 return NT_STATUS_NO_MEMORY;
2594
2595         pstr_sprintf(filter, "(&(objectClass=posixGroup)"
2596                      "(|(memberUid=%s)(gidNumber=%d)))",
2597                      username, primary_gid);
2598
2599         rc = smbldap_search(conn, lp_ldap_group_suffix(),
2600                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &msg);
2601
2602         if (rc != LDAP_SUCCESS)
2603                 goto done;
2604
2605         num_gids = 0;
2606         *pp_gids = NULL;
2607
2608         num_sids = 0;
2609         *pp_sids = NULL;
2610
2611         /* We need to add the primary group as the first gid/sid */
2612
2613         add_gid_to_array_unique(NULL, primary_gid, pp_gids, &num_gids);
2614
2615         /* This sid will be replaced later */
2616
2617         add_sid_to_array_unique(NULL, &global_sid_NULL, pp_sids, &num_sids);
2618
2619         for (entry = ldap_first_entry(conn->ldap_struct, msg);
2620              entry != NULL;
2621              entry = ldap_next_entry(conn->ldap_struct, entry))
2622         {
2623                 fstring str;
2624                 DOM_SID sid;
2625                 gid_t gid;
2626                 char *end;
2627
2628                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2629                                                   entry, "sambaSID",
2630                                                   str, sizeof(str)-1))
2631                         continue;
2632
2633                 if (!string_to_sid(&sid, str))
2634                         goto done;
2635
2636                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2637                                                   entry, "gidNumber",
2638                                                   str, sizeof(str)-1))
2639                         continue;
2640
2641                 gid = strtoul(str, &end, 10);
2642
2643                 if (PTR_DIFF(end, str) != strlen(str))
2644                         goto done;
2645
2646                 if (gid == primary_gid) {
2647                         sid_copy(&(*pp_sids)[0], &sid);
2648                 } else {
2649                         add_gid_to_array_unique(NULL, gid, pp_gids, &num_gids);
2650                         add_sid_to_array_unique(NULL, &sid, pp_sids, &num_sids);
2651                 }
2652         }
2653
2654         if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2655                 DEBUG(3, ("primary group of [%s] not found\n", username));
2656                 goto done;
2657         }
2658
2659         *p_num_groups = num_sids;
2660
2661         result = NT_STATUS_OK;
2662
2663  done:
2664
2665         SAFE_FREE(escape_name);
2666         if (msg != NULL)
2667                 ldap_msgfree(msg);
2668
2669         return result;
2670 }
2671
2672 /**********************************************************************
2673  *********************************************************************/
2674
2675 static int ldapsam_search_one_group_by_gid(struct ldapsam_privates *ldap_state,
2676                                            gid_t gid,
2677                                            LDAPMessage **result)
2678 {
2679         pstring filter;
2680
2681         pstr_sprintf(filter, "(&(|(objectClass=%s)(objectclass=%s))(%s=%lu))", 
2682                 LDAP_OBJ_POSIXGROUP, LDAP_OBJ_IDMAP_ENTRY,
2683                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2684                 (unsigned long)gid);
2685
2686         return ldapsam_search_one_group(ldap_state, filter, result);
2687 }
2688
2689 /**********************************************************************
2690  *********************************************************************/
2691
2692 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
2693                                                 GROUP_MAP *map)
2694 {
2695         struct ldapsam_privates *ldap_state =
2696                 (struct ldapsam_privates *)methods->private_data;
2697         LDAPMessage *result = NULL;
2698         LDAPMod **mods = NULL;
2699         int count;
2700
2701         char *tmp;
2702         pstring dn;
2703         LDAPMessage *entry;
2704
2705         GROUP_MAP dummy;
2706
2707         int rc;
2708
2709         if (NT_STATUS_IS_OK(ldapsam_getgrgid(methods, &dummy,
2710                                              map->gid))) {
2711                 DEBUG(0, ("ldapsam_add_group_mapping_entry: Group %ld already exists in LDAP\n", (unsigned long)map->gid));
2712                 return NT_STATUS_UNSUCCESSFUL;
2713         }
2714
2715         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
2716         if (rc != LDAP_SUCCESS) {
2717                 ldap_msgfree(result);
2718                 return NT_STATUS_UNSUCCESSFUL;
2719         }
2720
2721         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2722
2723         if ( count == 0 ) {
2724                 /* There's no posixGroup account, let's try to find an
2725                  * appropriate idmap entry for aliases */
2726
2727                 pstring suffix;
2728                 pstring filter;
2729                 const char **attr_list;
2730
2731                 ldap_msgfree(result);
2732
2733                 pstrcpy( suffix, lp_ldap_idmap_suffix() );
2734                 pstr_sprintf(filter, "(&(objectClass=%s)(%s=%u))",
2735                              LDAP_OBJ_IDMAP_ENTRY, LDAP_ATTRIBUTE_GIDNUMBER,
2736                              map->gid);
2737                 
2738                 attr_list = get_attr_list( sidmap_attr_list );
2739                 rc = smbldap_search(ldap_state->smbldap_state, suffix,
2740                                     LDAP_SCOPE_SUBTREE, filter, attr_list,
2741                                     0, &result);
2742
2743                 free_attr_list(attr_list);
2744
2745                 if (rc != LDAP_SUCCESS) {
2746                         DEBUG(3,("Failure looking up entry (%s)\n",
2747                                  ldap_err2string(rc) ));
2748                         ldap_msgfree(result);
2749                         return NT_STATUS_UNSUCCESSFUL;
2750                 }
2751         }
2752                            
2753         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2754         if ( count == 0 ) {
2755                 ldap_msgfree(result);
2756                 return NT_STATUS_UNSUCCESSFUL;
2757         }
2758
2759         if (count > 1) {
2760                 DEBUG(2, ("ldapsam_add_group_mapping_entry: Group %lu must exist exactly once in LDAP\n",
2761                           (unsigned long)map->gid));
2762                 ldap_msgfree(result);
2763                 return NT_STATUS_UNSUCCESSFUL;
2764         }
2765
2766         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2767         tmp = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2768         if (!tmp) {
2769                 ldap_msgfree(result);
2770                 return NT_STATUS_UNSUCCESSFUL;
2771         }
2772         pstrcpy(dn, tmp);
2773         SAFE_FREE(tmp);
2774
2775         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
2776                                   result, &mods, map)) {
2777                 DEBUG(0, ("ldapsam_add_group_mapping_entry: init_ldap_from_group failed!\n"));
2778                 ldap_mods_free(mods, True);
2779                 ldap_msgfree(result);
2780                 return NT_STATUS_UNSUCCESSFUL;
2781         }
2782
2783         ldap_msgfree(result);
2784
2785         if (mods == NULL) {
2786                 DEBUG(0, ("ldapsam_add_group_mapping_entry: mods is empty\n"));
2787                 return NT_STATUS_UNSUCCESSFUL;
2788         }
2789
2790         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP );
2791
2792         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2793         ldap_mods_free(mods, True);
2794
2795         if (rc != LDAP_SUCCESS) {
2796                 char *ld_error = NULL;
2797                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2798                                 &ld_error);
2799                 DEBUG(0, ("ldapsam_add_group_mapping_entry: failed to add group %lu error: %s (%s)\n", (unsigned long)map->gid, 
2800                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
2801                 SAFE_FREE(ld_error);
2802                 return NT_STATUS_UNSUCCESSFUL;
2803         }
2804
2805         DEBUG(2, ("ldapsam_add_group_mapping_entry: successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
2806         return NT_STATUS_OK;
2807 }
2808
2809 /**********************************************************************
2810  *********************************************************************/
2811
2812 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
2813                                                    GROUP_MAP *map)
2814 {
2815         struct ldapsam_privates *ldap_state =
2816                 (struct ldapsam_privates *)methods->private_data;
2817         int rc;
2818         char *dn = NULL;
2819         LDAPMessage *result = NULL;
2820         LDAPMessage *entry = NULL;
2821         LDAPMod **mods = NULL;
2822
2823         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
2824
2825         if (rc != LDAP_SUCCESS) {
2826                 return NT_STATUS_UNSUCCESSFUL;
2827         }
2828
2829         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
2830                 DEBUG(0, ("ldapsam_update_group_mapping_entry: No group to modify!\n"));
2831                 ldap_msgfree(result);
2832                 return NT_STATUS_UNSUCCESSFUL;
2833         }
2834
2835         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2836
2837         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
2838                                   result, &mods, map)) {
2839                 DEBUG(0, ("ldapsam_update_group_mapping_entry: init_ldap_from_group failed\n"));
2840                 ldap_msgfree(result);
2841                 if (mods != NULL)
2842                         ldap_mods_free(mods,True);
2843                 return NT_STATUS_UNSUCCESSFUL;
2844         }
2845
2846         if (mods == NULL) {
2847                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: nothing to do\n"));
2848                 ldap_msgfree(result);
2849                 return NT_STATUS_OK;
2850         }
2851
2852         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
2853         if (!dn) {
2854                 ldap_msgfree(result);
2855                 return NT_STATUS_UNSUCCESSFUL;
2856         }
2857         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2858         SAFE_FREE(dn);
2859
2860         ldap_mods_free(mods, True);
2861         ldap_msgfree(result);
2862
2863         if (rc != LDAP_SUCCESS) {
2864                 char *ld_error = NULL;
2865                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2866                                 &ld_error);
2867                 DEBUG(0, ("ldapsam_update_group_mapping_entry: failed to modify group %lu error: %s (%s)\n", (unsigned long)map->gid, 
2868                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
2869                 SAFE_FREE(ld_error);
2870                 return NT_STATUS_UNSUCCESSFUL;
2871         }
2872
2873         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
2874         return NT_STATUS_OK;
2875 }
2876
2877 /**********************************************************************
2878  *********************************************************************/
2879
2880 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
2881                                                    DOM_SID sid)
2882 {
2883         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)methods->private_data;
2884         pstring sidstring, filter;
2885         LDAPMessage *result = NULL;
2886         int rc;
2887         NTSTATUS ret;
2888         const char **attr_list;
2889
2890         sid_to_string(sidstring, &sid);
2891         
2892         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))", 
2893                 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID, sidstring);
2894
2895         rc = ldapsam_search_one_group(ldap_state, filter, &result);
2896
2897         if (rc != LDAP_SUCCESS) {
2898                 return NT_STATUS_NO_SUCH_GROUP;
2899         }
2900
2901         attr_list = get_attr_list( groupmap_attr_list_to_delete );
2902         ret = ldapsam_delete_entry(ldap_state, result, LDAP_OBJ_GROUPMAP, attr_list);
2903         free_attr_list ( attr_list );
2904
2905         ldap_msgfree(result);
2906
2907         return ret;
2908 }
2909
2910 /**********************************************************************
2911  *********************************************************************/
2912
2913 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods, BOOL update)
2914 {
2915         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2916         fstring filter;
2917         int rc;
2918         const char **attr_list;
2919
2920         pstr_sprintf( filter, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
2921         attr_list = get_attr_list( groupmap_attr_list );
2922         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
2923                             LDAP_SCOPE_SUBTREE, filter,
2924                             attr_list, 0, &ldap_state->result);
2925         free_attr_list( attr_list );
2926
2927         if (rc != LDAP_SUCCESS) {
2928                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n", ldap_err2string(rc)));
2929                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n", lp_ldap_group_suffix(), filter));
2930                 ldap_msgfree(ldap_state->result);
2931                 ldap_state->result = NULL;
2932                 return NT_STATUS_UNSUCCESSFUL;
2933         }
2934
2935         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
2936                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2937                                      ldap_state->result)));
2938
2939         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, ldap_state->result);
2940         ldap_state->index = 0;
2941
2942         return NT_STATUS_OK;
2943 }
2944
2945 /**********************************************************************
2946  *********************************************************************/
2947
2948 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
2949 {
2950         ldapsam_endsampwent(my_methods);
2951 }
2952
2953 /**********************************************************************
2954  *********************************************************************/
2955
2956 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
2957                                     GROUP_MAP *map)
2958 {
2959         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2960         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2961         BOOL bret = False;
2962
2963         while (!bret) {
2964                 if (!ldap_state->entry)
2965                         return ret;
2966                 
2967                 ldap_state->index++;
2968                 bret = init_group_from_ldap(ldap_state, map, ldap_state->entry);
2969                 
2970                 ldap_state->entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
2971                                             ldap_state->entry); 
2972         }
2973
2974         return NT_STATUS_OK;
2975 }
2976
2977 /**********************************************************************
2978  *********************************************************************/
2979
2980 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
2981                                            enum SID_NAME_USE sid_name_use,
2982                                            GROUP_MAP **pp_rmap, size_t *p_num_entries,
2983                                            BOOL unix_only)
2984 {
2985         GROUP_MAP map;
2986         GROUP_MAP *mapt;
2987         size_t entries = 0;
2988
2989         *p_num_entries = 0;
2990         *pp_rmap = NULL;
2991
2992         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
2993                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open passdb\n"));
2994                 return NT_STATUS_ACCESS_DENIED;
2995         }
2996
2997         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
2998                 if (sid_name_use != SID_NAME_UNKNOWN &&
2999                     sid_name_use != map.sid_name_use) {
3000                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is not of the requested type\n", map.nt_name));
3001                         continue;
3002                 }
3003                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3004                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is non mapped\n", map.nt_name));
3005                         continue;
3006                 }
3007
3008                 mapt=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3009                 if (!mapt) {
3010                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to enlarge group map!\n"));
3011                         SAFE_FREE(*pp_rmap);
3012                         return NT_STATUS_UNSUCCESSFUL;
3013                 }
3014                 else
3015                         (*pp_rmap) = mapt;
3016
3017                 mapt[entries] = map;
3018
3019                 entries += 1;
3020
3021         }
3022         ldapsam_endsamgrent(methods);
3023
3024         *p_num_entries = entries;
3025
3026         return NT_STATUS_OK;
3027 }
3028
3029 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3030                                         const DOM_SID *alias,
3031                                         const DOM_SID *member,
3032                                         int modop)
3033 {
3034         struct ldapsam_privates *ldap_state =
3035                 (struct ldapsam_privates *)methods->private_data;
3036         char *dn;
3037         LDAPMessage *result = NULL;
3038         LDAPMessage *entry = NULL;
3039         int count;
3040         LDAPMod **mods = NULL;
3041         int rc;
3042
3043         pstring filter;
3044
3045         pstr_sprintf(filter, "(&(|(objectClass=%s)(objectclass=%s))(%s=%s))",
3046                      LDAP_OBJ_GROUPMAP, LDAP_OBJ_IDMAP_ENTRY,
3047                      get_attr_key2string(groupmap_attr_list,
3048                                          LDAP_ATTR_GROUP_SID),
3049                      sid_string_static(alias));
3050
3051         if (ldapsam_search_one_group(ldap_state, filter,
3052                                      &result) != LDAP_SUCCESS)
3053                 return NT_STATUS_NO_SUCH_ALIAS;
3054
3055         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3056                                    result);
3057
3058         if (count < 1) {
3059                 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3060                 ldap_msgfree(result);
3061                 return NT_STATUS_NO_SUCH_ALIAS;
3062         }
3063
3064         if (count > 1) {
3065                 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for filter %s: "
3066                           "count=%d\n", filter, count));
3067                 ldap_msgfree(result);
3068                 return NT_STATUS_NO_SUCH_ALIAS;
3069         }
3070
3071         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3072                                  result);
3073
3074         if (!entry) {
3075                 ldap_msgfree(result);
3076                 return NT_STATUS_UNSUCCESSFUL;
3077         }
3078
3079         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
3080         if (!dn) {
3081                 ldap_msgfree(result);
3082                 return NT_STATUS_UNSUCCESSFUL;
3083         }
3084
3085         smbldap_set_mod(&mods, modop,
3086                         get_attr_key2string(groupmap_attr_list,
3087                                             LDAP_ATTR_SID_LIST),
3088                         sid_string_static(member));
3089
3090         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3091
3092         ldap_mods_free(mods, True);
3093         ldap_msgfree(result);
3094
3095         if (rc != LDAP_SUCCESS) {
3096                 char *ld_error = NULL;
3097                 ldap_get_option(ldap_state->smbldap_state->ldap_struct,
3098                                 LDAP_OPT_ERROR_STRING,&ld_error);
3099                 
3100                 DEBUG(0, ("ldapsam_modify_aliasmem: Could not modify alias "
3101                           "for %s, error: %s (%s)\n", dn, ldap_err2string(rc),
3102                           ld_error?ld_error:"unknown"));
3103                 SAFE_FREE(ld_error);
3104                 SAFE_FREE(dn);
3105                 return NT_STATUS_UNSUCCESSFUL;
3106         }
3107
3108         SAFE_FREE(dn);
3109
3110         return NT_STATUS_OK;
3111 }
3112
3113 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3114                                      const DOM_SID *alias,
3115                                      const DOM_SID *member)
3116 {
3117         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3118 }
3119
3120 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3121                                      const DOM_SID *alias,
3122                                      const DOM_SID *member)
3123 {
3124         return ldapsam_modify_aliasmem(methods, alias, member,
3125                                        LDAP_MOD_DELETE);
3126 }
3127
3128 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3129                                       const DOM_SID *alias, DOM_SID **pp_members,
3130                                       size_t *p_num_members)
3131 {
3132         struct ldapsam_privates *ldap_state =
3133                 (struct ldapsam_privates *)methods->private_data;
3134         LDAPMessage *result = NULL;
3135         LDAPMessage *entry = NULL;
3136         int count;
3137         char **values;
3138         int i;
3139         pstring filter;
3140         size_t num_members;
3141
3142         *pp_members = NULL;
3143         *p_num_members = 0;
3144
3145         pstr_sprintf(filter, "(&(|(objectClass=%s)(objectclass=%s))(%s=%s))",
3146                      LDAP_OBJ_GROUPMAP, LDAP_OBJ_IDMAP_ENTRY,
3147                      get_attr_key2string(groupmap_attr_list,
3148                                          LDAP_ATTR_GROUP_SID),
3149                      sid_string_static(alias));
3150
3151         if (ldapsam_search_one_group(ldap_state, filter,
3152                                      &result) != LDAP_SUCCESS)
3153                 return NT_STATUS_NO_SUCH_ALIAS;
3154
3155         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3156                                    result);
3157
3158         if (count < 1) {
3159                 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3160                 ldap_msgfree(result);
3161                 return NT_STATUS_NO_SUCH_ALIAS;
3162         }
3163
3164         if (count > 1) {
3165                 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for filter %s: "
3166                           "count=%d\n", filter, count));
3167                 ldap_msgfree(result);
3168                 return NT_STATUS_NO_SUCH_ALIAS;
3169         }
3170
3171         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3172                                  result);
3173
3174         if (!entry) {
3175                 ldap_msgfree(result);
3176                 return NT_STATUS_UNSUCCESSFUL;
3177         }
3178
3179         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3180                                  entry,
3181                                  get_attr_key2string(groupmap_attr_list,
3182                                                      LDAP_ATTR_SID_LIST));
3183
3184         if (values == NULL) {
3185                 ldap_msgfree(result);
3186                 return NT_STATUS_OK;
3187         }
3188
3189         count = ldap_count_values(values);
3190
3191         for (i=0; i<count; i++) {
3192                 DOM_SID member;
3193
3194                 if (!string_to_sid(&member, values[i]))
3195                         continue;
3196
3197                 add_sid_to_array(NULL, &member, pp_members, &num_members);
3198         }
3199
3200         *p_num_members = num_members;
3201         ldap_value_free(values);
3202         ldap_msgfree(result);
3203
3204         return NT_STATUS_OK;
3205 }
3206
3207 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3208                                           TALLOC_CTX *mem_ctx,
3209                                           const DOM_SID *domain_sid,
3210                                           const DOM_SID *members,
3211                                           size_t num_members,
3212                                           uint32 **pp_alias_rids,
3213                                           size_t *p_num_alias_rids)
3214 {
3215         struct ldapsam_privates *ldap_state =
3216                 (struct ldapsam_privates *)methods->private_data;
3217         LDAP *ldap_struct;
3218
3219         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3220
3221         LDAPMessage *result = NULL;
3222         LDAPMessage *entry = NULL;
3223         int i;
3224         int rc;
3225         char *filter;
3226
3227         /* This query could be further optimized by adding a
3228            (&(sambaSID=<domain-sid>*)) so that only those aliases that are
3229            asked for in the getuseraliases are returned. */        
3230
3231         filter = talloc_asprintf(mem_ctx,
3232                                  "(&(|(objectclass=%s)(objectclass=%s))(|",
3233                                  LDAP_OBJ_GROUPMAP, LDAP_OBJ_IDMAP_ENTRY);
3234
3235         for (i=0; i<num_members; i++)
3236                 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3237                                          filter,
3238                                          sid_string_static(&members[i]));
3239
3240         filter = talloc_asprintf(mem_ctx, "%s))", filter);
3241
3242         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3243                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3244
3245         if (rc != LDAP_SUCCESS)
3246                 return NT_STATUS_UNSUCCESSFUL;
3247
3248         ldap_struct = ldap_state->smbldap_state->ldap_struct;
3249
3250         for (entry = ldap_first_entry(ldap_struct, result);
3251              entry != NULL;
3252              entry = ldap_next_entry(ldap_struct, entry))
3253         {
3254                 fstring sid_str;
3255                 DOM_SID sid;
3256                 uint32 rid;
3257
3258                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3259                                                   LDAP_ATTRIBUTE_SID,
3260                                                   sid_str,
3261                                                   sizeof(sid_str)-1))
3262                         continue;
3263
3264                 if (!string_to_sid(&sid, sid_str))
3265                         continue;
3266
3267                 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3268                         continue;
3269
3270                 add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3271                                         p_num_alias_rids);
3272         }
3273
3274         ldap_msgfree(result);
3275         return NT_STATUS_OK;
3276 }
3277
3278 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods, int policy_index, uint32 value)
3279 {
3280         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3281         int rc;
3282         LDAPMod **mods = NULL;
3283         fstring value_string;
3284         const char *policy_attr = NULL;
3285
3286         struct ldapsam_privates *ldap_state =
3287                 (struct ldapsam_privates *)methods->private_data;
3288
3289         const char *attrs[2];
3290
3291         DEBUG(10,("ldapsam_set_account_policy\n"));
3292
3293         if (!ldap_state->domain_dn) {
3294                 return NT_STATUS_INVALID_PARAMETER;
3295         }
3296
3297         policy_attr = get_account_policy_attr(policy_index);
3298         if (policy_attr == NULL) {
3299                 DEBUG(0,("ldapsam_set_account_policy: invalid policy\n"));
3300                 return ntstatus;
3301         }
3302
3303         attrs[0] = policy_attr;
3304         attrs[1] = NULL;
3305
3306         slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3307
3308         smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3309
3310         rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn, mods);
3311
3312         ldap_mods_free(mods, True);
3313
3314         if (rc != LDAP_SUCCESS) {
3315                 char *ld_error = NULL;
3316                 ldap_get_option(ldap_state->smbldap_state->ldap_struct,
3317                                 LDAP_OPT_ERROR_STRING,&ld_error);
3318                 
3319                 DEBUG(0, ("ldapsam_set_account_policy: Could not set account policy "
3320                           "for %s, error: %s (%s)\n", ldap_state->domain_dn, ldap_err2string(rc),
3321                           ld_error?ld_error:"unknown"));
3322                 SAFE_FREE(ld_error);
3323                 return ntstatus;
3324         }
3325
3326         if (!cache_account_policy_set(policy_index, value)) {
3327                 DEBUG(0,("ldapsam_set_account_policy: failed to update local tdb cache\n"));
3328                 return ntstatus;
3329         }
3330
3331         return NT_STATUS_OK;
3332 }
3333
3334 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods, int policy_index, uint32 *value)
3335 {
3336         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3337         LDAPMessage *result = NULL;
3338         LDAPMessage *entry = NULL;
3339         int count;
3340         int rc;
3341         char **vals = NULL;
3342         const char *policy_attr = NULL;
3343
3344         struct ldapsam_privates *ldap_state =
3345                 (struct ldapsam_privates *)methods->private_data;
3346
3347         const char *attrs[2];
3348
3349         DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3350
3351         if (!ldap_state->domain_dn) {
3352                 return NT_STATUS_INVALID_PARAMETER;
3353         }
3354
3355         policy_attr = get_account_policy_attr(policy_index);
3356         if (!policy_attr) {
3357                 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid policy index: %d\n", policy_index));
3358                 return ntstatus;
3359         }
3360
3361         attrs[0] = policy_attr;
3362         attrs[1] = NULL;
3363
3364         rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3365                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &result);
3366
3367         if (rc != LDAP_SUCCESS) {
3368                 char *ld_error = NULL;
3369                 ldap_get_option(ldap_state->smbldap_state->ldap_struct,
3370                                 LDAP_OPT_ERROR_STRING,&ld_error);
3371                 
3372                 DEBUG(0, ("ldapsam_get_account_policy_from_ldap: Could not set account policy "
3373                           "for %s, error: %s (%s)\n", ldap_state->domain_dn, ldap_err2string(rc),
3374                           ld_error?ld_error:"unknown"));
3375                 SAFE_FREE(ld_error);
3376                 return ntstatus;
3377         }
3378
3379         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
3380         if (count < 1) {
3381                 goto out;
3382         }
3383
3384         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
3385         if (entry == NULL) {
3386                 goto out;
3387         }
3388
3389         vals = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, policy_attr);
3390         if (vals == NULL) {
3391                 goto out;
3392         }
3393
3394         *value = (uint32)atol(vals[0]);
3395         
3396         ntstatus = NT_STATUS_OK;
3397
3398 out:
3399         if (vals)
3400                 ldap_value_free(vals);
3401         ldap_msgfree(result);
3402
3403         return ntstatus;
3404 }
3405
3406 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache 
3407
3408    - if there is a valid cache entry, return that
3409    - if there is an LDAP entry, update cache and return 
3410    - otherwise set to default, update cache and return
3411
3412    Guenther
3413 */
3414 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods, int policy_index, uint32 *value)
3415 {
3416         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3417
3418         if (cache_account_policy_get(policy_index, value)) {
3419                 DEBUG(11,("ldapsam_get_account_policy: got valid value from cache\n"));
3420                 return NT_STATUS_OK;
3421         }
3422
3423         ntstatus = ldapsam_get_account_policy_from_ldap(methods, policy_index, value);
3424         if (NT_STATUS_IS_OK(ntstatus)) {
3425                 goto update_cache;
3426         }
3427
3428         DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from ldap, returning default.\n"));
3429
3430 #if 0
3431         /* should we automagically migrate old tdb value here ? */
3432         if (account_policy_get(policy_index, value))
3433                 goto update_ldap;
3434
3435         DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying default\n", policy_index));
3436 #endif
3437
3438         if (!account_policy_get_default(policy_index, value)) {
3439                 return ntstatus;
3440         }
3441         
3442 /* update_ldap: */
3443  
3444         ntstatus = ldapsam_set_account_policy(methods, policy_index, *value);
3445         if (!NT_STATUS_IS_OK(ntstatus)) {
3446                 return ntstatus;
3447         }
3448                 
3449  update_cache:
3450  
3451         if (!cache_account_policy_set(policy_index, *value)) {
3452                 DEBUG(0,("ldapsam_get_account_policy: failed to update local tdb as a cache\n"));
3453                 return NT_STATUS_UNSUCCESSFUL;
3454         }
3455
3456         return NT_STATUS_OK;
3457 }
3458
3459 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3460                                     TALLOC_CTX *mem_ctx,
3461                                     const DOM_SID *domain_sid,
3462                                     int num_rids,
3463                                     uint32 *rids,
3464                                     const char ***names,
3465                                     uint32 **attrs)
3466 {
3467         struct ldapsam_privates *ldap_state =
3468                 (struct ldapsam_privates *)methods->private_data;
3469         LDAP *ldap_struct = ldap_state->smbldap_state->ldap_struct;
3470         LDAPMessage *msg = NULL;
3471         LDAPMessage *entry;
3472         char *allsids = NULL;
3473         char *tmp;
3474         int i, rc, num_mapped;
3475         NTSTATUS result = NT_STATUS_UNSUCCESSFUL;
3476
3477         if (!lp_parm_bool(-1, "ldapsam", "trusted", False))
3478                 return pdb_default_lookup_rids(methods, mem_ctx, domain_sid,
3479                                                num_rids, rids, names, attrs);
3480
3481         if (!sid_equal(domain_sid, get_global_sam_sid())) {
3482                 /* TODO: Sooner or later we need to look up BUILTIN rids as
3483                  * well. -- vl */
3484                 goto done;
3485         }
3486
3487         (*names) = TALLOC_ZERO_ARRAY(mem_ctx, const char *, num_rids);
3488         (*attrs) = TALLOC_ARRAY(mem_ctx, uint32, num_rids);
3489
3490         if ((num_rids != 0) && (((*names) == NULL) || ((*attrs) == NULL)))
3491                 return NT_STATUS_NO_MEMORY;
3492
3493         for (i=0; i<num_rids; i++)
3494                 (*attrs)[i] = SID_NAME_UNKNOWN;
3495
3496         allsids = SMB_STRDUP("");
3497         if (allsids == NULL) return NT_STATUS_NO_MEMORY;
3498
3499         for (i=0; i<num_rids; i++) {
3500                 DOM_SID sid;
3501                 sid_copy(&sid, domain_sid);
3502                 sid_append_rid(&sid, rids[i]);
3503                 tmp = allsids;
3504                 asprintf(&allsids, "%s(sambaSid=%s)", allsids,
3505                          sid_string_static(&sid));
3506                 if (allsids == NULL) return NT_STATUS_NO_MEMORY;
3507                 free(tmp);
3508         }
3509
3510         /* First look for users */
3511
3512         {
3513                 char *filter;
3514                 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
3515
3516                 asprintf(&filter, ("(&(objectClass=sambaSamAccount)(|%s))"),
3517                          allsids);
3518                 if (filter == NULL) return NT_STATUS_NO_MEMORY;
3519
3520                 rc = smbldap_search(ldap_state->smbldap_state,
3521                                     lp_ldap_user_suffix(),
3522                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3523                                     &msg);
3524
3525                 SAFE_FREE(filter);
3526         }
3527
3528         if (rc != LDAP_SUCCESS)
3529                 goto done;
3530
3531         num_mapped = 0;
3532
3533         for (entry = ldap_first_entry(ldap_struct, msg);
3534              entry != NULL;
3535              entry = ldap_next_entry(ldap_struct, entry))
3536         {
3537                 uint32 rid;
3538                 int rid_index;
3539                 fstring str;
3540
3541                 if (!ldapsam_extract_rid_from_entry(ldap_struct, entry,
3542                                                     get_global_sam_sid(),
3543                                                     &rid)) {
3544                         DEBUG(2, ("Could not find sid from ldap entry\n"));
3545                         continue;
3546                 }
3547
3548                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3549                                                   "uid", str, sizeof(str)-1)) {
3550                         DEBUG(2, ("Could not retrieve uid attribute\n"));
3551                         continue;
3552                 }
3553
3554                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3555                         if (rid == rids[rid_index])
3556                                 break;
3557                 }
3558
3559                 if (rid_index == num_rids) {
3560                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3561                         continue;
3562                 }
3563
3564                 (*attrs)[rid_index] = SID_NAME_USER;
3565                 (*names)[rid_index] = talloc_strdup(mem_ctx, str);
3566                 if ((*names)[rid_index] == NULL) return NT_STATUS_NO_MEMORY;
3567
3568                 num_mapped += 1;
3569         }
3570
3571         if (num_mapped == num_rids) {
3572                 /* No need to look for groups anymore -- we're done */
3573                 result = NT_STATUS_OK;
3574                 goto done;
3575         }
3576
3577         /* Same game for groups */
3578
3579         {
3580                 char *filter;
3581                 const char *ldap_attrs[] = { "cn", "sambaSid", NULL };
3582
3583                 asprintf(&filter, ("(&(objectClass=sambaGroupMapping)(|%s))"),
3584                          allsids);
3585                 if (filter == NULL) return NT_STATUS_NO_MEMORY;
3586
3587                 rc = smbldap_search(ldap_state->smbldap_state,
3588                                     lp_ldap_group_suffix(),
3589                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3590                                     &msg);
3591
3592                 SAFE_FREE(filter);
3593         }
3594
3595         if (rc != LDAP_SUCCESS)
3596                 goto done;
3597
3598         for (entry = ldap_first_entry(ldap_struct, msg);
3599              entry != NULL;
3600              entry = ldap_next_entry(ldap_struct, entry))
3601         {
3602                 uint32 rid;
3603                 int rid_index;
3604                 fstring str;
3605
3606                 if (!ldapsam_extract_rid_from_entry(ldap_struct, entry,
3607                                                     get_global_sam_sid(),
3608                                                     &rid)) {
3609                         DEBUG(2, ("Could not find sid from ldap entry\n"));
3610                         continue;
3611                 }
3612
3613                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3614                                                   "cn", str, sizeof(str)-1)) {
3615                         DEBUG(2, ("Could not retrieve cn attribute\n"));
3616                         continue;
3617                 }
3618
3619                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3620                         if (rid == rids[rid_index])
3621                                 break;
3622                 }
3623
3624                 if (rid_index == num_rids) {
3625                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3626                         continue;
3627                 }
3628
3629                 (*attrs)[rid_index] = SID_NAME_DOM_GRP;
3630                 (*names)[rid_index] = talloc_strdup(mem_ctx, str);
3631                 if ((*names)[rid_index] == NULL) return NT_STATUS_NO_MEMORY;
3632                 num_mapped += 1;
3633         }
3634
3635         result = NT_STATUS_NONE_MAPPED;
3636
3637         if (num_mapped > 0)
3638                 result = (num_mapped == num_rids) ?
3639                         NT_STATUS_OK : STATUS_SOME_UNMAPPED;
3640  done:
3641         SAFE_FREE(allsids);
3642
3643         if (msg != NULL)
3644                 ldap_msgfree(msg);
3645
3646         return result;
3647 }
3648
3649 char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
3650 {
3651         char *filter = NULL;
3652         char *escaped = NULL;
3653         char *result = NULL;
3654
3655         asprintf(&filter, "(&%s(objectclass=sambaSamAccount))",
3656                  "(uid=%u)");
3657         if (filter == NULL) goto done;
3658
3659         escaped = escape_ldap_string_alloc(username);
3660         if (escaped == NULL) goto done;
3661
3662         filter = realloc_string_sub(filter, "%u", username);
3663         result = talloc_strdup(mem_ctx, filter);
3664
3665  done:
3666         SAFE_FREE(filter);
3667         SAFE_FREE(escaped);
3668
3669         return result;
3670 }
3671
3672 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
3673 {
3674         int i, num = 0;
3675         va_list ap;
3676         const char **result;
3677
3678         va_start(ap, mem_ctx);
3679         while (va_arg(ap, const char *) != NULL)
3680                 num += 1;
3681         va_end(ap);
3682
3683         result = TALLOC_ARRAY(mem_ctx, const char *, num+1);
3684
3685         va_start(ap, mem_ctx);
3686         for (i=0; i<num; i++)
3687                 result[i] = talloc_strdup(mem_ctx, va_arg(ap, const char*));
3688         va_end(ap);
3689
3690         result[num] = NULL;
3691         return result;
3692 }
3693
3694 struct ldap_search_state {
3695         struct smbldap_state *connection;
3696
3697         uint16 acct_flags;
3698         uint16 group_type;
3699
3700         const char *base;
3701         int scope;
3702         const char *filter;
3703         const char **attrs;
3704         int attrsonly;
3705         void *pagedresults_cookie;
3706
3707         LDAPMessage *entries, *current_entry;
3708         BOOL (*ldap2displayentry)(struct ldap_search_state *state,
3709                                   TALLOC_CTX *mem_ctx,
3710                                   LDAP *ld, LDAPMessage *entry,
3711                                   struct samr_displayentry *result);
3712 };
3713
3714 static BOOL ldapsam_search_firstpage(struct pdb_search *search)
3715 {
3716         struct ldap_search_state *state = search->private_data;
3717         LDAP *ld;
3718         int rc = LDAP_OPERATIONS_ERROR;
3719
3720         state->entries = NULL;
3721
3722         if (state->connection->paged_results) {
3723                 rc = smbldap_search_paged(state->connection, state->base,
3724                                           state->scope, state->filter,
3725                                           state->attrs, state->attrsonly,
3726                                           lp_ldap_page_size(), &state->entries,
3727                                           &state->pagedresults_cookie);
3728         }
3729
3730         if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
3731
3732                 if (state->entries != NULL) {
3733                         /* Left over from unsuccessful paged attempt */
3734                         ldap_msgfree(state->entries);
3735                         state->entries = NULL;
3736                 }
3737
3738                 rc = smbldap_search(state->connection, state->base,
3739                                     state->scope, state->filter, state->attrs,
3740                                     state->attrsonly, &state->entries);
3741
3742                 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
3743                         return False;
3744
3745                 /* Ok, the server was lying. It told us it could do paged
3746                  * searches when it could not. */
3747                 state->connection->paged_results = False;
3748         }
3749
3750         ld = state->connection->ldap_struct;
3751         if ( ld == NULL) {
3752                 DEBUG(5, ("Don't have an LDAP connection right after a "
3753                           "search\n"));
3754                 return False;
3755         }
3756         state->current_entry = ldap_first_entry(ld, state->entries);
3757
3758         if (state->current_entry == NULL) {
3759                 ldap_msgfree(state->entries);
3760                 state->entries = NULL;
3761         }
3762
3763         return True;
3764 }
3765
3766 static BOOL ldapsam_search_nextpage(struct pdb_search *search)
3767 {
3768         struct ldap_search_state *state = search->private_data;
3769         LDAP *ld = state->connection->ldap_struct;
3770         int rc;
3771
3772         if (!state->connection->paged_results) {
3773                 /* There is no next page when there are no paged results */
3774                 return False;
3775         }
3776
3777         rc = smbldap_search_paged(state->connection, state->base,
3778                                   state->scope, state->filter, state->attrs,
3779                                   state->attrsonly, lp_ldap_page_size(),
3780                                   &state->entries,
3781                                   &state->pagedresults_cookie);
3782
3783         if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
3784                 return False;
3785
3786         state->current_entry = ldap_first_entry(ld, state->entries);
3787
3788         if (state->current_entry == NULL) {
3789                 ldap_msgfree(state->entries);
3790                 state->entries = NULL;
3791         }
3792
3793         return True;
3794 }
3795
3796 static BOOL ldapsam_search_next_entry(struct pdb_search *search,
3797                                       struct samr_displayentry *entry)
3798 {
3799         struct ldap_search_state *state = search->private_data;
3800         LDAP *ld = state->connection->ldap_struct;
3801         BOOL result;
3802
3803  retry:
3804         if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
3805                 return False;
3806
3807         if ((state->entries == NULL) &&
3808             !ldapsam_search_nextpage(search))
3809                     return False;
3810
3811         result = state->ldap2displayentry(state, search->mem_ctx, ld,
3812                                           state->current_entry, entry);
3813
3814         if (!result) {
3815                 char *dn;
3816                 dn = ldap_get_dn(ld, state->current_entry);
3817                 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
3818                 if (dn != NULL) ldap_memfree(dn);
3819         }
3820
3821         state->current_entry = ldap_next_entry(ld, state->current_entry);
3822
3823         if (state->current_entry == NULL) {
3824                 ldap_msgfree(state->entries);
3825                 state->entries = NULL;
3826         }
3827
3828         if (!result) goto retry;
3829
3830         return True;
3831 }
3832
3833 static void ldapsam_search_end(struct pdb_search *search)
3834 {
3835         struct ldap_search_state *state = search->private_data;
3836         int rc;
3837
3838         if (state->pagedresults_cookie == NULL)
3839                 return;
3840
3841         if (state->entries != NULL)
3842                 ldap_msgfree(state->entries);
3843
3844         state->entries = NULL;
3845         state->current_entry = NULL;
3846
3847         if (!state->connection->paged_results)
3848                 return;
3849
3850         /* Tell the LDAP server we're not interested in the rest anymore. */
3851
3852         rc = smbldap_search_paged(state->connection, state->base, state->scope,
3853                                   state->filter, state->attrs,
3854                                   state->attrsonly, 0, &state->entries,
3855                                   &state->pagedresults_cookie);
3856
3857         if (rc != LDAP_SUCCESS)
3858                 DEBUG(5, ("Could not end search properly\n"));
3859
3860         return;
3861 }
3862
3863 static BOOL ldapuser2displayentry(struct ldap_search_state *state,
3864                                   TALLOC_CTX *mem_ctx,
3865                                   LDAP *ld, LDAPMessage *entry,
3866                                   struct samr_displayentry *result)
3867 {
3868         char **vals;
3869         DOM_SID sid;
3870         uint16 acct_flags;
3871
3872         vals = ldap_get_values(ld, entry, "sambaAcctFlags");
3873         if ((vals == NULL) || (vals[0] == NULL)) {
3874                 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
3875                 return False;
3876         }
3877         acct_flags = pdb_decode_acct_ctrl(vals[0]);
3878         ldap_value_free(vals);
3879
3880         if ((state->acct_flags != 0) &&
3881             ((state->acct_flags & acct_flags) == 0))
3882                 return False;           
3883
3884         result->acct_flags = acct_flags;
3885         result->account_name = "";
3886         result->fullname = "";
3887         result->description = "";
3888
3889         vals = ldap_get_values(ld, entry, "uid");
3890         if ((vals == NULL) || (vals[0] == NULL)) {
3891                 DEBUG(5, ("\"uid\" not found\n"));
3892                 return False;
3893         }
3894         pull_utf8_talloc(mem_ctx,
3895                          CONST_DISCARD(char **, &result->account_name),
3896                          vals[0]);
3897         ldap_value_free(vals);
3898
3899         vals = ldap_get_values(ld, entry, "displayName");
3900         if ((vals == NULL) || (vals[0] == NULL))
3901                 DEBUG(8, ("\"displayName\" not found\n"));
3902         else
3903                 pull_utf8_talloc(mem_ctx,
3904                                  CONST_DISCARD(char **, &result->fullname),
3905                                  vals[0]);
3906         ldap_value_free(vals);
3907
3908         vals = ldap_get_values(ld, entry, "description");
3909         if ((vals == NULL) || (vals[0] == NULL))
3910                 DEBUG(8, ("\"description\" not found\n"));
3911         else
3912                 pull_utf8_talloc(mem_ctx,
3913                                  CONST_DISCARD(char **, &result->description),
3914                                  vals[0]);
3915         ldap_value_free(vals);
3916
3917         if ((result->account_name == NULL) ||
3918             (result->fullname == NULL) ||
3919             (result->description == NULL)) {
3920                 DEBUG(0, ("talloc failed\n"));
3921                 return False;
3922         }
3923         
3924         vals = ldap_get_values(ld, entry, "sambaSid");
3925         if ((vals == NULL) || (vals[0] == NULL)) {
3926                 DEBUG(0, ("\"objectSid\" not found\n"));
3927                 return False;
3928         }
3929
3930         if (!string_to_sid(&sid, vals[0])) {
3931                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
3932                 ldap_value_free(vals);
3933                 return False;
3934         }
3935         ldap_value_free(vals);
3936
3937         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
3938                 DEBUG(0, ("sid %s does not belong to our domain\n", sid_string_static(&sid)));
3939                 return False;
3940         }
3941
3942         return True;
3943 }
3944
3945
3946 static BOOL ldapsam_search_users(struct pdb_methods *methods,
3947                                  struct pdb_search *search,
3948                                  uint16 acct_flags)
3949 {
3950         struct ldapsam_privates *ldap_state = methods->private_data;
3951         struct ldap_search_state *state;
3952
3953         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
3954         if (state == NULL) {
3955                 DEBUG(0, ("talloc failed\n"));
3956                 return False;
3957         }
3958
3959         state->connection = ldap_state->smbldap_state;
3960
3961         if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
3962                 state->base = lp_ldap_user_suffix();
3963         else if ((acct_flags != 0) &&
3964                  ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
3965                 state->base = lp_ldap_machine_suffix();
3966         else
3967                 state->base = lp_ldap_suffix();
3968
3969         state->acct_flags = acct_flags;
3970         state->base = talloc_strdup(search->mem_ctx, state->base);
3971         state->scope = LDAP_SCOPE_SUBTREE;
3972         state->filter = get_ldap_filter(search->mem_ctx, "*");
3973         state->attrs = talloc_attrs(search->mem_ctx, "uid", "sambaSid",
3974                                     "displayName", "description",
3975                                     "sambaAcctFlags", NULL);
3976         state->attrsonly = 0;
3977         state->pagedresults_cookie = NULL;
3978         state->entries = NULL;
3979         state->ldap2displayentry = ldapuser2displayentry;
3980
3981         if ((state->filter == NULL) || (state->attrs == NULL)) {
3982                 DEBUG(0, ("talloc failed\n"));
3983                 return False;
3984         }
3985
3986         search->private_data = state;
3987         search->next_entry = ldapsam_search_next_entry;
3988         search->search_end = ldapsam_search_end;
3989
3990         return ldapsam_search_firstpage(search);
3991 }
3992
3993 static BOOL ldapgroup2displayentry(struct ldap_search_state *state,
3994                                    TALLOC_CTX *mem_ctx,
3995                                    LDAP *ld, LDAPMessage *entry,
3996                                    struct samr_displayentry *result)
3997 {
3998         char **vals;
3999         DOM_SID sid;
4000         uint16 group_type;
4001
4002         result->account_name = "";
4003         result->fullname = "";
4004         result->description = "";
4005
4006
4007         vals = ldap_get_values(ld, entry, "sambaGroupType");
4008         if ((vals == NULL) || (vals[0] == NULL)) {
4009                 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4010                 return False;
4011         }
4012
4013         group_type = atoi(vals[0]);
4014
4015         if ((state->group_type != 0) &&
4016             ((state->group_type != group_type))) {
4017                 return False;
4018         }
4019
4020         /* display name is the NT group name */
4021
4022         vals = ldap_get_values(ld, entry, "displayName");
4023         if ((vals == NULL) || (vals[0] == NULL)) {
4024                 DEBUG(8, ("\"displayName\" not found\n"));
4025
4026                 /* fallback to the 'cn' attribute */
4027                 vals = ldap_get_values(ld, entry, "cn");
4028                 if ((vals == NULL) || (vals[0] == NULL)) {
4029                         DEBUG(5, ("\"cn\" not found\n"));
4030                         return False;
4031                 }
4032                 pull_utf8_talloc(mem_ctx, CONST_DISCARD(char **, &result->account_name), vals[0]);
4033         }
4034         else {
4035                 pull_utf8_talloc(mem_ctx, CONST_DISCARD(char **, &result->account_name), vals[0]);
4036         }
4037
4038         ldap_value_free(vals);
4039
4040         vals = ldap_get_values(ld, entry, "description");
4041         if ((vals == NULL) || (vals[0] == NULL))
4042                 DEBUG(8, ("\"description\" not found\n"));
4043         else
4044                 pull_utf8_talloc(mem_ctx,
4045                                  CONST_DISCARD(char **, &result->description),
4046                                  vals[0]);
4047         ldap_value_free(vals);
4048
4049         if ((result->account_name == NULL) ||
4050             (result->fullname == NULL) ||
4051             (result->description == NULL)) {
4052                 DEBUG(0, ("talloc failed\n"));
4053                 return False;
4054         }
4055         
4056         vals = ldap_get_values(ld, entry, "sambaSid");
4057         if ((vals == NULL) || (vals[0] == NULL)) {
4058                 DEBUG(0, ("\"objectSid\" not found\n"));
4059                 return False;
4060         }
4061
4062         if (!string_to_sid(&sid, vals[0])) {
4063                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4064                 return False;
4065         }
4066
4067         ldap_value_free(vals);
4068
4069         switch (group_type) {
4070                 case SID_NAME_DOM_GRP:
4071                 case SID_NAME_ALIAS:
4072
4073                         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4074                                 DEBUG(0, ("%s is not in our domain\n", sid_string_static(&sid)));
4075                                 return False;
4076                         }
4077                         break;
4078         
4079                 case SID_NAME_WKN_GRP:
4080
4081                         if (!sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid)) {
4082
4083                                 DEBUG(0, ("%s is not in builtin sid\n", sid_string_static(&sid)));
4084                                 return False;
4085                         }
4086                         break;
4087
4088                 default:
4089                         DEBUG(0,("unkown group type: %d\n", group_type));
4090                         return False;
4091         }
4092         
4093         return True;
4094 }
4095
4096 static BOOL ldapsam_search_grouptype(struct pdb_methods *methods,
4097                                      struct pdb_search *search,
4098                                      enum SID_NAME_USE type)
4099 {
4100         struct ldapsam_privates *ldap_state = methods->private_data;
4101         struct ldap_search_state *state;
4102
4103         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4104         if (state == NULL) {
4105                 DEBUG(0, ("talloc failed\n"));
4106                 return False;
4107         }
4108
4109         state->connection = ldap_state->smbldap_state;
4110
4111         state->base = talloc_strdup(search->mem_ctx, lp_ldap_group_suffix());
4112         state->connection = ldap_state->smbldap_state;
4113         state->scope = LDAP_SCOPE_SUBTREE;
4114         state->filter = talloc_asprintf(search->mem_ctx,
4115                                         "(&(objectclass=sambaGroupMapping)"
4116                                         "(sambaGroupType=%d))", type);
4117         state->attrs = talloc_attrs(search->mem_ctx, "cn", "sambaSid",
4118                                     "displayName", "description", "sambaGroupType", NULL);
4119         state->attrsonly = 0;
4120         state->pagedresults_cookie = NULL;
4121         state->entries = NULL;
4122         state->group_type = type;
4123         state->ldap2displayentry = ldapgroup2displayentry;
4124
4125         if ((state->filter == NULL) || (state->attrs == NULL)) {
4126                 DEBUG(0, ("talloc failed\n"));
4127                 return False;
4128         }
4129
4130         search->private_data = state;
4131         search->next_entry = ldapsam_search_next_entry;
4132         search->search_end = ldapsam_search_end;
4133
4134         return ldapsam_search_firstpage(search);
4135 }
4136
4137 static BOOL ldapsam_search_groups(struct pdb_methods *methods,
4138                                   struct pdb_search *search)
4139 {
4140         return ldapsam_search_grouptype(methods, search, SID_NAME_DOM_GRP);
4141 }
4142
4143 static BOOL ldapsam_search_aliases(struct pdb_methods *methods,
4144                                    struct pdb_search *search,
4145                                    const DOM_SID *sid)
4146 {
4147         if (sid_check_is_domain(sid))
4148                 return ldapsam_search_grouptype(methods, search,
4149                                                 SID_NAME_ALIAS);
4150
4151         if (sid_check_is_builtin(sid))
4152                 return ldapsam_search_grouptype(methods, search,
4153                                                 SID_NAME_WKN_GRP);
4154
4155         DEBUG(5, ("Don't know SID %s\n", sid_string_static(sid)));
4156         return False;
4157 }
4158
4159 /**********************************************************************
4160  Housekeeping
4161  *********************************************************************/
4162
4163 static void free_private_data(void **vp) 
4164 {
4165         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
4166
4167         smbldap_free_struct(&(*ldap_state)->smbldap_state);
4168
4169         if ((*ldap_state)->result != NULL) {
4170                 ldap_msgfree((*ldap_state)->result);
4171                 (*ldap_state)->result = NULL;
4172         }
4173         if ((*ldap_state)->domain_dn != NULL) {
4174                 SAFE_FREE((*ldap_state)->domain_dn);
4175         }
4176
4177         *ldap_state = NULL;
4178
4179         /* No need to free any further, as it is talloc()ed */
4180 }
4181
4182 /**********************************************************************
4183  Intitalise the parts of the pdb_context that are common to all pdb_ldap modes
4184  *********************************************************************/
4185
4186 static NTSTATUS pdb_init_ldapsam_common(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, 
4187                                         const char *location)
4188 {
4189         NTSTATUS nt_status;
4190         struct ldapsam_privates *ldap_state;
4191
4192         if (!NT_STATUS_IS_OK(nt_status = make_pdb_methods(pdb_context->mem_ctx, pdb_method))) {
4193                 return nt_status;
4194         }
4195
4196         (*pdb_method)->name = "ldapsam";
4197
4198         (*pdb_method)->setsampwent = ldapsam_setsampwent;
4199         (*pdb_method)->endsampwent = ldapsam_endsampwent;
4200         (*pdb_method)->getsampwent = ldapsam_getsampwent;
4201         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
4202         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
4203         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
4204         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
4205         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
4206
4207         (*pdb_method)->getgrsid = ldapsam_getgrsid;
4208         (*pdb_method)->getgrgid = ldapsam_getgrgid;
4209         (*pdb_method)->getgrnam = ldapsam_getgrnam;
4210         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
4211         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
4212         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
4213         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
4214         (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
4215         (*pdb_method)->enum_group_memberships = ldapsam_enum_group_memberships;
4216         (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
4217
4218         (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
4219         (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
4220
4221         (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
4222
4223         /* TODO: Setup private data and free */
4224
4225         ldap_state = TALLOC_ZERO_P(pdb_context->mem_ctx, struct ldapsam_privates);
4226         if (!ldap_state) {
4227                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
4228                 return NT_STATUS_NO_MEMORY;
4229         }
4230
4231         if (!NT_STATUS_IS_OK(nt_status = 
4232                              smbldap_init(pdb_context->mem_ctx, location, 
4233                                           &ldap_state->smbldap_state)));
4234
4235         ldap_state->domain_name = talloc_strdup(pdb_context->mem_ctx, get_global_sam_name());
4236         if (!ldap_state->domain_name) {
4237                 return NT_STATUS_NO_MEMORY;
4238         }
4239
4240         (*pdb_method)->private_data = ldap_state;
4241
4242         (*pdb_method)->free_private_data = free_private_data;
4243
4244         return NT_STATUS_OK;
4245 }
4246
4247 /**********************************************************************
4248  Initialise the 'compat' mode for pdb_ldap
4249  *********************************************************************/
4250
4251 NTSTATUS pdb_init_ldapsam_compat(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
4252 {
4253         NTSTATUS nt_status;
4254         struct ldapsam_privates *ldap_state;
4255
4256 #ifdef WITH_LDAP_SAMCONFIG
4257         if (!location) {
4258                 int ldap_port = lp_ldap_port();
4259                         
4260                 /* remap default port if not using SSL (ie clear or TLS) */
4261                 if ( (lp_ldap_ssl() != LDAP_SSL_ON) && (ldap_port == 636) ) {
4262                         ldap_port = 389;
4263                 }
4264
4265                 location = talloc_asprintf(pdb_context->mem_ctx, "%s://%s:%d", lp_ldap_ssl() == LDAP_SSL_ON ? "ldaps" : "ldap", lp_ldap_server(), ldap_port);
4266                 if (!location) {
4267                         return NT_STATUS_NO_MEMORY;
4268                 }
4269         }
4270 #endif
4271
4272         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
4273                 return nt_status;
4274         }
4275
4276         (*pdb_method)->name = "ldapsam_compat";
4277
4278         ldap_state = (*pdb_method)->private_data;
4279         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
4280
4281         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
4282
4283         return NT_STATUS_OK;
4284 }
4285
4286 /**********************************************************************
4287  Initialise the normal mode for pdb_ldap
4288  *********************************************************************/
4289
4290 NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
4291 {
4292         NTSTATUS nt_status;
4293         struct ldapsam_privates *ldap_state;
4294         uint32 alg_rid_base;
4295         pstring alg_rid_base_string;
4296         LDAPMessage *result = NULL;
4297         LDAPMessage *entry = NULL;
4298         DOM_SID ldap_domain_sid;
4299         DOM_SID secrets_domain_sid;
4300         pstring domain_sid_string;
4301         char *dn;
4302
4303         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
4304                 return nt_status;
4305         }
4306
4307         (*pdb_method)->name = "ldapsam";
4308
4309         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
4310         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
4311         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
4312         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
4313         (*pdb_method)->search_users = ldapsam_search_users;
4314         (*pdb_method)->search_groups = ldapsam_search_groups;
4315         (*pdb_method)->search_aliases = ldapsam_search_aliases;
4316
4317         ldap_state = (*pdb_method)->private_data;
4318         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
4319
4320         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
4321         
4322         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state, &result, 
4323                                                ldap_state->domain_name, True);
4324         
4325         if ( !NT_STATUS_IS_OK(nt_status) ) {
4326                 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain info, nor add one to the domain\n"));
4327                 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, will be unable to allocate new users/groups, \
4328 and will risk BDCs having inconsistant SIDs\n"));
4329                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
4330                 return NT_STATUS_OK;
4331         }
4332
4333         /* Given that the above might fail, everything below this must be optional */
4334         
4335         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
4336         if (!entry) {
4337                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info entry\n"));
4338                 ldap_msgfree(result);
4339                 return NT_STATUS_UNSUCCESSFUL;
4340         }
4341
4342         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
4343         if (!dn) {
4344                 return NT_STATUS_UNSUCCESSFUL;
4345         }
4346
4347         ldap_state->domain_dn = smb_xstrdup(dn);
4348         ldap_memfree(dn);
4349
4350         if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
4351                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
4352                                  domain_sid_string)) {
4353                 BOOL found_sid;
4354                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
4355                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be read as a valid SID\n", domain_sid_string));
4356                         return NT_STATUS_INVALID_PARAMETER;
4357                 }
4358                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name, &secrets_domain_sid);
4359                 if (!found_sid || !sid_equal(&secrets_domain_sid, &ldap_domain_sid)) {
4360                         fstring new_sid_str, old_sid_str;
4361                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain %s based on pdb_ldap results %s -> %s\n",
4362                                   ldap_state->domain_name, 
4363                                   sid_to_string(old_sid_str, &secrets_domain_sid),
4364                                   sid_to_string(new_sid_str, &ldap_domain_sid)));
4365                         
4366                         /* reset secrets.tdb sid */
4367                         secrets_store_domain_sid(ldap_state->domain_name, &ldap_domain_sid);
4368                         DEBUG(1, ("New global sam SID: %s\n", sid_to_string(new_sid_str, get_global_sam_sid())));
4369                 }
4370                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
4371         }
4372
4373         if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
4374                                  get_attr_key2string( dominfo_attr_list, LDAP_ATTR_ALGORITHMIC_RID_BASE ),
4375                                  alg_rid_base_string)) {
4376                 alg_rid_base = (uint32)atol(alg_rid_base_string);
4377                 if (alg_rid_base != algorithmic_rid_base()) {
4378                         DEBUG(0, ("The value of 'algorithmic RID base' has changed since the LDAP\n"
4379                                   "database was initialised.  Aborting. \n"));
4380                         ldap_msgfree(result);
4381                         return NT_STATUS_UNSUCCESSFUL;
4382                 }
4383         }
4384         ldap_msgfree(result);
4385
4386         return NT_STATUS_OK;
4387 }
4388
4389 NTSTATUS pdb_ldap_init(void)
4390 {
4391         NTSTATUS nt_status;
4392         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
4393                 return nt_status;
4394
4395         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
4396                 return nt_status;
4397
4398         /* Let pdb_nds register backends */
4399         pdb_nds_init();
4400
4401         return NT_STATUS_OK;
4402 }