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