Fix memleak
[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                 i+=1;
213         }
214
215         SAFE_FREE( list );
216 }
217
218 /*******************************************************************
219  find the ldap password
220 ******************************************************************/
221 BOOL fetch_ldap_pw(char **dn, char** pw)
222 {
223         char *key = NULL;
224         size_t size;
225         
226         *dn = smb_xstrdup(lp_ldap_admin_dn());
227         
228         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, *dn) < 0) {
229                 SAFE_FREE(*dn);
230                 DEBUG(0, ("fetch_ldap_pw: asprintf failed!\n"));
231         }
232         
233         *pw=secrets_fetch(key, &size);
234         SAFE_FREE(key);
235
236         if (!size) {
237                 /* Upgrade 2.2 style entry */
238                 char *p;
239                 char* old_style_key = strdup(*dn);
240                 char *data;
241                 fstring old_style_pw;
242                 
243                 if (!old_style_key) {
244                         DEBUG(0, ("fetch_ldap_pw: strdup failed!\n"));
245                         return False;
246                 }
247
248                 for (p=old_style_key; *p; p++)
249                         if (*p == ',') *p = '/';
250         
251                 data=secrets_fetch(old_style_key, &size);
252                 if (!size && size < sizeof(old_style_pw)) {
253                         DEBUG(0,("fetch_ldap_pw: neither ldap secret retrieved!\n"));
254                         SAFE_FREE(old_style_key);
255                         SAFE_FREE(*dn);
256                         return False;
257                 }
258
259                 strncpy(old_style_pw, data, size);
260                 old_style_pw[size] = 0;
261
262                 SAFE_FREE(data);
263
264                 if (!secrets_store_ldap_pw(*dn, old_style_pw)) {
265                         DEBUG(0,("fetch_ldap_pw: ldap secret could not be upgraded!\n"));
266                         SAFE_FREE(old_style_key);
267                         SAFE_FREE(*dn);
268                         return False;                   
269                 }
270                 if (!secrets_delete(old_style_key)) {
271                         DEBUG(0,("fetch_ldap_pw: old ldap secret could not be deleted!\n"));
272                 }
273
274                 SAFE_FREE(old_style_key);
275
276                 *pw = smb_xstrdup(old_style_pw);                
277         }
278         
279         return True;
280 }
281
282 /*******************************************************************
283 search an attribute and return the first value found.
284 ******************************************************************/
285  BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
286                                    const char *attribute, pstring value)
287 {
288         char **values;
289         
290         if ( !attribute )
291                 return False;
292                 
293         value[0] = '\0';
294
295         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
296                 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
297                 
298                 return False;
299         }
300         
301         if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, sizeof(pstring)) == (size_t)-1)
302         {
303                 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n", 
304                           attribute, values[0]));
305                 ldap_value_free(values);
306                 return False;
307         }
308         
309         ldap_value_free(values);
310 #ifdef DEBUG_PASSWORDS
311         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
312 #endif  
313         return True;
314 }
315
316 /************************************************************************
317  Routine to manage the LDAPMod structure array
318  manage memory used by the array, by each struct, and values
319  ***********************************************************************/
320
321  void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
322 {
323         LDAPMod **mods;
324         int i;
325         int j;
326
327         mods = *modlist;
328
329         /* sanity checks on the mod values */
330
331         if (attribute == NULL || *attribute == '\0')
332                 return; 
333 #if 0   /* commented out after discussion with abartlet.  Do not reenable.
334            left here so other so re-add similar code   --jerry */
335         if (value == NULL || *value == '\0')
336                 return;
337 #endif
338
339         if (mods == NULL) 
340         {
341                 mods = (LDAPMod **) malloc(sizeof(LDAPMod *));
342                 if (mods == NULL)
343                 {
344                         DEBUG(0, ("make_a_mod: out of memory!\n"));
345                         return;
346                 }
347                 mods[0] = NULL;
348         }
349
350         for (i = 0; mods[i] != NULL; ++i) {
351                 if (mods[i]->mod_op == modop && !strcasecmp(mods[i]->mod_type, attribute))
352                         break;
353         }
354
355         if (mods[i] == NULL)
356         {
357                 mods = (LDAPMod **) Realloc (mods, (i + 2) * sizeof (LDAPMod *));
358                 if (mods == NULL)
359                 {
360                         DEBUG(0, ("make_a_mod: out of memory!\n"));
361                         return;
362                 }
363                 mods[i] = (LDAPMod *) malloc(sizeof(LDAPMod));
364                 if (mods[i] == NULL)
365                 {
366                         DEBUG(0, ("make_a_mod: out of memory!\n"));
367                         return;
368                 }
369                 mods[i]->mod_op = modop;
370                 mods[i]->mod_values = NULL;
371                 mods[i]->mod_type = strdup(attribute);
372                 mods[i + 1] = NULL;
373         }
374
375         if (value != NULL)
376         {
377                 char *utf8_value = NULL;
378
379                 j = 0;
380                 if (mods[i]->mod_values != NULL) {
381                         for (; mods[i]->mod_values[j] != NULL; j++);
382                 }
383                 mods[i]->mod_values = (char **)Realloc(mods[i]->mod_values,
384                                                (j + 2) * sizeof (char *));
385                                                
386                 if (mods[i]->mod_values == NULL) {
387                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
388                         return;
389                 }
390
391                 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
392                         DEBUG (0, ("make_a_mod: String conversion failure!\n"));
393                         return;
394                 }
395
396                 mods[i]->mod_values[j] = utf8_value;
397
398                 mods[i]->mod_values[j + 1] = NULL;
399         }
400         *modlist = mods;
401 }
402
403
404 /**********************************************************************
405   Set attribute to newval in LDAP, regardless of what value the
406   attribute had in LDAP before.
407 *********************************************************************/
408  void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
409                       LDAPMod ***mods,
410                       const char *attribute, const char *newval)
411 {
412         char **values = NULL;
413
414         if (existing != NULL) {
415                 values = ldap_get_values(ldap_struct, existing, attribute);
416         }
417
418         /* all of our string attributes are case insensitive */
419         
420         if ((values != NULL) && (values[0] != NULL) &&
421             StrCaseCmp(values[0], newval) == 0) 
422         {
423                 
424                 /* Believe it or not, but LDAP will deny a delete and
425                    an add at the same time if the values are the
426                    same... */
427
428                 ldap_value_free(values);
429                 return;
430         }
431
432         /* Regardless of the real operation (add or modify)
433            we add the new value here. We rely on deleting
434            the old value, should it exist. */
435
436         if ((newval != NULL) && (strlen(newval) > 0)) {
437                 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
438         }
439
440         if (values == NULL) {
441                 /* There has been no value before, so don't delete it.
442                    Here's a possible race: We might end up with
443                    duplicate attributes */
444                 return;
445         }
446
447         /* By deleting exactly the value we found in the entry this
448            should be race-free in the sense that the LDAP-Server will
449            deny the complete operation if somebody changed the
450            attribute behind our back. */
451
452         smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, values[0]);
453         ldap_value_free(values);
454 }
455
456
457 /**********************************************************************
458  Some varients of the LDAP rebind code do not pass in the third 'arg' 
459  pointer to a void*, so we try and work around it by assuming that the 
460  value of the 'LDAP *' pointer is the same as the one we had passed in
461  **********************************************************************/
462
463 struct smbldap_state_lookup {
464         LDAP *ld;
465         struct smbldap_state *smbldap_state;
466         struct smbldap_state_lookup *prev, *next;
467 };
468
469 static struct smbldap_state_lookup *smbldap_state_lookup_list;
470
471 static struct smbldap_state *smbldap_find_state(LDAP *ld) 
472 {
473         struct smbldap_state_lookup *t;
474
475         for (t = smbldap_state_lookup_list; t; t = t->next) {
476                 if (t->ld == ld) {
477                         return t->smbldap_state;
478                 }
479         }
480         return NULL;
481 }
482
483 static void smbldap_delete_state(struct smbldap_state *smbldap_state) 
484 {
485         struct smbldap_state_lookup *t;
486
487         for (t = smbldap_state_lookup_list; t; t = t->next) {
488                 if (t->smbldap_state == smbldap_state) {
489                         DLIST_REMOVE(smbldap_state_lookup_list, t);
490                         SAFE_FREE(t);
491                         return;
492                 }
493         }
494 }
495
496 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state) 
497 {
498         struct smbldap_state *tmp_ldap_state;
499         struct smbldap_state_lookup *t;
500         struct smbldap_state_lookup *tmp;
501         
502         if ((tmp_ldap_state = smbldap_find_state(ld))) {
503                 SMB_ASSERT(tmp_ldap_state == smbldap_state);
504                 return;
505         }
506
507         t = smb_xmalloc(sizeof(*t));
508         ZERO_STRUCTP(t);
509         
510         DLIST_ADD_END(smbldap_state_lookup_list, t, tmp);
511         t->ld = ld;
512         t->smbldap_state = smbldap_state;
513 }
514
515 /*******************************************************************
516  open a connection to the ldap server.
517 ******************************************************************/
518 static int smbldap_open_connection (struct smbldap_state *ldap_state)
519
520 {
521         int rc = LDAP_SUCCESS;
522         int version;
523         BOOL ldap_v3 = False;
524         LDAP **ldap_struct = &ldap_state->ldap_struct;
525
526 #ifdef HAVE_LDAP_INITIALIZE
527         DEBUG(10, ("smbldap_open_connection: %s\n", ldap_state->uri));
528         
529         if ((rc = ldap_initialize(ldap_struct, ldap_state->uri)) != LDAP_SUCCESS) {
530                 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
531                 return rc;
532         }
533 #else 
534
535         /* Parse the string manually */
536
537         {
538                 int port = 0;
539                 fstring protocol;
540                 fstring host;
541                 const char *p = ldap_state->uri; 
542                 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
543                 
544                 /* skip leading "URL:" (if any) */
545                 if ( strncasecmp( p, "URL:", 4 ) == 0 ) {
546                         p += 4;
547                 }
548                 
549                 sscanf(p, "%10[^:]://%254s[^:]:%d", protocol, host, &port);
550                 
551                 if (port == 0) {
552                         if (strequal(protocol, "ldap")) {
553                                 port = LDAP_PORT;
554                         } else if (strequal(protocol, "ldaps")) {
555                                 port = LDAPS_PORT;
556                         } else {
557                                 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
558                         }
559                 }
560                 
561                 if ((*ldap_struct = ldap_init(host, port)) == NULL)     {
562                         DEBUG(0, ("ldap_init failed !\n"));
563                         return LDAP_OPERATIONS_ERROR;
564                 }
565                 
566                 if (strequal(protocol, "ldaps")) {
567 #ifdef LDAP_OPT_X_TLS
568                         int tls = LDAP_OPT_X_TLS_HARD;
569                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
570                         {
571                                 DEBUG(0, ("Failed to setup a TLS session\n"));
572                         }
573                         
574                         DEBUG(3,("LDAPS option set...!\n"));
575 #else
576                         DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
577                         return LDAP_OPERATIONS_ERROR;
578 #endif
579                 }
580         }
581 #endif
582
583         /* Store the LDAP pointer in a lookup list */
584
585         smbldap_store_state(*ldap_struct, ldap_state);
586
587         /* Upgrade to LDAPv3 if possible */
588
589         if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
590         {
591                 if (version != LDAP_VERSION3)
592                 {
593                         version = LDAP_VERSION3;
594                         if (ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS) {
595                                 ldap_v3 = True;
596                         }
597                 } else {
598                         ldap_v3 = True;
599                 }
600         }
601
602         if (lp_ldap_ssl() == LDAP_SSL_START_TLS) {
603 #ifdef LDAP_OPT_X_TLS
604                 if (ldap_v3) {
605                         if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
606                         {
607                                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
608                                          ldap_err2string(rc)));
609                                 return rc;
610                         }
611                         DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
612                 } else {
613                         
614                         DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
615                         return LDAP_OPERATIONS_ERROR;
616                 }
617 #else
618                 DEBUG(0,("smbldap_open_connection: StartTLS not supported by LDAP client libraries!\n"));
619                 return LDAP_OPERATIONS_ERROR;
620 #endif
621         }
622
623         DEBUG(2, ("smbldap_open_connection: connection opened\n"));
624         return rc;
625 }
626
627
628 /*******************************************************************
629  a rebind function for authenticated referrals
630  This version takes a void* that we can shove useful stuff in :-)
631 ******************************************************************/
632 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
633 #else
634 static int rebindproc_with_state  (LDAP * ld, char **whop, char **credp, 
635                                    int *methodp, int freeit, void *arg)
636 {
637         struct smbldap_state *ldap_state = arg;
638         
639         /** @TODO Should we be doing something to check what servers we rebind to?
640             Could we get a referral to a machine that we don't want to give our
641             username and password to? */
642         
643         if (freeit) {
644                 SAFE_FREE(*whop);
645                 memset(*credp, '\0', strlen(*credp));
646                 SAFE_FREE(*credp);
647         } else {
648                 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n", 
649                           ldap_state->bind_dn));
650
651                 *whop = strdup(ldap_state->bind_dn);
652                 if (!*whop) {
653                         return LDAP_NO_MEMORY;
654                 }
655                 *credp = strdup(ldap_state->bind_secret);
656                 if (!*credp) {
657                         SAFE_FREE(*whop);
658                         return LDAP_NO_MEMORY;
659                 }
660                 *methodp = LDAP_AUTH_SIMPLE;
661         }
662         return 0;
663 }
664 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
665
666 /*******************************************************************
667  a rebind function for authenticated referrals
668  This version takes a void* that we can shove useful stuff in :-)
669  and actually does the connection.
670 ******************************************************************/
671 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
672 static int rebindproc_connect_with_state (LDAP *ldap_struct, 
673                                           LDAP_CONST char *url, 
674                                           ber_tag_t request,
675                                           ber_int_t msgid, void *arg)
676 {
677         struct smbldap_state *ldap_state = arg;
678         int rc;
679         DEBUG(5,("rebindproc_connect_with_state: Rebinding as \"%s\"\n", 
680                  ldap_state->bind_dn));
681         
682         /** @TODO Should we be doing something to check what servers we rebind to?
683             Could we get a referral to a machine that we don't want to give our
684             username and password to? */
685
686         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
687         
688         return rc;
689 }
690 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
691
692 /*******************************************************************
693  Add a rebind function for authenticated referrals
694 ******************************************************************/
695 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
696 #else
697 # if LDAP_SET_REBIND_PROC_ARGS == 2
698 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
699                        int *method, int freeit )
700 {
701         struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
702
703         return rebindproc_with_state(ldap_struct, whop, credp,
704                                      method, freeit, ldap_state);
705         
706 }
707 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
708 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
709
710 /*******************************************************************
711  a rebind function for authenticated referrals
712  this also does the connection, but no void*.
713 ******************************************************************/
714 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
715 # if LDAP_SET_REBIND_PROC_ARGS == 2
716 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
717                                ber_int_t msgid)
718 {
719         struct smbldap_state *ldap_state = smbldap_find_state(ld);
720
721         return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid, 
722                                              ldap_state);
723 }
724 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
725 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
726
727 /*******************************************************************
728  connect to the ldap server under system privilege.
729 ******************************************************************/
730 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
731 {
732         int rc;
733         char *ldap_dn;
734         char *ldap_secret;
735
736         /* get the password */
737         if (!fetch_ldap_pw(&ldap_dn, &ldap_secret))
738         {
739                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
740                 return LDAP_INVALID_CREDENTIALS;
741         }
742
743         ldap_state->bind_dn = ldap_dn;
744         ldap_state->bind_secret = ldap_secret;
745
746         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
747            (OpenLDAP) doesnt' seem to support it */
748            
749         DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
750                   ldap_state->uri, ldap_dn));
751
752 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
753 # if LDAP_SET_REBIND_PROC_ARGS == 2     
754         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect); 
755 # endif
756 # if LDAP_SET_REBIND_PROC_ARGS == 3     
757         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);  
758 # endif
759 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
760 # if LDAP_SET_REBIND_PROC_ARGS == 2     
761         ldap_set_rebind_proc(ldap_struct, &rebindproc); 
762 # endif
763 # if LDAP_SET_REBIND_PROC_ARGS == 3     
764         ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);  
765 # endif
766 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
767
768         rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
769
770         if (rc != LDAP_SUCCESS) {
771                 char *ld_error = NULL;
772                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
773                                 &ld_error);
774                 DEBUG(ldap_state->num_failures ? 2 : 0,
775                       ("failed to bind to server with dn= %s Error: %s\n\t%s\n",
776                                ldap_dn ? ldap_dn : "(unknown)", ldap_err2string(rc),
777                                ld_error ? ld_error : "(unknown)"));
778                 SAFE_FREE(ld_error);
779                 ldap_state->num_failures++;
780                 return rc;
781         }
782
783         ldap_state->num_failures = 0;
784
785         DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
786         return rc;
787 }
788
789 /**********************************************************************
790 Connect to LDAP server (called before every ldap operation)
791 *********************************************************************/
792 static int smbldap_open(struct smbldap_state *ldap_state)
793 {
794         int rc;
795         SMB_ASSERT(ldap_state);
796                 
797 #ifndef NO_LDAP_SECURITY
798         if (geteuid() != 0) {
799                 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
800                 return  LDAP_INSUFFICIENT_ACCESS;
801         }
802 #endif
803
804         if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
805                 struct sockaddr_un addr;
806                 socklen_t len = sizeof(addr);
807                 int sd;
808                 if (ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd) == 0 &&
809                     getpeername(sd, (struct sockaddr *) &addr, &len) < 0) {
810                         /* the other end has died. reopen. */
811                         ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
812                         ldap_state->ldap_struct = NULL;
813                         ldap_state->last_ping = (time_t)0;
814                 } else {
815                         ldap_state->last_ping = time(NULL);
816                 } 
817         }
818
819         if (ldap_state->ldap_struct != NULL) {
820                 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
821                 return LDAP_SUCCESS;
822         }
823
824         if ((rc = smbldap_open_connection(ldap_state))) {
825                 return rc;
826         }
827
828         if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
829                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
830                 ldap_state->ldap_struct = NULL;
831                 return rc;
832         }
833
834
835         ldap_state->last_ping = time(NULL);
836         DEBUG(4,("The LDAP server is succesful connected\n"));
837
838         return LDAP_SUCCESS;
839 }
840
841 /**********************************************************************
842 Disconnect from LDAP server 
843 *********************************************************************/
844 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
845 {
846         if (!ldap_state)
847                 return NT_STATUS_INVALID_PARAMETER;
848                 
849         if (ldap_state->ldap_struct != NULL) {
850                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
851                 ldap_state->ldap_struct = NULL;
852         }
853
854         smbldap_delete_state(ldap_state);
855         
856         DEBUG(5,("The connection to the LDAP server was closed\n"));
857         /* maybe free the results here --metze */
858         
859         
860
861         return NT_STATUS_OK;
862 }
863
864 int smbldap_retry_open(struct smbldap_state *ldap_state, int *attempts)
865 {
866         int rc;
867
868         SMB_ASSERT(ldap_state && attempts);
869                 
870         if (*attempts != 0) {
871                 unsigned int sleep_time;
872                 uint8 rand_byte;
873
874                 /* Sleep for a random timeout */
875                 rand_byte = (char)(sys_random());
876
877                 sleep_time = (((*attempts)*(*attempts))/2)*rand_byte*2; 
878                 /* we retry after (0.5, 1, 2, 3, 4.5, 6) seconds
879                    on average.  
880                  */
881                 DEBUG(3, ("Sleeping for %u milliseconds before reconnecting\n", 
882                           sleep_time));
883                 msleep(sleep_time);
884         }
885         (*attempts)++;
886
887         if ((rc = smbldap_open(ldap_state))) {
888                 DEBUG(1,("Connection to LDAP Server failed for the %d try!\n",*attempts));
889                 return rc;
890         } 
891         
892         return LDAP_SUCCESS;            
893 }
894
895
896 /*********************************************************************
897  ********************************************************************/
898
899 int smbldap_search(struct smbldap_state *ldap_state, 
900                    const char *base, int scope, const char *filter, 
901                    char *attrs[], int attrsonly, 
902                    LDAPMessage **res)
903 {
904         int             rc = LDAP_SERVER_DOWN;
905         int             attempts = 0;
906         char           *utf8_filter;
907
908         SMB_ASSERT(ldap_state);
909
910         if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
911                 return LDAP_NO_MEMORY;
912         }
913
914         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
915                 
916                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
917                         continue;
918                 
919                 rc = ldap_search_s(ldap_state->ldap_struct, base, scope, 
920                                    utf8_filter, attrs, attrsonly, res);
921         }
922         
923         if (rc == LDAP_SERVER_DOWN) {
924                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
925                 smbldap_close(ldap_state);      
926         }
927
928         SAFE_FREE(utf8_filter);
929         return rc;
930 }
931
932 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
933 {
934         int             rc = LDAP_SERVER_DOWN;
935         int             attempts = 0;
936         char           *utf8_dn;
937
938         SMB_ASSERT(ldap_state);
939
940         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
941                 return LDAP_NO_MEMORY;
942         }
943
944         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
945                 
946                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
947                         continue;
948                 
949                 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
950         }
951         
952         if (rc == LDAP_SERVER_DOWN) {
953                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
954                 smbldap_close(ldap_state);      
955         }
956         
957         SAFE_FREE(utf8_dn);
958         return rc;
959 }
960
961 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
962 {
963         int             rc = LDAP_SERVER_DOWN;
964         int             attempts = 0;
965         char           *utf8_dn;
966         
967         SMB_ASSERT(ldap_state);
968
969         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
970                 return LDAP_NO_MEMORY;
971         }
972
973         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
974                 
975                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
976                         continue;
977                 
978                 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
979         }
980         
981         if (rc == LDAP_SERVER_DOWN) {
982                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
983                 smbldap_close(ldap_state);      
984         }
985                 
986         SAFE_FREE(utf8_dn);
987         return rc;
988 }
989
990 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
991 {
992         int             rc = LDAP_SERVER_DOWN;
993         int             attempts = 0;
994         char           *utf8_dn;
995         
996         SMB_ASSERT(ldap_state);
997
998         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
999                 return LDAP_NO_MEMORY;
1000         }
1001
1002         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1003                 
1004                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1005                         continue;
1006                 
1007                 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1008         }
1009         
1010         if (rc == LDAP_SERVER_DOWN) {
1011                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1012                 smbldap_close(ldap_state);      
1013         }
1014                 
1015         SAFE_FREE(utf8_dn);
1016         return rc;
1017 }
1018
1019 int smbldap_extended_operation(struct smbldap_state *ldap_state, 
1020                                LDAP_CONST char *reqoid, struct berval *reqdata, 
1021                                LDAPControl **serverctrls, LDAPControl **clientctrls, 
1022                                char **retoidp, struct berval **retdatap)
1023 {
1024         int             rc = LDAP_SERVER_DOWN;
1025         int             attempts = 0;
1026         
1027         if (!ldap_state)
1028                 return (-1);
1029
1030         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1031                 
1032                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1033                         continue;
1034                 
1035                 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid, reqdata, 
1036                                                serverctrls, clientctrls, retoidp, retdatap);
1037         }
1038         
1039         if (rc == LDAP_SERVER_DOWN) {
1040                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1041                 smbldap_close(ldap_state);      
1042         }
1043                 
1044         return rc;
1045 }
1046
1047 /*******************************************************************
1048  run the search by name.
1049 ******************************************************************/
1050 int smbldap_search_suffix (struct smbldap_state *ldap_state, const char *filter, 
1051                            char **search_attr, LDAPMessage ** result)
1052 {
1053         int scope = LDAP_SCOPE_SUBTREE;
1054         int rc;
1055
1056         DEBUG(2, ("smbldap_search_suffix: searching for:[%s]\n", filter));
1057
1058         rc = smbldap_search(ldap_state, lp_ldap_suffix(), scope, filter, search_attr, 0, result);
1059
1060         if (rc != LDAP_SUCCESS) {
1061                 char *ld_error = NULL;
1062                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1063                                 &ld_error);
1064                 DEBUG(0,("smbldap_search_suffix: Problem during the LDAP search: %s (%s)\n", 
1065                         ld_error?ld_error:"(unknown)", ldap_err2string (rc)));
1066                 DEBUG(3,("smbldap_search_suffix: Query was: %s, %s\n", lp_ldap_suffix(), 
1067                         filter));
1068                 SAFE_FREE(ld_error);
1069         }
1070         
1071         return rc;
1072 }
1073
1074 /**********************************************************************
1075  Housekeeping
1076  *********************************************************************/
1077
1078 void smbldap_free_struct(struct smbldap_state **ldap_state) 
1079 {
1080         smbldap_close(*ldap_state);
1081         
1082         if ((*ldap_state)->bind_secret) {
1083                 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1084         }
1085
1086         SAFE_FREE((*ldap_state)->bind_dn);
1087         SAFE_FREE((*ldap_state)->bind_secret);
1088
1089         *ldap_state = NULL;
1090
1091         /* No need to free any further, as it is talloc()ed */
1092 }
1093
1094
1095 /**********************************************************************
1096  Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1097  *********************************************************************/
1098
1099 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state) 
1100 {
1101         *smbldap_state = talloc_zero(mem_ctx, sizeof(**smbldap_state));
1102         if (!*smbldap_state) {
1103                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1104                 return NT_STATUS_NO_MEMORY;
1105         }
1106
1107         if (location) {
1108                 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1109         } else {
1110                 (*smbldap_state)->uri = "ldap://localhost";
1111         }
1112         return NT_STATUS_OK;
1113 }
1114
1115 /**********************************************************************
1116  Add the sambaDomain to LDAP, so we don't have to search for this stuff
1117  again.  This is a once-add operation for now.
1118
1119  TODO:  Add other attributes, and allow modification.
1120 *********************************************************************/
1121 static NTSTATUS add_new_domain_info(struct smbldap_state *ldap_state, 
1122                                     const char *domain_name) 
1123 {
1124         fstring sid_string;
1125         fstring algorithmic_rid_base_string;
1126         pstring filter, dn;
1127         LDAPMod **mods = NULL;
1128         int rc;
1129         int ldap_op;
1130         LDAPMessage *result = NULL;
1131         int num_result;
1132         char **attr_list;
1133
1134         slprintf (filter, sizeof (filter) - 1, "(&(%s=%s)(objectclass=%s))", 
1135                   get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1136                   domain_name, LDAP_OBJ_DOMINFO);
1137
1138         attr_list = get_attr_list( dominfo_attr_list );
1139         rc = smbldap_search_suffix(ldap_state, filter, attr_list, &result);
1140         free_attr_list( attr_list );
1141
1142         if (rc != LDAP_SUCCESS) {
1143                 return NT_STATUS_UNSUCCESSFUL;
1144         }
1145
1146         num_result = ldap_count_entries(ldap_state->ldap_struct, result);
1147         
1148         if (num_result > 1) {
1149                 DEBUG (0, ("More than domain with that name exists: bailing out!\n"));
1150                 ldap_msgfree(result);
1151                 return NT_STATUS_UNSUCCESSFUL;
1152         }
1153         
1154         /* Check if we need to add an entry */
1155         DEBUG(3,("Adding new domain\n"));
1156         ldap_op = LDAP_MOD_ADD;
1157
1158         snprintf(dn, sizeof(dn), "%s=%s,%s", get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN),
1159                 domain_name, lp_ldap_suffix());
1160
1161         /* Free original search */
1162         ldap_msgfree(result);
1163
1164         /* make the changes - the entry *must* not already have samba attributes */
1165         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1166                 domain_name);
1167
1168         /* If we don't have an entry, then ask secrets.tdb for what it thinks.  
1169            It may choose to make it up */
1170
1171         sid_to_string(sid_string, get_global_sam_sid());
1172         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOM_SID), sid_string);
1173
1174         slprintf(algorithmic_rid_base_string, sizeof(algorithmic_rid_base_string) - 1, "%i", algorithmic_rid_base());
1175         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_ALGORITHMIC_RID_BASE), 
1176                         algorithmic_rid_base_string);
1177         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_DOMINFO);
1178
1179         switch(ldap_op)
1180         {
1181         case LDAP_MOD_ADD: 
1182                 rc = smbldap_add(ldap_state, dn, mods);
1183                 break;
1184         case LDAP_MOD_REPLACE: 
1185                 rc = smbldap_modify(ldap_state, dn, mods);
1186                 break;
1187         default:        
1188                 DEBUG(0,("Wrong LDAP operation type: %d!\n", ldap_op));
1189                 return NT_STATUS_INVALID_PARAMETER;
1190         }
1191         
1192         if (rc!=LDAP_SUCCESS) {
1193                 char *ld_error = NULL;
1194                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
1195                 DEBUG(1,("failed to %s domain dn= %s with: %s\n\t%s\n",
1196                        ldap_op == LDAP_MOD_ADD ? "add" : "modify",
1197                        dn, ldap_err2string(rc),
1198                        ld_error?ld_error:"unknown"));
1199                 SAFE_FREE(ld_error);
1200
1201                 ldap_mods_free(mods, True);
1202                 return NT_STATUS_UNSUCCESSFUL;
1203         }
1204
1205         DEBUG(2,("added: domain = %s in the LDAP database\n", domain_name));
1206         ldap_mods_free(mods, True);
1207         return NT_STATUS_OK;
1208 }
1209
1210 /**********************************************************************
1211 Search for the domain info entry
1212 *********************************************************************/
1213 NTSTATUS smbldap_search_domain_info(struct smbldap_state *ldap_state,
1214                                     LDAPMessage ** result, const char *domain_name,
1215                                     BOOL try_add)
1216 {
1217         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1218         pstring filter;
1219         int rc;
1220         char **attr_list;
1221         int count;
1222
1223         snprintf(filter, sizeof(filter)-1, "(&(objectClass=%s)(%s=%s))",
1224                 LDAP_OBJ_DOMINFO,
1225                 get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1226                 domain_name);
1227
1228         DEBUG(2, ("Searching for:[%s]\n", filter));
1229
1230
1231         attr_list = get_attr_list( dominfo_attr_list );
1232         rc = smbldap_search_suffix(ldap_state, filter, attr_list , result);
1233         free_attr_list( attr_list );
1234
1235         if (rc != LDAP_SUCCESS) {
1236                 DEBUG(2,("Problem during LDAPsearch: %s\n", ldap_err2string (rc)));
1237                 DEBUG(2,("Query was: %s, %s\n", lp_ldap_suffix(), filter));
1238         } else if (ldap_count_entries(ldap_state->ldap_struct, *result) < 1) {
1239                 DEBUG(3, ("Got no domain info entries for domain\n"));
1240                 ldap_msgfree(*result);
1241                 *result = NULL;
1242                 if (try_add && NT_STATUS_IS_OK(ret = add_new_domain_info(ldap_state, domain_name))) {
1243                         return smbldap_search_domain_info(ldap_state, result, domain_name, False);
1244                 } 
1245                 else {
1246                         DEBUG(0, ("Adding domain info for %s failed with %s\n", 
1247                                 domain_name, nt_errstr(ret)));
1248                         return ret;
1249                 }
1250         } else if ((count = ldap_count_entries(ldap_state->ldap_struct, *result)) > 1) {
1251                 DEBUG(0, ("Got too many (%d) domain info entries for domain %s\n",
1252                           count, domain_name));
1253                 ldap_msgfree(*result);
1254                 *result = NULL;
1255                 return ret;
1256         } else {
1257                 return NT_STATUS_OK;
1258         }
1259         
1260         return ret;
1261 }
1262