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