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