get rid of some sompiler warnings on IRIX
[ira/wip.git] / source3 / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/CIFS mplementation.
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
9     
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
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/SAM_ACCOUNT
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 "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 #ifndef SAM_ACCOUNT
81 #define SAM_ACCOUNT struct sam_passwd
82 #endif
83
84 #include "smbldap.h"
85
86 struct ldapsam_privates {
87         struct smbldap_state *smbldap_state;
88
89         /* Former statics */
90         LDAPMessage *result;
91         LDAPMessage *entry;
92         int index;
93         
94         const char *domain_name;
95         DOM_SID domain_sid;
96         
97         /* configuration items */
98         int schema_ver;
99 };
100
101 /**********************************************************************
102  Free a LDAPMessage (one is stored on the SAM_ACCOUNT)
103  **********************************************************************/
104  
105 static void private_data_free_fn(void **result) 
106 {
107         ldap_msgfree(*result);
108         *result = NULL;
109 }
110
111 /**********************************************************************
112  get the attribute name given a user schame version 
113  **********************************************************************/
114  
115 static const char* get_userattr_key2string( int schema_ver, int key )
116 {
117         switch ( schema_ver )
118         {
119                 case SCHEMAVER_SAMBAACCOUNT:
120                         return get_attr_key2string( attrib_map_v22, key );
121                         
122                 case SCHEMAVER_SAMBASAMACCOUNT:
123                         return get_attr_key2string( attrib_map_v30, key );
124                         
125                 default:
126                         DEBUG(0,("get_userattr_key2string: unknown schema version specified\n"));
127                         break;
128         }
129         return NULL;
130 }
131
132 /**********************************************************************
133  return the list of attribute names given a user schema version 
134  **********************************************************************/
135
136 static char** get_userattr_list( int schema_ver )
137 {
138         switch ( schema_ver ) 
139         {
140                 case SCHEMAVER_SAMBAACCOUNT:
141                         return get_attr_list( attrib_map_v22 );
142                         
143                 case SCHEMAVER_SAMBASAMACCOUNT:
144                         return get_attr_list( attrib_map_v30 );
145                 default:
146                         DEBUG(0,("get_userattr_list: unknown schema version specified!\n"));
147                         break;
148         }
149         
150         return NULL;
151 }
152 /*******************************************************************
153  generate the LDAP search filter for the objectclass based on the 
154  version of the schema we are using 
155  ******************************************************************/
156
157 static const char* get_objclass_filter( int schema_ver )
158 {
159         static fstring objclass_filter;
160         
161         switch( schema_ver ) 
162         {
163                 case SCHEMAVER_SAMBAACCOUNT:
164                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBAACCOUNT );
165                         break;
166                 case SCHEMAVER_SAMBASAMACCOUNT:
167                         fstr_sprintf( objclass_filter, "(objectclass=%s)", LDAP_OBJ_SAMBASAMACCOUNT );
168                         break;
169                 default:
170                         DEBUG(0,("pdb_ldapsam: get_objclass_filter(): Invalid schema version specified!\n"));
171                         break;
172         }
173         
174         return objclass_filter; 
175 }
176
177 /*******************************************************************
178  run the search by name.
179 ******************************************************************/
180 static int ldapsam_search_suffix_by_name (struct ldapsam_privates *ldap_state, 
181                                           const char *user,
182                                           LDAPMessage ** result, char **attr)
183 {
184         pstring filter;
185         char *escape_user = escape_ldap_string_alloc(user);
186
187         if (!escape_user) {
188                 return LDAP_NO_MEMORY;
189         }
190
191         /*
192          * in the filter expression, replace %u with the real name
193          * so in ldap filter, %u MUST exist :-)
194          */
195         pstr_sprintf(filter, "(&%s%s)", lp_ldap_filter(), 
196                 get_objclass_filter(ldap_state->schema_ver));
197
198         /* 
199          * have to use this here because $ is filtered out
200            * in pstring_sub
201          */
202         
203
204         all_string_sub(filter, "%u", escape_user, sizeof(pstring));
205         SAFE_FREE(escape_user);
206
207         return smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
208 }
209
210 /*******************************************************************
211  run the search by rid.
212 ******************************************************************/
213 static int ldapsam_search_suffix_by_rid (struct ldapsam_privates *ldap_state, 
214                                          uint32 rid, LDAPMessage ** result, 
215                                          char **attr)
216 {
217         pstring filter;
218         int rc;
219
220         pstr_sprintf(filter, "(&(rid=%i)%s)", rid, 
221                 get_objclass_filter(ldap_state->schema_ver));
222         
223         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
224         
225         return rc;
226 }
227
228 /*******************************************************************
229  run the search by SID.
230 ******************************************************************/
231 static int ldapsam_search_suffix_by_sid (struct ldapsam_privates *ldap_state, 
232                                          const DOM_SID *sid, LDAPMessage ** result, 
233                                          char **attr)
234 {
235         pstring filter;
236         int rc;
237         fstring sid_string;
238
239         pstr_sprintf(filter, "(&(%s=%s)%s)", 
240                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
241                 sid_to_string(sid_string, sid), 
242                 get_objclass_filter(ldap_state->schema_ver));
243                 
244         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, attr, result);
245         
246         return rc;
247 }
248
249 /*******************************************************************
250  Delete complete object or objectclass and attrs from
251  object found in search_result depending on lp_ldap_delete_dn
252 ******************************************************************/
253 static NTSTATUS ldapsam_delete_entry(struct ldapsam_privates *ldap_state,
254                                      LDAPMessage *result,
255                                      const char *objectclass,
256                                      char **attrs)
257 {
258         int rc;
259         LDAPMessage *entry;
260         LDAPMod **mods = NULL;
261         char *name, *dn;
262         BerElement *ptr = NULL;
263
264         rc = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
265
266         if (rc != 1) {
267                 DEBUG(0, ("Entry must exist exactly once!\n"));
268                 return NT_STATUS_UNSUCCESSFUL;
269         }
270
271         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
272         dn    = ldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
273
274         if (lp_ldap_delete_dn()) {
275                 NTSTATUS ret = NT_STATUS_OK;
276                 rc = smbldap_delete(ldap_state->smbldap_state, dn);
277
278                 if (rc != LDAP_SUCCESS) {
279                         DEBUG(0, ("Could not delete object %s\n", dn));
280                         ret = NT_STATUS_UNSUCCESSFUL;
281                 }
282                 ldap_memfree(dn);
283                 return ret;
284         }
285
286         /* Ok, delete only the SAM attributes */
287         
288         for (name = ldap_first_attribute(ldap_state->smbldap_state->ldap_struct, entry, &ptr);
289              name != NULL;
290              name = ldap_next_attribute(ldap_state->smbldap_state->ldap_struct, entry, ptr)) 
291         {
292                 char **attrib;
293
294                 /* We are only allowed to delete the attributes that
295                    really exist. */
296
297                 for (attrib = attrs; *attrib != NULL; attrib++) 
298                 {
299                         if (StrCaseCmp(*attrib, name) == 0) {
300                                 DEBUG(10, ("deleting attribute %s\n", name));
301                                 smbldap_set_mod(&mods, LDAP_MOD_DELETE, name, NULL);
302                         }
303                 }
304
305                 ldap_memfree(name);
306         }
307         
308         if (ptr != NULL) {
309                 ber_free(ptr, 0);
310         }
311         
312         smbldap_set_mod(&mods, LDAP_MOD_DELETE, "objectClass", objectclass);
313
314         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
315         ldap_mods_free(mods, True);
316
317         if (rc != LDAP_SUCCESS) {
318                 char *ld_error = NULL;
319                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
320                                 &ld_error);
321                 
322                 DEBUG(0, ("could not delete attributes for %s, error: %s (%s)\n",
323                           dn, ldap_err2string(rc), ld_error?ld_error:"unknown"));
324                 SAFE_FREE(ld_error);
325                 ldap_memfree(dn);
326                 return NT_STATUS_UNSUCCESSFUL;
327         }
328
329         ldap_memfree(dn);
330         return NT_STATUS_OK;
331 }
332                   
333
334 /* New Interface is being implemented here */
335
336 /**********************************************************************
337 Initialize SAM_ACCOUNT from an LDAP query (unix attributes only)
338 *********************************************************************/
339 static BOOL get_unix_attributes (struct ldapsam_privates *ldap_state, 
340                                 SAM_ACCOUNT * sampass,
341                                 LDAPMessage * entry,
342                                 gid_t *gid)
343 {
344         pstring  homedir;
345         pstring  temp;
346         char **ldap_values;
347         char **values;
348
349         if ((ldap_values = ldap_get_values (ldap_state->smbldap_state->ldap_struct, entry, "objectClass")) == NULL) {
350                 DEBUG (1, ("get_unix_attributes: no objectClass! \n"));
351                 return False;
352         }
353
354         for (values=ldap_values;*values;values++) {
355                 if (strcasecmp(*values, LDAP_OBJ_POSIXACCOUNT ) == 0) {
356                         break;
357                 }
358         }
359         
360         if (!*values) { /*end of array, no posixAccount */
361                 DEBUG(10, ("user does not have %s attributes\n", LDAP_OBJ_POSIXACCOUNT));
362                 ldap_value_free(ldap_values);
363                 return False;
364         }
365         ldap_value_free(ldap_values);
366
367         if ( !smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
368                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_UNIX_HOME), homedir) ) 
369         {
370                 return False;
371         }
372         
373         if ( !smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
374                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_GIDNUMBER), temp) )
375         {
376                 return False;
377         }
378         
379         *gid = (gid_t)atol(temp);
380
381         pdb_set_unix_homedir(sampass, homedir, PDB_SET);
382         
383         DEBUG(10, ("user has %s attributes\n", LDAP_OBJ_POSIXACCOUNT));
384         
385         return True;
386 }
387
388
389 /**********************************************************************
390 Initialize SAM_ACCOUNT from an LDAP query
391 (Based on init_sam_from_buffer in pdb_tdb.c)
392 *********************************************************************/
393 static BOOL init_sam_from_ldap (struct ldapsam_privates *ldap_state, 
394                                 SAM_ACCOUNT * sampass,
395                                 LDAPMessage * entry)
396 {
397         time_t  logon_time,
398                         logoff_time,
399                         kickoff_time,
400                         pass_last_set_time, 
401                         pass_can_change_time, 
402                         pass_must_change_time;
403         pstring         username, 
404                         domain,
405                         nt_username,
406                         fullname,
407                         homedir,
408                         dir_drive,
409                         logon_script,
410                         profile_path,
411                         acct_desc,
412                         munged_dial,
413                         workstations;
414         uint32          user_rid; 
415         uint8           smblmpwd[LM_HASH_LEN],
416                         smbntpwd[NT_HASH_LEN];
417         uint16          acct_ctrl = 0, 
418                         logon_divs;
419         uint32 hours_len;
420         uint8           hours[MAX_HOURS_LEN];
421         pstring temp;
422         struct passwd   *pw = NULL;
423         uid_t           uid = -1;
424         gid_t           gid = -1;
425
426         /*
427          * do a little initialization
428          */
429         username[0]     = '\0';
430         domain[0]       = '\0';
431         nt_username[0]  = '\0';
432         fullname[0]     = '\0';
433         homedir[0]      = '\0';
434         dir_drive[0]    = '\0';
435         logon_script[0] = '\0';
436         profile_path[0] = '\0';
437         acct_desc[0]    = '\0';
438         munged_dial[0]  = '\0';
439         workstations[0] = '\0';
440          
441
442         if (sampass == NULL || ldap_state == NULL || entry == NULL) {
443                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
444                 return False;
445         }
446
447         if (ldap_state->smbldap_state->ldap_struct == NULL) {
448                 DEBUG(0, ("init_sam_from_ldap: ldap_state->smbldap_state->ldap_struct is NULL!\n"));
449                 return False;
450         }
451         
452         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, "uid", username)) {
453                 DEBUG(1, ("No uid attribute found for this user!\n"));
454                 return False;
455         }
456
457         DEBUG(2, ("Entry found for user: %s\n", username));
458
459         /* I'm not going to fail here, since there are checks 
460            higher up the cal stack to do this   --jerry */
461
462         if ( (pw=Get_Pwnam(username)) != NULL ) {
463                 uid = pw->pw_uid;
464                 gid = pw->pw_gid;
465         }
466
467         pstrcpy(nt_username, username);
468
469         pstrcpy(domain, ldap_state->domain_name);
470         
471         pdb_set_username(sampass, username, PDB_SET);
472
473         pdb_set_domain(sampass, domain, PDB_DEFAULT);
474         pdb_set_nt_username(sampass, nt_username, PDB_SET);
475
476         /* deal with different attributes between the schema first */
477         
478         if ( ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT ) 
479         {
480                 if (smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
481                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), temp)) 
482                 {
483                         pdb_set_user_sid_from_string(sampass, temp, PDB_SET);
484                 }
485                 
486                 if (smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
487                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_SID), temp)) 
488                 {
489                         pdb_set_group_sid_from_string(sampass, temp, PDB_SET);                  
490                 }
491                 else 
492                 {
493                         pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
494                 }
495
496
497         } 
498         else 
499         {
500                 if (smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
501                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), temp)) 
502                 {
503                         user_rid = (uint32)atol(temp);
504                         pdb_set_user_sid_from_rid(sampass, user_rid, PDB_SET);
505                 }
506                 
507                 if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
508                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PRIMARY_GROUP_RID), temp)) 
509                 {
510                         pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
511                 } else {
512                         uint32 group_rid;
513                         
514                         group_rid = (uint32)atol(temp);
515                         
516                         /* for some reason, we often have 0 as a primary group RID.
517                            Make sure that we treat this just as a 'default' value */
518                            
519                         if ( group_rid > 0 )
520                                 pdb_set_group_sid_from_rid(sampass, group_rid, PDB_SET);
521                         else
522                                 pdb_set_group_sid_from_rid(sampass, DOMAIN_GROUP_RID_USERS, PDB_DEFAULT);
523                 }
524         }
525
526         if (pdb_get_init_flags(sampass,PDB_USERSID) == PDB_DEFAULT) {
527                 DEBUG(1, ("no %s or %s attribute found for this user %s\n", 
528                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
529                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID),
530                         username));
531                 return False;
532         }
533
534
535         /* 
536          * If so configured, try and get the values from LDAP 
537          */
538
539         if (lp_ldap_trust_ids() && (get_unix_attributes(ldap_state, sampass, entry, &gid))) 
540         {       
541                 if (pdb_get_init_flags(sampass,PDB_GROUPSID) == PDB_DEFAULT) 
542                 {
543                         GROUP_MAP map;
544                         /* call the mapping code here */
545                         if(pdb_getgrgid(&map, gid)) {
546                                 pdb_set_group_sid(sampass, &map.sid, PDB_SET);
547                         } 
548                         else {
549                                 pdb_set_group_sid_from_rid(sampass, pdb_gid_to_group_rid(gid), PDB_SET);
550                         }
551                 }
552         }
553
554         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
555                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), temp)) 
556         {
557                 /* leave as default */
558         } else {
559                 pass_last_set_time = (time_t) atol(temp);
560                 pdb_set_pass_last_set_time(sampass, pass_last_set_time, PDB_SET);
561         }
562
563         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
564                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp)) 
565         {
566                 /* leave as default */
567         } else {
568                 logon_time = (time_t) atol(temp);
569                 pdb_set_logon_time(sampass, logon_time, PDB_SET);
570         }
571
572         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
573                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp)) 
574         {
575                 /* leave as default */
576         } else {
577                 logoff_time = (time_t) atol(temp);
578                 pdb_set_logoff_time(sampass, logoff_time, PDB_SET);
579         }
580
581         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
582                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp)) 
583         {
584                 /* leave as default */
585         } else {
586                 kickoff_time = (time_t) atol(temp);
587                 pdb_set_kickoff_time(sampass, kickoff_time, PDB_SET);
588         }
589
590         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
591                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp)) 
592         {
593                 /* leave as default */
594         } else {
595                 pass_can_change_time = (time_t) atol(temp);
596                 pdb_set_pass_can_change_time(sampass, pass_can_change_time, PDB_SET);
597         }
598
599         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
600                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp)) 
601         {       
602                 /* leave as default */
603         } else {
604                 pass_must_change_time = (time_t) atol(temp);
605                 pdb_set_pass_must_change_time(sampass, pass_must_change_time, PDB_SET);
606         }
607
608         /* recommend that 'gecos' and 'displayName' should refer to the same
609          * attribute OID.  userFullName depreciated, only used by Samba
610          * primary rules of LDAP: don't make a new attribute when one is already defined
611          * that fits your needs; using cn then displayName rather than 'userFullName'
612          */
613
614         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
615                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), fullname)) 
616         {
617                 if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
618                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_CN), fullname)) 
619                 {
620                         /* leave as default */
621                 } else {
622                         pdb_set_fullname(sampass, fullname, PDB_SET);
623                 }
624         } else {
625                 pdb_set_fullname(sampass, fullname, PDB_SET);
626         }
627
628         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
629                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), dir_drive)) 
630         {
631                 pdb_set_dir_drive(sampass, talloc_sub_specified(sampass->mem_ctx, 
632                                                                   lp_logon_drive(),
633                                                                   username, domain, 
634                                                                   uid, gid),
635                                   PDB_DEFAULT);
636         } else {
637                 pdb_set_dir_drive(sampass, dir_drive, PDB_SET);
638         }
639
640         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
641                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), homedir)) 
642         {
643                 pdb_set_homedir(sampass, talloc_sub_specified(sampass->mem_ctx, 
644                                                                   lp_logon_home(),
645                                                                   username, domain, 
646                                                                   uid, gid), 
647                                   PDB_DEFAULT);
648         } else {
649                 pdb_set_homedir(sampass, homedir, PDB_SET);
650         }
651
652         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
653                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), logon_script)) 
654         {
655                 pdb_set_logon_script(sampass, talloc_sub_specified(sampass->mem_ctx, 
656                                                                      lp_logon_script(),
657                                                                      username, domain, 
658                                                                      uid, gid), 
659                                      PDB_DEFAULT);
660         } else {
661                 pdb_set_logon_script(sampass, logon_script, PDB_SET);
662         }
663
664         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry,
665                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), profile_path)) 
666         {
667                 pdb_set_profile_path(sampass, talloc_sub_specified(sampass->mem_ctx, 
668                                                                      lp_logon_path(),
669                                                                      username, domain, 
670                                                                      uid, gid), 
671                                      PDB_DEFAULT);
672         } else {
673                 pdb_set_profile_path(sampass, profile_path, PDB_SET);
674         }
675
676         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
677                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), acct_desc)) 
678         {
679                 /* leave as default */
680         } else {
681                 pdb_set_acct_desc(sampass, acct_desc, PDB_SET);
682         }
683
684         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
685                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), workstations)) 
686         {
687                 /* leave as default */;
688         } else {
689                 pdb_set_workstations(sampass, workstations, PDB_SET);
690         }
691
692         /* FIXME: hours stuff should be cleaner */
693         
694         logon_divs = 168;
695         hours_len = 21;
696         memset(hours, 0xff, hours_len);
697
698         if (!smbldap_get_single_attribute (ldap_state->smbldap_state->ldap_struct, entry, 
699                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), temp)) 
700         {
701                 /* leave as default */
702         } else {
703                 pdb_gethexpwd(temp, smblmpwd);
704                 memset((char *)temp, '\0', strlen(temp)+1);
705                 if (!pdb_set_lanman_passwd(sampass, smblmpwd, PDB_SET))
706                         return False;
707                 ZERO_STRUCT(smblmpwd);
708         }
709
710         if (!smbldap_get_single_attribute (ldap_state->smbldap_state->ldap_struct, entry,
711                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), temp)) 
712         {
713                 /* leave as default */
714         } else {
715                 pdb_gethexpwd(temp, smbntpwd);
716                 memset((char *)temp, '\0', strlen(temp)+1);
717                 if (!pdb_set_nt_passwd(sampass, smbntpwd, PDB_SET))
718                         return False;
719                 ZERO_STRUCT(smbntpwd);
720         }
721
722         if (!smbldap_get_single_attribute (ldap_state->smbldap_state->ldap_struct, entry,
723                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), temp)) 
724         {
725                 acct_ctrl |= ACB_NORMAL;
726         } else {
727                 acct_ctrl = pdb_decode_acct_ctrl(temp);
728
729                 if (acct_ctrl == 0)
730                         acct_ctrl |= ACB_NORMAL;
731
732                 pdb_set_acct_ctrl(sampass, acct_ctrl, PDB_SET);
733         }
734
735         pdb_set_hours_len(sampass, hours_len, PDB_SET);
736         pdb_set_logon_divs(sampass, logon_divs, PDB_SET);
737
738         pdb_set_munged_dial(sampass, munged_dial, PDB_SET);
739         
740         /* pdb_set_unknown_3(sampass, unknown3, PDB_SET); */
741         /* pdb_set_unknown_5(sampass, unknown5, PDB_SET); */
742         /* pdb_set_unknown_6(sampass, unknown6, PDB_SET); */
743
744         pdb_set_hours(sampass, hours, PDB_SET);
745
746         return True;
747 }
748
749 /**********************************************************************
750 Initialize SAM_ACCOUNT from an LDAP query
751 (Based on init_buffer_from_sam in pdb_tdb.c)
752 *********************************************************************/
753 static BOOL init_ldap_from_sam (struct ldapsam_privates *ldap_state, 
754                                 LDAPMessage *existing,
755                                 LDAPMod *** mods, SAM_ACCOUNT * sampass,
756                                 BOOL (*need_update)(const SAM_ACCOUNT *,
757                                                     enum pdb_elements))
758 {
759         pstring temp;
760         uint32 rid;
761
762         if (mods == NULL || sampass == NULL) {
763                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
764                 return False;
765         }
766
767         *mods = NULL;
768
769         /* 
770          * took out adding "objectclass: sambaAccount"
771          * do this on a per-mod basis
772          */
773         if (need_update(sampass, PDB_USERNAME))
774                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods, 
775                               "uid", pdb_get_username(sampass));
776
777         DEBUG(2, ("Setting entry for user: %s\n", pdb_get_username(sampass)));
778
779         /* only update the RID if we actually need to */
780         if (need_update(sampass, PDB_USERSID)) 
781         {
782                 fstring sid_string;
783                 fstring dom_sid_string;
784                 const DOM_SID *user_sid = pdb_get_user_sid(sampass);
785                 
786                 switch ( ldap_state->schema_ver )
787                 {
788                         case SCHEMAVER_SAMBAACCOUNT:
789                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, user_sid, &rid)) {
790                                         DEBUG(1, ("User's SID (%s) is not for this domain (%s), cannot add to LDAP!\n", 
791                                                 sid_to_string(sid_string, user_sid), 
792                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
793                                         return False;
794                                 }
795                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
796                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
797                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_RID), 
798                                         temp);
799                                 break;
800                                 
801                         case SCHEMAVER_SAMBASAMACCOUNT:
802                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
803                                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
804                                         sid_to_string(sid_string, user_sid));                                 
805                                 break;
806                                 
807                         default:
808                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
809                                 break;
810                 }               
811         }
812
813         /* we don't need to store the primary group RID - so leaving it
814            'free' to hang off the unix primary group makes life easier */
815
816         if (need_update(sampass, PDB_GROUPSID)) 
817         {
818                 fstring sid_string;
819                 fstring dom_sid_string;
820                 const DOM_SID *group_sid = pdb_get_group_sid(sampass);
821                 
822                 switch ( ldap_state->schema_ver )
823                 {
824                         case SCHEMAVER_SAMBAACCOUNT:
825                                 if (!sid_peek_check_rid(&ldap_state->domain_sid, group_sid, &rid)) {
826                                         DEBUG(1, ("User's Primary Group SID (%s) is not for this domain (%s), cannot add to LDAP!\n",
827                                                 sid_to_string(sid_string, group_sid),
828                                                 sid_to_string(dom_sid_string, &ldap_state->domain_sid)));
829                                         return False;
830                                 }
831
832                                 slprintf(temp, sizeof(temp) - 1, "%i", rid);
833                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
834                                         get_userattr_key2string(ldap_state->schema_ver, 
835                                         LDAP_ATTR_PRIMARY_GROUP_RID), temp);
836                                 break;
837                                 
838                         case SCHEMAVER_SAMBASAMACCOUNT:
839                                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
840                                         get_userattr_key2string(ldap_state->schema_ver, 
841                                         LDAP_ATTR_PRIMARY_GROUP_SID), sid_to_string(sid_string, group_sid));
842                                 break;
843                                 
844                         default:
845                                 DEBUG(0,("init_ldap_from_sam: unknown schema version specified\n"));
846                                 break;
847                 }
848                 
849         }
850         
851         /* displayName, cn, and gecos should all be the same
852          *  most easily accomplished by giving them the same OID
853          *  gecos isn't set here b/c it should be handled by the 
854          *  add-user script
855          *  We change displayName only and fall back to cn if
856          *  it does not exist.
857          */
858
859         if (need_update(sampass, PDB_FULLNAME))
860                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
861                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DISPLAY_NAME), 
862                         pdb_get_fullname(sampass));
863
864         if (need_update(sampass, PDB_ACCTDESC))
865                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
866                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_DESC), 
867                         pdb_get_acct_desc(sampass));
868
869         if (need_update(sampass, PDB_WORKSTATIONS))
870                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
871                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_WKS), 
872                         pdb_get_workstations(sampass));
873
874         if (need_update(sampass, PDB_SMBHOME))
875                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
876                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_PATH), 
877                         pdb_get_homedir(sampass));
878                         
879         if (need_update(sampass, PDB_DRIVE))
880                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
881                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_HOME_DRIVE), 
882                         pdb_get_dir_drive(sampass));
883
884         if (need_update(sampass, PDB_LOGONSCRIPT))
885                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
886                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_SCRIPT), 
887                         pdb_get_logon_script(sampass));
888
889         if (need_update(sampass, PDB_PROFILE))
890                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
891                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PROFILE_PATH), 
892                         pdb_get_profile_path(sampass));
893
894         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
895         if (need_update(sampass, PDB_LOGONTIME))
896                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
897                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGON_TIME), temp);
898
899         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
900         if (need_update(sampass, PDB_LOGOFFTIME))
901                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
902                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LOGOFF_TIME), temp);
903
904         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
905         if (need_update(sampass, PDB_KICKOFFTIME))
906                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
907                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_KICKOFF_TIME), temp);
908
909         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
910         if (need_update(sampass, PDB_CANCHANGETIME))
911                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
912                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_CAN_CHANGE), temp);
913
914         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
915         if (need_update(sampass, PDB_MUSTCHANGETIME))
916                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
917                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_MUST_CHANGE), temp);
918
919         if ((pdb_get_acct_ctrl(sampass)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST))
920                 || (lp_ldap_passwd_sync()!=LDAP_PASSWD_SYNC_ONLY)) 
921         {
922
923                 pdb_sethexpwd(temp, pdb_get_lanman_passwd(sampass),
924                                pdb_get_acct_ctrl(sampass));
925
926                 if (need_update(sampass, PDB_LMPASSWD))
927                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
928                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_LMPW), 
929                                 temp);
930
931                 pdb_sethexpwd (temp, pdb_get_nt_passwd(sampass),
932                                pdb_get_acct_ctrl(sampass));
933
934                 if (need_update(sampass, PDB_NTPASSWD))
935                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
936                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_NTPW), 
937                                 temp);
938
939                 slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
940                 if (need_update(sampass, PDB_PASSLASTSET))
941                         smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
942                                 get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_PWD_LAST_SET), 
943                                 temp);
944         }
945
946         /* FIXME: Hours stuff goes in LDAP  */
947
948         if (need_update(sampass, PDB_ACCTCTRL))
949                 smbldap_make_mod(ldap_state->smbldap_state->ldap_struct, existing, mods,
950                         get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ACB_INFO), 
951                         pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass), NEW_PW_FORMAT_SPACE_PADDED_LEN));
952
953         return True;
954 }
955
956
957
958 /**********************************************************************
959 Connect to LDAP server for password enumeration
960 *********************************************************************/
961 static NTSTATUS ldapsam_setsampwent(struct pdb_methods *my_methods, BOOL update)
962 {
963         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
964         int rc;
965         pstring filter;
966         char **attr_list;
967
968         pstr_sprintf( filter, "(&%s%s)", lp_ldap_filter(), 
969                 get_objclass_filter(ldap_state->schema_ver));
970         all_string_sub(filter, "%u", "*", sizeof(pstring));
971
972         attr_list = get_userattr_list(ldap_state->schema_ver);
973         rc = smbldap_search_suffix(ldap_state->smbldap_state, filter, 
974                                    attr_list, &ldap_state->result);
975         free_attr_list( attr_list );
976
977         if (rc != LDAP_SUCCESS) {
978                 DEBUG(0, ("LDAP search failed: %s\n", ldap_err2string(rc)));
979                 DEBUG(3, ("Query was: %s, %s\n", lp_ldap_suffix(), filter));
980                 ldap_msgfree(ldap_state->result);
981                 ldap_state->result = NULL;
982                 return NT_STATUS_UNSUCCESSFUL;
983         }
984
985         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base!\n",
986                 ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
987                 ldap_state->result)));
988
989         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct,
990                                  ldap_state->result);
991         ldap_state->index = 0;
992
993         return NT_STATUS_OK;
994 }
995
996 /**********************************************************************
997 End enumeration of the LDAP password list 
998 *********************************************************************/
999 static void ldapsam_endsampwent(struct pdb_methods *my_methods)
1000 {
1001         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1002         if (ldap_state->result) {
1003                 ldap_msgfree(ldap_state->result);
1004                 ldap_state->result = NULL;
1005         }
1006 }
1007
1008 /**********************************************************************
1009 Get the next entry in the LDAP password database 
1010 *********************************************************************/
1011 static NTSTATUS ldapsam_getsampwent(struct pdb_methods *my_methods, SAM_ACCOUNT *user)
1012 {
1013         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1014         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1015         BOOL bret = False;
1016
1017         while (!bret) {
1018                 if (!ldap_state->entry)
1019                         return ret;
1020                 
1021                 ldap_state->index++;
1022                 bret = init_sam_from_ldap(ldap_state, user, ldap_state->entry);
1023                 
1024                 ldap_state->entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
1025                                             ldap_state->entry); 
1026         }
1027
1028         return NT_STATUS_OK;
1029 }
1030
1031 /**********************************************************************
1032 Get SAM_ACCOUNT entry from LDAP by username 
1033 *********************************************************************/
1034 static NTSTATUS ldapsam_getsampwnam(struct pdb_methods *my_methods, SAM_ACCOUNT *user, const char *sname)
1035 {
1036         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1037         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1038         LDAPMessage *result;
1039         LDAPMessage *entry;
1040         int count;
1041         char ** attr_list;
1042         int rc;
1043         
1044         attr_list = get_userattr_list( ldap_state->schema_ver );
1045         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result, attr_list);
1046         free_attr_list( attr_list );
1047
1048         if ( rc != LDAP_SUCCESS ) 
1049                 return NT_STATUS_NO_SUCH_USER;
1050         
1051         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1052         
1053         if (count < 1) {
1054                 DEBUG(4,
1055                       ("Unable to locate user [%s] count=%d\n", sname,
1056                        count));
1057                 ldap_msgfree(result);
1058                 return NT_STATUS_NO_SUCH_USER;
1059         } else if (count > 1) {
1060                 DEBUG(1,
1061                       ("Duplicate entries for this user [%s] Failing. count=%d\n", sname,
1062                        count));
1063                 ldap_msgfree(result);
1064                 return NT_STATUS_NO_SUCH_USER;
1065         }
1066
1067         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1068         if (entry) {
1069                 if (!init_sam_from_ldap(ldap_state, user, entry)) {
1070                         DEBUG(1,("ldapsam_getsampwnam: init_sam_from_ldap failed for user '%s'!\n", sname));
1071                         ldap_msgfree(result);
1072                         return NT_STATUS_NO_SUCH_USER;
1073                 }
1074                 pdb_set_backend_private_data(user, result, 
1075                                              private_data_free_fn, 
1076                                              my_methods, PDB_CHANGED);
1077                 ret = NT_STATUS_OK;
1078         } else {
1079                 ldap_msgfree(result);
1080         }
1081         return ret;
1082 }
1083
1084 static int ldapsam_get_ldap_user_by_sid(struct ldapsam_privates *ldap_state, 
1085                                    const DOM_SID *sid, LDAPMessage **result) 
1086 {
1087         int rc = -1;
1088         char ** attr_list;
1089         uint32 rid;
1090
1091         switch ( ldap_state->schema_ver )
1092         {
1093                 case SCHEMAVER_SAMBASAMACCOUNT:
1094                         attr_list = get_userattr_list(ldap_state->schema_ver);
1095                         rc = ldapsam_search_suffix_by_sid(ldap_state, sid, result, attr_list);
1096                         free_attr_list( attr_list );
1097
1098                         if ( rc != LDAP_SUCCESS ) 
1099                                 return rc;
1100                         break;
1101                         
1102                 case SCHEMAVER_SAMBAACCOUNT:
1103                         if (!sid_peek_check_rid(&ldap_state->domain_sid, sid, &rid)) {
1104                                 return rc;
1105                         }
1106                 
1107                         attr_list = get_userattr_list(ldap_state->schema_ver);
1108                         rc = ldapsam_search_suffix_by_rid(ldap_state, rid, result, attr_list );
1109                         free_attr_list( attr_list );
1110
1111                         if ( rc != LDAP_SUCCESS ) 
1112                                 return rc;
1113                         break;
1114         }
1115         return rc;
1116 }
1117
1118 /**********************************************************************
1119 Get SAM_ACCOUNT entry from LDAP by SID
1120 *********************************************************************/
1121 static NTSTATUS ldapsam_getsampwsid(struct pdb_methods *my_methods, SAM_ACCOUNT * user, const DOM_SID *sid)
1122 {
1123         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1124         LDAPMessage *result;
1125         LDAPMessage *entry;
1126         int count;
1127         int rc;
1128         fstring sid_string;
1129
1130         rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1131                                           sid, &result); 
1132         if (rc != LDAP_SUCCESS)
1133                 return NT_STATUS_NO_SUCH_USER;
1134
1135         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1136         
1137         if (count < 1) 
1138         {
1139                 DEBUG(4,
1140                       ("Unable to locate SID [%s] count=%d\n", sid_to_string(sid_string, sid),
1141                        count));
1142                 ldap_msgfree(result);
1143                 return NT_STATUS_NO_SUCH_USER;
1144         }  
1145         else if (count > 1) 
1146         {
1147                 DEBUG(1,
1148                       ("More than one user with SID [%s]. Failing. count=%d\n", sid_to_string(sid_string, sid),
1149                        count));
1150                 ldap_msgfree(result);
1151                 return NT_STATUS_NO_SUCH_USER;
1152         }
1153
1154         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1155         if (!entry) 
1156         {
1157                 ldap_msgfree(result);
1158                 return NT_STATUS_NO_SUCH_USER;
1159         }
1160
1161         if (!init_sam_from_ldap(ldap_state, user, entry)) {
1162                 DEBUG(1,("ldapsam_getsampwrid: init_sam_from_ldap failed!\n"));
1163                 ldap_msgfree(result);
1164                 return NT_STATUS_NO_SUCH_USER;
1165         }
1166
1167         pdb_set_backend_private_data(user, result, 
1168                                      private_data_free_fn, 
1169                                      my_methods, PDB_CHANGED);
1170         return NT_STATUS_OK;
1171 }       
1172
1173 /********************************************************************
1174 Do the actual modification - also change a plaintext passord if 
1175 it it set.
1176 **********************************************************************/
1177
1178 static NTSTATUS ldapsam_modify_entry(struct pdb_methods *my_methods, 
1179                                      SAM_ACCOUNT *newpwd, char *dn,
1180                                      LDAPMod **mods, int ldap_op, 
1181                                      BOOL (*need_update)(const SAM_ACCOUNT *,
1182                                                          enum pdb_elements))
1183 {
1184         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1185         int rc;
1186         
1187         if (!my_methods || !newpwd || !dn) {
1188                 return NT_STATUS_INVALID_PARAMETER;
1189         }
1190         
1191         if (!mods) {
1192                 DEBUG(5,("mods is empty: nothing to modify\n"));
1193                 /* may be password change below however */
1194         } else {
1195                 switch(ldap_op)
1196                 {
1197                         case LDAP_MOD_ADD: 
1198                                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1199                                                 "objectclass", 
1200                                                 LDAP_OBJ_ACCOUNT);
1201                                 rc = smbldap_add(ldap_state->smbldap_state, 
1202                                                  dn, mods);
1203                                 break;
1204                         case LDAP_MOD_REPLACE: 
1205                                 rc = smbldap_modify(ldap_state->smbldap_state, 
1206                                                     dn ,mods);
1207                                 break;
1208                         default:        
1209                                 DEBUG(0,("Wrong LDAP operation type: %d!\n", 
1210                                          ldap_op));
1211                                 return NT_STATUS_INVALID_PARAMETER;
1212                 }
1213                 
1214                 if (rc!=LDAP_SUCCESS) {
1215                         char *ld_error = NULL;
1216                         ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1217                                         &ld_error);
1218                         DEBUG(1,
1219                               ("failed to %s user dn= %s with: %s\n\t%s\n",
1220                                ldap_op == LDAP_MOD_ADD ? "add" : "modify",
1221                                dn, ldap_err2string(rc),
1222                                ld_error?ld_error:"unknown"));
1223                         SAFE_FREE(ld_error);
1224                         return NT_STATUS_UNSUCCESSFUL;
1225                 }  
1226         }
1227         
1228         if (!(pdb_get_acct_ctrl(newpwd)&(ACB_WSTRUST|ACB_SVRTRUST|ACB_DOMTRUST)) &&
1229                 (lp_ldap_passwd_sync() != LDAP_PASSWD_SYNC_OFF) &&
1230                 need_update(newpwd, PDB_PLAINTEXT_PW) &&
1231                 (pdb_get_plaintext_passwd(newpwd)!=NULL)) {
1232                 BerElement *ber;
1233                 struct berval *bv;
1234                 char *retoid;
1235                 struct berval *retdata;
1236                 char *utf8_password;
1237                 char *utf8_dn;
1238
1239                 if (push_utf8_allocate(&utf8_password, pdb_get_plaintext_passwd(newpwd)) == (size_t)-1) {
1240                         return NT_STATUS_NO_MEMORY;
1241                 }
1242
1243                 if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1244                         return NT_STATUS_NO_MEMORY;
1245                 }
1246
1247                 if ((ber = ber_alloc_t(LBER_USE_DER))==NULL) {
1248                         DEBUG(0,("ber_alloc_t returns NULL\n"));
1249                         SAFE_FREE(utf8_password);
1250                         return NT_STATUS_UNSUCCESSFUL;
1251                 }
1252
1253                 ber_printf (ber, "{");
1254                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_ID, utf8_dn);
1255                 ber_printf (ber, "ts", LDAP_TAG_EXOP_MODIFY_PASSWD_NEW, utf8_password);
1256                 ber_printf (ber, "N}");
1257
1258                 if ((rc = ber_flatten (ber, &bv))<0) {
1259                         DEBUG(0,("ber_flatten returns a value <0\n"));
1260                         ber_free(ber,1);
1261                         SAFE_FREE(utf8_dn);
1262                         SAFE_FREE(utf8_password);
1263                         return NT_STATUS_UNSUCCESSFUL;
1264                 }
1265                 
1266                 SAFE_FREE(utf8_dn);
1267                 SAFE_FREE(utf8_password);
1268                 ber_free(ber, 1);
1269
1270                 if ((rc = smbldap_extended_operation(ldap_state->smbldap_state, 
1271                                                      LDAP_EXOP_MODIFY_PASSWD,
1272                                                      bv, NULL, NULL, &retoid, 
1273                                                      &retdata)) != LDAP_SUCCESS) {
1274                         DEBUG(0,("LDAP Password could not be changed for user %s: %s\n",
1275                                 pdb_get_username(newpwd),ldap_err2string(rc)));
1276                 } else {
1277                         DEBUG(3,("LDAP Password changed for user %s\n",pdb_get_username(newpwd)));
1278 #ifdef DEBUG_PASSWORD
1279                         DEBUG(100,("LDAP Password changed to %s\n",pdb_get_plaintext_passwd(newpwd)));
1280 #endif    
1281                         ber_bvfree(retdata);
1282                         ber_memfree(retoid);
1283                 }
1284                 ber_bvfree(bv);
1285         }
1286         return NT_STATUS_OK;
1287 }
1288
1289 /**********************************************************************
1290 Delete entry from LDAP for username 
1291 *********************************************************************/
1292 static NTSTATUS ldapsam_delete_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * sam_acct)
1293 {
1294         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1295         const char *sname;
1296         int rc;
1297         LDAPMessage *result;
1298         NTSTATUS ret;
1299         char **attr_list;
1300         fstring objclass;
1301
1302         if (!sam_acct) {
1303                 DEBUG(0, ("sam_acct was NULL!\n"));
1304                 return NT_STATUS_INVALID_PARAMETER;
1305         }
1306
1307         sname = pdb_get_username(sam_acct);
1308
1309         DEBUG (3, ("Deleting user %s from LDAP.\n", sname));
1310
1311         attr_list= get_userattr_list( ldap_state->schema_ver );
1312         rc = ldapsam_search_suffix_by_name(ldap_state, sname, &result, attr_list);
1313
1314         if (rc != LDAP_SUCCESS)  {
1315                 free_attr_list( attr_list );
1316                 return NT_STATUS_NO_SUCH_USER;
1317         }
1318         
1319         switch ( ldap_state->schema_ver )
1320         {
1321                 case SCHEMAVER_SAMBASAMACCOUNT:
1322                         fstrcpy( objclass, LDAP_OBJ_SAMBASAMACCOUNT );
1323                         break;
1324                         
1325                 case SCHEMAVER_SAMBAACCOUNT:
1326                         fstrcpy( objclass, LDAP_OBJ_SAMBAACCOUNT );
1327                         break;
1328                 default:
1329                         fstrcpy( objclass, "UNKNOWN" );
1330                         DEBUG(0,("ldapsam_delete_sam_account: Unknown schema version specified!\n"));
1331                                 break;
1332         }
1333
1334         ret = ldapsam_delete_entry(ldap_state, result, objclass, attr_list );
1335         ldap_msgfree(result);
1336         free_attr_list( attr_list );
1337
1338         return ret;
1339 }
1340
1341 /**********************************************************************
1342   Helper function to determine for update_sam_account whether
1343   we need LDAP modification.
1344 *********************************************************************/
1345 static BOOL element_is_changed(const SAM_ACCOUNT *sampass,
1346                                enum pdb_elements element)
1347 {
1348         return IS_SAM_CHANGED(sampass, element);
1349 }
1350
1351 /**********************************************************************
1352 Update SAM_ACCOUNT 
1353 *********************************************************************/
1354 static NTSTATUS ldapsam_update_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * newpwd)
1355 {
1356         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1357         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1358         int rc;
1359         char *dn;
1360         LDAPMessage *result;
1361         LDAPMessage *entry;
1362         LDAPMod **mods;
1363         char **attr_list;
1364
1365         result = pdb_get_backend_private_data(newpwd, my_methods);
1366         if (!result) {
1367                 attr_list = get_userattr_list(ldap_state->schema_ver);
1368                 rc = ldapsam_search_suffix_by_name(ldap_state, pdb_get_username(newpwd), &result, attr_list );
1369                 free_attr_list( attr_list );
1370                 if (rc != LDAP_SUCCESS) {
1371                         return NT_STATUS_UNSUCCESSFUL;
1372                 }
1373                 pdb_set_backend_private_data(newpwd, result, private_data_free_fn, my_methods, PDB_CHANGED);
1374         }
1375
1376         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1377                 DEBUG(0, ("No user to modify!\n"));
1378                 return NT_STATUS_UNSUCCESSFUL;
1379         }
1380
1381         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1382         dn = ldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1383
1384         DEBUG(4, ("user %s to be modified has dn: %s\n", pdb_get_username(newpwd), dn));
1385
1386         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1387                                 element_is_changed)) {
1388                 DEBUG(0, ("ldapsam_update_sam_account: init_ldap_from_sam failed!\n"));
1389                 ldap_memfree(dn);
1390                 return NT_STATUS_UNSUCCESSFUL;
1391         }
1392         
1393         if (mods == NULL) {
1394                 DEBUG(4,("mods is empty: nothing to update for user: %s\n",
1395                          pdb_get_username(newpwd)));
1396                 ldap_mods_free(mods, True);
1397                 ldap_memfree(dn);
1398                 return NT_STATUS_OK;
1399         }
1400         
1401         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,LDAP_MOD_REPLACE, element_is_changed);
1402         ldap_mods_free(mods,True);
1403         ldap_memfree(dn);
1404
1405         if (!NT_STATUS_IS_OK(ret)) {
1406                 char *ld_error = NULL;
1407                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1408                                 &ld_error);
1409                 DEBUG(0,("failed to modify user with uid = %s, error: %s (%s)\n",
1410                          pdb_get_username(newpwd), ld_error?ld_error:"(unknwon)", ldap_err2string(rc)));
1411                 SAFE_FREE(ld_error);
1412                 return ret;
1413         }
1414
1415         DEBUG(2, ("successfully modified uid = %s in the LDAP database\n",
1416                   pdb_get_username(newpwd)));
1417         return NT_STATUS_OK;
1418 }
1419
1420 /**********************************************************************
1421   Helper function to determine for update_sam_account whether
1422   we need LDAP modification.
1423  *********************************************************************/
1424 static BOOL element_is_set_or_changed(const SAM_ACCOUNT *sampass,
1425                                       enum pdb_elements element)
1426 {
1427         return (IS_SAM_SET(sampass, element) ||
1428                 IS_SAM_CHANGED(sampass, element));
1429 }
1430
1431 /**********************************************************************
1432 Add SAM_ACCOUNT to LDAP 
1433 *********************************************************************/
1434
1435 static NTSTATUS ldapsam_add_sam_account(struct pdb_methods *my_methods, SAM_ACCOUNT * newpwd)
1436 {
1437         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1438         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
1439         int rc;
1440         LDAPMessage     *result = NULL;
1441         LDAPMessage     *entry  = NULL;
1442         pstring         dn;
1443         LDAPMod         **mods = NULL;
1444         int             ldap_op;
1445         uint32          num_result;
1446         char            **attr_list;
1447         char            *escape_user;
1448         const char      *username = pdb_get_username(newpwd);
1449         const DOM_SID   *sid = pdb_get_user_sid(newpwd);
1450         pstring         filter;
1451         fstring         sid_string;
1452
1453         if (!username || !*username) {
1454                 DEBUG(0, ("Cannot add user without a username!\n"));
1455                 return NT_STATUS_INVALID_PARAMETER;
1456         }
1457
1458         /* free this list after the second search or in case we exit on failure */
1459         attr_list = get_userattr_list(ldap_state->schema_ver);
1460
1461         rc = ldapsam_search_suffix_by_name (ldap_state, username, &result, attr_list);
1462
1463         if (rc != LDAP_SUCCESS) {
1464                 free_attr_list( attr_list );
1465                 return NT_STATUS_UNSUCCESSFUL;
1466         }
1467
1468         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1469                 DEBUG(0,("User '%s' already in the base, with samba attributes\n", 
1470                          username));
1471                 ldap_msgfree(result);
1472                 free_attr_list( attr_list );
1473                 return NT_STATUS_UNSUCCESSFUL;
1474         }
1475         ldap_msgfree(result);
1476         result = NULL;
1477
1478         if (element_is_set_or_changed(newpwd, PDB_USERSID)) {
1479                 rc = ldapsam_get_ldap_user_by_sid(ldap_state, 
1480                                                   sid, &result); 
1481                 if (rc == LDAP_SUCCESS) {
1482                         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) != 0) {
1483                                 DEBUG(0,("SID '%s' already in the base, with samba attributes\n", 
1484                                          sid_to_string(sid_string, sid)));
1485                                 free_attr_list( attr_list );
1486                                 return NT_STATUS_UNSUCCESSFUL;
1487                         }
1488                         ldap_msgfree(result);
1489                 }
1490         }
1491
1492         /* does the entry already exist but without a samba attributes?
1493            we need to return the samba attributes here */
1494            
1495         escape_user = escape_ldap_string_alloc( username );
1496         pstrcpy( filter, lp_ldap_filter() );
1497         all_string_sub( filter, "%u", escape_user, sizeof(filter) );
1498         SAFE_FREE( escape_user );
1499
1500         rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1501                                    filter, attr_list, &result);
1502         if ( rc != LDAP_SUCCESS ) {
1503                 free_attr_list( attr_list );
1504                 return NT_STATUS_UNSUCCESSFUL;
1505         }
1506
1507         num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1508         
1509         if (num_result > 1) {
1510                 DEBUG (0, ("More than one user with that uid exists: bailing out!\n"));
1511                 free_attr_list( attr_list );
1512                 ldap_msgfree(result);
1513                 return NT_STATUS_UNSUCCESSFUL;
1514         }
1515         
1516         /* Check if we need to update an existing entry */
1517         if (num_result == 1) {
1518                 char *tmp;
1519                 
1520                 DEBUG(3,("User exists without samba attributes: adding them\n"));
1521                 ldap_op = LDAP_MOD_REPLACE;
1522                 entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1523                 tmp = ldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1524                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1525                 ldap_memfree (tmp);
1526
1527         } else if (ldap_state->schema_ver == SCHEMAVER_SAMBASAMACCOUNT) {
1528
1529                 /* There might be a SID for this account already - say an idmap entry */
1530
1531                 pstr_sprintf(filter, "(&(%s=%s)(|(objectClass=%s)(objectClass=%s)))", 
1532                          get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID),
1533                          sid_to_string(sid_string, sid),
1534                          LDAP_OBJ_IDMAP_ENTRY,
1535                          LDAP_OBJ_SID_ENTRY);
1536                 
1537                 rc = smbldap_search_suffix(ldap_state->smbldap_state, 
1538                                            filter, attr_list, &result);
1539                         
1540                 if ( rc != LDAP_SUCCESS ) {
1541                         free_attr_list( attr_list );
1542                         return NT_STATUS_UNSUCCESSFUL;
1543                 }
1544                 
1545                 num_result = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1546                 
1547                 if (num_result > 1) {
1548                         DEBUG (0, ("More than one user with that uid exists: bailing out!\n"));
1549                         free_attr_list( attr_list );
1550                         ldap_msgfree(result);
1551                         return NT_STATUS_UNSUCCESSFUL;
1552                 }
1553                 
1554                 /* Check if we need to update an existing entry */
1555                 if (num_result == 1) {
1556                         char *tmp;
1557                         
1558                         DEBUG(3,("User exists without samba attributes: adding them\n"));
1559                         ldap_op = LDAP_MOD_REPLACE;
1560                         entry = ldap_first_entry (ldap_state->smbldap_state->ldap_struct, result);
1561                         tmp = ldap_get_dn (ldap_state->smbldap_state->ldap_struct, entry);
1562                         slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1563                         ldap_memfree (tmp);
1564                 }
1565         }
1566         
1567         free_attr_list( attr_list );
1568
1569         if (num_result == 0) {
1570                 /* Check if we need to add an entry */
1571                 DEBUG(3,("Adding new user\n"));
1572                 ldap_op = LDAP_MOD_ADD;
1573                 if (username[strlen(username)-1] == '$') {
1574                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_machine_suffix ());
1575                 } else {
1576                         slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", username, lp_ldap_user_suffix ());
1577                 }
1578         }
1579
1580         if (!init_ldap_from_sam(ldap_state, entry, &mods, newpwd,
1581                                 element_is_set_or_changed)) {
1582                 DEBUG(0, ("ldapsam_add_sam_account: init_ldap_from_sam failed!\n"));
1583                 ldap_msgfree(result);
1584                 return NT_STATUS_UNSUCCESSFUL;          
1585         }
1586         
1587         ldap_msgfree(result);
1588
1589         if (mods == NULL) {
1590                 DEBUG(0,("mods is empty: nothing to add for user: %s\n",pdb_get_username(newpwd)));
1591                 return NT_STATUS_UNSUCCESSFUL;
1592         }
1593         switch ( ldap_state->schema_ver )
1594         {
1595                 case SCHEMAVER_SAMBAACCOUNT:
1596                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBAACCOUNT);
1597                         break;
1598                 case SCHEMAVER_SAMBASAMACCOUNT:
1599                         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_SAMBASAMACCOUNT);
1600                         break;
1601                 default:
1602                         DEBUG(0,("ldapsam_add_sam_account: invalid schema version specified\n"));
1603                         break;
1604         }
1605
1606         ret = ldapsam_modify_entry(my_methods,newpwd,dn,mods,ldap_op, element_is_set_or_changed);
1607         if (!NT_STATUS_IS_OK(ret)) {
1608                 DEBUG(0,("failed to modify/add user with uid = %s (dn = %s)\n",
1609                          pdb_get_username(newpwd),dn));
1610                 ldap_mods_free(mods, True);
1611                 return ret;
1612         }
1613
1614         DEBUG(2,("added: uid == %s in the LDAP database\n", pdb_get_username(newpwd)));
1615         ldap_mods_free(mods, True);
1616         
1617         return NT_STATUS_OK;
1618 }
1619
1620 /**********************************************************************
1621  *********************************************************************/
1622
1623 static int ldapsam_search_one_group (struct ldapsam_privates *ldap_state,
1624                                      const char *filter,
1625                                      LDAPMessage ** result)
1626 {
1627         int scope = LDAP_SCOPE_SUBTREE;
1628         int rc;
1629         char **attr_list;
1630
1631         DEBUG(2, ("ldapsam_search_one_group: searching for:[%s]\n", filter));
1632
1633
1634         attr_list = get_attr_list(groupmap_attr_list);
1635         rc = smbldap_search(ldap_state->smbldap_state, 
1636                             lp_ldap_group_suffix (), scope,
1637                             filter, attr_list, 0, result);
1638         free_attr_list( attr_list );
1639
1640         if (rc != LDAP_SUCCESS) {
1641                 char *ld_error = NULL;
1642                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1643                                 &ld_error);
1644                 DEBUG(0, ("ldapsam_search_one_group: "
1645                           "Problem during the LDAP search: LDAP error: %s (%s)",
1646                           ld_error?ld_error:"(unknown)", ldap_err2string(rc)));
1647                 DEBUG(3, ("ldapsam_search_one_group: Query was: %s, %s\n",
1648                           lp_ldap_group_suffix(), filter));
1649                 SAFE_FREE(ld_error);
1650         }
1651
1652         return rc;
1653 }
1654
1655 /**********************************************************************
1656  *********************************************************************/
1657
1658 static BOOL init_group_from_ldap(struct ldapsam_privates *ldap_state,
1659                                  GROUP_MAP *map, LDAPMessage *entry)
1660 {
1661         pstring temp;
1662
1663         if (ldap_state == NULL || map == NULL || entry == NULL ||
1664             ldap_state->smbldap_state->ldap_struct == NULL) 
1665         {
1666                 DEBUG(0, ("init_group_from_ldap: NULL parameters found!\n"));
1667                 return False;
1668         }
1669
1670         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
1671                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER), temp)) 
1672         {
1673                 DEBUG(0, ("Mandatory attribute %s not found\n", 
1674                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GIDNUMBER)));
1675                 return False;
1676         }
1677         DEBUG(2, ("Entry found for group: %s\n", temp));
1678
1679         map->gid = (gid_t)atol(temp);
1680
1681         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
1682                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID), temp)) 
1683         {
1684                 DEBUG(0, ("Mandatory attribute %s not found\n",
1685                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_SID)));
1686                 return False;
1687         }
1688         string_to_sid(&map->sid, temp);
1689
1690         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
1691                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), temp)) 
1692         {
1693                 DEBUG(0, ("Mandatory attribute %s not found\n",
1694                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_GROUP_TYPE)));
1695                 return False;
1696         }
1697         map->sid_name_use = (enum SID_NAME_USE)atol(temp);
1698
1699         if ((map->sid_name_use < SID_NAME_USER) ||
1700             (map->sid_name_use > SID_NAME_UNKNOWN)) {
1701                 DEBUG(0, ("Unknown Group type: %d\n", map->sid_name_use));
1702                 return False;
1703         }
1704
1705         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
1706                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), temp)) 
1707         {
1708                 temp[0] = '\0';
1709                 if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
1710                         get_attr_key2string( groupmap_attr_list, LDAP_ATTR_CN), temp)) 
1711                 {
1712                         DEBUG(0, ("Attributes cn not found either "
1713                                   "for gidNumber(%lu)\n",(unsigned long)map->gid));
1714                         return False;
1715                 }
1716         }
1717         fstrcpy(map->nt_name, temp);
1718
1719         if (!smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
1720                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), temp)) 
1721         {
1722                 temp[0] = '\0';
1723         }
1724         fstrcpy(map->comment, temp);
1725
1726         return True;
1727 }
1728
1729 /**********************************************************************
1730  *********************************************************************/
1731
1732 static BOOL init_ldap_from_group(LDAP *ldap_struct,
1733                                  LDAPMessage *existing,
1734                                  LDAPMod ***mods,
1735                                  const GROUP_MAP *map)
1736 {
1737         pstring tmp;
1738
1739         if (mods == NULL || map == NULL) {
1740                 DEBUG(0, ("init_ldap_from_group: NULL parameters found!\n"));
1741                 return False;
1742         }
1743
1744         *mods = NULL;
1745
1746         sid_to_string(tmp, &map->sid);
1747         smbldap_make_mod(ldap_struct, existing, mods, 
1748                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID), tmp);
1749         pstr_sprintf(tmp, "%i", map->sid_name_use);
1750         smbldap_make_mod(ldap_struct, existing, mods, 
1751                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_TYPE), tmp);
1752
1753         smbldap_make_mod(ldap_struct, existing, mods, 
1754                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), map->nt_name);
1755         smbldap_make_mod(ldap_struct, existing, mods, 
1756                 get_attr_key2string( groupmap_attr_list, LDAP_ATTR_DESC), map->comment);
1757
1758         return True;
1759 }
1760
1761 /**********************************************************************
1762  *********************************************************************/
1763
1764 static NTSTATUS ldapsam_getgroup(struct pdb_methods *methods,
1765                                  const char *filter,
1766                                  GROUP_MAP *map)
1767 {
1768         struct ldapsam_privates *ldap_state =
1769                 (struct ldapsam_privates *)methods->private_data;
1770         LDAPMessage *result;
1771         LDAPMessage *entry;
1772         int count;
1773
1774         if (ldapsam_search_one_group(ldap_state, filter, &result)
1775             != LDAP_SUCCESS) {
1776                 return NT_STATUS_NO_SUCH_GROUP;
1777         }
1778
1779         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1780
1781         if (count < 1) {
1782                 DEBUG(4, ("Did not find group\n"));
1783                 ldap_msgfree(result);
1784                 return NT_STATUS_NO_SUCH_GROUP;
1785         }
1786
1787         if (count > 1) {
1788                 DEBUG(1, ("Duplicate entries for filter %s: count=%d\n",
1789                           filter, count));
1790                 ldap_msgfree(result);
1791                 return NT_STATUS_NO_SUCH_GROUP;
1792         }
1793
1794         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1795
1796         if (!entry) {
1797                 ldap_msgfree(result);
1798                 return NT_STATUS_UNSUCCESSFUL;
1799         }
1800
1801         if (!init_group_from_ldap(ldap_state, map, entry)) {
1802                 DEBUG(1, ("init_group_from_ldap failed for group filter %s\n",
1803                           filter));
1804                 ldap_msgfree(result);
1805                 return NT_STATUS_NO_SUCH_GROUP;
1806         }
1807
1808         ldap_msgfree(result);
1809         return NT_STATUS_OK;
1810 }
1811
1812 /**********************************************************************
1813  *********************************************************************/
1814
1815 static NTSTATUS ldapsam_getgrsid(struct pdb_methods *methods, GROUP_MAP *map,
1816                                  DOM_SID sid)
1817 {
1818         pstring filter;
1819
1820         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
1821                 LDAP_OBJ_GROUPMAP, 
1822                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GROUP_SID),
1823                 sid_string_static(&sid));
1824
1825         return ldapsam_getgroup(methods, filter, map);
1826 }
1827
1828 /**********************************************************************
1829  *********************************************************************/
1830
1831 static NTSTATUS ldapsam_getgrgid(struct pdb_methods *methods, GROUP_MAP *map,
1832                                  gid_t gid)
1833 {
1834         pstring filter;
1835
1836         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))",
1837                 LDAP_OBJ_GROUPMAP,
1838                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
1839                 (unsigned long)gid);
1840
1841         return ldapsam_getgroup(methods, filter, map);
1842 }
1843
1844 /**********************************************************************
1845  *********************************************************************/
1846
1847 static NTSTATUS ldapsam_getgrnam(struct pdb_methods *methods, GROUP_MAP *map,
1848                                  const char *name)
1849 {
1850         pstring filter;
1851         char *escape_name = escape_ldap_string_alloc(name);
1852
1853         if (!escape_name) {
1854                 return NT_STATUS_NO_MEMORY;
1855         }
1856
1857         pstr_sprintf(filter, "(&(objectClass=%s)(|(%s=%s)(%s=%s)))",
1858                 LDAP_OBJ_GROUPMAP,
1859                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_DISPLAY_NAME), escape_name,
1860                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_CN), escape_name);
1861
1862         SAFE_FREE(escape_name);
1863
1864         return ldapsam_getgroup(methods, filter, map);
1865 }
1866
1867 /**********************************************************************
1868  *********************************************************************/
1869
1870 static int ldapsam_search_one_group_by_gid(struct ldapsam_privates *ldap_state,
1871                                            gid_t gid,
1872                                            LDAPMessage **result)
1873 {
1874         pstring filter;
1875
1876         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%lu))", 
1877                 LDAP_OBJ_POSIXGROUP,
1878                 get_attr_key2string(groupmap_attr_list, LDAP_ATTR_GIDNUMBER),
1879                 (unsigned long)gid);
1880
1881         return ldapsam_search_one_group(ldap_state, filter, result);
1882 }
1883
1884 /**********************************************************************
1885  *********************************************************************/
1886
1887 static NTSTATUS ldapsam_add_group_mapping_entry(struct pdb_methods *methods,
1888                                                 GROUP_MAP *map)
1889 {
1890         struct ldapsam_privates *ldap_state =
1891                 (struct ldapsam_privates *)methods->private_data;
1892         LDAPMessage *result = NULL;
1893         LDAPMod **mods = NULL;
1894         int count;
1895
1896         char *tmp;
1897         pstring dn;
1898         LDAPMessage *entry;
1899
1900         GROUP_MAP dummy;
1901
1902         int rc;
1903
1904         if (NT_STATUS_IS_OK(ldapsam_getgrgid(methods, &dummy,
1905                                              map->gid))) {
1906                 DEBUG(0, ("Group %ld already exists in LDAP\n", (unsigned long)map->gid));
1907                 return NT_STATUS_UNSUCCESSFUL;
1908         }
1909
1910         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
1911         if (rc != LDAP_SUCCESS) {
1912                 ldap_msgfree(result);
1913                 return NT_STATUS_UNSUCCESSFUL;
1914         }
1915
1916         count = ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result);
1917
1918         if ( count == 0 ) {
1919                 ldap_msgfree(result);
1920                 return NT_STATUS_UNSUCCESSFUL;
1921         }
1922
1923         if (count > 1) {
1924                 DEBUG(2, ("Group %lu must exist exactly once in LDAP\n",
1925                           (unsigned long)map->gid));
1926                 ldap_msgfree(result);
1927                 return NT_STATUS_UNSUCCESSFUL;
1928         }
1929
1930         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1931         tmp = ldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1932         pstrcpy(dn, tmp);
1933         ldap_memfree(tmp);
1934
1935         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
1936                                   result, &mods, map)) {
1937                 DEBUG(0, ("init_ldap_from_group failed!\n"));
1938                 ldap_mods_free(mods, True);
1939                 ldap_msgfree(result);
1940                 return NT_STATUS_UNSUCCESSFUL;
1941         }
1942
1943         ldap_msgfree(result);
1944
1945         if (mods == NULL) {
1946                 DEBUG(0, ("mods is empty\n"));
1947                 return NT_STATUS_UNSUCCESSFUL;
1948         }
1949
1950         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectClass", LDAP_OBJ_GROUPMAP );
1951
1952         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
1953         ldap_mods_free(mods, True);
1954
1955         if (rc != LDAP_SUCCESS) {
1956                 char *ld_error = NULL;
1957                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1958                                 &ld_error);
1959                 DEBUG(0, ("failed to add group %lu error: %s (%s)\n", (unsigned long)map->gid, 
1960                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
1961                 SAFE_FREE(ld_error);
1962                 return NT_STATUS_UNSUCCESSFUL;
1963         }
1964
1965         DEBUG(2, ("successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
1966         return NT_STATUS_OK;
1967 }
1968
1969 /**********************************************************************
1970  *********************************************************************/
1971
1972 static NTSTATUS ldapsam_update_group_mapping_entry(struct pdb_methods *methods,
1973                                                    GROUP_MAP *map)
1974 {
1975         struct ldapsam_privates *ldap_state =
1976                 (struct ldapsam_privates *)methods->private_data;
1977         int rc;
1978         char *dn;
1979         LDAPMessage *result;
1980         LDAPMessage *entry;
1981         LDAPMod **mods;
1982
1983         rc = ldapsam_search_one_group_by_gid(ldap_state, map->gid, &result);
1984
1985         if (rc != LDAP_SUCCESS) {
1986                 return NT_STATUS_UNSUCCESSFUL;
1987         }
1988
1989         if (ldap_count_entries(ldap_state->smbldap_state->ldap_struct, result) == 0) {
1990                 DEBUG(0, ("No group to modify!\n"));
1991                 ldap_msgfree(result);
1992                 return NT_STATUS_UNSUCCESSFUL;
1993         }
1994
1995         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
1996         dn = ldap_get_dn(ldap_state->smbldap_state->ldap_struct, entry);
1997
1998         if (!init_ldap_from_group(ldap_state->smbldap_state->ldap_struct,
1999                                   result, &mods, map)) {
2000                 DEBUG(0, ("init_ldap_from_group failed\n"));
2001                 ldap_msgfree(result);
2002                 return NT_STATUS_UNSUCCESSFUL;
2003         }
2004
2005         ldap_msgfree(result);
2006
2007         if (mods == NULL) {
2008                 DEBUG(4, ("mods is empty: nothing to do\n"));
2009                 return NT_STATUS_UNSUCCESSFUL;
2010         }
2011
2012         rc = smbldap_modify(ldap_state->smbldap_state, dn, mods);
2013
2014         ldap_mods_free(mods, True);
2015
2016         if (rc != LDAP_SUCCESS) {
2017                 char *ld_error = NULL;
2018                 ldap_get_option(ldap_state->smbldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
2019                                 &ld_error);
2020                 DEBUG(0, ("failed to modify group %lu error: %s (%s)\n", (unsigned long)map->gid, 
2021                           ld_error ? ld_error : "(unknown)", ldap_err2string(rc)));
2022                 SAFE_FREE(ld_error);
2023         }
2024
2025         DEBUG(2, ("successfully modified group %lu in LDAP\n", (unsigned long)map->gid));
2026         return NT_STATUS_OK;
2027 }
2028
2029 /**********************************************************************
2030  *********************************************************************/
2031
2032 static NTSTATUS ldapsam_delete_group_mapping_entry(struct pdb_methods *methods,
2033                                                    DOM_SID sid)
2034 {
2035         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)methods->private_data;
2036         pstring sidstring, filter;
2037         LDAPMessage *result;
2038         int rc;
2039         NTSTATUS ret;
2040         char **attr_list;
2041
2042         sid_to_string(sidstring, &sid);
2043         
2044         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))", 
2045                 LDAP_OBJ_GROUPMAP, LDAP_ATTRIBUTE_SID, sidstring);
2046
2047         rc = ldapsam_search_one_group(ldap_state, filter, &result);
2048
2049         if (rc != LDAP_SUCCESS) {
2050                 return NT_STATUS_NO_SUCH_GROUP;
2051         }
2052
2053         attr_list = get_attr_list( groupmap_attr_list_to_delete );
2054         ret = ldapsam_delete_entry(ldap_state, result, LDAP_OBJ_GROUPMAP, attr_list);
2055         free_attr_list ( attr_list );
2056
2057         ldap_msgfree(result);
2058
2059         return ret;
2060 }
2061
2062 /**********************************************************************
2063  *********************************************************************/
2064
2065 static NTSTATUS ldapsam_setsamgrent(struct pdb_methods *my_methods, BOOL update)
2066 {
2067         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2068         fstring filter;
2069         int rc;
2070         char **attr_list;
2071
2072         pstr_sprintf( filter, "(objectclass=%s)", LDAP_OBJ_GROUPMAP);
2073         attr_list = get_attr_list( groupmap_attr_list );
2074         rc = smbldap_search(ldap_state->smbldap_state, lp_ldap_group_suffix(),
2075                             LDAP_SCOPE_SUBTREE, filter,
2076                             attr_list, 0, &ldap_state->result);
2077         free_attr_list( attr_list );
2078
2079         if (rc != LDAP_SUCCESS) {
2080                 DEBUG(0, ("LDAP search failed: %s\n", ldap_err2string(rc)));
2081                 DEBUG(3, ("Query was: %s, %s\n", lp_ldap_group_suffix(), filter));
2082                 ldap_msgfree(ldap_state->result);
2083                 ldap_state->result = NULL;
2084                 return NT_STATUS_UNSUCCESSFUL;
2085         }
2086
2087         DEBUG(2, ("ldapsam_setsampwent: %d entries in the base!\n",
2088                   ldap_count_entries(ldap_state->smbldap_state->ldap_struct,
2089                                      ldap_state->result)));
2090
2091         ldap_state->entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, ldap_state->result);
2092         ldap_state->index = 0;
2093
2094         return NT_STATUS_OK;
2095 }
2096
2097 /**********************************************************************
2098  *********************************************************************/
2099
2100 static void ldapsam_endsamgrent(struct pdb_methods *my_methods)
2101 {
2102         ldapsam_endsampwent(my_methods);
2103 }
2104
2105 /**********************************************************************
2106  *********************************************************************/
2107
2108 static NTSTATUS ldapsam_getsamgrent(struct pdb_methods *my_methods,
2109                                     GROUP_MAP *map)
2110 {
2111         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
2112         struct ldapsam_privates *ldap_state = (struct ldapsam_privates *)my_methods->private_data;
2113         BOOL bret = False;
2114
2115         while (!bret) {
2116                 if (!ldap_state->entry)
2117                         return ret;
2118                 
2119                 ldap_state->index++;
2120                 bret = init_group_from_ldap(ldap_state, map, ldap_state->entry);
2121                 
2122                 ldap_state->entry = ldap_next_entry(ldap_state->smbldap_state->ldap_struct,
2123                                             ldap_state->entry); 
2124         }
2125
2126         return NT_STATUS_OK;
2127 }
2128
2129 /**********************************************************************
2130  *********************************************************************/
2131
2132 static NTSTATUS ldapsam_enum_group_mapping(struct pdb_methods *methods,
2133                                            enum SID_NAME_USE sid_name_use,
2134                                            GROUP_MAP **rmap, int *num_entries,
2135                                            BOOL unix_only)
2136 {
2137         GROUP_MAP map;
2138         GROUP_MAP *mapt;
2139         int entries = 0;
2140
2141         *num_entries = 0;
2142         *rmap = NULL;
2143
2144         if (!NT_STATUS_IS_OK(ldapsam_setsamgrent(methods, False))) {
2145                 DEBUG(0, ("Unable to open passdb\n"));
2146                 return NT_STATUS_ACCESS_DENIED;
2147         }
2148
2149         while (NT_STATUS_IS_OK(ldapsam_getsamgrent(methods, &map))) {
2150                 if (sid_name_use != SID_NAME_UNKNOWN &&
2151                     sid_name_use != map.sid_name_use) {
2152                         DEBUG(11,("enum_group_mapping: group %s is not of the requested type\n", map.nt_name));
2153                         continue;
2154                 }
2155                 if (unix_only==ENUM_ONLY_MAPPED && map.gid==-1) {
2156                         DEBUG(11,("enum_group_mapping: group %s is non mapped\n", map.nt_name));
2157                         continue;
2158                 }
2159
2160                 mapt=(GROUP_MAP *)Realloc((*rmap), (entries+1)*sizeof(GROUP_MAP));
2161                 if (!mapt) {
2162                         DEBUG(0,("enum_group_mapping: Unable to enlarge group map!\n"));
2163                         SAFE_FREE(*rmap);
2164                         return NT_STATUS_UNSUCCESSFUL;
2165                 }
2166                 else
2167                         (*rmap) = mapt;
2168
2169                 mapt[entries] = map;
2170
2171                 entries += 1;
2172
2173         }
2174         ldapsam_endsamgrent(methods);
2175
2176         *num_entries = entries;
2177
2178         return NT_STATUS_OK;
2179 }
2180
2181 /**********************************************************************
2182  Housekeeping
2183  *********************************************************************/
2184
2185 static void free_private_data(void **vp) 
2186 {
2187         struct ldapsam_privates **ldap_state = (struct ldapsam_privates **)vp;
2188
2189         smbldap_free_struct(&(*ldap_state)->smbldap_state);
2190
2191         *ldap_state = NULL;
2192
2193         /* No need to free any further, as it is talloc()ed */
2194 }
2195
2196 /**********************************************************************
2197  Intitalise the parts of the pdb_context that are common to all pdb_ldap modes
2198  *********************************************************************/
2199
2200 static NTSTATUS pdb_init_ldapsam_common(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, 
2201                                         const char *location)
2202 {
2203         NTSTATUS nt_status;
2204         struct ldapsam_privates *ldap_state;
2205
2206         if (!NT_STATUS_IS_OK(nt_status = make_pdb_methods(pdb_context->mem_ctx, pdb_method))) {
2207                 return nt_status;
2208         }
2209
2210         (*pdb_method)->name = "ldapsam";
2211
2212         (*pdb_method)->setsampwent = ldapsam_setsampwent;
2213         (*pdb_method)->endsampwent = ldapsam_endsampwent;
2214         (*pdb_method)->getsampwent = ldapsam_getsampwent;
2215         (*pdb_method)->getsampwnam = ldapsam_getsampwnam;
2216         (*pdb_method)->getsampwsid = ldapsam_getsampwsid;
2217         (*pdb_method)->add_sam_account = ldapsam_add_sam_account;
2218         (*pdb_method)->update_sam_account = ldapsam_update_sam_account;
2219         (*pdb_method)->delete_sam_account = ldapsam_delete_sam_account;
2220
2221         (*pdb_method)->getgrsid = ldapsam_getgrsid;
2222         (*pdb_method)->getgrgid = ldapsam_getgrgid;
2223         (*pdb_method)->getgrnam = ldapsam_getgrnam;
2224         (*pdb_method)->add_group_mapping_entry = ldapsam_add_group_mapping_entry;
2225         (*pdb_method)->update_group_mapping_entry = ldapsam_update_group_mapping_entry;
2226         (*pdb_method)->delete_group_mapping_entry = ldapsam_delete_group_mapping_entry;
2227         (*pdb_method)->enum_group_mapping = ldapsam_enum_group_mapping;
2228
2229         /* TODO: Setup private data and free */
2230
2231         ldap_state = talloc_zero(pdb_context->mem_ctx, sizeof(*ldap_state));
2232         if (!ldap_state) {
2233                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
2234                 return NT_STATUS_NO_MEMORY;
2235         }
2236
2237         if (!NT_STATUS_IS_OK(nt_status = 
2238                              smbldap_init(pdb_context->mem_ctx, location, 
2239                                           &ldap_state->smbldap_state)));
2240
2241         ldap_state->domain_name = talloc_strdup(pdb_context->mem_ctx, get_global_sam_name());
2242         if (!ldap_state->domain_name) {
2243                 return NT_STATUS_NO_MEMORY;
2244         }
2245
2246         (*pdb_method)->private_data = ldap_state;
2247
2248         (*pdb_method)->free_private_data = free_private_data;
2249
2250         return NT_STATUS_OK;
2251 }
2252
2253 /**********************************************************************
2254  Initialise the 'compat' mode for pdb_ldap
2255  *********************************************************************/
2256
2257 static NTSTATUS pdb_init_ldapsam_compat(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
2258 {
2259         NTSTATUS nt_status;
2260         struct ldapsam_privates *ldap_state;
2261
2262 #ifdef WITH_LDAP_SAMCONFIG
2263         if (!location) {
2264                 int ldap_port = lp_ldap_port();
2265                         
2266                 /* remap default port if not using SSL (ie clear or TLS) */
2267                 if ( (lp_ldap_ssl() != LDAP_SSL_ON) && (ldap_port == 636) ) {
2268                         ldap_port = 389;
2269                 }
2270
2271                 location = talloc_asprintf(pdb_context->mem_ctx, "%s://%s:%d", lp_ldap_ssl() == LDAP_SSL_ON ? "ldaps" : "ldap", lp_ldap_server(), ldap_port);
2272                 if (!location) {
2273                         return NT_STATUS_NO_MEMORY;
2274                 }
2275         }
2276 #endif
2277
2278         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
2279                 return nt_status;
2280         }
2281
2282         (*pdb_method)->name = "ldapsam_compat";
2283
2284         ldap_state = (*pdb_method)->private_data;
2285         ldap_state->schema_ver = SCHEMAVER_SAMBAACCOUNT;
2286
2287         sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
2288
2289         return NT_STATUS_OK;
2290 }
2291
2292 /**********************************************************************
2293  Initialise the normal mode for pdb_ldap
2294  *********************************************************************/
2295
2296 static NTSTATUS pdb_init_ldapsam(PDB_CONTEXT *pdb_context, PDB_METHODS **pdb_method, const char *location)
2297 {
2298         NTSTATUS nt_status;
2299         struct ldapsam_privates *ldap_state;
2300         uint32 alg_rid_base;
2301         pstring alg_rid_base_string;
2302         LDAPMessage *result = NULL;
2303         LDAPMessage *entry = NULL;
2304         DOM_SID ldap_domain_sid;
2305         DOM_SID secrets_domain_sid;
2306         pstring domain_sid_string;
2307
2308         if (!NT_STATUS_IS_OK(nt_status = pdb_init_ldapsam_common(pdb_context, pdb_method, location))) {
2309                 return nt_status;
2310         }
2311
2312         (*pdb_method)->name = "ldapsam";
2313
2314         ldap_state = (*pdb_method)->private_data;
2315         ldap_state->schema_ver = SCHEMAVER_SAMBASAMACCOUNT;
2316
2317         /* Try to setup the Domain Name, Domain SID, algorithmic rid base */
2318         
2319         nt_status = smbldap_search_domain_info(ldap_state->smbldap_state, &result, 
2320                 ldap_state->domain_name, True);
2321         
2322         if ( !NT_STATUS_IS_OK(nt_status) ) {
2323                 DEBUG(2, ("WARNING: Could not get domain info, nor add one to the domain\n"));
2324                 DEBUGADD(2, ("Continuing on regardless, will be unable to allocate new users/groups, "
2325                         "and will risk BDCs having inconsistant SIDs\n"));
2326                 sid_copy(&ldap_state->domain_sid, get_global_sam_sid());
2327                 return NT_STATUS_OK;
2328         }
2329
2330         /* Given that the above might fail, everything below this must be optional */
2331         
2332         entry = ldap_first_entry(ldap_state->smbldap_state->ldap_struct, result);
2333         if (!entry) {
2334                 DEBUG(0, ("Could not get domain info entry\n"));
2335                 ldap_msgfree(result);
2336                 return NT_STATUS_UNSUCCESSFUL;
2337         }
2338
2339         if (smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
2340                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_USER_SID), 
2341                                  domain_sid_string)) 
2342         {
2343                 BOOL found_sid;
2344                 string_to_sid(&ldap_domain_sid, domain_sid_string);
2345                 found_sid = secrets_fetch_domain_sid(ldap_state->domain_name, &secrets_domain_sid);
2346                 if (!found_sid || !sid_equal(&secrets_domain_sid, &ldap_domain_sid)) {
2347                         /* reset secrets.tdb sid */
2348                         secrets_store_domain_sid(ldap_state->domain_name, &ldap_domain_sid);
2349                 }
2350                 sid_copy(&ldap_state->domain_sid, &ldap_domain_sid);
2351         }
2352
2353         if (smbldap_get_single_attribute(ldap_state->smbldap_state->ldap_struct, entry, 
2354                                  get_userattr_key2string(ldap_state->schema_ver, LDAP_ATTR_ALGORITHMIC_RID_BASE), 
2355                                  alg_rid_base_string)) 
2356         {
2357                 alg_rid_base = (uint32)atol(alg_rid_base_string);
2358                 if (alg_rid_base != algorithmic_rid_base()) {
2359                         DEBUG(0, ("The value of 'algorithmic RID base' has changed since the LDAP\n"
2360                                   "database was initialised.  Aborting. \n"));
2361                         ldap_msgfree(result);
2362                         return NT_STATUS_UNSUCCESSFUL;
2363                 }
2364         }
2365         ldap_msgfree(result);
2366
2367         return NT_STATUS_OK;
2368 }
2369
2370 NTSTATUS pdb_ldap_init(void)
2371 {
2372         NTSTATUS nt_status;
2373         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam", pdb_init_ldapsam)))
2374                 return nt_status;
2375
2376         if (!NT_STATUS_IS_OK(nt_status = smb_register_passdb(PASSDB_INTERFACE_VERSION, "ldapsam_compat", pdb_init_ldapsam_compat)))
2377                 return nt_status;
2378
2379         return NT_STATUS_OK;
2380 }
2381
2382