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