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