r4088: Get medieval on our ass about malloc.... :-). Take control of all our allocation
[tprouty/samba.git] / source / lib / smbldap.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-2003
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 #include "includes.h"
27 #include "smbldap.h"
28
29 #ifndef LDAP_OPT_SUCCESS
30 #define LDAP_OPT_SUCCESS 0
31 #endif
32
33 /* Try not to hit the up or down server forever */
34
35 #define SMBLDAP_DONT_PING_TIME 10       /* ping only all 10 seconds */
36 #define SMBLDAP_NUM_RETRIES 8           /* retry only 8 times */
37
38 #define SMBLDAP_IDLE_TIME 150           /* After 2.5 minutes disconnect */
39
40
41 /* attributes used by Samba 2.2 */
42
43 ATTRIB_MAP_ENTRY attrib_map_v22[] = {
44         { LDAP_ATTR_UID,                "uid"           },
45         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
46         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
47         { LDAP_ATTR_UNIX_HOME,          "homeDirectory" },
48         { LDAP_ATTR_PWD_LAST_SET,       "pwdLastSet"    },
49         { LDAP_ATTR_PWD_CAN_CHANGE,     "pwdCanChange"  },
50         { LDAP_ATTR_PWD_MUST_CHANGE,    "pwdMustChange" },
51         { LDAP_ATTR_LOGON_TIME,         "logonTime"     },
52         { LDAP_ATTR_LOGOFF_TIME,        "logoffTime"    },
53         { LDAP_ATTR_KICKOFF_TIME,       "kickoffTime"   },
54         { LDAP_ATTR_CN,                 "cn"            },
55         { LDAP_ATTR_DISPLAY_NAME,       "displayName"   },
56         { LDAP_ATTR_HOME_PATH,          "smbHome"       },
57         { LDAP_ATTR_HOME_DRIVE,         "homeDrive"     },
58         { LDAP_ATTR_LOGON_SCRIPT,       "scriptPath"    },
59         { LDAP_ATTR_PROFILE_PATH,       "profilePath"   },
60         { LDAP_ATTR_DESC,               "description"   },
61         { LDAP_ATTR_USER_WKS,           "userWorkstations"},
62         { LDAP_ATTR_USER_RID,           "rid"           },
63         { LDAP_ATTR_PRIMARY_GROUP_RID,  "primaryGroupID"},
64         { LDAP_ATTR_LMPW,               "lmPassword"    },
65         { LDAP_ATTR_NTPW,               "ntPassword"    },
66         { LDAP_ATTR_DOMAIN,             "domain"        },
67         { LDAP_ATTR_OBJCLASS,           "objectClass"   },
68         { LDAP_ATTR_ACB_INFO,           "acctFlags"     },
69         { LDAP_ATTR_MOD_TIMESTAMP,      "modifyTimestamp"       },
70         { LDAP_ATTR_LIST_END,           NULL            }
71 };
72
73 ATTRIB_MAP_ENTRY attrib_map_to_delete_v22[] = {
74         { LDAP_ATTR_PWD_LAST_SET,       "pwdLastSet"    },
75         { LDAP_ATTR_PWD_CAN_CHANGE,     "pwdCanChange"  },
76         { LDAP_ATTR_PWD_MUST_CHANGE,    "pwdMustChange" },
77         { LDAP_ATTR_LOGON_TIME,         "logonTime"     },
78         { LDAP_ATTR_LOGOFF_TIME,        "logoffTime"    },
79         { LDAP_ATTR_KICKOFF_TIME,       "kickoffTime"   },
80         { LDAP_ATTR_DISPLAY_NAME,       "displayName"   },
81         { LDAP_ATTR_HOME_PATH,          "smbHome"       },
82         { LDAP_ATTR_HOME_DRIVE,         "homeDrives"    },
83         { LDAP_ATTR_LOGON_SCRIPT,       "scriptPath"    },
84         { LDAP_ATTR_PROFILE_PATH,       "profilePath"   },
85         { LDAP_ATTR_USER_WKS,           "userWorkstations"},
86         { LDAP_ATTR_USER_RID,           "rid"           },
87         { LDAP_ATTR_PRIMARY_GROUP_RID,  "primaryGroupID"},
88         { LDAP_ATTR_LMPW,               "lmPassword"    },
89         { LDAP_ATTR_NTPW,               "ntPassword"    },
90         { LDAP_ATTR_DOMAIN,             "domain"        },
91         { LDAP_ATTR_ACB_INFO,           "acctFlags"     },
92         { LDAP_ATTR_LIST_END,           NULL            }
93 };
94
95 /* attributes used by Samba 3.0's sambaSamAccount */
96
97 ATTRIB_MAP_ENTRY attrib_map_v30[] = {
98         { LDAP_ATTR_UID,                "uid"                   },
99         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
100         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
101         { LDAP_ATTR_UNIX_HOME,          "homeDirectory"         },
102         { LDAP_ATTR_PWD_LAST_SET,       "sambaPwdLastSet"       },
103         { LDAP_ATTR_PWD_CAN_CHANGE,     "sambaPwdCanChange"     },
104         { LDAP_ATTR_PWD_MUST_CHANGE,    "sambaPwdMustChange"    },
105         { LDAP_ATTR_LOGON_TIME,         "sambaLogonTime"        },
106         { LDAP_ATTR_LOGOFF_TIME,        "sambaLogoffTime"       },
107         { LDAP_ATTR_KICKOFF_TIME,       "sambaKickoffTime"      },
108         { LDAP_ATTR_CN,                 "cn"                    },
109         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
110         { LDAP_ATTR_HOME_DRIVE,         "sambaHomeDrive"        },
111         { LDAP_ATTR_HOME_PATH,          "sambaHomePath"         },
112         { LDAP_ATTR_LOGON_SCRIPT,       "sambaLogonScript"      },
113         { LDAP_ATTR_PROFILE_PATH,       "sambaProfilePath"      },
114         { LDAP_ATTR_DESC,               "description"           },
115         { LDAP_ATTR_USER_WKS,           "sambaUserWorkstations" },
116         { LDAP_ATTR_USER_SID,           LDAP_ATTRIBUTE_SID      },
117         { LDAP_ATTR_PRIMARY_GROUP_SID,  "sambaPrimaryGroupSID"  },
118         { LDAP_ATTR_LMPW,               "sambaLMPassword"       },
119         { LDAP_ATTR_NTPW,               "sambaNTPassword"       },
120         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
121         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
122         { LDAP_ATTR_ACB_INFO,           "sambaAcctFlags"        },
123         { LDAP_ATTR_MUNGED_DIAL,        "sambaMungedDial"       },
124         { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
125         { LDAP_ATTR_BAD_PASSWORD_TIME,  "sambaBadPasswordTime"  },
126         { LDAP_ATTR_PWD_HISTORY,        "sambaPasswordHistory"  },
127         { LDAP_ATTR_MOD_TIMESTAMP,      "modifyTimestamp"       },
128         { LDAP_ATTR_LOGON_HOURS,        "sambaLogonHours"       },
129         { LDAP_ATTR_LIST_END,           NULL                    }
130 };
131
132 ATTRIB_MAP_ENTRY attrib_map_to_delete_v30[] = {
133         { LDAP_ATTR_PWD_LAST_SET,       "sambaPwdLastSet"       },
134         { LDAP_ATTR_PWD_CAN_CHANGE,     "sambaPwdCanChange"     },
135         { LDAP_ATTR_PWD_MUST_CHANGE,    "sambaPwdMustChange"    },
136         { LDAP_ATTR_LOGON_TIME,         "sambaLogonTime"        },
137         { LDAP_ATTR_LOGOFF_TIME,        "sambaLogoffTime"       },
138         { LDAP_ATTR_KICKOFF_TIME,       "sambaKickoffTime"      },
139         { LDAP_ATTR_HOME_DRIVE,         "sambaHomeDrive"        },
140         { LDAP_ATTR_HOME_PATH,          "sambaHomePath"         },
141         { LDAP_ATTR_LOGON_SCRIPT,       "sambaLogonScript"      },
142         { LDAP_ATTR_PROFILE_PATH,       "sambaProfilePath"      },
143         { LDAP_ATTR_USER_WKS,           "sambaUserWorkstations" },
144         { LDAP_ATTR_USER_SID,           LDAP_ATTRIBUTE_SID      },
145         { LDAP_ATTR_PRIMARY_GROUP_SID,  "sambaPrimaryGroupSID"  },
146         { LDAP_ATTR_LMPW,               "sambaLMPassword"       },
147         { LDAP_ATTR_NTPW,               "sambaNTPassword"       },
148         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
149         { LDAP_ATTR_ACB_INFO,           "sambaAcctFlags"        },
150         { LDAP_ATTR_MUNGED_DIAL,        "sambaMungedDial"       },
151         { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
152         { LDAP_ATTR_BAD_PASSWORD_TIME,  "sambaBadPasswordTime"  },
153         { LDAP_ATTR_PWD_HISTORY,        "sambaPasswordHistory"  },
154         { LDAP_ATTR_LOGON_HOURS,        "sambaLogonHours"       },
155         { LDAP_ATTR_LIST_END,           NULL                    }
156 };
157
158 /* attributes used for allocating RIDs */
159
160 ATTRIB_MAP_ENTRY dominfo_attr_list[] = {
161         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
162         { LDAP_ATTR_NEXT_RID,           "sambaNextRid"          },
163         { LDAP_ATTR_NEXT_USERRID,       "sambaNextUserRid"      },
164         { LDAP_ATTR_NEXT_GROUPRID,      "sambaNextGroupRid"     },
165         { LDAP_ATTR_DOM_SID,            LDAP_ATTRIBUTE_SID      },
166         { LDAP_ATTR_ALGORITHMIC_RID_BASE,"sambaAlgorithmicRidBase"},
167         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
168         { LDAP_ATTR_LIST_END,           NULL                    },
169 };
170
171 /* Samba 3.0 group mapping attributes */
172
173 ATTRIB_MAP_ENTRY groupmap_attr_list[] = {
174         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
175         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
176         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
177         { LDAP_ATTR_SID_LIST,           "sambaSIDList"          },
178         { LDAP_ATTR_DESC,               "description"           },
179         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
180         { LDAP_ATTR_CN,                 "cn"                    },
181         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
182         { LDAP_ATTR_LIST_END,           NULL                    }       
183 };
184
185 ATTRIB_MAP_ENTRY groupmap_attr_list_to_delete[] = {
186         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
187         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
188         { LDAP_ATTR_DESC,               "description"           },
189         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
190         { LDAP_ATTR_SID_LIST,           "sambaSIDList"          },
191         { LDAP_ATTR_LIST_END,           NULL                    }       
192 };
193
194 /* idmap_ldap sambaUnixIdPool */
195
196 ATTRIB_MAP_ENTRY idpool_attr_list[] = {
197         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
198         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
199         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
200         { LDAP_ATTR_LIST_END,           NULL                    }       
201 };
202
203 ATTRIB_MAP_ENTRY sidmap_attr_list[] = {
204         { LDAP_ATTR_SID,                LDAP_ATTRIBUTE_SID      },
205         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
206         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
207         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
208         { LDAP_ATTR_LIST_END,           NULL                    }       
209 };
210
211 /**********************************************************************
212  perform a simple table lookup and return the attribute name 
213  **********************************************************************/
214  
215  const char* get_attr_key2string( ATTRIB_MAP_ENTRY table[], int key )
216 {
217         int i = 0;
218         
219         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
220                 if ( table[i].attrib == key )
221                         return table[i].name;
222                 i++;
223         }
224         
225         return NULL;
226 }
227
228
229 /**********************************************************************
230  Return the list of attribute names from a mapping table
231  **********************************************************************/
232
233  char** get_attr_list( ATTRIB_MAP_ENTRY table[] )
234 {
235         char **names;
236         int i = 0;
237         
238         while ( table[i].attrib != LDAP_ATTR_LIST_END )
239                 i++;
240         i++;
241
242         names = SMB_MALLOC_ARRAY( char*, i );
243         if ( !names ) {
244                 DEBUG(0,("get_attr_list: out of memory\n"));
245                 return NULL;
246         }
247
248         i = 0;
249         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
250                 names[i] = SMB_STRDUP( table[i].name );
251                 i++;
252         }
253         names[i] = NULL;
254         
255         return names;
256 }
257
258 /*********************************************************************
259  Cleanup 
260  ********************************************************************/
261
262  void free_attr_list( char **list )
263 {
264         int i = 0;
265
266         if ( !list )
267                 return; 
268
269         while ( list[i] ) {
270                 SAFE_FREE( list[i] );
271                 i+=1;
272         }
273
274         SAFE_FREE( list );
275 }
276
277 /*******************************************************************
278  find the ldap password
279 ******************************************************************/
280 static BOOL fetch_ldap_pw(char **dn, char** pw)
281 {
282         char *key = NULL;
283         size_t size;
284         
285         *dn = smb_xstrdup(lp_ldap_admin_dn());
286         
287         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, *dn) < 0) {
288                 SAFE_FREE(*dn);
289                 DEBUG(0, ("fetch_ldap_pw: asprintf failed!\n"));
290         }
291         
292         *pw=secrets_fetch(key, &size);
293         SAFE_FREE(key);
294
295         if (!size) {
296                 /* Upgrade 2.2 style entry */
297                 char *p;
298                 char* old_style_key = SMB_STRDUP(*dn);
299                 char *data;
300                 fstring old_style_pw;
301                 
302                 if (!old_style_key) {
303                         DEBUG(0, ("fetch_ldap_pw: strdup failed!\n"));
304                         return False;
305                 }
306
307                 for (p=old_style_key; *p; p++)
308                         if (*p == ',') *p = '/';
309         
310                 data=secrets_fetch(old_style_key, &size);
311                 if (!size && size < sizeof(old_style_pw)) {
312                         DEBUG(0,("fetch_ldap_pw: neither ldap secret retrieved!\n"));
313                         SAFE_FREE(old_style_key);
314                         SAFE_FREE(*dn);
315                         return False;
316                 }
317
318                 size = MIN(size, sizeof(fstring)-1);
319                 strncpy(old_style_pw, data, size);
320                 old_style_pw[size] = 0;
321
322                 SAFE_FREE(data);
323
324                 if (!secrets_store_ldap_pw(*dn, old_style_pw)) {
325                         DEBUG(0,("fetch_ldap_pw: ldap secret could not be upgraded!\n"));
326                         SAFE_FREE(old_style_key);
327                         SAFE_FREE(*dn);
328                         return False;                   
329                 }
330                 if (!secrets_delete(old_style_key)) {
331                         DEBUG(0,("fetch_ldap_pw: old ldap secret could not be deleted!\n"));
332                 }
333
334                 SAFE_FREE(old_style_key);
335
336                 *pw = smb_xstrdup(old_style_pw);                
337         }
338         
339         return True;
340 }
341
342 /*******************************************************************
343  Search an attribute and return the first value found.
344 ******************************************************************/
345
346  BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
347                                     const char *attribute, char *value,
348                                     int max_len)
349 {
350         char **values;
351         
352         if ( !attribute )
353                 return False;
354                 
355         value[0] = '\0';
356
357         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
358                 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
359                 
360                 return False;
361         }
362         
363         if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, max_len, False) == (size_t)-1) {
364                 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n", 
365                           attribute, values[0]));
366                 ldap_value_free(values);
367                 return False;
368         }
369         
370         ldap_value_free(values);
371 #ifdef DEBUG_PASSWORDS
372         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
373 #endif  
374         return True;
375 }
376
377  BOOL smbldap_get_single_pstring (LDAP * ldap_struct, LDAPMessage * entry,
378                                   const char *attribute, pstring value)
379 {
380         return smbldap_get_single_attribute(ldap_struct, entry,
381                                             attribute, value, 
382                                             sizeof(pstring));
383 }
384
385 /************************************************************************
386  Routine to manage the LDAPMod structure array
387  manage memory used by the array, by each struct, and values
388  ***********************************************************************/
389
390  void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
391 {
392         LDAPMod **mods;
393         int i;
394         int j;
395
396         mods = *modlist;
397
398         /* sanity checks on the mod values */
399
400         if (attribute == NULL || *attribute == '\0') {
401                 return; 
402         }
403
404 #if 0   /* commented out after discussion with abartlet.  Do not reenable.
405            left here so other so re-add similar code   --jerry */
406         if (value == NULL || *value == '\0')
407                 return;
408 #endif
409
410         if (mods == NULL) {
411                 mods = SMB_MALLOC_P(LDAPMod *);
412                 if (mods == NULL) {
413                         DEBUG(0, ("make_a_mod: out of memory!\n"));
414                         return;
415                 }
416                 mods[0] = NULL;
417         }
418
419         for (i = 0; mods[i] != NULL; ++i) {
420                 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
421                         break;
422         }
423
424         if (mods[i] == NULL) {
425                 mods = SMB_REALLOC_ARRAY (mods, LDAPMod *, i + 2);
426                 if (mods == NULL) {
427                         DEBUG(0, ("make_a_mod: out of memory!\n"));
428                         return;
429                 }
430                 mods[i] = SMB_MALLOC_P(LDAPMod);
431                 if (mods[i] == NULL) {
432                         DEBUG(0, ("make_a_mod: out of memory!\n"));
433                         return;
434                 }
435                 mods[i]->mod_op = modop;
436                 mods[i]->mod_values = NULL;
437                 mods[i]->mod_type = SMB_STRDUP(attribute);
438                 mods[i + 1] = NULL;
439         }
440
441         if (value != NULL) {
442                 char *utf8_value = NULL;
443
444                 j = 0;
445                 if (mods[i]->mod_values != NULL) {
446                         for (; mods[i]->mod_values[j] != NULL; j++);
447                 }
448                 mods[i]->mod_values = SMB_REALLOC_ARRAY(mods[i]->mod_values, char *, j + 2);
449                                                
450                 if (mods[i]->mod_values == NULL) {
451                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
452                         return;
453                 }
454
455                 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
456                         DEBUG (0, ("make_a_mod: String conversion failure!\n"));
457                         return;
458                 }
459
460                 mods[i]->mod_values[j] = utf8_value;
461
462                 mods[i]->mod_values[j + 1] = NULL;
463         }
464         *modlist = mods;
465 }
466
467 /**********************************************************************
468   Set attribute to newval in LDAP, regardless of what value the
469   attribute had in LDAP before.
470 *********************************************************************/
471
472  void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
473                       LDAPMod ***mods,
474                       const char *attribute, const char *newval)
475 {
476         char oldval[2048]; /* current largest allowed value is mungeddial */
477         BOOL existed;
478
479         if (attribute == NULL) {
480                 /* This can actually happen for ldapsam_compat where we for
481                  * example don't have a password history */
482                 return;
483         }
484
485         if (existing != NULL) {
486                 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval, sizeof(oldval));
487         } else {
488                 existed = False;
489                 *oldval = '\0';
490         }
491
492         /* all of our string attributes are case insensitive */
493         
494         if (existed && newval && (StrCaseCmp(oldval, newval) == 0)) {
495                 
496                 /* Believe it or not, but LDAP will deny a delete and
497                    an add at the same time if the values are the
498                    same... */
499                 return;
500         }
501
502         if (existed) {
503                 /* There has been no value before, so don't delete it.
504                  * Here's a possible race: We might end up with
505                  * duplicate attributes */
506                 /* By deleting exactly the value we found in the entry this
507                  * should be race-free in the sense that the LDAP-Server will
508                  * deny the complete operation if somebody changed the
509                  * attribute behind our back. */
510                 /* This will also allow modifying single valued attributes 
511                  * in Novell NDS. In NDS you have to first remove attribute and then
512                  * you could add new value */
513                 
514                 smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, oldval);
515         }
516
517         /* Regardless of the real operation (add or modify)
518            we add the new value here. We rely on deleting
519            the old value, should it exist. */
520
521         if ((newval != NULL) && (strlen(newval) > 0)) {
522                 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
523         }
524 }
525
526 /**********************************************************************
527  Some varients of the LDAP rebind code do not pass in the third 'arg' 
528  pointer to a void*, so we try and work around it by assuming that the 
529  value of the 'LDAP *' pointer is the same as the one we had passed in
530  **********************************************************************/
531
532 struct smbldap_state_lookup {
533         LDAP *ld;
534         struct smbldap_state *smbldap_state;
535         struct smbldap_state_lookup *prev, *next;
536 };
537
538 static struct smbldap_state_lookup *smbldap_state_lookup_list;
539
540 static struct smbldap_state *smbldap_find_state(LDAP *ld) 
541 {
542         struct smbldap_state_lookup *t;
543
544         for (t = smbldap_state_lookup_list; t; t = t->next) {
545                 if (t->ld == ld) {
546                         return t->smbldap_state;
547                 }
548         }
549         return NULL;
550 }
551
552 static void smbldap_delete_state(struct smbldap_state *smbldap_state) 
553 {
554         struct smbldap_state_lookup *t;
555
556         for (t = smbldap_state_lookup_list; t; t = t->next) {
557                 if (t->smbldap_state == smbldap_state) {
558                         DLIST_REMOVE(smbldap_state_lookup_list, t);
559                         SAFE_FREE(t);
560                         return;
561                 }
562         }
563 }
564
565 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state) 
566 {
567         struct smbldap_state *tmp_ldap_state;
568         struct smbldap_state_lookup *t;
569         struct smbldap_state_lookup *tmp;
570         
571         if ((tmp_ldap_state = smbldap_find_state(ld))) {
572                 SMB_ASSERT(tmp_ldap_state == smbldap_state);
573                 return;
574         }
575
576         t = SMB_XMALLOC_P(struct smbldap_state_lookup);
577         ZERO_STRUCTP(t);
578         
579         DLIST_ADD_END(smbldap_state_lookup_list, t, tmp);
580         t->ld = ld;
581         t->smbldap_state = smbldap_state;
582 }
583
584 /*******************************************************************
585  open a connection to the ldap server.
586 ******************************************************************/
587 static int smbldap_open_connection (struct smbldap_state *ldap_state)
588
589 {
590         int rc = LDAP_SUCCESS;
591         int version;
592         BOOL ldap_v3 = False;
593         LDAP **ldap_struct = &ldap_state->ldap_struct;
594
595 #ifdef HAVE_LDAP_INITIALIZE
596         DEBUG(10, ("smbldap_open_connection: %s\n", ldap_state->uri));
597         
598         if ((rc = ldap_initialize(ldap_struct, ldap_state->uri)) != LDAP_SUCCESS) {
599                 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
600                 return rc;
601         }
602 #else 
603
604         /* Parse the string manually */
605
606         {
607                 int port = 0;
608                 fstring protocol;
609                 fstring host;
610                 const char *p = ldap_state->uri; 
611                 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
612                 
613                 /* skip leading "URL:" (if any) */
614                 if ( strnequal( p, "URL:", 4 ) ) {
615                         p += 4;
616                 }
617                 
618                 sscanf(p, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
619                 
620                 if (port == 0) {
621                         if (strequal(protocol, "ldap")) {
622                                 port = LDAP_PORT;
623                         } else if (strequal(protocol, "ldaps")) {
624                                 port = LDAPS_PORT;
625                         } else {
626                                 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
627                         }
628                 }
629                 
630                 if ((*ldap_struct = ldap_init(host, port)) == NULL)     {
631                         DEBUG(0, ("ldap_init failed !\n"));
632                         return LDAP_OPERATIONS_ERROR;
633                 }
634                 
635                 if (strequal(protocol, "ldaps")) {
636 #ifdef LDAP_OPT_X_TLS
637                         int tls = LDAP_OPT_X_TLS_HARD;
638                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
639                         {
640                                 DEBUG(0, ("Failed to setup a TLS session\n"));
641                         }
642                         
643                         DEBUG(3,("LDAPS option set...!\n"));
644 #else
645                         DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
646                         return LDAP_OPERATIONS_ERROR;
647 #endif
648                 }
649         }
650 #endif
651
652         /* Store the LDAP pointer in a lookup list */
653
654         smbldap_store_state(*ldap_struct, ldap_state);
655
656         /* Upgrade to LDAPv3 if possible */
657
658         if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
659         {
660                 if (version != LDAP_VERSION3)
661                 {
662                         version = LDAP_VERSION3;
663                         if (ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS) {
664                                 ldap_v3 = True;
665                         }
666                 } else {
667                         ldap_v3 = True;
668                 }
669         }
670
671         if (lp_ldap_ssl() == LDAP_SSL_START_TLS) {
672 #ifdef LDAP_OPT_X_TLS
673                 if (ldap_v3) {
674                         if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
675                         {
676                                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
677                                          ldap_err2string(rc)));
678                                 return rc;
679                         }
680                         DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
681                 } else {
682                         
683                         DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
684                         return LDAP_OPERATIONS_ERROR;
685                 }
686 #else
687                 DEBUG(0,("smbldap_open_connection: StartTLS not supported by LDAP client libraries!\n"));
688                 return LDAP_OPERATIONS_ERROR;
689 #endif
690         }
691
692         DEBUG(2, ("smbldap_open_connection: connection opened\n"));
693         return rc;
694 }
695
696
697 /*******************************************************************
698  a rebind function for authenticated referrals
699  This version takes a void* that we can shove useful stuff in :-)
700 ******************************************************************/
701 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
702 #else
703 static int rebindproc_with_state  (LDAP * ld, char **whop, char **credp, 
704                                    int *methodp, int freeit, void *arg)
705 {
706         struct smbldap_state *ldap_state = arg;
707         
708         /** @TODO Should we be doing something to check what servers we rebind to?
709             Could we get a referral to a machine that we don't want to give our
710             username and password to? */
711         
712         if (freeit) {
713                 SAFE_FREE(*whop);
714                 memset(*credp, '\0', strlen(*credp));
715                 SAFE_FREE(*credp);
716         } else {
717                 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n", 
718                           ldap_state->bind_dn));
719
720                 *whop = SMB_STRDUP(ldap_state->bind_dn);
721                 if (!*whop) {
722                         return LDAP_NO_MEMORY;
723                 }
724                 *credp = SMB_STRDUP(ldap_state->bind_secret);
725                 if (!*credp) {
726                         SAFE_FREE(*whop);
727                         return LDAP_NO_MEMORY;
728                 }
729                 *methodp = LDAP_AUTH_SIMPLE;
730         }
731
732         GetTimeOfDay(&ldap_state->last_rebind);
733                 
734         return 0;
735 }
736 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
737
738 /*******************************************************************
739  a rebind function for authenticated referrals
740  This version takes a void* that we can shove useful stuff in :-)
741  and actually does the connection.
742 ******************************************************************/
743 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
744 static int rebindproc_connect_with_state (LDAP *ldap_struct, 
745                                           LDAP_CONST char *url, 
746                                           ber_tag_t request,
747                                           ber_int_t msgid, void *arg)
748 {
749         struct smbldap_state *ldap_state = arg;
750         int rc;
751         DEBUG(5,("rebindproc_connect_with_state: Rebinding as \"%s\"\n", 
752                  ldap_state->bind_dn));
753         
754         /** @TODO Should we be doing something to check what servers we rebind to?
755             Could we get a referral to a machine that we don't want to give our
756             username and password to? */
757
758         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
759         
760         GetTimeOfDay(&ldap_state->last_rebind);
761
762         return rc;
763 }
764 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
765
766 /*******************************************************************
767  Add a rebind function for authenticated referrals
768 ******************************************************************/
769 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
770 #else
771 # if LDAP_SET_REBIND_PROC_ARGS == 2
772 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
773                        int *method, int freeit )
774 {
775         struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
776
777         return rebindproc_with_state(ldap_struct, whop, credp,
778                                      method, freeit, ldap_state);
779         
780 }
781 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
782 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
783
784 /*******************************************************************
785  a rebind function for authenticated referrals
786  this also does the connection, but no void*.
787 ******************************************************************/
788 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
789 # if LDAP_SET_REBIND_PROC_ARGS == 2
790 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
791                                ber_int_t msgid)
792 {
793         struct smbldap_state *ldap_state = smbldap_find_state(ld);
794
795         return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid, 
796                                              ldap_state);
797 }
798 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
799 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
800
801 /*******************************************************************
802  connect to the ldap server under system privilege.
803 ******************************************************************/
804 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
805 {
806         int rc;
807         char *ldap_dn;
808         char *ldap_secret;
809
810         /* get the password */
811         if (!fetch_ldap_pw(&ldap_dn, &ldap_secret)) {
812                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
813                 return LDAP_INVALID_CREDENTIALS;
814         }
815
816         ldap_state->bind_dn = ldap_dn;
817         ldap_state->bind_secret = ldap_secret;
818
819         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
820            (OpenLDAP) doesnt' seem to support it */
821            
822         DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
823                   ldap_state->uri, ldap_dn));
824
825 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
826 # if LDAP_SET_REBIND_PROC_ARGS == 2     
827         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect); 
828 # endif
829 # if LDAP_SET_REBIND_PROC_ARGS == 3     
830         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);  
831 # endif
832 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
833 # if LDAP_SET_REBIND_PROC_ARGS == 2     
834         ldap_set_rebind_proc(ldap_struct, &rebindproc); 
835 # endif
836 # if LDAP_SET_REBIND_PROC_ARGS == 3     
837         ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);  
838 # endif
839 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
840
841         rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
842
843         if (rc != LDAP_SUCCESS) {
844                 char *ld_error = NULL;
845                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
846                                 &ld_error);
847                 DEBUG(ldap_state->num_failures ? 2 : 0,
848                       ("failed to bind to server with dn= %s Error: %s\n\t%s\n",
849                                ldap_dn ? ldap_dn : "(unknown)", ldap_err2string(rc),
850                                ld_error ? ld_error : "(unknown)"));
851                 SAFE_FREE(ld_error);
852                 ldap_state->num_failures++;
853                 return rc;
854         }
855
856         ldap_state->num_failures = 0;
857
858         DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
859         return rc;
860 }
861
862 /**********************************************************************
863  Connect to LDAP server (called before every ldap operation)
864 *********************************************************************/
865 static int smbldap_open(struct smbldap_state *ldap_state)
866 {
867         int rc;
868         SMB_ASSERT(ldap_state);
869                 
870 #ifndef NO_LDAP_SECURITY
871         if (geteuid() != 0) {
872                 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
873                 return  LDAP_INSUFFICIENT_ACCESS;
874         }
875 #endif
876
877         if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
878                 struct sockaddr_un addr;
879                 socklen_t len = sizeof(addr);
880                 int sd;
881                 if (ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd) == 0 &&
882                     getpeername(sd, (struct sockaddr *) &addr, &len) < 0) {
883                         /* the other end has died. reopen. */
884                         ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
885                         ldap_state->ldap_struct = NULL;
886                         ldap_state->last_ping = (time_t)0;
887                 } else {
888                         ldap_state->last_ping = time(NULL);
889                 } 
890         }
891
892         if (ldap_state->ldap_struct != NULL) {
893                 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
894                 return LDAP_SUCCESS;
895         }
896
897         if ((rc = smbldap_open_connection(ldap_state))) {
898                 return rc;
899         }
900
901         if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
902                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
903                 ldap_state->ldap_struct = NULL;
904                 return rc;
905         }
906
907
908         ldap_state->last_ping = time(NULL);
909         ldap_state->pid = sys_getpid();
910         DEBUG(4,("The LDAP server is succesfully connected\n"));
911
912         return LDAP_SUCCESS;
913 }
914
915 /**********************************************************************
916 Disconnect from LDAP server 
917 *********************************************************************/
918 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
919 {
920         if (!ldap_state)
921                 return NT_STATUS_INVALID_PARAMETER;
922                 
923         if (ldap_state->ldap_struct != NULL) {
924                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
925                 ldap_state->ldap_struct = NULL;
926         }
927
928         smbldap_delete_state(ldap_state);
929         
930         DEBUG(5,("The connection to the LDAP server was closed\n"));
931         /* maybe free the results here --metze */
932         
933         
934
935         return NT_STATUS_OK;
936 }
937
938 static BOOL got_alarm;
939
940 static void (*old_handler)(int);
941
942 static void gotalarm_sig(int dummy)
943 {
944         got_alarm = True;
945 }
946
947 static int another_ldap_try(struct smbldap_state *ldap_state, int *rc,
948                             int *attempts, time_t endtime)
949 {
950         time_t now = time(NULL);
951         int open_rc = LDAP_SERVER_DOWN;
952
953         if (*rc != LDAP_SERVER_DOWN)
954                 goto no_next;
955
956         now = time(NULL);
957
958         if (now >= endtime) {
959                 smbldap_close(ldap_state);
960                 *rc = LDAP_TIMEOUT;
961                 goto no_next;
962         }
963
964         if (*attempts == 0) {
965                 got_alarm = False;
966                 old_handler = CatchSignal(SIGALRM, gotalarm_sig);
967                 alarm(endtime - now);
968
969                 if (ldap_state->pid != sys_getpid())
970                         smbldap_close(ldap_state);
971         }
972
973         while (1) {
974
975                 if (*attempts != 0)
976                         smb_msleep(1000);
977
978                 *attempts += 1;
979
980                 open_rc = smbldap_open(ldap_state);
981
982                 if (open_rc == LDAP_SUCCESS) {
983                         ldap_state->last_use = now;
984                         return True;
985                 }
986
987                 if (got_alarm) {
988                         *rc = LDAP_TIMEOUT;
989                         break;
990                 }
991
992                 if (open_rc != LDAP_SUCCESS) {
993                         DEBUG(1, ("Connection to LDAP server failed for the "
994                                   "%d try!\n", *attempts));
995                 }
996         }
997
998  no_next:
999         CatchSignal(SIGALRM, old_handler);
1000         alarm(0);
1001         ldap_state->last_use = now;
1002         return False;
1003 }
1004
1005 /*********************************************************************
1006  ********************************************************************/
1007
1008 int smbldap_search(struct smbldap_state *ldap_state, 
1009                    const char *base, int scope, const char *filter, 
1010                    char *attrs[], int attrsonly, 
1011                    LDAPMessage **res)
1012 {
1013         int             rc = LDAP_SERVER_DOWN;
1014         int             attempts = 0;
1015         char           *utf8_filter;
1016         time_t          endtime = time(NULL)+lp_ldap_timeout();
1017
1018         SMB_ASSERT(ldap_state);
1019         
1020         DEBUG(5,("smbldap_search: base => [%s], filter => [%s], scope => [%d]\n",
1021                 base, filter, scope));
1022
1023         if (ldap_state->last_rebind.tv_sec > 0) {
1024                 struct timeval  tval;
1025                 SMB_BIG_INT     tdiff = 0;
1026                 int             sleep_time = 0;
1027
1028                 ZERO_STRUCT(tval);
1029                 GetTimeOfDay(&tval);
1030
1031                 tdiff = usec_time_diff(&tval, &ldap_state->last_rebind);
1032                 tdiff /= 1000; /* Convert to milliseconds. */
1033
1034                 sleep_time = lp_ldap_replication_sleep()-(int)tdiff;
1035                 sleep_time = MIN(sleep_time, MAX_LDAP_REPLICATION_SLEEP_TIME);
1036
1037                 if (sleep_time > 0) {
1038                         /* we wait for the LDAP replication */
1039                         DEBUG(5,("smbldap_search: waiting %d milliseconds for LDAP replication.\n",sleep_time));
1040                         smb_msleep(sleep_time);
1041                         DEBUG(5,("smbldap_search: go on!\n"));
1042                 }
1043                 ZERO_STRUCT(ldap_state->last_rebind);
1044         }
1045
1046         if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
1047                 return LDAP_NO_MEMORY;
1048         }
1049
1050         while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1051                 rc = ldap_search_s(ldap_state->ldap_struct, base, scope, 
1052                                    utf8_filter, attrs, attrsonly, res);
1053         
1054         SAFE_FREE(utf8_filter);
1055         return rc;
1056 }
1057
1058 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1059 {
1060         int             rc = LDAP_SERVER_DOWN;
1061         int             attempts = 0;
1062         char           *utf8_dn;
1063         time_t          endtime = time(NULL)+lp_ldap_timeout();
1064
1065         SMB_ASSERT(ldap_state);
1066
1067         DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1068
1069         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1070                 return LDAP_NO_MEMORY;
1071         }
1072
1073         while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1074                 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1075                 
1076         SAFE_FREE(utf8_dn);
1077         return rc;
1078 }
1079
1080 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1081 {
1082         int             rc = LDAP_SERVER_DOWN;
1083         int             attempts = 0;
1084         char           *utf8_dn;
1085         time_t          endtime = time(NULL)+lp_ldap_timeout();
1086         
1087         SMB_ASSERT(ldap_state);
1088
1089         DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1090
1091         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1092                 return LDAP_NO_MEMORY;
1093         }
1094
1095         while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1096                 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1097         
1098         SAFE_FREE(utf8_dn);
1099         return rc;
1100 }
1101
1102 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1103 {
1104         int             rc = LDAP_SERVER_DOWN;
1105         int             attempts = 0;
1106         char           *utf8_dn;
1107         time_t          endtime = time(NULL)+lp_ldap_timeout();
1108         
1109         SMB_ASSERT(ldap_state);
1110
1111         DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1112
1113         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1114                 return LDAP_NO_MEMORY;
1115         }
1116
1117         while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1118                 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1119         
1120         SAFE_FREE(utf8_dn);
1121         return rc;
1122 }
1123
1124 int smbldap_extended_operation(struct smbldap_state *ldap_state, 
1125                                LDAP_CONST char *reqoid, struct berval *reqdata, 
1126                                LDAPControl **serverctrls, LDAPControl **clientctrls, 
1127                                char **retoidp, struct berval **retdatap)
1128 {
1129         int             rc = LDAP_SERVER_DOWN;
1130         int             attempts = 0;
1131         time_t          endtime = time(NULL)+lp_ldap_timeout();
1132         
1133         if (!ldap_state)
1134                 return (-1);
1135
1136         while (another_ldap_try(ldap_state, &rc, &attempts, endtime))
1137                 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid,
1138                                                reqdata, serverctrls,
1139                                                clientctrls, retoidp, retdatap);
1140         return rc;
1141 }
1142
1143 /*******************************************************************
1144  run the search by name.
1145 ******************************************************************/
1146 int smbldap_search_suffix (struct smbldap_state *ldap_state, const char *filter, 
1147                            char **search_attr, LDAPMessage ** result)
1148 {
1149         int scope = LDAP_SCOPE_SUBTREE;
1150         int rc;
1151
1152         rc = smbldap_search(ldap_state, lp_ldap_suffix(), scope, filter, search_attr, 0, result);
1153
1154         if (rc != LDAP_SUCCESS) {
1155                 char *ld_error = NULL;
1156                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1157                                 &ld_error);
1158                 DEBUG(0,("smbldap_search_suffix: Problem during the LDAP search: %s (%s)\n", 
1159                         ld_error?ld_error:"(unknown)", ldap_err2string (rc)));
1160                 SAFE_FREE(ld_error);
1161         }
1162         
1163         return rc;
1164 }
1165
1166 static void smbldap_idle_fn(void **data, time_t *interval, time_t now)
1167 {
1168         struct smbldap_state *state = (struct smbldap_state *)(*data);
1169
1170         if (state->ldap_struct == NULL) {
1171                 DEBUG(10,("ldap connection not connected...\n"));
1172                 return;
1173         }
1174                 
1175         if ((state->last_use+SMBLDAP_IDLE_TIME) > now) {
1176                 DEBUG(10,("ldap connection not idle...\n"));
1177                 return;
1178         }
1179                 
1180         DEBUG(7,("ldap connection idle...closing connection\n"));
1181         smbldap_close(state);
1182 }
1183
1184 /**********************************************************************
1185  Housekeeping
1186  *********************************************************************/
1187
1188 void smbldap_free_struct(struct smbldap_state **ldap_state) 
1189 {
1190         smbldap_close(*ldap_state);
1191         
1192         if ((*ldap_state)->bind_secret) {
1193                 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1194         }
1195
1196         SAFE_FREE((*ldap_state)->bind_dn);
1197         SAFE_FREE((*ldap_state)->bind_secret);
1198
1199         smb_unregister_idle_event((*ldap_state)->event_id);
1200
1201         *ldap_state = NULL;
1202
1203         /* No need to free any further, as it is talloc()ed */
1204 }
1205
1206
1207 /**********************************************************************
1208  Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1209  *********************************************************************/
1210
1211 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state) 
1212 {
1213         *smbldap_state = TALLOC_ZERO_P(mem_ctx, struct smbldap_state);
1214         if (!*smbldap_state) {
1215                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1216                 return NT_STATUS_NO_MEMORY;
1217         }
1218
1219         if (location) {
1220                 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1221         } else {
1222                 (*smbldap_state)->uri = "ldap://localhost";
1223         }
1224
1225         (*smbldap_state)->event_id =
1226                 smb_register_idle_event(smbldap_idle_fn, (void *)(*smbldap_state),
1227                                         SMBLDAP_IDLE_TIME);
1228
1229         if ((*smbldap_state)->event_id == SMB_EVENT_ID_INVALID) {
1230                 DEBUG(0,("Failed to register LDAP idle event!\n"));
1231                 return NT_STATUS_INVALID_HANDLE;
1232         }
1233
1234         return NT_STATUS_OK;
1235 }
1236
1237 /**********************************************************************
1238  Add the sambaDomain to LDAP, so we don't have to search for this stuff
1239  again.  This is a once-add operation for now.
1240
1241  TODO:  Add other attributes, and allow modification.
1242 *********************************************************************/
1243 static NTSTATUS add_new_domain_info(struct smbldap_state *ldap_state, 
1244                                     const char *domain_name) 
1245 {
1246         fstring sid_string;
1247         fstring algorithmic_rid_base_string;
1248         pstring filter, dn;
1249         LDAPMod **mods = NULL;
1250         int rc;
1251         int ldap_op;
1252         LDAPMessage *result = NULL;
1253         int num_result;
1254         char **attr_list;
1255         uid_t u_low, u_high;
1256         gid_t g_low, g_high;
1257         uint32 rid_low, rid_high;
1258
1259         slprintf (filter, sizeof (filter) - 1, "(&(%s=%s)(objectclass=%s))", 
1260                   get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1261                   domain_name, LDAP_OBJ_DOMINFO);
1262
1263         attr_list = get_attr_list( dominfo_attr_list );
1264         rc = smbldap_search_suffix(ldap_state, filter, attr_list, &result);
1265         free_attr_list( attr_list );
1266
1267         if (rc != LDAP_SUCCESS) {
1268                 return NT_STATUS_UNSUCCESSFUL;
1269         }
1270
1271         num_result = ldap_count_entries(ldap_state->ldap_struct, result);
1272         
1273         if (num_result > 1) {
1274                 DEBUG (0, ("More than domain with that name exists: bailing out!\n"));
1275                 ldap_msgfree(result);
1276                 return NT_STATUS_UNSUCCESSFUL;
1277         }
1278         
1279         /* Check if we need to add an entry */
1280         DEBUG(3,("Adding new domain\n"));
1281         ldap_op = LDAP_MOD_ADD;
1282
1283         pstr_sprintf(dn, "%s=%s,%s", get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN),
1284                 domain_name, lp_ldap_suffix());
1285
1286         /* Free original search */
1287         ldap_msgfree(result);
1288
1289         /* make the changes - the entry *must* not already have samba attributes */
1290         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1291                 domain_name);
1292
1293         /* If we don't have an entry, then ask secrets.tdb for what it thinks.  
1294            It may choose to make it up */
1295
1296         sid_to_string(sid_string, get_global_sam_sid());
1297         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOM_SID), sid_string);
1298
1299         slprintf(algorithmic_rid_base_string, sizeof(algorithmic_rid_base_string) - 1, "%i", algorithmic_rid_base());
1300         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_ALGORITHMIC_RID_BASE), 
1301                         algorithmic_rid_base_string);
1302         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_DOMINFO);
1303         
1304         /* add the sambaNext[User|Group]Rid attributes if the idmap ranges are set.
1305            TODO: fix all the places where the line between idmap and normal operations
1306            needed by smbd gets fuzzy   --jerry 2003-08-11                              */
1307         
1308         if ( lp_idmap_uid(&u_low, &u_high) && lp_idmap_gid(&g_low, &g_high)
1309                 && get_free_rid_range(&rid_low, &rid_high) ) 
1310         {
1311                 fstring rid_str;
1312                 
1313                 fstr_sprintf( rid_str, "%i", rid_high|USER_RID_TYPE );
1314                 DEBUG(10,("setting next available user rid [%s]\n", rid_str));
1315                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1316                         get_attr_key2string(dominfo_attr_list, LDAP_ATTR_NEXT_USERRID), 
1317                         rid_str);
1318                         
1319                 fstr_sprintf( rid_str, "%i", rid_high|GROUP_RID_TYPE );
1320                 DEBUG(10,("setting next available group rid [%s]\n", rid_str));
1321                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1322                         get_attr_key2string(dominfo_attr_list, LDAP_ATTR_NEXT_GROUPRID), 
1323                         rid_str);
1324                 
1325         }
1326
1327
1328         switch(ldap_op)
1329         {
1330         case LDAP_MOD_ADD: 
1331                 rc = smbldap_add(ldap_state, dn, mods);
1332                 break;
1333         case LDAP_MOD_REPLACE: 
1334                 rc = smbldap_modify(ldap_state, dn, mods);
1335                 break;
1336         default:        
1337                 DEBUG(0,("Wrong LDAP operation type: %d!\n", ldap_op));
1338                 return NT_STATUS_INVALID_PARAMETER;
1339         }
1340         
1341         if (rc!=LDAP_SUCCESS) {
1342                 char *ld_error = NULL;
1343                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
1344                 DEBUG(1,("failed to %s domain dn= %s with: %s\n\t%s\n",
1345                        ldap_op == LDAP_MOD_ADD ? "add" : "modify",
1346                        dn, ldap_err2string(rc),
1347                        ld_error?ld_error:"unknown"));
1348                 SAFE_FREE(ld_error);
1349
1350                 ldap_mods_free(mods, True);
1351                 return NT_STATUS_UNSUCCESSFUL;
1352         }
1353
1354         DEBUG(2,("added: domain = %s in the LDAP database\n", domain_name));
1355         ldap_mods_free(mods, True);
1356         return NT_STATUS_OK;
1357 }
1358
1359 /**********************************************************************
1360 Search for the domain info entry
1361 *********************************************************************/
1362 NTSTATUS smbldap_search_domain_info(struct smbldap_state *ldap_state,
1363                                     LDAPMessage ** result, const char *domain_name,
1364                                     BOOL try_add)
1365 {
1366         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1367         pstring filter;
1368         int rc;
1369         char **attr_list;
1370         int count;
1371
1372         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
1373                 LDAP_OBJ_DOMINFO,
1374                 get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1375                 domain_name);
1376
1377         DEBUG(2, ("Searching for:[%s]\n", filter));
1378
1379
1380         attr_list = get_attr_list( dominfo_attr_list );
1381         rc = smbldap_search_suffix(ldap_state, filter, attr_list , result);
1382         free_attr_list( attr_list );
1383
1384         if (rc != LDAP_SUCCESS) {
1385                 DEBUG(2,("Problem during LDAPsearch: %s\n", ldap_err2string (rc)));
1386                 DEBUG(2,("Query was: %s, %s\n", lp_ldap_suffix(), filter));
1387         } else if (ldap_count_entries(ldap_state->ldap_struct, *result) < 1) {
1388                 DEBUG(3, ("Got no domain info entries for domain\n"));
1389                 ldap_msgfree(*result);
1390                 *result = NULL;
1391                 if (try_add && NT_STATUS_IS_OK(ret = add_new_domain_info(ldap_state, domain_name))) {
1392                         return smbldap_search_domain_info(ldap_state, result, domain_name, False);
1393                 } 
1394                 else {
1395                         DEBUG(0, ("Adding domain info for %s failed with %s\n", 
1396                                 domain_name, nt_errstr(ret)));
1397                         return ret;
1398                 }
1399         } else if ((count = ldap_count_entries(ldap_state->ldap_struct, *result)) > 1) {
1400                 DEBUG(0, ("Got too many (%d) domain info entries for domain %s\n",
1401                           count, domain_name));
1402                 ldap_msgfree(*result);
1403                 *result = NULL;
1404                 return ret;
1405         } else {
1406                 return NT_STATUS_OK;
1407         }
1408         
1409         return ret;
1410 }
1411
1412 /*******************************************************************
1413  Return a copy of the DN for a LDAPMessage. Convert from utf8 to CH_UNIX.
1414 ********************************************************************/
1415
1416 char *smbldap_get_dn(LDAP *ld, LDAPMessage *entry)
1417 {
1418         char *utf8_dn, *unix_dn;
1419
1420         utf8_dn = ldap_get_dn(ld, entry);
1421         if (!utf8_dn) {
1422                 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1423                 return NULL;
1424         }
1425         if (pull_utf8_allocate(&unix_dn, utf8_dn) == (size_t)-1) {
1426                 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 [%s]\n", utf8_dn));
1427                 return NULL;
1428         }
1429         ldap_memfree(utf8_dn);
1430         return unix_dn;
1431 }
1432