r13316: Let the carnage begin....
[tprouty/samba.git] / source / lib / smbldap.c
1 /* 
2    Unix SMB/CIFS implementation.
3    LDAP protocol helper functions for SAMBA
4    Copyright (C) Jean François Micouleau       1998
5    Copyright (C) Gerald Carter                  2001-2003
6    Copyright (C) Shahms King                    2001
7    Copyright (C) Andrew Bartlett                2002-2003
8    Copyright (C) Stefan (metze) Metzmacher      2002-2003
9     
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  const char** get_attr_list( TALLOC_CTX *mem_ctx, ATTRIB_MAP_ENTRY table[] )
234 {
235         const char **names;
236         int i = 0;
237         
238         while ( table[i].attrib != LDAP_ATTR_LIST_END )
239                 i++;
240         i++;
241
242         names = TALLOC_ARRAY( mem_ctx, const 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] = talloc_strdup( names, table[i].name );
251                 i++;
252         }
253         names[i] = NULL;
254         
255         return names;
256 }
257
258 /*******************************************************************
259  Search an attribute and return the first value found.
260 ******************************************************************/
261
262  BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
263                                     const char *attribute, char *value,
264                                     int max_len)
265 {
266         char **values;
267         
268         if ( !attribute )
269                 return False;
270                 
271         value[0] = '\0';
272
273         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
274                 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
275                 
276                 return False;
277         }
278         
279         if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, max_len, False) == (size_t)-1) {
280                 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n", 
281                           attribute, values[0]));
282                 ldap_value_free(values);
283                 return False;
284         }
285         
286         ldap_value_free(values);
287 #ifdef DEBUG_PASSWORDS
288         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
289 #endif  
290         return True;
291 }
292
293  BOOL smbldap_get_single_pstring (LDAP * ldap_struct, LDAPMessage * entry,
294                                   const char *attribute, pstring value)
295 {
296         return smbldap_get_single_attribute(ldap_struct, entry,
297                                             attribute, value, 
298                                             sizeof(pstring));
299 }
300
301  char * smbldap_talloc_single_attribute(LDAP *ldap_struct, LDAPMessage *entry,
302                                         const char *attribute,
303                                         TALLOC_CTX *mem_ctx)
304 {
305         char **values;
306         char *result;
307
308         if (attribute == NULL) {
309                 return NULL;
310         }
311
312         values = ldap_get_values(ldap_struct, entry, attribute);
313
314         if (values == NULL) {
315                 DEBUG(10, ("attribute %s does not exist\n", attribute));
316                 return NULL;
317         }
318
319         if (ldap_count_values(values) != 1) {
320                 DEBUG(10, ("attribute %s has %d values, expected only one\n",
321                            attribute, ldap_count_values(values)));
322                 ldap_value_free(values);
323                 return NULL;
324         }
325
326         if (pull_utf8_talloc(mem_ctx, &result, values[0]) < 0) {
327                 DEBUG(10, ("pull_utf8_talloc failed\n"));
328                 ldap_value_free(values);
329                 return NULL;
330         }
331
332         ldap_value_free(values);
333
334 #ifdef DEBUG_PASSWORDS
335         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n",
336                      attribute, result));
337 #endif  
338         return result;
339 }
340
341  static int ldapmsg_destructor(void *p) {
342         LDAPMessage **result = talloc_get_type_abort(p, LDAPMessage *);
343         ldap_msgfree(*result);
344         return 0;
345 }
346
347  void talloc_autofree_ldapmsg(TALLOC_CTX *mem_ctx, LDAPMessage *result)
348 {
349         LDAPMessage **handle;
350
351         if (result == NULL) {
352                 return;
353         }
354
355         handle = TALLOC_P(mem_ctx, LDAPMessage *);
356         SMB_ASSERT(handle != NULL);
357
358         *handle = result;
359         talloc_set_destructor(handle, ldapmsg_destructor);
360 }
361
362  static int ldapmod_destructor(void *p) {
363         LDAPMod ***result = talloc_get_type_abort(p, LDAPMod **);
364         ldap_mods_free(*result, True);
365         return 0;
366 }
367
368  void talloc_autofree_ldapmod(TALLOC_CTX *mem_ctx, LDAPMod **mod)
369 {
370         LDAPMod ***handle;
371
372         if (mod == NULL) {
373                 return;
374         }
375
376         handle = TALLOC_P(mem_ctx, LDAPMod **);
377         SMB_ASSERT(handle != NULL);
378
379         *handle = mod;
380         talloc_set_destructor(handle, ldapmod_destructor);
381 }
382
383 /************************************************************************
384  Routine to manage the LDAPMod structure array
385  manage memory used by the array, by each struct, and values
386  ***********************************************************************/
387
388  void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
389 {
390         LDAPMod **mods;
391         int i;
392         int j;
393
394         mods = *modlist;
395
396         /* sanity checks on the mod values */
397
398         if (attribute == NULL || *attribute == '\0') {
399                 return; 
400         }
401
402 #if 0   /* commented out after discussion with abartlet.  Do not reenable.
403            left here so other do not re-add similar code   --jerry */
404         if (value == NULL || *value == '\0')
405                 return;
406 #endif
407
408         if (mods == NULL) {
409                 mods = SMB_MALLOC_P(LDAPMod *);
410                 if (mods == NULL) {
411                         DEBUG(0, ("make_a_mod: out of memory!\n"));
412                         return;
413                 }
414                 mods[0] = NULL;
415         }
416
417         for (i = 0; mods[i] != NULL; ++i) {
418                 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
419                         break;
420         }
421
422         if (mods[i] == NULL) {
423                 mods = SMB_REALLOC_ARRAY (mods, LDAPMod *, i + 2);
424                 if (mods == NULL) {
425                         DEBUG(0, ("make_a_mod: out of memory!\n"));
426                         return;
427                 }
428                 mods[i] = SMB_MALLOC_P(LDAPMod);
429                 if (mods[i] == NULL) {
430                         DEBUG(0, ("make_a_mod: out of memory!\n"));
431                         return;
432                 }
433                 mods[i]->mod_op = modop;
434                 mods[i]->mod_values = NULL;
435                 mods[i]->mod_type = SMB_STRDUP(attribute);
436                 mods[i + 1] = NULL;
437         }
438
439         if (value != NULL) {
440                 char *utf8_value = NULL;
441
442                 j = 0;
443                 if (mods[i]->mod_values != NULL) {
444                         for (; mods[i]->mod_values[j] != NULL; j++);
445                 }
446                 mods[i]->mod_values = SMB_REALLOC_ARRAY(mods[i]->mod_values, char *, j + 2);
447                                                
448                 if (mods[i]->mod_values == NULL) {
449                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
450                         return;
451                 }
452
453                 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
454                         DEBUG (0, ("make_a_mod: String conversion failure!\n"));
455                         return;
456                 }
457
458                 mods[i]->mod_values[j] = utf8_value;
459
460                 mods[i]->mod_values[j + 1] = NULL;
461         }
462         *modlist = mods;
463 }
464
465 /**********************************************************************
466   Set attribute to newval in LDAP, regardless of what value the
467   attribute had in LDAP before.
468 *********************************************************************/
469
470  void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
471                       LDAPMod ***mods,
472                       const char *attribute, const char *newval)
473 {
474         char oldval[2048]; /* current largest allowed value is mungeddial */
475         BOOL existed;
476
477         if (attribute == NULL) {
478                 /* This can actually happen for ldapsam_compat where we for
479                  * example don't have a password history */
480                 return;
481         }
482
483         if (existing != NULL) {
484                 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval, sizeof(oldval));
485         } else {
486                 existed = False;
487                 *oldval = '\0';
488         }
489
490         /* all of our string attributes are case insensitive */
491         
492         if (existed && newval && (StrCaseCmp(oldval, newval) == 0)) {
493                 
494                 /* Believe it or not, but LDAP will deny a delete and
495                    an add at the same time if the values are the
496                    same... */
497                 DEBUG(10,("smbldap_make_mod: attribute |%s| not changed.\n", attribute));
498                 return;
499         }
500
501         if (existed) {
502                 /* There has been no value before, so don't delete it.
503                  * Here's a possible race: We might end up with
504                  * duplicate attributes */
505                 /* By deleting exactly the value we found in the entry this
506                  * should be race-free in the sense that the LDAP-Server will
507                  * deny the complete operation if somebody changed the
508                  * attribute behind our back. */
509                 /* This will also allow modifying single valued attributes 
510                  * in Novell NDS. In NDS you have to first remove attribute and then
511                  * you could add new value */
512                 
513                 DEBUG(10,("smbldap_make_mod: deleting attribute |%s| values |%s|\n", attribute, oldval));
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                 DEBUG(10,("smbldap_make_mod: adding attribute |%s| value |%s|\n", attribute, newval));
523                 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
524         }
525 }
526
527 /**********************************************************************
528  Some varients of the LDAP rebind code do not pass in the third 'arg' 
529  pointer to a void*, so we try and work around it by assuming that the 
530  value of the 'LDAP *' pointer is the same as the one we had passed in
531  **********************************************************************/
532
533 struct smbldap_state_lookup {
534         LDAP *ld;
535         struct smbldap_state *smbldap_state;
536         struct smbldap_state_lookup *prev, *next;
537 };
538
539 static struct smbldap_state_lookup *smbldap_state_lookup_list;
540
541 static struct smbldap_state *smbldap_find_state(LDAP *ld) 
542 {
543         struct smbldap_state_lookup *t;
544
545         for (t = smbldap_state_lookup_list; t; t = t->next) {
546                 if (t->ld == ld) {
547                         return t->smbldap_state;
548                 }
549         }
550         return NULL;
551 }
552
553 static void smbldap_delete_state(struct smbldap_state *smbldap_state) 
554 {
555         struct smbldap_state_lookup *t;
556
557         for (t = smbldap_state_lookup_list; t; t = t->next) {
558                 if (t->smbldap_state == smbldap_state) {
559                         DLIST_REMOVE(smbldap_state_lookup_list, t);
560                         SAFE_FREE(t);
561                         return;
562                 }
563         }
564 }
565
566 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state) 
567 {
568         struct smbldap_state *tmp_ldap_state;
569         struct smbldap_state_lookup *t;
570         struct smbldap_state_lookup *tmp;
571         
572         if ((tmp_ldap_state = smbldap_find_state(ld))) {
573                 SMB_ASSERT(tmp_ldap_state == smbldap_state);
574                 return;
575         }
576
577         t = SMB_XMALLOC_P(struct smbldap_state_lookup);
578         ZERO_STRUCTP(t);
579         
580         DLIST_ADD_END(smbldap_state_lookup_list, t, tmp);
581         t->ld = ld;
582         t->smbldap_state = smbldap_state;
583 }
584
585 /********************************************************************
586  start TLS on an existing LDAP connection
587 *******************************************************************/
588
589 int smb_ldap_start_tls(LDAP *ldap_struct, int version)
590
591         int rc;
592         
593         if (lp_ldap_ssl() != LDAP_SSL_START_TLS) {
594                 return LDAP_SUCCESS;
595         }
596         
597 #ifdef LDAP_OPT_X_TLS
598         if (version != LDAP_VERSION3) {
599                 DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
600                 return LDAP_OPERATIONS_ERROR;
601         }
602
603         if ((rc = ldap_start_tls_s (ldap_struct, NULL, NULL)) != LDAP_SUCCESS)  {
604                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
605                          ldap_err2string(rc)));
606                 return rc;
607         }
608
609         DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
610         return LDAP_SUCCESS;
611 #else
612         DEBUG(0,("StartTLS not supported by LDAP client libraries!\n"));
613         return LDAP_OPERATIONS_ERROR;
614 #endif
615 }
616
617 /********************************************************************
618  setup a connection to the LDAP server based on a uri
619 *******************************************************************/
620
621 int smb_ldap_setup_conn(LDAP **ldap_struct, const char *uri)
622 {
623         int rc;
624
625         DEBUG(10, ("smb_ldap_setup_connection: %s\n", uri));
626         
627 #ifdef HAVE_LDAP_INITIALIZE
628         
629         rc = ldap_initialize(ldap_struct, uri);
630         if (rc) {
631                 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
632         }
633
634         return rc;
635 #else 
636
637         /* Parse the string manually */
638
639         {
640                 int port = 0;
641                 fstring protocol;
642                 fstring host;
643                 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
644
645
646                 /* skip leading "URL:" (if any) */
647                 if ( strnequal( uri, "URL:", 4 ) ) {
648                         uri += 4;
649                 }
650                 
651                 sscanf(uri, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
652                 
653                 if (port == 0) {
654                         if (strequal(protocol, "ldap")) {
655                                 port = LDAP_PORT;
656                         } else if (strequal(protocol, "ldaps")) {
657                                 port = LDAPS_PORT;
658                         } else {
659                                 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
660                         }
661                 }
662                 
663                 if ((*ldap_struct = ldap_init(host, port)) == NULL)     {
664                         DEBUG(0, ("ldap_init failed !\n"));
665                         return LDAP_OPERATIONS_ERROR;
666                 }
667                 
668                 if (strequal(protocol, "ldaps")) {
669 #ifdef LDAP_OPT_X_TLS
670                         int tls = LDAP_OPT_X_TLS_HARD;
671                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
672                         {
673                                 DEBUG(0, ("Failed to setup a TLS session\n"));
674                         }
675                         
676                         DEBUG(3,("LDAPS option set...!\n"));
677 #else
678                         DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
679                         return LDAP_OPERATIONS_ERROR;
680 #endif /* LDAP_OPT_X_TLS */
681                 }
682
683         }
684 #endif /* HAVE_LDAP_INITIALIZE */
685         return LDAP_SUCCESS;
686 }
687
688 /********************************************************************
689  try to upgrade to Version 3 LDAP if not already, in either case return current
690  version 
691  *******************************************************************/
692
693 int smb_ldap_upgrade_conn(LDAP *ldap_struct, int *new_version) 
694 {
695         int version;
696         int rc;
697         
698         /* assume the worst */
699         *new_version = LDAP_VERSION2;
700
701         rc = ldap_get_option(ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
702         if (rc) {
703                 return rc;
704         }
705
706         if (version == LDAP_VERSION3) {
707                 *new_version = LDAP_VERSION3;
708                 return LDAP_SUCCESS;
709         }
710
711         /* try upgrade */
712         version = LDAP_VERSION3;
713         rc = ldap_set_option (ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
714         if (rc) {
715                 return rc;
716         }
717                 
718         *new_version = LDAP_VERSION3;
719         return LDAP_SUCCESS;
720 }
721
722 /*******************************************************************
723  open a connection to the ldap server (just until the bind)
724  ******************************************************************/
725
726 int smb_ldap_setup_full_conn(LDAP **ldap_struct, const char *uri)
727 {
728         int rc, version;
729
730         rc = smb_ldap_setup_conn(ldap_struct, uri);
731         if (rc) {
732                 return rc;
733         }
734
735         rc = smb_ldap_upgrade_conn(*ldap_struct, &version);
736         if (rc) {
737                 return rc;
738         }
739
740         rc = smb_ldap_start_tls(*ldap_struct, version);
741         if (rc) {
742                 return rc;
743         }
744
745         return LDAP_SUCCESS;
746 }
747
748 /*******************************************************************
749  open a connection to the ldap server.
750 ******************************************************************/
751 static int smbldap_open_connection (struct smbldap_state *ldap_state)
752
753 {
754         int rc = LDAP_SUCCESS;
755         int version;
756         LDAP **ldap_struct = &ldap_state->ldap_struct;
757
758         rc = smb_ldap_setup_conn(ldap_struct, ldap_state->uri);
759         if (rc) {
760                 return rc;
761         }
762
763         /* Store the LDAP pointer in a lookup list */
764
765         smbldap_store_state(*ldap_struct, ldap_state);
766
767         /* Upgrade to LDAPv3 if possible */
768
769         rc = smb_ldap_upgrade_conn(*ldap_struct, &version);
770         if (rc) {
771                 return rc;
772         }
773
774         /* Start TLS if required */
775
776         rc = smb_ldap_start_tls(*ldap_struct, version);
777         if (rc) {
778                 return rc;
779         }
780         
781         DEBUG(2, ("smbldap_open_connection: connection opened\n"));
782         return rc;
783 }
784
785 /*******************************************************************
786  a rebind function for authenticated referrals
787  This version takes a void* that we can shove useful stuff in :-)
788 ******************************************************************/
789 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
790 #else
791 static int rebindproc_with_state  (LDAP * ld, char **whop, char **credp, 
792                                    int *methodp, int freeit, void *arg)
793 {
794         struct smbldap_state *ldap_state = arg;
795         
796         /** @TODO Should we be doing something to check what servers we rebind to?
797             Could we get a referral to a machine that we don't want to give our
798             username and password to? */
799         
800         if (freeit) {
801                 SAFE_FREE(*whop);
802                 memset(*credp, '\0', strlen(*credp));
803                 SAFE_FREE(*credp);
804         } else {
805                 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n", 
806                           ldap_state->bind_dn));
807
808                 *whop = SMB_STRDUP(ldap_state->bind_dn);
809                 if (!*whop) {
810                         return LDAP_NO_MEMORY;
811                 }
812                 *credp = SMB_STRDUP(ldap_state->bind_secret);
813                 if (!*credp) {
814                         SAFE_FREE(*whop);
815                         return LDAP_NO_MEMORY;
816                 }
817                 *methodp = LDAP_AUTH_SIMPLE;
818         }
819
820         GetTimeOfDay(&ldap_state->last_rebind);
821                 
822         return 0;
823 }
824 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
825
826 /*******************************************************************
827  a rebind function for authenticated referrals
828  This version takes a void* that we can shove useful stuff in :-)
829  and actually does the connection.
830 ******************************************************************/
831 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
832 static int rebindproc_connect_with_state (LDAP *ldap_struct, 
833                                           LDAP_CONST char *url, 
834                                           ber_tag_t request,
835                                           ber_int_t msgid, void *arg)
836 {
837         struct smbldap_state *ldap_state = arg;
838         int rc;
839         int version;
840
841         DEBUG(5,("rebindproc_connect_with_state: Rebinding to %s as \"%s\"\n", 
842                  url, ldap_state->bind_dn));
843
844         /* call START_TLS again (ldaps:// is handled by the OpenLDAP library
845          * itself) before rebinding to another LDAP server to avoid to expose
846          * our credentials. At least *try* to secure the connection - Guenther */
847
848         smb_ldap_upgrade_conn(ldap_struct, &version);
849         smb_ldap_start_tls(ldap_struct, version);
850
851         /** @TODO Should we be doing something to check what servers we rebind to?
852             Could we get a referral to a machine that we don't want to give our
853             username and password to? */
854
855         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
856         
857         GetTimeOfDay(&ldap_state->last_rebind);
858
859         return rc;
860 }
861 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
862
863 /*******************************************************************
864  Add a rebind function for authenticated referrals
865 ******************************************************************/
866 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
867 #else
868 # if LDAP_SET_REBIND_PROC_ARGS == 2
869 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
870                        int *method, int freeit )
871 {
872         struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
873
874         return rebindproc_with_state(ldap_struct, whop, credp,
875                                      method, freeit, ldap_state);
876         
877 }
878 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
879 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
880
881 /*******************************************************************
882  a rebind function for authenticated referrals
883  this also does the connection, but no void*.
884 ******************************************************************/
885 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
886 # if LDAP_SET_REBIND_PROC_ARGS == 2
887 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
888                                ber_int_t msgid)
889 {
890         struct smbldap_state *ldap_state = smbldap_find_state(ld);
891
892         return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid, 
893                                              ldap_state);
894 }
895 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
896 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
897
898 /*******************************************************************
899  connect to the ldap server under system privilege.
900 ******************************************************************/
901 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
902 {
903         int rc;
904         char *ldap_dn;
905         char *ldap_secret;
906         int version;
907
908         /* get the password */
909         if (!fetch_ldap_pw(&ldap_dn, &ldap_secret)) {
910                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
911                 return LDAP_INVALID_CREDENTIALS;
912         }
913
914         ldap_state->bind_dn = ldap_dn;
915         ldap_state->bind_secret = ldap_secret;
916
917         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
918            (OpenLDAP) doesnt' seem to support it */
919            
920         DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
921                   ldap_state->uri, ldap_dn));
922
923 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
924 # if LDAP_SET_REBIND_PROC_ARGS == 2     
925         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect); 
926 # endif
927 # if LDAP_SET_REBIND_PROC_ARGS == 3     
928         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);  
929 # endif
930 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
931 # if LDAP_SET_REBIND_PROC_ARGS == 2     
932         ldap_set_rebind_proc(ldap_struct, &rebindproc); 
933 # endif
934 # if LDAP_SET_REBIND_PROC_ARGS == 3     
935         ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);  
936 # endif
937 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
938
939         rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
940
941         if (rc != LDAP_SUCCESS) {
942                 char *ld_error = NULL;
943                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
944                                 &ld_error);
945                 DEBUG(ldap_state->num_failures ? 2 : 0,
946                       ("failed to bind to server %s with dn=\"%s\" Error: %s\n\t%s\n",
947                                ldap_state->uri,
948                                ldap_dn ? ldap_dn : "(unknown)", ldap_err2string(rc),
949                                ld_error ? ld_error : "(unknown)"));
950                 SAFE_FREE(ld_error);
951                 ldap_state->num_failures++;
952                 return rc;
953         }
954
955         ldap_state->num_failures = 0;
956         ldap_state->paged_results = False;
957
958         ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
959
960         if (smbldap_has_control(ldap_state, ADS_PAGE_CTL_OID) && version == 3) {
961                 ldap_state->paged_results = True;
962         }
963
964         DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
965         DEBUGADD(10, ("ldap_connect_system: LDAP server %s support paged results\n", 
966                 ldap_state->paged_results ? "does" : "does not"));
967         return rc;
968 }
969
970 /**********************************************************************
971  Connect to LDAP server (called before every ldap operation)
972 *********************************************************************/
973 static int smbldap_open(struct smbldap_state *ldap_state)
974 {
975         int rc, opt_rc;
976         BOOL reopen = False;
977         SMB_ASSERT(ldap_state);
978                 
979 #ifndef NO_LDAP_SECURITY
980         if (geteuid() != 0) {
981                 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
982                 return  LDAP_INSUFFICIENT_ACCESS;
983         }
984 #endif
985
986         if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
987
988                 struct sockaddr_un addr;
989                 socklen_t len = sizeof(addr);
990                 int sd;
991
992                 opt_rc = ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd);
993                 if (opt_rc == 0 && (getpeername(sd, (struct sockaddr *) &addr, &len)) < 0 )
994                         reopen = True;
995
996 #ifdef HAVE_UNIXSOCKET
997                 if (opt_rc == 0 && addr.sun_family == AF_UNIX)
998                         reopen = True;
999 #endif
1000                 if (reopen) {
1001                         /* the other end has died. reopen. */
1002                         ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
1003                         ldap_state->ldap_struct = NULL;
1004                         ldap_state->last_ping = (time_t)0;
1005                 } else {
1006                         ldap_state->last_ping = time(NULL);
1007                 } 
1008         }
1009
1010         if (ldap_state->ldap_struct != NULL) {
1011                 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
1012                 return LDAP_SUCCESS;
1013         }
1014
1015         if ((rc = smbldap_open_connection(ldap_state))) {
1016                 return rc;
1017         }
1018
1019         if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
1020                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
1021                 ldap_state->ldap_struct = NULL;
1022                 return rc;
1023         }
1024
1025
1026         ldap_state->last_ping = time(NULL);
1027         ldap_state->pid = sys_getpid();
1028         DEBUG(4,("The LDAP server is succesfully connected\n"));
1029
1030         return LDAP_SUCCESS;
1031 }
1032
1033 /**********************************************************************
1034 Disconnect from LDAP server 
1035 *********************************************************************/
1036 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
1037 {
1038         if (!ldap_state)
1039                 return NT_STATUS_INVALID_PARAMETER;
1040                 
1041         if (ldap_state->ldap_struct != NULL) {
1042                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
1043                 ldap_state->ldap_struct = NULL;
1044         }
1045
1046         smbldap_delete_state(ldap_state);
1047         
1048         DEBUG(5,("The connection to the LDAP server was closed\n"));
1049         /* maybe free the results here --metze */
1050         
1051         
1052
1053         return NT_STATUS_OK;
1054 }
1055
1056 static BOOL got_alarm;
1057
1058 static void (*old_handler)(int);
1059
1060 static void gotalarm_sig(int dummy)
1061 {
1062         got_alarm = True;
1063 }
1064
1065 static int another_ldap_try(struct smbldap_state *ldap_state, int *rc,
1066                             int *attempts, time_t endtime)
1067 {
1068         time_t now = time(NULL);
1069         int open_rc = LDAP_SERVER_DOWN;
1070
1071         if (*rc != LDAP_SERVER_DOWN)
1072                 goto no_next;
1073
1074         if (now >= endtime) {
1075                 smbldap_close(ldap_state);
1076                 *rc = LDAP_TIMEOUT;
1077                 goto no_next;
1078         }
1079
1080         if (*attempts == 0) {
1081                 got_alarm = False;
1082                 old_handler = CatchSignal(SIGALRM, gotalarm_sig);
1083                 alarm(endtime - now);
1084
1085                 if (ldap_state->pid != sys_getpid())
1086                         smbldap_close(ldap_state);
1087         }
1088
1089         while (1) {
1090
1091                 if (*attempts != 0)
1092                         smb_msleep(1000);
1093
1094                 *attempts += 1;
1095
1096                 open_rc = smbldap_open(ldap_state);
1097
1098                 if (open_rc == LDAP_SUCCESS) {
1099                         ldap_state->last_use = now;
1100                         return True;
1101                 }
1102
1103                 if (open_rc == LDAP_INSUFFICIENT_ACCESS) {
1104                         /* The fact that we are non-root or any other
1105                          * access-denied condition will not change in the next
1106                          * round of trying */
1107                         *rc = open_rc;
1108                         break;
1109                 }
1110
1111                 if (got_alarm) {
1112                         *rc = LDAP_TIMEOUT;
1113                         break;
1114                 }
1115
1116                 if (open_rc != LDAP_SUCCESS) {
1117                         DEBUG(1, ("Connection to LDAP server failed for the "
1118                                   "%d try!\n", *attempts));
1119                 }
1120         }
1121
1122  no_next:
1123         CatchSignal(SIGALRM, old_handler);
1124         alarm(0);
1125         ldap_state->last_use = now;
1126         return False;
1127 }
1128
1129 /*********************************************************************
1130  ********************************************************************/
1131
1132 static int smbldap_search_ext(struct smbldap_state *ldap_state,
1133                               const char *base, int scope, const char *filter, 
1134                               const char *attrs[], int attrsonly,
1135                               LDAPControl **sctrls, LDAPControl **cctrls, 
1136                               int sizelimit, LDAPMessage **res)
1137 {
1138         int             rc = LDAP_SERVER_DOWN;
1139         int             attempts = 0;
1140         char           *utf8_filter;
1141         time_t          endtime = time(NULL)+lp_ldap_timeout();
1142         struct          timeval timeout;
1143
1144         SMB_ASSERT(ldap_state);
1145         
1146         DEBUG(5,("smbldap_search_ext: base => [%s], filter => [%s], "
1147                  "scope => [%d]\n", base, filter, scope));
1148
1149         if (ldap_state->last_rebind.tv_sec > 0) {
1150                 struct timeval  tval;
1151                 SMB_BIG_INT     tdiff = 0;
1152                 int             sleep_time = 0;
1153
1154                 ZERO_STRUCT(tval);
1155                 GetTimeOfDay(&tval);
1156
1157                 tdiff = usec_time_diff(&tval, &ldap_state->last_rebind);
1158                 tdiff /= 1000; /* Convert to milliseconds. */
1159
1160                 sleep_time = lp_ldap_replication_sleep()-(int)tdiff;
1161                 sleep_time = MIN(sleep_time, MAX_LDAP_REPLICATION_SLEEP_TIME);
1162
1163                 if (sleep_time > 0) {
1164                         /* we wait for the LDAP replication */
1165                         DEBUG(5,("smbldap_search_ext: waiting %d milliseconds "
1166                                  "for LDAP replication.\n",sleep_time));
1167                         smb_msleep(sleep_time);
1168                         DEBUG(5,("smbldap_search_ext: go on!\n"));
1169                 }
1170                 ZERO_STRUCT(ldap_state->last_rebind);
1171         }
1172
1173         if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
1174                 return LDAP_NO_MEMORY;
1175         }
1176
1177         /* Setup timeout for the ldap_search_ext_s call - local and remote. */
1178         timeout.tv_sec = lp_ldap_timeout();
1179         timeout.tv_usec = 0;
1180
1181         /* Setup alarm timeout.... Do we need both of these ? JRA.
1182          * Yes, I think we do need both of these. The server timeout only
1183          * covers the case where the server's operation takes too long. It
1184          * does not cover the case where the request hangs on its way to the
1185          * server. The server side timeout is not strictly necessary, it's
1186          * just a bit more kind to the server. VL. */
1187
1188         got_alarm = 0;
1189         CatchSignal(SIGALRM, SIGNAL_CAST gotalarm_sig);
1190         alarm(lp_ldap_timeout());
1191         /* End setup timeout. */
1192
1193         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1194                 rc = ldap_search_ext_s(ldap_state->ldap_struct, base, scope, 
1195                                        utf8_filter,
1196                                        CONST_DISCARD(char **, attrs),
1197                                        attrsonly, sctrls, cctrls, &timeout,
1198                                        sizelimit, res);
1199                 if (rc != LDAP_SUCCESS) {
1200                         char *ld_error = NULL;
1201                         ldap_get_option(ldap_state->ldap_struct,
1202                                         LDAP_OPT_ERROR_STRING, &ld_error);
1203                         DEBUG(10,("Failed search for base: %s, error: %s "
1204                                   "(%s)\n", base, ldap_err2string(rc),
1205                                   ld_error ? ld_error : "unknown"));
1206                         SAFE_FREE(ld_error);
1207                 }
1208         }
1209
1210         SAFE_FREE(utf8_filter);
1211
1212         /* Teardown timeout. */
1213         CatchSignal(SIGALRM, SIGNAL_CAST SIG_IGN);
1214         alarm(0);
1215
1216         if (got_alarm != 0)
1217                 return LDAP_TIMELIMIT_EXCEEDED;
1218
1219         return rc;
1220 }
1221
1222 int smbldap_search(struct smbldap_state *ldap_state, 
1223                    const char *base, int scope, const char *filter, 
1224                    const char *attrs[], int attrsonly, 
1225                    LDAPMessage **res)
1226 {
1227         return smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1228                                   attrsonly, NULL, NULL, LDAP_NO_LIMIT, res);
1229 }
1230
1231 int smbldap_search_paged(struct smbldap_state *ldap_state, 
1232                          const char *base, int scope, const char *filter, 
1233                          const char **attrs, int attrsonly, int pagesize,
1234                          LDAPMessage **res, void **cookie)
1235 {
1236         LDAPControl     pr;
1237         LDAPControl     **rcontrols;
1238         LDAPControl     *controls[2] = { NULL, NULL};
1239         BerElement      *cookie_be = NULL;
1240         struct berval   *cookie_bv = NULL;
1241         int             tmp = 0, i, rc;
1242         BOOL            critical = True;
1243
1244         *res = NULL;
1245
1246         DEBUG(3,("smbldap_search_paged: base => [%s], filter => [%s],"
1247                  "scope => [%d], pagesize => [%d]\n",
1248                  base, filter, scope, pagesize));
1249
1250         cookie_be = ber_alloc_t(LBER_USE_DER);
1251         if (cookie_be == NULL) {
1252                 DEBUG(0,("smbldap_create_page_control: ber_alloc_t returns "
1253                          "NULL\n"));
1254                 return LDAP_NO_MEMORY;
1255         }
1256
1257         /* construct cookie */
1258         if (*cookie != NULL) {
1259                 ber_printf(cookie_be, "{iO}", (ber_int_t) pagesize, *cookie);
1260                 ber_bvfree(*cookie); /* don't need it from last time */
1261                 *cookie = NULL;
1262         } else {
1263                 ber_printf(cookie_be, "{io}", (ber_int_t) pagesize, "", 0);
1264         }
1265         ber_flatten(cookie_be, &cookie_bv);
1266
1267         pr.ldctl_oid = CONST_DISCARD(char *, ADS_PAGE_CTL_OID);
1268         pr.ldctl_iscritical = (char) critical;
1269         pr.ldctl_value.bv_len = cookie_bv->bv_len;
1270         pr.ldctl_value.bv_val = cookie_bv->bv_val;
1271
1272         controls[0] = &pr;
1273         controls[1] = NULL;
1274
1275         rc = smbldap_search_ext(ldap_state, base, scope, filter, attrs, 
1276                                  0, controls, NULL, LDAP_NO_LIMIT, res);
1277
1278         ber_free(cookie_be, 1);
1279         ber_bvfree(cookie_bv);
1280
1281         if (rc != 0) {
1282                 DEBUG(3,("smbldap_search_paged: smbldap_search_ext(%s) "
1283                          "failed with [%s]\n", filter, ldap_err2string(rc)));
1284                 goto done;
1285         }
1286
1287         DEBUG(3,("smbldap_search_paged: search was successfull\n"));
1288
1289         rc = ldap_parse_result(ldap_state->ldap_struct, *res, NULL, NULL, 
1290                                NULL, NULL, &rcontrols,  0);
1291         if (rc != 0) {
1292                 DEBUG(3,("smbldap_search_paged: ldap_parse_result failed " \
1293                          "with [%s]\n", ldap_err2string(rc)));
1294                 goto done;
1295         }
1296
1297         if (rcontrols == NULL)
1298                 goto done;
1299
1300         for (i=0; rcontrols[i]; i++) {
1301
1302                 if (strcmp(ADS_PAGE_CTL_OID, rcontrols[i]->ldctl_oid) != 0)
1303                         continue;
1304
1305                 cookie_be = ber_init(&rcontrols[i]->ldctl_value);
1306                 ber_scanf(cookie_be,"{iO}", &tmp, &cookie_bv);
1307                 /* the berval is the cookie, but must be freed when it is all
1308                    done */
1309                 if (cookie_bv->bv_len)
1310                         *cookie=ber_bvdup(cookie_bv);
1311                 else
1312                         *cookie=NULL;
1313                 ber_bvfree(cookie_bv);
1314                 ber_free(cookie_be, 1);
1315                 break;
1316         }
1317         ldap_controls_free(rcontrols);
1318 done:   
1319         return rc;
1320 }
1321
1322 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1323 {
1324         int             rc = LDAP_SERVER_DOWN;
1325         int             attempts = 0;
1326         char           *utf8_dn;
1327         time_t          endtime = time(NULL)+lp_ldap_timeout();
1328
1329         SMB_ASSERT(ldap_state);
1330
1331         DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1332
1333         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1334                 return LDAP_NO_MEMORY;
1335         }
1336
1337         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1338                 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1339                 if (rc != LDAP_SUCCESS) {
1340                         char *ld_error = NULL;
1341                         ldap_get_option(ldap_state->ldap_struct,
1342                                         LDAP_OPT_ERROR_STRING, &ld_error);
1343                         DEBUG(10,("Failed to modify dn: %s, error: %s "
1344                                   "(%s)\n", dn, ldap_err2string(rc),
1345                                   ld_error ? ld_error : "unknown"));
1346                         SAFE_FREE(ld_error);
1347                 }
1348         }
1349                 
1350         SAFE_FREE(utf8_dn);
1351         return rc;
1352 }
1353
1354 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1355 {
1356         int             rc = LDAP_SERVER_DOWN;
1357         int             attempts = 0;
1358         char           *utf8_dn;
1359         time_t          endtime = time(NULL)+lp_ldap_timeout();
1360         
1361         SMB_ASSERT(ldap_state);
1362
1363         DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1364
1365         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1366                 return LDAP_NO_MEMORY;
1367         }
1368
1369         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1370                 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1371                 if (rc != LDAP_SUCCESS) {
1372                         char *ld_error = NULL;
1373                         ldap_get_option(ldap_state->ldap_struct,
1374                                         LDAP_OPT_ERROR_STRING, &ld_error);
1375                         DEBUG(10,("Failed to add dn: %s, error: %s "
1376                                   "(%s)\n", dn, ldap_err2string(rc),
1377                                   ld_error ? ld_error : "unknown"));
1378                         SAFE_FREE(ld_error);
1379                 }
1380         }
1381         
1382         SAFE_FREE(utf8_dn);
1383         return rc;
1384 }
1385
1386 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1387 {
1388         int             rc = LDAP_SERVER_DOWN;
1389         int             attempts = 0;
1390         char           *utf8_dn;
1391         time_t          endtime = time(NULL)+lp_ldap_timeout();
1392         
1393         SMB_ASSERT(ldap_state);
1394
1395         DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1396
1397         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1398                 return LDAP_NO_MEMORY;
1399         }
1400
1401         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1402                 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1403                 if (rc != LDAP_SUCCESS) {
1404                         char *ld_error = NULL;
1405                         ldap_get_option(ldap_state->ldap_struct,
1406                                         LDAP_OPT_ERROR_STRING, &ld_error);
1407                         DEBUG(10,("Failed to delete dn: %s, error: %s "
1408                                   "(%s)\n", dn, ldap_err2string(rc),
1409                                   ld_error ? ld_error : "unknown"));
1410                         SAFE_FREE(ld_error);
1411                 }
1412         }
1413         
1414         SAFE_FREE(utf8_dn);
1415         return rc;
1416 }
1417
1418 int smbldap_extended_operation(struct smbldap_state *ldap_state, 
1419                                LDAP_CONST char *reqoid, struct berval *reqdata, 
1420                                LDAPControl **serverctrls, LDAPControl **clientctrls, 
1421                                char **retoidp, struct berval **retdatap)
1422 {
1423         int             rc = LDAP_SERVER_DOWN;
1424         int             attempts = 0;
1425         time_t          endtime = time(NULL)+lp_ldap_timeout();
1426         
1427         if (!ldap_state)
1428                 return (-1);
1429
1430         while (another_ldap_try(ldap_state, &rc, &attempts, endtime)) {
1431                 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid,
1432                                                reqdata, serverctrls,
1433                                                clientctrls, retoidp, retdatap);
1434                 if (rc != LDAP_SUCCESS) {
1435                         char *ld_error = NULL;
1436                         ldap_get_option(ldap_state->ldap_struct,
1437                                         LDAP_OPT_ERROR_STRING, &ld_error);
1438                         DEBUG(10,("Extended operation failed with error: %s "
1439                                   "(%s)\n", ldap_err2string(rc),
1440                                   ld_error ? ld_error : "unknown"));
1441                         SAFE_FREE(ld_error);
1442                 }
1443         }
1444                 
1445         return rc;
1446 }
1447
1448 /*******************************************************************
1449  run the search by name.
1450 ******************************************************************/
1451 int smbldap_search_suffix (struct smbldap_state *ldap_state,
1452                            const char *filter, const char **search_attr,
1453                            LDAPMessage ** result)
1454 {
1455         return smbldap_search(ldap_state, lp_ldap_suffix(), LDAP_SCOPE_SUBTREE,
1456                               filter, search_attr, 0, result);
1457 }
1458
1459 static void smbldap_idle_fn(void **data, time_t *interval, time_t now)
1460 {
1461         struct smbldap_state *state = (struct smbldap_state *)(*data);
1462
1463         if (state->ldap_struct == NULL) {
1464                 DEBUG(10,("ldap connection not connected...\n"));
1465                 return;
1466         }
1467                 
1468         if ((state->last_use+SMBLDAP_IDLE_TIME) > now) {
1469                 DEBUG(10,("ldap connection not idle...\n"));
1470                 return;
1471         }
1472                 
1473         DEBUG(7,("ldap connection idle...closing connection\n"));
1474         smbldap_close(state);
1475 }
1476
1477 /**********************************************************************
1478  Housekeeping
1479  *********************************************************************/
1480
1481 void smbldap_free_struct(struct smbldap_state **ldap_state) 
1482 {
1483         smbldap_close(*ldap_state);
1484         
1485         if ((*ldap_state)->bind_secret) {
1486                 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1487         }
1488
1489         SAFE_FREE((*ldap_state)->bind_dn);
1490         SAFE_FREE((*ldap_state)->bind_secret);
1491
1492         smb_unregister_idle_event((*ldap_state)->event_id);
1493
1494         *ldap_state = NULL;
1495
1496         /* No need to free any further, as it is talloc()ed */
1497 }
1498
1499
1500 /**********************************************************************
1501  Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1502  *********************************************************************/
1503
1504 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state) 
1505 {
1506         *smbldap_state = TALLOC_ZERO_P(mem_ctx, struct smbldap_state);
1507         if (!*smbldap_state) {
1508                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1509                 return NT_STATUS_NO_MEMORY;
1510         }
1511
1512         if (location) {
1513                 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1514         } else {
1515                 (*smbldap_state)->uri = "ldap://localhost";
1516         }
1517
1518         (*smbldap_state)->event_id =
1519                 smb_register_idle_event(smbldap_idle_fn, (void *)(*smbldap_state),
1520                                         SMBLDAP_IDLE_TIME);
1521
1522         if ((*smbldap_state)->event_id == SMB_EVENT_ID_INVALID) {
1523                 DEBUG(0,("Failed to register LDAP idle event!\n"));
1524                 return NT_STATUS_INVALID_HANDLE;
1525         }
1526
1527         return NT_STATUS_OK;
1528 }
1529
1530 /*******************************************************************
1531  Return a copy of the DN for a LDAPMessage. Convert from utf8 to CH_UNIX.
1532 ********************************************************************/
1533
1534 char *smbldap_get_dn(LDAP *ld, LDAPMessage *entry)
1535 {
1536         char *utf8_dn, *unix_dn;
1537
1538         utf8_dn = ldap_get_dn(ld, entry);
1539         if (!utf8_dn) {
1540                 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1541                 return NULL;
1542         }
1543         if (pull_utf8_allocate(&unix_dn, utf8_dn) == (size_t)-1) {
1544                 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 [%s]\n", utf8_dn));
1545                 return NULL;
1546         }
1547         ldap_memfree(utf8_dn);
1548         return unix_dn;
1549 }
1550
1551  const char *smbldap_talloc_dn(TALLOC_CTX *mem_ctx, LDAP *ld,
1552                                LDAPMessage *entry)
1553 {
1554         char *utf8_dn, *unix_dn;
1555
1556         utf8_dn = ldap_get_dn(ld, entry);
1557         if (!utf8_dn) {
1558                 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1559                 return NULL;
1560         }
1561         if (pull_utf8_talloc(mem_ctx, &unix_dn, utf8_dn) == (size_t)-1) {
1562                 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 "
1563                            "[%s]\n", utf8_dn));
1564                 return NULL;
1565         }
1566         ldap_memfree(utf8_dn);
1567         return unix_dn;
1568 }
1569
1570 /*******************************************************************
1571  Check if root-dse has a certain Control or Extension
1572 ********************************************************************/
1573
1574 static BOOL smbldap_check_root_dse(struct smbldap_state *ldap_state, const char **attrs, const char *value) 
1575 {
1576         LDAPMessage *msg = NULL;
1577         LDAPMessage *entry = NULL;
1578         char **values = NULL;
1579         int rc, num_result, num_values, i;
1580         BOOL result = False;
1581
1582         if (!attrs[0]) {
1583                 DEBUG(3,("smbldap_check_root_dse: nothing to look for\n"));
1584                 return False;
1585         }
1586
1587         if (!strequal(attrs[0], "supportedExtension") && 
1588             !strequal(attrs[0], "supportedControl") && 
1589             !strequal(attrs[0], "namingContexts")) {
1590                 DEBUG(3,("smbldap_check_root_dse: no idea what to query root-dse for: %s ?\n", attrs[0]));
1591                 return False;
1592         }
1593
1594         rc = ldap_search_s(ldap_state->ldap_struct, "", LDAP_SCOPE_BASE, 
1595                            "(objectclass=*)", CONST_DISCARD(char **, attrs), 0 , &msg);
1596
1597         if (rc != LDAP_SUCCESS) {
1598                 DEBUG(3,("smbldap_check_root_dse: Could not search rootDSE\n"));
1599                 return False;
1600         }
1601
1602         num_result = ldap_count_entries(ldap_state->ldap_struct, msg);
1603
1604         if (num_result != 1) {
1605                 DEBUG(3,("smbldap_check_root_dse: Expected one rootDSE, got %d\n", num_result));
1606                 goto done;
1607         }
1608
1609         entry = ldap_first_entry(ldap_state->ldap_struct, msg);
1610
1611         if (entry == NULL) {
1612                 DEBUG(3,("smbldap_check_root_dse: Could not retrieve rootDSE\n"));
1613                 goto done;
1614         }
1615
1616         values = ldap_get_values(ldap_state->ldap_struct, entry, attrs[0]);
1617
1618         if (values == NULL) {
1619                 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not support any %s\n", attrs[0]));
1620                 goto done;
1621         }
1622
1623         num_values = ldap_count_values(values);
1624
1625         if (num_values == 0) {
1626                 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not have any %s\n", attrs[0]));
1627                 goto done;
1628         }
1629
1630         for (i=0; i<num_values; i++) {
1631                 if (strcmp(values[i], value) == 0)
1632                         result = True;
1633         }
1634
1635
1636  done:
1637         if (values != NULL)
1638                 ldap_value_free(values);
1639         if (msg != NULL)
1640                 ldap_msgfree(msg);
1641
1642         return result;
1643
1644 }
1645
1646 /*******************************************************************
1647  Check if LDAP-Server supports a certain Control (OID in string format)
1648 ********************************************************************/
1649
1650 BOOL smbldap_has_control(struct smbldap_state *ldap_state, const char *control)
1651 {
1652         const char *attrs[] = { "supportedControl", NULL };
1653         return smbldap_check_root_dse(ldap_state, attrs, control);
1654 }
1655
1656 /*******************************************************************
1657  Check if LDAP-Server supports a certain Extension (OID in string format)
1658 ********************************************************************/
1659
1660 BOOL smbldap_has_extension(struct smbldap_state *ldap_state, const char *extension)
1661 {
1662         const char *attrs[] = { "supportedExtension", NULL };
1663         return smbldap_check_root_dse(ldap_state, attrs, extension);
1664 }
1665
1666 /*******************************************************************
1667  Check if LDAP-Server holds a given namingContext
1668 ********************************************************************/
1669
1670 BOOL smbldap_has_naming_context(struct smbldap_state *ldap_state, const char *naming_context)
1671 {
1672         const char *attrs[] = { "namingContexts", NULL };
1673         return smbldap_check_root_dse(ldap_state, attrs, naming_context);
1674 }