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