Fixes to our LDAP/vampire codepaths:
[tprouty/samba.git] / source / lib / smbldap.c
1 /* 
2    Unix SMB/CIFS mplementation.
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
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
39 /* attributes used by Samba 2.2 */
40
41 ATTRIB_MAP_ENTRY attrib_map_v22[] = {
42         { LDAP_ATTR_UID,                "uid"           },
43         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
44         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
45         { LDAP_ATTR_UNIX_HOME,          "homeDirectory" },
46         { LDAP_ATTR_PWD_LAST_SET,       "pwdLastSet"    },
47         { LDAP_ATTR_PWD_CAN_CHANGE,     "pwdCanChange"  },
48         { LDAP_ATTR_PWD_MUST_CHANGE,    "pwdMustChange" },
49         { LDAP_ATTR_LOGON_TIME,         "logonTime"     },
50         { LDAP_ATTR_LOGOFF_TIME,        "logoffTime"    },
51         { LDAP_ATTR_KICKOFF_TIME,       "kickoffTime"   },
52         { LDAP_ATTR_CN,                 "cn"            },
53         { LDAP_ATTR_DISPLAY_NAME,       "displayName"   },
54         { LDAP_ATTR_HOME_PATH,          "smbHome"       },
55         { LDAP_ATTR_HOME_DRIVE,         "homeDrives"    },
56         { LDAP_ATTR_LOGON_SCRIPT,       "scriptPath"    },
57         { LDAP_ATTR_PROFILE_PATH,       "profilePath"   },
58         { LDAP_ATTR_DESC,               "description"   },
59         { LDAP_ATTR_USER_WKS,           "userWorkstations"},
60         { LDAP_ATTR_USER_RID,           "rid"           },
61         { LDAP_ATTR_PRIMARY_GROUP_RID,  "primaryGroupID"},
62         { LDAP_ATTR_LMPW,               "lmPassword"    },
63         { LDAP_ATTR_NTPW,               "ntPassword"    },
64         { LDAP_ATTR_DOMAIN,             "domain"        },
65         { LDAP_ATTR_OBJCLASS,           "objectClass"   },
66         { LDAP_ATTR_ACB_INFO,           "acctFlags"     },
67         { LDAP_ATTR_LIST_END,           NULL            }
68 };
69
70 /* attributes used by Samba 3.0's sambaSamAccount */
71
72 ATTRIB_MAP_ENTRY attrib_map_v30[] = {
73         { LDAP_ATTR_UID,                "uid"                   },
74         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
75         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
76         { LDAP_ATTR_UNIX_HOME,          "homeDirectory"         },
77         { LDAP_ATTR_PWD_LAST_SET,       "sambaPwdLastSet"       },
78         { LDAP_ATTR_PWD_CAN_CHANGE,     "sambaPwdCanChange"     },
79         { LDAP_ATTR_PWD_MUST_CHANGE,    "sambaPwdMustChange"    },
80         { LDAP_ATTR_LOGON_TIME,         "sambaLogonTime"        },
81         { LDAP_ATTR_LOGOFF_TIME,        "sambaLogoffTime"       },
82         { LDAP_ATTR_KICKOFF_TIME,       "sambaKickoffTime"      },
83         { LDAP_ATTR_CN,                 "cn"                    },
84         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
85         { LDAP_ATTR_HOME_DRIVE,         "sambaHomeDrive"        },
86         { LDAP_ATTR_HOME_PATH,          "sambaHomePath"         },
87         { LDAP_ATTR_LOGON_SCRIPT,       "sambaLogonScript"      },
88         { LDAP_ATTR_PROFILE_PATH,       "sambaProfilePath"      },
89         { LDAP_ATTR_DESC,               "description"           },
90         { LDAP_ATTR_USER_WKS,           "sambaUserWorkstations" },
91         { LDAP_ATTR_USER_SID,           LDAP_ATTRIBUTE_SID      },
92         { LDAP_ATTR_PRIMARY_GROUP_SID,  "sambaPrimaryGroupSID"  },
93         { LDAP_ATTR_LMPW,               "sambaLMPassword"       },
94         { LDAP_ATTR_NTPW,               "sambaNTPassword"       },
95         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
96         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
97         { LDAP_ATTR_ACB_INFO,           "sambaAcctFlags"        },
98         { LDAP_ATTR_LIST_END,           NULL                    }
99 };
100
101 /* attributes used for alalocating RIDs */
102
103 ATTRIB_MAP_ENTRY dominfo_attr_list[] = {
104         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
105         { LDAP_ATTR_NEXT_RID,           "sambaNextRid"          },
106         { LDAP_ATTR_NEXT_USERRID,       "sambaNextUserRid"      },
107         { LDAP_ATTR_NEXT_GROUPRID,      "sambaNextGroupRid"     },
108         { LDAP_ATTR_DOM_SID,            LDAP_ATTRIBUTE_SID      },
109         { LDAP_ATTR_ALGORITHMIC_RID_BASE,"sambaAlgorithmicRidBase"},
110         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
111         { LDAP_ATTR_LIST_END,           NULL                    },
112 };
113
114 /* Samba 3.0 group mapping attributes */
115
116 ATTRIB_MAP_ENTRY groupmap_attr_list[] = {
117         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
118         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
119         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
120         { LDAP_ATTR_DESC,               "description"           },
121         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
122         { LDAP_ATTR_CN,                 "cn"                    },
123         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
124         { LDAP_ATTR_LIST_END,           NULL                    }       
125 };
126
127 ATTRIB_MAP_ENTRY groupmap_attr_list_to_delete[] = {
128         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
129         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
130         { LDAP_ATTR_DESC,               "description"           },
131         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
132         { LDAP_ATTR_LIST_END,           NULL                    }       
133 };
134
135 /* idmap_ldap sambaUnixIdPool */
136
137 ATTRIB_MAP_ENTRY idpool_attr_list[] = {
138         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
139         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
140         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
141         { LDAP_ATTR_LIST_END,           NULL                    }       
142 };
143
144 ATTRIB_MAP_ENTRY sidmap_attr_list[] = {
145         { LDAP_ATTR_SID,                LDAP_ATTRIBUTE_SID      },
146         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
147         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
148         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
149         { LDAP_ATTR_LIST_END,           NULL                    }       
150 };
151
152 /**********************************************************************
153  perform a simple table lookup and return the attribute name 
154  **********************************************************************/
155  
156  const char* get_attr_key2string( ATTRIB_MAP_ENTRY table[], int key )
157 {
158         int i = 0;
159         
160         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
161                 if ( table[i].attrib == key )
162                         return table[i].name;
163                 i++;
164         }
165         
166         return NULL;
167 }
168
169
170 /**********************************************************************
171  Return the list of attribute names from a mapping table
172  **********************************************************************/
173
174  char** get_attr_list( ATTRIB_MAP_ENTRY table[] )
175 {
176         char **names;
177         int i = 0;
178         
179         while ( table[i].attrib != LDAP_ATTR_LIST_END )
180                 i++;
181         i++;
182
183         names = (char**)malloc( sizeof(char*)*i );
184         if ( !names ) {
185                 DEBUG(0,("get_attr_list: out of memory\n"));
186                 return NULL;
187         }
188
189         i = 0;
190         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
191                 names[i] = strdup( table[i].name );
192                 i++;
193         }
194         names[i] = NULL;
195         
196         return names;
197 }
198
199 /*********************************************************************
200  Cleanup 
201  ********************************************************************/
202
203  void free_attr_list( char **list )
204 {
205         int i = 0;
206
207         if ( !list )
208                 return; 
209
210         while ( list[i] )
211                 SAFE_FREE( list[i] );
212
213         SAFE_FREE( list );
214 }
215
216 /*******************************************************************
217  find the ldap password
218 ******************************************************************/
219 BOOL fetch_ldap_pw(char **dn, char** pw)
220 {
221         char *key = NULL;
222         size_t size;
223         
224         *dn = smb_xstrdup(lp_ldap_admin_dn());
225         
226         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, *dn) < 0) {
227                 SAFE_FREE(*dn);
228                 DEBUG(0, ("fetch_ldap_pw: asprintf failed!\n"));
229         }
230         
231         *pw=secrets_fetch(key, &size);
232         SAFE_FREE(key);
233
234         if (!size) {
235                 /* Upgrade 2.2 style entry */
236                 char *p;
237                 char* old_style_key = strdup(*dn);
238                 char *data;
239                 fstring old_style_pw;
240                 
241                 if (!old_style_key) {
242                         DEBUG(0, ("fetch_ldap_pw: strdup failed!\n"));
243                         return False;
244                 }
245
246                 for (p=old_style_key; *p; p++)
247                         if (*p == ',') *p = '/';
248         
249                 data=secrets_fetch(old_style_key, &size);
250                 if (!size && size < sizeof(old_style_pw)) {
251                         DEBUG(0,("fetch_ldap_pw: neither ldap secret retrieved!\n"));
252                         SAFE_FREE(old_style_key);
253                         SAFE_FREE(*dn);
254                         return False;
255                 }
256
257                 strncpy(old_style_pw, data, size);
258                 old_style_pw[size] = 0;
259
260                 SAFE_FREE(data);
261
262                 if (!secrets_store_ldap_pw(*dn, old_style_pw)) {
263                         DEBUG(0,("fetch_ldap_pw: ldap secret could not be upgraded!\n"));
264                         SAFE_FREE(old_style_key);
265                         SAFE_FREE(*dn);
266                         return False;                   
267                 }
268                 if (!secrets_delete(old_style_key)) {
269                         DEBUG(0,("fetch_ldap_pw: old ldap secret could not be deleted!\n"));
270                 }
271
272                 SAFE_FREE(old_style_key);
273
274                 *pw = smb_xstrdup(old_style_pw);                
275         }
276         
277         return True;
278 }
279
280 /*******************************************************************
281 search an attribute and return the first value found.
282 ******************************************************************/
283  BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
284                                    const char *attribute, pstring value)
285 {
286         char **values;
287         
288         if ( !attribute )
289                 return False;
290                 
291         value[0] = '\0';
292
293         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
294                 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
295                 
296                 return False;
297         }
298         
299         if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, sizeof(pstring)) == (size_t)-1)
300         {
301                 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n", 
302                           attribute, values[0]));
303                 ldap_value_free(values);
304                 return False;
305         }
306         
307         ldap_value_free(values);
308 #ifdef DEBUG_PASSWORDS
309         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
310 #endif  
311         return True;
312 }
313
314 /************************************************************************
315  Routine to manage the LDAPMod structure array
316  manage memory used by the array, by each struct, and values
317  ***********************************************************************/
318
319  void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
320 {
321         LDAPMod **mods;
322         int i;
323         int j;
324
325         mods = *modlist;
326
327         /* sanity checks on the mod values */
328
329         if (attribute == NULL || *attribute == '\0')
330                 return; 
331 #if 0   /* commented out after discussion with abartlet.  Do not reenable.
332            left here so other so re-add similar code   --jerry */
333         if (value == NULL || *value == '\0')
334                 return;
335 #endif
336
337         if (mods == NULL) 
338         {
339                 mods = (LDAPMod **) malloc(sizeof(LDAPMod *));
340                 if (mods == NULL)
341                 {
342                         DEBUG(0, ("make_a_mod: out of memory!\n"));
343                         return;
344                 }
345                 mods[0] = NULL;
346         }
347
348         for (i = 0; mods[i] != NULL; ++i) {
349                 if (mods[i]->mod_op == modop && !strcasecmp(mods[i]->mod_type, attribute))
350                         break;
351         }
352
353         if (mods[i] == NULL)
354         {
355                 mods = (LDAPMod **) Realloc (mods, (i + 2) * sizeof (LDAPMod *));
356                 if (mods == NULL)
357                 {
358                         DEBUG(0, ("make_a_mod: out of memory!\n"));
359                         return;
360                 }
361                 mods[i] = (LDAPMod *) malloc(sizeof(LDAPMod));
362                 if (mods[i] == NULL)
363                 {
364                         DEBUG(0, ("make_a_mod: out of memory!\n"));
365                         return;
366                 }
367                 mods[i]->mod_op = modop;
368                 mods[i]->mod_values = NULL;
369                 mods[i]->mod_type = strdup(attribute);
370                 mods[i + 1] = NULL;
371         }
372
373         if (value != NULL)
374         {
375                 char *utf8_value = NULL;
376
377                 j = 0;
378                 if (mods[i]->mod_values != NULL) {
379                         for (; mods[i]->mod_values[j] != NULL; j++);
380                 }
381                 mods[i]->mod_values = (char **)Realloc(mods[i]->mod_values,
382                                                (j + 2) * sizeof (char *));
383                                                
384                 if (mods[i]->mod_values == NULL) {
385                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
386                         return;
387                 }
388
389                 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
390                         DEBUG (0, ("make_a_mod: String conversion failure!\n"));
391                         return;
392                 }
393
394                 mods[i]->mod_values[j] = utf8_value;
395
396                 mods[i]->mod_values[j + 1] = NULL;
397         }
398         *modlist = mods;
399 }
400
401
402 /**********************************************************************
403   Set attribute to newval in LDAP, regardless of what value the
404   attribute had in LDAP before.
405 *********************************************************************/
406  void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
407                       LDAPMod ***mods,
408                       const char *attribute, const char *newval)
409 {
410         char **values = NULL;
411
412         if (existing != NULL) {
413                 values = ldap_get_values(ldap_struct, existing, attribute);
414         }
415
416         /* all of our string attributes are case insensitive */
417         
418         if ((values != NULL) && (values[0] != NULL) &&
419             StrCaseCmp(values[0], newval) == 0) 
420         {
421                 
422                 /* Believe it or not, but LDAP will deny a delete and
423                    an add at the same time if the values are the
424                    same... */
425
426                 ldap_value_free(values);
427                 return;
428         }
429
430         /* Regardless of the real operation (add or modify)
431            we add the new value here. We rely on deleting
432            the old value, should it exist. */
433
434         if ((newval != NULL) && (strlen(newval) > 0)) {
435                 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
436         }
437
438         if (values == NULL) {
439                 /* There has been no value before, so don't delete it.
440                    Here's a possible race: We might end up with
441                    duplicate attributes */
442                 return;
443         }
444
445         /* By deleting exactly the value we found in the entry this
446            should be race-free in the sense that the LDAP-Server will
447            deny the complete operation if somebody changed the
448            attribute behind our back. */
449
450         smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, values[0]);
451         ldap_value_free(values);
452 }
453
454
455 /**********************************************************************
456  Some varients of the LDAP rebind code do not pass in the third 'arg' 
457  pointer to a void*, so we try and work around it by assuming that the 
458  value of the 'LDAP *' pointer is the same as the one we had passed in
459  **********************************************************************/
460
461 struct smbldap_state_lookup {
462         LDAP *ld;
463         struct smbldap_state *smbldap_state;
464         struct smbldap_state_lookup *prev, *next;
465 };
466
467 static struct smbldap_state_lookup *smbldap_state_lookup_list;
468
469 static struct smbldap_state *smbldap_find_state(LDAP *ld) 
470 {
471         struct smbldap_state_lookup *t;
472
473         for (t = smbldap_state_lookup_list; t; t = t->next) {
474                 if (t->ld == ld) {
475                         return t->smbldap_state;
476                 }
477         }
478         return NULL;
479 }
480
481 static void smbldap_delete_state(struct smbldap_state *smbldap_state) 
482 {
483         struct smbldap_state_lookup *t;
484
485         for (t = smbldap_state_lookup_list; t; t = t->next) {
486                 if (t->smbldap_state == smbldap_state) {
487                         DLIST_REMOVE(smbldap_state_lookup_list, t);
488                         SAFE_FREE(t);
489                         return;
490                 }
491         }
492 }
493
494 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state) 
495 {
496         struct smbldap_state *tmp_ldap_state;
497         struct smbldap_state_lookup *t;
498         struct smbldap_state_lookup *tmp;
499         
500         if ((tmp_ldap_state = smbldap_find_state(ld))) {
501                 SMB_ASSERT(tmp_ldap_state == smbldap_state);
502                 return;
503         }
504
505         t = smb_xmalloc(sizeof(*t));
506         ZERO_STRUCTP(t);
507         
508         DLIST_ADD_END(smbldap_state_lookup_list, t, tmp);
509         t->ld = ld;
510         t->smbldap_state = smbldap_state;
511 }
512
513 /*******************************************************************
514  open a connection to the ldap server.
515 ******************************************************************/
516 static int smbldap_open_connection (struct smbldap_state *ldap_state)
517
518 {
519         int rc = LDAP_SUCCESS;
520         int version;
521         BOOL ldap_v3 = False;
522         LDAP **ldap_struct = &ldap_state->ldap_struct;
523
524 #ifdef HAVE_LDAP_INITIALIZE
525         DEBUG(10, ("smbldap_open_connection: %s\n", ldap_state->uri));
526         
527         if ((rc = ldap_initialize(ldap_struct, ldap_state->uri)) != LDAP_SUCCESS) {
528                 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
529                 return rc;
530         }
531 #else 
532
533         /* Parse the string manually */
534
535         {
536                 int port = 0;
537                 fstring protocol;
538                 fstring host;
539                 const char *p = ldap_state->uri; 
540                 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
541                 
542                 /* skip leading "URL:" (if any) */
543                 if ( strncasecmp( p, "URL:", 4 ) == 0 ) {
544                         p += 4;
545                 }
546                 
547                 sscanf(p, "%10[^:]://%254s[^:]:%d", protocol, host, &port);
548                 
549                 if (port == 0) {
550                         if (strequal(protocol, "ldap")) {
551                                 port = LDAP_PORT;
552                         } else if (strequal(protocol, "ldaps")) {
553                                 port = LDAPS_PORT;
554                         } else {
555                                 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
556                         }
557                 }
558                 
559                 if ((*ldap_struct = ldap_init(host, port)) == NULL)     {
560                         DEBUG(0, ("ldap_init failed !\n"));
561                         return LDAP_OPERATIONS_ERROR;
562                 }
563                 
564                 if (strequal(protocol, "ldaps")) {
565 #ifdef LDAP_OPT_X_TLS
566                         int tls = LDAP_OPT_X_TLS_HARD;
567                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
568                         {
569                                 DEBUG(0, ("Failed to setup a TLS session\n"));
570                         }
571                         
572                         DEBUG(3,("LDAPS option set...!\n"));
573 #else
574                         DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
575                         return LDAP_OPERATIONS_ERROR;
576 #endif
577                 }
578         }
579 #endif
580
581         /* Store the LDAP pointer in a lookup list */
582
583         smbldap_store_state(*ldap_struct, ldap_state);
584
585         /* Upgrade to LDAPv3 if possible */
586
587         if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
588         {
589                 if (version != LDAP_VERSION3)
590                 {
591                         version = LDAP_VERSION3;
592                         if (ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS) {
593                                 ldap_v3 = True;
594                         }
595                 } else {
596                         ldap_v3 = True;
597                 }
598         }
599
600         if (lp_ldap_ssl() == LDAP_SSL_START_TLS) {
601 #ifdef LDAP_OPT_X_TLS
602                 if (ldap_v3) {
603                         if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
604                         {
605                                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
606                                          ldap_err2string(rc)));
607                                 return rc;
608                         }
609                         DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
610                 } else {
611                         
612                         DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
613                         return LDAP_OPERATIONS_ERROR;
614                 }
615 #else
616                 DEBUG(0,("smbldap_open_connection: StartTLS not supported by LDAP client libraries!\n"));
617                 return LDAP_OPERATIONS_ERROR;
618 #endif
619         }
620
621         DEBUG(2, ("smbldap_open_connection: connection opened\n"));
622         return rc;
623 }
624
625
626 /*******************************************************************
627  a rebind function for authenticated referrals
628  This version takes a void* that we can shove useful stuff in :-)
629 ******************************************************************/
630 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
631 #else
632 static int rebindproc_with_state  (LDAP * ld, char **whop, char **credp, 
633                                    int *methodp, int freeit, void *arg)
634 {
635         struct smbldap_state *ldap_state = arg;
636         
637         /** @TODO Should we be doing something to check what servers we rebind to?
638             Could we get a referral to a machine that we don't want to give our
639             username and password to? */
640         
641         if (freeit) {
642                 SAFE_FREE(*whop);
643                 memset(*credp, '\0', strlen(*credp));
644                 SAFE_FREE(*credp);
645         } else {
646                 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n", 
647                           ldap_state->bind_dn));
648
649                 *whop = strdup(ldap_state->bind_dn);
650                 if (!*whop) {
651                         return LDAP_NO_MEMORY;
652                 }
653                 *credp = strdup(ldap_state->bind_secret);
654                 if (!*credp) {
655                         SAFE_FREE(*whop);
656                         return LDAP_NO_MEMORY;
657                 }
658                 *methodp = LDAP_AUTH_SIMPLE;
659         }
660         return 0;
661 }
662 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
663
664 /*******************************************************************
665  a rebind function for authenticated referrals
666  This version takes a void* that we can shove useful stuff in :-)
667  and actually does the connection.
668 ******************************************************************/
669 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
670 static int rebindproc_connect_with_state (LDAP *ldap_struct, 
671                                           LDAP_CONST char *url, 
672                                           ber_tag_t request,
673                                           ber_int_t msgid, void *arg)
674 {
675         struct smbldap_state *ldap_state = arg;
676         int rc;
677         DEBUG(5,("rebindproc_connect_with_state: Rebinding as \"%s\"\n", 
678                  ldap_state->bind_dn));
679         
680         /** @TODO Should we be doing something to check what servers we rebind to?
681             Could we get a referral to a machine that we don't want to give our
682             username and password to? */
683
684         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
685         
686         return rc;
687 }
688 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
689
690 /*******************************************************************
691  Add a rebind function for authenticated referrals
692 ******************************************************************/
693 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
694 #else
695 # if LDAP_SET_REBIND_PROC_ARGS == 2
696 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
697                        int *method, int freeit )
698 {
699         struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
700
701         return rebindproc_with_state(ldap_struct, whop, credp,
702                                      method, freeit, ldap_state);
703         
704 }
705 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
706 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
707
708 /*******************************************************************
709  a rebind function for authenticated referrals
710  this also does the connection, but no void*.
711 ******************************************************************/
712 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
713 # if LDAP_SET_REBIND_PROC_ARGS == 2
714 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
715                                ber_int_t msgid)
716 {
717         struct smbldap_state *ldap_state = smbldap_find_state(ld);
718
719         return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid, 
720                                              ldap_state);
721 }
722 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
723 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
724
725 /*******************************************************************
726  connect to the ldap server under system privilege.
727 ******************************************************************/
728 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
729 {
730         int rc;
731         char *ldap_dn;
732         char *ldap_secret;
733
734         /* get the password */
735         if (!fetch_ldap_pw(&ldap_dn, &ldap_secret))
736         {
737                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
738                 return LDAP_INVALID_CREDENTIALS;
739         }
740
741         ldap_state->bind_dn = ldap_dn;
742         ldap_state->bind_secret = ldap_secret;
743
744         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
745            (OpenLDAP) doesnt' seem to support it */
746            
747         DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
748                   ldap_state->uri, ldap_dn));
749
750 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
751 # if LDAP_SET_REBIND_PROC_ARGS == 2     
752         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect); 
753 # endif
754 # if LDAP_SET_REBIND_PROC_ARGS == 3     
755         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);  
756 # endif
757 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
758 # if LDAP_SET_REBIND_PROC_ARGS == 2     
759         ldap_set_rebind_proc(ldap_struct, &rebindproc); 
760 # endif
761 # if LDAP_SET_REBIND_PROC_ARGS == 3     
762         ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);  
763 # endif
764 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
765
766         rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
767
768         if (rc != LDAP_SUCCESS) {
769                 char *ld_error = NULL;
770                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
771                                 &ld_error);
772                 DEBUG(ldap_state->num_failures ? 2 : 0,
773                       ("failed to bind to server with dn= %s Error: %s\n\t%s\n",
774                                ldap_dn ? ldap_dn : "(unknown)", ldap_err2string(rc),
775                                ld_error ? ld_error : "(unknown)"));
776                 SAFE_FREE(ld_error);
777                 ldap_state->num_failures++;
778                 return rc;
779         }
780
781         ldap_state->num_failures = 0;
782
783         DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
784         return rc;
785 }
786
787 /**********************************************************************
788 Connect to LDAP server (called before every ldap operation)
789 *********************************************************************/
790 static int smbldap_open(struct smbldap_state *ldap_state)
791 {
792         int rc;
793         SMB_ASSERT(ldap_state);
794                 
795 #ifndef NO_LDAP_SECURITY
796         if (geteuid() != 0) {
797                 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
798                 return  LDAP_INSUFFICIENT_ACCESS;
799         }
800 #endif
801
802         if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
803                 struct sockaddr_un addr;
804                 socklen_t len = sizeof(addr);
805                 int sd;
806                 if (ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd) == 0 &&
807                     getpeername(sd, (struct sockaddr *) &addr, &len) < 0) {
808                         /* the other end has died. reopen. */
809                         ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
810                         ldap_state->ldap_struct = NULL;
811                         ldap_state->last_ping = (time_t)0;
812                 } else {
813                         ldap_state->last_ping = time(NULL);
814                 } 
815         }
816
817         if (ldap_state->ldap_struct != NULL) {
818                 DEBUG(5,("smbldap_open: already connected to the LDAP server\n"));
819                 return LDAP_SUCCESS;
820         }
821
822         if ((rc = smbldap_open_connection(ldap_state))) {
823                 return rc;
824         }
825
826         if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
827                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
828                 ldap_state->ldap_struct = NULL;
829                 return rc;
830         }
831
832
833         ldap_state->last_ping = time(NULL);
834         DEBUG(4,("The LDAP server is succesful connected\n"));
835
836         return LDAP_SUCCESS;
837 }
838
839 /**********************************************************************
840 Disconnect from LDAP server 
841 *********************************************************************/
842 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
843 {
844         if (!ldap_state)
845                 return NT_STATUS_INVALID_PARAMETER;
846                 
847         if (ldap_state->ldap_struct != NULL) {
848                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
849                 ldap_state->ldap_struct = NULL;
850         }
851
852         smbldap_delete_state(ldap_state);
853         
854         DEBUG(5,("The connection to the LDAP server was closed\n"));
855         /* maybe free the results here --metze */
856         
857         
858
859         return NT_STATUS_OK;
860 }
861
862 int smbldap_retry_open(struct smbldap_state *ldap_state, int *attempts)
863 {
864         int rc;
865
866         SMB_ASSERT(ldap_state && attempts);
867                 
868         if (*attempts != 0) {
869                 unsigned int sleep_time;
870                 uint8 rand_byte;
871
872                 /* Sleep for a random timeout */
873                 rand_byte = (char)(sys_random());
874
875                 sleep_time = (((*attempts)*(*attempts))/2)*rand_byte*2; 
876                 /* we retry after (0.5, 1, 2, 3, 4.5, 6) seconds
877                    on average.  
878                  */
879                 DEBUG(3, ("Sleeping for %u milliseconds before reconnecting\n", 
880                           sleep_time));
881                 msleep(sleep_time);
882         }
883         (*attempts)++;
884
885         if ((rc = smbldap_open(ldap_state))) {
886                 DEBUG(1,("Connection to LDAP Server failed for the %d try!\n",*attempts));
887                 return rc;
888         } 
889         
890         return LDAP_SUCCESS;            
891 }
892
893
894 /*********************************************************************
895  ********************************************************************/
896
897 int smbldap_search(struct smbldap_state *ldap_state, 
898                    const char *base, int scope, const char *filter, 
899                    char *attrs[], int attrsonly, 
900                    LDAPMessage **res)
901 {
902         int             rc = LDAP_SERVER_DOWN;
903         int             attempts = 0;
904         char           *utf8_filter;
905
906         SMB_ASSERT(ldap_state);
907
908         if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
909                 return LDAP_NO_MEMORY;
910         }
911
912         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
913                 
914                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
915                         continue;
916                 
917                 rc = ldap_search_s(ldap_state->ldap_struct, base, scope, 
918                                    utf8_filter, attrs, attrsonly, res);
919         }
920         
921         if (rc == LDAP_SERVER_DOWN) {
922                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
923                 smbldap_close(ldap_state);      
924         }
925
926         SAFE_FREE(utf8_filter);
927         return rc;
928 }
929
930 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
931 {
932         int             rc = LDAP_SERVER_DOWN;
933         int             attempts = 0;
934         char           *utf8_dn;
935
936         SMB_ASSERT(ldap_state);
937
938         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
939                 return LDAP_NO_MEMORY;
940         }
941
942         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
943                 
944                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
945                         continue;
946                 
947                 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
948         }
949         
950         if (rc == LDAP_SERVER_DOWN) {
951                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
952                 smbldap_close(ldap_state);      
953         }
954         
955         SAFE_FREE(utf8_dn);
956         return rc;
957 }
958
959 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
960 {
961         int             rc = LDAP_SERVER_DOWN;
962         int             attempts = 0;
963         char           *utf8_dn;
964         
965         SMB_ASSERT(ldap_state);
966
967         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
968                 return LDAP_NO_MEMORY;
969         }
970
971         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
972                 
973                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
974                         continue;
975                 
976                 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
977         }
978         
979         if (rc == LDAP_SERVER_DOWN) {
980                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
981                 smbldap_close(ldap_state);      
982         }
983                 
984         SAFE_FREE(utf8_dn);
985         return rc;
986 }
987
988 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
989 {
990         int             rc = LDAP_SERVER_DOWN;
991         int             attempts = 0;
992         char           *utf8_dn;
993         
994         SMB_ASSERT(ldap_state);
995
996         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
997                 return LDAP_NO_MEMORY;
998         }
999
1000         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1001                 
1002                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1003                         continue;
1004                 
1005                 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1006         }
1007         
1008         if (rc == LDAP_SERVER_DOWN) {
1009                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1010                 smbldap_close(ldap_state);      
1011         }
1012                 
1013         SAFE_FREE(utf8_dn);
1014         return rc;
1015 }
1016
1017 int smbldap_extended_operation(struct smbldap_state *ldap_state, 
1018                                LDAP_CONST char *reqoid, struct berval *reqdata, 
1019                                LDAPControl **serverctrls, LDAPControl **clientctrls, 
1020                                char **retoidp, struct berval **retdatap)
1021 {
1022         int             rc = LDAP_SERVER_DOWN;
1023         int             attempts = 0;
1024         
1025         if (!ldap_state)
1026                 return (-1);
1027
1028         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1029                 
1030                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1031                         continue;
1032                 
1033                 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid, reqdata, 
1034                                                serverctrls, clientctrls, retoidp, retdatap);
1035         }
1036         
1037         if (rc == LDAP_SERVER_DOWN) {
1038                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1039                 smbldap_close(ldap_state);      
1040         }
1041                 
1042         return rc;
1043 }
1044
1045 /*******************************************************************
1046  run the search by name.
1047 ******************************************************************/
1048 int smbldap_search_suffix (struct smbldap_state *ldap_state, const char *filter, 
1049                            char **search_attr, LDAPMessage ** result)
1050 {
1051         int scope = LDAP_SCOPE_SUBTREE;
1052         int rc;
1053
1054         DEBUG(2, ("smbldap_search_suffix: searching for:[%s]\n", filter));
1055
1056         rc = smbldap_search(ldap_state, lp_ldap_suffix(), scope, filter, search_attr, 0, result);
1057
1058         if (rc != LDAP_SUCCESS) {
1059                 char *ld_error = NULL;
1060                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1061                                 &ld_error);
1062                 DEBUG(0,("smbldap_search_suffix: Problem during the LDAP search: %s (%s)\n", 
1063                         ld_error?ld_error:"(unknown)", ldap_err2string (rc)));
1064                 DEBUG(3,("smbldap_search_suffix: Query was: %s, %s\n", lp_ldap_suffix(), 
1065                         filter));
1066                 SAFE_FREE(ld_error);
1067         }
1068         
1069         return rc;
1070 }
1071
1072 /**********************************************************************
1073  Housekeeping
1074  *********************************************************************/
1075
1076 void smbldap_free_struct(struct smbldap_state **ldap_state) 
1077 {
1078         smbldap_close(*ldap_state);
1079         
1080         if ((*ldap_state)->bind_secret) {
1081                 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1082         }
1083
1084         SAFE_FREE((*ldap_state)->bind_dn);
1085         SAFE_FREE((*ldap_state)->bind_secret);
1086
1087         *ldap_state = NULL;
1088
1089         /* No need to free any further, as it is talloc()ed */
1090 }
1091
1092
1093 /**********************************************************************
1094  Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1095  *********************************************************************/
1096
1097 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state) 
1098 {
1099         *smbldap_state = talloc_zero(mem_ctx, sizeof(**smbldap_state));
1100         if (!*smbldap_state) {
1101                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1102                 return NT_STATUS_NO_MEMORY;
1103         }
1104
1105         if (location) {
1106                 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1107         } else {
1108                 (*smbldap_state)->uri = "ldap://localhost";
1109         }
1110         return NT_STATUS_OK;
1111 }
1112