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