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