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