Move the alarm setup/teardown out of another_ldap_try() and into separate
[samba.git] / source3 / 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 3 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, see <http://www.gnu.org/licenses/>.
22
23 */
24
25 #include "includes.h"
26 #include "smbldap.h"
27 #include "secrets.h"
28 #include "../libcli/security/security.h"
29
30 /* Try not to hit the up or down server forever */
31
32 #define SMBLDAP_DONT_PING_TIME 10       /* ping only all 10 seconds */
33 #define SMBLDAP_NUM_RETRIES 8           /* retry only 8 times */
34
35 #define SMBLDAP_IDLE_TIME 150           /* After 2.5 minutes disconnect */
36
37
38 /* attributes used by Samba 2.2 */
39
40 ATTRIB_MAP_ENTRY attrib_map_v22[] = {
41         { LDAP_ATTR_UID,                "uid"           },
42         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
43         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
44         { LDAP_ATTR_UNIX_HOME,          "homeDirectory" },
45         { LDAP_ATTR_PWD_LAST_SET,       "pwdLastSet"    },
46         { LDAP_ATTR_PWD_CAN_CHANGE,     "pwdCanChange"  },
47         { LDAP_ATTR_PWD_MUST_CHANGE,    "pwdMustChange" },
48         { LDAP_ATTR_LOGON_TIME,         "logonTime"     },
49         { LDAP_ATTR_LOGOFF_TIME,        "logoffTime"    },
50         { LDAP_ATTR_KICKOFF_TIME,       "kickoffTime"   },
51         { LDAP_ATTR_CN,                 "cn"            },
52         { LDAP_ATTR_SN,                 "sn"            },
53         { LDAP_ATTR_DISPLAY_NAME,       "displayName"   },
54         { LDAP_ATTR_HOME_PATH,          "smbHome"       },
55         { LDAP_ATTR_HOME_DRIVE,         "homeDrive"     },
56         { LDAP_ATTR_LOGON_SCRIPT,       "scriptPath"    },
57         { LDAP_ATTR_PROFILE_PATH,       "profilePath"   },
58         { LDAP_ATTR_DESC,               "description"   },
59         { LDAP_ATTR_USER_WKS,           "userWorkstations"},
60         { LDAP_ATTR_USER_RID,           "rid"           },
61         { LDAP_ATTR_PRIMARY_GROUP_RID,  "primaryGroupID"},
62         { LDAP_ATTR_LMPW,               "lmPassword"    },
63         { LDAP_ATTR_NTPW,               "ntPassword"    },
64         { LDAP_ATTR_DOMAIN,             "domain"        },
65         { LDAP_ATTR_OBJCLASS,           "objectClass"   },
66         { LDAP_ATTR_ACB_INFO,           "acctFlags"     },
67         { LDAP_ATTR_MOD_TIMESTAMP,      "modifyTimestamp"       },
68         { LDAP_ATTR_LIST_END,           NULL            }
69 };
70
71 ATTRIB_MAP_ENTRY attrib_map_to_delete_v22[] = {
72         { LDAP_ATTR_PWD_LAST_SET,       "pwdLastSet"    },
73         { LDAP_ATTR_PWD_CAN_CHANGE,     "pwdCanChange"  },
74         { LDAP_ATTR_PWD_MUST_CHANGE,    "pwdMustChange" },
75         { LDAP_ATTR_LOGON_TIME,         "logonTime"     },
76         { LDAP_ATTR_LOGOFF_TIME,        "logoffTime"    },
77         { LDAP_ATTR_KICKOFF_TIME,       "kickoffTime"   },
78         { LDAP_ATTR_DISPLAY_NAME,       "displayName"   },
79         { LDAP_ATTR_HOME_PATH,          "smbHome"       },
80         { LDAP_ATTR_HOME_DRIVE,         "homeDrives"    },
81         { LDAP_ATTR_LOGON_SCRIPT,       "scriptPath"    },
82         { LDAP_ATTR_PROFILE_PATH,       "profilePath"   },
83         { LDAP_ATTR_USER_WKS,           "userWorkstations"},
84         { LDAP_ATTR_USER_RID,           "rid"           },
85         { LDAP_ATTR_PRIMARY_GROUP_RID,  "primaryGroupID"},
86         { LDAP_ATTR_LMPW,               "lmPassword"    },
87         { LDAP_ATTR_NTPW,               "ntPassword"    },
88         { LDAP_ATTR_DOMAIN,             "domain"        },
89         { LDAP_ATTR_ACB_INFO,           "acctFlags"     },
90         { LDAP_ATTR_LIST_END,           NULL            }
91 };
92
93 /* attributes used by Samba 3.0's sambaSamAccount */
94
95 ATTRIB_MAP_ENTRY attrib_map_v30[] = {
96         { LDAP_ATTR_UID,                "uid"                   },
97         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
98         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
99         { LDAP_ATTR_UNIX_HOME,          "homeDirectory"         },
100         { LDAP_ATTR_PWD_LAST_SET,       "sambaPwdLastSet"       },
101         { LDAP_ATTR_PWD_CAN_CHANGE,     "sambaPwdCanChange"     },
102         { LDAP_ATTR_PWD_MUST_CHANGE,    "sambaPwdMustChange"    },
103         { LDAP_ATTR_LOGON_TIME,         "sambaLogonTime"        },
104         { LDAP_ATTR_LOGOFF_TIME,        "sambaLogoffTime"       },
105         { LDAP_ATTR_KICKOFF_TIME,       "sambaKickoffTime"      },
106         { LDAP_ATTR_CN,                 "cn"                    },
107         { LDAP_ATTR_SN,                 "sn"                    },
108         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
109         { LDAP_ATTR_HOME_DRIVE,         "sambaHomeDrive"        },
110         { LDAP_ATTR_HOME_PATH,          "sambaHomePath"         },
111         { LDAP_ATTR_LOGON_SCRIPT,       "sambaLogonScript"      },
112         { LDAP_ATTR_PROFILE_PATH,       "sambaProfilePath"      },
113         { LDAP_ATTR_DESC,               "description"           },
114         { LDAP_ATTR_USER_WKS,           "sambaUserWorkstations" },
115         { LDAP_ATTR_USER_SID,           LDAP_ATTRIBUTE_SID      },
116         { LDAP_ATTR_PRIMARY_GROUP_SID,  "sambaPrimaryGroupSID"  },
117         { LDAP_ATTR_LMPW,               "sambaLMPassword"       },
118         { LDAP_ATTR_NTPW,               "sambaNTPassword"       },
119         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
120         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
121         { LDAP_ATTR_ACB_INFO,           "sambaAcctFlags"        },
122         { LDAP_ATTR_MUNGED_DIAL,        "sambaMungedDial"       },
123         { LDAP_ATTR_BAD_PASSWORD_COUNT, "sambaBadPasswordCount" },
124         { LDAP_ATTR_BAD_PASSWORD_TIME,  "sambaBadPasswordTime"  },
125         { LDAP_ATTR_PWD_HISTORY,        "sambaPasswordHistory"  },
126         { LDAP_ATTR_MOD_TIMESTAMP,      "modifyTimestamp"       },
127         { LDAP_ATTR_LOGON_HOURS,        "sambaLogonHours"       },
128         { LDAP_ATTR_LIST_END,           NULL                    }
129 };
130
131 ATTRIB_MAP_ENTRY attrib_map_to_delete_v30[] = {
132         { LDAP_ATTR_PWD_LAST_SET,       "sambaPwdLastSet"       },
133         { LDAP_ATTR_PWD_CAN_CHANGE,     "sambaPwdCanChange"     },
134         { LDAP_ATTR_PWD_MUST_CHANGE,    "sambaPwdMustChange"    },
135         { LDAP_ATTR_LOGON_TIME,         "sambaLogonTime"        },
136         { LDAP_ATTR_LOGOFF_TIME,        "sambaLogoffTime"       },
137         { LDAP_ATTR_KICKOFF_TIME,       "sambaKickoffTime"      },
138         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
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         size_t size = 0;
268
269         if ( !attribute )
270                 return False;
271
272         value[0] = '\0';
273
274         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
275                 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
276
277                 return False;
278         }
279
280         if (!convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, max_len, &size)) {
281                 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n", 
282                           attribute, values[0]));
283                 ldap_value_free(values);
284                 return False;
285         }
286
287         ldap_value_free(values);
288 #ifdef DEBUG_PASSWORDS
289         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
290 #endif  
291         return True;
292 }
293
294  char * smbldap_talloc_single_attribute(LDAP *ldap_struct, LDAPMessage *entry,
295                                         const char *attribute,
296                                         TALLOC_CTX *mem_ctx)
297 {
298         char **values;
299         char *result;
300         size_t converted_size;
301
302         if (attribute == NULL) {
303                 return NULL;
304         }
305
306         values = ldap_get_values(ldap_struct, entry, attribute);
307
308         if (values == NULL) {
309                 DEBUG(10, ("attribute %s does not exist\n", attribute));
310                 return NULL;
311         }
312
313         if (ldap_count_values(values) != 1) {
314                 DEBUG(10, ("attribute %s has %d values, expected only one\n",
315                            attribute, ldap_count_values(values)));
316                 ldap_value_free(values);
317                 return NULL;
318         }
319
320         if (!pull_utf8_talloc(mem_ctx, &result, values[0], &converted_size)) {
321                 DEBUG(10, ("pull_utf8_talloc failed\n"));
322                 ldap_value_free(values);
323                 return NULL;
324         }
325
326         ldap_value_free(values);
327
328 #ifdef DEBUG_PASSWORDS
329         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n",
330                      attribute, result));
331 #endif  
332         return result;
333 }
334
335  char * smbldap_talloc_first_attribute(LDAP *ldap_struct, LDAPMessage *entry,
336                                        const char *attribute,
337                                        TALLOC_CTX *mem_ctx)
338 {
339         char **values;
340         char *result;
341         size_t converted_size;
342
343         if (attribute == NULL) {
344                 return NULL;
345         }
346
347         values = ldap_get_values(ldap_struct, entry, attribute);
348
349         if (values == NULL) {
350                 DEBUG(10, ("attribute %s does not exist\n", attribute));
351                 return NULL;
352         }
353
354         if (!pull_utf8_talloc(mem_ctx, &result, values[0], &converted_size)) {
355                 DEBUG(10, ("pull_utf8_talloc failed\n"));
356                 ldap_value_free(values);
357                 return NULL;
358         }
359
360         ldap_value_free(values);
361
362 #ifdef DEBUG_PASSWORDS
363         DEBUG (100, ("smbldap_get_first_attribute: [%s] = [%s]\n",
364                      attribute, result));
365 #endif
366         return result;
367 }
368
369  char * smbldap_talloc_smallest_attribute(LDAP *ldap_struct, LDAPMessage *entry,
370                                           const char *attribute,
371                                           TALLOC_CTX *mem_ctx)
372 {
373         char **values;
374         char *result;
375         size_t converted_size;
376         int i, num_values;
377
378         if (attribute == NULL) {
379                 return NULL;
380         }
381
382         values = ldap_get_values(ldap_struct, entry, attribute);
383
384         if (values == NULL) {
385                 DEBUG(10, ("attribute %s does not exist\n", attribute));
386                 return NULL;
387         }
388
389         if (!pull_utf8_talloc(mem_ctx, &result, values[0], &converted_size)) {
390                 DEBUG(10, ("pull_utf8_talloc failed\n"));
391                 ldap_value_free(values);
392                 return NULL;
393         }
394
395         num_values = ldap_count_values(values);
396
397         for (i=1; i<num_values; i++) {
398                 char *tmp;
399
400                 if (!pull_utf8_talloc(mem_ctx, &tmp, values[i],
401                                       &converted_size)) {
402                         DEBUG(10, ("pull_utf8_talloc failed\n"));
403                         TALLOC_FREE(result);
404                         ldap_value_free(values);
405                         return NULL;
406                 }
407
408                 if (strcasecmp_m(tmp, result) < 0) {
409                         TALLOC_FREE(result);
410                         result = tmp;
411                 } else {
412                         TALLOC_FREE(tmp);
413                 }
414         }
415
416         ldap_value_free(values);
417
418 #ifdef DEBUG_PASSWORDS
419         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n",
420                      attribute, result));
421 #endif
422         return result;
423 }
424
425  bool smbldap_talloc_single_blob(TALLOC_CTX *mem_ctx, LDAP *ld,
426                                  LDAPMessage *msg, const char *attrib,
427                                  DATA_BLOB *blob)
428 {
429         struct berval **values;
430
431         values = ldap_get_values_len(ld, msg, attrib);
432         if (!values) {
433                 return false;
434         }
435
436         if (ldap_count_values_len(values) != 1) {
437                 DEBUG(10, ("Expected one value for %s, got %d\n", attrib,
438                            ldap_count_values_len(values)));
439                 return false;
440         }
441
442         *blob = data_blob_talloc(mem_ctx, values[0]->bv_val,
443                                  values[0]->bv_len);
444         ldap_value_free_len(values);
445
446         return (blob->data != NULL);
447 }
448
449  bool smbldap_pull_sid(LDAP *ld, LDAPMessage *msg, const char *attrib,
450                        struct dom_sid *sid)
451 {
452         DATA_BLOB blob;
453         bool ret;
454
455         if (!smbldap_talloc_single_blob(talloc_tos(), ld, msg, attrib,
456                                         &blob)) {
457                 return false;
458         }
459         ret = sid_parse((char *)blob.data, blob.length, sid);
460         TALLOC_FREE(blob.data);
461         return ret;
462 }
463
464  static int ldapmsg_destructor(LDAPMessage **result) {
465         ldap_msgfree(*result);
466         return 0;
467 }
468
469  void talloc_autofree_ldapmsg(TALLOC_CTX *mem_ctx, LDAPMessage *result)
470 {
471         LDAPMessage **handle;
472
473         if (result == NULL) {
474                 return;
475         }
476
477         handle = talloc(mem_ctx, LDAPMessage *);
478         SMB_ASSERT(handle != NULL);
479
480         *handle = result;
481         talloc_set_destructor(handle, ldapmsg_destructor);
482 }
483
484  static int ldapmod_destructor(LDAPMod ***mod) {
485         ldap_mods_free(*mod, True);
486         return 0;
487 }
488
489  void talloc_autofree_ldapmod(TALLOC_CTX *mem_ctx, LDAPMod **mod)
490 {
491         LDAPMod ***handle;
492
493         if (mod == NULL) {
494                 return;
495         }
496
497         handle = talloc(mem_ctx, LDAPMod **);
498         SMB_ASSERT(handle != NULL);
499
500         *handle = mod;
501         talloc_set_destructor(handle, ldapmod_destructor);
502 }
503
504 /************************************************************************
505  Routine to manage the LDAPMod structure array
506  manage memory used by the array, by each struct, and values
507  ***********************************************************************/
508
509 static void smbldap_set_mod_internal(LDAPMod *** modlist, int modop, const char *attribute, const char *value, const DATA_BLOB *blob)
510 {
511         LDAPMod **mods;
512         int i;
513         int j;
514
515         mods = *modlist;
516
517         /* sanity checks on the mod values */
518
519         if (attribute == NULL || *attribute == '\0') {
520                 return; 
521         }
522
523 #if 0   /* commented out after discussion with abartlet.  Do not reenable.
524            left here so other do not re-add similar code   --jerry */
525         if (value == NULL || *value == '\0')
526                 return;
527 #endif
528
529         if (mods == NULL) {
530                 mods = SMB_MALLOC_P(LDAPMod *);
531                 if (mods == NULL) {
532                         smb_panic("smbldap_set_mod: out of memory!");
533                         /* notreached. */
534                 }
535                 mods[0] = NULL;
536         }
537
538         for (i = 0; mods[i] != NULL; ++i) {
539                 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
540                         break;
541         }
542
543         if (mods[i] == NULL) {
544                 mods = SMB_REALLOC_ARRAY (mods, LDAPMod *, i + 2);
545                 if (mods == NULL) {
546                         smb_panic("smbldap_set_mod: out of memory!");
547                         /* notreached. */
548                 }
549                 mods[i] = SMB_MALLOC_P(LDAPMod);
550                 if (mods[i] == NULL) {
551                         smb_panic("smbldap_set_mod: out of memory!");
552                         /* notreached. */
553                 }
554                 mods[i]->mod_op = modop;
555                 mods[i]->mod_values = NULL;
556                 mods[i]->mod_type = SMB_STRDUP(attribute);
557                 mods[i + 1] = NULL;
558         }
559
560         if (blob && (modop & LDAP_MOD_BVALUES)) {
561                 j = 0;
562                 if (mods[i]->mod_bvalues != NULL) {
563                         for (; mods[i]->mod_bvalues[j] != NULL; j++);
564                 }
565                 mods[i]->mod_bvalues = SMB_REALLOC_ARRAY(mods[i]->mod_bvalues, struct berval *, j + 2);
566
567                 if (mods[i]->mod_bvalues == NULL) {
568                         smb_panic("smbldap_set_mod: out of memory!");
569                         /* notreached. */
570                 }
571
572                 mods[i]->mod_bvalues[j] = SMB_MALLOC_P(struct berval);
573                 SMB_ASSERT(mods[i]->mod_bvalues[j] != NULL);
574
575                 mods[i]->mod_bvalues[j]->bv_val = (char *)memdup(blob->data, blob->length);
576                 SMB_ASSERT(mods[i]->mod_bvalues[j]->bv_val != NULL);
577                 mods[i]->mod_bvalues[j]->bv_len = blob->length;
578
579                 mods[i]->mod_bvalues[j + 1] = NULL;
580         } else if (value != NULL) {
581                 char *utf8_value = NULL;
582                 size_t converted_size;
583
584                 j = 0;
585                 if (mods[i]->mod_values != NULL) {
586                         for (; mods[i]->mod_values[j] != NULL; j++);
587                 }
588                 mods[i]->mod_values = SMB_REALLOC_ARRAY(mods[i]->mod_values, char *, j + 2);
589
590                 if (mods[i]->mod_values == NULL) {
591                         smb_panic("smbldap_set_mod: out of memory!");
592                         /* notreached. */
593                 }
594
595                 if (!push_utf8_talloc(talloc_tos(), &utf8_value, value, &converted_size)) {
596                         smb_panic("smbldap_set_mod: String conversion failure!");
597                         /* notreached. */
598                 }
599
600                 mods[i]->mod_values[j] = SMB_STRDUP(utf8_value);
601                 TALLOC_FREE(utf8_value);
602                 SMB_ASSERT(mods[i]->mod_values[j] != NULL);
603
604                 mods[i]->mod_values[j + 1] = NULL;
605         }
606         *modlist = mods;
607 }
608
609  void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
610 {
611         smbldap_set_mod_internal(modlist, modop, attribute, value, NULL);
612 }
613
614  void smbldap_set_mod_blob(LDAPMod *** modlist, int modop, const char *attribute, const DATA_BLOB *value)
615 {
616         smbldap_set_mod_internal(modlist, modop | LDAP_MOD_BVALUES, attribute, NULL, value);
617 }
618
619 /**********************************************************************
620   Set attribute to newval in LDAP, regardless of what value the
621   attribute had in LDAP before.
622 *********************************************************************/
623
624 static void smbldap_make_mod_internal(LDAP *ldap_struct, LDAPMessage *existing,
625                                       LDAPMod ***mods,
626                                       const char *attribute, int op,
627                                       const char *newval,
628                                       const DATA_BLOB *newblob)
629 {
630         char oldval[2048]; /* current largest allowed value is mungeddial */
631         bool existed;
632         DATA_BLOB oldblob = data_blob_null;
633
634         if (attribute == NULL) {
635                 /* This can actually happen for ldapsam_compat where we for
636                  * example don't have a password history */
637                 return;
638         }
639
640         if (existing != NULL) {
641                 if (op & LDAP_MOD_BVALUES) {
642                         existed = smbldap_talloc_single_blob(talloc_tos(), ldap_struct, existing, attribute, &oldblob);
643                 } else {
644                         existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval, sizeof(oldval));
645                 }
646         } else {
647                 existed = False;
648                 *oldval = '\0';
649         }
650
651         if (existed) {
652                 bool equal = false;
653                 if (op & LDAP_MOD_BVALUES) {
654                         equal = (newblob && (data_blob_cmp(&oldblob, newblob) == 0));
655                 } else {
656                         /* all of our string attributes are case insensitive */
657                         equal = (newval && (strcasecmp_m(oldval, newval) == 0));
658                 }
659
660                 if (equal) {
661                         /* Believe it or not, but LDAP will deny a delete and
662                            an add at the same time if the values are the
663                            same... */
664                         DEBUG(10,("smbldap_make_mod: attribute |%s| not changed.\n", attribute));
665                         return;
666                 }
667
668                 /* There has been no value before, so don't delete it.
669                  * Here's a possible race: We might end up with
670                  * duplicate attributes */
671                 /* By deleting exactly the value we found in the entry this
672                  * should be race-free in the sense that the LDAP-Server will
673                  * deny the complete operation if somebody changed the
674                  * attribute behind our back. */
675                 /* This will also allow modifying single valued attributes 
676                  * in Novell NDS. In NDS you have to first remove attribute and then
677                  * you could add new value */
678
679                 if (op & LDAP_MOD_BVALUES) {
680                         DEBUG(10,("smbldap_make_mod: deleting attribute |%s| blob\n", attribute));
681                         smbldap_set_mod_blob(mods, LDAP_MOD_DELETE, attribute, &oldblob);
682                 } else {
683                         DEBUG(10,("smbldap_make_mod: deleting attribute |%s| values |%s|\n", attribute, oldval));
684                         smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, oldval);
685                 }
686         }
687
688         /* Regardless of the real operation (add or modify)
689            we add the new value here. We rely on deleting
690            the old value, should it exist. */
691
692         if (op & LDAP_MOD_BVALUES) {
693                 if (newblob && newblob->length) {
694                         DEBUG(10,("smbldap_make_mod: adding attribute |%s| blob\n", attribute));
695                         smbldap_set_mod_blob(mods, LDAP_MOD_ADD, attribute, newblob);
696                 }
697         } else {
698                 if ((newval != NULL) && (strlen(newval) > 0)) {
699                         DEBUG(10,("smbldap_make_mod: adding attribute |%s| value |%s|\n", attribute, newval));
700                         smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
701                 }
702         }
703 }
704
705  void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
706                       LDAPMod ***mods,
707                       const char *attribute, const char *newval)
708 {
709         smbldap_make_mod_internal(ldap_struct, existing, mods, attribute,
710                                   0, newval, NULL);
711 }
712
713  void smbldap_make_mod_blob(LDAP *ldap_struct, LDAPMessage *existing,
714                             LDAPMod ***mods,
715                             const char *attribute, const DATA_BLOB *newblob)
716 {
717         smbldap_make_mod_internal(ldap_struct, existing, mods, attribute,
718                                   LDAP_MOD_BVALUES, NULL, newblob);
719 }
720
721 /**********************************************************************
722  Some varients of the LDAP rebind code do not pass in the third 'arg' 
723  pointer to a void*, so we try and work around it by assuming that the 
724  value of the 'LDAP *' pointer is the same as the one we had passed in
725  **********************************************************************/
726
727 struct smbldap_state_lookup {
728         LDAP *ld;
729         struct smbldap_state *smbldap_state;
730         struct smbldap_state_lookup *prev, *next;
731 };
732
733 static struct smbldap_state_lookup *smbldap_state_lookup_list;
734
735 static struct smbldap_state *smbldap_find_state(LDAP *ld) 
736 {
737         struct smbldap_state_lookup *t;
738
739         for (t = smbldap_state_lookup_list; t; t = t->next) {
740                 if (t->ld == ld) {
741                         return t->smbldap_state;
742                 }
743         }
744         return NULL;
745 }
746
747 static void smbldap_delete_state(struct smbldap_state *smbldap_state) 
748 {
749         struct smbldap_state_lookup *t;
750
751         for (t = smbldap_state_lookup_list; t; t = t->next) {
752                 if (t->smbldap_state == smbldap_state) {
753                         DLIST_REMOVE(smbldap_state_lookup_list, t);
754                         SAFE_FREE(t);
755                         return;
756                 }
757         }
758 }
759
760 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state) 
761 {
762         struct smbldap_state *tmp_ldap_state;
763         struct smbldap_state_lookup *t;
764
765         if ((tmp_ldap_state = smbldap_find_state(ld))) {
766                 SMB_ASSERT(tmp_ldap_state == smbldap_state);
767                 return;
768         }
769
770         t = SMB_XMALLOC_P(struct smbldap_state_lookup);
771         ZERO_STRUCTP(t);
772
773         DLIST_ADD_END(smbldap_state_lookup_list, t, struct smbldap_state_lookup *);
774         t->ld = ld;
775         t->smbldap_state = smbldap_state;
776 }
777
778 /********************************************************************
779  start TLS on an existing LDAP connection
780 *******************************************************************/
781
782 int smb_ldap_start_tls(LDAP *ldap_struct, int version)
783
784 #ifdef LDAP_OPT_X_TLS
785         int rc;
786 #endif
787
788         if (lp_ldap_ssl() != LDAP_SSL_START_TLS) {
789                 return LDAP_SUCCESS;
790         }
791
792 #ifdef LDAP_OPT_X_TLS
793         if (version != LDAP_VERSION3) {
794                 DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
795                 return LDAP_OPERATIONS_ERROR;
796         }
797
798         if ((rc = ldap_start_tls_s (ldap_struct, NULL, NULL)) != LDAP_SUCCESS)  {
799                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
800                          ldap_err2string(rc)));
801                 return rc;
802         }
803
804         DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
805         return LDAP_SUCCESS;
806 #else
807         DEBUG(0,("StartTLS not supported by LDAP client libraries!\n"));
808         return LDAP_OPERATIONS_ERROR;
809 #endif
810 }
811
812 /********************************************************************
813  setup a connection to the LDAP server based on a uri
814 *******************************************************************/
815
816 static int smb_ldap_setup_conn(LDAP **ldap_struct, const char *uri)
817 {
818         int rc;
819
820         DEBUG(10, ("smb_ldap_setup_connection: %s\n", uri));
821
822 #ifdef HAVE_LDAP_INITIALIZE
823
824         rc = ldap_initialize(ldap_struct, uri);
825         if (rc) {
826                 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
827                 return rc;
828         }
829
830         if (lp_ldap_follow_referral() != Auto) {
831                 rc = ldap_set_option(*ldap_struct, LDAP_OPT_REFERRALS,
832                      lp_ldap_follow_referral() ? LDAP_OPT_ON : LDAP_OPT_OFF);
833                 if (rc != LDAP_SUCCESS)
834                         DEBUG(0, ("Failed to set LDAP_OPT_REFERRALS: %s\n",
835                                 ldap_err2string(rc)));
836         }
837
838         return LDAP_SUCCESS;
839 #else 
840
841         /* Parse the string manually */
842
843         {
844                 int port = 0;
845                 fstring protocol;
846                 fstring host;
847                 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
848
849
850                 /* skip leading "URL:" (if any) */
851                 if ( strnequal( uri, "URL:", 4 ) ) {
852                         uri += 4;
853                 }
854
855                 sscanf(uri, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
856
857                 if (port == 0) {
858                         if (strequal(protocol, "ldap")) {
859                                 port = LDAP_PORT;
860                         } else if (strequal(protocol, "ldaps")) {
861                                 port = LDAPS_PORT;
862                         } else {
863                                 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
864                         }
865                 }
866
867                 if ((*ldap_struct = ldap_init(host, port)) == NULL)     {
868                         DEBUG(0, ("ldap_init failed !\n"));
869                         return LDAP_OPERATIONS_ERROR;
870                 }
871
872                 if (strequal(protocol, "ldaps")) {
873 #ifdef LDAP_OPT_X_TLS
874                         int tls = LDAP_OPT_X_TLS_HARD;
875                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
876                         {
877                                 DEBUG(0, ("Failed to setup a TLS session\n"));
878                         }
879
880                         DEBUG(3,("LDAPS option set...!\n"));
881 #else
882                         DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
883                         return LDAP_OPERATIONS_ERROR;
884 #endif /* LDAP_OPT_X_TLS */
885                 }
886         }
887 #endif /* HAVE_LDAP_INITIALIZE */
888
889         /* now set connection timeout */
890 #ifdef LDAP_X_OPT_CONNECT_TIMEOUT /* Netscape */
891         {
892                 int ct = lp_ldap_connection_timeout()*1000;
893                 rc = ldap_set_option(*ldap_struct, LDAP_X_OPT_CONNECT_TIMEOUT, &ct);
894                 if (rc != LDAP_SUCCESS) {
895                         DEBUG(0,("Failed to setup an ldap connection timeout %d: %s\n",
896                                 ct, ldap_err2string(rc)));
897                 }
898         }
899 #elif defined (LDAP_OPT_NETWORK_TIMEOUT) /* OpenLDAP */
900         {
901                 struct timeval ct;
902                 ct.tv_usec = 0;
903                 ct.tv_sec = lp_ldap_connection_timeout();
904                 rc = ldap_set_option(*ldap_struct, LDAP_OPT_NETWORK_TIMEOUT, &ct);
905                 if (rc != LDAP_SUCCESS) {
906                         DEBUG(0,("Failed to setup an ldap connection timeout %d: %s\n",
907                                 (int)ct.tv_sec, ldap_err2string(rc)));
908                 }
909         }
910 #endif
911
912         return LDAP_SUCCESS;
913 }
914
915 /********************************************************************
916  try to upgrade to Version 3 LDAP if not already, in either case return current
917  version 
918  *******************************************************************/
919
920 static int smb_ldap_upgrade_conn(LDAP *ldap_struct, int *new_version)
921 {
922         int version;
923         int rc;
924
925         /* assume the worst */
926         *new_version = LDAP_VERSION2;
927
928         rc = ldap_get_option(ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
929         if (rc) {
930                 return rc;
931         }
932
933         if (version == LDAP_VERSION3) {
934                 *new_version = LDAP_VERSION3;
935                 return LDAP_SUCCESS;
936         }
937
938         /* try upgrade */
939         version = LDAP_VERSION3;
940         rc = ldap_set_option (ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
941         if (rc) {
942                 return rc;
943         }
944
945         *new_version = LDAP_VERSION3;
946         return LDAP_SUCCESS;
947 }
948
949 /*******************************************************************
950  open a connection to the ldap server (just until the bind)
951  ******************************************************************/
952
953 int smb_ldap_setup_full_conn(LDAP **ldap_struct, const char *uri)
954 {
955         int rc, version;
956
957         rc = smb_ldap_setup_conn(ldap_struct, uri);
958         if (rc) {
959                 return rc;
960         }
961
962         rc = smb_ldap_upgrade_conn(*ldap_struct, &version);
963         if (rc) {
964                 return rc;
965         }
966
967         rc = smb_ldap_start_tls(*ldap_struct, version);
968         if (rc) {
969                 return rc;
970         }
971
972         return LDAP_SUCCESS;
973 }
974
975 /*******************************************************************
976  open a connection to the ldap server.
977 ******************************************************************/
978 static int smbldap_open_connection (struct smbldap_state *ldap_state)
979
980 {
981         int rc = LDAP_SUCCESS;
982         int version;
983         int deref;
984         LDAP **ldap_struct = &ldap_state->ldap_struct;
985
986         rc = smb_ldap_setup_conn(ldap_struct, ldap_state->uri);
987         if (rc) {
988                 return rc;
989         }
990
991         /* Store the LDAP pointer in a lookup list */
992
993         smbldap_store_state(*ldap_struct, ldap_state);
994
995         /* Upgrade to LDAPv3 if possible */
996
997         rc = smb_ldap_upgrade_conn(*ldap_struct, &version);
998         if (rc) {
999                 return rc;
1000         }
1001
1002         /* Start TLS if required */
1003
1004         rc = smb_ldap_start_tls(*ldap_struct, version);
1005         if (rc) {
1006                 return rc;
1007         }
1008
1009         /* Set alias dereferencing method */
1010         deref = lp_ldap_deref();
1011         if (deref != -1) {
1012                 if (ldap_set_option (*ldap_struct, LDAP_OPT_DEREF, &deref) != LDAP_OPT_SUCCESS) {
1013                         DEBUG(1,("smbldap_open_connection: Failed to set dereferencing method: %d\n", deref));
1014                 } else {
1015                         DEBUG(5,("Set dereferencing method: %d\n", deref));
1016                 }
1017         }
1018
1019         DEBUG(2, ("smbldap_open_connection: connection opened\n"));
1020         return rc;
1021 }
1022
1023 /*******************************************************************
1024  a rebind function for authenticated referrals
1025  This version takes a void* that we can shove useful stuff in :-)
1026 ******************************************************************/
1027 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1028 #else
1029 static int rebindproc_with_state  (LDAP * ld, char **whop, char **credp, 
1030                                    int *methodp, int freeit, void *arg)
1031 {
1032         struct smbldap_state *ldap_state = arg;
1033         struct timespec ts;
1034
1035         /** @TODO Should we be doing something to check what servers we rebind to?
1036             Could we get a referral to a machine that we don't want to give our
1037             username and password to? */
1038
1039         if (freeit) {
1040                 SAFE_FREE(*whop);
1041                 if (*credp) {
1042                         memset(*credp, '\0', strlen(*credp));
1043                 }
1044                 SAFE_FREE(*credp);
1045         } else {
1046                 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n", 
1047                           ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
1048
1049                 if (ldap_state->anonymous) {
1050                         *whop = NULL;
1051                         *credp = NULL;
1052                 } else {
1053                         *whop = SMB_STRDUP(ldap_state->bind_dn);
1054                         if (!*whop) {
1055                                 return LDAP_NO_MEMORY;
1056                         }
1057                         *credp = SMB_STRDUP(ldap_state->bind_secret);
1058                         if (!*credp) {
1059                                 SAFE_FREE(*whop);
1060                                 return LDAP_NO_MEMORY;
1061                         }
1062                 }
1063                 *methodp = LDAP_AUTH_SIMPLE;
1064         }
1065
1066         clock_gettime_mono(&ts);
1067         ldap_state->last_rebind = convert_timespec_to_timeval(ts);
1068
1069         return 0;
1070 }
1071 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1072
1073 /*******************************************************************
1074  a rebind function for authenticated referrals
1075  This version takes a void* that we can shove useful stuff in :-)
1076  and actually does the connection.
1077 ******************************************************************/
1078 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1079 static int rebindproc_connect_with_state (LDAP *ldap_struct, 
1080                                           LDAP_CONST char *url, 
1081                                           ber_tag_t request,
1082                                           ber_int_t msgid, void *arg)
1083 {
1084         struct smbldap_state *ldap_state =
1085                 (struct smbldap_state *)arg;
1086         int rc;
1087         struct timespec ts;
1088         int version;
1089
1090         DEBUG(5,("rebindproc_connect_with_state: Rebinding to %s as \"%s\"\n", 
1091                  url, ldap_state->bind_dn?ldap_state->bind_dn:"[Anonymous bind]"));
1092
1093         /* call START_TLS again (ldaps:// is handled by the OpenLDAP library
1094          * itself) before rebinding to another LDAP server to avoid to expose
1095          * our credentials. At least *try* to secure the connection - Guenther */
1096
1097         smb_ldap_upgrade_conn(ldap_struct, &version);
1098         smb_ldap_start_tls(ldap_struct, version);
1099
1100         /** @TODO Should we be doing something to check what servers we rebind to?
1101             Could we get a referral to a machine that we don't want to give our
1102             username and password to? */
1103
1104         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
1105
1106         /* only set the last rebind timestamp when we did rebind after a
1107          * non-read LDAP operation. That way we avoid the replication sleep
1108          * after a simple redirected search operation - Guenther */
1109
1110         switch (request) {
1111
1112                 case LDAP_REQ_MODIFY:
1113                 case LDAP_REQ_ADD:
1114                 case LDAP_REQ_DELETE:
1115                 case LDAP_REQ_MODDN:
1116                 case LDAP_REQ_EXTENDED:
1117                         DEBUG(10,("rebindproc_connect_with_state: "
1118                                 "setting last_rebind timestamp "
1119                                 "(req: 0x%02x)\n", (unsigned int)request));
1120                         clock_gettime_mono(&ts);
1121                         ldap_state->last_rebind = convert_timespec_to_timeval(ts);
1122                         break;
1123                 default:
1124                         ZERO_STRUCT(ldap_state->last_rebind);
1125                         break;
1126         }
1127
1128         return rc;
1129 }
1130 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1131
1132 /*******************************************************************
1133  Add a rebind function for authenticated referrals
1134 ******************************************************************/
1135 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1136 #else
1137 # if LDAP_SET_REBIND_PROC_ARGS == 2
1138 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
1139                        int *method, int freeit )
1140 {
1141         struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
1142
1143         return rebindproc_with_state(ldap_struct, whop, credp,
1144                                      method, freeit, ldap_state);
1145 }
1146 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
1147 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1148
1149 /*******************************************************************
1150  a rebind function for authenticated referrals
1151  this also does the connection, but no void*.
1152 ******************************************************************/
1153 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1154 # if LDAP_SET_REBIND_PROC_ARGS == 2
1155 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
1156                                ber_int_t msgid)
1157 {
1158         struct smbldap_state *ldap_state = smbldap_find_state(ld);
1159
1160         return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid, 
1161                                              ldap_state);
1162 }
1163 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
1164 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1165
1166 /*******************************************************************
1167  connect to the ldap server under system privilege.
1168 ******************************************************************/
1169 static int smbldap_connect_system(struct smbldap_state *ldap_state)
1170 {
1171         LDAP *ldap_struct = ldap_state->ldap_struct;
1172         int rc;
1173         int version;
1174
1175         if (!ldap_state->anonymous && !ldap_state->bind_dn) {
1176                 char *bind_dn = NULL;
1177                 char *bind_secret = NULL;
1178
1179                 /* get the default dn and password only if they are not set already */
1180                 if (!fetch_ldap_pw(&bind_dn, &bind_secret)) {
1181                         DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
1182                         rc = LDAP_INVALID_CREDENTIALS;
1183                         goto done;
1184                 }
1185                 smbldap_set_creds(ldap_state, false, bind_dn, bind_secret);
1186                 SAFE_FREE(bind_dn);
1187                 memset(bind_secret, '\0', strlen(bind_secret));
1188                 SAFE_FREE(bind_secret);
1189         }
1190
1191         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
1192            (OpenLDAP) doesnt' seem to support it */
1193
1194         DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
1195                   ldap_state->uri, ldap_state->bind_dn));
1196
1197 #ifdef HAVE_LDAP_SET_REBIND_PROC
1198 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
1199 # if LDAP_SET_REBIND_PROC_ARGS == 2     
1200         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect); 
1201 # endif
1202 # if LDAP_SET_REBIND_PROC_ARGS == 3     
1203         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);  
1204 # endif
1205 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1206 # if LDAP_SET_REBIND_PROC_ARGS == 2     
1207         ldap_set_rebind_proc(ldap_struct, &rebindproc); 
1208 # endif
1209 # if LDAP_SET_REBIND_PROC_ARGS == 3     
1210         ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);  
1211 # endif
1212 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
1213 #endif
1214
1215         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
1216
1217         if (rc != LDAP_SUCCESS) {
1218                 char *ld_error = NULL;
1219                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1220                                 &ld_error);
1221                 DEBUG(ldap_state->num_failures ? 2 : 0,
1222                       ("failed to bind to server %s with dn=\"%s\" Error: %s\n\t%s\n",
1223                                ldap_state->uri,
1224                                ldap_state->bind_dn ? ldap_state->bind_dn : "[Anonymous bind]",
1225                                ldap_err2string(rc),
1226                                ld_error ? ld_error : "(unknown)"));
1227                 SAFE_FREE(ld_error);
1228                 ldap_state->num_failures++;
1229                 goto done;
1230         }
1231
1232         ldap_state->num_failures = 0;
1233         ldap_state->paged_results = False;
1234
1235         ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version);
1236
1237         if (smbldap_has_control(ldap_state->ldap_struct, ADS_PAGE_CTL_OID) && version == 3) {
1238                 ldap_state->paged_results = True;
1239         }
1240
1241         DEBUG(3, ("ldap_connect_system: successful connection to the LDAP server\n"));
1242         DEBUGADD(10, ("ldap_connect_system: LDAP server %s support paged results\n", 
1243                 ldap_state->paged_results ? "does" : "does not"));
1244 done:
1245         if (rc != 0) {
1246                 ldap_unbind(ldap_struct);
1247                 ldap_state->ldap_struct = NULL;
1248         }
1249         return rc;
1250 }
1251
1252 static void smbldap_idle_fn(struct event_context *event_ctx,
1253                             struct timed_event *te,
1254                             struct timeval now_abs,
1255                             void *private_data);
1256
1257 /**********************************************************************
1258  Connect to LDAP server (called before every ldap operation)
1259 *********************************************************************/
1260 static int smbldap_open(struct smbldap_state *ldap_state)
1261 {
1262         int rc, opt_rc;
1263         bool reopen = False;
1264         SMB_ASSERT(ldap_state);
1265
1266         if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time_mono(NULL))) {
1267
1268 #ifdef HAVE_UNIXSOCKET
1269                 struct sockaddr_un addr;
1270 #else
1271                 struct sockaddr addr;
1272 #endif
1273                 socklen_t len = sizeof(addr);
1274                 int sd;
1275
1276                 opt_rc = ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd);
1277                 if (opt_rc == 0 && (getpeername(sd, (struct sockaddr *) &addr, &len)) < 0 )
1278                         reopen = True;
1279
1280 #ifdef HAVE_UNIXSOCKET
1281                 if (opt_rc == 0 && addr.sun_family == AF_UNIX)
1282                         reopen = True;
1283 #endif
1284                 if (reopen) {
1285                         /* the other end has died. reopen. */
1286                         ldap_unbind(ldap_state->ldap_struct);
1287                         ldap_state->ldap_struct = NULL;
1288                         ldap_state->last_ping = (time_t)0;
1289                 } else {
1290                         ldap_state->last_ping = time_mono(NULL);
1291                 } 
1292         }
1293
1294         if (ldap_state->ldap_struct != NULL) {
1295                 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
1296                 return LDAP_SUCCESS;
1297         }
1298
1299         if ((rc = smbldap_open_connection(ldap_state))) {
1300                 return rc;
1301         }
1302
1303         if ((rc = smbldap_connect_system(ldap_state))) {
1304                 return rc;
1305         }
1306
1307
1308         ldap_state->last_ping = time_mono(NULL);
1309         ldap_state->pid = sys_getpid();
1310
1311         TALLOC_FREE(ldap_state->idle_event);
1312
1313         if (ldap_state->event_context != NULL) {
1314                 ldap_state->idle_event = event_add_timed(
1315                         ldap_state->event_context, ldap_state,
1316                         timeval_current_ofs(SMBLDAP_IDLE_TIME, 0),
1317                         smbldap_idle_fn, ldap_state);
1318         }
1319
1320         DEBUG(4,("The LDAP server is successfully connected\n"));
1321
1322         return LDAP_SUCCESS;
1323 }
1324
1325 /**********************************************************************
1326 Disconnect from LDAP server 
1327 *********************************************************************/
1328 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
1329 {
1330         if (!ldap_state)
1331                 return NT_STATUS_INVALID_PARAMETER;
1332
1333         if (ldap_state->ldap_struct != NULL) {
1334                 ldap_unbind(ldap_state->ldap_struct);
1335                 ldap_state->ldap_struct = NULL;
1336         }
1337
1338         smbldap_delete_state(ldap_state);
1339
1340         TALLOC_FREE(ldap_state->idle_event);
1341
1342         DEBUG(5,("The connection to the LDAP server was closed\n"));
1343         /* maybe free the results here --metze */
1344
1345         return NT_STATUS_OK;
1346 }
1347
1348 static SIG_ATOMIC_T got_alarm;
1349
1350 static void gotalarm_sig(int dummy)
1351 {
1352         got_alarm = 1;
1353 }
1354
1355 static time_t calc_ldap_abs_endtime(int ldap_to)
1356 {
1357         if (ldap_to == 0) {
1358                 /* No timeout - don't
1359                    return a value for
1360                    the alarm. */
1361                 return (time_t)0;
1362         }
1363
1364         /* Make the alarm time one second beyond
1365            the timout we're setting for the
1366            remote search timeout, to allow that
1367            to fire in preference. */
1368
1369         return time_mono(NULL)+ldap_to+1;
1370 }
1371
1372 static int end_ldap_local_alarm(time_t absolute_endtime, int rc)
1373 {
1374         if (absolute_endtime) {
1375                 alarm(0);
1376                 CatchSignal(SIGALRM, SIG_IGN);
1377                 if (got_alarm) {
1378                         /* Client timeout error code. */
1379                         got_alarm = 0;
1380                         return LDAP_TIMEOUT;
1381                 }
1382         }
1383         return rc;
1384 }
1385
1386 static void setup_ldap_local_alarm(struct smbldap_state *ldap_state, time_t absolute_endtime)
1387 {
1388         time_t now = time_mono(NULL);
1389
1390         if (absolute_endtime) {
1391                 got_alarm = 0;
1392                 CatchSignal(SIGALRM, gotalarm_sig);
1393                 alarm(absolute_endtime - now);
1394         }
1395
1396         if (ldap_state->pid != sys_getpid()) {
1397                 smbldap_close(ldap_state);
1398         }
1399 }
1400
1401 static int another_ldap_try(struct smbldap_state *ldap_state, int *rc,
1402                             int *attempts, time_t abs_endtime)
1403 {
1404         time_t now = time_mono(NULL);
1405         int open_rc = LDAP_SERVER_DOWN;
1406
1407         if (*rc != LDAP_SERVER_DOWN)
1408                 goto no_next;
1409
1410         if (abs_endtime && now >= abs_endtime) {
1411                 smbldap_close(ldap_state);
1412                 *rc = LDAP_TIMEOUT;
1413                 goto no_next;
1414         }
1415
1416         while (1) {
1417
1418                 if (*attempts != 0)
1419                         smb_msleep(1000);
1420
1421                 *attempts += 1;
1422
1423                 open_rc = smbldap_open(ldap_state);
1424
1425                 if (open_rc == LDAP_SUCCESS) {
1426                         ldap_state->last_use = now;
1427                         return True;
1428                 }
1429
1430                 if (open_rc == LDAP_INSUFFICIENT_ACCESS) {
1431                         /* The fact that we are non-root or any other
1432                          * access-denied condition will not change in the next
1433                          * round of trying */
1434                         *rc = open_rc;
1435                         break;
1436                 }
1437
1438                 if (got_alarm) {
1439                         *rc = LDAP_TIMEOUT;
1440                         break;
1441                 }
1442
1443                 if (open_rc != LDAP_SUCCESS) {
1444                         DEBUG(1, ("Connection to LDAP server failed for the "
1445                                   "%d try!\n", *attempts));
1446                 }
1447         }
1448
1449  no_next:
1450         ldap_state->last_use = now;
1451         return False;
1452 }
1453
1454 /*********************************************************************
1455  ********************************************************************/
1456
1457 static int smbldap_search_ext(struct smbldap_state *ldap_state,
1458                               const char *base, int scope, const char *filter, 
1459                               const char *attrs[], int attrsonly,
1460                               LDAPControl **sctrls, LDAPControl **cctrls, 
1461                               int sizelimit, LDAPMessage **res)
1462 {
1463         int             rc = LDAP_SERVER_DOWN;
1464         int             attempts = 0;
1465         char           *utf8_filter;
1466         int             to = lp_ldap_timeout();
1467         time_t          abs_endtime = calc_ldap_abs_endtime(to);
1468         struct          timeval timeout;
1469         struct          timeval *timeout_ptr = NULL;
1470         size_t          converted_size;
1471
1472         SMB_ASSERT(ldap_state);
1473
1474         DEBUG(5,("smbldap_search_ext: base => [%s], filter => [%s], "
1475                  "scope => [%d]\n", base, filter, scope));
1476
1477         if (ldap_state->last_rebind.tv_sec > 0) {
1478                 struct timeval  tval;
1479                 struct timespec ts;
1480                 int64_t tdiff = 0;
1481                 int             sleep_time = 0;
1482
1483                 clock_gettime_mono(&ts);
1484                 tval = convert_timespec_to_timeval(ts);
1485
1486                 tdiff = usec_time_diff(&tval, &ldap_state->last_rebind);
1487                 tdiff /= 1000; /* Convert to milliseconds. */
1488
1489                 sleep_time = lp_ldap_replication_sleep()-(int)tdiff;
1490                 sleep_time = MIN(sleep_time, MAX_LDAP_REPLICATION_SLEEP_TIME);
1491
1492                 if (sleep_time > 0) {
1493                         /* we wait for the LDAP replication */
1494                         DEBUG(5,("smbldap_search_ext: waiting %d milliseconds "
1495                                  "for LDAP replication.\n",sleep_time));
1496                         smb_msleep(sleep_time);
1497                         DEBUG(5,("smbldap_search_ext: go on!\n"));
1498                 }
1499                 ZERO_STRUCT(ldap_state->last_rebind);
1500         }
1501
1502         if (!push_utf8_talloc(talloc_tos(), &utf8_filter, filter, &converted_size)) {
1503                 return LDAP_NO_MEMORY;
1504         }
1505
1506         /* Setup remote timeout for the ldap_search_ext_s call. */
1507         if (to) {
1508                 timeout.tv_sec = to;
1509                 timeout.tv_usec = 0;
1510                 timeout_ptr = &timeout;
1511         }
1512
1513         setup_ldap_local_alarm(ldap_state, abs_endtime);
1514
1515         while (another_ldap_try(ldap_state, &rc, &attempts, abs_endtime)) {
1516                 rc = ldap_search_ext_s(ldap_state->ldap_struct, base, scope, 
1517                                        utf8_filter,
1518                                        discard_const_p(char *, attrs),
1519                                        attrsonly, sctrls, cctrls, timeout_ptr,
1520                                        sizelimit, res);
1521                 if (rc != LDAP_SUCCESS) {
1522                         char *ld_error = NULL;
1523                         int ld_errno;
1524
1525                         ldap_get_option(ldap_state->ldap_struct,
1526                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1527
1528                         ldap_get_option(ldap_state->ldap_struct,
1529                                         LDAP_OPT_ERROR_STRING, &ld_error);
1530                         DEBUG(10, ("Failed search for base: %s, error: %d (%s) "
1531                                    "(%s)\n", base, ld_errno,
1532                                    ldap_err2string(rc),
1533                                    ld_error ? ld_error : "unknown"));
1534                         SAFE_FREE(ld_error);
1535
1536                         if (ld_errno == LDAP_SERVER_DOWN) {
1537                                 ldap_unbind(ldap_state->ldap_struct);
1538                                 ldap_state->ldap_struct = NULL;
1539                         }
1540                 }
1541         }
1542
1543         TALLOC_FREE(utf8_filter);
1544         return end_ldap_local_alarm(abs_endtime, rc);
1545 }
1546
1547 int smbldap_search(struct smbldap_state *ldap_state, 
1548                    const char *base, int scope, const char *filter, 
1549                    const char *attrs[], int attrsonly, 
1550                    LDAPMessage **res)
1551 {
1552         return smbldap_search_ext(ldap_state, base, scope, filter, attrs,
1553                                   attrsonly, NULL, NULL, LDAP_NO_LIMIT, res);
1554 }
1555
1556 int smbldap_search_paged(struct smbldap_state *ldap_state, 
1557                          const char *base, int scope, const char *filter, 
1558                          const char **attrs, int attrsonly, int pagesize,
1559                          LDAPMessage **res, void **cookie)
1560 {
1561         LDAPControl     pr;
1562         LDAPControl     **rcontrols;
1563         LDAPControl     *controls[2] = { NULL, NULL};
1564         BerElement      *cookie_be = NULL;
1565         struct berval   *cookie_bv = NULL;
1566         int             tmp = 0, i, rc;
1567         bool            critical = True;
1568
1569         *res = NULL;
1570
1571         DEBUG(3,("smbldap_search_paged: base => [%s], filter => [%s],"
1572                  "scope => [%d], pagesize => [%d]\n",
1573                  base, filter, scope, pagesize));
1574
1575         cookie_be = ber_alloc_t(LBER_USE_DER);
1576         if (cookie_be == NULL) {
1577                 DEBUG(0,("smbldap_create_page_control: ber_alloc_t returns "
1578                          "NULL\n"));
1579                 return LDAP_NO_MEMORY;
1580         }
1581
1582         /* construct cookie */
1583         if (*cookie != NULL) {
1584                 ber_printf(cookie_be, "{iO}", (ber_int_t) pagesize, *cookie);
1585                 ber_bvfree((struct berval *)*cookie); /* don't need it from last time */
1586                 *cookie = NULL;
1587         } else {
1588                 ber_printf(cookie_be, "{io}", (ber_int_t) pagesize, "", 0);
1589         }
1590         ber_flatten(cookie_be, &cookie_bv);
1591
1592         pr.ldctl_oid = discard_const_p(char, ADS_PAGE_CTL_OID);
1593         pr.ldctl_iscritical = (char) critical;
1594         pr.ldctl_value.bv_len = cookie_bv->bv_len;
1595         pr.ldctl_value.bv_val = cookie_bv->bv_val;
1596
1597         controls[0] = &pr;
1598         controls[1] = NULL;
1599
1600         rc = smbldap_search_ext(ldap_state, base, scope, filter, attrs, 
1601                                  0, controls, NULL, LDAP_NO_LIMIT, res);
1602
1603         ber_free(cookie_be, 1);
1604         ber_bvfree(cookie_bv);
1605
1606         if (rc != 0) {
1607                 DEBUG(3,("smbldap_search_paged: smbldap_search_ext(%s) "
1608                          "failed with [%s]\n", filter, ldap_err2string(rc)));
1609                 goto done;
1610         }
1611
1612         DEBUG(3,("smbldap_search_paged: search was successful\n"));
1613
1614         rc = ldap_parse_result(ldap_state->ldap_struct, *res, NULL, NULL, 
1615                                NULL, NULL, &rcontrols,  0);
1616         if (rc != 0) {
1617                 DEBUG(3,("smbldap_search_paged: ldap_parse_result failed " \
1618                          "with [%s]\n", ldap_err2string(rc)));
1619                 goto done;
1620         }
1621
1622         if (rcontrols == NULL)
1623                 goto done;
1624
1625         for (i=0; rcontrols[i]; i++) {
1626
1627                 if (strcmp(ADS_PAGE_CTL_OID, rcontrols[i]->ldctl_oid) != 0)
1628                         continue;
1629
1630                 cookie_be = ber_init(&rcontrols[i]->ldctl_value);
1631                 ber_scanf(cookie_be,"{iO}", &tmp, &cookie_bv);
1632                 /* the berval is the cookie, but must be freed when it is all
1633                    done */
1634                 if (cookie_bv->bv_len)
1635                         *cookie=ber_bvdup(cookie_bv);
1636                 else
1637                         *cookie=NULL;
1638                 ber_bvfree(cookie_bv);
1639                 ber_free(cookie_be, 1);
1640                 break;
1641         }
1642         ldap_controls_free(rcontrols);
1643 done:   
1644         return rc;
1645 }
1646
1647 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1648 {
1649         int             rc = LDAP_SERVER_DOWN;
1650         int             attempts = 0;
1651         char           *utf8_dn;
1652         time_t          abs_endtime = calc_ldap_abs_endtime(lp_ldap_timeout());
1653         size_t          converted_size;
1654
1655         SMB_ASSERT(ldap_state);
1656
1657         DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
1658
1659         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1660                 return LDAP_NO_MEMORY;
1661         }
1662
1663         setup_ldap_local_alarm(ldap_state, abs_endtime);
1664
1665         while (another_ldap_try(ldap_state, &rc, &attempts, abs_endtime)) {
1666                 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
1667                 if (rc != LDAP_SUCCESS) {
1668                         char *ld_error = NULL;
1669                         int ld_errno;
1670
1671                         ldap_get_option(ldap_state->ldap_struct,
1672                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1673
1674                         ldap_get_option(ldap_state->ldap_struct,
1675                                         LDAP_OPT_ERROR_STRING, &ld_error);
1676                         DEBUG(10, ("Failed to modify dn: %s, error: %d (%s) "
1677                                    "(%s)\n", dn, ld_errno,
1678                                    ldap_err2string(rc),
1679                                    ld_error ? ld_error : "unknown"));
1680                         SAFE_FREE(ld_error);
1681
1682                         if (ld_errno == LDAP_SERVER_DOWN) {
1683                                 ldap_unbind(ldap_state->ldap_struct);
1684                                 ldap_state->ldap_struct = NULL;
1685                         }
1686                 }
1687         }
1688
1689         TALLOC_FREE(utf8_dn);
1690         return end_ldap_local_alarm(abs_endtime, rc);
1691 }
1692
1693 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1694 {
1695         int             rc = LDAP_SERVER_DOWN;
1696         int             attempts = 0;
1697         char           *utf8_dn;
1698         time_t          abs_endtime = calc_ldap_abs_endtime(lp_ldap_timeout());
1699         size_t          converted_size;
1700
1701         SMB_ASSERT(ldap_state);
1702
1703         DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1704
1705         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1706                 return LDAP_NO_MEMORY;
1707         }
1708
1709         setup_ldap_local_alarm(ldap_state, abs_endtime);
1710
1711         while (another_ldap_try(ldap_state, &rc, &attempts, abs_endtime)) {
1712                 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1713                 if (rc != LDAP_SUCCESS) {
1714                         char *ld_error = NULL;
1715                         int ld_errno;
1716
1717                         ldap_get_option(ldap_state->ldap_struct,
1718                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1719
1720                         ldap_get_option(ldap_state->ldap_struct,
1721                                         LDAP_OPT_ERROR_STRING, &ld_error);
1722                         DEBUG(10, ("Failed to add dn: %s, error: %d (%s) "
1723                                    "(%s)\n", dn, ld_errno,
1724                                    ldap_err2string(rc),
1725                                    ld_error ? ld_error : "unknown"));
1726                         SAFE_FREE(ld_error);
1727
1728                         if (ld_errno == LDAP_SERVER_DOWN) {
1729                                 ldap_unbind(ldap_state->ldap_struct);
1730                                 ldap_state->ldap_struct = NULL;
1731                         }
1732                 }
1733         }
1734
1735         TALLOC_FREE(utf8_dn);
1736         return end_ldap_local_alarm(abs_endtime, rc);
1737 }
1738
1739 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1740 {
1741         int             rc = LDAP_SERVER_DOWN;
1742         int             attempts = 0;
1743         char           *utf8_dn;
1744         time_t          abs_endtime = calc_ldap_abs_endtime(lp_ldap_timeout());
1745         size_t          converted_size;
1746
1747         SMB_ASSERT(ldap_state);
1748
1749         DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1750
1751         if (!push_utf8_talloc(talloc_tos(), &utf8_dn, dn, &converted_size)) {
1752                 return LDAP_NO_MEMORY;
1753         }
1754
1755         setup_ldap_local_alarm(ldap_state, abs_endtime);
1756
1757         while (another_ldap_try(ldap_state, &rc, &attempts, abs_endtime)) {
1758                 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1759                 if (rc != LDAP_SUCCESS) {
1760                         char *ld_error = NULL;
1761                         int ld_errno;
1762
1763                         ldap_get_option(ldap_state->ldap_struct,
1764                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1765
1766                         ldap_get_option(ldap_state->ldap_struct,
1767                                         LDAP_OPT_ERROR_STRING, &ld_error);
1768                         DEBUG(10, ("Failed to delete dn: %s, error: %d (%s) "
1769                                    "(%s)\n", dn, ld_errno,
1770                                    ldap_err2string(rc),
1771                                    ld_error ? ld_error : "unknown"));
1772                         SAFE_FREE(ld_error);
1773
1774                         if (ld_errno == LDAP_SERVER_DOWN) {
1775                                 ldap_unbind(ldap_state->ldap_struct);
1776                                 ldap_state->ldap_struct = NULL;
1777                         }
1778                 }
1779         }
1780
1781         TALLOC_FREE(utf8_dn);
1782         return end_ldap_local_alarm(abs_endtime, rc);
1783 }
1784
1785 int smbldap_extended_operation(struct smbldap_state *ldap_state, 
1786                                LDAP_CONST char *reqoid, struct berval *reqdata, 
1787                                LDAPControl **serverctrls, LDAPControl **clientctrls, 
1788                                char **retoidp, struct berval **retdatap)
1789 {
1790         int             rc = LDAP_SERVER_DOWN;
1791         int             attempts = 0;
1792         time_t          abs_endtime = calc_ldap_abs_endtime(lp_ldap_timeout());
1793
1794         if (!ldap_state)
1795                 return (-1);
1796
1797         setup_ldap_local_alarm(ldap_state, abs_endtime);
1798
1799         while (another_ldap_try(ldap_state, &rc, &attempts, abs_endtime)) {
1800                 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid,
1801                                                reqdata, serverctrls,
1802                                                clientctrls, retoidp, retdatap);
1803                 if (rc != LDAP_SUCCESS) {
1804                         char *ld_error = NULL;
1805                         int ld_errno;
1806
1807                         ldap_get_option(ldap_state->ldap_struct,
1808                                         LDAP_OPT_ERROR_NUMBER, &ld_errno);
1809
1810                         ldap_get_option(ldap_state->ldap_struct,
1811                                         LDAP_OPT_ERROR_STRING, &ld_error);
1812                         DEBUG(10, ("Extended operation failed with error: "
1813                                    "%d (%s) (%s)\n", ld_errno,
1814                                    ldap_err2string(rc),
1815                                    ld_error ? ld_error : "unknown"));
1816                         SAFE_FREE(ld_error);
1817
1818                         if (ld_errno == LDAP_SERVER_DOWN) {
1819                                 ldap_unbind(ldap_state->ldap_struct);
1820                                 ldap_state->ldap_struct = NULL;
1821                         }
1822                 }
1823         }
1824
1825         return end_ldap_local_alarm(abs_endtime, rc);
1826 }
1827
1828 /*******************************************************************
1829  run the search by name.
1830 ******************************************************************/
1831 int smbldap_search_suffix (struct smbldap_state *ldap_state,
1832                            const char *filter, const char **search_attr,
1833                            LDAPMessage ** result)
1834 {
1835         return smbldap_search(ldap_state, lp_ldap_suffix(), LDAP_SCOPE_SUBTREE,
1836                               filter, search_attr, 0, result);
1837 }
1838
1839 static void smbldap_idle_fn(struct event_context *event_ctx,
1840                             struct timed_event *te,
1841                             struct timeval now_abs,
1842                             void *private_data)
1843 {
1844         struct smbldap_state *state = (struct smbldap_state *)private_data;
1845
1846         TALLOC_FREE(state->idle_event);
1847
1848         if (state->ldap_struct == NULL) {
1849                 DEBUG(10,("ldap connection not connected...\n"));
1850                 return;
1851         }
1852
1853         if ((state->last_use+SMBLDAP_IDLE_TIME) > time_mono(NULL)) {
1854                 DEBUG(10,("ldap connection not idle...\n"));
1855
1856                 /* this needs to be made monotonic clock aware inside tevent: */
1857                 state->idle_event = event_add_timed(
1858                         event_ctx, state,
1859                         timeval_add(&now_abs, SMBLDAP_IDLE_TIME, 0),
1860                         smbldap_idle_fn,
1861                         private_data);
1862                 return;
1863         }
1864
1865         DEBUG(7,("ldap connection idle...closing connection\n"));
1866         smbldap_close(state);
1867 }
1868
1869 /**********************************************************************
1870  Housekeeping
1871  *********************************************************************/
1872
1873 void smbldap_free_struct(struct smbldap_state **ldap_state) 
1874 {
1875         smbldap_close(*ldap_state);
1876
1877         if ((*ldap_state)->bind_secret) {
1878                 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1879         }
1880
1881         SAFE_FREE((*ldap_state)->bind_dn);
1882         SAFE_FREE((*ldap_state)->bind_secret);
1883
1884         TALLOC_FREE(*ldap_state);
1885
1886         /* No need to free any further, as it is talloc()ed */
1887 }
1888
1889 static int smbldap_state_destructor(struct smbldap_state *state)
1890 {
1891         smbldap_free_struct(&state);
1892         return 0;
1893 }
1894
1895
1896 /**********************************************************************
1897  Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1898  *********************************************************************/
1899
1900 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, struct event_context *event_ctx,
1901                       const char *location,
1902                       struct smbldap_state **smbldap_state)
1903 {
1904         *smbldap_state = talloc_zero(mem_ctx, struct smbldap_state);
1905         if (!*smbldap_state) {
1906                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1907                 return NT_STATUS_NO_MEMORY;
1908         }
1909
1910         if (location) {
1911                 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1912         } else {
1913                 (*smbldap_state)->uri = "ldap://localhost";
1914         }
1915
1916         (*smbldap_state)->event_context = event_ctx;
1917
1918         talloc_set_destructor(*smbldap_state, smbldap_state_destructor);
1919         return NT_STATUS_OK;
1920 }
1921
1922  char *smbldap_talloc_dn(TALLOC_CTX *mem_ctx, LDAP *ld,
1923                          LDAPMessage *entry)
1924 {
1925         char *utf8_dn, *unix_dn;
1926         size_t converted_size;
1927
1928         utf8_dn = ldap_get_dn(ld, entry);
1929         if (!utf8_dn) {
1930                 DEBUG (5, ("smbldap_talloc_dn: ldap_get_dn failed\n"));
1931                 return NULL;
1932         }
1933         if (!pull_utf8_talloc(mem_ctx, &unix_dn, utf8_dn, &converted_size)) {
1934                 DEBUG (0, ("smbldap_talloc_dn: String conversion failure utf8 "
1935                            "[%s]\n", utf8_dn));
1936                 return NULL;
1937         }
1938         ldap_memfree(utf8_dn);
1939         return unix_dn;
1940 }
1941
1942 /*******************************************************************
1943  Check if root-dse has a certain Control or Extension
1944 ********************************************************************/
1945
1946 static bool smbldap_check_root_dse(LDAP *ld, const char **attrs, const char *value) 
1947 {
1948         LDAPMessage *msg = NULL;
1949         LDAPMessage *entry = NULL;
1950         char **values = NULL;
1951         int rc, num_result, num_values, i;
1952         bool result = False;
1953
1954         if (!attrs[0]) {
1955                 DEBUG(3,("smbldap_check_root_dse: nothing to look for\n"));
1956                 return False;
1957         }
1958
1959         if (!strequal(attrs[0], "supportedExtension") && 
1960             !strequal(attrs[0], "supportedControl") && 
1961             !strequal(attrs[0], "namingContexts")) {
1962                 DEBUG(3,("smbldap_check_root_dse: no idea what to query root-dse for: %s ?\n", attrs[0]));
1963                 return False;
1964         }
1965
1966         rc = ldap_search_s(ld, "", LDAP_SCOPE_BASE, 
1967                            "(objectclass=*)", discard_const_p(char *, attrs), 0 , &msg);
1968
1969         if (rc != LDAP_SUCCESS) {
1970                 DEBUG(3,("smbldap_check_root_dse: Could not search rootDSE\n"));
1971                 return False;
1972         }
1973
1974         num_result = ldap_count_entries(ld, msg);
1975
1976         if (num_result != 1) {
1977                 DEBUG(3,("smbldap_check_root_dse: Expected one rootDSE, got %d\n", num_result));
1978                 goto done;
1979         }
1980
1981         entry = ldap_first_entry(ld, msg);
1982
1983         if (entry == NULL) {
1984                 DEBUG(3,("smbldap_check_root_dse: Could not retrieve rootDSE\n"));
1985                 goto done;
1986         }
1987
1988         values = ldap_get_values(ld, entry, attrs[0]);
1989
1990         if (values == NULL) {
1991                 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not support any %s\n", attrs[0]));
1992                 goto done;
1993         }
1994
1995         num_values = ldap_count_values(values);
1996
1997         if (num_values == 0) {
1998                 DEBUG(5,("smbldap_check_root_dse: LDAP Server does not have any %s\n", attrs[0]));
1999                 goto done;
2000         }
2001
2002         for (i=0; i<num_values; i++) {
2003                 if (strcmp(values[i], value) == 0)
2004                         result = True;
2005         }
2006
2007
2008  done:
2009         if (values != NULL)
2010                 ldap_value_free(values);
2011         if (msg != NULL)
2012                 ldap_msgfree(msg);
2013
2014         return result;
2015
2016 }
2017
2018 /*******************************************************************
2019  Check if LDAP-Server supports a certain Control (OID in string format)
2020 ********************************************************************/
2021
2022 bool smbldap_has_control(LDAP *ld, const char *control)
2023 {
2024         const char *attrs[] = { "supportedControl", NULL };
2025         return smbldap_check_root_dse(ld, attrs, control);
2026 }
2027
2028 /*******************************************************************
2029  Check if LDAP-Server supports a certain Extension (OID in string format)
2030 ********************************************************************/
2031
2032 bool smbldap_has_extension(LDAP *ld, const char *extension)
2033 {
2034         const char *attrs[] = { "supportedExtension", NULL };
2035         return smbldap_check_root_dse(ld, attrs, extension);
2036 }
2037
2038 /*******************************************************************
2039  Check if LDAP-Server holds a given namingContext
2040 ********************************************************************/
2041
2042 bool smbldap_has_naming_context(LDAP *ld, const char *naming_context)
2043 {
2044         const char *attrs[] = { "namingContexts", NULL };
2045         return smbldap_check_root_dse(ld, attrs, naming_context);
2046 }
2047
2048 bool smbldap_set_creds(struct smbldap_state *ldap_state, bool anon, const char *dn, const char *secret)
2049 {
2050         ldap_state->anonymous = anon;
2051
2052         /* free any previously set credential */
2053
2054         SAFE_FREE(ldap_state->bind_dn);
2055         if (ldap_state->bind_secret) {
2056                 /* make sure secrets are zeroed out of memory */
2057                 memset(ldap_state->bind_secret, '\0', strlen(ldap_state->bind_secret));
2058                 SAFE_FREE(ldap_state->bind_secret);
2059         }
2060
2061         if ( ! anon) {
2062                 ldap_state->bind_dn = SMB_STRDUP(dn);
2063                 ldap_state->bind_secret = SMB_STRDUP(secret);
2064         }
2065
2066         return True;
2067 }