r21608: Fix a couple of memleaks in error code paths before
[samba.git] / source / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/CIFS implementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Jean François Micouleau        1998
5    Copyright (C) Gerald Carter                  2001-2003
6    Copyright (C) Shahms King                    2001
7    Copyright (C) Andrew Bartlett                2002-2003
8    Copyright (C) Stefan (metze) Metzmacher      2002-2003
9    Copyright (C) Simo Sorce                     2006
10     
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 2 of the License, or
14    (at your option) any later version.
15    
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20    
21    You should have received a copy of the GNU General Public License
22    along with this program; if not, write to the Free Software
23    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24    
25 */
26
27 /* TODO:
28 *  persistent connections: if using NSS LDAP, many connections are made
29 *      however, using only one within Samba would be nice
30 *  
31 *  Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
32 *
33 *  Other LDAP based login attributes: accountExpires, etc.
34 *  (should be the domain of Samba proper, but the sam_password/struct samu
35 *  structures don't have fields for some of these attributes)
36 *
37 *  SSL is done, but can't get the certificate based authentication to work
38 *  against on my test platform (Linux 2.4, OpenLDAP 2.x)
39 */
40
41 /* NOTE: this will NOT work against an Active Directory server
42 *  due to the fact that the two password fields cannot be retrieved
43 *  from a server; recommend using security = domain in this situation
44 *  and/or winbind
45 */
46
47 #include "includes.h"
48
49 #undef DBGC_CLASS
50 #define DBGC_CLASS DBGC_PASSDB
51
52 #include <lber.h>
53 #include <ldap.h>
54
55 /*
56  * Work around versions of the LDAP client libs that don't have the OIDs
57  * defined, or have them defined under the old name.  
58  * This functionality is really a factor of the server, not the client 
59  *
60  */
61
62 #if defined(LDAP_EXOP_X_MODIFY_PASSWD) && !defined(LDAP_EXOP_MODIFY_PASSWD)
63 #define LDAP_EXOP_MODIFY_PASSWD LDAP_EXOP_X_MODIFY_PASSWD
64 #elif !defined(LDAP_EXOP_MODIFY_PASSWD)
65 #define LDAP_EXOP_MODIFY_PASSWD "1.3.6.1.4.1.4203.1.11.1"
66 #endif
67
68 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_ID) && !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
69 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID LDAP_EXOP_X_MODIFY_PASSWD_ID
70 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_ID)
71 #define LDAP_TAG_EXOP_MODIFY_PASSWD_ID        ((ber_tag_t) 0x80U)
72 #endif
73
74 #if defined(LDAP_EXOP_X_MODIFY_PASSWD_NEW) && !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
75 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW LDAP_EXOP_X_MODIFY_PASSWD_NEW
76 #elif !defined(LDAP_EXOP_MODIFY_PASSWD_NEW)
77 #define LDAP_TAG_EXOP_MODIFY_PASSWD_NEW       ((ber_tag_t) 0x82U)
78 #endif
79
80
81 #include "smbldap.h"
82
83 /**********************************************************************
84  Simple helper function to make stuff better readable
85  **********************************************************************/
86
87 static LDAP *priv2ld(struct ldapsam_privates *priv)
88 {
89         return priv->smbldap_state->ldap_struct;
90 }
91
92 /**********************************************************************
93  Get the attribute name given a user schame version.
94  **********************************************************************/
95  
96 static const char* get_userattr_key2string( int schema_ver, int key )
97 {
98         switch ( schema_ver ) {
99                 case SCHEMAVER_SAMBAACCOUNT:
100                         return get_attr_key2string( attrib_map_v22, key );
101                         
102                 case SCHEMAVER_SAMBASAMACCOUNT:
103                         return get_attr_key2string( attrib_map_v30, key );
104                         
105                 default:
106                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
107                         break;
108         }
109         return NULL;
110 }
111
112 /**********************************************************************
113  Return the list of attribute names given a user schema version.
114 **********************************************************************/
115
116 const char** get_userattr_list( TALLOC_CTX *mem_ctx, int schema_ver )
117 {
118         switch ( schema_ver ) {
119                 case SCHEMAVER_SAMBAACCOUNT:
120                         return get_attr_list( mem_ctx, attrib_map_v22 );
121                         
122                 case SCHEMAVER_SAMBASAMACCOUNT:
123                         return get_attr_list( mem_ctx, attrib_map_v30 );
124                 default:
125                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
126                         break;
127         }
128         
129         return NULL;
130 }
131
132 /**************************************************************************
133  Return the list of attribute names to delete given a user schema version.
134 **************************************************************************/
135
136 static const char** get_userattr_delete_list( TALLOC_CTX *mem_ctx,
137                                               int schema_ver )
138 {
139         switch ( schema_ver ) {
140                 case SCHEMAVER_SAMBAACCOUNT:
141                         return get_attr_list( mem_ctx,
142                                               attrib_map_to_delete_v22 );
143                         
144                 case SCHEMAVER_SAMBASAMACCOUNT:
145                         return get_attr_list( mem_ctx,
146                                               attrib_map_to_delete_v30 );
147                 default:
148                         DEBUG(0,("get_userattr_delete_list: unknown schema version specified!\n"));
149                         break;
150         }
151         
152         return NULL;
153 }
154
155
156 /*******************************************************************
157  Generate the LDAP search filter for the objectclass based on the 
158  version of the schema we are using.
159 ******************************************************************/
160
161 static const char* get_objclass_filter( int schema_ver )
162 {
163         static fstring objclass_filter;
164         
165         switch( schema_ver ) {
166                 case SCHEMAVER_SAMBAACCOUNT:
167                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
168                         break;
169                 case SCHEMAVER_SAMBASAMACCOUNT:
170                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
171                         break;
172                 default:
173                         DEBUG(0,("get_objclass_filter: Invalid schema version specified!\n"));
174                         break;
175         }
176         
177         return objclass_filter; 
178 }
179
180 /*****************************************************************
181  Scan a sequence number off OpenLDAP's syncrepl contextCSN
182 ******************************************************************/
183
184 static NTSTATUS ldapsam_get_seq_num(struct pdb_methods *my_methods, time_t *seq_num)
185 {
186         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
187         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
188         LDAPMessage *msg = NULL;
189         LDAPMessage *entry = NULL;
190         TALLOC_CTX *mem_ctx;
191         char **values = NULL;
192         int rc, num_result, num_values, rid;
193         pstring suffix;
194         fstring tok;
195         const char *p;
196         const char **attrs;
197
198         /* Unfortunatly there is no proper way to detect syncrepl-support in
199          * smbldap_connect_system(). The syncrepl OIDs are submitted for publication
200          * but do not show up in the root-DSE yet. Neither we can query the
201          * subschema-context for the syncProviderSubentry or syncConsumerSubentry
202          * objectclass. Currently we require lp_ldap_suffix() to show up as
203          * namingContext.  -  Guenther
204          */
205
206         if (!lp_parm_bool(-1, "ldapsam", "syncrepl_seqnum", False)) {
207                 return ntstatus;
208         }
209
210         if (!seq_num) {
211                 DEBUG(3,("ldapsam_get_seq_num: no sequence_number\n"));
212                 return ntstatus;
213         }
214
215         if (!smbldap_has_naming_context(ldap_state->smbldap_state->ldap_struct, lp_ldap_suffix())) {
216                 DEBUG(3,("ldapsam_get_seq_num: DIT not configured to hold %s "
217                          "as top-level namingContext\n", lp_ldap_suffix()));
218                 return ntstatus;
219         }
220
221         mem_ctx = talloc_init("ldapsam_get_seq_num");
222
223         if (mem_ctx == NULL)
224                 return NT_STATUS_NO_MEMORY;
225
226         if ((attrs = TALLOC_ARRAY(mem_ctx, const char *, 2)) == NULL) {
227                 ntstatus = NT_STATUS_NO_MEMORY;
228                 goto done;
229         }
230
231         /* if we got a syncrepl-rid (up to three digits long) we speak with a consumer */
232         rid = lp_parm_int(-1, "ldapsam", "syncrepl_rid", -1);
233         if (rid > 0) {
234
235                 /* consumer syncreplCookie: */
236                 /* csn=20050126161620Z#0000001#00#00000 */
237                 attrs[0] = talloc_strdup(mem_ctx, "syncreplCookie");
238                 attrs[1] = NULL;
239                 pstr_sprintf( suffix, "cn=syncrepl%d,%s", rid, lp_ldap_suffix());
240
241         } else {
242
243                 /* provider contextCSN */
244                 /* 20050126161620Z#000009#00#000000 */
245                 attrs[0] = talloc_strdup(mem_ctx, "contextCSN");
246                 attrs[1] = NULL;
247                 pstr_sprintf( suffix, "cn=ldapsync,%s", lp_ldap_suffix());
248
249         }
250
251         rc = smbldap_search(ldap_state->smbldap_state, suffix,
252                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0, &msg);
253
254         if (rc != LDAP_SUCCESS) {
255                 goto done;
256         }
257
258         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg);
259         if (num_result != 1) {
260                 DEBUG(3,("ldapsam_get_seq_num: Expected one entry, got %d\n", num_result));
261                 goto done;
262         }
263
264         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg);
265         if (entry == NULL) {
266                 DEBUG(3,("ldapsam_get_seq_num: Could not retrieve entry\n"));
267                 goto done;
268         }
269
270         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct, entry, attrs[0]);
271         if (values == NULL) {
272                 DEBUG(3,("ldapsam_get_seq_num: no values\n"));
273                 goto done;
274         }
275
276         num_values = ldap_count_values(values);
277         if (num_values == 0) {
278                 DEBUG(3,("ldapsam_get_seq_num: not a single value\n"));
279                 goto done;
280         }
281
282         p = values[0];
283         if (!next_token(&p, tok, "#", sizeof(tok))) {
284                 DEBUG(0,("ldapsam_get_seq_num: failed to parse sequence number\n"));
285                 goto done;
286         }
287
288         p = tok;
289         if (!strncmp(p, "csn=", strlen("csn=")))
290                 p += strlen("csn=");
291
292         DEBUG(10,("ldapsam_get_seq_num: got %s: %s\n", attrs[0], p));
293
294         *seq_num = generalized_to_unix_time(p);
295
296         /* very basic sanity check */
297         if (*seq_num <= 0) {
298                 DEBUG(3,("ldapsam_get_seq_num: invalid sequence number: %d\n", 
299                         (int)*seq_num));
300                 goto done;
301         }
302
303         ntstatus = NT_STATUS_OK;
304
305  done:
306         if (values != NULL)
307                 ldap_value_free(values);
308         if (msg != NULL)
309                 ldap_msgfree(msg);
310         if (mem_ctx)
311                 talloc_destroy(mem_ctx);
312
313         return ntstatus;
314 }
315
316 /*******************************************************************
317  Run the search by name.
318 ******************************************************************/
319
320 int ldapsam_search_suffix_by_name(struct ldapsam_privates *ldap_state, 
321                                           const char *user,
322                                           LDAPMessage ** result,
323                                           const char **attr)
324 {
325         pstring filter;
326         char *escape_user = escape_ldap_string_alloc(user);
327
328         if (!escape_user) {
329                 return LDAP_NO_MEMORY;
330         }
331
332         /*
333          * in the filter expression, replace %u with the real name
334          * so in ldap filter, %u MUST exist :-)
335          */
336         pstr_sprintf(filter, "(&%s%s)", "(uid=%u)", 
337                 get_objclass_filter(ldap_state->schema_ver));
338
339         /* 
340          * have to use this here because $ is filtered out
341            * in pstring_sub
342          */
343         
344
345         all_string_sub(filter, "%u", escape_user, sizeof(pstring));
346         SAFE_FREE(escape_user);
347
348         return smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
349 }
350
351 /*******************************************************************
352  Run the search by rid.
353 ******************************************************************/
354
355 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state, 
356                                          uint32 rid, LDAPMessage ** result, 
357                                          const char **attr)
358 {
359         pstring filter;
360         int rc;
361
362         pstr_sprintf(filter, "(&(rid=%i)%s)", rid, 
363                 get_objclass_filter(ldap_state->schema_ver));
364         
365         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
366         
367         return rc;
368 }
369
370 /*******************************************************************
371  Run the search by SID.
372 ******************************************************************/
373
374 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state, 
375                                          const DOM_SID *sid, LDAPMessage ** result, 
376                                          const char **attr)
377 {
378         pstring filter;
379         int rc;
380         fstring sid_string;
381
382         pstr_sprintf(filter, "(&(%s=%s)%s)", 
383                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
384                 sid_to_string(sid_string, sid), 
385                 get_objclass_filter(ldap_state->schema_ver));
386                 
387         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
388         
389         return rc;
390 }
391
392 /*******************************************************************
393  Delete complete object or objectclass and attrs from
394  object found in search_result depending on lp_ldap_delete_dn
395 ******************************************************************/
396
397 static int ldapsam_delete_entry(struct ldapsam_privates *priv,
398                                 TALLOC_CTX *mem_ctx,
399                                 LDAPMessage *entry,
400                                 const char *objectclass,
401                                 const char **attrs)
402 {
403         LDAPMod **mods = NULL;
404         char *name;
405         const char *dn;
406         BerElement *ptr = NULL;
407
408         dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry);
409         if (dn == NULL) {
410                 return LDAP_NO_MEMORY;
411         }
412
413         if (lp_ldap_delete_dn()) {
414                 return smbldap_delete(priv->smbldap_state, dn);
415         }
416
417         /* Ok, delete only the SAM attributes */
418         
419         for (name = ldap_first_attribute(priv2ld(priv), entry, &ptr);
420              name != NULL;
421              name = ldap_next_attribute(priv2ld(priv), entry, ptr)) {
422                 const char **attrib;
423
424                 /* We are only allowed to delete the attributes that
425                    really exist. */
426
427                 for (attrib = attrs; *attrib != NULL; attrib++) {
428                         if (strequal(*attrib, name)) {
429                                 DEBUG(10, ("ldapsam_delete_entry: deleting "
430                                            "attribute %s\n", name));
431                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name,
432                                                 NULL);
433                         }
434                 }
435                 ldap_memfree(name);
436         }
437
438         if (ptr != NULL) {
439                 ber_free(ptr, 0);
440         }
441         
442         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
443         talloc_autofree_ldapmod(mem_ctx, mods);
444         
445         return smbldap_modify(priv->smbldap_state, dn, mods);
446 }
447                   
448 static time_t ldapsam_get_entry_timestamp( struct ldapsam_privates *ldap_state, LDAPMessage * entry)
449 {
450         pstring temp;   
451         struct tm tm;
452
453         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
454                         get_userattr_key2string(ldap_state->schema_ver,LDAP_ATTR_MOD_TIMESTAMP),
455                         temp))
456                 return (time_t) 0;
457
458         strptime(temp, "%Y%m%d%H%M%SZ", &tm);
459         tzset();
460         return timegm(&tm);
461 }
462
463 /**********************************************************************
464  Initialize struct samu from an LDAP query.
465  (Based on init_sam_from_buffer in pdb_tdb.c)
466 *********************************************************************/
467
468 static BOOL init_sam_from_ldap(struct ldapsam_privates *ldap_state, 
469                                 struct samu * sampass,
470                                 LDAPMessage * entry)
471 {
472         time_t  logon_time,
473                         logoff_time,
474                         kickoff_time,
475                         pass_last_set_time, 
476                         pass_can_change_time, 
477                         pass_must_change_time,
478                         ldap_entry_time,
479                         bad_password_time;
480         pstring         username, 
481                         domain,
482                         nt_username,
483                         fullname,
484                         homedir,
485                         dir_drive,
486                         logon_script,
487                         profile_path,
488                         acct_desc,
489                         workstations;
490         char            munged_dial[2048];
491         uint32          user_rid; 
492         uint8           smblmpwd[LM_HASH_LEN],
493                         smbntpwd[NT_HASH_LEN];
494         BOOL            use_samba_attrs = True;
495         uint32          acct_ctrl = 0;
496         uint16          logon_divs;
497         uint16          bad_password_count = 0, 
498                         logon_count = 0;
499         uint32 hours_len;
500         uint8           hours[MAX_HOURS_LEN];
501         pstring temp;
502         LOGIN_CACHE     *cache_entry = NULL;
503         uint32          pwHistLen;
504         pstring         tmpstring;
505         BOOL expand_explicit = lp_passdb_expand_explicit();
506
507         /*
508          * do a little initialization
509          */
510         username[0]     = '\0';
511         domain[0]       = '\0';
512         nt_username[0]  = '\0';
513         fullname[0]     = '\0';
514         homedir[0]      = '\0';
515         dir_drive[0]    = '\0';
516         logon_script[0] = '\0';
517         profile_path[0] = '\0';
518         acct_desc[0]    = '\0';
519         munged_dial[0]  = '\0';
520         workstations[0] = '\0';
521          
522
523         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
524                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
525                 return False;
526         }
527
528         if (priv2ld(ldap_state) == NULL) {
529                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->"
530                           "ldap_struct is NULL!\n"));
531                 return False;
532         }
533         
534         if (!smbldap_get_single_pstring(priv2ld(ldap_state), entry, "uid",
535                                         username)) {
536                 DEBUG(1, ("init_sam_from_ldap: No uid attribute found for "
537                           "this user!\n"));
538                 return False;
539         }
540
541         DEBUG(2, ("init_sam_from_ldap: Entry found for user: %s\n", username));
542
543         pstrcpy(nt_username, username);
544
545         pstrcpy(domain, ldap_state->domain_name);
546         
547         pdb_set_username(sampass, username, PDB_SET);
548
549         pdb_set_domain(sampass, domain, PDB_DEFAULT);
550         pdb_set_nt_username(sampass, nt_username, PDB_SET);
551
552         /* deal with different attributes between the schema first */
553         
554         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) {
555                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
556                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), temp)) {
557                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
558                 }
559         } else {
560                 if (smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
561                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), temp)) {
562                         user_rid = (uint32)atol(temp);
563                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
564                 }
565         }
566
567         if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
568                 DEBUG(1, ("init_sam_from_ldap: no %s or %s attribute found for this user %s\n", 
569                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
570                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
571                         username));
572                 return False;
573         }
574
575         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
576                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), temp)) {
577                 /* leave as default */
578         } else {
579                 pass_last_set_time = (time_t) atol(temp);
580                 pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
581         }
582
583         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
584                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp)) {
585                 /* leave as default */
586         } else {
587                 logon_time = (time_t) atol(temp);
588                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
589         }
590
591         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
592                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp)) {
593                 /* leave as default */
594         } else {
595                 logoff_time = (time_t) atol(temp);
596                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
597         }
598
599         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
600                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp)) {
601                 /* leave as default */
602         } else {
603                 kickoff_time = (time_t) atol(temp);
604                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
605         }
606
607         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
608                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp)) {
609                 /* leave as default */
610         } else {
611                 pass_can_change_time = (time_t) atol(temp);
612                 pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
613         }
614
615         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
616                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp)) {    
617                 /* leave as default */
618         } else {
619                 pass_must_change_time = (time_t) atol(temp);
620                 pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
621         }
622
623         /* recommend that 'gecos' and 'displayName' should refer to the same
624          * attribute OID.  userFullName depreciated, only used by Samba
625          * primary rules of LDAP: don't make a new attribute when one is already defined
626          * that fits your needs; using cn then displayName rather than 'userFullName'
627          */
628
629         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
630                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), fullname)) {
631                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
632                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_CN), fullname)) {
633                         /* leave as default */
634                 } else {
635                         pdb_set_fullname(sampass, fullname, PDB_SET);
636                 }
637         } else {
638                 pdb_set_fullname(sampass, fullname, PDB_SET);
639         }
640
641         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
642                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), dir_drive)) 
643         {
644                 pdb_set_dir_drive( sampass, lp_logon_drive(), PDB_DEFAULT );
645         } else {
646                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
647         }
648
649         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
650                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), homedir)) 
651         {
652                 pdb_set_homedir( sampass, 
653                         talloc_sub_basic(sampass, username, domain,
654                                          lp_logon_home()),
655                         PDB_DEFAULT );
656         } else {
657                 pstrcpy( tmpstring, homedir );
658                 if (expand_explicit) {
659                         standard_sub_basic( username, domain, tmpstring,
660                                             sizeof(tmpstring) );
661                 }
662                 pdb_set_homedir(sampass, tmpstring, PDB_SET);
663         }
664
665         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
666                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), logon_script)) 
667         {
668                 pdb_set_logon_script( sampass, 
669                         talloc_sub_basic(sampass, username, domain,
670                                          lp_logon_script()), 
671                         PDB_DEFAULT );
672         } else {
673                 pstrcpy( tmpstring, logon_script );
674                 if (expand_explicit) {
675                         standard_sub_basic( username, domain, tmpstring,
676                                             sizeof(tmpstring) );
677                 }
678                 pdb_set_logon_script(sampass, tmpstring, PDB_SET);
679         }
680
681         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
682                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), profile_path)) 
683         {
684                 pdb_set_profile_path( sampass, 
685                         talloc_sub_basic( sampass, username, domain,
686                                           lp_logon_path()),
687                         PDB_DEFAULT );
688         } else {
689                 pstrcpy( tmpstring, profile_path );
690                 if (expand_explicit) {
691                         standard_sub_basic( username, domain, tmpstring,
692                                             sizeof(tmpstring) );
693                 }
694                 pdb_set_profile_path(sampass, tmpstring, PDB_SET);
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_DESC), acct_desc)) 
699         {
700                 /* leave as default */
701         } else {
702                 pdb_set_acct_desc(sampass, acct_desc, 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_USER_WKS), workstations)) {
707                 /* leave as default */;
708         } else {
709                 pdb_set_workstations(sampass, workstations, PDB_SET);
710         }
711
712         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
713                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), munged_dial, sizeof(munged_dial))) {
714                 /* leave as default */;
715         } else {
716                 pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
717         }
718         
719         /* FIXME: hours stuff should be cleaner */
720         
721         logon_divs = 168;
722         hours_len = 21;
723         memset(hours, 0xff, hours_len);
724
725         if (ldap_state->is_nds_ldap) {
726                 char *user_dn;
727                 size_t pwd_len;
728                 char clear_text_pw[512];
729    
730                 /* Make call to Novell eDirectory ldap extension to get clear text password.
731                         NOTE: This will only work if we have an SSL connection to eDirectory. */
732                 user_dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
733                 if (user_dn != NULL) {
734                         DEBUG(3, ("init_sam_from_ldap: smbldap_get_dn(%s) returned '%s'\n", username, user_dn));
735
736                         pwd_len = sizeof(clear_text_pw);
737                         if (pdb_nds_get_password(ldap_state->smbldap_state, user_dn, &pwd_len, clear_text_pw) == LDAP_SUCCESS) {
738                                 nt_lm_owf_gen(clear_text_pw, smbntpwd, smblmpwd);
739                                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET)) {
740                                         SAFE_FREE(user_dn);
741                                         return False;
742                                 }
743                                 ZERO_STRUCT(smblmpwd);
744                                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET)) {
745                                         SAFE_FREE(user_dn);
746                                         return False;
747                                 }
748                                 ZERO_STRUCT(smbntpwd);
749                                 use_samba_attrs = False;
750                         }
751
752                         SAFE_FREE(user_dn);
753
754                 } else {
755                         DEBUG(0, ("init_sam_from_ldap: failed to get user_dn for '%s'\n", username));
756                 }
757         }
758
759         if (use_samba_attrs) {
760                 if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry, 
761                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), temp)) {
762                         /* leave as default */
763                 } else {
764                         pdb_gethexpwd(temp, smblmpwd);
765                         memset((char *)temp, '\0', strlen(temp)+1);
766                         if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
767                                 return False;
768                         ZERO_STRUCT(smblmpwd);
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_NTPW), temp)) {
773                         /* leave as default */
774                 } else {
775                         pdb_gethexpwd(temp, smbntpwd);
776                         memset((char *)temp, '\0', strlen(temp)+1);
777                         if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
778                                 return False;
779                         ZERO_STRUCT(smbntpwd);
780                 }
781         }
782
783         pwHistLen = 0;
784
785         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
786         if (pwHistLen > 0){
787                 uint8 *pwhist = NULL;
788                 int i;
789                 char history_string[MAX_PW_HISTORY_LEN*64];
790
791                 pwHistLen = MIN(pwHistLen, MAX_PW_HISTORY_LEN);
792
793                 if ((pwhist = SMB_MALLOC_ARRAY(uint8, pwHistLen * PW_HISTORY_ENTRY_LEN)) == NULL){
794                         DEBUG(0, ("init_sam_from_ldap: malloc failed!\n"));
795                         return False;
796                 }
797                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
798
799                 if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
800                                                   get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY),
801                                                   history_string, sizeof(history_string))) {
802                         /* leave as default - zeros */
803                 } else {
804                         BOOL hex_failed = False;
805                         for (i = 0; i < pwHistLen; i++){
806                                 /* Get the 16 byte salt. */
807                                 if (!pdb_gethexpwd(&history_string[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN])) {
808                                         hex_failed = True;
809                                         break;
810                                 }
811                                 /* Get the 16 byte MD5 hash of salt+passwd. */
812                                 if (!pdb_gethexpwd(&history_string[(i*64)+32],
813                                                 &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN])) {
814                                         hex_failed = True;
815                                         break;
816                                 }
817                         }
818                         if (hex_failed) {
819                                 DEBUG(0,("init_sam_from_ldap: Failed to get password history for user %s\n",
820                                         username));
821                                 memset(pwhist, '\0', pwHistLen * PW_HISTORY_ENTRY_LEN);
822                         }
823                 }
824                 if (!pdb_set_pw_history(sampass, pwhist, pwHistLen, PDB_SET)){
825                         SAFE_FREE(pwhist);
826                         return False;
827                 }
828                 SAFE_FREE(pwhist);
829         }
830
831         if (!smbldap_get_single_pstring (ldap_state->smbldap_state->ldap_struct, entry,
832                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), temp)) {
833                 acct_ctrl |= ACB_NORMAL;
834         } else {
835                 acct_ctrl = pdb_decode_acct_ctrl(temp);
836
837                 if (acct_ctrl == 0)
838                         acct_ctrl |= ACB_NORMAL;
839
840                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
841         }
842
843         pdb_set_hours_len(sampass, hours_len, PDB_SET);
844         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
845
846         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
847                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_COUNT), temp)) {
848                         /* leave as default */
849         } else {
850                 bad_password_count = (uint32) atol(temp);
851                 pdb_set_bad_password_count(sampass, bad_password_count, PDB_SET);
852         }
853
854         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
855                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_BAD_PASSWORD_TIME), temp)) {
856                 /* leave as default */
857         } else {
858                 bad_password_time = (time_t) atol(temp);
859                 pdb_set_bad_password_time(sampass, bad_password_time, PDB_SET);
860         }
861
862
863         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
864                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_COUNT), temp)) {
865                         /* leave as default */
866         } else {
867                 logon_count = (uint32) atol(temp);
868                 pdb_set_logon_count(sampass, logon_count, PDB_SET);
869         }
870
871         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
872
873         if(!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry,
874                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_HOURS), temp)) {
875                         /* leave as default */
876         } else {
877                 pdb_gethexhours(temp, hours);
878                 memset((char *)temp, '\0', strlen(temp) +1);
879                 pdb_set_hours(sampass, hours, PDB_SET);
880                 ZERO_STRUCT(hours);
881         }
882
883         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
884                 if (smbldap_get_single_pstring(priv2ld(ldap_state), entry,
885                                                "uidNumber", temp)) {
886                         /* We've got a uid, feed the cache */
887                         uid_t uid = strtoul(temp, NULL, 10);
888                         store_uid_sid_cache(pdb_get_user_sid(sampass), uid);
889                 }
890         }
891
892         /* check the timestamp of the cache vs ldap entry */
893         if (!(ldap_entry_time = ldapsam_get_entry_timestamp(ldap_state, 
894                                                             entry)))
895                 return True;
896
897         /* see if we have newer updates */
898         if (!(cache_entry = login_cache_read(sampass))) {
899                 DEBUG (9, ("No cache entry, bad count = %u, bad time = %u\n",
900                            (unsigned int)pdb_get_bad_password_count(sampass),
901                            (unsigned int)pdb_get_bad_password_time(sampass)));
902                 return True;
903         }
904
905         DEBUG(7, ("ldap time is %u, cache time is %u, bad time = %u\n", 
906                   (unsigned int)ldap_entry_time, (unsigned int)cache_entry->entry_timestamp, 
907                   (unsigned int)cache_entry->bad_password_time));
908
909         if (ldap_entry_time > cache_entry->entry_timestamp) {
910                 /* cache is older than directory , so
911                    we need to delete the entry but allow the 
912                    fields to be written out */
913                 login_cache_delentry(sampass);
914         } else {
915                 /* read cache in */
916                 pdb_set_acct_ctrl(sampass, 
917                                   pdb_get_acct_ctrl(sampass) | 
918                                   (cache_entry->acct_ctrl & ACB_AUTOLOCK),
919                                   PDB_SET);
920                 pdb_set_bad_password_count(sampass, 
921                                            cache_entry->bad_password_count, 
922                                            PDB_SET);
923                 pdb_set_bad_password_time(sampass, 
924                                           cache_entry->bad_password_time, 
925                                           PDB_SET);
926         }
927
928         SAFE_FREE(cache_entry);
929         return True;
930 }
931
932 /**********************************************************************
933  Initialize the ldap db from a struct samu. Called on update.
934  (Based on init_buffer_from_sam in pdb_tdb.c)
935 *********************************************************************/
936
937 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state, 
938                                 LDAPMessage *existing,
939                                 LDAPMod *** mods, struct samu * sampass,
940                                 BOOL (*need_update)(const struct samu *,
941                                                     enum pdb_elements))
942 {
943         pstring temp;
944         uint32 rid;
945
946         if (mods == NULL || sampass == NULL) {
947                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
948                 return False;
949         }
950
951         *mods = NULL;
952
953         /* 
954          * took out adding "objectclass: sambaAccount"
955          * do this on a per-mod basis
956          */
957         if (need_update(sampass, PDB_USERNAME)) {
958                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
959                               "uid", pdb_get_username(sampass));
960                 if (ldap_state->is_nds_ldap) {
961                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
962                                       "cn", pdb_get_username(sampass));
963                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
964                                       "sn", pdb_get_username(sampass));
965                 }
966         }
967
968         DEBUG(2, ("init_ldap_from_sam: Setting entry for user: %s\n", pdb_get_username(sampass)));
969
970         /* only update the RID if we actually need to */
971         if (need_update(sampass, PDB_USERSID)) {
972                 fstring sid_string;
973                 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
974                 
975                 switch ( ldap_state->schema_ver ) {
976                         case SCHEMAVER_SAMBAACCOUNT:
977                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
978                                         DEBUG(1, ("init_ldap_from_sam: User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
979                                                   sid_string_static(user_sid), 
980                                                   sid_string_static(&ldap_state->domain_sid)));
981                                         return False;
982                                 }
983                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
984                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
985                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
986                                         temp);
987                                 break;
988                                 
989                         case SCHEMAVER_SAMBASAMACCOUNT:
990                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
991                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
992                                         sid_to_string(sid_string, user_sid));                                 
993                                 break;
994                                 
995                         default:
996                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
997                                 break;
998                 }               
999         }
1000
1001         /* we don't need to store the primary group RID - so leaving it
1002            'free' to hang off the unix primary group makes life easier */
1003
1004         if (need_update(sampass, PDB_GROUPSID)) {
1005                 fstring sid_string;
1006                 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
1007                 
1008                 switch ( ldap_state->schema_ver ) {
1009                         case SCHEMAVER_SAMBAACCOUNT:
1010                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
1011                                         DEBUG(1, ("init_ldap_from_sam: User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
1012                                                   sid_string_static(group_sid),
1013                                                   sid_string_static(&ldap_state->domain_sid)));
1014                                         return False;
1015                                 }
1016
1017                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
1018                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1019                                         get_userattr_key2string(ldap_state->schema_ver, 
1020                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
1021                                 break;
1022                                 
1023                         case SCHEMAVER_SAMBASAMACCOUNT:
1024                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1025                                         get_userattr_key2string(ldap_state->schema_ver, 
1026                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_string(sid_string, group_sid));
1027                                 break;
1028                                 
1029                         default:
1030                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
1031                                 break;
1032                 }
1033                 
1034         }
1035         
1036         /* displayName, cn, and gecos should all be the same
1037          *  most easily accomplished by giving them the same OID
1038          *  gecos isn't set here b/c it should be handled by the 
1039          *  add-user script
1040          *  We change displayName only and fall back to cn if
1041          *  it does not exist.
1042          */
1043
1044         if (need_update(sampass, PDB_FULLNAME))
1045                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1046                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
1047                         pdb_get_fullname(sampass));
1048
1049         if (need_update(sampass, PDB_ACCTDESC))
1050                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1051                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
1052                         pdb_get_acct_desc(sampass));
1053
1054         if (need_update(sampass, PDB_WORKSTATIONS))
1055                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1056                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
1057                         pdb_get_workstations(sampass));
1058         
1059         if (need_update(sampass, PDB_MUNGEDDIAL))
1060                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1061                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_MUNGED_DIAL), 
1062                         pdb_get_munged_dial(sampass));
1063         
1064         if (need_update(sampass, PDB_SMBHOME))
1065                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1066                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
1067                         pdb_get_homedir(sampass));
1068                         
1069         if (need_update(sampass, PDB_DRIVE))
1070                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1071                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
1072                         pdb_get_dir_drive(sampass));
1073
1074         if (need_update(sampass, PDB_LOGONSCRIPT))
1075                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1076                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
1077                         pdb_get_logon_script(sampass));
1078
1079         if (need_update(sampass, PDB_PROFILE))
1080                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1081                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
1082                         pdb_get_profile_path(sampass));
1083
1084         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
1085         if (need_update(sampass, PDB_LOGONTIME))
1086                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1087                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
1088
1089         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
1090         if (need_update(sampass, PDB_LOGOFFTIME))
1091                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1092                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
1093
1094         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
1095         if (need_update(sampass, PDB_KICKOFFTIME))
1096                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1097                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
1098
1099         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time_noncalc(sampass));
1100         if (need_update(sampass, PDB_CANCHANGETIME))
1101                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1102                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
1103
1104         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
1105         if (need_update(sampass, PDB_MUSTCHANGETIME))
1106                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1107                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
1108
1109
1110         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
1111                         || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) {
1112
1113                 if (need_update(sampass, PDB_LMPASSWD)) {
1114                         const uchar *lm_pw =  pdb_get_lanman_passwd(sampass);
1115                         if (lm_pw) {
1116                                 pdb_sethexpwd(temp, lm_pw,
1117                                               pdb_get_acct_ctrl(sampass));
1118                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1119                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1120                                                  temp);
1121                         } else {
1122                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1123                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
1124                                                  NULL);
1125                         }
1126                 }
1127                 if (need_update(sampass, PDB_NTPASSWD)) {
1128                         const uchar *nt_pw =  pdb_get_nt_passwd(sampass);
1129                         if (nt_pw) {
1130                                 pdb_sethexpwd(temp, nt_pw,
1131                                               pdb_get_acct_ctrl(sampass));
1132                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1133                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1134                                                  temp);
1135                         } else {
1136                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1137                                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
1138                                                  NULL);
1139                         }
1140                 }
1141
1142                 if (need_update(sampass, PDB_PWHISTORY)) {
1143                         uint32 pwHistLen = 0;
1144                         pdb_get_account_policy(AP_PASSWORD_HISTORY, &pwHistLen);
1145                         if (pwHistLen == 0) {
1146                                 /* Remove any password history from the LDAP store. */
1147                                 memset(temp, '0', 64); /* NOTE !!!! '0' *NOT '\0' */
1148                                 temp[64] = '\0';
1149                         } else {
1150                                 int i; 
1151                                 uint32 currHistLen = 0;
1152                                 const uint8 *pwhist = pdb_get_pw_history(sampass, &currHistLen);
1153                                 if (pwhist != NULL) {
1154                                         /* We can only store (sizeof(pstring)-1)/64 password history entries. */
1155                                         pwHistLen = MIN(pwHistLen, ((sizeof(temp)-1)/64));
1156                                         for (i=0; i< pwHistLen && i < currHistLen; i++) {
1157                                                 /* Store the salt. */
1158                                                 pdb_sethexpwd(&temp[i*64], &pwhist[i*PW_HISTORY_ENTRY_LEN], 0);
1159                                                 /* Followed by the md5 hash of salt + md4 hash */
1160                                                 pdb_sethexpwd(&temp[(i*64)+32],
1161                                                         &pwhist[(i*PW_HISTORY_ENTRY_LEN)+PW_HISTORY_SALT_LEN], 0);
1162                                                 DEBUG(100, ("temp=%s\n", temp));
1163                                         }
1164                                 } 
1165                         }
1166                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1167                                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_HISTORY), 
1168                                          temp);
1169                 }
1170
1171                 if (need_update(sampass, PDB_PASSLASTSET)) {
1172                         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
1173                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1174                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
1175                                 temp);
1176                 }
1177         }
1178
1179         if (need_update(sampass, PDB_HOURS)) {
1180                 const uint8 *hours = pdb_get_hours(sampass);
1181                 if (hours) {
1182                         pdb_sethexhours(temp, hours);
1183                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct,
1184                                 existing,
1185                                 mods,
1186                                 get_userattr_key2string(ldap_state->schema_ver,
1187                                                 LDAP_ATTR_LOGON_HOURS),
1188                                 temp);
1189                 }
1190         }
1191
1192         if (need_update(sampass, PDB_ACCTCTRL))
1193                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
1194                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
1195                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
1196
1197         /* password lockout cache: 
1198            - If we are now autolocking or clearing, we write to ldap
1199            - If we are clearing, we delete the cache entry
1200            - If the count is > 0, we update the cache
1201
1202            This even means when autolocking, we cache, just in case the
1203            update doesn't work, and we have to cache the autolock flag */
1204
1205         if (need_update(sampass, PDB_BAD_PASSWORD_COUNT))  /* &&
1206             need_update(sampass, PDB_BAD_PASSWORD_TIME)) */ {
1207                 uint16 badcount = pdb_get_bad_password_count(sampass);
1208                 time_t badtime = pdb_get_bad_password_time(sampass);
1209                 uint32 pol;
1210                 pdb_get_account_policy(AP_BAD_ATTEMPT_LOCKOUT, &pol);
1211
1212                 DEBUG(3, ("updating bad password fields, policy=%u, count=%u, time=%u\n",
1213                         (unsigned int)pol, (unsigned int)badcount, (unsigned int)badtime));
1214
1215                 if ((badcount >= pol) || (badcount == 0)) {
1216                         DEBUG(7, ("making mods to update ldap, count=%u, time=%u\n",
1217                                 (unsigned int)badcount, (unsigned int)badtime));
1218                         slprintf (temp, sizeof (temp) - 1, "%li", (long)badcount);
1219                         smbldap_make_mod(
1220                                 ldap_state->smbldap_state->ldap_struct,
1221                                 existing, mods, 
1222                                 get_userattr_key2string(
1223                                         ldap_state->schema_ver, 
1224                                         LDAP_ATTR_BAD_PASSWORD_COUNT),
1225                                 temp);
1226
1227                         slprintf (temp, sizeof (temp) - 1, "%li", badtime);
1228                         smbldap_make_mod(
1229                                 ldap_state->smbldap_state->ldap_struct, 
1230                                 existing, mods,
1231                                 get_userattr_key2string(
1232                                         ldap_state->schema_ver, 
1233                                         LDAP_ATTR_BAD_PASSWORD_TIME), 
1234                                 temp);
1235                 }
1236                 if (badcount == 0) {
1237                         DEBUG(7, ("bad password count is reset, deleting login cache entry for %s\n", pdb_get_nt_username(sampass)));
1238                         login_cache_delentry(sampass);
1239                 } else {
1240                         LOGIN_CACHE cache_entry;
1241
1242                         cache_entry.entry_timestamp = time(NULL);
1243                         cache_entry.acct_ctrl = pdb_get_acct_ctrl(sampass);
1244                         cache_entry.bad_password_count = badcount;
1245                         cache_entry.bad_password_time = badtime;
1246
1247                         DEBUG(7, ("Updating bad password count and time in login cache\n"));
1248                         login_cache_write(sampass, cache_entry);
1249                 }
1250         }
1251
1252         return True;
1253 }
1254
1255 /**********************************************************************
1256  Connect to LDAP server for password enumeration.
1257 *********************************************************************/
1258
1259 static NTSTATUS ldapsam_setsampwent(struct pdb_methods *my_methods, BOOL update, uint32 acb_mask)
1260 {
1261         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1262         int rc;
1263         pstring filter, suffix;
1264         const char **attr_list;
1265         BOOL machine_mask = False, user_mask = False;
1266
1267         pstr_sprintf( filter, "(&%s%s)", "(uid=%u)", 
1268                 get_objclass_filter(ldap_state->schema_ver));
1269         all_string_sub(filter, "%u", "*", sizeof(pstring));
1270
1271         machine_mask    = ((acb_mask != 0) && (acb_mask & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)));
1272         user_mask       = ((acb_mask != 0) && (acb_mask & ACB_NORMAL));
1273
1274         if (machine_mask) {
1275                 pstrcpy(suffix, lp_ldap_machine_suffix());
1276         } else if (user_mask) {
1277                 pstrcpy(suffix, lp_ldap_user_suffix());
1278         } else {
1279                 pstrcpy(suffix, lp_ldap_suffix());
1280         }
1281
1282         DEBUG(10,("ldapsam_setsampwent: LDAP Query for acb_mask 0x%x will use suffix %s\n", 
1283                 acb_mask, suffix));
1284
1285         attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1286         rc = smbldap_search(ldap_state->smbldap_state, suffix, LDAP_SCOPE_SUBTREE, filter, 
1287                             attr_list, 0, &ldap_state->result);
1288         TALLOC_FREE( attr_list );
1289
1290         if (rc != LDAP_SUCCESS) {
1291                 DEBUG(0, ("ldapsam_setsampwent: LDAP search failed: %s\n", ldap_err2string(rc)));
1292                 DEBUG(3, ("ldapsam_setsampwent: Query was: %s, %s\n", suffix, filter));
1293                 ldap_msgfree(ldap_state->result);
1294                 ldap_state->result = NULL;
1295                 return NT_STATUS_UNSUCCESSFUL;
1296         }
1297
1298         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base %s\n",
1299                 ldap_count_entries(ldap_state->smbldap_state->ldap_struct, 
1300                 ldap_state->result), suffix));
1301
1302         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
1303                                  ldap_state->result);
1304         ldap_state->index = 0;
1305
1306         return NT_STATUS_OK;
1307 }
1308
1309 /**********************************************************************
1310  End enumeration of the LDAP password list.
1311 *********************************************************************/
1312
1313 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1314 {
1315         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1316         if (ldap_state->result) {
1317                 ldap_msgfree(ldap_state->result);
1318                 ldap_state->result = NULL;
1319         }
1320 }
1321
1322 /**********************************************************************
1323 Get the next entry in the LDAP password database.
1324 *********************************************************************/
1325
1326 static NTSTATUS ldapsam_getsampwent(struct pdb_methods *my_methods,
1327                                     struct samu *user)
1328 {
1329         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1330         struct ldapsam_privates *ldap_state =
1331                 (struct ldapsam_privates *)my_methods->private_data;
1332         BOOL bret = False;
1333
1334         while (!bret) {
1335                 if (!ldap_state->entry)
1336                         return ret;
1337                 
1338                 ldap_state->index++;
1339                 bret = init_sam_from_ldap(ldap_state, user, ldap_state->entry);
1340                 
1341                 ldap_state->entry = ldap_next_entry(priv2ld(ldap_state),
1342                                                     ldap_state->entry); 
1343         }
1344
1345         return NT_STATUS_OK;
1346 }
1347
1348 static void append_attr(TALLOC_CTX *mem_ctx, const char ***attr_list,
1349                         const char *new_attr)
1350 {
1351         int i;
1352
1353         if (new_attr == NULL) {
1354                 return;
1355         }
1356
1357         for (i=0; (*attr_list)[i] != NULL; i++) {
1358                 ;
1359         }
1360
1361         (*attr_list) = TALLOC_REALLOC_ARRAY(mem_ctx, (*attr_list),
1362                                             const char *,  i+2);
1363         SMB_ASSERT((*attr_list) != NULL);
1364         (*attr_list)[i] = talloc_strdup((*attr_list), new_attr);
1365         (*attr_list)[i+1] = NULL;
1366 }
1367
1368 /**********************************************************************
1369 Get struct samu entry from LDAP by username.
1370 *********************************************************************/
1371
1372 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, struct samu *user, const char *sname)
1373 {
1374         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1375         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1376         LDAPMessage *result = NULL;
1377         LDAPMessage *entry = NULL;
1378         int count;
1379         const char ** attr_list;
1380         int rc;
1381         
1382         attr_list = get_userattr_list( user, ldap_state->schema_ver );
1383         append_attr(user, &attr_list,
1384                     get_userattr_key2string(ldap_state->schema_ver,
1385                                             LDAP_ATTR_MOD_TIMESTAMP));
1386         append_attr(user, &attr_list, "uidNumber");
1387         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result,
1388                                            attr_list);
1389         TALLOC_FREE( attr_list );
1390
1391         if ( rc != LDAP_SUCCESS ) 
1392                 return NT_STATUS_NO_SUCH_USER;
1393         
1394         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1395         
1396         if (count < 1) {
1397                 DEBUG(4, ("ldapsam_getsampwnam: Unable to locate user [%s] count=%d\n", sname, count));
1398                 ldap_msgfree(result);
1399                 return NT_STATUS_NO_SUCH_USER;
1400         } else if (count > 1) {
1401                 DEBUG(1, ("ldapsam_getsampwnam: Duplicate entries for this user [%s] Failing. count=%d\n", sname, count));
1402                 ldap_msgfree(result);
1403                 return NT_STATUS_NO_SUCH_USER;
1404         }
1405
1406         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1407         if (entry) {
1408                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1409                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1410                         ldap_msgfree(result);
1411                         return NT_STATUS_NO_SUCH_USER;
1412                 }
1413                 pdb_set_backend_private_data(user, result, NULL,
1414                                              my_methods, PDB_CHANGED);
1415                 talloc_autofree_ldapmsg(user, result);
1416                 ret = NT_STATUS_OK;
1417         } else {
1418                 ldap_msgfree(result);
1419         }
1420         return ret;
1421 }
1422
1423 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1424                                    const DOM_SID *sid, LDAPMessage **result) 
1425 {
1426         int rc = -1;
1427         const char ** attr_list;
1428         uint32 rid;
1429
1430         switch ( ldap_state->schema_ver ) {
1431                 case SCHEMAVER_SAMBASAMACCOUNT: {
1432                         TALLOC_CTX *tmp_ctx = talloc_new(NULL);
1433                         if (tmp_ctx == NULL) {
1434                                 return LDAP_NO_MEMORY;
1435                         }
1436
1437                         attr_list = get_userattr_list(tmp_ctx,
1438                                                       ldap_state->schema_ver);
1439                         append_attr(tmp_ctx, &attr_list,
1440                                     get_userattr_key2string(
1441                                             ldap_state->schema_ver,
1442                                             LDAP_ATTR_MOD_TIMESTAMP));
1443                         append_attr(tmp_ctx, &attr_list, "uidNumber");
1444                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid,
1445                                                           result, attr_list);
1446                         TALLOC_FREE(tmp_ctx);
1447
1448                         if ( rc != LDAP_SUCCESS ) 
1449                                 return rc;
1450                         break;
1451                 }
1452                         
1453                 case SCHEMAVER_SAMBAACCOUNT:
1454                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1455                                 return rc;
1456                         }
1457                 
1458                         attr_list = get_userattr_list(NULL,
1459                                                       ldap_state->schema_ver);
1460                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1461                         TALLOC_FREE( attr_list );
1462
1463                         if ( rc != LDAP_SUCCESS ) 
1464                                 return rc;
1465                         break;
1466         }
1467         return rc;
1468 }
1469
1470 /**********************************************************************
1471  Get struct samu entry from LDAP by SID.
1472 *********************************************************************/
1473
1474 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, struct samu * user, const DOM_SID *sid)
1475 {
1476         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1477         LDAPMessage *result = NULL;
1478         LDAPMessage *entry = NULL;
1479         int count;
1480         int rc;
1481         fstring sid_string;
1482
1483         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1484                                           sid, &result); 
1485         if (rc != LDAP_SUCCESS)
1486                 return NT_STATUS_NO_SUCH_USER;
1487
1488         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1489         
1490         if (count < 1) {
1491                 DEBUG(4, ("ldapsam_getsampwsid: Unable to locate SID [%s] count=%d\n", sid_to_string(sid_string, sid),
1492                        count));
1493                 ldap_msgfree(result);
1494                 return NT_STATUS_NO_SUCH_USER;
1495         }  else if (count > 1) {
1496                 DEBUG(1, ("ldapsam_getsampwsid: More than one user with SID [%s]. Failing. count=%d\n", sid_to_string(sid_string, sid),
1497                        count));
1498                 ldap_msgfree(result);
1499                 return NT_STATUS_NO_SUCH_USER;
1500         }
1501
1502         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1503         if (!entry) {
1504                 ldap_msgfree(result);
1505                 return NT_STATUS_NO_SUCH_USER;
1506         }
1507
1508         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1509                 DEBUG(1,("ldapsam_getsampwsid: init_sam_from_ldap failed!\n"));
1510                 ldap_msgfree(result);
1511                 return NT_STATUS_NO_SUCH_USER;
1512         }
1513
1514         pdb_set_backend_private_data(user, result, NULL,
1515                                      my_methods, PDB_CHANGED);
1516         talloc_autofree_ldapmsg(user, result);
1517         return NT_STATUS_OK;
1518 }       
1519
1520 /********************************************************************
1521  Do the actual modification - also change a plaintext passord if 
1522  it it set.
1523 **********************************************************************/
1524
1525 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1526                                      struct samu *newpwd, char *dn,
1527                                      LDAPMod **mods, int ldap_op, 
1528                                      BOOL (*need_update)(const struct samu *, enum pdb_elements))
1529 {
1530         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1531         int rc;
1532         
1533         if (!newpwd || !dn) {
1534                 return NT_STATUS_INVALID_PARAMETER;
1535         }
1536         
1537         if (!mods) {
1538                 DEBUG(5,("ldapsam_modify_entry: mods is empty: nothing to modify\n"));
1539                 /* may be password change below however */
1540         } else {
1541                 switch(ldap_op) {
1542                         case LDAP_MOD_ADD:
1543                                 if (ldap_state->is_nds_ldap) {
1544                                         smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1545                                                         "objectclass", 
1546                                                         "inetOrgPerson");
1547                                 } else {
1548                                         smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1549                                                         "objectclass", 
1550                                                         LDAP_OBJ_ACCOUNT);
1551                                 }
1552                                 rc = smbldap_add(ldap_state->smbldap_state, 
1553                                                  dn, mods);
1554                                 break;
1555                         case LDAP_MOD_REPLACE: 
1556                                 rc = smbldap_modify(ldap_state->smbldap_state, 
1557                                                     dn ,mods);
1558                                 break;
1559                         default:        
1560                                 DEBUG(0,("ldapsam_modify_entry: Wrong LDAP operation type: %d!\n", 
1561                                          ldap_op));
1562                                 return NT_STATUS_INVALID_PARAMETER;
1563                 }
1564                 
1565                 if (rc!=LDAP_SUCCESS) {
1566                         return NT_STATUS_UNSUCCESSFUL;
1567                 }  
1568         }
1569         
1570         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1571                         (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1572                         need_update(newpwd, PDB_PLAINTEXT_PW) &&
1573                         (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1574                 BerElement *ber;
1575                 struct berval *bv;
1576                 char *retoid = NULL;
1577                 struct berval *retdata = NULL;
1578                 char *utf8_password;
1579                 char *utf8_dn;
1580
1581                 if (!ldap_state->is_nds_ldap) {
1582
1583                         if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct, 
1584                                                    LDAP_EXOP_MODIFY_PASSWD)) {
1585                                 DEBUG(2, ("ldap password change requested, but LDAP "
1586                                           "server does not support it -- ignoring\n"));
1587                                 return NT_STATUS_OK;
1588                         }
1589                 }
1590
1591                 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1592                         return NT_STATUS_NO_MEMORY;
1593                 }
1594
1595                 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1596                         SAFE_FREE(utf8_password);
1597                         return NT_STATUS_NO_MEMORY;
1598                 }
1599
1600                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1601                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1602                         SAFE_FREE(utf8_password);
1603                         SAFE_FREE(utf8_dn);
1604                         return NT_STATUS_UNSUCCESSFUL;
1605                 }
1606
1607                 ber_printf (ber, "{");
1608                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn);
1609                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password);
1610                 ber_printf (ber, "N}");
1611
1612                 if ((rc = ber_flatten (ber, &bv))<0) {
1613                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1614                         ber_free(ber,1);
1615                         SAFE_FREE(utf8_dn);
1616                         SAFE_FREE(utf8_password);
1617                         return NT_STATUS_UNSUCCESSFUL;
1618                 }
1619                 
1620                 SAFE_FREE(utf8_dn);
1621                 SAFE_FREE(utf8_password);
1622                 ber_free(ber, 1);
1623
1624                 if (!ldap_state->is_nds_ldap) {
1625                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1626                                                         LDAP_EXOP_MODIFY_PASSWD,
1627                                                         bv, NULL, NULL, &retoid, 
1628                                                         &retdata);
1629                 } else {
1630                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1631                                                         pdb_get_plaintext_passwd(newpwd));
1632                 }
1633                 if (rc != LDAP_SUCCESS) {
1634                         char *ld_error = NULL;
1635
1636                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1637                                 DEBUG(3, ("Could not set userPassword "
1638                                           "attribute due to an objectClass "
1639                                           "violation -- ignoring\n"));
1640                                 ber_bvfree(bv);
1641                                 return NT_STATUS_OK;
1642                         }
1643
1644                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1645                                         &ld_error);
1646                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1647                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1648                         SAFE_FREE(ld_error);
1649                         ber_bvfree(bv);
1650                         return NT_STATUS_UNSUCCESSFUL;
1651                 } else {
1652                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1653 #ifdef DEBUG_PASSWORD
1654                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1655 #endif    
1656                         if (retdata)
1657                                 ber_bvfree(retdata);
1658                         if (retoid)
1659                                 ldap_memfree(retoid);
1660                 }
1661                 ber_bvfree(bv);
1662         }
1663         return NT_STATUS_OK;
1664 }
1665
1666 /**********************************************************************
1667  Delete entry from LDAP for username.
1668 *********************************************************************/
1669
1670 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1671                                            struct samu * sam_acct)
1672 {
1673         struct ldapsam_privates *priv =
1674                 (struct ldapsam_privates *)my_methods->private_data;
1675         const char *sname;
1676         int rc;
1677         LDAPMessage *msg, *entry;
1678         NTSTATUS result = NT_STATUS_NO_MEMORY;
1679         const char **attr_list;
1680         TALLOC_CTX *mem_ctx;
1681
1682         if (!sam_acct) {
1683                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1684                 return NT_STATUS_INVALID_PARAMETER;
1685         }
1686
1687         sname = pdb_get_username(sam_acct);
1688
1689         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1690                   "LDAP.\n", sname));
1691
1692         mem_ctx = talloc_new(NULL);
1693         if (mem_ctx == NULL) {
1694                 DEBUG(0, ("talloc_new failed\n"));
1695                 goto done;
1696         }
1697
1698         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1699         if (attr_list == NULL) {
1700                 goto done;
1701         }
1702
1703         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1704
1705         if ((rc != LDAP_SUCCESS) ||
1706             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1707             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1708                 DEBUG(5, ("Could not find user %s\n", sname));
1709                 result = NT_STATUS_NO_SUCH_USER;
1710                 goto done;
1711         }
1712         
1713         rc = ldapsam_delete_entry(
1714                 priv, mem_ctx, entry,
1715                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1716                 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1717                 attr_list);
1718
1719         result = (rc == LDAP_SUCCESS) ?
1720                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1721
1722  done:
1723         TALLOC_FREE(mem_ctx);
1724         return result;
1725 }
1726
1727 /**********************************************************************
1728  Helper function to determine for update_sam_account whether
1729  we need LDAP modification.
1730 *********************************************************************/
1731
1732 static BOOL element_is_changed(const struct samu *sampass,
1733                                enum pdb_elements element)
1734 {
1735         return IS_SAM_CHANGED(sampass, element);
1736 }
1737
1738 /**********************************************************************
1739  Update struct samu.
1740 *********************************************************************/
1741
1742 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1743 {
1744         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1745         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1746         int rc = 0;
1747         char *dn;
1748         LDAPMessage *result = NULL;
1749         LDAPMessage *entry = NULL;
1750         LDAPMod **mods = NULL;
1751         const char **attr_list;
1752
1753         result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1754         if (!result) {
1755                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1756                 if (pdb_get_username(newpwd) == NULL) {
1757                         return NT_STATUS_INVALID_PARAMETER;
1758                 }
1759                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1760                 TALLOC_FREE( attr_list );
1761                 if (rc != LDAP_SUCCESS) {
1762                         return NT_STATUS_UNSUCCESSFUL;
1763                 }
1764                 pdb_set_backend_private_data(newpwd, result, NULL,
1765                                              my_methods, PDB_CHANGED);
1766                 talloc_autofree_ldapmsg(newpwd, result);
1767         }
1768
1769         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1770                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1771                 return NT_STATUS_UNSUCCESSFUL;
1772         }
1773
1774         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1775         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1776         if (!dn) {
1777                 return NT_STATUS_UNSUCCESSFUL;
1778         }
1779
1780         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1781
1782         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1783                                 element_is_changed)) {
1784                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1785                 SAFE_FREE(dn);
1786                 if (mods != NULL)
1787                         ldap_mods_free(mods,True);
1788                 return NT_STATUS_UNSUCCESSFUL;
1789         }
1790         
1791         if (mods == NULL) {
1792                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1793                          pdb_get_username(newpwd)));
1794                 SAFE_FREE(dn);
1795                 return NT_STATUS_OK;
1796         }
1797         
1798         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1799         ldap_mods_free(mods,True);
1800         SAFE_FREE(dn);
1801
1802         /*
1803          * We need to set the backend private data to NULL here. For example
1804          * setuserinfo level 25 does a pdb_update_sam_account twice on the
1805          * same one, and with the explicit delete / add logic for attribute
1806          * values the second time we would use the wrong "old" value which
1807          * does not exist in LDAP anymore. Thus the LDAP server would refuse
1808          * the update.
1809          * The existing LDAPMessage is still being auto-freed by the
1810          * destructor.
1811          */
1812         pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1813                                      PDB_CHANGED);
1814
1815         if (!NT_STATUS_IS_OK(ret)) {
1816                 return ret;
1817         }
1818
1819         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1820                   pdb_get_username(newpwd)));
1821         return NT_STATUS_OK;
1822 }
1823
1824 /***************************************************************************
1825  Renames a struct samu
1826  - The "rename user script" has full responsibility for changing everything
1827 ***************************************************************************/
1828
1829 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1830                                            struct samu *old_acct, 
1831                                            const char *newname)
1832 {
1833         const char *oldname;
1834         int rc;
1835         pstring rename_script;
1836         fstring oldname_lower, newname_lower;
1837
1838         if (!old_acct) {
1839                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
1840                 return NT_STATUS_INVALID_PARAMETER;
1841         }
1842         if (!newname) {
1843                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
1844                 return NT_STATUS_INVALID_PARAMETER;
1845         }
1846                 
1847         oldname = pdb_get_username(old_acct);
1848
1849         /* rename the posix user */
1850         pstrcpy(rename_script, lp_renameuser_script());
1851
1852         if (!(*rename_script))
1853                 return NT_STATUS_ACCESS_DENIED;
1854
1855         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n", 
1856                    oldname, newname));
1857
1858         /* We have to allow the account name to end with a '$'.
1859            Also, follow the semantics in _samr_create_user() and lower case the
1860            posix name but preserve the case in passdb */
1861
1862         fstrcpy( oldname_lower, oldname );
1863         strlower_m( oldname_lower );
1864         fstrcpy( newname_lower, newname );
1865         strlower_m( newname_lower );
1866         string_sub2(rename_script, "%unew", newname_lower, sizeof(pstring), 
1867                     True, False, True);
1868         string_sub2(rename_script, "%uold", oldname_lower, sizeof(pstring), 
1869                     True, False, True);
1870         rc = smbrun(rename_script, NULL);
1871
1872         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n", 
1873                           rename_script, rc));
1874
1875         if (rc == 0) {
1876                 smb_nscd_flush_user_cache();
1877         }
1878
1879         if (rc)
1880                 return NT_STATUS_UNSUCCESSFUL;
1881
1882         return NT_STATUS_OK;
1883 }
1884
1885 /**********************************************************************
1886  Helper function to determine for update_sam_account whether
1887  we need LDAP modification.
1888  *********************************************************************/
1889
1890 static BOOL element_is_set_or_changed(const struct samu *sampass,
1891                                       enum pdb_elements element)
1892 {
1893         return (IS_SAM_SET(sampass, element) ||
1894                 IS_SAM_CHANGED(sampass, element));
1895 }
1896
1897 /**********************************************************************
1898  Add struct samu to LDAP.
1899 *********************************************************************/
1900
1901 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1902 {
1903         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1904         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1905         int rc;
1906         LDAPMessage     *result = NULL;
1907         LDAPMessage     *entry  = NULL;
1908         pstring         dn;
1909         LDAPMod         **mods = NULL;
1910         int             ldap_op = LDAP_MOD_REPLACE;
1911         uint32          num_result;
1912         const char      **attr_list;
1913         char            *escape_user;
1914         const char      *username = pdb_get_username(newpwd);
1915         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
1916         pstring         filter;
1917         fstring         sid_string;
1918
1919         if (!username || !*username) {
1920                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
1921                 return NT_STATUS_INVALID_PARAMETER;
1922         }
1923
1924         /* free this list after the second search or in case we exit on failure */
1925         attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1926
1927         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
1928
1929         if (rc != LDAP_SUCCESS) {
1930                 TALLOC_FREE( attr_list );
1931                 return NT_STATUS_UNSUCCESSFUL;
1932         }
1933
1934         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1935                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
1936                          username));
1937                 ldap_msgfree(result);
1938                 TALLOC_FREE( attr_list );
1939                 return NT_STATUS_UNSUCCESSFUL;
1940         }
1941         ldap_msgfree(result);
1942         result = NULL;
1943
1944         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
1945                 rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1946                                                   sid, &result); 
1947                 if (rc == LDAP_SUCCESS) {
1948                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1949                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' already in the base, with samba attributes\n", 
1950                                          sid_to_string(sid_string, sid)));
1951                                 TALLOC_FREE( attr_list );
1952                                 ldap_msgfree(result);
1953                                 return NT_STATUS_UNSUCCESSFUL;
1954                         }
1955                         ldap_msgfree(result);
1956                 }
1957         }
1958
1959         /* does the entry already exist but without a samba attributes?
1960            we need to return the samba attributes here */
1961            
1962         escape_user = escape_ldap_string_alloc( username );
1963         pstrcpy( filter, "(uid=%u)" );
1964         all_string_sub( filter, "%u", escape_user, sizeof(filter) );
1965         SAFE_FREE( escape_user );
1966
1967         rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1968                                    filter, attr_list, &result);
1969         if ( rc != LDAP_SUCCESS ) {
1970                 TALLOC_FREE( attr_list );
1971                 return NT_STATUS_UNSUCCESSFUL;
1972         }
1973
1974         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1975         
1976         if (num_result > 1) {
1977                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
1978                 TALLOC_FREE( attr_list );
1979                 ldap_msgfree(result);
1980                 return NT_STATUS_UNSUCCESSFUL;
1981         }
1982         
1983         /* Check if we need to update an existing entry */
1984         if (num_result == 1) {
1985                 char *tmp;
1986                 
1987                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
1988                 ldap_op = LDAP_MOD_REPLACE;
1989                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1990                 tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1991                 if (!tmp) {
1992                         TALLOC_FREE( attr_list );
1993                         ldap_msgfree(result);
1994                         return NT_STATUS_UNSUCCESSFUL;
1995                 }
1996                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1997                 SAFE_FREE(tmp);
1998
1999         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2000
2001                 /* There might be a SID for this account already - say an idmap entry */
2002
2003                 pstr_sprintf(filter, "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))", 
2004                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
2005                          sid_to_string(sid_string, sid),
2006                          LDAP_OBJ_IDMAP_ENTRY,
2007                          LDAP_OBJ_SID_ENTRY);
2008                 
2009                 /* free old result before doing a new search */
2010                 if (result != NULL) {
2011                         ldap_msgfree(result);
2012                         result = NULL;
2013                 }
2014                 rc = smbldap_search_suffix(ldap_state->smbldap_state, 
2015                                            filter, attr_list, &result);
2016                         
2017                 if ( rc != LDAP_SUCCESS ) {
2018                         TALLOC_FREE( attr_list );
2019                         return NT_STATUS_UNSUCCESSFUL;
2020                 }
2021                 
2022                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2023                 
2024                 if (num_result > 1) {
2025                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2026                         TALLOC_FREE( attr_list );
2027                         ldap_msgfree(result);
2028                         return NT_STATUS_UNSUCCESSFUL;
2029                 }
2030                 
2031                 /* Check if we need to update an existing entry */
2032                 if (num_result == 1) {
2033                         char *tmp;
2034                         
2035                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2036                         ldap_op = LDAP_MOD_REPLACE;
2037                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2038                         tmp = smbldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
2039                         if (!tmp) {
2040                                 TALLOC_FREE( attr_list );
2041                                 ldap_msgfree(result);
2042                                 return NT_STATUS_UNSUCCESSFUL;
2043                         }
2044                         slprintf (dn, sizeof (dn) - 1, "%s", tmp);
2045                         SAFE_FREE(tmp);
2046                 }
2047         }
2048         
2049         TALLOC_FREE( attr_list );
2050
2051         if (num_result == 0) {
2052                 char *escape_username;
2053                 /* Check if we need to add an entry */
2054                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2055                 ldap_op = LDAP_MOD_ADD;
2056
2057                 escape_username = escape_rdn_val_string_alloc(username);
2058                 if (!escape_username) {
2059                         DEBUG(0, ("Out of memory!\n"));
2060                         ldap_msgfree(result);
2061                         return NT_STATUS_NO_MEMORY;
2062                 }
2063
2064                 if (username[strlen(username)-1] == '$') {
2065                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", escape_username, lp_ldap_machine_suffix ());
2066                 } else {
2067                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", escape_username, lp_ldap_user_suffix ());
2068                 }
2069
2070                 SAFE_FREE(escape_username);
2071         }
2072
2073         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2074                                 element_is_set_or_changed)) {
2075                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2076                 ldap_msgfree(result);
2077                 if (mods != NULL)
2078                         ldap_mods_free(mods,True);
2079                 return NT_STATUS_UNSUCCESSFUL;          
2080         }
2081         
2082         ldap_msgfree(result);
2083
2084         if (mods == NULL) {
2085                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2086                 return NT_STATUS_UNSUCCESSFUL;
2087         }
2088         switch ( ldap_state->schema_ver ) {
2089                 case SCHEMAVER_SAMBAACCOUNT:
2090                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2091                         break;
2092                 case SCHEMAVER_SAMBASAMACCOUNT:
2093                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2094                         break;
2095                 default:
2096                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2097                         break;
2098         }
2099
2100         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2101         if (!NT_STATUS_IS_OK(ret)) {
2102                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2103                          pdb_get_username(newpwd),dn));
2104                 ldap_mods_free(mods, True);
2105                 return ret;
2106         }
2107
2108         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2109         ldap_mods_free(mods, True);
2110         
2111         return NT_STATUS_OK;
2112 }
2113
2114 /**********************************************************************
2115  *********************************************************************/
2116
2117 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2118                                      const char *filter,
2119                                      LDAPMessage ** result)
2120 {
2121         int scope = LDAP_SCOPE_SUBTREE;
2122         int rc;
2123         const char **attr_list;
2124
2125         attr_list = get_attr_list(NULL, groupmap_attr_list);
2126         rc = smbldap_search(ldap_state->smbldap_state, 
2127                             lp_ldap_group_suffix (), scope,
2128                             filter, attr_list, 0, result);
2129         TALLOC_FREE(attr_list);
2130
2131         return rc;
2132 }
2133
2134 /**********************************************************************
2135  *********************************************************************/
2136
2137 static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
2138                                  GROUP_MAP *map, LDAPMessage *entry)
2139 {
2140         pstring temp;
2141
2142         if (ldap_state == NULL || map == NULL || entry == NULL ||
2143                         ldap_state->smbldap_state->ldap_struct == NULL) {
2144                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2145                 return False;
2146         }
2147
2148         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2149                         get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER), temp)) {
2150                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2151                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2152                 return False;
2153         }
2154         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2155
2156         map->gid = (gid_t)atol(temp);
2157
2158         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2159                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID), temp)) {
2160                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2161                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2162                 return False;
2163         }
2164         
2165         if (!string_to_sid(&map->sid, temp)) {
2166                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2167                 return False;
2168         }
2169
2170         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2171                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), temp)) {
2172                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2173                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2174                 return False;
2175         }
2176         map->sid_name_use = (enum lsa_SidType)atol(temp);
2177
2178         if ((map->sid_name_use < SID_NAME_USER) ||
2179                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2180                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2181                 return False;
2182         }
2183
2184         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2185                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), temp)) {
2186                 temp[0] = '\0';
2187                 if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2188                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_CN), temp)) 
2189                 {
2190                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2191 for gidNumber(%lu)\n",(unsigned long)map->gid));
2192                         return False;
2193                 }
2194         }
2195         fstrcpy(map->nt_name, temp);
2196
2197         if (!smbldap_get_single_pstring(ldap_state->smbldap_state->ldap_struct, entry, 
2198                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), temp)) {
2199                 temp[0] = '\0';
2200         }
2201         fstrcpy(map->comment, temp);
2202
2203         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
2204                 store_gid_sid_cache(&map->sid, map->gid);
2205         }
2206
2207         return True;
2208 }
2209
2210 /**********************************************************************
2211  *********************************************************************/
2212
2213 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2214                                  const char *filter,
2215                                  GROUP_MAP *map)
2216 {
2217         struct ldapsam_privates *ldap_state =
2218                 (struct ldapsam_privates *)methods->private_data;
2219         LDAPMessage *result = NULL;
2220         LDAPMessage *entry = NULL;
2221         int count;
2222
2223         if (ldapsam_search_one_group(ldap_state, filter, &result)
2224             != LDAP_SUCCESS) {
2225                 return NT_STATUS_NO_SUCH_GROUP;
2226         }
2227
2228         count = ldap_count_entries(priv2ld(ldap_state), result);
2229
2230         if (count < 1) {
2231                 DEBUG(4, ("ldapsam_getgroup: Did not find group\n"));
2232                 ldap_msgfree(result);
2233                 return NT_STATUS_NO_SUCH_GROUP;
2234         }
2235
2236         if (count > 1) {
2237                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2238                           "count=%d\n", filter, count));
2239                 ldap_msgfree(result);
2240                 return NT_STATUS_NO_SUCH_GROUP;
2241         }
2242
2243         entry = ldap_first_entry(priv2ld(ldap_state), result);
2244
2245         if (!entry) {
2246                 ldap_msgfree(result);
2247                 return NT_STATUS_UNSUCCESSFUL;
2248         }
2249
2250         if (!init_group_from_ldap(ldap_state, map, entry)) {
2251                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2252                           "group filter %s\n", filter));
2253                 ldap_msgfree(result);
2254                 return NT_STATUS_NO_SUCH_GROUP;
2255         }
2256
2257         ldap_msgfree(result);
2258         return NT_STATUS_OK;
2259 }
2260
2261 /**********************************************************************
2262  *********************************************************************/
2263
2264 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2265                                  DOM_SID sid)
2266 {
2267         pstring filter;
2268
2269         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
2270                 LDAP_OBJ_GROUPMAP, 
2271                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2272                 sid_string_static(&sid));
2273
2274         return ldapsam_getgroup(methods, filter, map);
2275 }
2276
2277 /**********************************************************************
2278  *********************************************************************/
2279
2280 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2281                                  gid_t gid)
2282 {
2283         pstring filter;
2284
2285         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))",
2286                 LDAP_OBJ_GROUPMAP,
2287                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2288                 (unsigned long)gid);
2289
2290         return ldapsam_getgroup(methods, filter, map);
2291 }
2292
2293 /**********************************************************************
2294  *********************************************************************/
2295
2296 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2297                                  const char *name)
2298 {
2299         pstring filter;
2300         char *escape_name = escape_ldap_string_alloc(name);
2301
2302         if (!escape_name) {
2303                 return NT_STATUS_NO_MEMORY;
2304         }
2305
2306         pstr_sprintf(filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2307                 LDAP_OBJ_GROUPMAP,
2308                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2309                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN), escape_name);
2310
2311         SAFE_FREE(escape_name);
2312
2313         return ldapsam_getgroup(methods, filter, map);
2314 }
2315
2316 static BOOL ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2317                                            LDAPMessage *entry,
2318                                            const DOM_SID *domain_sid,
2319                                            uint32 *rid)
2320 {
2321         fstring str;
2322         DOM_SID sid;
2323
2324         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2325                                           str, sizeof(str)-1)) {
2326                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2327                 return False;
2328         }
2329
2330         if (!string_to_sid(&sid, str)) {
2331                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2332                 return False;
2333         }
2334
2335         if (sid_compare_domain(&sid, domain_sid) != 0) {
2336                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2337                            str, sid_string_static(domain_sid)));
2338                 return False;
2339         }
2340
2341         if (!sid_peek_rid(&sid, rid)) {
2342                 DEBUG(10, ("Could not peek into RID\n"));
2343                 return False;
2344         }
2345
2346         return True;
2347 }
2348
2349 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2350                                            TALLOC_CTX *mem_ctx,
2351                                            const DOM_SID *group,
2352                                            uint32 **pp_member_rids,
2353                                            size_t *p_num_members)
2354 {
2355         struct ldapsam_privates *ldap_state =
2356                 (struct ldapsam_privates *)methods->private_data;
2357         struct smbldap_state *conn = ldap_state->smbldap_state;
2358         const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2359         const char *sid_attrs[] = { "sambaSID", NULL };
2360         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2361         LDAPMessage *result = NULL;
2362         LDAPMessage *entry;
2363         char *filter;
2364         char **values = NULL;
2365         char **memberuid;
2366         char *gidstr;
2367         int rc, count;
2368
2369         *pp_member_rids = NULL;
2370         *p_num_members = 0;
2371
2372         filter = talloc_asprintf(mem_ctx,
2373                                  "(&(objectClass=%s)"
2374                                  "(objectClass=%s)"
2375                                  "(sambaSID=%s))",
2376                                  LDAP_OBJ_POSIXGROUP,
2377                                  LDAP_OBJ_GROUPMAP,
2378                                  sid_string_static(group));
2379         if (filter == NULL) {
2380                 ret = NT_STATUS_NO_MEMORY;
2381                 goto done;
2382         }
2383
2384         rc = smbldap_search(conn, lp_ldap_group_suffix(),
2385                             LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2386                             &result);
2387
2388         if (rc != LDAP_SUCCESS)
2389                 goto done;
2390
2391         talloc_autofree_ldapmsg(mem_ctx, result);
2392
2393         count = ldap_count_entries(conn->ldap_struct, result);
2394
2395         if (count > 1) {
2396                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2397                           sid_string_static(group)));
2398                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2399                 goto done;
2400         }
2401
2402         if (count == 0) {
2403                 ret = NT_STATUS_NO_SUCH_GROUP;
2404                 goto done;
2405         }
2406
2407         entry = ldap_first_entry(conn->ldap_struct, result);
2408         if (entry == NULL)
2409                 goto done;
2410
2411         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2412         if (!gidstr) {
2413                 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2414                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2415                 goto done;
2416         }
2417
2418         values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2419
2420         if (values) {
2421
2422                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2423                 if (filter == NULL) {
2424                         ret = NT_STATUS_NO_MEMORY;
2425                         goto done;
2426                 }
2427
2428                 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2429                         char *escape_memberuid;
2430
2431                         escape_memberuid = escape_ldap_string_alloc(*memberuid);
2432                         if (escape_memberuid == NULL) {
2433                                 ret = NT_STATUS_NO_MEMORY;
2434                                 goto done;
2435                         }
2436                         
2437                         filter = talloc_asprintf_append(filter, "(uid=%s)", escape_memberuid);
2438                         if (filter == NULL) {
2439                                 SAFE_FREE(escape_memberuid);
2440                                 ret = NT_STATUS_NO_MEMORY;
2441                                 goto done;
2442                         }
2443
2444                         SAFE_FREE(escape_memberuid);
2445                 }
2446
2447                 filter = talloc_asprintf_append(filter, "))");
2448                 if (filter == NULL) {
2449                         ret = NT_STATUS_NO_MEMORY;
2450                         goto done;
2451                 }
2452
2453                 rc = smbldap_search(conn, lp_ldap_user_suffix(),
2454                                     LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2455                                     &result);
2456
2457                 if (rc != LDAP_SUCCESS)
2458                         goto done;
2459
2460                 count = ldap_count_entries(conn->ldap_struct, result);
2461                 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2462
2463                 talloc_autofree_ldapmsg(mem_ctx, result);
2464
2465                 for (entry = ldap_first_entry(conn->ldap_struct, result);
2466                      entry != NULL;
2467                      entry = ldap_next_entry(conn->ldap_struct, entry))
2468                 {
2469                         char *sidstr;
2470                         DOM_SID sid;
2471                         uint32 rid;
2472
2473                         sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2474                                                                  entry, "sambaSID",
2475                                                                  mem_ctx);
2476                         if (!sidstr) {
2477                                 DEBUG(0, ("Severe DB error, sambaSamAccount can't miss "
2478                                           "the sambaSID attribute\n"));
2479                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2480                                 goto done;
2481                         }
2482
2483                         if (!string_to_sid(&sid, sidstr))
2484                                 goto done;
2485
2486                         if (!sid_check_is_in_our_domain(&sid)) {
2487                                 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2488                                           "in our domain\n"));
2489                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2490                                 goto done;
2491                         }
2492
2493                         sid_peek_rid(&sid, &rid);
2494
2495                         if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2496                                                 p_num_members)) {
2497                                 ret = NT_STATUS_NO_MEMORY;
2498                                 goto done;
2499                         }
2500                 }
2501         }
2502
2503         filter = talloc_asprintf(mem_ctx,
2504                                  "(&(objectClass=%s)"
2505                                  "(gidNumber=%s))",
2506                                  LDAP_OBJ_SAMBASAMACCOUNT,
2507                                  gidstr);
2508
2509         rc = smbldap_search(conn, lp_ldap_user_suffix(),
2510                             LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2511                             &result);
2512
2513         if (rc != LDAP_SUCCESS)
2514                 goto done;
2515
2516         talloc_autofree_ldapmsg(mem_ctx, result);
2517
2518         for (entry = ldap_first_entry(conn->ldap_struct, result);
2519              entry != NULL;
2520              entry = ldap_next_entry(conn->ldap_struct, entry))
2521         {
2522                 uint32 rid;
2523
2524                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2525                                                     entry,
2526                                                     get_global_sam_sid(),
2527                                                     &rid)) {
2528                         DEBUG(0, ("Severe DB error, sambaSamAccount can't miss "
2529                                   "the sambaSID attribute\n"));
2530                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2531                         goto done;
2532                 }
2533
2534                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2535                                         p_num_members)) {
2536                         ret = NT_STATUS_NO_MEMORY;
2537                         goto done;
2538                 }
2539         }
2540
2541         ret = NT_STATUS_OK;
2542         
2543  done:
2544
2545         if (values)
2546                 ldap_value_free(values);
2547
2548         return ret;
2549 }
2550
2551 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2552                                                TALLOC_CTX *mem_ctx,
2553                                                struct samu *user,
2554                                                DOM_SID **pp_sids,
2555                                                gid_t **pp_gids,
2556                                                size_t *p_num_groups)
2557 {
2558         struct ldapsam_privates *ldap_state =
2559                 (struct ldapsam_privates *)methods->private_data;
2560         struct smbldap_state *conn = ldap_state->smbldap_state;
2561         char *filter;
2562         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2563         char *escape_name;
2564         int rc, count;
2565         LDAPMessage *result = NULL;
2566         LDAPMessage *entry;
2567         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2568         size_t num_sids, num_gids;
2569         char *gidstr;
2570         gid_t primary_gid = -1;
2571
2572         *pp_sids = NULL;
2573         num_sids = 0;
2574
2575         if (pdb_get_username(user) == NULL) {
2576                 return NT_STATUS_INVALID_PARAMETER;
2577         }
2578
2579         escape_name = escape_ldap_string_alloc(pdb_get_username(user));
2580         if (escape_name == NULL)
2581                 return NT_STATUS_NO_MEMORY;
2582
2583         /* retrieve the users primary gid */
2584         filter = talloc_asprintf(mem_ctx,
2585                                  "(&(objectClass=%s)(uid=%s))",
2586                                  LDAP_OBJ_SAMBASAMACCOUNT,
2587                                  escape_name);
2588         if (filter == NULL) {
2589                 ret = NT_STATUS_NO_MEMORY;
2590                 goto done;
2591         }
2592
2593         rc = smbldap_search(conn, lp_ldap_user_suffix(),
2594                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2595
2596         if (rc != LDAP_SUCCESS)
2597                 goto done;
2598
2599         talloc_autofree_ldapmsg(mem_ctx, result);
2600
2601         count = ldap_count_entries(priv2ld(ldap_state), result);
2602
2603         switch (count) {
2604         case 0: 
2605                 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2606                 ret = NT_STATUS_NO_SUCH_USER;
2607                 goto done;
2608         case 1:
2609                 entry = ldap_first_entry(priv2ld(ldap_state), result);
2610
2611                 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2612                 if (!gidstr) {
2613                         DEBUG (1, ("Unable to find the member's gid!\n"));
2614                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2615                         goto done;
2616                 }
2617                 primary_gid = strtoul(gidstr, NULL, 10);
2618                 break;
2619         default:
2620                 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2621                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2622                 goto done;
2623         }
2624
2625         filter = talloc_asprintf(mem_ctx,
2626                                  "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%d)))",
2627                                  LDAP_OBJ_POSIXGROUP, escape_name, primary_gid);
2628         if (filter == NULL) {
2629                 ret = NT_STATUS_NO_MEMORY;
2630                 goto done;
2631         }
2632
2633         rc = smbldap_search(conn, lp_ldap_group_suffix(),
2634                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2635
2636         if (rc != LDAP_SUCCESS)
2637                 goto done;
2638
2639         talloc_autofree_ldapmsg(mem_ctx, result);
2640
2641         num_gids = 0;
2642         *pp_gids = NULL;
2643
2644         num_sids = 0;
2645         *pp_sids = NULL;
2646
2647         /* We need to add the primary group as the first gid/sid */
2648
2649         if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2650                 ret = NT_STATUS_NO_MEMORY;
2651                 goto done;
2652         }
2653
2654         /* This sid will be replaced later */
2655
2656         if (!add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids, &num_sids)) {
2657                 ret = NT_STATUS_NO_MEMORY;
2658                 goto done;
2659         }
2660
2661         for (entry = ldap_first_entry(conn->ldap_struct, result);
2662              entry != NULL;
2663              entry = ldap_next_entry(conn->ldap_struct, entry))
2664         {
2665                 fstring str;
2666                 DOM_SID sid;
2667                 gid_t gid;
2668                 char *end;
2669
2670                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2671                                                   entry, "sambaSID",
2672                                                   str, sizeof(str)-1))
2673                         continue;
2674
2675                 if (!string_to_sid(&sid, str))
2676                         goto done;
2677
2678                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2679                                                   entry, "gidNumber",
2680                                                   str, sizeof(str)-1))
2681                         continue;
2682
2683                 gid = strtoul(str, &end, 10);
2684
2685                 if (PTR_DIFF(end, str) != strlen(str))
2686                         goto done;
2687
2688                 if (gid == primary_gid) {
2689                         sid_copy(&(*pp_sids)[0], &sid);
2690                 } else {
2691                         if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2692                                                 &num_gids)) {
2693                                 ret = NT_STATUS_NO_MEMORY;
2694                                 goto done;
2695                         }
2696                         if (!add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2697                                                 &num_sids)) {
2698                                 ret = NT_STATUS_NO_MEMORY;
2699                                 goto done;
2700                         }
2701                 }
2702         }
2703
2704         if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2705                 DEBUG(3, ("primary group of [%s] not found\n",
2706                           pdb_get_username(user)));
2707                 goto done;
2708         }
2709
2710         *p_num_groups = num_sids;
2711
2712         ret = NT_STATUS_OK;
2713
2714  done:
2715
2716         SAFE_FREE(escape_name);
2717         return ret;
2718 }
2719
2720 /**********************************************************************
2721  * Augment a posixGroup object with a sambaGroupMapping domgroup
2722  *********************************************************************/
2723
2724 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2725                                        struct ldapsam_privates *ldap_state,
2726                                        GROUP_MAP *map)
2727 {
2728         const char *filter, *dn;
2729         LDAPMessage *msg, *entry;
2730         LDAPMod **mods;
2731         int rc;
2732
2733         filter = talloc_asprintf(mem_ctx,
2734                                  "(&(objectClass=posixGroup)(gidNumber=%u))",
2735                                  map->gid);
2736         if (filter == NULL) {
2737                 return NT_STATUS_NO_MEMORY;
2738         }
2739
2740         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2741                                    get_attr_list(mem_ctx, groupmap_attr_list),
2742                                    &msg);
2743         talloc_autofree_ldapmsg(mem_ctx, msg);
2744
2745         if ((rc != LDAP_SUCCESS) ||
2746             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2747             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2748                 return NT_STATUS_NO_SUCH_GROUP;
2749         }
2750
2751         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2752         if (dn == NULL) {
2753                 return NT_STATUS_NO_MEMORY;
2754         }
2755
2756         mods = NULL;
2757         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
2758                         "sambaGroupMapping");
2759         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
2760                          sid_string_static(&map->sid));
2761         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
2762                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2763         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2764                          map->nt_name);
2765         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2766                          map->comment);
2767         talloc_autofree_ldapmod(mem_ctx, mods);
2768
2769         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2770         if (rc != LDAP_SUCCESS) {
2771                 return NT_STATUS_ACCESS_DENIED;
2772         }
2773
2774         return NT_STATUS_OK;
2775 }
2776
2777 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
2778                                                 GROUP_MAP *map)
2779 {
2780         struct ldapsam_privates *ldap_state =
2781                 (struct ldapsam_privates *)methods->private_data;
2782         LDAPMessage *msg = NULL;
2783         LDAPMod **mods = NULL;
2784         const char *attrs[] = { NULL };
2785         char *filter;
2786
2787         char *dn;
2788         TALLOC_CTX *mem_ctx;
2789         NTSTATUS result;
2790
2791         DOM_SID sid;
2792
2793         int rc;
2794
2795         mem_ctx = talloc_new(NULL);
2796         if (mem_ctx == NULL) {
2797                 DEBUG(0, ("talloc_new failed\n"));
2798                 return NT_STATUS_NO_MEMORY;
2799         }
2800
2801         filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
2802                                  sid_string_static(&map->sid));
2803         if (filter == NULL) {
2804                 result = NT_STATUS_NO_MEMORY;
2805                 goto done;
2806         }
2807
2808         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
2809                             LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
2810         talloc_autofree_ldapmsg(mem_ctx, msg);
2811
2812         if ((rc == LDAP_SUCCESS) &&
2813             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
2814
2815                 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
2816                           "group mapping entry\n",
2817                           sid_string_static(&map->sid)));
2818                 result = NT_STATUS_GROUP_EXISTS;
2819                 goto done;
2820         }
2821
2822         switch (map->sid_name_use) {
2823
2824         case SID_NAME_DOM_GRP:
2825                 /* To map a domain group we need to have a posix group
2826                    to attach to. */
2827                 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
2828                 goto done;
2829                 break;
2830
2831         case SID_NAME_ALIAS:
2832                 if (!sid_check_is_in_our_domain(&map->sid) 
2833                         && !sid_check_is_in_builtin(&map->sid) ) 
2834                 {
2835                         DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
2836                                   sid_string_static(&map->sid)));
2837                         result = NT_STATUS_INVALID_PARAMETER;
2838                         goto done;
2839                 }
2840                 break;
2841
2842         default:
2843                 DEBUG(3, ("Got invalid use '%s' for mapping\n",
2844                           sid_type_lookup(map->sid_name_use)));
2845                 result = NT_STATUS_INVALID_PARAMETER;
2846                 goto done;
2847         }
2848
2849         /* Domain groups have been mapped in a separate routine, we have to
2850          * create an alias now */
2851
2852         if (map->gid == -1) {
2853                 DEBUG(10, ("Refusing to map gid==-1\n"));
2854                 result = NT_STATUS_INVALID_PARAMETER;
2855                 goto done;
2856         }
2857
2858         if (pdb_gid_to_sid(map->gid, &sid)) {
2859                 DEBUG(3, ("Gid %d is already mapped to SID %s, refusing to "
2860                           "add\n", map->gid, sid_string_static(&sid)));
2861                 result = NT_STATUS_GROUP_EXISTS;
2862                 goto done;
2863         }
2864
2865         /* Ok, enough checks done. It's still racy to go ahead now, but that's
2866          * the best we can get out of LDAP. */
2867
2868         dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
2869                              sid_string_static(&map->sid),
2870                              lp_ldap_group_suffix());
2871         if (dn == NULL) {
2872                 result = NT_STATUS_NO_MEMORY;
2873                 goto done;
2874         }
2875
2876         mods = NULL;
2877
2878         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
2879                          "sambaSidEntry");
2880         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
2881                          "sambaGroupMapping");
2882
2883         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
2884                          sid_string_static(&map->sid));
2885         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
2886                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
2887         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
2888                          map->nt_name);
2889         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
2890                          map->comment);
2891         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
2892                          talloc_asprintf(mem_ctx, "%u", map->gid));
2893         talloc_autofree_ldapmod(mem_ctx, mods);
2894
2895         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
2896
2897         result = (rc == LDAP_SUCCESS) ?
2898                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
2899
2900  done:
2901         TALLOC_FREE(mem_ctx);
2902         return result;
2903 }
2904
2905 /**********************************************************************
2906  * Update a group mapping entry. We're quite strict about what can be changed:
2907  * Only the description and displayname may be changed. It simply does not
2908  * make any sense to change the SID, gid or the type in a mapping.
2909  *********************************************************************/
2910
2911 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
2912                                                    GROUP_MAP *map)
2913 {
2914         struct ldapsam_privates *ldap_state =
2915                 (struct ldapsam_privates *)methods->private_data;
2916         int rc;
2917         const char *filter, *dn;
2918         LDAPMessage *msg = NULL;
2919         LDAPMessage *entry = NULL;
2920         LDAPMod **mods = NULL;
2921         TALLOC_CTX *mem_ctx;
2922         NTSTATUS result;
2923
2924         mem_ctx = talloc_new(NULL);
2925         if (mem_ctx == NULL) {
2926                 DEBUG(0, ("talloc_new failed\n"));
2927                 return NT_STATUS_NO_MEMORY;
2928         }
2929
2930         /* Make 100% sure that sid, gid and type are not changed by looking up
2931          * exactly the values we're given in LDAP. */
2932
2933         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
2934                                  "(sambaSid=%s)(gidNumber=%u)"
2935                                  "(sambaGroupType=%d))",
2936                                  LDAP_OBJ_GROUPMAP,
2937                                  sid_string_static(&map->sid), map->gid,
2938                                  map->sid_name_use);
2939         if (filter == NULL) {
2940                 result = NT_STATUS_NO_MEMORY;
2941                 goto done;
2942         }
2943
2944         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2945                                    get_attr_list(mem_ctx, groupmap_attr_list),
2946                                    &msg);
2947         talloc_autofree_ldapmsg(mem_ctx, msg);
2948
2949         if ((rc != LDAP_SUCCESS) ||
2950             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
2951             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
2952                 result = NT_STATUS_NO_SUCH_GROUP;
2953                 goto done;
2954         }
2955
2956         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
2957
2958         if (dn == NULL) {
2959                 result = NT_STATUS_NO_MEMORY;
2960                 goto done;
2961         }
2962
2963         mods = NULL;
2964         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
2965                          map->nt_name);
2966         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
2967                          map->comment);
2968         talloc_autofree_ldapmod(mem_ctx, mods);
2969
2970         if (mods == NULL) {
2971                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
2972                           "nothing to do\n"));
2973                 result = NT_STATUS_OK;
2974                 goto done;
2975         }
2976
2977         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2978
2979         if (rc != LDAP_SUCCESS) {
2980                 result = NT_STATUS_ACCESS_DENIED;
2981                 goto done;
2982         }
2983
2984         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
2985                   "group %lu in LDAP\n", (unsigned long)map->gid));
2986
2987         result = NT_STATUS_OK;
2988
2989  done:
2990         TALLOC_FREE(mem_ctx);
2991         return result;
2992 }
2993
2994 /**********************************************************************
2995  *********************************************************************/
2996
2997 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
2998                                                    DOM_SID sid)
2999 {
3000         struct ldapsam_privates *priv =
3001                 (struct ldapsam_privates *)methods->private_data;
3002         LDAPMessage *msg, *entry;
3003         int rc;
3004         NTSTATUS result;
3005         TALLOC_CTX *mem_ctx;
3006         char *filter;
3007
3008         mem_ctx = talloc_new(NULL);
3009         if (mem_ctx == NULL) {
3010                 DEBUG(0, ("talloc_new failed\n"));
3011                 return NT_STATUS_NO_MEMORY;
3012         }
3013
3014         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3015                                  LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3016                                  sid_string_static(&sid));
3017         if (filter == NULL) {
3018                 result = NT_STATUS_NO_MEMORY;
3019                 goto done;
3020         }
3021         rc = smbldap_search_suffix(priv->smbldap_state, filter,
3022                                    get_attr_list(mem_ctx, groupmap_attr_list),
3023                                    &msg);
3024         talloc_autofree_ldapmsg(mem_ctx, msg);
3025
3026         if ((rc != LDAP_SUCCESS) ||
3027             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3028             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3029                 result = NT_STATUS_NO_SUCH_GROUP;
3030                 goto done;
3031         }
3032
3033         rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3034                                   get_attr_list(mem_ctx,
3035                                                 groupmap_attr_list_to_delete));
3036  
3037         if ((rc == LDAP_NAMING_VIOLATION) ||
3038             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3039                 const char *attrs[] = { "sambaGroupType", "description",
3040                                         "displayName", "sambaSIDList",
3041                                         NULL };
3042
3043                 /* Second try. Don't delete the sambaSID attribute, this is
3044                    for "old" entries that are tacked on a winbind
3045                    sambaIdmapEntry. */
3046
3047                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3048                                           LDAP_OBJ_GROUPMAP, attrs);
3049         }
3050
3051         if ((rc == LDAP_NAMING_VIOLATION) ||
3052             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3053                 const char *attrs[] = { "sambaGroupType", "description",
3054                                         "displayName", "sambaSIDList",
3055                                         "gidNumber", NULL };
3056
3057                 /* Third try. This is a post-3.0.21 alias (containing only
3058                  * sambaSidEntry and sambaGroupMapping classes), we also have
3059                  * to delete the gidNumber attribute, only the sambaSidEntry
3060                  * remains */
3061
3062                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3063                                           LDAP_OBJ_GROUPMAP, attrs);
3064         }
3065
3066         result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3067
3068  done:
3069         TALLOC_FREE(mem_ctx);
3070         return result;
3071  }
3072
3073 /**********************************************************************
3074  *********************************************************************/
3075
3076 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3077                                     BOOL update)
3078 {
3079         struct ldapsam_privates *ldap_state =
3080                 (struct ldapsam_privates *)my_methods->private_data;
3081         fstring filter;
3082         int rc;
3083         const char **attr_list;
3084
3085         pstr_sprintf( filter, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3086         attr_list = get_attr_list( NULL, groupmap_attr_list );
3087         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3088                             LDAP_SCOPE_SUBTREE, filter,
3089                             attr_list, 0, &ldap_state->result);
3090         TALLOC_FREE(attr_list);
3091
3092         if (rc != LDAP_SUCCESS) {
3093                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3094                           ldap_err2string(rc)));
3095                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3096                           lp_ldap_group_suffix(), filter));
3097                 ldap_msgfree(ldap_state->result);
3098                 ldap_state->result = NULL;
3099                 return NT_STATUS_UNSUCCESSFUL;
3100         }
3101
3102         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3103                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3104                                      ldap_state->result)));
3105
3106         ldap_state->entry =
3107                 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3108                                  ldap_state->result);
3109         ldap_state->index = 0;
3110
3111         return NT_STATUS_OK;
3112 }
3113
3114 /**********************************************************************
3115  *********************************************************************/
3116
3117 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3118 {
3119         ldapsam_endsampwent(my_methods);
3120 }
3121
3122 /**********************************************************************
3123  *********************************************************************/
3124
3125 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3126                                     GROUP_MAP *map)
3127 {
3128         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3129         struct ldapsam_privates *ldap_state =
3130                 (struct ldapsam_privates *)my_methods->private_data;
3131         BOOL bret = False;
3132
3133         while (!bret) {
3134                 if (!ldap_state->entry)
3135                         return ret;
3136                 
3137                 ldap_state->index++;
3138                 bret = init_group_from_ldap(ldap_state, map,
3139                                             ldap_state->entry);
3140                 
3141                 ldap_state->entry =
3142                         ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3143                                         ldap_state->entry);     
3144         }
3145
3146         return NT_STATUS_OK;
3147 }
3148
3149 /**********************************************************************
3150  *********************************************************************/
3151
3152 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3153                                            const DOM_SID *domsid, enum lsa_SidType sid_name_use,
3154                                            GROUP_MAP **pp_rmap,
3155                                            size_t *p_num_entries,
3156                                            BOOL unix_only)
3157 {
3158         GROUP_MAP map;
3159         size_t entries = 0;
3160
3161         *p_num_entries = 0;
3162         *pp_rmap = NULL;
3163
3164         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3165                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3166                           "passdb\n"));
3167                 return NT_STATUS_ACCESS_DENIED;
3168         }
3169
3170         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3171                 if (sid_name_use != SID_NAME_UNKNOWN &&
3172                     sid_name_use != map.sid_name_use) {
3173                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3174                                   "not of the requested type\n", map.nt_name));
3175                         continue;
3176                 }
3177                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3178                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3179                                   "non mapped\n", map.nt_name));
3180                         continue;
3181                 }
3182
3183                 (*pp_rmap)=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3184                 if (!(*pp_rmap)) {
3185                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3186                                  "enlarge group map!\n"));
3187                         return NT_STATUS_UNSUCCESSFUL;
3188                 }
3189
3190                 (*pp_rmap)[entries] = map;
3191
3192                 entries += 1;
3193
3194         }
3195         ldapsam_endsamgrent(methods);
3196
3197         *p_num_entries = entries;
3198
3199         return NT_STATUS_OK;
3200 }
3201
3202 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3203                                         const DOM_SID *alias,
3204                                         const DOM_SID *member,
3205                                         int modop)
3206 {
3207         struct ldapsam_privates *ldap_state =
3208                 (struct ldapsam_privates *)methods->private_data;
3209         char *dn;
3210         LDAPMessage *result = NULL;
3211         LDAPMessage *entry = NULL;
3212         int count;
3213         LDAPMod **mods = NULL;
3214         int rc;
3215         enum lsa_SidType type = SID_NAME_USE_NONE;
3216
3217         pstring filter;
3218
3219         if (sid_check_is_in_builtin(alias)) {
3220                 type = SID_NAME_ALIAS;
3221         }
3222
3223         if (sid_check_is_in_our_domain(alias)) {
3224                 type = SID_NAME_ALIAS;
3225         }
3226
3227         if (type == SID_NAME_USE_NONE) {
3228                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3229                           sid_string_static(alias)));
3230                 return NT_STATUS_NO_SUCH_ALIAS;
3231         }
3232
3233         pstr_sprintf(filter,
3234                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3235                      LDAP_OBJ_GROUPMAP, sid_string_static(alias),
3236                      type);
3237
3238         if (ldapsam_search_one_group(ldap_state, filter,
3239                                      &result) != LDAP_SUCCESS)
3240                 return NT_STATUS_NO_SUCH_ALIAS;
3241
3242         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3243                                    result);
3244
3245         if (count < 1) {
3246                 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3247                 ldap_msgfree(result);
3248                 return NT_STATUS_NO_SUCH_ALIAS;
3249         }
3250
3251         if (count > 1) {
3252                 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3253                           "filter %s: count=%d\n", filter, count));
3254                 ldap_msgfree(result);
3255                 return NT_STATUS_NO_SUCH_ALIAS;
3256         }
3257
3258         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3259                                  result);
3260
3261         if (!entry) {
3262                 ldap_msgfree(result);
3263                 return NT_STATUS_UNSUCCESSFUL;
3264         }
3265
3266         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
3267         if (!dn) {
3268                 ldap_msgfree(result);
3269                 return NT_STATUS_UNSUCCESSFUL;
3270         }
3271
3272         smbldap_set_mod(&mods, modop,
3273                         get_attr_key2string(groupmap_attr_list,
3274                                             LDAP_ATTR_SID_LIST),
3275                         sid_string_static(member));
3276
3277         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3278
3279         ldap_mods_free(mods, True);
3280         ldap_msgfree(result);
3281         SAFE_FREE(dn);
3282
3283         if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3284                 return NT_STATUS_MEMBER_IN_ALIAS;
3285         }
3286
3287         if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3288                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3289         }
3290
3291         if (rc != LDAP_SUCCESS) {
3292                 return NT_STATUS_UNSUCCESSFUL;
3293         }
3294
3295         return NT_STATUS_OK;
3296 }
3297
3298 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3299                                      const DOM_SID *alias,
3300                                      const DOM_SID *member)
3301 {
3302         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3303 }
3304
3305 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3306                                      const DOM_SID *alias,
3307                                      const DOM_SID *member)
3308 {
3309         return ldapsam_modify_aliasmem(methods, alias, member,
3310                                        LDAP_MOD_DELETE);
3311 }
3312
3313 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3314                                       const DOM_SID *alias,
3315                                       DOM_SID **pp_members,
3316                                       size_t *p_num_members)
3317 {
3318         struct ldapsam_privates *ldap_state =
3319                 (struct ldapsam_privates *)methods->private_data;
3320         LDAPMessage *result = NULL;
3321         LDAPMessage *entry = NULL;
3322         int count;
3323         char **values;
3324         int i;
3325         pstring filter;
3326         size_t num_members = 0;
3327         enum lsa_SidType type = SID_NAME_USE_NONE;
3328
3329         *pp_members = NULL;
3330         *p_num_members = 0;
3331
3332         if (sid_check_is_in_builtin(alias)) {
3333                 type = SID_NAME_ALIAS;
3334         }
3335
3336         if (sid_check_is_in_our_domain(alias)) {
3337                 type = SID_NAME_ALIAS;
3338         }
3339
3340         if (type == SID_NAME_USE_NONE) {
3341                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3342                           sid_string_static(alias)));
3343                 return NT_STATUS_NO_SUCH_ALIAS;
3344         }
3345
3346         pstr_sprintf(filter,
3347                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3348                      LDAP_OBJ_GROUPMAP, sid_string_static(alias),
3349                      type);
3350
3351         if (ldapsam_search_one_group(ldap_state, filter,
3352                                      &result) != LDAP_SUCCESS)
3353                 return NT_STATUS_NO_SUCH_ALIAS;
3354
3355         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3356                                    result);
3357
3358         if (count < 1) {
3359                 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3360                 ldap_msgfree(result);
3361                 return NT_STATUS_NO_SUCH_ALIAS;
3362         }
3363
3364         if (count > 1) {
3365                 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3366                           "filter %s: count=%d\n", filter, count));
3367                 ldap_msgfree(result);
3368                 return NT_STATUS_NO_SUCH_ALIAS;
3369         }
3370
3371         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3372                                  result);
3373
3374         if (!entry) {
3375                 ldap_msgfree(result);
3376                 return NT_STATUS_UNSUCCESSFUL;
3377         }
3378
3379         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3380                                  entry,
3381                                  get_attr_key2string(groupmap_attr_list,
3382                                                      LDAP_ATTR_SID_LIST));
3383
3384         if (values == NULL) {
3385                 ldap_msgfree(result);
3386                 return NT_STATUS_OK;
3387         }
3388
3389         count = ldap_count_values(values);
3390
3391         for (i=0; i<count; i++) {
3392                 DOM_SID member;
3393
3394                 if (!string_to_sid(&member, values[i]))
3395                         continue;
3396
3397                 if (!add_sid_to_array(NULL, &member, pp_members, &num_members)) {
3398                         ldap_value_free(values);
3399                         ldap_msgfree(result);
3400                         return NT_STATUS_NO_MEMORY;
3401                 }
3402         }
3403
3404         *p_num_members = num_members;
3405         ldap_value_free(values);
3406         ldap_msgfree(result);
3407
3408         return NT_STATUS_OK;
3409 }
3410
3411 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3412                                           TALLOC_CTX *mem_ctx,
3413                                           const DOM_SID *domain_sid,
3414                                           const DOM_SID *members,
3415                                           size_t num_members,
3416                                           uint32 **pp_alias_rids,
3417                                           size_t *p_num_alias_rids)
3418 {
3419         struct ldapsam_privates *ldap_state =
3420                 (struct ldapsam_privates *)methods->private_data;
3421         LDAP *ldap_struct;
3422
3423         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3424
3425         LDAPMessage *result = NULL;
3426         LDAPMessage *entry = NULL;
3427         int i;
3428         int rc;
3429         char *filter;
3430         enum lsa_SidType type = SID_NAME_USE_NONE;
3431
3432         if (sid_check_is_builtin(domain_sid)) {
3433                 type = SID_NAME_ALIAS;
3434         }
3435
3436         if (sid_check_is_domain(domain_sid)) {
3437                 type = SID_NAME_ALIAS;
3438         }
3439
3440         if (type == SID_NAME_USE_NONE) {
3441                 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3442                           sid_string_static(domain_sid)));
3443                 return NT_STATUS_UNSUCCESSFUL;
3444         }
3445
3446         filter = talloc_asprintf(mem_ctx,
3447                                  "(&(|(objectclass=%s)(sambaGroupType=%d))(|",
3448                                  LDAP_OBJ_GROUPMAP, type);
3449
3450         for (i=0; i<num_members; i++)
3451                 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3452                                          filter,
3453                                          sid_string_static(&members[i]));
3454
3455         filter = talloc_asprintf(mem_ctx, "%s))", filter);
3456
3457         if (filter == NULL) {
3458                 return NT_STATUS_NO_MEMORY;
3459         }
3460
3461         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
3462                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3463
3464         if (rc != LDAP_SUCCESS)
3465                 return NT_STATUS_UNSUCCESSFUL;
3466
3467         ldap_struct = ldap_state->smbldap_state->ldap_struct;
3468
3469         for (entry = ldap_first_entry(ldap_struct, result);
3470              entry != NULL;
3471              entry = ldap_next_entry(ldap_struct, entry))
3472         {
3473                 fstring sid_str;
3474                 DOM_SID sid;
3475                 uint32 rid;
3476
3477                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3478                                                   LDAP_ATTRIBUTE_SID,
3479                                                   sid_str,
3480                                                   sizeof(sid_str)-1))
3481                         continue;
3482
3483                 if (!string_to_sid(&sid, sid_str))
3484                         continue;
3485
3486                 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3487                         continue;
3488
3489                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3490                                         p_num_alias_rids)) {
3491                         ldap_msgfree(result);
3492                         return NT_STATUS_NO_MEMORY;
3493                 }
3494         }
3495
3496         ldap_msgfree(result);
3497         return NT_STATUS_OK;
3498 }
3499
3500 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3501                                                    int policy_index,
3502                                                    uint32 value)
3503 {
3504         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3505         int rc;
3506         LDAPMod **mods = NULL;
3507         fstring value_string;
3508         const char *policy_attr = NULL;
3509
3510         struct ldapsam_privates *ldap_state =
3511                 (struct ldapsam_privates *)methods->private_data;
3512
3513         DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3514
3515         if (!ldap_state->domain_dn) {
3516                 return NT_STATUS_INVALID_PARAMETER;
3517         }
3518
3519         policy_attr = get_account_policy_attr(policy_index);
3520         if (policy_attr == NULL) {
3521                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3522                          "policy\n"));
3523                 return ntstatus;
3524         }
3525
3526         slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3527
3528         smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3529
3530         rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3531                             mods);
3532
3533         ldap_mods_free(mods, True);
3534
3535         if (rc != LDAP_SUCCESS) {
3536                 return ntstatus;
3537         }
3538
3539         if (!cache_account_policy_set(policy_index, value)) {
3540                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3541                          "update local tdb cache\n"));
3542                 return ntstatus;
3543         }
3544
3545         return NT_STATUS_OK;
3546 }
3547
3548 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3549                                            int policy_index, uint32 value)
3550 {
3551         return ldapsam_set_account_policy_in_ldap(methods, policy_index,
3552                                                   value);
3553 }
3554
3555 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3556                                                      int policy_index,
3557                                                      uint32 *value)
3558 {
3559         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3560         LDAPMessage *result = NULL;
3561         LDAPMessage *entry = NULL;
3562         int count;
3563         int rc;
3564         char **vals = NULL;
3565         const char *policy_attr = NULL;
3566
3567         struct ldapsam_privates *ldap_state =
3568                 (struct ldapsam_privates *)methods->private_data;
3569
3570         const char *attrs[2];
3571
3572         DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3573
3574         if (!ldap_state->domain_dn) {
3575                 return NT_STATUS_INVALID_PARAMETER;
3576         }
3577
3578         policy_attr = get_account_policy_attr(policy_index);
3579         if (!policy_attr) {
3580                 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3581                          "policy index: %d\n", policy_index));
3582                 return ntstatus;
3583         }
3584
3585         attrs[0] = policy_attr;
3586         attrs[1] = NULL;
3587
3588         rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3589                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0,
3590                             &result);
3591
3592         if (rc != LDAP_SUCCESS) {
3593                 return ntstatus;
3594         }
3595
3596         count = ldap_count_entries(priv2ld(ldap_state), result);
3597         if (count < 1) {
3598                 goto out;
3599         }
3600
3601         entry = ldap_first_entry(priv2ld(ldap_state), result);
3602         if (entry == NULL) {
3603                 goto out;
3604         }
3605
3606         vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3607         if (vals == NULL) {
3608                 goto out;
3609         }
3610
3611         *value = (uint32)atol(vals[0]);
3612         
3613         ntstatus = NT_STATUS_OK;
3614
3615 out:
3616         if (vals)
3617                 ldap_value_free(vals);
3618         ldap_msgfree(result);
3619
3620         return ntstatus;
3621 }
3622
3623 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache 
3624
3625    - if user hasn't decided to use account policies inside LDAP just reuse the
3626      old tdb values
3627    
3628    - if there is a valid cache entry, return that
3629    - if there is an LDAP entry, update cache and return 
3630    - otherwise set to default, update cache and return
3631
3632    Guenther
3633 */
3634 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3635                                            int policy_index, uint32 *value)
3636 {
3637         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3638
3639         if (cache_account_policy_get(policy_index, value)) {
3640                 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3641                           "cache\n"));
3642                 return NT_STATUS_OK;
3643         }
3644
3645         ntstatus = ldapsam_get_account_policy_from_ldap(methods, policy_index,
3646                                                         value);
3647         if (NT_STATUS_IS_OK(ntstatus)) {
3648                 goto update_cache;
3649         }
3650
3651         DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3652                   "ldap\n"));
3653
3654 #if 0
3655         /* should we automagically migrate old tdb value here ? */
3656         if (account_policy_get(policy_index, value))
3657                 goto update_ldap;
3658
3659         DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3660                   "default\n", policy_index));
3661 #endif
3662
3663         if (!account_policy_get_default(policy_index, value)) {
3664                 return ntstatus;
3665         }
3666         
3667 /* update_ldap: */
3668  
3669         ntstatus = ldapsam_set_account_policy(methods, policy_index, *value);
3670         if (!NT_STATUS_IS_OK(ntstatus)) {
3671                 return ntstatus;
3672         }
3673                 
3674  update_cache:
3675  
3676         if (!cache_account_policy_set(policy_index, *value)) {
3677                 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3678                          "tdb as a cache\n"));
3679                 return NT_STATUS_UNSUCCESSFUL;
3680         }
3681
3682         return NT_STATUS_OK;
3683 }
3684
3685 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3686                                     const DOM_SID *domain_sid,
3687                                     int num_rids,
3688                                     uint32 *rids,
3689                                     const char **names,
3690                                     enum lsa_SidType *attrs)
3691 {
3692         struct ldapsam_privates *ldap_state =
3693                 (struct ldapsam_privates *)methods->private_data;
3694         LDAPMessage *msg = NULL;
3695         LDAPMessage *entry;
3696         char *allsids = NULL;
3697         int i, rc, num_mapped;
3698         NTSTATUS result = NT_STATUS_NO_MEMORY;
3699         TALLOC_CTX *mem_ctx;
3700         LDAP *ld;
3701         BOOL is_builtin;
3702
3703         mem_ctx = talloc_new(NULL);
3704         if (mem_ctx == NULL) {
3705                 DEBUG(0, ("talloc_new failed\n"));
3706                 goto done;
3707         }
3708
3709         if (!sid_check_is_builtin(domain_sid) &&
3710             !sid_check_is_domain(domain_sid)) {
3711                 result = NT_STATUS_INVALID_PARAMETER;
3712                 goto done;
3713         }
3714
3715         for (i=0; i<num_rids; i++)
3716                 attrs[i] = SID_NAME_UNKNOWN;
3717
3718         allsids = talloc_strdup(mem_ctx, "");
3719         if (allsids == NULL) {
3720                 goto done;
3721         }
3722
3723         for (i=0; i<num_rids; i++) {
3724                 DOM_SID sid;
3725                 sid_compose(&sid, domain_sid, rids[i]);
3726                 allsids = talloc_asprintf_append(allsids, "(sambaSid=%s)",
3727                                                  sid_string_static(&sid));
3728                 if (allsids == NULL) {
3729                         goto done;
3730                 }
3731         }
3732
3733         /* First look for users */
3734
3735         {
3736                 char *filter;
3737                 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
3738
3739                 filter = talloc_asprintf(
3740                         mem_ctx, ("(&(objectClass=%s)(|%s))"),
3741                         LDAP_OBJ_SAMBASAMACCOUNT, allsids);
3742
3743                 if (filter == NULL) {
3744                         goto done;
3745                 }
3746
3747                 rc = smbldap_search(ldap_state->smbldap_state,
3748                                     lp_ldap_user_suffix(),
3749                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3750                                     &msg);
3751                 talloc_autofree_ldapmsg(mem_ctx, msg);
3752         }
3753
3754         if (rc != LDAP_SUCCESS)
3755                 goto done;
3756
3757         ld = ldap_state->smbldap_state->ldap_struct;
3758         num_mapped = 0;
3759
3760         for (entry = ldap_first_entry(ld, msg);
3761              entry != NULL;
3762              entry = ldap_next_entry(ld, entry)) {
3763                 uint32 rid;
3764                 int rid_index;
3765                 const char *name;
3766
3767                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
3768                                                     &rid)) {
3769                         DEBUG(2, ("Could not find sid from ldap entry\n"));
3770                         continue;
3771                 }
3772
3773                 name = smbldap_talloc_single_attribute(ld, entry, "uid",
3774                                                        names);
3775                 if (name == NULL) {
3776                         DEBUG(2, ("Could not retrieve uid attribute\n"));
3777                         continue;
3778                 }
3779
3780                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3781                         if (rid == rids[rid_index])
3782                                 break;
3783                 }
3784
3785                 if (rid_index == num_rids) {
3786                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3787                         continue;
3788                 }
3789
3790                 attrs[rid_index] = SID_NAME_USER;
3791                 names[rid_index] = name;
3792                 num_mapped += 1;
3793         }
3794
3795         if (num_mapped == num_rids) {
3796                 /* No need to look for groups anymore -- we're done */
3797                 result = NT_STATUS_OK;
3798                 goto done;
3799         }
3800
3801         /* Same game for groups */
3802
3803         {
3804                 char *filter;
3805                 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
3806                                              "sambaGroupType", NULL };
3807
3808                 filter = talloc_asprintf(
3809                         mem_ctx, "(&(objectClass=%s)(|%s))",
3810                         LDAP_OBJ_GROUPMAP, allsids);
3811                 if (filter == NULL) {
3812                         goto done;
3813                 }
3814
3815                 rc = smbldap_search(ldap_state->smbldap_state,
3816                                     lp_ldap_group_suffix(),
3817                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
3818                                     &msg);
3819                 talloc_autofree_ldapmsg(mem_ctx, msg);
3820         }
3821
3822         if (rc != LDAP_SUCCESS)
3823                 goto done;
3824
3825         /* ldap_struct might have changed due to a reconnect */
3826
3827         ld = ldap_state->smbldap_state->ldap_struct;
3828
3829         /* For consistency checks, we already checked we're only domain or builtin */
3830
3831         is_builtin = sid_check_is_builtin(domain_sid);
3832
3833         for (entry = ldap_first_entry(ld, msg);
3834              entry != NULL;
3835              entry = ldap_next_entry(ld, entry))
3836         {
3837                 uint32 rid;
3838                 int rid_index;
3839                 const char *attr;
3840                 enum lsa_SidType type;
3841                 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
3842
3843                 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
3844                                                        mem_ctx);
3845                 if (attr == NULL) {
3846                         DEBUG(2, ("Could not extract type from ldap entry %s\n",
3847                                   dn));
3848                         continue;
3849                 }
3850
3851                 type = (enum lsa_SidType)atol(attr);
3852
3853                 /* Consistency checks */
3854                 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
3855                     (!is_builtin && ((type != SID_NAME_ALIAS) &&
3856                                      (type != SID_NAME_DOM_GRP)))) {
3857                         DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
3858                 }
3859
3860                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
3861                                                     &rid)) {
3862                         DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
3863                         continue;
3864                 }
3865
3866                 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
3867
3868                 if (attr == NULL) {
3869                         DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
3870                                    dn));
3871                         attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
3872                 }
3873
3874                 if (attr == NULL) {
3875                         DEBUG(2, ("Could not retrieve naming attribute from %s\n",
3876                                   dn));
3877                         continue;
3878                 }
3879
3880                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
3881                         if (rid == rids[rid_index])
3882                                 break;
3883                 }
3884
3885                 if (rid_index == num_rids) {
3886                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
3887                         continue;
3888                 }
3889
3890                 attrs[rid_index] = type;
3891                 names[rid_index] = attr;
3892                 num_mapped += 1;
3893         }
3894
3895         result = NT_STATUS_NONE_MAPPED;
3896
3897         if (num_mapped > 0)
3898                 result = (num_mapped == num_rids) ?
3899                         NT_STATUS_OK : STATUS_SOME_UNMAPPED;
3900  done:
3901         TALLOC_FREE(mem_ctx);
3902         return result;
3903 }
3904
3905 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
3906 {
3907         char *filter = NULL;
3908         char *escaped = NULL;
3909         char *result = NULL;
3910
3911         asprintf(&filter, "(&%s(objectclass=sambaSamAccount))",
3912                  "(uid=%u)");
3913         if (filter == NULL) goto done;
3914
3915         escaped = escape_ldap_string_alloc(username);
3916         if (escaped == NULL) goto done;
3917
3918         result = talloc_string_sub(mem_ctx, filter, "%u", username);
3919
3920  done:
3921         SAFE_FREE(filter);
3922         SAFE_FREE(escaped);
3923
3924         return result;
3925 }
3926
3927 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
3928 {
3929         int i, num = 0;
3930         va_list ap;
3931         const char **result;
3932
3933         va_start(ap, mem_ctx);
3934         while (va_arg(ap, const char *) != NULL)
3935                 num += 1;
3936         va_end(ap);
3937
3938         if ((result = TALLOC_ARRAY(mem_ctx, const char *, num+1)) == NULL) {
3939                 return NULL;
3940         }
3941
3942         va_start(ap, mem_ctx);
3943         for (i=0; i<num; i++) {
3944                 result[i] = talloc_strdup(result, va_arg(ap, const char*));
3945                 if (result[i] == NULL) {
3946                         talloc_free(result);
3947                         return NULL;
3948                 }
3949         }
3950         va_end(ap);
3951
3952         result[num] = NULL;
3953         return result;
3954 }
3955
3956 struct ldap_search_state {
3957         struct smbldap_state *connection;
3958
3959         uint32 acct_flags;
3960         uint16 group_type;
3961
3962         const char *base;
3963         int scope;
3964         const char *filter;
3965         const char **attrs;
3966         int attrsonly;
3967         void *pagedresults_cookie;
3968
3969         LDAPMessage *entries, *current_entry;
3970         BOOL (*ldap2displayentry)(struct ldap_search_state *state,
3971                                   TALLOC_CTX *mem_ctx,
3972                                   LDAP *ld, LDAPMessage *entry,
3973                                   struct samr_displayentry *result);
3974 };
3975
3976 static BOOL ldapsam_search_firstpage(struct pdb_search *search)
3977 {
3978         struct ldap_search_state *state =
3979                 (struct ldap_search_state *)search->private_data;
3980         LDAP *ld;
3981         int rc = LDAP_OPERATIONS_ERROR;
3982
3983         state->entries = NULL;
3984
3985         if (state->connection->paged_results) {
3986                 rc = smbldap_search_paged(state->connection, state->base,
3987                                           state->scope, state->filter,
3988                                           state->attrs, state->attrsonly,
3989                                           lp_ldap_page_size(), &state->entries,
3990                                           &state->pagedresults_cookie);
3991         }
3992
3993         if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
3994
3995                 if (state->entries != NULL) {
3996                         /* Left over from unsuccessful paged attempt */
3997                         ldap_msgfree(state->entries);
3998                         state->entries = NULL;
3999                 }
4000
4001                 rc = smbldap_search(state->connection, state->base,
4002                                     state->scope, state->filter, state->attrs,
4003                                     state->attrsonly, &state->entries);
4004
4005                 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4006                         return False;
4007
4008                 /* Ok, the server was lying. It told us it could do paged
4009                  * searches when it could not. */
4010                 state->connection->paged_results = False;
4011         }
4012
4013         ld = state->connection->ldap_struct;
4014         if ( ld == NULL) {
4015                 DEBUG(5, ("Don't have an LDAP connection right after a "
4016                           "search\n"));
4017                 return False;
4018         }
4019         state->current_entry = ldap_first_entry(ld, state->entries);
4020
4021         if (state->current_entry == NULL) {
4022                 ldap_msgfree(state->entries);
4023                 state->entries = NULL;
4024         }
4025
4026         return True;
4027 }
4028
4029 static BOOL ldapsam_search_nextpage(struct pdb_search *search)
4030 {
4031         struct ldap_search_state *state =
4032                 (struct ldap_search_state *)search->private_data;
4033         int rc;
4034
4035         if (!state->connection->paged_results) {
4036                 /* There is no next page when there are no paged results */
4037                 return False;
4038         }
4039
4040         rc = smbldap_search_paged(state->connection, state->base,
4041                                   state->scope, state->filter, state->attrs,
4042                                   state->attrsonly, lp_ldap_page_size(),
4043                                   &state->entries,
4044                                   &state->pagedresults_cookie);
4045
4046         if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4047                 return False;
4048
4049         state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4050
4051         if (state->current_entry == NULL) {
4052                 ldap_msgfree(state->entries);
4053                 state->entries = NULL;
4054         }
4055
4056         return True;
4057 }
4058
4059 static BOOL ldapsam_search_next_entry(struct pdb_search *search,
4060                                       struct samr_displayentry *entry)
4061 {
4062         struct ldap_search_state *state =
4063                 (struct ldap_search_state *)search->private_data;
4064         BOOL result;
4065
4066  retry:
4067         if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4068                 return False;
4069
4070         if ((state->entries == NULL) &&
4071             !ldapsam_search_nextpage(search))
4072                     return False;
4073
4074         result = state->ldap2displayentry(state, search->mem_ctx, state->connection->ldap_struct,
4075                                           state->current_entry, entry);
4076
4077         if (!result) {
4078                 char *dn;
4079                 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4080                 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4081                 if (dn != NULL) ldap_memfree(dn);
4082         }
4083
4084         state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4085
4086         if (state->current_entry == NULL) {
4087                 ldap_msgfree(state->entries);
4088                 state->entries = NULL;
4089         }
4090
4091         if (!result) goto retry;
4092
4093         return True;
4094 }
4095
4096 static void ldapsam_search_end(struct pdb_search *search)
4097 {
4098         struct ldap_search_state *state =
4099                 (struct ldap_search_state *)search->private_data;
4100         int rc;
4101
4102         if (state->pagedresults_cookie == NULL)
4103                 return;
4104
4105         if (state->entries != NULL)
4106                 ldap_msgfree(state->entries);
4107
4108         state->entries = NULL;
4109         state->current_entry = NULL;
4110
4111         if (!state->connection->paged_results)
4112                 return;
4113
4114         /* Tell the LDAP server we're not interested in the rest anymore. */
4115
4116         rc = smbldap_search_paged(state->connection, state->base, state->scope,
4117                                   state->filter, state->attrs,
4118                                   state->attrsonly, 0, &state->entries,
4119                                   &state->pagedresults_cookie);
4120
4121         if (rc != LDAP_SUCCESS)
4122                 DEBUG(5, ("Could not end search properly\n"));
4123
4124         return;
4125 }
4126
4127 static BOOL ldapuser2displayentry(struct ldap_search_state *state,
4128                                   TALLOC_CTX *mem_ctx,
4129                                   LDAP *ld, LDAPMessage *entry,
4130                                   struct samr_displayentry *result)
4131 {
4132         char **vals;
4133         DOM_SID sid;
4134         uint32 acct_flags;
4135
4136         vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4137         if ((vals == NULL) || (vals[0] == NULL)) {
4138                 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4139                 return False;
4140         }
4141         acct_flags = pdb_decode_acct_ctrl(vals[0]);
4142         ldap_value_free(vals);
4143
4144         if ((state->acct_flags != 0) &&
4145             ((state->acct_flags & acct_flags) == 0))
4146                 return False;           
4147
4148         result->acct_flags = acct_flags;
4149         result->account_name = "";
4150         result->fullname = "";
4151         result->description = "";
4152
4153         vals = ldap_get_values(ld, entry, "uid");
4154         if ((vals == NULL) || (vals[0] == NULL)) {
4155                 DEBUG(5, ("\"uid\" not found\n"));
4156                 return False;
4157         }
4158         pull_utf8_talloc(mem_ctx,
4159                          CONST_DISCARD(char **, &result->account_name),
4160                          vals[0]);
4161         ldap_value_free(vals);
4162
4163         vals = ldap_get_values(ld, entry, "displayName");
4164         if ((vals == NULL) || (vals[0] == NULL))
4165                 DEBUG(8, ("\"displayName\" not found\n"));
4166         else
4167                 pull_utf8_talloc(mem_ctx,
4168                                  CONST_DISCARD(char **, &result->fullname),
4169                                  vals[0]);
4170         ldap_value_free(vals);
4171
4172         vals = ldap_get_values(ld, entry, "description");
4173         if ((vals == NULL) || (vals[0] == NULL))
4174                 DEBUG(8, ("\"description\" not found\n"));
4175         else
4176                 pull_utf8_talloc(mem_ctx,
4177                                  CONST_DISCARD(char **, &result->description),
4178                                  vals[0]);
4179         ldap_value_free(vals);
4180
4181         if ((result->account_name == NULL) ||
4182             (result->fullname == NULL) ||
4183             (result->description == NULL)) {
4184                 DEBUG(0, ("talloc failed\n"));
4185                 return False;
4186         }
4187         
4188         vals = ldap_get_values(ld, entry, "sambaSid");
4189         if ((vals == NULL) || (vals[0] == NULL)) {
4190                 DEBUG(0, ("\"objectSid\" not found\n"));
4191                 return False;
4192         }
4193
4194         if (!string_to_sid(&sid, vals[0])) {
4195                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4196                 ldap_value_free(vals);
4197                 return False;
4198         }
4199         ldap_value_free(vals);
4200
4201         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4202                 DEBUG(0, ("sid %s does not belong to our domain\n",
4203                           sid_string_static(&sid)));
4204                 return False;
4205         }
4206
4207         return True;
4208 }
4209
4210
4211 static BOOL ldapsam_search_users(struct pdb_methods *methods,
4212                                  struct pdb_search *search,
4213                                  uint32 acct_flags)
4214 {
4215         struct ldapsam_privates *ldap_state =
4216                 (struct ldapsam_privates *)methods->private_data;
4217         struct ldap_search_state *state;
4218
4219         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4220         if (state == NULL) {
4221                 DEBUG(0, ("talloc failed\n"));
4222                 return False;
4223         }
4224
4225         state->connection = ldap_state->smbldap_state;
4226
4227         if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4228                 state->base = lp_ldap_user_suffix();
4229         else if ((acct_flags != 0) &&
4230                  ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4231                 state->base = lp_ldap_machine_suffix();
4232         else
4233                 state->base = lp_ldap_suffix();
4234
4235         state->acct_flags = acct_flags;
4236         state->base = talloc_strdup(search->mem_ctx, state->base);
4237         state->scope = LDAP_SCOPE_SUBTREE;
4238         state->filter = get_ldap_filter(search->mem_ctx, "*");
4239         state->attrs = talloc_attrs(search->mem_ctx, "uid", "sambaSid",
4240                                     "displayName", "description",
4241                                     "sambaAcctFlags", NULL);
4242         state->attrsonly = 0;
4243         state->pagedresults_cookie = NULL;
4244         state->entries = NULL;
4245         state->ldap2displayentry = ldapuser2displayentry;
4246
4247         if ((state->filter == NULL) || (state->attrs == NULL)) {
4248                 DEBUG(0, ("talloc failed\n"));
4249                 return False;
4250         }
4251
4252         search->private_data = state;
4253         search->next_entry = ldapsam_search_next_entry;
4254         search->search_end = ldapsam_search_end;
4255
4256         return ldapsam_search_firstpage(search);
4257 }
4258
4259 static BOOL ldapgroup2displayentry(struct ldap_search_state *state,
4260                                    TALLOC_CTX *mem_ctx,
4261                                    LDAP *ld, LDAPMessage *entry,
4262                                    struct samr_displayentry *result)
4263 {
4264         char **vals;
4265         DOM_SID sid;
4266         uint16 group_type;
4267
4268         result->account_name = "";
4269         result->fullname = "";
4270         result->description = "";
4271
4272
4273         vals = ldap_get_values(ld, entry, "sambaGroupType");
4274         if ((vals == NULL) || (vals[0] == NULL)) {
4275                 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4276                 if (vals != NULL) {
4277                         ldap_value_free(vals);
4278                 }
4279                 return False;
4280         }
4281
4282         group_type = atoi(vals[0]);
4283
4284         if ((state->group_type != 0) &&
4285             ((state->group_type != group_type))) {
4286                 ldap_value_free(vals);
4287                 return False;
4288         }
4289
4290         ldap_value_free(vals);
4291
4292         /* display name is the NT group name */
4293
4294         vals = ldap_get_values(ld, entry, "displayName");
4295         if ((vals == NULL) || (vals[0] == NULL)) {
4296                 DEBUG(8, ("\"displayName\" not found\n"));
4297
4298                 /* fallback to the 'cn' attribute */
4299                 vals = ldap_get_values(ld, entry, "cn");
4300                 if ((vals == NULL) || (vals[0] == NULL)) {
4301                         DEBUG(5, ("\"cn\" not found\n"));
4302                         return False;
4303                 }
4304                 pull_utf8_talloc(mem_ctx,
4305                                  CONST_DISCARD(char **, &result->account_name),
4306                                  vals[0]);
4307         }
4308         else {
4309                 pull_utf8_talloc(mem_ctx,
4310                                  CONST_DISCARD(char **, &result->account_name),
4311                                  vals[0]);
4312         }
4313
4314         ldap_value_free(vals);
4315
4316         vals = ldap_get_values(ld, entry, "description");
4317         if ((vals == NULL) || (vals[0] == NULL))
4318                 DEBUG(8, ("\"description\" not found\n"));
4319         else
4320                 pull_utf8_talloc(mem_ctx,
4321                                  CONST_DISCARD(char **, &result->description),
4322                                  vals[0]);
4323         ldap_value_free(vals);
4324
4325         if ((result->account_name == NULL) ||
4326             (result->fullname == NULL) ||
4327             (result->description == NULL)) {
4328                 DEBUG(0, ("talloc failed\n"));
4329                 return False;
4330         }
4331         
4332         vals = ldap_get_values(ld, entry, "sambaSid");
4333         if ((vals == NULL) || (vals[0] == NULL)) {
4334                 DEBUG(0, ("\"objectSid\" not found\n"));
4335                 if (vals != NULL) {
4336                         ldap_value_free(vals);
4337                 }
4338                 return False;
4339         }
4340
4341         if (!string_to_sid(&sid, vals[0])) {
4342                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4343                 return False;
4344         }
4345
4346         ldap_value_free(vals);
4347
4348         switch (group_type) {
4349                 case SID_NAME_DOM_GRP:
4350                 case SID_NAME_ALIAS:
4351
4352                         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid) 
4353                                 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid)) 
4354                         {
4355                                 DEBUG(0, ("%s is not in our domain\n",
4356                                           sid_string_static(&sid)));
4357                                 return False;
4358                         }
4359                         break;
4360         
4361                 default:
4362                         DEBUG(0,("unkown group type: %d\n", group_type));
4363                         return False;
4364         }
4365         
4366         return True;
4367 }
4368
4369 static BOOL ldapsam_search_grouptype(struct pdb_methods *methods,
4370                                      struct pdb_search *search,
4371                                      const DOM_SID *sid,
4372                                      enum lsa_SidType type)
4373 {
4374         struct ldapsam_privates *ldap_state =
4375                 (struct ldapsam_privates *)methods->private_data;
4376         struct ldap_search_state *state;
4377
4378         state = TALLOC_P(search->mem_ctx, struct ldap_search_state);
4379         if (state == NULL) {
4380                 DEBUG(0, ("talloc failed\n"));
4381                 return False;
4382         }
4383
4384         state->connection = ldap_state->smbldap_state;
4385
4386         state->base = talloc_strdup(search->mem_ctx, lp_ldap_group_suffix());
4387         state->connection = ldap_state->smbldap_state;
4388         state->scope = LDAP_SCOPE_SUBTREE;
4389         state->filter = talloc_asprintf(search->mem_ctx,
4390                                         "(&(objectclass=sambaGroupMapping)"
4391                                         "(sambaGroupType=%d)(sambaSID=%s*))", 
4392                                         type, sid_string_static(sid));
4393         state->attrs = talloc_attrs(search->mem_ctx, "cn", "sambaSid",
4394                                     "displayName", "description",
4395                                     "sambaGroupType", NULL);
4396         state->attrsonly = 0;
4397         state->pagedresults_cookie = NULL;
4398         state->entries = NULL;
4399         state->group_type = type;
4400         state->ldap2displayentry = ldapgroup2displayentry;
4401
4402         if ((state->filter == NULL) || (state->attrs == NULL)) {
4403                 DEBUG(0, ("talloc failed\n"));
4404                 return False;
4405         }
4406
4407         search->private_data = state;
4408         search->next_entry = ldapsam_search_next_entry;
4409         search->search_end = ldapsam_search_end;
4410
4411         return ldapsam_search_firstpage(search);
4412 }
4413
4414 static BOOL ldapsam_search_groups(struct pdb_methods *methods,
4415                                   struct pdb_search *search)
4416 {
4417         return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4418 }
4419
4420 static BOOL ldapsam_search_aliases(struct pdb_methods *methods,
4421                                    struct pdb_search *search,
4422                                    const DOM_SID *sid)
4423 {
4424         return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4425 }
4426
4427 static BOOL ldapsam_rid_algorithm(struct pdb_methods *methods)
4428 {
4429         return False;
4430 }
4431
4432 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4433                                     uint32 *rid)
4434 {
4435         struct smbldap_state *smbldap_state = priv->smbldap_state;
4436
4437         LDAPMessage *result = NULL;
4438         LDAPMessage *entry = NULL;
4439         LDAPMod **mods = NULL;
4440         NTSTATUS status;
4441         char *value;
4442         int rc;
4443         uint32 nextRid = 0;
4444         const char *dn;
4445
4446         TALLOC_CTX *mem_ctx;
4447
4448         mem_ctx = talloc_new(NULL);
4449         if (mem_ctx == NULL) {
4450                 DEBUG(0, ("talloc_new failed\n"));
4451                 return NT_STATUS_NO_MEMORY;
4452         }
4453
4454         status = smbldap_search_domain_info(smbldap_state, &result,
4455                                             get_global_sam_name(), False);
4456         if (!NT_STATUS_IS_OK(status)) {
4457                 DEBUG(3, ("Could not get domain info: %s\n",
4458                           nt_errstr(status)));
4459                 goto done;
4460         }
4461
4462         talloc_autofree_ldapmsg(mem_ctx, result);
4463
4464         entry = ldap_first_entry(priv2ld(priv), result);
4465         if (entry == NULL) {
4466                 DEBUG(0, ("Could not get domain info entry\n"));
4467                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4468                 goto done;
4469         }
4470
4471         /* Find the largest of the three attributes "sambaNextRid",
4472            "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4473            concept of differentiating between user and group rids, and will
4474            use only "sambaNextRid" in the future. But for compatibility
4475            reasons I look if others have chosen different strategies -- VL */
4476
4477         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4478                                                 "sambaNextRid", mem_ctx);
4479         if (value != NULL) {
4480                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4481                 nextRid = MAX(nextRid, tmp);
4482         }
4483
4484         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4485                                                 "sambaNextUserRid", mem_ctx);
4486         if (value != NULL) {
4487                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4488                 nextRid = MAX(nextRid, tmp);
4489         }
4490
4491         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4492                                                 "sambaNextGroupRid", mem_ctx);
4493         if (value != NULL) {
4494                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4495                 nextRid = MAX(nextRid, tmp);
4496         }
4497
4498         if (nextRid == 0) {
4499                 nextRid = BASE_RID-1;
4500         }
4501
4502         nextRid += 1;
4503
4504         smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4505                          talloc_asprintf(mem_ctx, "%d", nextRid));
4506         talloc_autofree_ldapmod(mem_ctx, mods);
4507
4508         if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4509                 status = NT_STATUS_NO_MEMORY;
4510                 goto done;
4511         }
4512
4513         rc = smbldap_modify(smbldap_state, dn, mods);
4514
4515         /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4516          * please retry" */
4517
4518         status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4519
4520  done:
4521         if (NT_STATUS_IS_OK(status)) {
4522                 *rid = nextRid;
4523         }
4524
4525         TALLOC_FREE(mem_ctx);
4526         return status;
4527 }
4528
4529 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32 *rid)
4530 {
4531         int i;
4532
4533         for (i=0; i<10; i++) {
4534                 NTSTATUS result = ldapsam_get_new_rid(
4535                         (struct ldapsam_privates *)methods->private_data, rid);
4536                 if (NT_STATUS_IS_OK(result)) {
4537                         return result;
4538                 }
4539
4540                 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4541                         return result;
4542                 }
4543
4544                 /* The ldap update failed (maybe a race condition), retry */
4545         }
4546
4547         /* Tried 10 times, fail. */
4548         return NT_STATUS_ACCESS_DENIED;
4549 }
4550
4551 static BOOL ldapsam_new_rid(struct pdb_methods *methods, uint32 *rid)
4552 {
4553         NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4554         return NT_STATUS_IS_OK(result) ? True : False;
4555 }
4556
4557 static BOOL ldapsam_sid_to_id(struct pdb_methods *methods,
4558                               const DOM_SID *sid,
4559                               union unid_t *id, enum lsa_SidType *type)
4560 {
4561         struct ldapsam_privates *priv =
4562                 (struct ldapsam_privates *)methods->private_data;
4563         char *filter;
4564         const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4565                                 NULL };
4566         LDAPMessage *result = NULL;
4567         LDAPMessage *entry = NULL;
4568         BOOL ret = False;
4569         char *value;
4570         int rc;
4571
4572         TALLOC_CTX *mem_ctx;
4573
4574         mem_ctx = talloc_new(NULL);
4575         if (mem_ctx == NULL) {
4576                 DEBUG(0, ("talloc_new failed\n"));
4577                 return False;
4578         }
4579
4580         filter = talloc_asprintf(mem_ctx,
4581                                  "(&(sambaSid=%s)"
4582                                  "(|(objectClass=%s)(objectClass=%s)))",
4583                                  sid_string_static(sid),
4584                                  LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4585         if (filter == NULL) {
4586                 DEBUG(5, ("talloc_asprintf failed\n"));
4587                 goto done;
4588         }
4589
4590         rc = smbldap_search_suffix(priv->smbldap_state, filter,
4591                                    attrs, &result);
4592         if (rc != LDAP_SUCCESS) {
4593                 goto done;
4594         }
4595         talloc_autofree_ldapmsg(mem_ctx, result);
4596
4597         if (ldap_count_entries(priv2ld(priv), result) != 1) {
4598                 DEBUG(10, ("Got %d entries, expected one\n",
4599                            ldap_count_entries(priv2ld(priv), result)));
4600                 goto done;
4601         }
4602
4603         entry = ldap_first_entry(priv2ld(priv), result);
4604
4605         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4606                                                 "sambaGroupType", mem_ctx);
4607
4608         if (value != NULL) {
4609                 const char *gid_str;
4610                 /* It's a group */
4611
4612                 gid_str = smbldap_talloc_single_attribute(
4613                         priv2ld(priv), entry, "gidNumber", mem_ctx);
4614                 if (gid_str == NULL) {
4615                         DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4616                                   smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4617                                                     entry)));
4618                         goto done;
4619                 }
4620
4621                 id->gid = strtoul(gid_str, NULL, 10);
4622                 *type = (enum lsa_SidType)strtoul(value, NULL, 10);
4623                 ret = True;
4624                 goto done;
4625         }
4626
4627         /* It must be a user */
4628
4629         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4630                                                 "uidNumber", mem_ctx);
4631         if (value == NULL) {
4632                 DEBUG(1, ("Could not find uidNumber in %s\n",
4633                           smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4634                 goto done;
4635         }
4636
4637         id->uid = strtoul(value, NULL, 10);
4638         *type = SID_NAME_USER;
4639
4640         ret = True;
4641  done:
4642         TALLOC_FREE(mem_ctx);
4643         return ret;
4644 }
4645
4646 /*
4647  * The following functions is called only if
4648  * ldapsam:trusted and ldapsam:editposix are
4649  * set to true
4650  */
4651
4652 /*
4653  * ldapsam_create_user creates a new
4654  * posixAccount and sambaSamAccount object
4655  * in the ldap users subtree
4656  *
4657  * The uid is allocated by winbindd.
4658  */
4659
4660 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
4661                                     TALLOC_CTX *tmp_ctx, const char *name,
4662                                     uint32 acb_info, uint32 *rid)
4663 {
4664         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
4665         LDAPMessage *entry = NULL;
4666         LDAPMessage *result = NULL;
4667         uint32 num_result;
4668         BOOL is_machine = False;
4669         BOOL add_posix = False;
4670         LDAPMod **mods = NULL;
4671         struct samu *user;
4672         char *filter;
4673         char *username;
4674         char *homedir;
4675         char *gidstr;
4676         char *uidstr;
4677         char *shell;
4678         const char *dn = NULL;
4679         DOM_SID group_sid;
4680         DOM_SID user_sid;
4681         gid_t gid = -1;
4682         uid_t uid = -1;
4683         NTSTATUS ret;
4684         int rc;
4685         
4686         if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
4687               acb_info & ACB_WSTRUST ||
4688               acb_info & ACB_SVRTRUST ||
4689               acb_info & ACB_DOMTRUST) {
4690                 is_machine = True;
4691         }
4692
4693         username = escape_ldap_string_alloc(name);
4694         filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
4695                                  username, LDAP_OBJ_POSIXACCOUNT);
4696         SAFE_FREE(username);
4697
4698         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
4699         if (rc != LDAP_SUCCESS) {
4700                 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
4701                 return NT_STATUS_UNSUCCESSFUL;
4702         }
4703         talloc_autofree_ldapmsg(tmp_ctx, result);
4704
4705         num_result = ldap_count_entries(priv2ld(ldap_state), result);
4706
4707         if (num_result > 1) {
4708                 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
4709                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
4710         }
4711         
4712         if (num_result == 1) {
4713                 char *tmp;
4714                 /* check if it is just a posix account.
4715                  * or if there is a sid attached to this entry
4716                  */
4717
4718                 entry = ldap_first_entry(priv2ld(ldap_state), result);
4719                 if (!entry) {
4720                         return NT_STATUS_UNSUCCESSFUL;
4721                 }
4722
4723                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
4724                 if (tmp) {
4725                         DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
4726                         return NT_STATUS_USER_EXISTS;
4727                 }
4728
4729                 /* it is just a posix account, retrieve the dn for later use */
4730                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
4731                 if (!dn) {
4732                         DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
4733                         return NT_STATUS_NO_MEMORY;
4734                 }
4735         }
4736
4737         if (num_result == 0) {
4738                 add_posix = True;
4739         }
4740         
4741         /* Create the basic samu structure and generate the mods for the ldap commit */
4742         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
4743                 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
4744                 return ret;
4745         }
4746
4747         sid_compose(&user_sid, get_global_sam_sid(), *rid);
4748
4749         user = samu_new(tmp_ctx);
4750         if (!user) {
4751                 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
4752                 return NT_STATUS_NO_MEMORY;
4753         }
4754
4755         if (!pdb_set_username(user, name, PDB_SET)) {
4756                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
4757                 return NT_STATUS_UNSUCCESSFUL;
4758         }
4759         if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
4760                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
4761                 return NT_STATUS_UNSUCCESSFUL;
4762         }
4763         if (is_machine) {
4764                 if (acb_info & ACB_NORMAL) {
4765                         if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
4766                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
4767                                 return NT_STATUS_UNSUCCESSFUL;
4768                         }
4769                 } else {
4770                         if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
4771                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
4772                                 return NT_STATUS_UNSUCCESSFUL;
4773                         }
4774                 }
4775         } else {
4776                 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
4777                         DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
4778                         return NT_STATUS_UNSUCCESSFUL;
4779                 }
4780         }
4781
4782         if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
4783                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
4784                 return NT_STATUS_UNSUCCESSFUL;
4785         }
4786
4787         if (!init_ldap_from_sam(ldap_state, NULL, &mods, user, element_is_set_or_changed)) {
4788                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
4789                 return NT_STATUS_UNSUCCESSFUL;
4790         }
4791
4792         if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
4793                 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
4794         }
4795         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
4796
4797         if (add_posix) {
4798                 char *escape_name;
4799
4800                 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
4801
4802                 /* retrieve the Domain Users group gid */
4803                 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_GROUP_RID_USERS) ||
4804                     !sid_to_gid(&group_sid, &gid)) {
4805                         DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
4806                         return NT_STATUS_INVALID_PRIMARY_GROUP;
4807                 }
4808
4809                 /* lets allocate a new userid for this user */
4810                 if (!winbind_allocate_uid(&uid)) {
4811                         DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
4812                         return NT_STATUS_UNSUCCESSFUL;
4813                 }
4814
4815
4816                 if (is_machine) {
4817                         /* TODO: choose a more appropriate default for machines */
4818                         homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
4819                         shell = talloc_strdup(tmp_ctx, "/bin/false");
4820                 } else {
4821                         homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
4822                         shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
4823                 }
4824                 uidstr = talloc_asprintf(tmp_ctx, "%d", uid);
4825                 gidstr = talloc_asprintf(tmp_ctx, "%d", gid);
4826
4827                 escape_name = escape_rdn_val_string_alloc(name);
4828                 if (!escape_name) {
4829                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
4830                         return NT_STATUS_NO_MEMORY;
4831                 }
4832
4833                 if (is_machine) {
4834                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix ());
4835                 } else {
4836                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix ());
4837                 }
4838
4839                 SAFE_FREE(escape_name);
4840
4841                 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
4842                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
4843                         return NT_STATUS_NO_MEMORY;
4844                 }
4845
4846                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
4847                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
4848                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
4849                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
4850                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
4851                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
4852                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
4853         }
4854
4855         talloc_autofree_ldapmod(tmp_ctx, mods);
4856
4857         if (add_posix) {        
4858                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
4859         } else {
4860                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
4861         }       
4862
4863         if (rc != LDAP_SUCCESS) {
4864                 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
4865                 return NT_STATUS_UNSUCCESSFUL;
4866         }
4867
4868         DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
4869
4870         flush_pwnam_cache();
4871
4872         return NT_STATUS_OK;
4873 }
4874
4875 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
4876 {
4877         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
4878         LDAPMessage *result = NULL;
4879         LDAPMessage *entry = NULL;
4880         int num_result;
4881         const char *dn;
4882         char *filter;
4883         int rc;
4884
4885         DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
4886         
4887         filter = talloc_asprintf(tmp_ctx,
4888                                  "(&(uid=%s)"
4889                                  "(objectClass=%s)"
4890                                  "(objectClass=%s))",
4891                                  pdb_get_username(sam_acct),
4892                                  LDAP_OBJ_POSIXACCOUNT,
4893                                  LDAP_OBJ_SAMBASAMACCOUNT);
4894         if (filter == NULL) {
4895                 return NT_STATUS_NO_MEMORY;
4896         }
4897
4898         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
4899         if (rc != LDAP_SUCCESS) {
4900                 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
4901                 return NT_STATUS_UNSUCCESSFUL;
4902         }
4903         talloc_autofree_ldapmsg(tmp_ctx, result);
4904
4905         num_result = ldap_count_entries(priv2ld(ldap_state), result);
4906
4907         if (num_result == 0) {
4908                 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
4909                 return NT_STATUS_NO_SUCH_USER;
4910         }
4911
4912         if (num_result > 1) {
4913                 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
4914                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
4915         }
4916
4917         entry = ldap_first_entry(priv2ld(ldap_state), result);
4918         if (!entry) {
4919                 return NT_STATUS_UNSUCCESSFUL;
4920         }
4921
4922         /* it is just a posix account, retrieve the dn for later use */
4923         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
4924         if (!dn) {
4925                 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
4926                 return NT_STATUS_NO_MEMORY;
4927         }
4928
4929         rc = smbldap_delete(ldap_state->smbldap_state, dn);
4930         if (rc != LDAP_SUCCESS) {
4931                 return NT_STATUS_UNSUCCESSFUL;
4932         }
4933
4934         flush_pwnam_cache();
4935
4936         return NT_STATUS_OK;
4937 }
4938
4939 /*
4940  * ldapsam_create_group creates a new
4941  * posixGroup and sambaGroupMapping object
4942  * in the ldap groups subtree
4943  *
4944  * The gid is allocated by winbindd.
4945  */
4946
4947 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
4948                                          TALLOC_CTX *tmp_ctx,
4949                                          const char *name,
4950                                          uint32 *rid)
4951 {
4952         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
4953         NTSTATUS ret;
4954         LDAPMessage *entry = NULL;
4955         LDAPMessage *result = NULL;
4956         uint32 num_result;
4957         BOOL is_new_entry = False;
4958         LDAPMod **mods = NULL;
4959         char *filter;
4960         char *groupsidstr;
4961         char *groupname;
4962         char *grouptype;
4963         char *gidstr;
4964         const char *dn = NULL;
4965         DOM_SID group_sid;
4966         gid_t gid = -1;
4967         int rc;
4968         
4969         groupname = escape_ldap_string_alloc(name);
4970         filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
4971                                  groupname, LDAP_OBJ_POSIXGROUP);
4972         SAFE_FREE(groupname);
4973
4974         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
4975         if (rc != LDAP_SUCCESS) {
4976                 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
4977                 return NT_STATUS_UNSUCCESSFUL;
4978         }
4979         talloc_autofree_ldapmsg(tmp_ctx, result);
4980
4981         num_result = ldap_count_entries(priv2ld(ldap_state), result);
4982
4983         if (num_result > 1) {
4984                 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
4985                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
4986         }
4987         
4988         if (num_result == 1) {
4989                 char *tmp;
4990                 /* check if it is just a posix group.
4991                  * or if there is a sid attached to this entry
4992                  */
4993
4994                 entry = ldap_first_entry(priv2ld(ldap_state), result);
4995                 if (!entry) {
4996                         return NT_STATUS_UNSUCCESSFUL;
4997                 }
4998
4999                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5000                 if (tmp) {
5001                         DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5002                         return NT_STATUS_GROUP_EXISTS;
5003                 }
5004
5005                 /* it is just a posix group, retrieve the gid and the dn for later use */
5006                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5007                 if (!tmp) {
5008                         DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5009                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5010                 }
5011                 
5012                 gid = strtoul(tmp, NULL, 10);
5013
5014                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5015                 if (!dn) {
5016                         DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5017                         return NT_STATUS_NO_MEMORY;
5018                 }
5019         }
5020
5021         if (num_result == 0) {
5022                 char *escape_name;
5023
5024                 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5025
5026                 is_new_entry = True;
5027         
5028                 /* lets allocate a new groupid for this group */
5029                 if (!winbind_allocate_gid(&gid)) {
5030                         DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5031                         return NT_STATUS_UNSUCCESSFUL;
5032                 }
5033
5034                 gidstr = talloc_asprintf(tmp_ctx, "%d", gid);
5035
5036                 escape_name = escape_rdn_val_string_alloc(name);
5037                 if (!escape_name) {
5038                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5039                         return NT_STATUS_NO_MEMORY;
5040                 }
5041
5042                 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix());
5043
5044                 SAFE_FREE(escape_name);
5045
5046                 if (!gidstr || !dn) {
5047                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5048                         return NT_STATUS_NO_MEMORY;
5049                 }
5050
5051                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5052                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5053                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5054         }
5055
5056         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5057                 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5058                 return ret;
5059         }
5060
5061         sid_compose(&group_sid, get_global_sam_sid(), *rid);
5062
5063         groupsidstr = talloc_strdup(tmp_ctx, sid_string_static(&group_sid));
5064         grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5065
5066         if (!groupsidstr || !grouptype) {
5067                 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5068                 return NT_STATUS_NO_MEMORY;
5069         }
5070
5071         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5072         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5073         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5074         smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5075         talloc_autofree_ldapmod(tmp_ctx, mods);
5076
5077         if (is_new_entry) {     
5078                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5079 #if 0
5080                 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5081                         /* This call may fail with rfc2307bis schema */
5082                         /* Retry adding a structural class */
5083                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5084                         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5085                 }
5086 #endif
5087         } else {
5088                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5089         }       
5090
5091         if (rc != LDAP_SUCCESS) {
5092                 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5093                 return NT_STATUS_UNSUCCESSFUL;
5094         }
5095
5096         DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5097
5098         return NT_STATUS_OK;
5099 }
5100
5101 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32 rid)
5102 {
5103         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5104         LDAPMessage *result = NULL;
5105         LDAPMessage *entry = NULL;
5106         int num_result;
5107         const char *dn;
5108         char *gidstr;
5109         char *filter;
5110         DOM_SID group_sid;
5111         int rc;
5112
5113         /* get the group sid */
5114         sid_compose(&group_sid, get_global_sam_sid(), rid);
5115
5116         filter = talloc_asprintf(tmp_ctx,
5117                                  "(&(sambaSID=%s)"
5118                                  "(objectClass=%s)"
5119                                  "(objectClass=%s))",
5120                                  sid_string_static(&group_sid),
5121                                  LDAP_OBJ_POSIXGROUP,
5122                                  LDAP_OBJ_GROUPMAP);
5123         if (filter == NULL) {
5124                 return NT_STATUS_NO_MEMORY;
5125         }
5126
5127         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5128         if (rc != LDAP_SUCCESS) {
5129                 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5130                 return NT_STATUS_UNSUCCESSFUL;
5131         }
5132         talloc_autofree_ldapmsg(tmp_ctx, result);
5133
5134         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5135
5136         if (num_result == 0) {
5137                 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5138                 return NT_STATUS_NO_SUCH_GROUP;
5139         }
5140
5141         if (num_result > 1) {
5142                 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5143                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5144         }
5145
5146         entry = ldap_first_entry(priv2ld(ldap_state), result);
5147         if (!entry) {
5148                 return NT_STATUS_UNSUCCESSFUL;
5149         }
5150
5151         /* here it is, retrieve the dn for later use */
5152         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5153         if (!dn) {
5154                 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5155                 return NT_STATUS_NO_MEMORY;
5156         }
5157
5158         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5159         if (!gidstr) {
5160                 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5161                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5162         }
5163
5164         /* check no user have this group marked as primary group */
5165         filter = talloc_asprintf(tmp_ctx,
5166                                  "(&(gidNumber=%s)"
5167                                  "(objectClass=%s)"
5168                                  "(objectClass=%s))",
5169                                  gidstr,
5170                                  LDAP_OBJ_POSIXACCOUNT,
5171                                  LDAP_OBJ_SAMBASAMACCOUNT);
5172
5173         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5174         if (rc != LDAP_SUCCESS) {
5175                 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5176                 return NT_STATUS_UNSUCCESSFUL;
5177         }
5178         talloc_autofree_ldapmsg(tmp_ctx, result);
5179
5180         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5181
5182         if (num_result != 0) {
5183                 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5184                 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5185         }
5186
5187         rc = smbldap_delete(ldap_state->smbldap_state, dn);
5188         if (rc != LDAP_SUCCESS) {
5189                 return NT_STATUS_UNSUCCESSFUL;
5190         }
5191
5192         return NT_STATUS_OK;
5193 }
5194
5195 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5196                                         TALLOC_CTX *tmp_ctx,
5197                                         uint32 group_rid,
5198                                         uint32 member_rid,
5199                                         int modop)
5200 {
5201         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5202         LDAPMessage *entry = NULL;
5203         LDAPMessage *result = NULL;
5204         uint32 num_result;
5205         LDAPMod **mods = NULL;
5206         char *filter;
5207         char *uidstr;
5208         const char *dn = NULL;
5209         DOM_SID group_sid;
5210         DOM_SID member_sid;
5211         int rc;
5212
5213         switch (modop) {
5214         case LDAP_MOD_ADD:
5215                 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5216                 break;
5217         case LDAP_MOD_DELETE:
5218                 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5219                 break;
5220         default:
5221                 return NT_STATUS_UNSUCCESSFUL;
5222         }
5223         
5224         /* get member sid  */
5225         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5226
5227         /* get the group sid */
5228         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5229
5230         filter = talloc_asprintf(tmp_ctx,
5231                                  "(&(sambaSID=%s)"
5232                                  "(objectClass=%s)"
5233                                  "(objectClass=%s))",
5234                                  sid_string_static(&member_sid),
5235                                  LDAP_OBJ_POSIXACCOUNT,
5236                                  LDAP_OBJ_SAMBASAMACCOUNT);
5237         if (filter == NULL) {
5238                 return NT_STATUS_NO_MEMORY;
5239         }
5240
5241         /* get the member uid */
5242         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5243         if (rc != LDAP_SUCCESS) {
5244                 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5245                 return NT_STATUS_UNSUCCESSFUL;
5246         }
5247         talloc_autofree_ldapmsg(tmp_ctx, result);
5248
5249         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5250
5251         if (num_result == 0) {
5252                 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5253                 return NT_STATUS_NO_SUCH_MEMBER;
5254         }
5255
5256         if (num_result > 1) {
5257                 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5258                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5259         }
5260
5261         entry = ldap_first_entry(priv2ld(ldap_state), result);
5262         if (!entry) {
5263                 return NT_STATUS_UNSUCCESSFUL;
5264         }
5265
5266         if (modop == LDAP_MOD_DELETE) {
5267                 /* check if we are trying to remove the member from his primary group */
5268                 char *gidstr;
5269                 gid_t user_gid, group_gid;
5270                 
5271                 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5272                 if (!gidstr) {
5273                         DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5274                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5275                 }
5276
5277                 user_gid = strtoul(gidstr, NULL, 10);
5278         
5279                 if (!sid_to_gid(&group_sid, &group_gid)) {
5280                         DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5281                         return NT_STATUS_UNSUCCESSFUL;
5282                 }
5283
5284                 if (user_gid == group_gid) {
5285                         DEBUG (3, ("ldapsam_change_groupmem: can't remove user from it's own primary group!\n"));
5286                         return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5287                 }
5288         }
5289
5290         /* here it is, retrieve the uid for later use */
5291         uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5292         if (!uidstr) {
5293                 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5294                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5295         }
5296
5297         filter = talloc_asprintf(tmp_ctx,
5298                                  "(&(sambaSID=%s)"
5299                                  "(objectClass=%s)"
5300                                  "(objectClass=%s))",
5301                                  sid_string_static(&group_sid),
5302                                  LDAP_OBJ_POSIXGROUP,
5303                                  LDAP_OBJ_GROUPMAP);
5304
5305         /* get the group */
5306         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5307         if (rc != LDAP_SUCCESS) {
5308                 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5309                 return NT_STATUS_UNSUCCESSFUL;
5310         }
5311         talloc_autofree_ldapmsg(tmp_ctx, result);
5312
5313         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5314
5315         if (num_result == 0) {
5316                 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5317                 return NT_STATUS_NO_SUCH_GROUP;
5318         }
5319
5320         if (num_result > 1) {
5321                 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5322                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5323         }
5324
5325         entry = ldap_first_entry(priv2ld(ldap_state), result);
5326         if (!entry) {
5327                 return NT_STATUS_UNSUCCESSFUL;
5328         }
5329
5330         /* here it is, retrieve the dn for later use */
5331         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5332         if (!dn) {
5333                 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5334                 return NT_STATUS_NO_MEMORY;
5335         }
5336
5337         smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5338
5339         talloc_autofree_ldapmod(tmp_ctx, mods);
5340
5341         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5342         if (rc != LDAP_SUCCESS) {
5343                 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5344                         DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5345                         return NT_STATUS_MEMBER_IN_GROUP;
5346                 }
5347                 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5348                         DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5349                         return NT_STATUS_MEMBER_NOT_IN_GROUP;
5350                 }
5351                 return NT_STATUS_UNSUCCESSFUL;
5352         }
5353         
5354         return NT_STATUS_OK;
5355 }
5356
5357 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5358                                      TALLOC_CTX *tmp_ctx,
5359                                      uint32 group_rid,
5360                                      uint32 member_rid)
5361 {
5362         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5363 }
5364 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5365                                      TALLOC_CTX *tmp_ctx,
5366                                      uint32 group_rid,
5367                                      uint32 member_rid)
5368 {
5369         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5370 }
5371
5372 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5373                                           TALLOC_CTX *mem_ctx,
5374                                           struct samu *sampass)
5375 {
5376         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5377         LDAPMessage *entry = NULL;
5378         LDAPMessage *result = NULL;
5379         uint32 num_result;
5380         LDAPMod **mods = NULL;
5381         char *filter;
5382         char *escape_username;
5383         char *gidstr;
5384         const char *dn = NULL;
5385         gid_t gid;
5386         int rc;
5387
5388         DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5389
5390         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5391                 DEBUG(0,("ldapsam_set_primary_group: failed to retieve gid from user's group SID!\n"));
5392                 return NT_STATUS_UNSUCCESSFUL;
5393         }
5394         gidstr = talloc_asprintf(mem_ctx, "%d", gid);
5395         if (!gidstr) {
5396                 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5397                 return NT_STATUS_NO_MEMORY;
5398         }
5399
5400         escape_username = escape_ldap_string_alloc(pdb_get_username(sampass));
5401         if (escape_username== NULL) {
5402                 return NT_STATUS_NO_MEMORY;
5403         }
5404
5405         filter = talloc_asprintf(mem_ctx,
5406                                  "(&(uid=%s)"
5407                                  "(objectClass=%s)"
5408                                  "(objectClass=%s))",
5409                                  escape_username,
5410                                  LDAP_OBJ_POSIXACCOUNT,
5411                                  LDAP_OBJ_SAMBASAMACCOUNT);
5412
5413         SAFE_FREE(escape_username);
5414
5415         if (filter == NULL) {
5416                 return NT_STATUS_NO_MEMORY;
5417         }
5418
5419         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5420         if (rc != LDAP_SUCCESS) {
5421                 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5422                 return NT_STATUS_UNSUCCESSFUL;
5423         }
5424         talloc_autofree_ldapmsg(mem_ctx, result);
5425
5426         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5427
5428         if (num_result == 0) {
5429                 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5430                 return NT_STATUS_NO_SUCH_USER;
5431         }
5432
5433         if (num_result > 1) {
5434                 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
5435                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5436         }
5437
5438         entry = ldap_first_entry(priv2ld(ldap_state), result);
5439         if (!entry) {
5440                 return NT_STATUS_UNSUCCESSFUL;
5441         }
5442
5443         /* retrieve the dn for later use */
5444         dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
5445         if (!dn) {
5446                 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
5447                 return NT_STATUS_NO_MEMORY;
5448         }
5449
5450         /* remove the old one, and add the new one, this way we do not risk races */
5451         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
5452
5453         if (mods == NULL) {
5454                 return NT_STATUS_OK;
5455         }
5456
5457         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5458
5459         if (rc != LDAP_SUCCESS) {
5460                 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
5461                          pdb_get_username(sampass), gidstr));
5462                 return NT_STATUS_UNSUCCESSFUL;
5463         }
5464
5465         flush_pwnam_cache();
5466
5467         return NT_STATUS_OK;
5468 }
5469
5470 /**********************************************************************
5471  Housekeeping
5472  *********************************************************************/
5473
5474 static void free_private_data(void **vp) 
5475 {
5476         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
5477
5478         smbldap_free_struct(&(*ldap_state)->smbldap_state);
5479
5480         if ((*ldap_state)->result != NULL) {
5481                 ldap_msgfree((*ldap_state)->result);
5482                 (*ldap_state)->result = NULL;
5483         }
5484         if ((*ldap_state)->domain_dn != NULL) {
5485                 SAFE_FREE((*ldap_state)->domain_dn);
5486         }
5487
5488         *ldap_state = NULL;
5489
5490         /* No need to free any further, as it is talloc()ed */
5491 }
5492
5493 /*********************************************************************
5494  Intitalise the parts of the pdb_methods structure that are common to 
5495  all pdb_ldap modes
5496 *********************************************************************/
5497
5498 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
5499 {
5500         NTSTATUS nt_status;
5501         struct ldapsam_privates *ldap_state;
5502
5503         if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
5504                 return nt_status;
5505         }
5506
5507         (*pdb_method)->name = "ldapsam";
5508
5509         (*pdb_method)->setsampwent = ldapsam_setsampwent;
5510         (*pdb_method)->endsampwent = ldapsam_endsampwent;
5511         (*pdb_method)->getsampwent = ldapsam_getsampwent;
5512         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
5513         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
5514         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
5515         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
5516         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
5517         (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
5518
5519         (*pdb_method)->getgrsid = ldapsam_getgrsid;
5520         (*pdb_method)->getgrgid = ldapsam_getgrgid;
5521         (*pdb_method)->getgrnam = ldapsam_getgrnam;
5522         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
5523         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
5524         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
5525         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
5526
5527         (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
5528         (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
5529
5530         (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
5531
5532         (*pdb_method)->rid_algorithm = ldapsam_rid_algorithm;
5533         (*pdb_method)->new_rid = ldapsam_new_rid;
5534
5535         /* TODO: Setup private data and free */
5536
5537         if ( !(ldap_state = TALLOC_ZERO_P(*pdb_method, struct ldapsam_privates)) ) {
5538                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
5539                 return NT_STATUS_NO_MEMORY;
5540         }
5541
5542         nt_status = smbldap_init(*pdb_method, location, &ldap_state->smbldap_state);
5543
5544         if ( !NT_STATUS_IS_OK(nt_status) ) {
5545                 return nt_status;
5546         }
5547
5548         if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
5549                 return NT_STATUS_NO_MEMORY;
5550         }
5551
5552         (*pdb_method)->private_data = ldap_state;
5553
5554         (*pdb_method)->free_private_data = free_private_data;
5555
5556         return NT_STATUS_OK;
5557 }
5558
5559 /**********************************************************************
5560  Initialise the 'compat' mode for pdb_ldap
5561  *********************************************************************/
5562
5563 NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
5564 {
5565         NTSTATUS nt_status;
5566         struct ldapsam_privates *ldap_state;
5567         char *uri = talloc_strdup( NULL, location );
5568
5569         trim_char( uri, '\"', '\"' );
5570         nt_status = pdb_init_ldapsam_common( pdb_method, uri );
5571         if ( uri )
5572                 TALLOC_FREE( uri );
5573
5574         if ( !NT_STATUS_IS_OK(nt_status) ) {
5575                 return nt_status;
5576         }
5577
5578         (*pdb_method)->name = "ldapsam_compat";
5579
5580         ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
5581         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
5582
5583         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
5584
5585         return NT_STATUS_OK;
5586 }
5587
5588 /**********************************************************************
5589  Initialise the normal mode for pdb_ldap
5590  *********************************************************************/
5591
5592 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
5593 {
5594         NTSTATUS nt_status;
5595         struct ldapsam_privates *ldap_state;
5596         uint32 alg_rid_base;
5597         pstring alg_rid_base_string;
5598         LDAPMessage *result = NULL;
5599         LDAPMessage *entry = NULL;
5600         DOM_SID ldap_domain_sid;
5601         DOM_SID secrets_domain_sid;
5602         pstring domain_sid_string;
5603         char *dn;
5604         char *uri = talloc_strdup( NULL, location );
5605
5606         trim_char( uri, '\"', '\"' );
5607         nt_status = pdb_init_ldapsam_common(pdb_method, uri);
5608         if ( uri )
5609                 TALLOC_FREE( uri );
5610
5611         if (!NT_STATUS_IS_OK(nt_status)) {
5612                 return nt_status;
5613         }
5614
5615         (*pdb_method)->name = "ldapsam";
5616
5617         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
5618         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
5619         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
5620         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
5621         (*pdb_method)->search_users = ldapsam_search_users;
5622         (*pdb_method)->search_groups = ldapsam_search_groups;
5623         (*pdb_method)->search_aliases = ldapsam_search_aliases;
5624
5625         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
5626                 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
5627                 (*pdb_method)->enum_group_memberships =
5628                         ldapsam_enum_group_memberships;
5629                 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
5630                 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
5631                 
5632                 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
5633                         (*pdb_method)->create_user = ldapsam_create_user;
5634                         (*pdb_method)->delete_user = ldapsam_delete_user;
5635                         (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
5636                         (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
5637                         (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
5638                         (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
5639                         (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
5640                 }
5641         }
5642
5643         ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
5644         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
5645
5646         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
5647         
5648         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
5649                                                &result, 
5650                                                ldap_state->domain_name, True);
5651         
5652         if ( !NT_STATUS_IS_OK(nt_status) ) {
5653                 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain "
5654                           "info, nor add one to the domain\n"));
5655                 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, "
5656                              "will be unable to allocate new users/groups, "
5657                              "and will risk BDCs having inconsistant SIDs\n"));
5658                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
5659                 return NT_STATUS_OK;
5660         }
5661
5662         /* Given that the above might fail, everything below this must be
5663          * optional */
5664         
5665         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
5666                                  result);
5667         if (!entry) {
5668                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
5669                           "entry\n"));
5670                 ldap_msgfree(result);
5671                 return NT_STATUS_UNSUCCESSFUL;
5672         }
5673
5674         dn = smbldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
5675         if (!dn) {
5676                 return NT_STATUS_UNSUCCESSFUL;
5677         }
5678
5679         ldap_state->domain_dn = smb_xstrdup(dn);
5680         ldap_memfree(dn);
5681
5682         if (smbldap_get_single_pstring(
5683                     ldap_state->smbldap_state->ldap_struct,
5684                     entry, 
5685                     get_userattr_key2string(ldap_state->schema_ver,
5686                                             LDAP_ATTR_USER_SID), 
5687                     domain_sid_string)) {
5688                 BOOL found_sid;
5689                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
5690                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
5691                                   "read as a valid SID\n", domain_sid_string));
5692                         return NT_STATUS_INVALID_PARAMETER;
5693                 }
5694                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
5695                                                      &secrets_domain_sid);
5696                 if (!found_sid || !sid_equal(&secrets_domain_sid,
5697                                              &ldap_domain_sid)) {
5698                         fstring new_sid_str, old_sid_str;
5699                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
5700                                   "%s based on pdb_ldap results %s -> %s\n",
5701                                   ldap_state->domain_name,
5702                                   sid_to_string(old_sid_str,
5703                                                 &secrets_domain_sid),
5704                                   sid_to_string(new_sid_str,
5705                                                 &ldap_domain_sid)));
5706                         
5707                         /* reset secrets.tdb sid */
5708                         secrets_store_domain_sid(ldap_state->domain_name,
5709                                                  &ldap_domain_sid);
5710                         DEBUG(1, ("New global sam SID: %s\n",
5711                                   sid_to_string(new_sid_str,
5712                                                 get_global_sam_sid())));
5713                 }
5714                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
5715         }
5716
5717         if (smbldap_get_single_pstring(
5718                     ldap_state->smbldap_state->ldap_struct,
5719                     entry, 
5720                     get_attr_key2string( dominfo_attr_list,
5721                                          LDAP_ATTR_ALGORITHMIC_RID_BASE ),
5722                     alg_rid_base_string)) {
5723                 alg_rid_base = (uint32)atol(alg_rid_base_string);
5724                 if (alg_rid_base != algorithmic_rid_base()) {
5725                         DEBUG(0, ("The value of 'algorithmic RID base' has "
5726                                   "changed since the LDAP\n"
5727                                   "database was initialised.  Aborting. \n"));
5728                         ldap_msgfree(result);
5729                         return NT_STATUS_UNSUCCESSFUL;
5730                 }
5731         }
5732         ldap_msgfree(result);
5733
5734         return NT_STATUS_OK;
5735 }
5736
5737 NTSTATUS pdb_ldap_init(void)
5738 {
5739         NTSTATUS nt_status;
5740         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
5741                 return nt_status;
5742
5743         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
5744                 return nt_status;
5745
5746         /* Let pdb_nds register backends */
5747         pdb_nds_init();
5748
5749         return NT_STATUS_OK;
5750 }