Removed version number from file header.
[kai/samba.git] / source3 / passdb / pdb_ldap.c
1 /* 
2    Unix SMB/CIFS implementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Gerald Carter 2001
5    Copyright (C) Shahms King 2001
6    Copyright (C) Jean Fran├žois Micouleau 1998
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21    
22 */
23
24 #include "includes.h"
25
26 #ifdef WITH_LDAP_SAM
27 /* TODO:
28 *  persistent connections: if using NSS LDAP, many connections are made
29 *      however, using only one within Samba would be nice
30 *  
31 *  Clean up SSL stuff, compile on OpenLDAP 1.x, 2.x, and Netscape SDK
32 *
33 *  Other LDAP based login attributes: accountExpires, etc.
34 *  (should be the domain of Samba proper, but the sam_password/SAM_ACCOUNT
35 *  structures don't have fields for some of these attributes)
36 *
37 *  SSL is done, but can't get the certificate based authentication to work
38 *  against on my test platform (Linux 2.4, OpenLDAP 2.x)
39 */
40
41 /* NOTE: this will NOT work against an Active Directory server
42 *  due to the fact that the two password fields cannot be retrieved
43 *  from a server; recommend using security = domain in this situation
44 *  and/or winbind
45 */
46
47 #include <lber.h>
48 #include <ldap.h>
49
50 #ifndef SAM_ACCOUNT
51 #define SAM_ACCOUNT struct sam_passwd
52 #endif
53
54 struct ldap_enum_info {
55         LDAP *ldap_struct;
56         LDAPMessage *result;
57         LDAPMessage *entry;
58 };
59
60 static struct ldap_enum_info global_ldap_ent;
61
62
63
64 /*******************************************************************
65  open a connection to the ldap server.
66 ******************************************************************/
67 static BOOL ldap_open_connection (LDAP ** ldap_struct)
68 {
69         int port;
70         int version, rc;
71         int tls = LDAP_OPT_X_TLS_HARD;
72
73         /* there should be an lp_ldap_ssl_port(), what happen if for some
74            reason we need to bind an SSLed LDAP on port 389 ?? ---simo */
75         if (lp_ldap_ssl() == LDAP_SSL_ON && lp_ldap_port() == 389) {
76                 port = 636;
77         }
78         else {
79                 port = lp_ldap_port();
80         }
81
82         if ((*ldap_struct = ldap_init(lp_ldap_server(), port)) == NULL) {
83                 DEBUG(0, ("The LDAP server is not responding !\n"));
84                 return False;
85         }
86
87         /* Connect to older servers using SSL and V2 rather than Start TLS */
88         if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
89         {
90                 if (version != LDAP_VERSION2)
91                 {
92                         version = LDAP_VERSION2;
93                         ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
94                 }
95         }
96
97         switch (lp_ldap_ssl())
98         {
99                 case LDAP_SSL_START_TLS:
100                         if (ldap_get_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, 
101                                 &version) == LDAP_OPT_SUCCESS)
102                         {
103                                 if (version < LDAP_VERSION3)
104                                 {
105                                         version = LDAP_VERSION3;
106                                         ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION,
107                                                         &version);
108                                 }
109                         }
110                         if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
111                         {
112                                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
113                                        ldap_err2string(rc)));
114                                 return False;
115                         }
116                         DEBUG (2, ("StartTLS issued: using a TLS connection\n"));
117                         break;
118                         
119                 case LDAP_SSL_ON:
120                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
121                         {
122                                 DEBUG(0, ("Failed to setup a TLS session\n"));
123                         }
124                         break;
125                         
126                 case LDAP_SSL_OFF:
127                 default:
128                         /* 
129                          * No special needs to setup options prior to the LDAP
130                          * bind (which should be called next via ldap_connect_system()
131                          */
132                         break;
133         }
134
135         DEBUG(2, ("ldap_open_connection: connection opened\n"));
136         return True;
137 }
138
139 /*******************************************************************
140  connect to the ldap server under system privilege.
141 ******************************************************************/
142 static BOOL ldap_connect_system(LDAP * ldap_struct)
143 {
144         int rc;
145         static BOOL got_pw = False;
146         static pstring ldap_secret;
147
148         /* get the password if we don't have it already */
149         if (!got_pw && !(got_pw=fetch_ldap_pw(lp_ldap_admin_dn(), ldap_secret, sizeof(pstring)))) 
150         {
151                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password for %s from secrets.tdb\n",
152                         lp_ldap_admin_dn()));
153                 return False;
154         }
155
156         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
157            (OpenLDAP) doesnt' seem to support it */
158            
159         DEBUG(10,("ldap_connect_system: Binding to ldap server as \"%s\"\n",
160                 lp_ldap_admin_dn()));
161                 
162         if ((rc = ldap_simple_bind_s(ldap_struct, lp_ldap_admin_dn(), 
163                 ldap_secret)) != LDAP_SUCCESS)
164         {
165                 DEBUG(0, ("Bind failed: %s\n", ldap_err2string(rc)));
166                 return False;
167         }
168         
169         DEBUG(2, ("ldap_connect_system: succesful connection to the LDAP server\n"));
170         return True;
171 }
172
173 /*******************************************************************
174  run the search by name.
175 ******************************************************************/
176 static int ldap_search_one_user (LDAP * ldap_struct, const char *filter, LDAPMessage ** result)
177 {
178         int scope = LDAP_SCOPE_SUBTREE;
179         int rc;
180
181         DEBUG(2, ("ldap_search_one_user: searching for:[%s]\n", filter));
182
183         rc = ldap_search_s(ldap_struct, lp_ldap_suffix (), scope, filter, NULL, 0, result);
184
185         if (rc != LDAP_SUCCESS) {
186                 DEBUG(0,("ldap_search_one_user: Problem during the LDAP search: %s\n", 
187                         ldap_err2string (rc)));
188                 DEBUG(3,("ldap_search_one_user: Query was: %s, %s\n", lp_ldap_suffix(), 
189                         filter));
190         }
191         
192         return rc;
193 }
194
195 /*******************************************************************
196  run the search by name.
197 ******************************************************************/
198 static int ldap_search_one_user_by_name (LDAP * ldap_struct, const char *user,
199                              LDAPMessage ** result)
200 {
201         pstring filter;
202         
203         /*
204          * in the filter expression, replace %u with the real name
205          * so in ldap filter, %u MUST exist :-)
206          */
207         pstrcpy(filter, lp_ldap_filter());
208
209         /* 
210          * have to use this here because $ is filtered out
211            * in pstring_sub
212          */
213         all_string_sub(filter, "%u", user, sizeof(pstring));
214
215         return ldap_search_one_user(ldap_struct, filter, result);
216 }
217
218 /*******************************************************************
219  run the search by uid.
220 ******************************************************************/
221 static int ldap_search_one_user_by_uid(LDAP * ldap_struct, int uid,
222                             LDAPMessage ** result)
223 {
224         struct passwd *user;
225         pstring filter;
226
227         /* Get the username from the system and look that up in the LDAP */
228         
229         if ((user = sys_getpwuid(uid)) == NULL) {
230                 DEBUG(3,("ldap_search_one_user_by_uid: Failed to locate uid [%d]\n", uid));
231                 return LDAP_NO_SUCH_OBJECT;
232         }
233         
234         pstrcpy(filter, lp_ldap_filter());
235         
236         all_string_sub(filter, "%u", user->pw_name, sizeof(pstring));
237
238         return ldap_search_one_user(ldap_struct, filter, result);
239 }
240
241 /*******************************************************************
242  run the search by rid.
243 ******************************************************************/
244 static int ldap_search_one_user_by_rid (LDAP * ldap_struct, uint32 rid,
245                             LDAPMessage ** result)
246 {
247         pstring filter;
248         int rc;
249
250         /* check if the user rid exsists, if not, try searching on the uid */
251         
252         snprintf(filter, sizeof(filter) - 1, "rid=%i", rid);
253         rc = ldap_search_one_user(ldap_struct, filter, result);
254         
255         if (rc != LDAP_SUCCESS)
256                 rc = ldap_search_one_user_by_uid(ldap_struct, 
257                         pdb_user_rid_to_uid(rid), result);
258
259         return rc;
260 }
261
262 /*******************************************************************
263 search an attribute and return the first value found.
264 ******************************************************************/
265 static BOOL get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
266                      char *attribute, char *value)
267 {
268         char **values;
269
270         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
271                 value = NULL;
272                 DEBUG (2, ("get_single_attribute: [%s] = [<does not exist>]\n", attribute));
273                 
274                 return False;
275         }
276
277         pstrcpy(value, values[0]);
278         ldap_value_free(values);
279         DEBUG (2, ("get_single_attribute: [%s] = [%s]\n", attribute, value));
280                 
281         return True;
282 }
283
284 /************************************************************************
285 Routine to manage the LDAPMod structure array
286 manage memory used by the array, by each struct, and values
287
288 ************************************************************************/
289 static void make_a_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
290 {
291         LDAPMod **mods;
292         int i;
293         int j;
294
295         mods = *modlist;
296
297         if (attribute == NULL || *attribute == '\0')
298                 return;
299
300         if (value == NULL || *value == '\0')
301                 return;
302
303         if (mods == NULL) 
304         {
305                 mods = (LDAPMod **) malloc(sizeof(LDAPMod *));
306                 if (mods == NULL)
307                 {
308                         DEBUG(0, ("make_a_mod: out of memory!\n"));
309                         return;
310                 }
311                 mods[0] = NULL;
312         }
313
314         for (i = 0; mods[i] != NULL; ++i) {
315                 if (mods[i]->mod_op == modop && !strcasecmp(mods[i]->mod_type, attribute))
316                         break;
317         }
318
319         if (mods[i] == NULL)
320         {
321                 mods = (LDAPMod **) Realloc (mods, (i + 2) * sizeof (LDAPMod *));
322                 if (mods == NULL)
323                 {
324                         DEBUG(0, ("make_a_mod: out of memory!\n"));
325                         return;
326                 }
327                 mods[i] = (LDAPMod *) malloc(sizeof(LDAPMod));
328                 if (mods[i] == NULL)
329                 {
330                         DEBUG(0, ("make_a_mod: out of memory!\n"));
331                         return;
332                 }
333                 mods[i]->mod_op = modop;
334                 mods[i]->mod_values = NULL;
335                 mods[i]->mod_type = strdup(attribute);
336                 mods[i + 1] = NULL;
337         }
338
339         if (value != NULL)
340         {
341                 j = 0;
342                 if (mods[i]->mod_values != NULL) {
343                         for (; mods[i]->mod_values[j] != NULL; j++);
344                 }
345                 mods[i]->mod_values = (char **)Realloc(mods[i]->mod_values,
346                                                (j + 2) * sizeof (char *));
347                                                
348                 if (mods[i]->mod_values == NULL) {
349                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
350                         return;
351                 }
352                 mods[i]->mod_values[j] = strdup(value);
353                 mods[i]->mod_values[j + 1] = NULL;
354         }
355         *modlist = mods;
356 }
357
358 /* New Interface is being implemented here */
359
360 /**********************************************************************
361 Initialize SAM_ACCOUNT from an LDAP query
362 (Based on init_sam_from_buffer in pdb_tdb.c)
363 *********************************************************************/
364 static BOOL init_sam_from_ldap (SAM_ACCOUNT * sampass,
365                    LDAP * ldap_struct, LDAPMessage * entry)
366 {
367         time_t  logon_time,
368                         logoff_time,
369                         kickoff_time,
370                         pass_last_set_time, 
371                         pass_can_change_time, 
372                         pass_must_change_time;
373         pstring         username, 
374                         domain,
375                         nt_username,
376                         fullname,
377                         homedir,
378                         dir_drive,
379                         logon_script,
380                         profile_path,
381                         acct_desc,
382                         munged_dial,
383                         workstations;
384         struct passwd   *pw;
385         uint32          user_rid, 
386                         group_rid;
387         uint8           smblmpwd[16],
388                         smbntpwd[16];
389         uint16          acct_ctrl, 
390                         logon_divs;
391         uint32 hours_len;
392         uint8           hours[MAX_HOURS_LEN];
393         pstring temp;
394         uid_t           uid = -1;
395         gid_t           gid = getegid();
396
397
398         /*
399          * do a little initialization
400          */
401         username[0]     = '\0';
402         domain[0]       = '\0';
403         nt_username[0]  = '\0';
404         fullname[0]     = '\0';
405         homedir[0]      = '\0';
406         dir_drive[0]    = '\0';
407         logon_script[0] = '\0';
408         profile_path[0] = '\0';
409         acct_desc[0]    = '\0';
410         munged_dial[0]  = '\0';
411         workstations[0] = '\0';
412          
413
414         if (sampass == NULL || ldap_struct == NULL || entry == NULL) {
415                 DEBUG(0, ("init_sam_from_ldap: NULL parameters found!\n"));
416                 return False;
417         }
418
419         get_single_attribute(ldap_struct, entry, "uid", username);
420         DEBUG(2, ("Entry found for user: %s\n", username));
421
422         pstrcpy(nt_username, username);
423
424         pstrcpy(domain, lp_workgroup());
425
426         get_single_attribute(ldap_struct, entry, "pwdLastSet", temp);
427         pass_last_set_time = (time_t) strtol(temp, NULL, 16);
428
429         get_single_attribute(ldap_struct, entry, "logonTime", temp);
430         logon_time = (time_t) strtol(temp, NULL, 16);
431
432         get_single_attribute(ldap_struct, entry, "logoffTime", temp);
433         logoff_time = (time_t) strtol(temp, NULL, 16);
434
435         get_single_attribute(ldap_struct, entry, "kickoffTime", temp);
436         kickoff_time = (time_t) strtol(temp, NULL, 16);
437
438         get_single_attribute(ldap_struct, entry, "pwdCanChange", temp);
439         pass_can_change_time = (time_t) strtol(temp, NULL, 16);
440
441         get_single_attribute(ldap_struct, entry, "pwdMustChange", temp);
442         pass_must_change_time = (time_t) strtol(temp, NULL, 16);
443
444         /* recommend that 'gecos' and 'displayName' should refer to the same
445            * attribute OID.  userFullName depreciated, only used by Samba
446            * primary rules of LDAP: don't make a new attribute when one is already defined
447          * that fits your needs; using cn then displayName rather than 'userFullName'
448          */
449
450         if (!get_single_attribute(ldap_struct, entry, "cn", fullname)) {
451                 get_single_attribute(ldap_struct, entry, "displayName", fullname);
452         }
453
454
455         if (!get_single_attribute(ldap_struct, entry, "homeDrive", dir_drive)) {
456                 pstrcpy(dir_drive, lp_logon_drive());
457                 standard_sub_advanced(-1, username, "", gid, username, dir_drive);
458                 DEBUG(5,("homeDrive fell back to %s\n",dir_drive));
459                 pdb_set_dir_drive(sampass, dir_drive, False);
460         }
461         else
462                 pdb_set_dir_drive(sampass, dir_drive, True);
463
464         if (!get_single_attribute(ldap_struct, entry, "smbHome", homedir)) {
465                 pstrcpy(homedir, lp_logon_home());
466                 standard_sub_advanced(-1, username, "", gid, username, homedir);
467                 DEBUG(5,("smbHome fell back to %s\n",homedir));
468                 pdb_set_homedir(sampass, homedir, False);
469         }
470         else
471                 pdb_set_homedir(sampass, homedir, True);
472
473         if (!get_single_attribute(ldap_struct, entry, "scriptPath", logon_script)) {
474                 pstrcpy(logon_script, lp_logon_script());
475                 standard_sub_advanced(-1, username, "", gid, username, logon_script);
476                 DEBUG(5,("scriptPath fell back to %s\n",logon_script));
477                 pdb_set_logon_script(sampass, logon_script, False);
478         }
479         else
480                 pdb_set_logon_script(sampass, logon_script, True);
481
482         if (!get_single_attribute(ldap_struct, entry, "profilePath", profile_path)) {
483                 pstrcpy(profile_path, lp_logon_path());
484                 standard_sub_advanced(-1, username, "", gid, username, profile_path);
485                 DEBUG(5,("profilePath fell back to %s\n",profile_path));
486                 pdb_set_profile_path(sampass, profile_path, False);
487         }
488         else
489                 pdb_set_profile_path(sampass, profile_path, True);
490                 
491         get_single_attribute(ldap_struct, entry, "description", acct_desc);
492         get_single_attribute(ldap_struct, entry, "userWorkstations", workstations);
493         get_single_attribute(ldap_struct, entry, "rid", temp);
494         user_rid = (uint32)strtol(temp, NULL, 10);
495         get_single_attribute(ldap_struct, entry, "primaryGroupID", temp);
496         group_rid = (uint32)strtol(temp, NULL, 10);
497
498
499         /* These values MAY be in LDAP, but they can also be retrieved through 
500          *  sys_getpw*() which is how we're doing it 
501          */
502         pw = getpwnam_alloc(username);
503         if (pw == NULL) {
504                 DEBUG (2,("init_sam_from_ldap: User [%s] does not ave a uid!\n", username));
505                 return False;
506         }
507         uid = pw->pw_uid;
508         gid = pw->pw_gid;
509
510         passwd_free(&pw);
511
512         /* FIXME: hours stuff should be cleaner */
513         
514         logon_divs = 168;
515         hours_len = 21;
516         memset(hours, 0xff, hours_len);
517
518         get_single_attribute (ldap_struct, entry, "lmPassword", temp);
519         pdb_gethexpwd(temp, smblmpwd);
520         memset((char *)temp, '\0', sizeof(temp));
521         get_single_attribute (ldap_struct, entry, "ntPassword", temp);
522         pdb_gethexpwd(temp, smbntpwd);
523         memset((char *)temp, '\0', sizeof(temp));
524         get_single_attribute (ldap_struct, entry, "acctFlags", temp);
525         acct_ctrl = pdb_decode_acct_ctrl(temp);
526
527         if (acct_ctrl == 0)
528                 acct_ctrl |= ACB_NORMAL;
529
530         pdb_set_uid(sampass, uid);
531         pdb_set_gid(sampass, gid);
532         
533         pdb_set_acct_ctrl(sampass, acct_ctrl);
534         pdb_set_logon_time(sampass, logon_time);
535         pdb_set_logoff_time(sampass, logoff_time);
536         pdb_set_kickoff_time(sampass, kickoff_time);
537         pdb_set_pass_can_change_time(sampass, pass_can_change_time);
538         pdb_set_pass_must_change_time(sampass, pass_must_change_time);
539         pdb_set_pass_last_set_time(sampass, pass_last_set_time);
540
541         pdb_set_hours_len(sampass, hours_len);
542         pdb_set_logon_divs(sampass, logon_divs);
543
544         pdb_set_user_rid(sampass, user_rid);
545         pdb_set_group_rid(sampass, group_rid);
546
547         pdb_set_username(sampass, username);
548
549         pdb_set_domain(sampass, domain);
550         pdb_set_nt_username(sampass, nt_username);
551
552         pdb_set_fullname(sampass, fullname);
553
554         pdb_set_acct_desc(sampass, acct_desc);
555         pdb_set_workstations(sampass, workstations);
556         pdb_set_munged_dial(sampass, munged_dial);
557         
558         if (!pdb_set_nt_passwd(sampass, smbntpwd))
559                 return False;
560         if (!pdb_set_lanman_passwd(sampass, smblmpwd))
561                 return False;
562
563         /* pdb_set_unknown_3(sampass, unknown3); */
564         /* pdb_set_unknown_5(sampass, unknown5); */
565         /* pdb_set_unknown_6(sampass, unknown6); */
566
567         pdb_set_hours(sampass, hours);
568
569         return True;
570 }
571
572 /**********************************************************************
573 Initialize SAM_ACCOUNT from an LDAP query
574 (Based on init_buffer_from_sam in pdb_tdb.c)
575 *********************************************************************/
576 static BOOL init_ldap_from_sam (LDAPMod *** mods, int ldap_state, const SAM_ACCOUNT * sampass)
577 {
578         pstring temp;
579
580         if (mods == NULL || sampass == NULL) {
581                 DEBUG(0, ("init_ldap_from_sam: NULL parameters found!\n"));
582                 return False;
583         }
584
585         *mods = NULL;
586
587         /* 
588          * took out adding "objectclass: sambaAccount"
589          * do this on a per-mod basis
590          */
591
592
593         make_a_mod(mods, ldap_state, "uid", pdb_get_username(sampass));
594         DEBUG(2, ("Setting entry for user: %s\n", pdb_get_username(sampass)));
595
596         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_last_set_time(sampass));
597         make_a_mod(mods, ldap_state, "pwdLastSet", temp);
598
599         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logon_time(sampass));
600         make_a_mod(mods, ldap_state, "logonTime", temp);
601
602         slprintf(temp, sizeof(temp) - 1, "%li", pdb_get_logoff_time(sampass));
603         make_a_mod(mods, ldap_state, "logoffTime", temp);
604
605         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_kickoff_time(sampass));
606         make_a_mod(mods, ldap_state, "kickoffTime", temp);
607
608         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_can_change_time(sampass));
609         make_a_mod(mods, ldap_state, "pwdCanChange", temp);
610
611         slprintf (temp, sizeof (temp) - 1, "%li", pdb_get_pass_must_change_time(sampass));
612         make_a_mod(mods, ldap_state, "pwdMustChange", temp);
613
614         /* displayName, cn, and gecos should all be the same
615            *  most easily accomplished by giving them the same OID
616            *  gecos isn't set here b/c it should be handled by the 
617            *  add-user script
618          */
619
620         make_a_mod(mods, ldap_state, "displayName", pdb_get_fullname(sampass));
621         make_a_mod(mods, ldap_state, "cn", pdb_get_fullname(sampass));
622         make_a_mod(mods, ldap_state, "description", pdb_get_acct_desc(sampass));
623         make_a_mod(mods, ldap_state, "userWorkstations", pdb_get_workstations(sampass));
624
625         /*
626          * Only updates fields which have been set (not defaults from smb.conf)
627          */
628
629         if (IS_SAM_SET(sampass, FLAG_SAM_SMBHOME))
630         make_a_mod(mods, ldap_state, "smbHome", pdb_get_homedir(sampass));
631                 
632         if (IS_SAM_SET(sampass, FLAG_SAM_DRIVE))
633         make_a_mod(mods, ldap_state, "homeDrive", pdb_get_dirdrive(sampass));
634                 
635         if (IS_SAM_SET(sampass, FLAG_SAM_LOGONSCRIPT))
636         make_a_mod(mods, ldap_state, "scriptPath", pdb_get_logon_script(sampass));
637
638         if (IS_SAM_SET(sampass, FLAG_SAM_PROFILE))
639         make_a_mod(mods, ldap_state, "profilePath", pdb_get_profile_path(sampass));
640
641
642         if ( !pdb_get_user_rid(sampass))
643                 slprintf(temp, sizeof(temp) - 1, "%i", pdb_uid_to_user_rid(pdb_get_uid(sampass)));
644         else
645                 slprintf(temp, sizeof(temp) - 1, "%i", pdb_get_user_rid(sampass));
646         make_a_mod(mods, ldap_state, "rid", temp);
647
648         if ( !pdb_get_group_rid(sampass))
649                 slprintf(temp, sizeof(temp) - 1, "%i", pdb_gid_to_group_rid(pdb_get_gid(sampass)));
650         else
651                 slprintf(temp, sizeof(temp) - 1, "%i", pdb_get_group_rid(sampass));
652         make_a_mod(mods, ldap_state, "primaryGroupID", temp);
653
654         /* FIXME: Hours stuff goes in LDAP  */
655         pdb_sethexpwd (temp, pdb_get_lanman_passwd(sampass), pdb_get_acct_ctrl(sampass));
656         make_a_mod (mods, ldap_state, "lmPassword", temp);
657         
658         pdb_sethexpwd (temp, pdb_get_nt_passwd(sampass), pdb_get_acct_ctrl(sampass));
659         make_a_mod (mods, ldap_state, "ntPassword", temp);
660         
661         make_a_mod (mods, ldap_state, "acctFlags", pdb_encode_acct_ctrl (pdb_get_acct_ctrl(sampass),
662                 NEW_PW_FORMAT_SPACE_PADDED_LEN));
663
664         return True;
665 }
666
667 /**********************************************************************
668 Connect to LDAP server for password enumeration
669 *********************************************************************/
670 BOOL pdb_setsampwent(BOOL update)
671 {
672         int rc;
673         pstring filter;
674
675         if (!ldap_open_connection(&global_ldap_ent.ldap_struct))
676         {
677                 return False;
678         }
679         if (!ldap_connect_system(global_ldap_ent.ldap_struct))
680         {
681                 ldap_unbind(global_ldap_ent.ldap_struct);
682                 return False;
683         }
684
685         pstrcpy(filter, lp_ldap_filter());
686         all_string_sub(filter, "%u", "*", sizeof(pstring));
687
688         rc = ldap_search_s(global_ldap_ent.ldap_struct, lp_ldap_suffix(),
689                            LDAP_SCOPE_SUBTREE, filter, NULL, 0,
690                            &global_ldap_ent.result);
691
692         if (rc != LDAP_SUCCESS)
693         {
694                 DEBUG(0, ("LDAP search failed: %s\n", ldap_err2string(rc)));
695                 DEBUG(3, ("Query was: %s, %s\n", lp_ldap_suffix(), filter));
696                 ldap_msgfree(global_ldap_ent.result);
697                 ldap_unbind(global_ldap_ent.ldap_struct);
698                 global_ldap_ent.ldap_struct = NULL;
699                 global_ldap_ent.result = NULL;
700                 return False;
701         }
702
703         DEBUG(2, ("pdb_setsampwent: %d entries in the base!\n",
704                 ldap_count_entries(global_ldap_ent.ldap_struct,
705                 global_ldap_ent.result)));
706
707         global_ldap_ent.entry = ldap_first_entry(global_ldap_ent.ldap_struct,
708                                  global_ldap_ent.result);
709
710         return True;
711 }
712
713 /**********************************************************************
714 End enumeration of the LDAP password list 
715 *********************************************************************/
716 void pdb_endsampwent(void)
717 {
718         if (global_ldap_ent.ldap_struct && global_ldap_ent.result)
719         {
720                 ldap_msgfree(global_ldap_ent.result);
721                 ldap_unbind(global_ldap_ent.ldap_struct);
722                 global_ldap_ent.ldap_struct = NULL;
723                 global_ldap_ent.result = NULL;
724         }
725 }
726
727 /**********************************************************************
728 Get the next entry in the LDAP password database 
729 *********************************************************************/
730 BOOL pdb_getsampwent(SAM_ACCOUNT * user)
731 {
732         if (!global_ldap_ent.entry)
733                 return False;
734
735         global_ldap_ent.entry = ldap_next_entry(global_ldap_ent.ldap_struct,
736                                 global_ldap_ent.entry);
737
738         if (global_ldap_ent.entry != NULL)
739         {
740                 return init_sam_from_ldap(user, global_ldap_ent.ldap_struct,
741                                           global_ldap_ent.entry);
742         }
743         return False;
744 }
745
746 /**********************************************************************
747 Get SAM_ACCOUNT entry from LDAP by username 
748 *********************************************************************/
749 BOOL pdb_getsampwnam(SAM_ACCOUNT * user, const char *sname)
750 {
751         LDAP *ldap_struct;
752         LDAPMessage *result;
753         LDAPMessage *entry;
754
755         if (!ldap_open_connection(&ldap_struct))
756                 return False;
757         if (!ldap_connect_system(ldap_struct))
758         {
759                 ldap_unbind(ldap_struct);
760                 return False;
761         }
762         if (ldap_search_one_user_by_name(ldap_struct, sname, &result) != LDAP_SUCCESS)
763         {
764                 ldap_unbind(ldap_struct);
765                 return False;
766         }
767         if (ldap_count_entries(ldap_struct, result) < 1)
768         {
769                 DEBUG(0,
770                       ("We don't find this user [%s] count=%d\n", sname,
771                        ldap_count_entries(ldap_struct, result)));
772                 ldap_unbind(ldap_struct);
773                 return False;
774         }
775         entry = ldap_first_entry(ldap_struct, result);
776         if (entry)
777         {
778                 init_sam_from_ldap(user, ldap_struct, entry);
779                 ldap_msgfree(result);
780                 ldap_unbind(ldap_struct);
781                 return True;
782         }
783         else
784         {
785                 ldap_msgfree(result);
786                 ldap_unbind(ldap_struct);
787                 return False;
788         }
789 }
790
791 /**********************************************************************
792 Get SAM_ACCOUNT entry from LDAP by rid 
793 *********************************************************************/
794 BOOL pdb_getsampwrid(SAM_ACCOUNT * user, uint32 rid)
795 {
796         LDAP *ldap_struct;
797         LDAPMessage *result;
798         LDAPMessage *entry;
799
800         if (!ldap_open_connection(&ldap_struct))
801                 return False;
802
803         if (!ldap_connect_system(ldap_struct))
804         {
805                 ldap_unbind(ldap_struct);
806                 return False;
807         }
808         if (ldap_search_one_user_by_rid(ldap_struct, rid, &result) !=
809             LDAP_SUCCESS)
810         {
811                 ldap_unbind(ldap_struct);
812                 return False;
813         }
814
815         if (ldap_count_entries(ldap_struct, result) < 1)
816         {
817                 DEBUG(0,
818                       ("We don't find this rid [%i] count=%d\n", rid,
819                        ldap_count_entries(ldap_struct, result)));
820                 ldap_unbind(ldap_struct);
821                 return False;
822         }
823
824         entry = ldap_first_entry(ldap_struct, result);
825         if (entry)
826         {
827                 init_sam_from_ldap(user, ldap_struct, entry);
828                 ldap_msgfree(result);
829                 ldap_unbind(ldap_struct);
830                 return True;
831         }
832         else
833         {
834                 ldap_msgfree(result);
835                 ldap_unbind(ldap_struct);
836                 return False;
837         }
838 }
839
840 /**********************************************************************
841 Delete entry from LDAP for username 
842 *********************************************************************/
843 BOOL pdb_delete_sam_account(SAM_ACCOUNT * sam_acct)
844 {
845         const char *sname;
846         int rc;
847         char *dn;
848         LDAP *ldap_struct;
849         LDAPMessage *entry;
850         LDAPMessage *result;
851
852         if (!sam_acct) {
853                 DEBUG(0, ("sam_acct was NULL!\n"));
854                 return False;
855         }
856
857         sname = pdb_get_username(sam_acct);
858
859         if (!ldap_open_connection (&ldap_struct))
860                 return False;
861
862         DEBUG (3, ("Deleting user %s from LDAP.\n", sname));
863         
864         if (!ldap_connect_system (ldap_struct)) {
865                 ldap_unbind (ldap_struct);
866                 DEBUG(0, ("Failed to delete user %s from LDAP.\n", sname));
867                 return False;
868         }
869
870         rc = ldap_search_one_user_by_name (ldap_struct, sname, &result);
871         if (ldap_count_entries (ldap_struct, result) == 0) {
872                 DEBUG (0, ("User doesn't exit!\n"));
873                 ldap_msgfree (result);
874                 ldap_unbind (ldap_struct);
875                 return False;
876         }
877
878         entry = ldap_first_entry (ldap_struct, result);
879         dn = ldap_get_dn (ldap_struct, entry);
880
881         rc = ldap_delete_s (ldap_struct, dn);
882
883         ldap_memfree (dn);
884         if (rc != LDAP_SUCCESS) {
885                 char *ld_error;
886                 ldap_get_option (ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
887                 DEBUG (0,("failed to delete user with uid = %s with: %s\n\t%s\n",
888                         sname, ldap_err2string (rc), ld_error));
889                 free (ld_error);
890                 ldap_unbind (ldap_struct);
891                 return False;
892         }
893
894         DEBUG (2,("successfully deleted uid = %s from the LDAP database\n", sname));
895         ldap_unbind (ldap_struct);
896         return True;
897 }
898
899 /**********************************************************************
900 Update SAM_ACCOUNT 
901 *********************************************************************/
902 BOOL pdb_update_sam_account(SAM_ACCOUNT * newpwd)
903 {
904         int rc;
905         char *dn;
906         LDAP *ldap_struct;
907         LDAPMessage *result;
908         LDAPMessage *entry;
909         LDAPMod **mods;
910
911         if (!ldap_open_connection(&ldap_struct)) /* open a connection to the server */
912                 return False;
913
914         if (!ldap_connect_system(ldap_struct))  /* connect as system account */
915         {
916                 ldap_unbind(ldap_struct);
917                 return False;
918         }
919
920         rc = ldap_search_one_user_by_name(ldap_struct,
921                                           pdb_get_username(newpwd), &result);
922
923         if (ldap_count_entries(ldap_struct, result) == 0)
924         {
925                 DEBUG(0, ("No user to modify!\n"));
926                 ldap_msgfree(result);
927                 ldap_unbind(ldap_struct);
928                 return False;
929         }
930
931         init_ldap_from_sam(&mods, LDAP_MOD_REPLACE, newpwd);
932
933         entry = ldap_first_entry(ldap_struct, result);
934         dn = ldap_get_dn(ldap_struct, entry);
935
936         rc = ldap_modify_s(ldap_struct, dn, mods);
937
938         if (rc != LDAP_SUCCESS)
939         {
940                 char *ld_error;
941                 ldap_get_option(ldap_struct, LDAP_OPT_ERROR_STRING,
942                                 &ld_error);
943                 DEBUG(0,
944                       ("failed to modify user with uid = %s with: %s\n\t%s\n",
945                        pdb_get_username(newpwd), ldap_err2string(rc),
946                        ld_error));
947                 free(ld_error);
948                 ldap_unbind(ldap_struct);
949                 return False;
950         }
951
952         DEBUG(2,
953               ("successfully modified uid = %s in the LDAP database\n",
954                pdb_get_username(newpwd)));
955         ldap_mods_free(mods, 1);
956         ldap_unbind(ldap_struct);
957         return True;
958 }
959
960 /**********************************************************************
961 Add SAM_ACCOUNT to LDAP 
962 *********************************************************************/
963 BOOL pdb_add_sam_account(SAM_ACCOUNT * newpwd)
964 {
965         int rc;
966         pstring filter;
967         LDAP *ldap_struct;
968         LDAPMessage *result;
969         pstring dn;
970         LDAPMod **mods;
971         int             ldap_op;
972         uint32          num_result;
973
974         if (!ldap_open_connection(&ldap_struct))        /* open a connection to the server */
975         {
976                 return False;
977         }
978
979         if (!ldap_connect_system(ldap_struct))  /* connect as system account */
980         {
981                 ldap_unbind(ldap_struct);
982                 return False;
983         }
984
985         rc = ldap_search_one_user_by_name (ldap_struct, pdb_get_username(newpwd), &result);
986
987         if (ldap_count_entries(ldap_struct, result) != 0)
988         {
989                 DEBUG(0,("User already in the base, with samba properties\n"));
990                 ldap_msgfree(result);
991                 ldap_unbind(ldap_struct);
992                 return False;
993         }
994         ldap_msgfree(result);
995
996         slprintf (filter, sizeof (filter) - 1, "uid=%s", pdb_get_username(newpwd));
997         rc = ldap_search_one_user(ldap_struct, filter, &result);
998         num_result = ldap_count_entries(ldap_struct, result);
999         
1000         if (num_result > 1) {
1001                 DEBUG (0, ("More than one user with that uid exists: bailing out!\n"));
1002                 return False;
1003         }
1004         
1005         /* Check if we need to update an existing entry */
1006         if (num_result == 1) {
1007                 char *tmp;
1008                 LDAPMessage *entry;
1009                 
1010                 DEBUG(3,("User exists without samba properties: adding them\n"));
1011                 ldap_op = LDAP_MOD_REPLACE;
1012                 entry = ldap_first_entry (ldap_struct, result);
1013                 tmp = ldap_get_dn (ldap_struct, entry);
1014                 slprintf (dn, sizeof (dn) - 1, "%s", tmp);
1015                 ldap_memfree (tmp);
1016         }
1017         else {
1018                 /* Check if we need to add an entry */
1019                 DEBUG(3,("Adding new user\n"));
1020                 ldap_op = LDAP_MOD_ADD;
1021                 slprintf (dn, sizeof (dn) - 1, "uid=%s,%s", pdb_get_username(newpwd), lp_ldap_suffix ());
1022         }
1023
1024         ldap_msgfree(result);
1025
1026         init_ldap_from_sam(&mods, ldap_op, newpwd);
1027         make_a_mod(&mods, LDAP_MOD_ADD, "objectclass", "sambaAccount");
1028
1029         if (ldap_op == LDAP_MOD_REPLACE) {
1030                 rc = ldap_modify_s(ldap_struct, dn, mods);
1031         }
1032         else {
1033                 rc = ldap_add_s(ldap_struct, dn, mods);
1034         }
1035
1036         if (rc != LDAP_SUCCESS)
1037         {
1038                 char *ld_error;
1039
1040                 ldap_get_option (ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
1041                 DEBUG(0,("failed to modify user with uid = %s with: %s\n\t%s\n",
1042                         pdb_get_username(newpwd), ldap_err2string (rc), ld_error));
1043                 free(ld_error);
1044                 ldap_mods_free(mods, 1);
1045                 ldap_unbind(ldap_struct);
1046                 return False;
1047         }
1048         
1049         DEBUG(2,("added: uid = %s in the LDAP database\n", pdb_get_username(newpwd)));
1050         ldap_mods_free(mods, 1);
1051         ldap_unbind(ldap_struct);
1052         return True;
1053 }
1054
1055 #else
1056 void dummy_function(void);
1057 void
1058 dummy_function (void)
1059 {
1060 }                               /* stop some compilers complaining */
1061 #endif