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