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