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