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