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