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