Fix bug 5886
[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                 int ret;
1705
1706                 if (!ldap_state->is_nds_ldap) {
1707
1708                         if (!smbldap_has_extension(ldap_state->smbldap_state->ldap_struct, 
1709                                                    LDAP_EXOP_MODIFY_PASSWD)) {
1710                                 DEBUG(2, ("ldap password change requested, but LDAP "
1711                                           "server does not support it -- ignoring\n"));
1712                                 return NT_STATUS_OK;
1713                         }
1714                 }
1715
1716                 if (!push_utf8_talloc(talloc_tos(), &utf8_password,
1717                                         pdb_get_plaintext_passwd(newpwd),
1718                                         &converted_size))
1719                 {
1720                         return NT_STATUS_NO_MEMORY;
1721                 }
1722
1723                 if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1724                         TALLOC_FREE(utf8_password);
1725                         return NT_STATUS_NO_MEMORY;
1726                 }
1727
1728                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1729                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1730                         TALLOC_FREE(utf8_password);
1731                         TALLOC_FREE(utf8_dn);
1732                         return NT_STATUS_UNSUCCESSFUL;
1733                 }
1734
1735                 if ((ber_printf (ber, "{") < 0) ||
1736                     (ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID,
1737                                  utf8_dn) < 0)) {
1738                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1739                                  "value <0\n"));
1740                         ber_free(ber,1);
1741                         TALLOC_FREE(utf8_dn);
1742                         TALLOC_FREE(utf8_password);
1743                         return NT_STATUS_UNSUCCESSFUL;
1744                 }
1745
1746                 if ((utf8_password != NULL) && (*utf8_password != '\0')) {
1747                         ret = ber_printf(ber, "ts}",
1748                                          LDAP_TAG_EXOP_MODIFY_PASSWD_NEW,
1749                                          utf8_password);
1750                 } else {
1751                         ret = ber_printf(ber, "}");
1752                 }
1753
1754                 if (ret < 0) {
1755                         DEBUG(0,("ldapsam_modify_entry: ber_printf returns a "
1756                                  "value <0\n"));
1757                         ber_free(ber,1);
1758                         TALLOC_FREE(utf8_dn);
1759                         TALLOC_FREE(utf8_password);
1760                         return NT_STATUS_UNSUCCESSFUL;
1761                 }
1762
1763                 if ((rc = ber_flatten (ber, &bv))<0) {
1764                         DEBUG(0,("ldapsam_modify_entry: ber_flatten returns a value <0\n"));
1765                         ber_free(ber,1);
1766                         TALLOC_FREE(utf8_dn);
1767                         TALLOC_FREE(utf8_password);
1768                         return NT_STATUS_UNSUCCESSFUL;
1769                 }
1770
1771                 TALLOC_FREE(utf8_dn);
1772                 TALLOC_FREE(utf8_password);
1773                 ber_free(ber, 1);
1774
1775                 if (!ldap_state->is_nds_ldap) {
1776                         rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1777                                                         LDAP_EXOP_MODIFY_PASSWD,
1778                                                         bv, NULL, NULL, &retoid, 
1779                                                         &retdata);
1780                 } else {
1781                         rc = pdb_nds_set_password(ldap_state->smbldap_state, dn,
1782                                                         pdb_get_plaintext_passwd(newpwd));
1783                 }
1784                 if (rc != LDAP_SUCCESS) {
1785                         char *ld_error = NULL;
1786
1787                         if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
1788                                 DEBUG(3, ("Could not set userPassword "
1789                                           "attribute due to an objectClass "
1790                                           "violation -- ignoring\n"));
1791                                 ber_bvfree(bv);
1792                                 return NT_STATUS_OK;
1793                         }
1794
1795                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1796                                         &ld_error);
1797                         DEBUG(0,("ldapsam_modify_entry: LDAP Password could not be changed for user %s: %s\n\t%s\n",
1798                                 pdb_get_username(newpwd), ldap_err2string(rc), ld_error?ld_error:"unknown"));
1799                         SAFE_FREE(ld_error);
1800                         ber_bvfree(bv);
1801 #if defined(LDAP_CONSTRAINT_VIOLATION)
1802                         if (rc == LDAP_CONSTRAINT_VIOLATION)
1803                                 return NT_STATUS_PASSWORD_RESTRICTION;
1804 #endif
1805                         return NT_STATUS_UNSUCCESSFUL;
1806                 } else {
1807                         DEBUG(3,("ldapsam_modify_entry: LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1808 #ifdef DEBUG_PASSWORD
1809                         DEBUG(100,("ldapsam_modify_entry: LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1810 #endif    
1811                         if (retdata)
1812                                 ber_bvfree(retdata);
1813                         if (retoid)
1814                                 ldap_memfree(retoid);
1815                 }
1816                 ber_bvfree(bv);
1817         }
1818         return NT_STATUS_OK;
1819 }
1820
1821 /**********************************************************************
1822  Delete entry from LDAP for username.
1823 *********************************************************************/
1824
1825 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods,
1826                                            struct samu * sam_acct)
1827 {
1828         struct ldapsam_privates *priv =
1829                 (struct ldapsam_privates *)my_methods->private_data;
1830         const char *sname;
1831         int rc;
1832         LDAPMessage *msg, *entry;
1833         NTSTATUS result = NT_STATUS_NO_MEMORY;
1834         const char **attr_list;
1835         TALLOC_CTX *mem_ctx;
1836
1837         if (!sam_acct) {
1838                 DEBUG(0, ("ldapsam_delete_sam_account: sam_acct was NULL!\n"));
1839                 return NT_STATUS_INVALID_PARAMETER;
1840         }
1841
1842         sname = pdb_get_username(sam_acct);
1843
1844         DEBUG(3, ("ldapsam_delete_sam_account: Deleting user %s from "
1845                   "LDAP.\n", sname));
1846
1847         mem_ctx = talloc_new(NULL);
1848         if (mem_ctx == NULL) {
1849                 DEBUG(0, ("talloc_new failed\n"));
1850                 goto done;
1851         }
1852
1853         attr_list = get_userattr_delete_list(mem_ctx, priv->schema_ver );
1854         if (attr_list == NULL) {
1855                 goto done;
1856         }
1857
1858         rc = ldapsam_search_suffix_by_name(priv, sname, &msg, attr_list);
1859
1860         if ((rc != LDAP_SUCCESS) ||
1861             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
1862             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
1863                 DEBUG(5, ("Could not find user %s\n", sname));
1864                 result = NT_STATUS_NO_SUCH_USER;
1865                 goto done;
1866         }
1867
1868         rc = ldapsam_delete_entry(
1869                 priv, mem_ctx, entry,
1870                 priv->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ?
1871                 LDAP_OBJ_SAMBASAMACCOUNT : LDAP_OBJ_SAMBAACCOUNT,
1872                 attr_list);
1873
1874         result = (rc == LDAP_SUCCESS) ?
1875                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
1876
1877  done:
1878         TALLOC_FREE(mem_ctx);
1879         return result;
1880 }
1881
1882 /**********************************************************************
1883  Helper function to determine for update_sam_account whether
1884  we need LDAP modification.
1885 *********************************************************************/
1886
1887 static bool element_is_changed(const struct samu *sampass,
1888                                enum pdb_elements element)
1889 {
1890         return IS_SAM_CHANGED(sampass, element);
1891 }
1892
1893 /**********************************************************************
1894  Update struct samu.
1895 *********************************************************************/
1896
1897 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
1898 {
1899         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1900         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1901         int rc = 0;
1902         char *dn;
1903         LDAPMessage *result = NULL;
1904         LDAPMessage *entry = NULL;
1905         LDAPMod **mods = NULL;
1906         const char **attr_list;
1907
1908         result = (LDAPMessage *)pdb_get_backend_private_data(newpwd, my_methods);
1909         if (!result) {
1910                 attr_list = get_userattr_list(NULL, ldap_state->schema_ver);
1911                 if (pdb_get_username(newpwd) == NULL) {
1912                         return NT_STATUS_INVALID_PARAMETER;
1913                 }
1914                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1915                 TALLOC_FREE( attr_list );
1916                 if (rc != LDAP_SUCCESS) {
1917                         return NT_STATUS_UNSUCCESSFUL;
1918                 }
1919                 pdb_set_backend_private_data(newpwd, result, NULL,
1920                                              my_methods, PDB_CHANGED);
1921                 talloc_autofree_ldapmsg(newpwd, result);
1922         }
1923
1924         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1925                 DEBUG(0, ("ldapsam_update_sam_account: No user to modify!\n"));
1926                 return NT_STATUS_UNSUCCESSFUL;
1927         }
1928
1929         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1930         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
1931         if (!dn) {
1932                 return NT_STATUS_UNSUCCESSFUL;
1933         }
1934
1935         DEBUG(4, ("ldapsam_update_sam_account: user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1936
1937         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1938                                 element_is_changed)) {
1939                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1940                 TALLOC_FREE(dn);
1941                 if (mods != NULL)
1942                         ldap_mods_free(mods,True);
1943                 return NT_STATUS_UNSUCCESSFUL;
1944         }
1945
1946         if ((lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_ONLY)
1947             && (mods == NULL)) {
1948                 DEBUG(4,("ldapsam_update_sam_account: mods is empty: nothing to update for user: %s\n",
1949                          pdb_get_username(newpwd)));
1950                 TALLOC_FREE(dn);
1951                 return NT_STATUS_OK;
1952         }
1953
1954         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1955
1956         if (mods != NULL) {
1957                 ldap_mods_free(mods,True);
1958         }
1959
1960         TALLOC_FREE(dn);
1961
1962         /*
1963          * We need to set the backend private data to NULL here. For example
1964          * setuserinfo level 25 does a pdb_update_sam_account twice on the
1965          * same one, and with the explicit delete / add logic for attribute
1966          * values the second time we would use the wrong "old" value which
1967          * does not exist in LDAP anymore. Thus the LDAP server would refuse
1968          * the update.
1969          * The existing LDAPMessage is still being auto-freed by the
1970          * destructor.
1971          */
1972         pdb_set_backend_private_data(newpwd, NULL, NULL, my_methods,
1973                                      PDB_CHANGED);
1974
1975         if (!NT_STATUS_IS_OK(ret)) {
1976                 return ret;
1977         }
1978
1979         DEBUG(2, ("ldapsam_update_sam_account: successfully modified uid = %s in the LDAP database\n",
1980                   pdb_get_username(newpwd)));
1981         return NT_STATUS_OK;
1982 }
1983
1984 /***************************************************************************
1985  Renames a struct samu
1986  - The "rename user script" has full responsibility for changing everything
1987 ***************************************************************************/
1988
1989 static NTSTATUS ldapsam_rename_sam_account(struct pdb_methods *my_methods,
1990                                            struct samu *old_acct,
1991                                            const char *newname)
1992 {
1993         const char *oldname;
1994         int rc;
1995         char *rename_script = NULL;
1996         fstring oldname_lower, newname_lower;
1997
1998         if (!old_acct) {
1999                 DEBUG(0, ("ldapsam_rename_sam_account: old_acct was NULL!\n"));
2000                 return NT_STATUS_INVALID_PARAMETER;
2001         }
2002         if (!newname) {
2003                 DEBUG(0, ("ldapsam_rename_sam_account: newname was NULL!\n"));
2004                 return NT_STATUS_INVALID_PARAMETER;
2005         }
2006
2007         oldname = pdb_get_username(old_acct);
2008
2009         /* rename the posix user */
2010         rename_script = SMB_STRDUP(lp_renameuser_script());
2011         if (rename_script == NULL) {
2012                 return NT_STATUS_NO_MEMORY;
2013         }
2014
2015         if (!(*rename_script)) {
2016                 SAFE_FREE(rename_script);
2017                 return NT_STATUS_ACCESS_DENIED;
2018         }
2019
2020         DEBUG (3, ("ldapsam_rename_sam_account: Renaming user %s to %s.\n",
2021                    oldname, newname));
2022
2023         /* We have to allow the account name to end with a '$'.
2024            Also, follow the semantics in _samr_create_user() and lower case the
2025            posix name but preserve the case in passdb */
2026
2027         fstrcpy( oldname_lower, oldname );
2028         strlower_m( oldname_lower );
2029         fstrcpy( newname_lower, newname );
2030         strlower_m( newname_lower );
2031         rename_script = realloc_string_sub2(rename_script,
2032                                         "%unew",
2033                                         newname_lower,
2034                                         true,
2035                                         true);
2036         if (!rename_script) {
2037                 return NT_STATUS_NO_MEMORY;
2038         }
2039         rename_script = realloc_string_sub2(rename_script,
2040                                         "%uold",
2041                                         oldname_lower,
2042                                         true,
2043                                         true);
2044         rc = smbrun(rename_script, NULL);
2045
2046         DEBUG(rc ? 0 : 3,("Running the command `%s' gave %d\n",
2047                           rename_script, rc));
2048
2049         SAFE_FREE(rename_script);
2050
2051         if (rc == 0) {
2052                 smb_nscd_flush_user_cache();
2053         }
2054
2055         if (rc)
2056                 return NT_STATUS_UNSUCCESSFUL;
2057
2058         return NT_STATUS_OK;
2059 }
2060
2061 /**********************************************************************
2062  Helper function to determine for update_sam_account whether
2063  we need LDAP modification.
2064  *********************************************************************/
2065
2066 static bool element_is_set_or_changed(const struct samu *sampass,
2067                                       enum pdb_elements element)
2068 {
2069         return (IS_SAM_SET(sampass, element) ||
2070                 IS_SAM_CHANGED(sampass, element));
2071 }
2072
2073 /**********************************************************************
2074  Add struct samu to LDAP.
2075 *********************************************************************/
2076
2077 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, struct samu * newpwd)
2078 {
2079         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2080         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2081         int rc;
2082         LDAPMessage     *result = NULL;
2083         LDAPMessage     *entry  = NULL;
2084         LDAPMod         **mods = NULL;
2085         int             ldap_op = LDAP_MOD_REPLACE;
2086         uint32          num_result;
2087         const char      **attr_list;
2088         char *escape_user = NULL;
2089         const char      *username = pdb_get_username(newpwd);
2090         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
2091         char *filter = NULL;
2092         char *dn = NULL;
2093         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2094         TALLOC_CTX *ctx = talloc_init("ldapsam_add_sam_account");
2095
2096         if (!ctx) {
2097                 return NT_STATUS_NO_MEMORY;
2098         }
2099
2100         if (!username || !*username) {
2101                 DEBUG(0, ("ldapsam_add_sam_account: Cannot add user without a username!\n"));
2102                 status = NT_STATUS_INVALID_PARAMETER;
2103                 goto fn_exit;
2104         }
2105
2106         /* free this list after the second search or in case we exit on failure */
2107         attr_list = get_userattr_list(ctx, ldap_state->schema_ver);
2108
2109         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
2110
2111         if (rc != LDAP_SUCCESS) {
2112                 goto fn_exit;
2113         }
2114
2115         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2116                 DEBUG(0,("ldapsam_add_sam_account: User '%s' already in the base, with samba attributes\n", 
2117                          username));
2118                 goto fn_exit;
2119         }
2120         ldap_msgfree(result);
2121         result = NULL;
2122
2123         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
2124                 rc = ldapsam_get_ldap_user_by_sid(ldap_state,
2125                                                   sid, &result);
2126                 if (rc == LDAP_SUCCESS) {
2127                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
2128                                 DEBUG(0,("ldapsam_add_sam_account: SID '%s' "
2129                                          "already in the base, with samba "
2130                                          "attributes\n", sid_string_dbg(sid)));
2131                                 goto fn_exit;
2132                         }
2133                         ldap_msgfree(result);
2134                         result = NULL;
2135                 }
2136         }
2137
2138         /* does the entry already exist but without a samba attributes?
2139            we need to return the samba attributes here */
2140
2141         escape_user = escape_ldap_string(talloc_tos(), username);
2142         filter = talloc_strdup(attr_list, "(uid=%u)");
2143         if (!filter) {
2144                 status = NT_STATUS_NO_MEMORY;
2145                 goto fn_exit;
2146         }
2147         filter = talloc_all_string_sub(attr_list, filter, "%u", escape_user);
2148         TALLOC_FREE(escape_user);
2149         if (!filter) {
2150                 status = NT_STATUS_NO_MEMORY;
2151                 goto fn_exit;
2152         }
2153
2154         rc = smbldap_search_suffix(ldap_state->smbldap_state,
2155                                    filter, attr_list, &result);
2156         if ( rc != LDAP_SUCCESS ) {
2157                 goto fn_exit;
2158         }
2159
2160         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2161
2162         if (num_result > 1) {
2163                 DEBUG (0, ("ldapsam_add_sam_account: More than one user with that uid exists: bailing out!\n"));
2164                 goto fn_exit;
2165         }
2166
2167         /* Check if we need to update an existing entry */
2168         if (num_result == 1) {
2169                 DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2170                 ldap_op = LDAP_MOD_REPLACE;
2171                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2172                 dn = smbldap_talloc_dn(ctx, ldap_state->smbldap_state->ldap_struct, entry);
2173                 if (!dn) {
2174                         status = NT_STATUS_NO_MEMORY;
2175                         goto fn_exit;
2176                 }
2177
2178         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
2179
2180                 /* There might be a SID for this account already - say an idmap entry */
2181
2182                 filter = talloc_asprintf(ctx,
2183                                 "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))",
2184                                  get_userattr_key2string(ldap_state->schema_ver,
2185                                          LDAP_ATTR_USER_SID),
2186                                  sid_string_talloc(ctx, sid),
2187                                  LDAP_OBJ_IDMAP_ENTRY,
2188                                  LDAP_OBJ_SID_ENTRY);
2189                 if (!filter) {
2190                         status = NT_STATUS_NO_MEMORY;
2191                         goto fn_exit;
2192                 }
2193
2194                 /* free old result before doing a new search */
2195                 if (result != NULL) {
2196                         ldap_msgfree(result);
2197                         result = NULL;
2198                 }
2199                 rc = smbldap_search_suffix(ldap_state->smbldap_state,
2200                                            filter, attr_list, &result);
2201
2202                 if ( rc != LDAP_SUCCESS ) {
2203                         goto fn_exit;
2204                 }
2205
2206                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
2207
2208                 if (num_result > 1) {
2209                         DEBUG (0, ("ldapsam_add_sam_account: More than one user with specified Sid exists: bailing out!\n"));
2210                         goto fn_exit;
2211                 }
2212
2213                 /* Check if we need to update an existing entry */
2214                 if (num_result == 1) {
2215
2216                         DEBUG(3,("ldapsam_add_sam_account: User exists without samba attributes: adding them\n"));
2217                         ldap_op = LDAP_MOD_REPLACE;
2218                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
2219                         dn = smbldap_talloc_dn (ctx, ldap_state->smbldap_state->ldap_struct, entry);
2220                         if (!dn) {
2221                                 status = NT_STATUS_NO_MEMORY;
2222                                 goto fn_exit;
2223                         }
2224                 }
2225         }
2226
2227         if (num_result == 0) {
2228                 char *escape_username;
2229                 /* Check if we need to add an entry */
2230                 DEBUG(3,("ldapsam_add_sam_account: Adding new user\n"));
2231                 ldap_op = LDAP_MOD_ADD;
2232
2233                 escape_username = escape_rdn_val_string_alloc(username);
2234                 if (!escape_username) {
2235                         status = NT_STATUS_NO_MEMORY;
2236                         goto fn_exit;
2237                 }
2238
2239                 if (username[strlen(username)-1] == '$') {
2240                         dn = talloc_asprintf(ctx,
2241                                         "uid=%s,%s",
2242                                         escape_username,
2243                                         lp_ldap_machine_suffix());
2244                 } else {
2245                         dn = talloc_asprintf(ctx,
2246                                         "uid=%s,%s",
2247                                         escape_username,
2248                                         lp_ldap_user_suffix());
2249                 }
2250
2251                 SAFE_FREE(escape_username);
2252                 if (!dn) {
2253                         status = NT_STATUS_NO_MEMORY;
2254                         goto fn_exit;
2255                 }
2256         }
2257
2258         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
2259                                 element_is_set_or_changed)) {
2260                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
2261                 if (mods != NULL) {
2262                         ldap_mods_free(mods, true);
2263                 }
2264                 goto fn_exit;
2265         }
2266
2267         if (mods == NULL) {
2268                 DEBUG(0,("ldapsam_add_sam_account: mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
2269                 goto fn_exit;
2270         }
2271         switch ( ldap_state->schema_ver ) {
2272                 case SCHEMAVER_SAMBAACCOUNT:
2273                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
2274                         break;
2275                 case SCHEMAVER_SAMBASAMACCOUNT:
2276                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
2277                         break;
2278                 default:
2279                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
2280                         break;
2281         }
2282
2283         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
2284         if (!NT_STATUS_IS_OK(ret)) {
2285                 DEBUG(0,("ldapsam_add_sam_account: failed to modify/add user with uid = %s (dn = %s)\n",
2286                          pdb_get_username(newpwd),dn));
2287                 ldap_mods_free(mods, true);
2288                 goto fn_exit;
2289         }
2290
2291         DEBUG(2,("ldapsam_add_sam_account: added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
2292         ldap_mods_free(mods, true);
2293
2294         status = NT_STATUS_OK;
2295
2296   fn_exit:
2297
2298         TALLOC_FREE(ctx);
2299         if (result) {
2300                 ldap_msgfree(result);
2301         }
2302         return status;
2303 }
2304
2305 /**********************************************************************
2306  *********************************************************************/
2307
2308 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
2309                                      const char *filter,
2310                                      LDAPMessage ** result)
2311 {
2312         int scope = LDAP_SCOPE_SUBTREE;
2313         int rc;
2314         const char **attr_list;
2315
2316         attr_list = get_attr_list(NULL, groupmap_attr_list);
2317         rc = smbldap_search(ldap_state->smbldap_state,
2318                             lp_ldap_suffix (), scope,
2319                             filter, attr_list, 0, result);
2320         TALLOC_FREE(attr_list);
2321
2322         return rc;
2323 }
2324
2325 /**********************************************************************
2326  *********************************************************************/
2327
2328 static bool init_group_from_ldap(struct ldapsam_privates *ldap_state,
2329                                  GROUP_MAP *map, LDAPMessage *entry)
2330 {
2331         char *temp = NULL;
2332         TALLOC_CTX *ctx = talloc_init("init_group_from_ldap");
2333
2334         if (ldap_state == NULL || map == NULL || entry == NULL ||
2335                         ldap_state->smbldap_state->ldap_struct == NULL) {
2336                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
2337                 TALLOC_FREE(ctx);
2338                 return false;
2339         }
2340
2341         temp = smbldap_talloc_single_attribute(
2342                         ldap_state->smbldap_state->ldap_struct,
2343                         entry,
2344                         get_attr_key2string(groupmap_attr_list,
2345                                 LDAP_ATTR_GIDNUMBER),
2346                         ctx);
2347         if (!temp) {
2348                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n", 
2349                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
2350                 TALLOC_FREE(ctx);
2351                 return false;
2352         }
2353         DEBUG(2, ("init_group_from_ldap: Entry found for group: %s\n", temp));
2354
2355         map->gid = (gid_t)atol(temp);
2356
2357         TALLOC_FREE(temp);
2358         temp = smbldap_talloc_single_attribute(
2359                         ldap_state->smbldap_state->ldap_struct,
2360                         entry,
2361                         get_attr_key2string(groupmap_attr_list,
2362                                 LDAP_ATTR_GROUP_SID),
2363                         ctx);
2364         if (!temp) {
2365                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2366                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
2367                 TALLOC_FREE(ctx);
2368                 return false;
2369         }
2370
2371         if (!string_to_sid(&map->sid, temp)) {
2372                 DEBUG(1, ("SID string [%s] could not be read as a valid SID\n", temp));
2373                 TALLOC_FREE(ctx);
2374                 return false;
2375         }
2376
2377         TALLOC_FREE(temp);
2378         temp = smbldap_talloc_single_attribute(
2379                         ldap_state->smbldap_state->ldap_struct,
2380                         entry,
2381                         get_attr_key2string(groupmap_attr_list,
2382                                 LDAP_ATTR_GROUP_TYPE),
2383                         ctx);
2384         if (!temp) {
2385                 DEBUG(0, ("init_group_from_ldap: Mandatory attribute %s not found\n",
2386                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
2387                 TALLOC_FREE(ctx);
2388                 return false;
2389         }
2390         map->sid_name_use = (enum lsa_SidType)atol(temp);
2391
2392         if ((map->sid_name_use < SID_NAME_USER) ||
2393                         (map->sid_name_use > SID_NAME_UNKNOWN)) {
2394                 DEBUG(0, ("init_group_from_ldap: Unknown Group type: %d\n", map->sid_name_use));
2395                 TALLOC_FREE(ctx);
2396                 return false;
2397         }
2398
2399         TALLOC_FREE(temp);
2400         temp = smbldap_talloc_single_attribute(
2401                         ldap_state->smbldap_state->ldap_struct,
2402                         entry,
2403                         get_attr_key2string(groupmap_attr_list,
2404                                 LDAP_ATTR_DISPLAY_NAME),
2405                         ctx);
2406         if (!temp) {
2407                 temp = smbldap_talloc_single_attribute(
2408                                 ldap_state->smbldap_state->ldap_struct,
2409                                 entry,
2410                                 get_attr_key2string(groupmap_attr_list,
2411                                         LDAP_ATTR_CN),
2412                                 ctx);
2413                 if (!temp) {
2414                         DEBUG(0, ("init_group_from_ldap: Attributes cn not found either \
2415 for gidNumber(%lu)\n",(unsigned long)map->gid));
2416                         TALLOC_FREE(ctx);
2417                         return false;
2418                 }
2419         }
2420         fstrcpy(map->nt_name, temp);
2421
2422         TALLOC_FREE(temp);
2423         temp = smbldap_talloc_single_attribute(
2424                         ldap_state->smbldap_state->ldap_struct,
2425                         entry,
2426                         get_attr_key2string(groupmap_attr_list,
2427                                 LDAP_ATTR_DESC),
2428                         ctx);
2429         if (!temp) {
2430                 temp = talloc_strdup(ctx, "");
2431                 if (!temp) {
2432                         TALLOC_FREE(ctx);
2433                         return false;
2434                 }
2435         }
2436         fstrcpy(map->comment, temp);
2437
2438         if (lp_parm_bool(-1, "ldapsam", "trusted", false)) {
2439                 store_gid_sid_cache(&map->sid, map->gid);
2440         }
2441
2442         TALLOC_FREE(ctx);
2443         return true;
2444 }
2445
2446 /**********************************************************************
2447  *********************************************************************/
2448
2449 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
2450                                  const char *filter,
2451                                  GROUP_MAP *map)
2452 {
2453         struct ldapsam_privates *ldap_state =
2454                 (struct ldapsam_privates *)methods->private_data;
2455         LDAPMessage *result = NULL;
2456         LDAPMessage *entry = NULL;
2457         int count;
2458
2459         if (ldapsam_search_one_group(ldap_state, filter, &result)
2460             != LDAP_SUCCESS) {
2461                 return NT_STATUS_NO_SUCH_GROUP;
2462         }
2463
2464         count = ldap_count_entries(priv2ld(ldap_state), result);
2465
2466         if (count < 1) {
2467                 DEBUG(4, ("ldapsam_getgroup: Did not find group, filter was "
2468                           "%s\n", filter));
2469                 ldap_msgfree(result);
2470                 return NT_STATUS_NO_SUCH_GROUP;
2471         }
2472
2473         if (count > 1) {
2474                 DEBUG(1, ("ldapsam_getgroup: Duplicate entries for filter %s: "
2475                           "count=%d\n", filter, count));
2476                 ldap_msgfree(result);
2477                 return NT_STATUS_NO_SUCH_GROUP;
2478         }
2479
2480         entry = ldap_first_entry(priv2ld(ldap_state), result);
2481
2482         if (!entry) {
2483                 ldap_msgfree(result);
2484                 return NT_STATUS_UNSUCCESSFUL;
2485         }
2486
2487         if (!init_group_from_ldap(ldap_state, map, entry)) {
2488                 DEBUG(1, ("ldapsam_getgroup: init_group_from_ldap failed for "
2489                           "group filter %s\n", filter));
2490                 ldap_msgfree(result);
2491                 return NT_STATUS_NO_SUCH_GROUP;
2492         }
2493
2494         ldap_msgfree(result);
2495         return NT_STATUS_OK;
2496 }
2497
2498 /**********************************************************************
2499  *********************************************************************/
2500
2501 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
2502                                  DOM_SID sid)
2503 {
2504         char *filter = NULL;
2505         NTSTATUS status;
2506         fstring tmp;
2507
2508         if (asprintf(&filter, "(&(objectClass=%s)(%s=%s))",
2509                 LDAP_OBJ_GROUPMAP,
2510                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
2511                 sid_to_fstring(tmp, &sid)) < 0) {
2512                 return NT_STATUS_NO_MEMORY;
2513         }
2514
2515         status = ldapsam_getgroup(methods, filter, map);
2516         SAFE_FREE(filter);
2517         return status;
2518 }
2519
2520 /**********************************************************************
2521  *********************************************************************/
2522
2523 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
2524                                  gid_t gid)
2525 {
2526         char *filter = NULL;
2527         NTSTATUS status;
2528
2529         if (asprintf(&filter, "(&(objectClass=%s)(%s=%lu))",
2530                 LDAP_OBJ_GROUPMAP,
2531                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
2532                 (unsigned long)gid) < 0) {
2533                 return NT_STATUS_NO_MEMORY;
2534         }
2535
2536         status = ldapsam_getgroup(methods, filter, map);
2537         SAFE_FREE(filter);
2538         return status;
2539 }
2540
2541 /**********************************************************************
2542  *********************************************************************/
2543
2544 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
2545                                  const char *name)
2546 {
2547         char *filter = NULL;
2548         char *escape_name = escape_ldap_string(talloc_tos(), name);
2549         NTSTATUS status;
2550
2551         if (!escape_name) {
2552                 return NT_STATUS_NO_MEMORY;
2553         }
2554
2555         if (asprintf(&filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
2556                 LDAP_OBJ_GROUPMAP,
2557                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
2558                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN),
2559                 escape_name) < 0) {
2560                 TALLOC_FREE(escape_name);
2561                 return NT_STATUS_NO_MEMORY;
2562         }
2563
2564         TALLOC_FREE(escape_name);
2565         status = ldapsam_getgroup(methods, filter, map);
2566         SAFE_FREE(filter);
2567         return status;
2568 }
2569
2570 static bool ldapsam_extract_rid_from_entry(LDAP *ldap_struct,
2571                                            LDAPMessage *entry,
2572                                            const DOM_SID *domain_sid,
2573                                            uint32 *rid)
2574 {
2575         fstring str;
2576         DOM_SID sid;
2577
2578         if (!smbldap_get_single_attribute(ldap_struct, entry, "sambaSID",
2579                                           str, sizeof(str)-1)) {
2580                 DEBUG(10, ("Could not find sambaSID attribute\n"));
2581                 return False;
2582         }
2583
2584         if (!string_to_sid(&sid, str)) {
2585                 DEBUG(10, ("Could not convert string %s to sid\n", str));
2586                 return False;
2587         }
2588
2589         if (sid_compare_domain(&sid, domain_sid) != 0) {
2590                 DEBUG(10, ("SID %s is not in expected domain %s\n",
2591                            str, sid_string_dbg(domain_sid)));
2592                 return False;
2593         }
2594
2595         if (!sid_peek_rid(&sid, rid)) {
2596                 DEBUG(10, ("Could not peek into RID\n"));
2597                 return False;
2598         }
2599
2600         return True;
2601 }
2602
2603 static NTSTATUS ldapsam_enum_group_members(struct pdb_methods *methods,
2604                                            TALLOC_CTX *mem_ctx,
2605                                            const DOM_SID *group,
2606                                            uint32 **pp_member_rids,
2607                                            size_t *p_num_members)
2608 {
2609         struct ldapsam_privates *ldap_state =
2610                 (struct ldapsam_privates *)methods->private_data;
2611         struct smbldap_state *conn = ldap_state->smbldap_state;
2612         const char *id_attrs[] = { "memberUid", "gidNumber", NULL };
2613         const char *sid_attrs[] = { "sambaSID", NULL };
2614         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2615         LDAPMessage *result = NULL;
2616         LDAPMessage *entry;
2617         char *filter;
2618         char **values = NULL;
2619         char **memberuid;
2620         char *gidstr;
2621         int rc, count;
2622
2623         *pp_member_rids = NULL;
2624         *p_num_members = 0;
2625
2626         filter = talloc_asprintf(mem_ctx,
2627                                  "(&(objectClass=%s)"
2628                                  "(objectClass=%s)"
2629                                  "(sambaSID=%s))",
2630                                  LDAP_OBJ_POSIXGROUP,
2631                                  LDAP_OBJ_GROUPMAP,
2632                                  sid_string_talloc(mem_ctx, group));
2633         if (filter == NULL) {
2634                 ret = NT_STATUS_NO_MEMORY;
2635                 goto done;
2636         }
2637
2638         rc = smbldap_search(conn, lp_ldap_suffix(),
2639                             LDAP_SCOPE_SUBTREE, filter, id_attrs, 0,
2640                             &result);
2641
2642         if (rc != LDAP_SUCCESS)
2643                 goto done;
2644
2645         talloc_autofree_ldapmsg(mem_ctx, result);
2646
2647         count = ldap_count_entries(conn->ldap_struct, result);
2648
2649         if (count > 1) {
2650                 DEBUG(1, ("Found more than one groupmap entry for %s\n",
2651                           sid_string_dbg(group)));
2652                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2653                 goto done;
2654         }
2655
2656         if (count == 0) {
2657                 ret = NT_STATUS_NO_SUCH_GROUP;
2658                 goto done;
2659         }
2660
2661         entry = ldap_first_entry(conn->ldap_struct, result);
2662         if (entry == NULL)
2663                 goto done;
2664
2665         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2666         if (!gidstr) {
2667                 DEBUG (0, ("ldapsam_enum_group_members: Unable to find the group's gid!\n"));
2668                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2669                 goto done;
2670         }
2671
2672         values = ldap_get_values(conn->ldap_struct, entry, "memberUid");
2673
2674         if (values) {
2675
2676                 filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(|", LDAP_OBJ_SAMBASAMACCOUNT);
2677                 if (filter == NULL) {
2678                         ret = NT_STATUS_NO_MEMORY;
2679                         goto done;
2680                 }
2681
2682                 for (memberuid = values; *memberuid != NULL; memberuid += 1) {
2683                         char *escape_memberuid;
2684
2685                         escape_memberuid = escape_ldap_string(talloc_tos(),
2686                                                               *memberuid);
2687                         if (escape_memberuid == NULL) {
2688                                 ret = NT_STATUS_NO_MEMORY;
2689                                 goto done;
2690                         }
2691
2692                         filter = talloc_asprintf_append_buffer(filter, "(uid=%s)", escape_memberuid);
2693                         TALLOC_FREE(escape_memberuid);
2694                         if (filter == NULL) {
2695                                 ret = NT_STATUS_NO_MEMORY;
2696                                 goto done;
2697                         }
2698                 }
2699
2700                 filter = talloc_asprintf_append_buffer(filter, "))");
2701                 if (filter == NULL) {
2702                         ret = NT_STATUS_NO_MEMORY;
2703                         goto done;
2704                 }
2705
2706                 rc = smbldap_search(conn, lp_ldap_suffix(),
2707                                     LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2708                                     &result);
2709
2710                 if (rc != LDAP_SUCCESS)
2711                         goto done;
2712
2713                 count = ldap_count_entries(conn->ldap_struct, result);
2714                 DEBUG(10,("ldapsam_enum_group_members: found %d accounts\n", count));
2715
2716                 talloc_autofree_ldapmsg(mem_ctx, result);
2717
2718                 for (entry = ldap_first_entry(conn->ldap_struct, result);
2719                      entry != NULL;
2720                      entry = ldap_next_entry(conn->ldap_struct, entry))
2721                 {
2722                         char *sidstr;
2723                         DOM_SID sid;
2724                         uint32 rid;
2725
2726                         sidstr = smbldap_talloc_single_attribute(conn->ldap_struct,
2727                                                                  entry, "sambaSID",
2728                                                                  mem_ctx);
2729                         if (!sidstr) {
2730                                 DEBUG(0, ("Severe DB error, %s can't miss the sambaSID"
2731                                           "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2732                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2733                                 goto done;
2734                         }
2735
2736                         if (!string_to_sid(&sid, sidstr))
2737                                 goto done;
2738
2739                         if (!sid_check_is_in_our_domain(&sid)) {
2740                                 DEBUG(0, ("Inconsistent SAM -- group member uid not "
2741                                           "in our domain\n"));
2742                                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2743                                 goto done;
2744                         }
2745
2746                         sid_peek_rid(&sid, &rid);
2747
2748                         if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2749                                                 p_num_members)) {
2750                                 ret = NT_STATUS_NO_MEMORY;
2751                                 goto done;
2752                         }
2753                 }
2754         }
2755
2756         filter = talloc_asprintf(mem_ctx,
2757                                  "(&(objectClass=%s)"
2758                                  "(gidNumber=%s))",
2759                                  LDAP_OBJ_SAMBASAMACCOUNT,
2760                                  gidstr);
2761
2762         rc = smbldap_search(conn, lp_ldap_suffix(),
2763                             LDAP_SCOPE_SUBTREE, filter, sid_attrs, 0,
2764                             &result);
2765
2766         if (rc != LDAP_SUCCESS)
2767                 goto done;
2768
2769         talloc_autofree_ldapmsg(mem_ctx, result);
2770
2771         for (entry = ldap_first_entry(conn->ldap_struct, result);
2772              entry != NULL;
2773              entry = ldap_next_entry(conn->ldap_struct, entry))
2774         {
2775                 uint32 rid;
2776
2777                 if (!ldapsam_extract_rid_from_entry(conn->ldap_struct,
2778                                                     entry,
2779                                                     get_global_sam_sid(),
2780                                                     &rid)) {
2781                         DEBUG(0, ("Severe DB error, %s can't miss the samba SID"                                                                "attribute\n", LDAP_OBJ_SAMBASAMACCOUNT));
2782                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2783                         goto done;
2784                 }
2785
2786                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_member_rids,
2787                                         p_num_members)) {
2788                         ret = NT_STATUS_NO_MEMORY;
2789                         goto done;
2790                 }
2791         }
2792
2793         ret = NT_STATUS_OK;
2794
2795  done:
2796
2797         if (values)
2798                 ldap_value_free(values);
2799
2800         return ret;
2801 }
2802
2803 static NTSTATUS ldapsam_enum_group_memberships(struct pdb_methods *methods,
2804                                                TALLOC_CTX *mem_ctx,
2805                                                struct samu *user,
2806                                                DOM_SID **pp_sids,
2807                                                gid_t **pp_gids,
2808                                                size_t *p_num_groups)
2809 {
2810         struct ldapsam_privates *ldap_state =
2811                 (struct ldapsam_privates *)methods->private_data;
2812         struct smbldap_state *conn = ldap_state->smbldap_state;
2813         char *filter;
2814         const char *attrs[] = { "gidNumber", "sambaSID", NULL };
2815         char *escape_name;
2816         int rc, count;
2817         LDAPMessage *result = NULL;
2818         LDAPMessage *entry;
2819         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2820         size_t num_sids, num_gids;
2821         char *gidstr;
2822         gid_t primary_gid = -1;
2823
2824         *pp_sids = NULL;
2825         num_sids = 0;
2826
2827         if (pdb_get_username(user) == NULL) {
2828                 return NT_STATUS_INVALID_PARAMETER;
2829         }
2830
2831         escape_name = escape_ldap_string(talloc_tos(), pdb_get_username(user));
2832         if (escape_name == NULL)
2833                 return NT_STATUS_NO_MEMORY;
2834
2835         /* retrieve the users primary gid */
2836         filter = talloc_asprintf(mem_ctx,
2837                                  "(&(objectClass=%s)(uid=%s))",
2838                                  LDAP_OBJ_SAMBASAMACCOUNT,
2839                                  escape_name);
2840         if (filter == NULL) {
2841                 ret = NT_STATUS_NO_MEMORY;
2842                 goto done;
2843         }
2844
2845         rc = smbldap_search(conn, lp_ldap_suffix(),
2846                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2847
2848         if (rc != LDAP_SUCCESS)
2849                 goto done;
2850
2851         talloc_autofree_ldapmsg(mem_ctx, result);
2852
2853         count = ldap_count_entries(priv2ld(ldap_state), result);
2854
2855         switch (count) {
2856         case 0: 
2857                 DEBUG(1, ("User account [%s] not found!\n", pdb_get_username(user)));
2858                 ret = NT_STATUS_NO_SUCH_USER;
2859                 goto done;
2860         case 1:
2861                 entry = ldap_first_entry(priv2ld(ldap_state), result);
2862
2863                 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", mem_ctx);
2864                 if (!gidstr) {
2865                         DEBUG (1, ("Unable to find the member's gid!\n"));
2866                         ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2867                         goto done;
2868                 }
2869                 primary_gid = strtoul(gidstr, NULL, 10);
2870                 break;
2871         default:
2872                 DEBUG(1, ("found more than one account with the same user name ?!\n"));
2873                 ret = NT_STATUS_INTERNAL_DB_CORRUPTION;
2874                 goto done;
2875         }
2876
2877         filter = talloc_asprintf(mem_ctx,
2878                                  "(&(objectClass=%s)(|(memberUid=%s)(gidNumber=%u)))",
2879                                  LDAP_OBJ_POSIXGROUP, escape_name, (unsigned int)primary_gid);
2880         if (filter == NULL) {
2881                 ret = NT_STATUS_NO_MEMORY;
2882                 goto done;
2883         }
2884
2885         rc = smbldap_search(conn, lp_ldap_suffix(),
2886                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
2887
2888         if (rc != LDAP_SUCCESS)
2889                 goto done;
2890
2891         talloc_autofree_ldapmsg(mem_ctx, result);
2892
2893         num_gids = 0;
2894         *pp_gids = NULL;
2895
2896         num_sids = 0;
2897         *pp_sids = NULL;
2898
2899         /* We need to add the primary group as the first gid/sid */
2900
2901         if (!add_gid_to_array_unique(mem_ctx, primary_gid, pp_gids, &num_gids)) {
2902                 ret = NT_STATUS_NO_MEMORY;
2903                 goto done;
2904         }
2905
2906         /* This sid will be replaced later */
2907
2908         ret = add_sid_to_array_unique(mem_ctx, &global_sid_NULL, pp_sids,
2909                                       &num_sids);
2910         if (!NT_STATUS_IS_OK(ret)) {
2911                 goto done;
2912         }
2913
2914         for (entry = ldap_first_entry(conn->ldap_struct, result);
2915              entry != NULL;
2916              entry = ldap_next_entry(conn->ldap_struct, entry))
2917         {
2918                 fstring str;
2919                 DOM_SID sid;
2920                 gid_t gid;
2921                 char *end;
2922
2923                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2924                                                   entry, "sambaSID",
2925                                                   str, sizeof(str)-1))
2926                         continue;
2927
2928                 if (!string_to_sid(&sid, str))
2929                         goto done;
2930
2931                 if (!smbldap_get_single_attribute(conn->ldap_struct,
2932                                                   entry, "gidNumber",
2933                                                   str, sizeof(str)-1))
2934                         continue;
2935
2936                 gid = strtoul(str, &end, 10);
2937
2938                 if (PTR_DIFF(end, str) != strlen(str))
2939                         goto done;
2940
2941                 if (gid == primary_gid) {
2942                         sid_copy(&(*pp_sids)[0], &sid);
2943                 } else {
2944                         if (!add_gid_to_array_unique(mem_ctx, gid, pp_gids,
2945                                                 &num_gids)) {
2946                                 ret = NT_STATUS_NO_MEMORY;
2947                                 goto done;
2948                         }
2949                         ret = add_sid_to_array_unique(mem_ctx, &sid, pp_sids,
2950                                                       &num_sids);
2951                         if (!NT_STATUS_IS_OK(ret)) {
2952                                 goto done;
2953                         }
2954                 }
2955         }
2956
2957         if (sid_compare(&global_sid_NULL, &(*pp_sids)[0]) == 0) {
2958                 DEBUG(3, ("primary group of [%s] not found\n",
2959                           pdb_get_username(user)));
2960                 goto done;
2961         }
2962
2963         *p_num_groups = num_sids;
2964
2965         ret = NT_STATUS_OK;
2966
2967  done:
2968
2969         TALLOC_FREE(escape_name);
2970         return ret;
2971 }
2972
2973 /**********************************************************************
2974  * Augment a posixGroup object with a sambaGroupMapping domgroup
2975  *********************************************************************/
2976
2977 static NTSTATUS ldapsam_map_posixgroup(TALLOC_CTX *mem_ctx,
2978                                        struct ldapsam_privates *ldap_state,
2979                                        GROUP_MAP *map)
2980 {
2981         const char *filter, *dn;
2982         LDAPMessage *msg, *entry;
2983         LDAPMod **mods;
2984         int rc;
2985
2986         filter = talloc_asprintf(mem_ctx,
2987                                  "(&(objectClass=%s)(gidNumber=%u))",
2988                                  LDAP_OBJ_POSIXGROUP, (unsigned int)map->gid);
2989         if (filter == NULL) {
2990                 return NT_STATUS_NO_MEMORY;
2991         }
2992
2993         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
2994                                    get_attr_list(mem_ctx, groupmap_attr_list),
2995                                    &msg);
2996         talloc_autofree_ldapmsg(mem_ctx, msg);
2997
2998         if ((rc != LDAP_SUCCESS) ||
2999             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3000             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3001                 return NT_STATUS_NO_SUCH_GROUP;
3002         }
3003
3004         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3005         if (dn == NULL) {
3006                 return NT_STATUS_NO_MEMORY;
3007         }
3008
3009         mods = NULL;
3010         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass",
3011                         LDAP_OBJ_GROUPMAP);
3012         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaSid",
3013                          sid_string_talloc(mem_ctx, &map->sid));
3014         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "sambaGroupType",
3015                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3016         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3017                          map->nt_name);
3018         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3019                          map->comment);
3020         talloc_autofree_ldapmod(mem_ctx, mods);
3021
3022         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3023         if (rc != LDAP_SUCCESS) {
3024                 return NT_STATUS_ACCESS_DENIED;
3025         }
3026
3027         return NT_STATUS_OK;
3028 }
3029
3030 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
3031                                                 GROUP_MAP *map)
3032 {
3033         struct ldapsam_privates *ldap_state =
3034                 (struct ldapsam_privates *)methods->private_data;
3035         LDAPMessage *msg = NULL;
3036         LDAPMod **mods = NULL;
3037         const char *attrs[] = { NULL };
3038         char *filter;
3039
3040         char *dn;
3041         TALLOC_CTX *mem_ctx;
3042         NTSTATUS result;
3043
3044         DOM_SID sid;
3045
3046         int rc;
3047
3048         mem_ctx = talloc_new(NULL);
3049         if (mem_ctx == NULL) {
3050                 DEBUG(0, ("talloc_new failed\n"));
3051                 return NT_STATUS_NO_MEMORY;
3052         }
3053
3054         filter = talloc_asprintf(mem_ctx, "(sambaSid=%s)",
3055                                  sid_string_talloc(mem_ctx, &map->sid));
3056         if (filter == NULL) {
3057                 result = NT_STATUS_NO_MEMORY;
3058                 goto done;
3059         }
3060
3061         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3062                             LDAP_SCOPE_SUBTREE, filter, attrs, True, &msg);
3063         talloc_autofree_ldapmsg(mem_ctx, msg);
3064
3065         if ((rc == LDAP_SUCCESS) &&
3066             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) > 0)) {
3067
3068                 DEBUG(3, ("SID %s already present in LDAP, refusing to add "
3069                           "group mapping entry\n", sid_string_dbg(&map->sid)));
3070                 result = NT_STATUS_GROUP_EXISTS;
3071                 goto done;
3072         }
3073
3074         switch (map->sid_name_use) {
3075
3076         case SID_NAME_DOM_GRP:
3077                 /* To map a domain group we need to have a posix group
3078                    to attach to. */
3079                 result = ldapsam_map_posixgroup(mem_ctx, ldap_state, map);
3080                 goto done;
3081                 break;
3082
3083         case SID_NAME_ALIAS:
3084                 if (!sid_check_is_in_our_domain(&map->sid) 
3085                         && !sid_check_is_in_builtin(&map->sid) ) 
3086                 {
3087                         DEBUG(3, ("Refusing to map sid %s as an alias, not in our domain\n",
3088                                   sid_string_dbg(&map->sid)));
3089                         result = NT_STATUS_INVALID_PARAMETER;
3090                         goto done;
3091                 }
3092                 break;
3093
3094         default:
3095                 DEBUG(3, ("Got invalid use '%s' for mapping\n",
3096                           sid_type_lookup(map->sid_name_use)));
3097                 result = NT_STATUS_INVALID_PARAMETER;
3098                 goto done;
3099         }
3100
3101         /* Domain groups have been mapped in a separate routine, we have to
3102          * create an alias now */
3103
3104         if (map->gid == -1) {
3105                 DEBUG(10, ("Refusing to map gid==-1\n"));
3106                 result = NT_STATUS_INVALID_PARAMETER;
3107                 goto done;
3108         }
3109
3110         if (pdb_gid_to_sid(map->gid, &sid)) {
3111                 DEBUG(3, ("Gid %u is already mapped to SID %s, refusing to "
3112                           "add\n", (unsigned int)map->gid, sid_string_dbg(&sid)));
3113                 result = NT_STATUS_GROUP_EXISTS;
3114                 goto done;
3115         }
3116
3117         /* Ok, enough checks done. It's still racy to go ahead now, but that's
3118          * the best we can get out of LDAP. */
3119
3120         dn = talloc_asprintf(mem_ctx, "sambaSid=%s,%s",
3121                              sid_string_talloc(mem_ctx, &map->sid),
3122                              lp_ldap_group_suffix());
3123         if (dn == NULL) {
3124                 result = NT_STATUS_NO_MEMORY;
3125                 goto done;
3126         }
3127
3128         mods = NULL;
3129
3130         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3131                          LDAP_OBJ_SID_ENTRY);
3132         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "objectClass",
3133                          LDAP_OBJ_GROUPMAP);
3134         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaSid",
3135                          sid_string_talloc(mem_ctx, &map->sid));
3136         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "sambaGroupType",
3137                          talloc_asprintf(mem_ctx, "%d", map->sid_name_use));
3138         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "displayName",
3139                          map->nt_name);
3140         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "description",
3141                          map->comment);
3142         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, NULL, &mods, "gidNumber",
3143                          talloc_asprintf(mem_ctx, "%u", (unsigned int)map->gid));
3144         talloc_autofree_ldapmod(mem_ctx, mods);
3145
3146         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
3147
3148         result = (rc == LDAP_SUCCESS) ?
3149                 NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
3150
3151  done:
3152         TALLOC_FREE(mem_ctx);
3153         return result;
3154 }
3155
3156 /**********************************************************************
3157  * Update a group mapping entry. We're quite strict about what can be changed:
3158  * Only the description and displayname may be changed. It simply does not
3159  * make any sense to change the SID, gid or the type in a mapping.
3160  *********************************************************************/
3161
3162 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
3163                                                    GROUP_MAP *map)
3164 {
3165         struct ldapsam_privates *ldap_state =
3166                 (struct ldapsam_privates *)methods->private_data;
3167         int rc;
3168         const char *filter, *dn;
3169         LDAPMessage *msg = NULL;
3170         LDAPMessage *entry = NULL;
3171         LDAPMod **mods = NULL;
3172         TALLOC_CTX *mem_ctx;
3173         NTSTATUS result;
3174
3175         mem_ctx = talloc_new(NULL);
3176         if (mem_ctx == NULL) {
3177                 DEBUG(0, ("talloc_new failed\n"));
3178                 return NT_STATUS_NO_MEMORY;
3179         }
3180
3181         /* Make 100% sure that sid, gid and type are not changed by looking up
3182          * exactly the values we're given in LDAP. */
3183
3184         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)"
3185                                  "(sambaSid=%s)(gidNumber=%u)"
3186                                  "(sambaGroupType=%d))",
3187                                  LDAP_OBJ_GROUPMAP,
3188                                  sid_string_talloc(mem_ctx, &map->sid),
3189                                  (unsigned int)map->gid, map->sid_name_use);
3190         if (filter == NULL) {
3191                 result = NT_STATUS_NO_MEMORY;
3192                 goto done;
3193         }
3194
3195         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter,
3196                                    get_attr_list(mem_ctx, groupmap_attr_list),
3197                                    &msg);
3198         talloc_autofree_ldapmsg(mem_ctx, msg);
3199
3200         if ((rc != LDAP_SUCCESS) ||
3201             (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, msg) != 1) ||
3202             ((entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, msg)) == NULL)) {
3203                 result = NT_STATUS_NO_SUCH_GROUP;
3204                 goto done;
3205         }
3206
3207         dn = smbldap_talloc_dn(mem_ctx, ldap_state->smbldap_state->ldap_struct, entry);
3208
3209         if (dn == NULL) {
3210                 result = NT_STATUS_NO_MEMORY;
3211                 goto done;
3212         }
3213
3214         mods = NULL;
3215         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "displayName",
3216                          map->nt_name);
3217         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, entry, &mods, "description",
3218                          map->comment);
3219         talloc_autofree_ldapmod(mem_ctx, mods);
3220
3221         if (mods == NULL) {
3222                 DEBUG(4, ("ldapsam_update_group_mapping_entry: mods is empty: "
3223                           "nothing to do\n"));
3224                 result = NT_STATUS_OK;
3225                 goto done;
3226         }
3227
3228         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3229
3230         if (rc != LDAP_SUCCESS) {
3231                 result = NT_STATUS_ACCESS_DENIED;
3232                 goto done;
3233         }
3234
3235         DEBUG(2, ("ldapsam_update_group_mapping_entry: successfully modified "
3236                   "group %lu in LDAP\n", (unsigned long)map->gid));
3237
3238         result = NT_STATUS_OK;
3239
3240  done:
3241         TALLOC_FREE(mem_ctx);
3242         return result;
3243 }
3244
3245 /**********************************************************************
3246  *********************************************************************/
3247
3248 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
3249                                                    DOM_SID sid)
3250 {
3251         struct ldapsam_privates *priv =
3252                 (struct ldapsam_privates *)methods->private_data;
3253         LDAPMessage *msg, *entry;
3254         int rc;
3255         NTSTATUS result;
3256         TALLOC_CTX *mem_ctx;
3257         char *filter;
3258
3259         mem_ctx = talloc_new(NULL);
3260         if (mem_ctx == NULL) {
3261                 DEBUG(0, ("talloc_new failed\n"));
3262                 return NT_STATUS_NO_MEMORY;
3263         }
3264
3265         filter = talloc_asprintf(mem_ctx, "(&(objectClass=%s)(%s=%s))",
3266                                  LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID,
3267                                  sid_string_talloc(mem_ctx, &sid));
3268         if (filter == NULL) {
3269                 result = NT_STATUS_NO_MEMORY;
3270                 goto done;
3271         }
3272         rc = smbldap_search_suffix(priv->smbldap_state, filter,
3273                                    get_attr_list(mem_ctx, groupmap_attr_list),
3274                                    &msg);
3275         talloc_autofree_ldapmsg(mem_ctx, msg);
3276
3277         if ((rc != LDAP_SUCCESS) ||
3278             (ldap_count_entries(priv2ld(priv), msg) != 1) ||
3279             ((entry = ldap_first_entry(priv2ld(priv), msg)) == NULL)) {
3280                 result = NT_STATUS_NO_SUCH_GROUP;
3281                 goto done;
3282         }
3283
3284         rc = ldapsam_delete_entry(priv, mem_ctx, entry, LDAP_OBJ_GROUPMAP,
3285                                   get_attr_list(mem_ctx,
3286                                                 groupmap_attr_list_to_delete));
3287
3288         if ((rc == LDAP_NAMING_VIOLATION) ||
3289             (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3290             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3291                 const char *attrs[] = { "sambaGroupType", "description",
3292                                         "displayName", "sambaSIDList",
3293                                         NULL };
3294
3295                 /* Second try. Don't delete the sambaSID attribute, this is
3296                    for "old" entries that are tacked on a winbind
3297                    sambaIdmapEntry. */
3298
3299                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3300                                           LDAP_OBJ_GROUPMAP, attrs);
3301         }
3302
3303         if ((rc == LDAP_NAMING_VIOLATION) ||
3304             (rc == LDAP_NOT_ALLOWED_ON_RDN) ||
3305             (rc == LDAP_OBJECT_CLASS_VIOLATION)) {
3306                 const char *attrs[] = { "sambaGroupType", "description",
3307                                         "displayName", "sambaSIDList",
3308                                         "gidNumber", NULL };
3309
3310                 /* Third try. This is a post-3.0.21 alias (containing only
3311                  * sambaSidEntry and sambaGroupMapping classes), we also have
3312                  * to delete the gidNumber attribute, only the sambaSidEntry
3313                  * remains */
3314
3315                 rc = ldapsam_delete_entry(priv, mem_ctx, entry,
3316                                           LDAP_OBJ_GROUPMAP, attrs);
3317         }
3318
3319         result = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_UNSUCCESSFUL;
3320
3321  done:
3322         TALLOC_FREE(mem_ctx);
3323         return result;
3324  }
3325
3326 /**********************************************************************
3327  *********************************************************************/
3328
3329 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods,
3330                                     bool update)
3331 {
3332         struct ldapsam_privates *ldap_state =
3333                 (struct ldapsam_privates *)my_methods->private_data;
3334         char *filter = NULL;
3335         int rc;
3336         const char **attr_list;
3337
3338         filter = talloc_asprintf(NULL, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
3339         if (!filter) {
3340                 return NT_STATUS_NO_MEMORY;
3341         }
3342         attr_list = get_attr_list( NULL, groupmap_attr_list );
3343         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3344                             LDAP_SCOPE_SUBTREE, filter,
3345                             attr_list, 0, &ldap_state->result);
3346         TALLOC_FREE(attr_list);
3347
3348         if (rc != LDAP_SUCCESS) {
3349                 DEBUG(0, ("ldapsam_setsamgrent: LDAP search failed: %s\n",
3350                           ldap_err2string(rc)));
3351                 DEBUG(3, ("ldapsam_setsamgrent: Query was: %s, %s\n",
3352                           lp_ldap_suffix(), filter));
3353                 ldap_msgfree(ldap_state->result);
3354                 ldap_state->result = NULL;
3355                 TALLOC_FREE(filter);
3356                 return NT_STATUS_UNSUCCESSFUL;
3357         }
3358
3359         TALLOC_FREE(filter);
3360
3361         DEBUG(2, ("ldapsam_setsamgrent: %d entries in the base!\n",
3362                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3363                                      ldap_state->result)));
3364
3365         ldap_state->entry =
3366                 ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3367                                  ldap_state->result);
3368         ldap_state->index = 0;
3369
3370         return NT_STATUS_OK;
3371 }
3372
3373 /**********************************************************************
3374  *********************************************************************/
3375
3376 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
3377 {
3378         ldapsam_endsampwent(my_methods);
3379 }
3380
3381 /**********************************************************************
3382  *********************************************************************/
3383
3384 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
3385                                     GROUP_MAP *map)
3386 {
3387         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
3388         struct ldapsam_privates *ldap_state =
3389                 (struct ldapsam_privates *)my_methods->private_data;
3390         bool bret = False;
3391
3392         while (!bret) {
3393                 if (!ldap_state->entry)
3394                         return ret;
3395
3396                 ldap_state->index++;
3397                 bret = init_group_from_ldap(ldap_state, map,
3398                                             ldap_state->entry);
3399
3400                 ldap_state->entry =
3401                         ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
3402                                         ldap_state->entry);     
3403         }
3404
3405         return NT_STATUS_OK;
3406 }
3407
3408 /**********************************************************************
3409  *********************************************************************/
3410
3411 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
3412                                            const DOM_SID *domsid, enum lsa_SidType sid_name_use,
3413                                            GROUP_MAP **pp_rmap,
3414                                            size_t *p_num_entries,
3415                                            bool unix_only)
3416 {
3417         GROUP_MAP map;
3418         size_t entries = 0;
3419
3420         *p_num_entries = 0;
3421         *pp_rmap = NULL;
3422
3423         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
3424                 DEBUG(0, ("ldapsam_enum_group_mapping: Unable to open "
3425                           "passdb\n"));
3426                 return NT_STATUS_ACCESS_DENIED;
3427         }
3428
3429         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
3430                 if (sid_name_use != SID_NAME_UNKNOWN &&
3431                     sid_name_use != map.sid_name_use) {
3432                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3433                                   "not of the requested type\n", map.nt_name));
3434                         continue;
3435                 }
3436                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
3437                         DEBUG(11,("ldapsam_enum_group_mapping: group %s is "
3438                                   "non mapped\n", map.nt_name));
3439                         continue;
3440                 }
3441
3442                 (*pp_rmap)=SMB_REALLOC_ARRAY((*pp_rmap), GROUP_MAP, entries+1);
3443                 if (!(*pp_rmap)) {
3444                         DEBUG(0,("ldapsam_enum_group_mapping: Unable to "
3445                                  "enlarge group map!\n"));
3446                         return NT_STATUS_UNSUCCESSFUL;
3447                 }
3448
3449                 (*pp_rmap)[entries] = map;
3450
3451                 entries += 1;
3452
3453         }
3454         ldapsam_endsamgrent(methods);
3455
3456         *p_num_entries = entries;
3457
3458         return NT_STATUS_OK;
3459 }
3460
3461 static NTSTATUS ldapsam_modify_aliasmem(struct pdb_methods *methods,
3462                                         const DOM_SID *alias,
3463                                         const DOM_SID *member,
3464                                         int modop)
3465 {
3466         struct ldapsam_privates *ldap_state =
3467                 (struct ldapsam_privates *)methods->private_data;
3468         char *dn = NULL;
3469         LDAPMessage *result = NULL;
3470         LDAPMessage *entry = NULL;
3471         int count;
3472         LDAPMod **mods = NULL;
3473         int rc;
3474         enum lsa_SidType type = SID_NAME_USE_NONE;
3475         fstring tmp;
3476
3477         char *filter = NULL;
3478
3479         if (sid_check_is_in_builtin(alias)) {
3480                 type = SID_NAME_ALIAS;
3481         }
3482
3483         if (sid_check_is_in_our_domain(alias)) {
3484                 type = SID_NAME_ALIAS;
3485         }
3486
3487         if (type == SID_NAME_USE_NONE) {
3488                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3489                           sid_string_dbg(alias)));
3490                 return NT_STATUS_NO_SUCH_ALIAS;
3491         }
3492
3493         if (asprintf(&filter,
3494                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3495                      LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3496                      type) < 0) {
3497                 return NT_STATUS_NO_MEMORY;
3498         }
3499
3500         if (ldapsam_search_one_group(ldap_state, filter,
3501                                      &result) != LDAP_SUCCESS) {
3502                 SAFE_FREE(filter);
3503                 return NT_STATUS_NO_SUCH_ALIAS;
3504         }
3505
3506         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3507                                    result);
3508
3509         if (count < 1) {
3510                 DEBUG(4, ("ldapsam_modify_aliasmem: Did not find alias\n"));
3511                 ldap_msgfree(result);
3512                 SAFE_FREE(filter);
3513                 return NT_STATUS_NO_SUCH_ALIAS;
3514         }
3515
3516         if (count > 1) {
3517                 DEBUG(1, ("ldapsam_modify_aliasmem: Duplicate entries for "
3518                           "filter %s: count=%d\n", filter, count));
3519                 ldap_msgfree(result);
3520                 SAFE_FREE(filter);
3521                 return NT_STATUS_NO_SUCH_ALIAS;
3522         }
3523
3524         SAFE_FREE(filter);
3525
3526         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3527                                  result);
3528
3529         if (!entry) {
3530                 ldap_msgfree(result);
3531                 return NT_STATUS_UNSUCCESSFUL;
3532         }
3533
3534         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
3535         if (!dn) {
3536                 ldap_msgfree(result);
3537                 return NT_STATUS_UNSUCCESSFUL;
3538         }
3539
3540         smbldap_set_mod(&mods, modop,
3541                         get_attr_key2string(groupmap_attr_list,
3542                                             LDAP_ATTR_SID_LIST),
3543                         sid_to_fstring(tmp, member));
3544
3545         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
3546
3547         ldap_mods_free(mods, True);
3548         ldap_msgfree(result);
3549         TALLOC_FREE(dn);
3550
3551         if (rc == LDAP_TYPE_OR_VALUE_EXISTS) {
3552                 return NT_STATUS_MEMBER_IN_ALIAS;
3553         }
3554
3555         if (rc == LDAP_NO_SUCH_ATTRIBUTE) {
3556                 return NT_STATUS_MEMBER_NOT_IN_ALIAS;
3557         }
3558
3559         if (rc != LDAP_SUCCESS) {
3560                 return NT_STATUS_UNSUCCESSFUL;
3561         }
3562
3563         return NT_STATUS_OK;
3564 }
3565
3566 static NTSTATUS ldapsam_add_aliasmem(struct pdb_methods *methods,
3567                                      const DOM_SID *alias,
3568                                      const DOM_SID *member)
3569 {
3570         return ldapsam_modify_aliasmem(methods, alias, member, LDAP_MOD_ADD);
3571 }
3572
3573 static NTSTATUS ldapsam_del_aliasmem(struct pdb_methods *methods,
3574                                      const DOM_SID *alias,
3575                                      const DOM_SID *member)
3576 {
3577         return ldapsam_modify_aliasmem(methods, alias, member,
3578                                        LDAP_MOD_DELETE);
3579 }
3580
3581 static NTSTATUS ldapsam_enum_aliasmem(struct pdb_methods *methods,
3582                                       const DOM_SID *alias,
3583                                       TALLOC_CTX *mem_ctx,
3584                                       DOM_SID **pp_members,
3585                                       size_t *p_num_members)
3586 {
3587         struct ldapsam_privates *ldap_state =
3588                 (struct ldapsam_privates *)methods->private_data;
3589         LDAPMessage *result = NULL;
3590         LDAPMessage *entry = NULL;
3591         int count;
3592         char **values = NULL;
3593         int i;
3594         char *filter = NULL;
3595         size_t num_members = 0;
3596         enum lsa_SidType type = SID_NAME_USE_NONE;
3597         fstring tmp;
3598
3599         *pp_members = NULL;
3600         *p_num_members = 0;
3601
3602         if (sid_check_is_in_builtin(alias)) {
3603                 type = SID_NAME_ALIAS;
3604         }
3605
3606         if (sid_check_is_in_our_domain(alias)) {
3607                 type = SID_NAME_ALIAS;
3608         }
3609
3610         if (type == SID_NAME_USE_NONE) {
3611                 DEBUG(5, ("SID %s is neither in builtin nor in our domain!\n",
3612                           sid_string_dbg(alias)));
3613                 return NT_STATUS_NO_SUCH_ALIAS;
3614         }
3615
3616         if (asprintf(&filter,
3617                      "(&(objectClass=%s)(sambaSid=%s)(sambaGroupType=%d))",
3618                      LDAP_OBJ_GROUPMAP, sid_to_fstring(tmp, alias),
3619                      type) < 0) {
3620                 return NT_STATUS_NO_MEMORY;
3621         }
3622
3623         if (ldapsam_search_one_group(ldap_state, filter,
3624                                      &result) != LDAP_SUCCESS) {
3625                 SAFE_FREE(filter);
3626                 return NT_STATUS_NO_SUCH_ALIAS;
3627         }
3628
3629         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
3630                                    result);
3631
3632         if (count < 1) {
3633                 DEBUG(4, ("ldapsam_enum_aliasmem: Did not find alias\n"));
3634                 ldap_msgfree(result);
3635                 SAFE_FREE(filter);
3636                 return NT_STATUS_NO_SUCH_ALIAS;
3637         }
3638
3639         if (count > 1) {
3640                 DEBUG(1, ("ldapsam_enum_aliasmem: Duplicate entries for "
3641                           "filter %s: count=%d\n", filter, count));
3642                 ldap_msgfree(result);
3643                 SAFE_FREE(filter);
3644                 return NT_STATUS_NO_SUCH_ALIAS;
3645         }
3646
3647         SAFE_FREE(filter);
3648
3649         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
3650                                  result);
3651
3652         if (!entry) {
3653                 ldap_msgfree(result);
3654                 return NT_STATUS_UNSUCCESSFUL;
3655         }
3656
3657         values = ldap_get_values(ldap_state->smbldap_state->ldap_struct,
3658                                  entry,
3659                                  get_attr_key2string(groupmap_attr_list,
3660                                                      LDAP_ATTR_SID_LIST));
3661
3662         if (values == NULL) {
3663                 ldap_msgfree(result);
3664                 return NT_STATUS_OK;
3665         }
3666
3667         count = ldap_count_values(values);
3668
3669         for (i=0; i<count; i++) {
3670                 DOM_SID member;
3671                 NTSTATUS status;
3672
3673                 if (!string_to_sid(&member, values[i]))
3674                         continue;
3675
3676                 status = add_sid_to_array(mem_ctx, &member, pp_members,
3677                                           &num_members);
3678                 if (!NT_STATUS_IS_OK(status)) {
3679                         ldap_value_free(values);
3680                         ldap_msgfree(result);
3681                         return status;
3682                 }
3683         }
3684
3685         *p_num_members = num_members;
3686         ldap_value_free(values);
3687         ldap_msgfree(result);
3688
3689         return NT_STATUS_OK;
3690 }
3691
3692 static NTSTATUS ldapsam_alias_memberships(struct pdb_methods *methods,
3693                                           TALLOC_CTX *mem_ctx,
3694                                           const DOM_SID *domain_sid,
3695                                           const DOM_SID *members,
3696                                           size_t num_members,
3697                                           uint32 **pp_alias_rids,
3698                                           size_t *p_num_alias_rids)
3699 {
3700         struct ldapsam_privates *ldap_state =
3701                 (struct ldapsam_privates *)methods->private_data;
3702         LDAP *ldap_struct;
3703
3704         const char *attrs[] = { LDAP_ATTRIBUTE_SID, NULL };
3705
3706         LDAPMessage *result = NULL;
3707         LDAPMessage *entry = NULL;
3708         int i;
3709         int rc;
3710         char *filter;
3711         enum lsa_SidType type = SID_NAME_USE_NONE;
3712
3713         if (sid_check_is_builtin(domain_sid)) {
3714                 type = SID_NAME_ALIAS;
3715         }
3716
3717         if (sid_check_is_domain(domain_sid)) {
3718                 type = SID_NAME_ALIAS;
3719         }
3720
3721         if (type == SID_NAME_USE_NONE) {
3722                 DEBUG(5, ("SID %s is neither builtin nor domain!\n",
3723                           sid_string_dbg(domain_sid)));
3724                 return NT_STATUS_UNSUCCESSFUL;
3725         }
3726
3727         filter = talloc_asprintf(mem_ctx,
3728                                  "(&(|(objectclass=%s)(sambaGroupType=%d))(|",
3729                                  LDAP_OBJ_GROUPMAP, type);
3730
3731         for (i=0; i<num_members; i++)
3732                 filter = talloc_asprintf(mem_ctx, "%s(sambaSIDList=%s)",
3733                                          filter,
3734                                          sid_string_talloc(mem_ctx,
3735                                                            &members[i]));
3736
3737         filter = talloc_asprintf(mem_ctx, "%s))", filter);
3738
3739         if (filter == NULL) {
3740                 return NT_STATUS_NO_MEMORY;
3741         }
3742
3743         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_suffix(),
3744                             LDAP_SCOPE_SUBTREE, filter, attrs, 0, &result);
3745
3746         if (rc != LDAP_SUCCESS)
3747                 return NT_STATUS_UNSUCCESSFUL;
3748
3749         ldap_struct = ldap_state->smbldap_state->ldap_struct;
3750
3751         for (entry = ldap_first_entry(ldap_struct, result);
3752              entry != NULL;
3753              entry = ldap_next_entry(ldap_struct, entry))
3754         {
3755                 fstring sid_str;
3756                 DOM_SID sid;
3757                 uint32 rid;
3758
3759                 if (!smbldap_get_single_attribute(ldap_struct, entry,
3760                                                   LDAP_ATTRIBUTE_SID,
3761                                                   sid_str,
3762                                                   sizeof(sid_str)-1))
3763                         continue;
3764
3765                 if (!string_to_sid(&sid, sid_str))
3766                         continue;
3767
3768                 if (!sid_peek_check_rid(domain_sid, &sid, &rid))
3769                         continue;
3770
3771                 if (!add_rid_to_array_unique(mem_ctx, rid, pp_alias_rids,
3772                                         p_num_alias_rids)) {
3773                         ldap_msgfree(result);
3774                         return NT_STATUS_NO_MEMORY;
3775                 }
3776         }
3777
3778         ldap_msgfree(result);
3779         return NT_STATUS_OK;
3780 }
3781
3782 static NTSTATUS ldapsam_set_account_policy_in_ldap(struct pdb_methods *methods,
3783                                                    enum pdb_policy_type type,
3784                                                    uint32 value)
3785 {
3786         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3787         int rc;
3788         LDAPMod **mods = NULL;
3789         fstring value_string;
3790         const char *policy_attr = NULL;
3791
3792         struct ldapsam_privates *ldap_state =
3793                 (struct ldapsam_privates *)methods->private_data;
3794
3795         DEBUG(10,("ldapsam_set_account_policy_in_ldap\n"));
3796
3797         if (!ldap_state->domain_dn) {
3798                 return NT_STATUS_INVALID_PARAMETER;
3799         }
3800
3801         policy_attr = get_account_policy_attr(type);
3802         if (policy_attr == NULL) {
3803                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: invalid "
3804                          "policy\n"));
3805                 return ntstatus;
3806         }
3807
3808         slprintf(value_string, sizeof(value_string) - 1, "%i", value);
3809
3810         smbldap_set_mod(&mods, LDAP_MOD_REPLACE, policy_attr, value_string);
3811
3812         rc = smbldap_modify(ldap_state->smbldap_state, ldap_state->domain_dn,
3813                             mods);
3814
3815         ldap_mods_free(mods, True);
3816
3817         if (rc != LDAP_SUCCESS) {
3818                 return ntstatus;
3819         }
3820
3821         if (!cache_account_policy_set(type, value)) {
3822                 DEBUG(0,("ldapsam_set_account_policy_in_ldap: failed to "
3823                          "update local tdb cache\n"));
3824                 return ntstatus;
3825         }
3826
3827         return NT_STATUS_OK;
3828 }
3829
3830 static NTSTATUS ldapsam_set_account_policy(struct pdb_methods *methods,
3831                                            enum pdb_policy_type type,
3832                                            uint32_t value)
3833 {
3834         return ldapsam_set_account_policy_in_ldap(methods, type,
3835                                                   value);
3836 }
3837
3838 static NTSTATUS ldapsam_get_account_policy_from_ldap(struct pdb_methods *methods,
3839                                                      enum pdb_policy_type type,
3840                                                      uint32 *value)
3841 {
3842         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3843         LDAPMessage *result = NULL;
3844         LDAPMessage *entry = NULL;
3845         int count;
3846         int rc;
3847         char **vals = NULL;
3848         const char *policy_attr = NULL;
3849
3850         struct ldapsam_privates *ldap_state =
3851                 (struct ldapsam_privates *)methods->private_data;
3852
3853         const char *attrs[2];
3854
3855         DEBUG(10,("ldapsam_get_account_policy_from_ldap\n"));
3856
3857         if (!ldap_state->domain_dn) {
3858                 return NT_STATUS_INVALID_PARAMETER;
3859         }
3860
3861         policy_attr = get_account_policy_attr(type);
3862         if (!policy_attr) {
3863                 DEBUG(0,("ldapsam_get_account_policy_from_ldap: invalid "
3864                          "policy index: %d\n", type));
3865                 return ntstatus;
3866         }
3867
3868         attrs[0] = policy_attr;
3869         attrs[1] = NULL;
3870
3871         rc = smbldap_search(ldap_state->smbldap_state, ldap_state->domain_dn,
3872                             LDAP_SCOPE_BASE, "(objectclass=*)", attrs, 0,
3873                             &result);
3874
3875         if (rc != LDAP_SUCCESS) {
3876                 return ntstatus;
3877         }
3878
3879         count = ldap_count_entries(priv2ld(ldap_state), result);
3880         if (count < 1) {
3881                 goto out;
3882         }
3883
3884         entry = ldap_first_entry(priv2ld(ldap_state), result);
3885         if (entry == NULL) {
3886                 goto out;
3887         }
3888
3889         vals = ldap_get_values(priv2ld(ldap_state), entry, policy_attr);
3890         if (vals == NULL) {
3891                 goto out;
3892         }
3893
3894         *value = (uint32)atol(vals[0]);
3895
3896         ntstatus = NT_STATUS_OK;
3897
3898 out:
3899         if (vals)
3900                 ldap_value_free(vals);
3901         ldap_msgfree(result);
3902
3903         return ntstatus;
3904 }
3905
3906 /* wrapper around ldapsam_get_account_policy_from_ldap(), handles tdb as cache 
3907
3908    - if user hasn't decided to use account policies inside LDAP just reuse the
3909      old tdb values
3910
3911    - if there is a valid cache entry, return that
3912    - if there is an LDAP entry, update cache and return 
3913    - otherwise set to default, update cache and return
3914
3915    Guenther
3916 */
3917 static NTSTATUS ldapsam_get_account_policy(struct pdb_methods *methods,
3918                                            enum pdb_policy_type type,
3919                                            uint32_t *value)
3920 {
3921         NTSTATUS ntstatus = NT_STATUS_UNSUCCESSFUL;
3922
3923         if (cache_account_policy_get(type, value)) {
3924                 DEBUG(11,("ldapsam_get_account_policy: got valid value from "
3925                           "cache\n"));
3926                 return NT_STATUS_OK;
3927         }
3928
3929         ntstatus = ldapsam_get_account_policy_from_ldap(methods, type,
3930                                                         value);
3931         if (NT_STATUS_IS_OK(ntstatus)) {
3932                 goto update_cache;
3933         }
3934
3935         DEBUG(10,("ldapsam_get_account_policy: failed to retrieve from "
3936                   "ldap\n"));
3937
3938 #if 0
3939         /* should we automagically migrate old tdb value here ? */
3940         if (account_policy_get(type, value))
3941                 goto update_ldap;
3942
3943         DEBUG(10,("ldapsam_get_account_policy: no tdb for %d, trying "
3944                   "default\n", type));
3945 #endif
3946
3947         if (!account_policy_get_default(type, value)) {
3948                 return ntstatus;
3949         }
3950
3951 /* update_ldap: */
3952
3953         ntstatus = ldapsam_set_account_policy(methods, type, *value);
3954         if (!NT_STATUS_IS_OK(ntstatus)) {
3955                 return ntstatus;
3956         }
3957
3958  update_cache:
3959
3960         if (!cache_account_policy_set(type, *value)) {
3961                 DEBUG(0,("ldapsam_get_account_policy: failed to update local "
3962                          "tdb as a cache\n"));
3963                 return NT_STATUS_UNSUCCESSFUL;
3964         }
3965
3966         return NT_STATUS_OK;
3967 }
3968
3969 static NTSTATUS ldapsam_lookup_rids(struct pdb_methods *methods,
3970                                     const DOM_SID *domain_sid,
3971                                     int num_rids,
3972                                     uint32 *rids,
3973                                     const char **names,
3974                                     enum lsa_SidType *attrs)
3975 {
3976         struct ldapsam_privates *ldap_state =
3977                 (struct ldapsam_privates *)methods->private_data;
3978         LDAPMessage *msg = NULL;
3979         LDAPMessage *entry;
3980         char *allsids = NULL;
3981         int i, rc, num_mapped;
3982         NTSTATUS result = NT_STATUS_NO_MEMORY;
3983         TALLOC_CTX *mem_ctx;
3984         LDAP *ld;
3985         bool is_builtin;
3986
3987         mem_ctx = talloc_new(NULL);
3988         if (mem_ctx == NULL) {
3989                 DEBUG(0, ("talloc_new failed\n"));
3990                 goto done;
3991         }
3992
3993         if (!sid_check_is_builtin(domain_sid) &&
3994             !sid_check_is_domain(domain_sid)) {
3995                 result = NT_STATUS_INVALID_PARAMETER;
3996                 goto done;
3997         }
3998
3999         if (num_rids == 0) {
4000                 result = NT_STATUS_NONE_MAPPED;
4001                 goto done;
4002         }
4003
4004         for (i=0; i<num_rids; i++)
4005                 attrs[i] = SID_NAME_UNKNOWN;
4006
4007         allsids = talloc_strdup(mem_ctx, "");
4008         if (allsids == NULL) {
4009                 goto done;
4010         }
4011
4012         for (i=0; i<num_rids; i++) {
4013                 DOM_SID sid;
4014                 sid_compose(&sid, domain_sid, rids[i]);
4015                 allsids = talloc_asprintf_append_buffer(
4016                         allsids, "(sambaSid=%s)",
4017                         sid_string_talloc(mem_ctx, &sid));
4018                 if (allsids == NULL) {
4019                         goto done;
4020                 }
4021         }
4022
4023         /* First look for users */
4024
4025         {
4026                 char *filter;
4027                 const char *ldap_attrs[] = { "uid", "sambaSid", NULL };
4028
4029                 filter = talloc_asprintf(
4030                         mem_ctx, ("(&(objectClass=%s)(|%s))"),
4031                         LDAP_OBJ_SAMBASAMACCOUNT, allsids);
4032
4033                 if (filter == NULL) {
4034                         goto done;
4035                 }
4036
4037                 rc = smbldap_search(ldap_state->smbldap_state,
4038                                     lp_ldap_user_suffix(),
4039                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4040                                     &msg);
4041                 talloc_autofree_ldapmsg(mem_ctx, msg);
4042         }
4043
4044         if (rc != LDAP_SUCCESS)
4045                 goto done;
4046
4047         ld = ldap_state->smbldap_state->ldap_struct;
4048         num_mapped = 0;
4049
4050         for (entry = ldap_first_entry(ld, msg);
4051              entry != NULL;
4052              entry = ldap_next_entry(ld, entry)) {
4053                 uint32 rid;
4054                 int rid_index;
4055                 const char *name;
4056
4057                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4058                                                     &rid)) {
4059                         DEBUG(2, ("Could not find sid from ldap entry\n"));
4060                         continue;
4061                 }
4062
4063                 name = smbldap_talloc_single_attribute(ld, entry, "uid",
4064                                                        names);
4065                 if (name == NULL) {
4066                         DEBUG(2, ("Could not retrieve uid attribute\n"));
4067                         continue;
4068                 }
4069
4070                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4071                         if (rid == rids[rid_index])
4072                                 break;
4073                 }
4074
4075                 if (rid_index == num_rids) {
4076                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4077                         continue;
4078                 }
4079
4080                 attrs[rid_index] = SID_NAME_USER;
4081                 names[rid_index] = name;
4082                 num_mapped += 1;
4083         }
4084
4085         if (num_mapped == num_rids) {
4086                 /* No need to look for groups anymore -- we're done */
4087                 result = NT_STATUS_OK;
4088                 goto done;
4089         }
4090
4091         /* Same game for groups */
4092
4093         {
4094                 char *filter;
4095                 const char *ldap_attrs[] = { "cn", "displayName", "sambaSid",
4096                                              "sambaGroupType", NULL };
4097
4098                 filter = talloc_asprintf(
4099                         mem_ctx, "(&(objectClass=%s)(|%s))",
4100                         LDAP_OBJ_GROUPMAP, allsids);
4101                 if (filter == NULL) {
4102                         goto done;
4103                 }
4104
4105                 rc = smbldap_search(ldap_state->smbldap_state,
4106                                     lp_ldap_suffix(),
4107                                     LDAP_SCOPE_SUBTREE, filter, ldap_attrs, 0,
4108                                     &msg);
4109                 talloc_autofree_ldapmsg(mem_ctx, msg);
4110         }
4111
4112         if (rc != LDAP_SUCCESS)
4113                 goto done;
4114
4115         /* ldap_struct might have changed due to a reconnect */
4116
4117         ld = ldap_state->smbldap_state->ldap_struct;
4118
4119         /* For consistency checks, we already checked we're only domain or builtin */
4120
4121         is_builtin = sid_check_is_builtin(domain_sid);
4122
4123         for (entry = ldap_first_entry(ld, msg);
4124              entry != NULL;
4125              entry = ldap_next_entry(ld, entry))
4126         {
4127                 uint32 rid;
4128                 int rid_index;
4129                 const char *attr;
4130                 enum lsa_SidType type;
4131                 const char *dn = smbldap_talloc_dn(mem_ctx, ld, entry);
4132
4133                 attr = smbldap_talloc_single_attribute(ld, entry, "sambaGroupType",
4134                                                        mem_ctx);
4135                 if (attr == NULL) {
4136                         DEBUG(2, ("Could not extract type from ldap entry %s\n",
4137                                   dn));
4138                         continue;
4139                 }
4140
4141                 type = (enum lsa_SidType)atol(attr);
4142
4143                 /* Consistency checks */
4144                 if ((is_builtin && (type != SID_NAME_ALIAS)) ||
4145                     (!is_builtin && ((type != SID_NAME_ALIAS) &&
4146                                      (type != SID_NAME_DOM_GRP)))) {
4147                         DEBUG(2, ("Rejecting invalid group mapping entry %s\n", dn));
4148                 }
4149
4150                 if (!ldapsam_extract_rid_from_entry(ld, entry, domain_sid,
4151                                                     &rid)) {
4152                         DEBUG(2, ("Could not find sid from ldap entry %s\n", dn));
4153                         continue;
4154                 }
4155
4156                 attr = smbldap_talloc_single_attribute(ld, entry, "displayName", names);
4157
4158                 if (attr == NULL) {
4159                         DEBUG(10, ("Could not retrieve 'displayName' attribute from %s\n",
4160                                    dn));
4161                         attr = smbldap_talloc_single_attribute(ld, entry, "cn", names);
4162                 }
4163
4164                 if (attr == NULL) {
4165                         DEBUG(2, ("Could not retrieve naming attribute from %s\n",
4166                                   dn));
4167                         continue;
4168                 }
4169
4170                 for (rid_index = 0; rid_index < num_rids; rid_index++) {
4171                         if (rid == rids[rid_index])
4172                                 break;
4173                 }
4174
4175                 if (rid_index == num_rids) {
4176                         DEBUG(2, ("Got a RID not asked for: %d\n", rid));
4177                         continue;
4178                 }
4179
4180                 attrs[rid_index] = type;
4181                 names[rid_index] = attr;
4182                 num_mapped += 1;
4183         }
4184
4185         result = NT_STATUS_NONE_MAPPED;
4186
4187         if (num_mapped > 0)
4188                 result = (num_mapped == num_rids) ?
4189                         NT_STATUS_OK : STATUS_SOME_UNMAPPED;
4190  done:
4191         TALLOC_FREE(mem_ctx);
4192         return result;
4193 }
4194
4195 static char *get_ldap_filter(TALLOC_CTX *mem_ctx, const char *username)
4196 {
4197         char *filter = NULL;
4198         char *escaped = NULL;
4199         char *result = NULL;
4200
4201         if (asprintf(&filter, "(&%s(objectclass=%s))",
4202                           "(uid=%u)", LDAP_OBJ_SAMBASAMACCOUNT) < 0) {
4203                 goto done;
4204         }
4205
4206         escaped = escape_ldap_string(talloc_tos(), username);
4207         if (escaped == NULL) goto done;
4208
4209         result = talloc_string_sub(mem_ctx, filter, "%u", username);
4210
4211  done:
4212         SAFE_FREE(filter);
4213         TALLOC_FREE(escaped);
4214
4215         return result;
4216 }
4217
4218 const char **talloc_attrs(TALLOC_CTX *mem_ctx, ...)
4219 {
4220         int i, num = 0;
4221         va_list ap;
4222         const char **result;
4223
4224         va_start(ap, mem_ctx);
4225         while (va_arg(ap, const char *) != NULL)
4226                 num += 1;
4227         va_end(ap);
4228
4229         if ((result = TALLOC_ARRAY(mem_ctx, const char *, num+1)) == NULL) {
4230                 return NULL;
4231         }
4232
4233         va_start(ap, mem_ctx);
4234         for (i=0; i<num; i++) {
4235                 result[i] = talloc_strdup(result, va_arg(ap, const char*));
4236                 if (result[i] == NULL) {
4237                         talloc_free(result);
4238                         va_end(ap);
4239                         return NULL;
4240                 }
4241         }
4242         va_end(ap);
4243
4244         result[num] = NULL;
4245         return result;
4246 }
4247
4248 struct ldap_search_state {
4249         struct smbldap_state *connection;
4250
4251         uint32 acct_flags;
4252         uint16 group_type;
4253
4254         const char *base;
4255         int scope;
4256         const char *filter;
4257         const char **attrs;
4258         int attrsonly;
4259         void *pagedresults_cookie;
4260
4261         LDAPMessage *entries, *current_entry;
4262         bool (*ldap2displayentry)(struct ldap_search_state *state,
4263                                   TALLOC_CTX *mem_ctx,
4264                                   LDAP *ld, LDAPMessage *entry,
4265                                   struct samr_displayentry *result);
4266 };
4267
4268 static bool ldapsam_search_firstpage(struct pdb_search *search)
4269 {
4270         struct ldap_search_state *state =
4271                 (struct ldap_search_state *)search->private_data;
4272         LDAP *ld;
4273         int rc = LDAP_OPERATIONS_ERROR;
4274
4275         state->entries = NULL;
4276
4277         if (state->connection->paged_results) {
4278                 rc = smbldap_search_paged(state->connection, state->base,
4279                                           state->scope, state->filter,
4280                                           state->attrs, state->attrsonly,
4281                                           lp_ldap_page_size(), &state->entries,
4282                                           &state->pagedresults_cookie);
4283         }
4284
4285         if ((rc != LDAP_SUCCESS) || (state->entries == NULL)) {
4286
4287                 if (state->entries != NULL) {
4288                         /* Left over from unsuccessful paged attempt */
4289                         ldap_msgfree(state->entries);
4290                         state->entries = NULL;
4291                 }
4292
4293                 rc = smbldap_search(state->connection, state->base,
4294                                     state->scope, state->filter, state->attrs,
4295                                     state->attrsonly, &state->entries);
4296
4297                 if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4298                         return False;
4299
4300                 /* Ok, the server was lying. It told us it could do paged
4301                  * searches when it could not. */
4302                 state->connection->paged_results = False;
4303         }
4304
4305         ld = state->connection->ldap_struct;
4306         if ( ld == NULL) {
4307                 DEBUG(5, ("Don't have an LDAP connection right after a "
4308                           "search\n"));
4309                 return False;
4310         }
4311         state->current_entry = ldap_first_entry(ld, state->entries);
4312
4313         if (state->current_entry == NULL) {
4314                 ldap_msgfree(state->entries);
4315                 state->entries = NULL;
4316         }
4317
4318         return True;
4319 }
4320
4321 static bool ldapsam_search_nextpage(struct pdb_search *search)
4322 {
4323         struct ldap_search_state *state =
4324                 (struct ldap_search_state *)search->private_data;
4325         int rc;
4326
4327         if (!state->connection->paged_results) {
4328                 /* There is no next page when there are no paged results */
4329                 return False;
4330         }
4331
4332         rc = smbldap_search_paged(state->connection, state->base,
4333                                   state->scope, state->filter, state->attrs,
4334                                   state->attrsonly, lp_ldap_page_size(),
4335                                   &state->entries,
4336                                   &state->pagedresults_cookie);
4337
4338         if ((rc != LDAP_SUCCESS) || (state->entries == NULL))
4339                 return False;
4340
4341         state->current_entry = ldap_first_entry(state->connection->ldap_struct, state->entries);
4342
4343         if (state->current_entry == NULL) {
4344                 ldap_msgfree(state->entries);
4345                 state->entries = NULL;
4346         }
4347
4348         return True;
4349 }
4350
4351 static bool ldapsam_search_next_entry(struct pdb_search *search,
4352                                       struct samr_displayentry *entry)
4353 {
4354         struct ldap_search_state *state =
4355                 (struct ldap_search_state *)search->private_data;
4356         bool result;
4357
4358  retry:
4359         if ((state->entries == NULL) && (state->pagedresults_cookie == NULL))
4360                 return False;
4361
4362         if ((state->entries == NULL) &&
4363             !ldapsam_search_nextpage(search))
4364                     return False;
4365
4366         result = state->ldap2displayentry(state, search,
4367                                           state->connection->ldap_struct,
4368                                           state->current_entry, entry);
4369
4370         if (!result) {
4371                 char *dn;
4372                 dn = ldap_get_dn(state->connection->ldap_struct, state->current_entry);
4373                 DEBUG(5, ("Skipping entry %s\n", dn != NULL ? dn : "<NULL>"));
4374                 if (dn != NULL) ldap_memfree(dn);
4375         }
4376
4377         state->current_entry = ldap_next_entry(state->connection->ldap_struct, state->current_entry);
4378
4379         if (state->current_entry == NULL) {
4380                 ldap_msgfree(state->entries);
4381                 state->entries = NULL;
4382         }
4383
4384         if (!result) goto retry;
4385
4386         return True;
4387 }
4388
4389 static void ldapsam_search_end(struct pdb_search *search)
4390 {
4391         struct ldap_search_state *state =
4392                 (struct ldap_search_state *)search->private_data;
4393         int rc;
4394
4395         if (state->pagedresults_cookie == NULL)
4396                 return;
4397
4398         if (state->entries != NULL)
4399                 ldap_msgfree(state->entries);
4400
4401         state->entries = NULL;
4402         state->current_entry = NULL;
4403
4404         if (!state->connection->paged_results)
4405                 return;
4406
4407         /* Tell the LDAP server we're not interested in the rest anymore. */
4408
4409         rc = smbldap_search_paged(state->connection, state->base, state->scope,
4410                                   state->filter, state->attrs,
4411                                   state->attrsonly, 0, &state->entries,
4412                                   &state->pagedresults_cookie);
4413
4414         if (rc != LDAP_SUCCESS)
4415                 DEBUG(5, ("Could not end search properly\n"));
4416
4417         return;
4418 }
4419
4420 static bool ldapuser2displayentry(struct ldap_search_state *state,
4421                                   TALLOC_CTX *mem_ctx,
4422                                   LDAP *ld, LDAPMessage *entry,
4423                                   struct samr_displayentry *result)
4424 {
4425         char **vals;
4426         size_t converted_size;
4427         DOM_SID sid;
4428         uint32 acct_flags;
4429
4430         vals = ldap_get_values(ld, entry, "sambaAcctFlags");
4431         if ((vals == NULL) || (vals[0] == NULL)) {
4432                 DEBUG(5, ("\"sambaAcctFlags\" not found\n"));
4433                 return False;
4434         }
4435         acct_flags = pdb_decode_acct_ctrl(vals[0]);
4436         ldap_value_free(vals);
4437
4438         if ((state->acct_flags != 0) &&
4439             ((state->acct_flags & acct_flags) == 0))
4440                 return False;           
4441
4442         result->acct_flags = acct_flags;
4443         result->account_name = "";
4444         result->fullname = "";
4445         result->description = "";
4446
4447         vals = ldap_get_values(ld, entry, "uid");
4448         if ((vals == NULL) || (vals[0] == NULL)) {
4449                 DEBUG(5, ("\"uid\" not found\n"));
4450                 return False;
4451         }
4452         if (!pull_utf8_talloc(mem_ctx,
4453                               CONST_DISCARD(char **, &result->account_name),
4454                               vals[0], &converted_size))
4455         {
4456                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4457                          strerror(errno)));
4458         }
4459
4460         ldap_value_free(vals);
4461
4462         vals = ldap_get_values(ld, entry, "displayName");
4463         if ((vals == NULL) || (vals[0] == NULL))
4464                 DEBUG(8, ("\"displayName\" not found\n"));
4465         else if (!pull_utf8_talloc(mem_ctx,
4466                                    CONST_DISCARD(char **, &result->fullname),
4467                                    vals[0], &converted_size))
4468         {
4469                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4470                          strerror(errno)));
4471         }
4472
4473         ldap_value_free(vals);
4474
4475         vals = ldap_get_values(ld, entry, "description");
4476         if ((vals == NULL) || (vals[0] == NULL))
4477                 DEBUG(8, ("\"description\" not found\n"));
4478         else if (!pull_utf8_talloc(mem_ctx,
4479                                    CONST_DISCARD(char **, &result->description),
4480                                    vals[0], &converted_size))
4481         {
4482                 DEBUG(0,("ldapuser2displayentry: pull_utf8_talloc failed: %s",
4483                          strerror(errno)));
4484         }
4485
4486         ldap_value_free(vals);
4487
4488         if ((result->account_name == NULL) ||
4489             (result->fullname == NULL) ||
4490             (result->description == NULL)) {
4491                 DEBUG(0, ("talloc failed\n"));
4492                 return False;
4493         }
4494
4495         vals = ldap_get_values(ld, entry, "sambaSid");
4496         if ((vals == NULL) || (vals[0] == NULL)) {
4497                 DEBUG(0, ("\"objectSid\" not found\n"));
4498                 return False;
4499         }
4500
4501         if (!string_to_sid(&sid, vals[0])) {
4502                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4503                 ldap_value_free(vals);
4504                 return False;
4505         }
4506         ldap_value_free(vals);
4507
4508         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid)) {
4509                 DEBUG(0, ("sid %s does not belong to our domain\n",
4510                           sid_string_dbg(&sid)));
4511                 return False;
4512         }
4513
4514         return True;
4515 }
4516
4517
4518 static bool ldapsam_search_users(struct pdb_methods *methods,
4519                                  struct pdb_search *search,
4520                                  uint32 acct_flags)
4521 {
4522         struct ldapsam_privates *ldap_state =
4523                 (struct ldapsam_privates *)methods->private_data;
4524         struct ldap_search_state *state;
4525
4526         state = talloc(search, struct ldap_search_state);
4527         if (state == NULL) {
4528                 DEBUG(0, ("talloc failed\n"));
4529                 return False;
4530         }
4531
4532         state->connection = ldap_state->smbldap_state;
4533
4534         if ((acct_flags != 0) && ((acct_flags & ACB_NORMAL) != 0))
4535                 state->base = lp_ldap_user_suffix();
4536         else if ((acct_flags != 0) &&
4537                  ((acct_flags & (ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) != 0))
4538                 state->base = lp_ldap_machine_suffix();
4539         else
4540                 state->base = lp_ldap_suffix();
4541
4542         state->acct_flags = acct_flags;
4543         state->base = talloc_strdup(search, state->base);
4544         state->scope = LDAP_SCOPE_SUBTREE;
4545         state->filter = get_ldap_filter(search, "*");
4546         state->attrs = talloc_attrs(search, "uid", "sambaSid",
4547                                     "displayName", "description",
4548                                     "sambaAcctFlags", NULL);
4549         state->attrsonly = 0;
4550         state->pagedresults_cookie = NULL;
4551         state->entries = NULL;
4552         state->ldap2displayentry = ldapuser2displayentry;
4553
4554         if ((state->filter == NULL) || (state->attrs == NULL)) {
4555                 DEBUG(0, ("talloc failed\n"));
4556                 return False;
4557         }
4558
4559         search->private_data = state;
4560         search->next_entry = ldapsam_search_next_entry;
4561         search->search_end = ldapsam_search_end;
4562
4563         return ldapsam_search_firstpage(search);
4564 }
4565
4566 static bool ldapgroup2displayentry(struct ldap_search_state *state,
4567                                    TALLOC_CTX *mem_ctx,
4568                                    LDAP *ld, LDAPMessage *entry,
4569                                    struct samr_displayentry *result)
4570 {
4571         char **vals;
4572         size_t converted_size;
4573         DOM_SID sid;
4574         uint16 group_type;
4575
4576         result->account_name = "";
4577         result->fullname = "";
4578         result->description = "";
4579
4580
4581         vals = ldap_get_values(ld, entry, "sambaGroupType");
4582         if ((vals == NULL) || (vals[0] == NULL)) {
4583                 DEBUG(5, ("\"sambaGroupType\" not found\n"));
4584                 if (vals != NULL) {
4585                         ldap_value_free(vals);
4586                 }
4587                 return False;
4588         }
4589
4590         group_type = atoi(vals[0]);
4591
4592         if ((state->group_type != 0) &&
4593             ((state->group_type != group_type))) {
4594                 ldap_value_free(vals);
4595                 return False;
4596         }
4597
4598         ldap_value_free(vals);
4599
4600         /* display name is the NT group name */
4601
4602         vals = ldap_get_values(ld, entry, "displayName");
4603         if ((vals == NULL) || (vals[0] == NULL)) {
4604                 DEBUG(8, ("\"displayName\" not found\n"));
4605
4606                 /* fallback to the 'cn' attribute */
4607                 vals = ldap_get_values(ld, entry, "cn");
4608                 if ((vals == NULL) || (vals[0] == NULL)) {
4609                         DEBUG(5, ("\"cn\" not found\n"));
4610                         return False;
4611                 }
4612                 if (!pull_utf8_talloc(mem_ctx,
4613                                       CONST_DISCARD(char **,
4614                                                     &result->account_name),
4615                                       vals[0], &converted_size))
4616                 {
4617                         DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc "
4618                                   "failed: %s", strerror(errno)));
4619                 }
4620         }
4621         else if (!pull_utf8_talloc(mem_ctx,
4622                                    CONST_DISCARD(char **,
4623                                                  &result->account_name),
4624                                    vals[0], &converted_size))
4625         {
4626                 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4627                           strerror(errno)));
4628         }
4629
4630         ldap_value_free(vals);
4631
4632         vals = ldap_get_values(ld, entry, "description");
4633         if ((vals == NULL) || (vals[0] == NULL))
4634                 DEBUG(8, ("\"description\" not found\n"));
4635         else if (!pull_utf8_talloc(mem_ctx,
4636                                    CONST_DISCARD(char **, &result->description),
4637                                    vals[0], &converted_size))
4638         {
4639                 DEBUG(0,("ldapgroup2displayentry: pull_utf8_talloc failed: %s",
4640                           strerror(errno)));
4641         }
4642         ldap_value_free(vals);
4643
4644         if ((result->account_name == NULL) ||
4645             (result->fullname == NULL) ||
4646             (result->description == NULL)) {
4647                 DEBUG(0, ("talloc failed\n"));
4648                 return False;
4649         }
4650
4651         vals = ldap_get_values(ld, entry, "sambaSid");
4652         if ((vals == NULL) || (vals[0] == NULL)) {
4653                 DEBUG(0, ("\"objectSid\" not found\n"));
4654                 if (vals != NULL) {
4655                         ldap_value_free(vals);
4656                 }
4657                 return False;
4658         }
4659
4660         if (!string_to_sid(&sid, vals[0])) {
4661                 DEBUG(0, ("Could not convert %s to SID\n", vals[0]));
4662                 return False;
4663         }
4664
4665         ldap_value_free(vals);
4666
4667         switch (group_type) {
4668                 case SID_NAME_DOM_GRP:
4669                 case SID_NAME_ALIAS:
4670
4671                         if (!sid_peek_check_rid(get_global_sam_sid(), &sid, &result->rid) 
4672                                 && !sid_peek_check_rid(&global_sid_Builtin, &sid, &result->rid)) 
4673                         {
4674                                 DEBUG(0, ("%s is not in our domain\n",
4675                                           sid_string_dbg(&sid)));
4676                                 return False;
4677                         }
4678                         break;
4679
4680                 default:
4681                         DEBUG(0,("unkown group type: %d\n", group_type));
4682                         return False;
4683         }
4684
4685         result->acct_flags = 0;
4686
4687         return True;
4688 }
4689
4690 static bool ldapsam_search_grouptype(struct pdb_methods *methods,
4691                                      struct pdb_search *search,
4692                                      const DOM_SID *sid,
4693                                      enum lsa_SidType type)
4694 {
4695         struct ldapsam_privates *ldap_state =
4696                 (struct ldapsam_privates *)methods->private_data;
4697         struct ldap_search_state *state;
4698         fstring tmp;
4699
4700         state = talloc(search, struct ldap_search_state);
4701         if (state == NULL) {
4702                 DEBUG(0, ("talloc failed\n"));
4703                 return False;
4704         }
4705
4706         state->connection = ldap_state->smbldap_state;
4707
4708         state->base = talloc_strdup(search, lp_ldap_suffix());
4709         state->connection = ldap_state->smbldap_state;
4710         state->scope = LDAP_SCOPE_SUBTREE;
4711         state->filter = talloc_asprintf(search, "(&(objectclass=%s)"
4712                                         "(sambaGroupType=%d)(sambaSID=%s*))",
4713                                          LDAP_OBJ_GROUPMAP,
4714                                          type, sid_to_fstring(tmp, sid));
4715         state->attrs = talloc_attrs(search, "cn", "sambaSid",
4716                                     "displayName", "description",
4717                                     "sambaGroupType", NULL);
4718         state->attrsonly = 0;
4719         state->pagedresults_cookie = NULL;
4720         state->entries = NULL;
4721         state->group_type = type;
4722         state->ldap2displayentry = ldapgroup2displayentry;
4723
4724         if ((state->filter == NULL) || (state->attrs == NULL)) {
4725                 DEBUG(0, ("talloc failed\n"));
4726                 return False;
4727         }
4728
4729         search->private_data = state;
4730         search->next_entry = ldapsam_search_next_entry;
4731         search->search_end = ldapsam_search_end;
4732
4733         return ldapsam_search_firstpage(search);
4734 }
4735
4736 static bool ldapsam_search_groups(struct pdb_methods *methods,
4737                                   struct pdb_search *search)
4738 {
4739         return ldapsam_search_grouptype(methods, search, get_global_sam_sid(), SID_NAME_DOM_GRP);
4740 }
4741
4742 static bool ldapsam_search_aliases(struct pdb_methods *methods,
4743                                    struct pdb_search *search,
4744                                    const DOM_SID *sid)
4745 {
4746         return ldapsam_search_grouptype(methods, search, sid, SID_NAME_ALIAS);
4747 }
4748
4749 static uint32_t ldapsam_capabilities(struct pdb_methods *methods)
4750 {
4751         return PDB_CAP_STORE_RIDS;
4752 }
4753
4754 static NTSTATUS ldapsam_get_new_rid(struct ldapsam_privates *priv,
4755                                     uint32 *rid)
4756 {
4757         struct smbldap_state *smbldap_state = priv->smbldap_state;
4758
4759         LDAPMessage *result = NULL;
4760         LDAPMessage *entry = NULL;
4761         LDAPMod **mods = NULL;
4762         NTSTATUS status;
4763         char *value;
4764         int rc;
4765         uint32 nextRid = 0;
4766         const char *dn;
4767
4768         TALLOC_CTX *mem_ctx;
4769
4770         mem_ctx = talloc_new(NULL);
4771         if (mem_ctx == NULL) {
4772                 DEBUG(0, ("talloc_new failed\n"));
4773                 return NT_STATUS_NO_MEMORY;
4774         }
4775
4776         status = smbldap_search_domain_info(smbldap_state, &result,
4777                                             get_global_sam_name(), False);
4778         if (!NT_STATUS_IS_OK(status)) {
4779                 DEBUG(3, ("Could not get domain info: %s\n",
4780                           nt_errstr(status)));
4781                 goto done;
4782         }
4783
4784         talloc_autofree_ldapmsg(mem_ctx, result);
4785
4786         entry = ldap_first_entry(priv2ld(priv), result);
4787         if (entry == NULL) {
4788                 DEBUG(0, ("Could not get domain info entry\n"));
4789                 status = NT_STATUS_INTERNAL_DB_CORRUPTION;
4790                 goto done;
4791         }
4792
4793         /* Find the largest of the three attributes "sambaNextRid",
4794            "sambaNextGroupRid" and "sambaNextUserRid". I gave up on the
4795            concept of differentiating between user and group rids, and will
4796            use only "sambaNextRid" in the future. But for compatibility
4797            reasons I look if others have chosen different strategies -- VL */
4798
4799         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4800                                                 "sambaNextRid", mem_ctx);
4801         if (value != NULL) {
4802                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4803                 nextRid = MAX(nextRid, tmp);
4804         }
4805
4806         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4807                                                 "sambaNextUserRid", mem_ctx);
4808         if (value != NULL) {
4809                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4810                 nextRid = MAX(nextRid, tmp);
4811         }
4812
4813         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4814                                                 "sambaNextGroupRid", mem_ctx);
4815         if (value != NULL) {
4816                 uint32 tmp = (uint32)strtoul(value, NULL, 10);
4817                 nextRid = MAX(nextRid, tmp);
4818         }
4819
4820         if (nextRid == 0) {
4821                 nextRid = BASE_RID-1;
4822         }
4823
4824         nextRid += 1;
4825
4826         smbldap_make_mod(priv2ld(priv), entry, &mods, "sambaNextRid",
4827                          talloc_asprintf(mem_ctx, "%d", nextRid));
4828         talloc_autofree_ldapmod(mem_ctx, mods);
4829
4830         if ((dn = smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)) == NULL) {
4831                 status = NT_STATUS_NO_MEMORY;
4832                 goto done;
4833         }
4834
4835         rc = smbldap_modify(smbldap_state, dn, mods);
4836
4837         /* ACCESS_DENIED is used as a placeholder for "the modify failed,
4838          * please retry" */
4839
4840         status = (rc == LDAP_SUCCESS) ? NT_STATUS_OK : NT_STATUS_ACCESS_DENIED;
4841
4842  done:
4843         if (NT_STATUS_IS_OK(status)) {
4844                 *rid = nextRid;
4845         }
4846
4847         TALLOC_FREE(mem_ctx);
4848         return status;
4849 }
4850
4851 static NTSTATUS ldapsam_new_rid_internal(struct pdb_methods *methods, uint32 *rid)
4852 {
4853         int i;
4854
4855         for (i=0; i<10; i++) {
4856                 NTSTATUS result = ldapsam_get_new_rid(
4857                         (struct ldapsam_privates *)methods->private_data, rid);
4858                 if (NT_STATUS_IS_OK(result)) {
4859                         return result;
4860                 }
4861
4862                 if (!NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED)) {
4863                         return result;
4864                 }
4865
4866                 /* The ldap update failed (maybe a race condition), retry */
4867         }
4868
4869         /* Tried 10 times, fail. */
4870         return NT_STATUS_ACCESS_DENIED;
4871 }
4872
4873 static bool ldapsam_new_rid(struct pdb_methods *methods, uint32 *rid)
4874 {
4875         NTSTATUS result = ldapsam_new_rid_internal(methods, rid);
4876         return NT_STATUS_IS_OK(result) ? True : False;
4877 }
4878
4879 static bool ldapsam_sid_to_id(struct pdb_methods *methods,
4880                               const DOM_SID *sid,
4881                               union unid_t *id, enum lsa_SidType *type)
4882 {
4883         struct ldapsam_privates *priv =
4884                 (struct ldapsam_privates *)methods->private_data;
4885         char *filter;
4886         const char *attrs[] = { "sambaGroupType", "gidNumber", "uidNumber",
4887                                 NULL };
4888         LDAPMessage *result = NULL;
4889         LDAPMessage *entry = NULL;
4890         bool ret = False;
4891         char *value;
4892         int rc;
4893
4894         TALLOC_CTX *mem_ctx;
4895
4896         mem_ctx = talloc_new(NULL);
4897         if (mem_ctx == NULL) {
4898                 DEBUG(0, ("talloc_new failed\n"));
4899                 return False;
4900         }
4901
4902         filter = talloc_asprintf(mem_ctx,
4903                                  "(&(sambaSid=%s)"
4904                                  "(|(objectClass=%s)(objectClass=%s)))",
4905                                  sid_string_talloc(mem_ctx, sid),
4906                                  LDAP_OBJ_GROUPMAP, LDAP_OBJ_SAMBASAMACCOUNT);
4907         if (filter == NULL) {
4908                 DEBUG(5, ("talloc_asprintf failed\n"));
4909                 goto done;
4910         }
4911
4912         rc = smbldap_search_suffix(priv->smbldap_state, filter,
4913                                    attrs, &result);
4914         if (rc != LDAP_SUCCESS) {
4915                 goto done;
4916         }
4917         talloc_autofree_ldapmsg(mem_ctx, result);
4918
4919         if (ldap_count_entries(priv2ld(priv), result) != 1) {
4920                 DEBUG(10, ("Got %d entries, expected one\n",
4921                            ldap_count_entries(priv2ld(priv), result)));
4922                 goto done;
4923         }
4924
4925         entry = ldap_first_entry(priv2ld(priv), result);
4926
4927         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4928                                                 "sambaGroupType", mem_ctx);
4929
4930         if (value != NULL) {
4931                 const char *gid_str;
4932                 /* It's a group */
4933
4934                 gid_str = smbldap_talloc_single_attribute(
4935                         priv2ld(priv), entry, "gidNumber", mem_ctx);
4936                 if (gid_str == NULL) {
4937                         DEBUG(1, ("%s has sambaGroupType but no gidNumber\n",
4938                                   smbldap_talloc_dn(mem_ctx, priv2ld(priv),
4939                                                     entry)));
4940                         goto done;
4941                 }
4942
4943                 id->gid = strtoul(gid_str, NULL, 10);
4944                 *type = (enum lsa_SidType)strtoul(value, NULL, 10);
4945                 ret = True;
4946                 goto done;
4947         }
4948
4949         /* It must be a user */
4950
4951         value = smbldap_talloc_single_attribute(priv2ld(priv), entry,
4952                                                 "uidNumber", mem_ctx);
4953         if (value == NULL) {
4954                 DEBUG(1, ("Could not find uidNumber in %s\n",
4955                           smbldap_talloc_dn(mem_ctx, priv2ld(priv), entry)));
4956                 goto done;
4957         }
4958
4959         id->uid = strtoul(value, NULL, 10);
4960         *type = SID_NAME_USER;
4961
4962         ret = True;
4963  done:
4964         TALLOC_FREE(mem_ctx);
4965         return ret;
4966 }
4967
4968 /*
4969  * The following functions is called only if
4970  * ldapsam:trusted and ldapsam:editposix are
4971  * set to true
4972  */
4973
4974 /*
4975  * ldapsam_create_user creates a new
4976  * posixAccount and sambaSamAccount object
4977  * in the ldap users subtree
4978  *
4979  * The uid is allocated by winbindd.
4980  */
4981
4982 static NTSTATUS ldapsam_create_user(struct pdb_methods *my_methods,
4983                                     TALLOC_CTX *tmp_ctx, const char *name,
4984                                     uint32 acb_info, uint32 *rid)
4985 {
4986         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
4987         LDAPMessage *entry = NULL;
4988         LDAPMessage *result = NULL;
4989         uint32 num_result;
4990         bool is_machine = False;
4991         bool add_posix = False;
4992         LDAPMod **mods = NULL;
4993         struct samu *user;
4994         char *filter;
4995         char *username;
4996         char *homedir;
4997         char *gidstr;
4998         char *uidstr;
4999         char *shell;
5000         const char *dn = NULL;
5001         DOM_SID group_sid;
5002         DOM_SID user_sid;
5003         gid_t gid = -1;
5004         uid_t uid = -1;
5005         NTSTATUS ret;
5006         int rc;
5007
5008         if (((acb_info & ACB_NORMAL) && name[strlen(name)-1] == '$') ||
5009               acb_info & ACB_WSTRUST ||
5010               acb_info & ACB_SVRTRUST ||
5011               acb_info & ACB_DOMTRUST) {
5012                 is_machine = True;
5013         }
5014
5015         username = escape_ldap_string(talloc_tos(), name);
5016         filter = talloc_asprintf(tmp_ctx, "(&(uid=%s)(objectClass=%s))",
5017                                  username, LDAP_OBJ_POSIXACCOUNT);
5018         TALLOC_FREE(username);
5019
5020         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5021         if (rc != LDAP_SUCCESS) {
5022                 DEBUG(0,("ldapsam_create_user: ldap search failed!\n"));
5023                 return NT_STATUS_ACCESS_DENIED;
5024         }
5025         talloc_autofree_ldapmsg(tmp_ctx, result);
5026
5027         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5028
5029         if (num_result > 1) {
5030                 DEBUG (0, ("ldapsam_create_user: More than one user with name [%s] ?!\n", name));
5031                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5032         }
5033
5034         if (num_result == 1) {
5035                 char *tmp;
5036                 /* check if it is just a posix account.
5037                  * or if there is a sid attached to this entry
5038                  */
5039
5040                 entry = ldap_first_entry(priv2ld(ldap_state), result);
5041                 if (!entry) {
5042                         return NT_STATUS_UNSUCCESSFUL;
5043                 }
5044
5045                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5046                 if (tmp) {
5047                         DEBUG (1, ("ldapsam_create_user: The user [%s] already exist!\n", name));
5048                         return NT_STATUS_USER_EXISTS;
5049                 }
5050
5051                 /* it is just a posix account, retrieve the dn for later use */
5052                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5053                 if (!dn) {
5054                         DEBUG(0,("ldapsam_create_user: Out of memory!\n"));
5055                         return NT_STATUS_NO_MEMORY;
5056                 }
5057         }
5058
5059         if (num_result == 0) {
5060                 add_posix = True;
5061         }
5062
5063         /* Create the basic samu structure and generate the mods for the ldap commit */
5064         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5065                 DEBUG(1, ("ldapsam_create_user: Could not allocate a new RID\n"));
5066                 return ret;
5067         }
5068
5069         sid_compose(&user_sid, get_global_sam_sid(), *rid);
5070
5071         user = samu_new(tmp_ctx);
5072         if (!user) {
5073                 DEBUG(1,("ldapsam_create_user: Unable to allocate user struct\n"));
5074                 return NT_STATUS_NO_MEMORY;
5075         }
5076
5077         if (!pdb_set_username(user, name, PDB_SET)) {
5078                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5079                 return NT_STATUS_UNSUCCESSFUL;
5080         }
5081         if (!pdb_set_domain(user, get_global_sam_name(), PDB_SET)) {
5082                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5083                 return NT_STATUS_UNSUCCESSFUL;
5084         }
5085         if (is_machine) {
5086                 if (acb_info & ACB_NORMAL) {
5087                         if (!pdb_set_acct_ctrl(user, ACB_WSTRUST, PDB_SET)) {
5088                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5089                                 return NT_STATUS_UNSUCCESSFUL;
5090                         }
5091                 } else {
5092                         if (!pdb_set_acct_ctrl(user, acb_info, PDB_SET)) {
5093                                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5094                                 return NT_STATUS_UNSUCCESSFUL;
5095                         }
5096                 }
5097         } else {
5098                 if (!pdb_set_acct_ctrl(user, ACB_NORMAL | ACB_DISABLED, PDB_SET)) {
5099                         DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5100                         return NT_STATUS_UNSUCCESSFUL;
5101                 }
5102         }
5103
5104         if (!pdb_set_user_sid(user, &user_sid, PDB_SET)) {
5105                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5106                 return NT_STATUS_UNSUCCESSFUL;
5107         }
5108
5109         if (!init_ldap_from_sam(ldap_state, NULL, &mods, user, element_is_set_or_changed)) {
5110                 DEBUG(1,("ldapsam_create_user: Unable to fill user structs\n"));
5111                 return NT_STATUS_UNSUCCESSFUL;
5112         }
5113
5114         if (ldap_state->schema_ver != SCHEMAVER_SAMBASAMACCOUNT) {
5115                 DEBUG(1,("ldapsam_create_user: Unsupported schema version\n"));
5116         }
5117         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_SAMBASAMACCOUNT);
5118
5119         if (add_posix) {
5120                 char *escape_name;
5121
5122                 DEBUG(3,("ldapsam_create_user: Creating new posix user\n"));
5123
5124                 /* retrieve the Domain Users group gid */
5125                 if (!sid_compose(&group_sid, get_global_sam_sid(), DOMAIN_GROUP_RID_USERS) ||
5126                     !sid_to_gid(&group_sid, &gid)) {
5127                         DEBUG (0, ("ldapsam_create_user: Unable to get the Domain Users gid: bailing out!\n"));
5128                         return NT_STATUS_INVALID_PRIMARY_GROUP;
5129                 }
5130
5131                 /* lets allocate a new userid for this user */
5132                 if (!winbind_allocate_uid(&uid)) {
5133                         DEBUG (0, ("ldapsam_create_user: Unable to allocate a new user id: bailing out!\n"));
5134                         return NT_STATUS_UNSUCCESSFUL;
5135                 }
5136
5137
5138                 if (is_machine) {
5139                         /* TODO: choose a more appropriate default for machines */
5140                         homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), "SMB_workstations_home", ldap_state->domain_name, uid, gid);
5141                         shell = talloc_strdup(tmp_ctx, "/bin/false");
5142                 } else {
5143                         homedir = talloc_sub_specified(tmp_ctx, lp_template_homedir(), name, ldap_state->domain_name, uid, gid);
5144                         shell = talloc_sub_specified(tmp_ctx, lp_template_shell(), name, ldap_state->domain_name, uid, gid);
5145                 }
5146                 uidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)uid);
5147                 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5148
5149                 escape_name = escape_rdn_val_string_alloc(name);
5150                 if (!escape_name) {
5151                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5152                         return NT_STATUS_NO_MEMORY;
5153                 }
5154
5155                 if (is_machine) {
5156                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_machine_suffix ());
5157                 } else {
5158                         dn = talloc_asprintf(tmp_ctx, "uid=%s,%s", escape_name, lp_ldap_user_suffix ());
5159                 }
5160
5161                 SAFE_FREE(escape_name);
5162
5163                 if (!homedir || !shell || !uidstr || !gidstr || !dn) {
5164                         DEBUG (0, ("ldapsam_create_user: Out of memory!\n"));
5165                         return NT_STATUS_NO_MEMORY;
5166                 }
5167
5168                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_ACCOUNT);
5169                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_POSIXACCOUNT);
5170                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5171                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "uidNumber", uidstr);
5172                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5173                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "homeDirectory", homedir);
5174                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "loginShell", shell);
5175         }
5176
5177         talloc_autofree_ldapmod(tmp_ctx, mods);
5178
5179         if (add_posix) {        
5180                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5181         } else {
5182                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5183         }       
5184
5185         if (rc != LDAP_SUCCESS) {
5186                 DEBUG(0,("ldapsam_create_user: failed to create a new user [%s] (dn = %s)\n", name ,dn));
5187                 return NT_STATUS_UNSUCCESSFUL;
5188         }
5189
5190         DEBUG(2,("ldapsam_create_user: added account [%s] in the LDAP database\n", name));
5191
5192         flush_pwnam_cache();
5193
5194         return NT_STATUS_OK;
5195 }
5196
5197 static NTSTATUS ldapsam_delete_user(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, struct samu *sam_acct)
5198 {
5199         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5200         LDAPMessage *result = NULL;
5201         LDAPMessage *entry = NULL;
5202         int num_result;
5203         const char *dn;
5204         char *filter;
5205         int rc;
5206
5207         DEBUG(0,("ldapsam_delete_user: Attempt to delete user [%s]\n", pdb_get_username(sam_acct)));
5208
5209         filter = talloc_asprintf(tmp_ctx,
5210                                  "(&(uid=%s)"
5211                                  "(objectClass=%s)"
5212                                  "(objectClass=%s))",
5213                                  pdb_get_username(sam_acct),
5214                                  LDAP_OBJ_POSIXACCOUNT,
5215                                  LDAP_OBJ_SAMBASAMACCOUNT);
5216         if (filter == NULL) {
5217                 return NT_STATUS_NO_MEMORY;
5218         }
5219
5220         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5221         if (rc != LDAP_SUCCESS) {
5222                 DEBUG(0,("ldapsam_delete_user: user search failed!\n"));
5223                 return NT_STATUS_UNSUCCESSFUL;
5224         }
5225         talloc_autofree_ldapmsg(tmp_ctx, result);
5226
5227         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5228
5229         if (num_result == 0) {
5230                 DEBUG(0,("ldapsam_delete_user: user not found!\n"));
5231                 return NT_STATUS_NO_SUCH_USER;
5232         }
5233
5234         if (num_result > 1) {
5235                 DEBUG (0, ("ldapsam_delete_user: More than one user with name [%s] ?!\n", pdb_get_username(sam_acct)));
5236                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5237         }
5238
5239         entry = ldap_first_entry(priv2ld(ldap_state), result);
5240         if (!entry) {
5241                 return NT_STATUS_UNSUCCESSFUL;
5242         }
5243
5244         /* it is just a posix account, retrieve the dn for later use */
5245         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5246         if (!dn) {
5247                 DEBUG(0,("ldapsam_delete_user: Out of memory!\n"));
5248                 return NT_STATUS_NO_MEMORY;
5249         }
5250
5251         rc = smbldap_delete(ldap_state->smbldap_state, dn);
5252         if (rc != LDAP_SUCCESS) {
5253                 return NT_STATUS_UNSUCCESSFUL;
5254         }
5255
5256         flush_pwnam_cache();
5257
5258         return NT_STATUS_OK;
5259 }
5260
5261 /*
5262  * ldapsam_create_group creates a new
5263  * posixGroup and sambaGroupMapping object
5264  * in the ldap groups subtree
5265  *
5266  * The gid is allocated by winbindd.
5267  */
5268
5269 static NTSTATUS ldapsam_create_dom_group(struct pdb_methods *my_methods,
5270                                          TALLOC_CTX *tmp_ctx,
5271                                          const char *name,
5272                                          uint32 *rid)
5273 {
5274         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5275         NTSTATUS ret;
5276         LDAPMessage *entry = NULL;
5277         LDAPMessage *result = NULL;
5278         uint32 num_result;
5279         bool is_new_entry = False;
5280         LDAPMod **mods = NULL;
5281         char *filter;
5282         char *groupsidstr;
5283         char *groupname;
5284         char *grouptype;
5285         char *gidstr;
5286         const char *dn = NULL;
5287         DOM_SID group_sid;
5288         gid_t gid = -1;
5289         int rc;
5290
5291         groupname = escape_ldap_string(talloc_tos(), name);
5292         filter = talloc_asprintf(tmp_ctx, "(&(cn=%s)(objectClass=%s))",
5293                                  groupname, LDAP_OBJ_POSIXGROUP);
5294         TALLOC_FREE(groupname);
5295
5296         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5297         if (rc != LDAP_SUCCESS) {
5298                 DEBUG(0,("ldapsam_create_group: ldap search failed!\n"));
5299                 return NT_STATUS_UNSUCCESSFUL;
5300         }
5301         talloc_autofree_ldapmsg(tmp_ctx, result);
5302
5303         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5304
5305         if (num_result > 1) {
5306                 DEBUG (0, ("ldapsam_create_group: There exists more than one group with name [%s]: bailing out!\n", name));
5307                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5308         }
5309
5310         if (num_result == 1) {
5311                 char *tmp;
5312                 /* check if it is just a posix group.
5313                  * or if there is a sid attached to this entry
5314                  */
5315
5316                 entry = ldap_first_entry(priv2ld(ldap_state), result);
5317                 if (!entry) {
5318                         return NT_STATUS_UNSUCCESSFUL;
5319                 }
5320
5321                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "sambaSID", tmp_ctx);
5322                 if (tmp) {
5323                         DEBUG (1, ("ldapsam_create_group: The group [%s] already exist!\n", name));
5324                         return NT_STATUS_GROUP_EXISTS;
5325                 }
5326
5327                 /* it is just a posix group, retrieve the gid and the dn for later use */
5328                 tmp = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5329                 if (!tmp) {
5330                         DEBUG (1, ("ldapsam_create_group: Couldn't retrieve the gidNumber for [%s]?!?!\n", name));
5331                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5332                 }
5333
5334                 gid = strtoul(tmp, NULL, 10);
5335
5336                 dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5337                 if (!dn) {
5338                         DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5339                         return NT_STATUS_NO_MEMORY;
5340                 }
5341         }
5342
5343         if (num_result == 0) {
5344                 char *escape_name;
5345
5346                 DEBUG(3,("ldapsam_create_user: Creating new posix group\n"));
5347
5348                 is_new_entry = True;
5349
5350                 /* lets allocate a new groupid for this group */
5351                 if (!winbind_allocate_gid(&gid)) {
5352                         DEBUG (0, ("ldapsam_create_group: Unable to allocate a new group id: bailing out!\n"));
5353                         return NT_STATUS_UNSUCCESSFUL;
5354                 }
5355
5356                 gidstr = talloc_asprintf(tmp_ctx, "%u", (unsigned int)gid);
5357
5358                 escape_name = escape_rdn_val_string_alloc(name);
5359                 if (!escape_name) {
5360                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5361                         return NT_STATUS_NO_MEMORY;
5362                 }
5363
5364                 dn = talloc_asprintf(tmp_ctx, "cn=%s,%s", escape_name, lp_ldap_group_suffix());
5365
5366                 SAFE_FREE(escape_name);
5367
5368                 if (!gidstr || !dn) {
5369                         DEBUG (0, ("ldapsam_create_group: Out of memory!\n"));
5370                         return NT_STATUS_NO_MEMORY;
5371                 }
5372
5373                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_POSIXGROUP);
5374                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "cn", name);
5375                 smbldap_set_mod(&mods, LDAP_MOD_ADD, "gidNumber", gidstr);
5376         }
5377
5378         if (!NT_STATUS_IS_OK((ret = ldapsam_new_rid_internal(my_methods, rid)))) {
5379                 DEBUG(1, ("ldapsam_create_group: Could not allocate a new RID\n"));
5380                 return ret;
5381         }
5382
5383         sid_compose(&group_sid, get_global_sam_sid(), *rid);
5384
5385         groupsidstr = talloc_strdup(tmp_ctx, sid_string_talloc(tmp_ctx,
5386                                                                &group_sid));
5387         grouptype = talloc_asprintf(tmp_ctx, "%d", SID_NAME_DOM_GRP);
5388
5389         if (!groupsidstr || !grouptype) {
5390                 DEBUG(0,("ldapsam_create_group: Out of memory!\n"));
5391                 return NT_STATUS_NO_MEMORY;
5392         }
5393
5394         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP);
5395         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaSid", groupsidstr);
5396         smbldap_set_mod(&mods, LDAP_MOD_ADD, "sambaGroupType", grouptype);
5397         smbldap_set_mod(&mods, LDAP_MOD_ADD, "displayName", name);
5398         talloc_autofree_ldapmod(tmp_ctx, mods);
5399
5400         if (is_new_entry) {     
5401                 rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5402 #if 0
5403                 if (rc == LDAP_OBJECT_CLASS_VIOLATION) {
5404                         /* This call may fail with rfc2307bis schema */
5405                         /* Retry adding a structural class */
5406                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", "????");
5407                         rc = smbldap_add(ldap_state->smbldap_state, dn, mods);
5408                 }
5409 #endif
5410         } else {
5411                 rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5412         }       
5413
5414         if (rc != LDAP_SUCCESS) {
5415                 DEBUG(0,("ldapsam_create_group: failed to create a new group [%s] (dn = %s)\n", name ,dn));
5416                 return NT_STATUS_UNSUCCESSFUL;
5417         }
5418
5419         DEBUG(2,("ldapsam_create_group: added group [%s] in the LDAP database\n", name));
5420
5421         return NT_STATUS_OK;
5422 }
5423
5424 static NTSTATUS ldapsam_delete_dom_group(struct pdb_methods *my_methods, TALLOC_CTX *tmp_ctx, uint32 rid)
5425 {
5426         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5427         LDAPMessage *result = NULL;
5428         LDAPMessage *entry = NULL;
5429         int num_result;
5430         const char *dn;
5431         char *gidstr;
5432         char *filter;
5433         DOM_SID group_sid;
5434         int rc;
5435
5436         /* get the group sid */
5437         sid_compose(&group_sid, get_global_sam_sid(), rid);
5438
5439         filter = talloc_asprintf(tmp_ctx,
5440                                  "(&(sambaSID=%s)"
5441                                  "(objectClass=%s)"
5442                                  "(objectClass=%s))",
5443                                  sid_string_talloc(tmp_ctx, &group_sid),
5444                                  LDAP_OBJ_POSIXGROUP,
5445                                  LDAP_OBJ_GROUPMAP);
5446         if (filter == NULL) {
5447                 return NT_STATUS_NO_MEMORY;
5448         }
5449
5450         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5451         if (rc != LDAP_SUCCESS) {
5452                 DEBUG(1,("ldapsam_delete_dom_group: group search failed!\n"));
5453                 return NT_STATUS_UNSUCCESSFUL;
5454         }
5455         talloc_autofree_ldapmsg(tmp_ctx, result);
5456
5457         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5458
5459         if (num_result == 0) {
5460                 DEBUG(1,("ldapsam_delete_dom_group: group not found!\n"));
5461                 return NT_STATUS_NO_SUCH_GROUP;
5462         }
5463
5464         if (num_result > 1) {
5465                 DEBUG (0, ("ldapsam_delete_dom_group: More than one group with the same SID ?!\n"));
5466                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5467         }
5468
5469         entry = ldap_first_entry(priv2ld(ldap_state), result);
5470         if (!entry) {
5471                 return NT_STATUS_UNSUCCESSFUL;
5472         }
5473
5474         /* here it is, retrieve the dn for later use */
5475         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5476         if (!dn) {
5477                 DEBUG(0,("ldapsam_delete_dom_group: Out of memory!\n"));
5478                 return NT_STATUS_NO_MEMORY;
5479         }
5480
5481         gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5482         if (!gidstr) {
5483                 DEBUG (0, ("ldapsam_delete_dom_group: Unable to find the group's gid!\n"));
5484                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5485         }
5486
5487         /* check no user have this group marked as primary group */
5488         filter = talloc_asprintf(tmp_ctx,
5489                                  "(&(gidNumber=%s)"
5490                                  "(objectClass=%s)"
5491                                  "(objectClass=%s))",
5492                                  gidstr,
5493                                  LDAP_OBJ_POSIXACCOUNT,
5494                                  LDAP_OBJ_SAMBASAMACCOUNT);
5495
5496         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5497         if (rc != LDAP_SUCCESS) {
5498                 DEBUG(1,("ldapsam_delete_dom_group: accounts search failed!\n"));
5499                 return NT_STATUS_UNSUCCESSFUL;
5500         }
5501         talloc_autofree_ldapmsg(tmp_ctx, result);
5502
5503         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5504
5505         if (num_result != 0) {
5506                 DEBUG(3,("ldapsam_delete_dom_group: Can't delete group, it is a primary group for %d users\n", num_result));
5507                 return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5508         }
5509
5510         rc = smbldap_delete(ldap_state->smbldap_state, dn);
5511         if (rc != LDAP_SUCCESS) {
5512                 return NT_STATUS_UNSUCCESSFUL;
5513         }
5514
5515         return NT_STATUS_OK;
5516 }
5517
5518 static NTSTATUS ldapsam_change_groupmem(struct pdb_methods *my_methods,
5519                                         TALLOC_CTX *tmp_ctx,
5520                                         uint32 group_rid,
5521                                         uint32 member_rid,
5522                                         int modop)
5523 {
5524         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5525         LDAPMessage *entry = NULL;
5526         LDAPMessage *result = NULL;
5527         uint32 num_result;
5528         LDAPMod **mods = NULL;
5529         char *filter;
5530         char *uidstr;
5531         const char *dn = NULL;
5532         DOM_SID group_sid;
5533         DOM_SID member_sid;
5534         int rc;
5535
5536         switch (modop) {
5537         case LDAP_MOD_ADD:
5538                 DEBUG(1,("ldapsam_change_groupmem: add new member(rid=%d) to a domain group(rid=%d)", member_rid, group_rid));
5539                 break;
5540         case LDAP_MOD_DELETE:
5541                 DEBUG(1,("ldapsam_change_groupmem: delete member(rid=%d) from a domain group(rid=%d)", member_rid, group_rid));
5542                 break;
5543         default:
5544                 return NT_STATUS_UNSUCCESSFUL;
5545         }
5546
5547         /* get member sid  */
5548         sid_compose(&member_sid, get_global_sam_sid(), member_rid);
5549
5550         /* get the group sid */
5551         sid_compose(&group_sid, get_global_sam_sid(), group_rid);
5552
5553         filter = talloc_asprintf(tmp_ctx,
5554                                  "(&(sambaSID=%s)"
5555                                  "(objectClass=%s)"
5556                                  "(objectClass=%s))",
5557                                  sid_string_talloc(tmp_ctx, &member_sid),
5558                                  LDAP_OBJ_POSIXACCOUNT,
5559                                  LDAP_OBJ_SAMBASAMACCOUNT);
5560         if (filter == NULL) {
5561                 return NT_STATUS_NO_MEMORY;
5562         }
5563
5564         /* get the member uid */
5565         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5566         if (rc != LDAP_SUCCESS) {
5567                 DEBUG(1,("ldapsam_change_groupmem: member search failed!\n"));
5568                 return NT_STATUS_UNSUCCESSFUL;
5569         }
5570         talloc_autofree_ldapmsg(tmp_ctx, result);
5571
5572         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5573
5574         if (num_result == 0) {
5575                 DEBUG(1,("ldapsam_change_groupmem: member not found!\n"));
5576                 return NT_STATUS_NO_SUCH_MEMBER;
5577         }
5578
5579         if (num_result > 1) {
5580                 DEBUG (0, ("ldapsam_change_groupmem: More than one account with the same SID ?!\n"));
5581                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5582         }
5583
5584         entry = ldap_first_entry(priv2ld(ldap_state), result);
5585         if (!entry) {
5586                 return NT_STATUS_UNSUCCESSFUL;
5587         }
5588
5589         if (modop == LDAP_MOD_DELETE) {
5590                 /* check if we are trying to remove the member from his primary group */
5591                 char *gidstr;
5592                 gid_t user_gid, group_gid;
5593
5594                 gidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "gidNumber", tmp_ctx);
5595                 if (!gidstr) {
5596                         DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's gid!\n"));
5597                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
5598                 }
5599
5600                 user_gid = strtoul(gidstr, NULL, 10);
5601
5602                 if (!sid_to_gid(&group_sid, &group_gid)) {
5603                         DEBUG (0, ("ldapsam_change_groupmem: Unable to get group gid from SID!\n"));
5604                         return NT_STATUS_UNSUCCESSFUL;
5605                 }
5606
5607                 if (user_gid == group_gid) {
5608                         DEBUG (3, ("ldapsam_change_groupmem: can't remove user from its own primary group!\n"));
5609                         return NT_STATUS_MEMBERS_PRIMARY_GROUP;
5610                 }
5611         }
5612
5613         /* here it is, retrieve the uid for later use */
5614         uidstr = smbldap_talloc_single_attribute(priv2ld(ldap_state), entry, "uid", tmp_ctx);
5615         if (!uidstr) {
5616                 DEBUG (0, ("ldapsam_change_groupmem: Unable to find the member's name!\n"));
5617                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5618         }
5619
5620         filter = talloc_asprintf(tmp_ctx,
5621                                  "(&(sambaSID=%s)"
5622                                  "(objectClass=%s)"
5623                                  "(objectClass=%s))",
5624                                  sid_string_talloc(tmp_ctx, &group_sid),
5625                                  LDAP_OBJ_POSIXGROUP,
5626                                  LDAP_OBJ_GROUPMAP);
5627
5628         /* get the group */
5629         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5630         if (rc != LDAP_SUCCESS) {
5631                 DEBUG(1,("ldapsam_change_groupmem: group search failed!\n"));
5632                 return NT_STATUS_UNSUCCESSFUL;
5633         }
5634         talloc_autofree_ldapmsg(tmp_ctx, result);
5635
5636         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5637
5638         if (num_result == 0) {
5639                 DEBUG(1,("ldapsam_change_groupmem: group not found!\n"));
5640                 return NT_STATUS_NO_SUCH_GROUP;
5641         }
5642
5643         if (num_result > 1) {
5644                 DEBUG (0, ("ldapsam_change_groupmem: More than one group with the same SID ?!\n"));
5645                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5646         }
5647
5648         entry = ldap_first_entry(priv2ld(ldap_state), result);
5649         if (!entry) {
5650                 return NT_STATUS_UNSUCCESSFUL;
5651         }
5652
5653         /* here it is, retrieve the dn for later use */
5654         dn = smbldap_talloc_dn(tmp_ctx, priv2ld(ldap_state), entry);
5655         if (!dn) {
5656                 DEBUG(0,("ldapsam_change_groupmem: Out of memory!\n"));
5657                 return NT_STATUS_NO_MEMORY;
5658         }
5659
5660         smbldap_set_mod(&mods, modop, "memberUid", uidstr);
5661
5662         talloc_autofree_ldapmod(tmp_ctx, mods);
5663
5664         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5665         if (rc != LDAP_SUCCESS) {
5666                 if (rc == LDAP_TYPE_OR_VALUE_EXISTS && modop == LDAP_MOD_ADD) {
5667                         DEBUG(1,("ldapsam_change_groupmem: member is already in group, add failed!\n"));
5668                         return NT_STATUS_MEMBER_IN_GROUP;
5669                 }
5670                 if (rc == LDAP_NO_SUCH_ATTRIBUTE && modop == LDAP_MOD_DELETE) {
5671                         DEBUG(1,("ldapsam_change_groupmem: member is not in group, delete failed!\n"));
5672                         return NT_STATUS_MEMBER_NOT_IN_GROUP;
5673                 }
5674                 return NT_STATUS_UNSUCCESSFUL;
5675         }
5676
5677         return NT_STATUS_OK;
5678 }
5679
5680 static NTSTATUS ldapsam_add_groupmem(struct pdb_methods *my_methods,
5681                                      TALLOC_CTX *tmp_ctx,
5682                                      uint32 group_rid,
5683                                      uint32 member_rid)
5684 {
5685         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_ADD);
5686 }
5687 static NTSTATUS ldapsam_del_groupmem(struct pdb_methods *my_methods,
5688                                      TALLOC_CTX *tmp_ctx,
5689                                      uint32 group_rid,
5690                                      uint32 member_rid)
5691 {
5692         return ldapsam_change_groupmem(my_methods, tmp_ctx, group_rid, member_rid, LDAP_MOD_DELETE);
5693 }
5694
5695 static NTSTATUS ldapsam_set_primary_group(struct pdb_methods *my_methods,
5696                                           TALLOC_CTX *mem_ctx,
5697                                           struct samu *sampass)
5698 {
5699         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
5700         LDAPMessage *entry = NULL;
5701         LDAPMessage *result = NULL;
5702         uint32 num_result;
5703         LDAPMod **mods = NULL;
5704         char *filter;
5705         char *escape_username;
5706         char *gidstr;
5707         const char *dn = NULL;
5708         gid_t gid;
5709         int rc;
5710
5711         DEBUG(0,("ldapsam_set_primary_group: Attempt to set primary group for user [%s]\n", pdb_get_username(sampass)));
5712
5713         if (!sid_to_gid(pdb_get_group_sid(sampass), &gid)) {
5714                 DEBUG(0,("ldapsam_set_primary_group: failed to retrieve gid from user's group SID!\n"));
5715                 return NT_STATUS_UNSUCCESSFUL;
5716         }
5717         gidstr = talloc_asprintf(mem_ctx, "%u", (unsigned int)gid);
5718         if (!gidstr) {
5719                 DEBUG(0,("ldapsam_set_primary_group: Out of Memory!\n"));
5720                 return NT_STATUS_NO_MEMORY;
5721         }
5722
5723         escape_username = escape_ldap_string(talloc_tos(),
5724                                              pdb_get_username(sampass));
5725         if (escape_username== NULL) {
5726                 return NT_STATUS_NO_MEMORY;
5727         }
5728
5729         filter = talloc_asprintf(mem_ctx,
5730                                  "(&(uid=%s)"
5731                                  "(objectClass=%s)"
5732                                  "(objectClass=%s))",
5733                                  escape_username,
5734                                  LDAP_OBJ_POSIXACCOUNT,
5735                                  LDAP_OBJ_SAMBASAMACCOUNT);
5736
5737         TALLOC_FREE(escape_username);
5738
5739         if (filter == NULL) {
5740                 return NT_STATUS_NO_MEMORY;
5741         }
5742
5743         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, NULL, &result);
5744         if (rc != LDAP_SUCCESS) {
5745                 DEBUG(0,("ldapsam_set_primary_group: user search failed!\n"));
5746                 return NT_STATUS_UNSUCCESSFUL;
5747         }
5748         talloc_autofree_ldapmsg(mem_ctx, result);
5749
5750         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5751
5752         if (num_result == 0) {
5753                 DEBUG(0,("ldapsam_set_primary_group: user not found!\n"));
5754                 return NT_STATUS_NO_SUCH_USER;
5755         }
5756
5757         if (num_result > 1) {
5758                 DEBUG (0, ("ldapsam_set_primary_group: More than one user with name [%s] ?!\n", pdb_get_username(sampass)));
5759                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
5760         }
5761
5762         entry = ldap_first_entry(priv2ld(ldap_state), result);
5763         if (!entry) {
5764                 return NT_STATUS_UNSUCCESSFUL;
5765         }
5766
5767         /* retrieve the dn for later use */
5768         dn = smbldap_talloc_dn(mem_ctx, priv2ld(ldap_state), entry);
5769         if (!dn) {
5770                 DEBUG(0,("ldapsam_set_primary_group: Out of memory!\n"));
5771                 return NT_STATUS_NO_MEMORY;
5772         }
5773
5774         /* remove the old one, and add the new one, this way we do not risk races */
5775         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "gidNumber", gidstr);
5776
5777         if (mods == NULL) {
5778                 return NT_STATUS_OK;
5779         }
5780
5781         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
5782
5783         if (rc != LDAP_SUCCESS) {
5784                 DEBUG(0,("ldapsam_set_primary_group: failed to modify [%s] primary group to [%s]\n",
5785                          pdb_get_username(sampass), gidstr));
5786                 return NT_STATUS_UNSUCCESSFUL;
5787         }
5788
5789         flush_pwnam_cache();
5790
5791         return NT_STATUS_OK;
5792 }
5793
5794
5795 /**********************************************************************
5796  trusted domains functions
5797  *********************************************************************/
5798
5799 static char *trusteddom_dn(struct ldapsam_privates *ldap_state,
5800                            const char *domain)
5801 {
5802         return talloc_asprintf(talloc_tos(), "sambaDomainName=%s,%s", domain,
5803                                ldap_state->domain_dn);
5804 }
5805
5806 static bool get_trusteddom_pw_int(struct ldapsam_privates *ldap_state,
5807                                   TALLOC_CTX *mem_ctx,
5808                                   const char *domain, LDAPMessage **entry)
5809 {
5810         int rc;
5811         char *filter;
5812         int scope = LDAP_SCOPE_SUBTREE;
5813         const char **attrs = NULL; /* NULL: get all attrs */
5814         int attrsonly = 0; /* 0: return values too */
5815         LDAPMessage *result = NULL;
5816         char *trusted_dn;
5817         uint32 num_result;
5818
5819         filter = talloc_asprintf(talloc_tos(),
5820                                  "(&(objectClass=%s)(sambaDomainName=%s))",
5821                                  LDAP_OBJ_TRUSTDOM_PASSWORD, domain);
5822
5823         trusted_dn = trusteddom_dn(ldap_state, domain);
5824         if (trusted_dn == NULL) {
5825                 return False;
5826         }
5827         rc = smbldap_search(ldap_state->smbldap_state, trusted_dn, scope,
5828                             filter, attrs, attrsonly, &result);
5829
5830         if (result != NULL) {
5831                 talloc_autofree_ldapmsg(mem_ctx, result);
5832         }
5833
5834         if (rc == LDAP_NO_SUCH_OBJECT) {
5835                 *entry = NULL;
5836                 return True;
5837         }
5838
5839         if (rc != LDAP_SUCCESS) {
5840                 return False;
5841         }
5842
5843         num_result = ldap_count_entries(priv2ld(ldap_state), result);
5844
5845         if (num_result > 1) {
5846                 DEBUG(1, ("ldapsam_get_trusteddom_pw: more than one "
5847                           "%s object for domain '%s'?!\n",
5848                           LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
5849                 return False;
5850         }
5851
5852         if (num_result == 0) {
5853                 DEBUG(1, ("ldapsam_get_trusteddom_pw: no "
5854                           "%s object for domain %s.\n",
5855                           LDAP_OBJ_TRUSTDOM_PASSWORD, domain));
5856                 *entry = NULL;
5857         } else {
5858                 *entry = ldap_first_entry(priv2ld(ldap_state), result);
5859         }
5860
5861         return True;
5862 }
5863
5864 static bool ldapsam_get_trusteddom_pw(struct pdb_methods *methods,
5865                                       const char *domain,
5866                                       char** pwd,
5867                                       DOM_SID *sid,
5868                                       time_t *pass_last_set_time)
5869 {
5870         struct ldapsam_privates *ldap_state =
5871                 (struct ldapsam_privates *)methods->private_data;
5872         LDAPMessage *entry = NULL;
5873
5874         DEBUG(10, ("ldapsam_get_trusteddom_pw called for domain %s\n", domain));
5875
5876         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry) ||
5877             (entry == NULL))
5878         {
5879                 return False;
5880         }
5881
5882         /* password */
5883         if (pwd != NULL) {
5884                 char *pwd_str;
5885                 pwd_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5886                                 entry, "sambaClearTextPassword", talloc_tos());
5887                 if (pwd_str == NULL) {
5888                         return False;
5889                 }
5890                 /* trusteddom_pw routines do not use talloc yet... */
5891                 *pwd = SMB_STRDUP(pwd_str);
5892                 if (*pwd == NULL) {
5893                         return False;
5894                 }
5895         }
5896
5897         /* last change time */
5898         if (pass_last_set_time != NULL) {
5899                 char *time_str;
5900                 time_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5901                                 entry, "sambaPwdLastSet", talloc_tos());
5902                 if (time_str == NULL) {
5903                         return False;
5904                 }
5905                 *pass_last_set_time = (time_t)atol(time_str);
5906         }
5907
5908         /* domain sid */
5909         if (sid != NULL) {
5910                 char *sid_str;
5911                 DOM_SID *dom_sid;
5912                 sid_str = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5913                                                           entry, "sambaSID",
5914                                                           talloc_tos());
5915                 if (sid_str == NULL) {
5916                         return False;
5917                 }
5918                 dom_sid = string_sid_talloc(talloc_tos(), sid_str);
5919                 if (dom_sid == NULL) {
5920                         return False;
5921                 }
5922                 sid_copy(sid, dom_sid);
5923         }
5924
5925         return True;
5926 }
5927
5928 static bool ldapsam_set_trusteddom_pw(struct pdb_methods *methods,
5929                                       const char* domain,
5930                                       const char* pwd,
5931                                       const DOM_SID *sid)
5932 {
5933         struct ldapsam_privates *ldap_state =
5934                 (struct ldapsam_privates *)methods->private_data;
5935         LDAPMessage *entry = NULL;
5936         LDAPMod **mods = NULL;
5937         char *prev_pwd = NULL;
5938         char *trusted_dn = NULL;
5939         int rc;
5940
5941         DEBUG(10, ("ldapsam_set_trusteddom_pw called for domain %s\n", domain));
5942
5943         /*
5944          * get the current entry (if there is one) in order to put the
5945          * current password into the previous password attribute
5946          */
5947         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
5948                 return False;
5949         }
5950
5951         mods = NULL;
5952         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "objectClass",
5953                          LDAP_OBJ_TRUSTDOM_PASSWORD);
5954         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaDomainName",
5955                          domain);
5956         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaSID",
5957                          sid_string_tos(sid));
5958         smbldap_make_mod(priv2ld(ldap_state), entry, &mods, "sambaPwdLastSet",
5959                          talloc_asprintf(talloc_tos(), "%li", (long int)time(NULL)));
5960         smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
5961                          "sambaClearTextPassword", pwd);
5962
5963         talloc_autofree_ldapmod(talloc_tos(), mods);
5964
5965         if (entry != NULL) {
5966                 prev_pwd = smbldap_talloc_single_attribute(priv2ld(ldap_state),
5967                                 entry, "sambaClearTextPassword", talloc_tos());
5968                 if (prev_pwd != NULL) {
5969                         smbldap_make_mod(priv2ld(ldap_state), entry, &mods,
5970                                          "sambaPreviousClearTextPassword",
5971                                          prev_pwd);
5972                 }
5973         }
5974
5975         trusted_dn = trusteddom_dn(ldap_state, domain);
5976         if (trusted_dn == NULL) {
5977                 return False;
5978         }
5979         if (entry == NULL) {
5980                 rc = smbldap_add(ldap_state->smbldap_state, trusted_dn, mods);
5981         } else {
5982                 rc = smbldap_modify(ldap_state->smbldap_state, trusted_dn, mods);
5983         }
5984
5985         if (rc != LDAP_SUCCESS) {
5986                 DEBUG(1, ("error writing trusted domain password!\n"));
5987                 return False;
5988         }
5989
5990         return True;
5991 }
5992
5993 static bool ldapsam_del_trusteddom_pw(struct pdb_methods *methods,
5994                                       const char *domain)
5995 {
5996         int rc;
5997         struct ldapsam_privates *ldap_state =
5998                 (struct ldapsam_privates *)methods->private_data;
5999         LDAPMessage *entry = NULL;
6000         const char *trusted_dn;
6001
6002         if (!get_trusteddom_pw_int(ldap_state, talloc_tos(), domain, &entry)) {
6003                 return False;
6004         }
6005
6006         if (entry == NULL) {
6007                 DEBUG(5, ("ldapsam_del_trusteddom_pw: no such trusted domain: "
6008                           "%s\n", domain));
6009                 return True;
6010         }
6011
6012         trusted_dn = smbldap_talloc_dn(talloc_tos(), priv2ld(ldap_state),
6013                                        entry);
6014         if (trusted_dn == NULL) {
6015                 DEBUG(0,("ldapsam_del_trusteddom_pw: Out of memory!\n"));
6016                 return False;
6017         }
6018
6019         rc = smbldap_delete(ldap_state->smbldap_state, trusted_dn);
6020         if (rc != LDAP_SUCCESS) {
6021                 return False;
6022         }
6023
6024         return True;
6025 }
6026
6027 static NTSTATUS ldapsam_enum_trusteddoms(struct pdb_methods *methods,
6028                                          TALLOC_CTX *mem_ctx,
6029                                          uint32 *num_domains,
6030                                          struct trustdom_info ***domains)
6031 {
6032         int rc;
6033         struct ldapsam_privates *ldap_state =
6034                 (struct ldapsam_privates *)methods->private_data;
6035         char *filter;
6036         int scope = LDAP_SCOPE_SUBTREE;
6037         const char *attrs[] = { "sambaDomainName", "sambaSID", NULL };
6038         int attrsonly = 0; /* 0: return values too */
6039         LDAPMessage *result = NULL;
6040         LDAPMessage *entry = NULL;
6041
6042         filter = talloc_asprintf(talloc_tos(), "(objectClass=%s)",
6043                                  LDAP_OBJ_TRUSTDOM_PASSWORD);
6044
6045         rc = smbldap_search(ldap_state->smbldap_state,
6046                             ldap_state->domain_dn,
6047                             scope,
6048                             filter,
6049                             attrs,
6050                             attrsonly,
6051                             &result);
6052
6053         if (result != NULL) {
6054                 talloc_autofree_ldapmsg(mem_ctx, result);
6055         }
6056
6057         if (rc != LDAP_SUCCESS) {
6058                 return NT_STATUS_UNSUCCESSFUL;
6059         }
6060
6061         *num_domains = 0;
6062         if (!(*domains = TALLOC_ARRAY(mem_ctx, struct trustdom_info *, 1))) {
6063                 DEBUG(1, ("talloc failed\n"));
6064                 return NT_STATUS_NO_MEMORY;
6065         }
6066
6067         for (entry = ldap_first_entry(priv2ld(ldap_state), result);
6068              entry != NULL;
6069              entry = ldap_next_entry(priv2ld(ldap_state), entry))
6070         {
6071                 char *dom_name, *dom_sid_str;
6072                 struct trustdom_info *dom_info;
6073
6074                 dom_info = TALLOC_P(*domains, struct trustdom_info);
6075                 if (dom_info == NULL) {
6076                         DEBUG(1, ("talloc failed\n"));
6077                         return NT_STATUS_NO_MEMORY;
6078                 }
6079
6080                 dom_name = smbldap_talloc_single_attribute(priv2ld(ldap_state),
6081                                                            entry,
6082                                                            "sambaDomainName",
6083                                                            talloc_tos());
6084                 if (dom_name == NULL) {
6085                         DEBUG(1, ("talloc failed\n"));
6086                         return NT_STATUS_NO_MEMORY;
6087                 }
6088                 dom_info->name = dom_name;
6089
6090                 dom_sid_str = smbldap_talloc_single_attribute(
6091                                         priv2ld(ldap_state), entry, "sambaSID",
6092                                         talloc_tos());
6093                 if (dom_sid_str == NULL) {
6094                         DEBUG(1, ("talloc failed\n"));
6095                         return NT_STATUS_NO_MEMORY;
6096                 }
6097                 if (!string_to_sid(&dom_info->sid, dom_sid_str)) {
6098                         DEBUG(1, ("Error calling string_to_sid on SID %s\n",
6099                                   dom_sid_str));
6100                         return NT_STATUS_UNSUCCESSFUL;
6101                 }
6102
6103                 ADD_TO_ARRAY(*domains, struct trustdom_info *, dom_info,
6104                              domains, num_domains);
6105
6106                 if (*domains == NULL) {
6107                         DEBUG(1, ("talloc failed\n"));
6108                         return NT_STATUS_NO_MEMORY;
6109                 }
6110         }
6111
6112         DEBUG(5, ("ldapsam_enum_trusteddoms: got %d domains\n", *num_domains));
6113         return NT_STATUS_OK;
6114 }
6115
6116
6117 /**********************************************************************
6118  Housekeeping
6119  *********************************************************************/
6120
6121 static void free_private_data(void **vp) 
6122 {
6123         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
6124
6125         smbldap_free_struct(&(*ldap_state)->smbldap_state);
6126
6127         if ((*ldap_state)->result != NULL) {
6128                 ldap_msgfree((*ldap_state)->result);
6129                 (*ldap_state)->result = NULL;
6130         }
6131         if ((*ldap_state)->domain_dn != NULL) {
6132                 SAFE_FREE((*ldap_state)->domain_dn);
6133         }
6134
6135         *ldap_state = NULL;
6136
6137         /* No need to free any further, as it is talloc()ed */
6138 }
6139
6140 /*********************************************************************
6141  Intitalise the parts of the pdb_methods structure that are common to 
6142  all pdb_ldap modes
6143 *********************************************************************/
6144
6145 static NTSTATUS pdb_init_ldapsam_common(struct pdb_methods **pdb_method, const char *location)
6146 {
6147         NTSTATUS nt_status;
6148         struct ldapsam_privates *ldap_state;
6149
6150         if (!NT_STATUS_IS_OK(nt_status = make_pdb_method( pdb_method ))) {
6151                 return nt_status;
6152         }
6153
6154         (*pdb_method)->name = "ldapsam";
6155
6156         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
6157         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
6158         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
6159         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
6160         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
6161         (*pdb_method)->rename_sam_account = ldapsam_rename_sam_account;
6162
6163         (*pdb_method)->getgrsid = ldapsam_getgrsid;
6164         (*pdb_method)->getgrgid = ldapsam_getgrgid;
6165         (*pdb_method)->getgrnam = ldapsam_getgrnam;
6166         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
6167         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
6168         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
6169         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
6170
6171         (*pdb_method)->get_account_policy = ldapsam_get_account_policy;
6172         (*pdb_method)->set_account_policy = ldapsam_set_account_policy;
6173
6174         (*pdb_method)->get_seq_num = ldapsam_get_seq_num;
6175
6176         (*pdb_method)->capabilities = ldapsam_capabilities;
6177         (*pdb_method)->new_rid = ldapsam_new_rid;
6178
6179         (*pdb_method)->get_trusteddom_pw = ldapsam_get_trusteddom_pw;
6180         (*pdb_method)->set_trusteddom_pw = ldapsam_set_trusteddom_pw;
6181         (*pdb_method)->del_trusteddom_pw = ldapsam_del_trusteddom_pw;
6182         (*pdb_method)->enum_trusteddoms = ldapsam_enum_trusteddoms;
6183
6184         /* TODO: Setup private data and free */
6185
6186         if ( !(ldap_state = TALLOC_ZERO_P(*pdb_method, struct ldapsam_privates)) ) {
6187                 DEBUG(0, ("pdb_init_ldapsam_common: talloc() failed for ldapsam private_data!\n"));
6188                 return NT_STATUS_NO_MEMORY;
6189         }
6190
6191         nt_status = smbldap_init(*pdb_method, pdb_get_event_context(),
6192                                  location, &ldap_state->smbldap_state);
6193
6194         if ( !NT_STATUS_IS_OK(nt_status) ) {
6195                 return nt_status;
6196         }
6197
6198         if ( !(ldap_state->domain_name = talloc_strdup(*pdb_method, get_global_sam_name()) ) ) {
6199                 return NT_STATUS_NO_MEMORY;
6200         }
6201
6202         (*pdb_method)->private_data = ldap_state;
6203
6204         (*pdb_method)->free_private_data = free_private_data;
6205
6206         return NT_STATUS_OK;
6207 }
6208
6209 /**********************************************************************
6210  Initialise the 'compat' mode for pdb_ldap
6211  *********************************************************************/
6212
6213 NTSTATUS pdb_init_ldapsam_compat(struct pdb_methods **pdb_method, const char *location)
6214 {
6215         NTSTATUS nt_status;
6216         struct ldapsam_privates *ldap_state;
6217         char *uri = talloc_strdup( NULL, location );
6218
6219         trim_char( uri, '\"', '\"' );
6220         nt_status = pdb_init_ldapsam_common( pdb_method, uri );
6221         if ( uri )
6222                 TALLOC_FREE( uri );
6223
6224         if ( !NT_STATUS_IS_OK(nt_status) ) {
6225                 return nt_status;
6226         }
6227
6228         (*pdb_method)->name = "ldapsam_compat";
6229
6230         ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6231         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
6232
6233         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
6234
6235         return NT_STATUS_OK;
6236 }
6237
6238 /**********************************************************************
6239  Initialise the normal mode for pdb_ldap
6240  *********************************************************************/
6241
6242 NTSTATUS pdb_init_ldapsam(struct pdb_methods **pdb_method, const char *location)
6243 {
6244         NTSTATUS nt_status;
6245         struct ldapsam_privates *ldap_state = NULL;
6246         uint32 alg_rid_base;
6247         char *alg_rid_base_string = NULL;
6248         LDAPMessage *result = NULL;
6249         LDAPMessage *entry = NULL;
6250         DOM_SID ldap_domain_sid;
6251         DOM_SID secrets_domain_sid;
6252         char *domain_sid_string = NULL;
6253         char *dn = NULL;
6254         char *uri = talloc_strdup( NULL, location );
6255
6256         trim_char( uri, '\"', '\"' );
6257         nt_status = pdb_init_ldapsam_common(pdb_method, uri);
6258         if (uri) {
6259                 TALLOC_FREE(uri);
6260         }
6261
6262         if (!NT_STATUS_IS_OK(nt_status)) {
6263                 return nt_status;
6264         }
6265
6266         (*pdb_method)->name = "ldapsam";
6267
6268         (*pdb_method)->add_aliasmem = ldapsam_add_aliasmem;
6269         (*pdb_method)->del_aliasmem = ldapsam_del_aliasmem;
6270         (*pdb_method)->enum_aliasmem = ldapsam_enum_aliasmem;
6271         (*pdb_method)->enum_alias_memberships = ldapsam_alias_memberships;
6272         (*pdb_method)->search_users = ldapsam_search_users;
6273         (*pdb_method)->search_groups = ldapsam_search_groups;
6274         (*pdb_method)->search_aliases = ldapsam_search_aliases;
6275
6276         if (lp_parm_bool(-1, "ldapsam", "trusted", False)) {
6277                 (*pdb_method)->enum_group_members = ldapsam_enum_group_members;
6278                 (*pdb_method)->enum_group_memberships =
6279                         ldapsam_enum_group_memberships;
6280                 (*pdb_method)->lookup_rids = ldapsam_lookup_rids;
6281                 (*pdb_method)->sid_to_id = ldapsam_sid_to_id;
6282
6283                 if (lp_parm_bool(-1, "ldapsam", "editposix", False)) {
6284                         (*pdb_method)->create_user = ldapsam_create_user;
6285                         (*pdb_method)->delete_user = ldapsam_delete_user;
6286                         (*pdb_method)->create_dom_group = ldapsam_create_dom_group;
6287                         (*pdb_method)->delete_dom_group = ldapsam_delete_dom_group;
6288                         (*pdb_method)->add_groupmem = ldapsam_add_groupmem;
6289                         (*pdb_method)->del_groupmem = ldapsam_del_groupmem;
6290                         (*pdb_method)->set_unix_primary_group = ldapsam_set_primary_group;
6291                 }
6292         }
6293
6294         ldap_state = (struct ldapsam_privates *)((*pdb_method)->private_data);
6295         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
6296
6297         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
6298
6299         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state,
6300                                                &result,
6301                                                ldap_state->domain_name, True);
6302
6303         if ( !NT_STATUS_IS_OK(nt_status) ) {
6304                 DEBUG(2, ("pdb_init_ldapsam: WARNING: Could not get domain "
6305                           "info, nor add one to the domain\n"));
6306                 DEBUGADD(2, ("pdb_init_ldapsam: Continuing on regardless, "
6307                              "will be unable to allocate new users/groups, "
6308                              "and will risk BDCs having inconsistant SIDs\n"));
6309                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
6310                 return NT_STATUS_OK;
6311         }
6312
6313         /* Given that the above might fail, everything below this must be
6314          * optional */
6315
6316         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
6317                                  result);
6318         if (!entry) {
6319                 DEBUG(0, ("pdb_init_ldapsam: Could not get domain info "
6320                           "entry\n"));
6321                 ldap_msgfree(result);
6322                 return NT_STATUS_UNSUCCESSFUL;
6323         }
6324
6325         dn = smbldap_talloc_dn(talloc_tos(), ldap_state->smbldap_state->ldap_struct, entry);
6326         if (!dn) {
6327                 ldap_msgfree(result);
6328                 return NT_STATUS_UNSUCCESSFUL;
6329         }
6330
6331         ldap_state->domain_dn = smb_xstrdup(dn);
6332         TALLOC_FREE(dn);
6333
6334         domain_sid_string = smbldap_talloc_single_attribute(
6335                     ldap_state->smbldap_state->ldap_struct,
6336                     entry,
6337                     get_userattr_key2string(ldap_state->schema_ver,
6338                                             LDAP_ATTR_USER_SID),
6339                     talloc_tos());
6340
6341         if (domain_sid_string) {
6342                 bool found_sid;
6343                 if (!string_to_sid(&ldap_domain_sid, domain_sid_string)) {
6344                         DEBUG(1, ("pdb_init_ldapsam: SID [%s] could not be "
6345                                   "read as a valid SID\n", domain_sid_string));
6346                         ldap_msgfree(result);
6347                         TALLOC_FREE(domain_sid_string);
6348                         return NT_STATUS_INVALID_PARAMETER;
6349                 }
6350                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name,
6351                                                      &secrets_domain_sid);
6352                 if (!found_sid || !sid_equal(&secrets_domain_sid,
6353                                              &ldap_domain_sid)) {
6354                         DEBUG(1, ("pdb_init_ldapsam: Resetting SID for domain "
6355                                   "%s based on pdb_ldap results %s -> %s\n",
6356                                   ldap_state->domain_name,
6357                                   sid_string_dbg(&secrets_domain_sid),
6358                                   sid_string_dbg(&ldap_domain_sid)));
6359
6360                         /* reset secrets.tdb sid */
6361                         secrets_store_domain_sid(ldap_state->domain_name,
6362                                                  &ldap_domain_sid);
6363                         DEBUG(1, ("New global sam SID: %s\n",
6364                                   sid_string_dbg(get_global_sam_sid())));
6365                 }
6366                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
6367                 TALLOC_FREE(domain_sid_string);
6368         }
6369
6370         alg_rid_base_string = smbldap_talloc_single_attribute(
6371                     ldap_state->smbldap_state->ldap_struct,
6372                     entry,
6373                     get_attr_key2string( dominfo_attr_list,
6374                                          LDAP_ATTR_ALGORITHMIC_RID_BASE ),
6375                     talloc_tos());
6376         if (alg_rid_base_string) {
6377                 alg_rid_base = (uint32)atol(alg_rid_base_string);
6378                 if (alg_rid_base != algorithmic_rid_base()) {
6379                         DEBUG(0, ("The value of 'algorithmic RID base' has "
6380                                   "changed since the LDAP\n"
6381                                   "database was initialised.  Aborting. \n"));
6382                         ldap_msgfree(result);
6383                         TALLOC_FREE(alg_rid_base_string);
6384                         return NT_STATUS_UNSUCCESSFUL;
6385                 }
6386                 TALLOC_FREE(alg_rid_base_string);
6387         }
6388         ldap_msgfree(result);
6389
6390         return NT_STATUS_OK;
6391 }
6392
6393 NTSTATUS pdb_ldap_init(void)
6394 {
6395         NTSTATUS nt_status;
6396         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
6397                 return nt_status;
6398
6399         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
6400                 return nt_status;
6401
6402         /* Let pdb_nds register backends */
6403         pdb_nds_init();
6404
6405         return NT_STATUS_OK;
6406 }