isolate ldap debug messages to the common smbldap_XXX() functions
[samba.git] / source3 / 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-2003
9     
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23    
24 */
25
26 #include "includes.h"
27 #include "smbldap.h"
28
29 #ifndef LDAP_OPT_SUCCESS
30 #define LDAP_OPT_SUCCESS 0
31 #endif
32
33 /* Try not to hit the up or down server forever */
34
35 #define SMBLDAP_DONT_PING_TIME 10       /* ping only all 10 seconds */
36 #define SMBLDAP_NUM_RETRIES 8           /* retry only 8 times */
37
38 #define SMBLDAP_IDLE_TIME 150           /* After 2.5 minutes disconnect */
39
40
41 /* attributes used by Samba 2.2 */
42
43 ATTRIB_MAP_ENTRY attrib_map_v22[] = {
44         { LDAP_ATTR_UID,                "uid"           },
45         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
46         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
47         { LDAP_ATTR_UNIX_HOME,          "homeDirectory" },
48         { LDAP_ATTR_PWD_LAST_SET,       "pwdLastSet"    },
49         { LDAP_ATTR_PWD_CAN_CHANGE,     "pwdCanChange"  },
50         { LDAP_ATTR_PWD_MUST_CHANGE,    "pwdMustChange" },
51         { LDAP_ATTR_LOGON_TIME,         "logonTime"     },
52         { LDAP_ATTR_LOGOFF_TIME,        "logoffTime"    },
53         { LDAP_ATTR_KICKOFF_TIME,       "kickoffTime"   },
54         { LDAP_ATTR_CN,                 "cn"            },
55         { LDAP_ATTR_DISPLAY_NAME,       "displayName"   },
56         { LDAP_ATTR_HOME_PATH,          "smbHome"       },
57         { LDAP_ATTR_HOME_DRIVE,         "homeDrives"    },
58         { LDAP_ATTR_LOGON_SCRIPT,       "scriptPath"    },
59         { LDAP_ATTR_PROFILE_PATH,       "profilePath"   },
60         { LDAP_ATTR_DESC,               "description"   },
61         { LDAP_ATTR_USER_WKS,           "userWorkstations"},
62         { LDAP_ATTR_USER_RID,           "rid"           },
63         { LDAP_ATTR_PRIMARY_GROUP_RID,  "primaryGroupID"},
64         { LDAP_ATTR_LMPW,               "lmPassword"    },
65         { LDAP_ATTR_NTPW,               "ntPassword"    },
66         { LDAP_ATTR_DOMAIN,             "domain"        },
67         { LDAP_ATTR_OBJCLASS,           "objectClass"   },
68         { LDAP_ATTR_ACB_INFO,           "acctFlags"     },
69         { LDAP_ATTR_LIST_END,           NULL            }
70 };
71
72 /* attributes used by Samba 3.0's sambaSamAccount */
73
74 ATTRIB_MAP_ENTRY attrib_map_v30[] = {
75         { LDAP_ATTR_UID,                "uid"                   },
76         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
77         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
78         { LDAP_ATTR_UNIX_HOME,          "homeDirectory"         },
79         { LDAP_ATTR_PWD_LAST_SET,       "sambaPwdLastSet"       },
80         { LDAP_ATTR_PWD_CAN_CHANGE,     "sambaPwdCanChange"     },
81         { LDAP_ATTR_PWD_MUST_CHANGE,    "sambaPwdMustChange"    },
82         { LDAP_ATTR_LOGON_TIME,         "sambaLogonTime"        },
83         { LDAP_ATTR_LOGOFF_TIME,        "sambaLogoffTime"       },
84         { LDAP_ATTR_KICKOFF_TIME,       "sambaKickoffTime"      },
85         { LDAP_ATTR_CN,                 "cn"                    },
86         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
87         { LDAP_ATTR_HOME_DRIVE,         "sambaHomeDrive"        },
88         { LDAP_ATTR_HOME_PATH,          "sambaHomePath"         },
89         { LDAP_ATTR_LOGON_SCRIPT,       "sambaLogonScript"      },
90         { LDAP_ATTR_PROFILE_PATH,       "sambaProfilePath"      },
91         { LDAP_ATTR_DESC,               "description"           },
92         { LDAP_ATTR_USER_WKS,           "sambaUserWorkstations" },
93         { LDAP_ATTR_USER_SID,           LDAP_ATTRIBUTE_SID      },
94         { LDAP_ATTR_PRIMARY_GROUP_SID,  "sambaPrimaryGroupSID"  },
95         { LDAP_ATTR_LMPW,               "sambaLMPassword"       },
96         { LDAP_ATTR_NTPW,               "sambaNTPassword"       },
97         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
98         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
99         { LDAP_ATTR_ACB_INFO,           "sambaAcctFlags"        },
100         { LDAP_ATTR_MUNGED_DIAL,        "sambaMungedDial"       },
101         { LDAP_ATTR_LIST_END,           NULL                    }
102 };
103
104 /* attributes used for alalocating RIDs */
105
106 ATTRIB_MAP_ENTRY dominfo_attr_list[] = {
107         { LDAP_ATTR_DOMAIN,             "sambaDomainName"       },
108         { LDAP_ATTR_NEXT_RID,           "sambaNextRid"          },
109         { LDAP_ATTR_NEXT_USERRID,       "sambaNextUserRid"      },
110         { LDAP_ATTR_NEXT_GROUPRID,      "sambaNextGroupRid"     },
111         { LDAP_ATTR_DOM_SID,            LDAP_ATTRIBUTE_SID      },
112         { LDAP_ATTR_ALGORITHMIC_RID_BASE,"sambaAlgorithmicRidBase"},
113         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
114         { LDAP_ATTR_LIST_END,           NULL                    },
115 };
116
117 /* Samba 3.0 group mapping attributes */
118
119 ATTRIB_MAP_ENTRY groupmap_attr_list[] = {
120         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
121         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
122         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
123         { LDAP_ATTR_DESC,               "description"           },
124         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
125         { LDAP_ATTR_CN,                 "cn"                    },
126         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
127         { LDAP_ATTR_LIST_END,           NULL                    }       
128 };
129
130 ATTRIB_MAP_ENTRY groupmap_attr_list_to_delete[] = {
131         { LDAP_ATTR_GROUP_SID,          LDAP_ATTRIBUTE_SID      },
132         { LDAP_ATTR_GROUP_TYPE,         "sambaGroupType"        },
133         { LDAP_ATTR_DESC,               "description"           },
134         { LDAP_ATTR_DISPLAY_NAME,       "displayName"           },
135         { LDAP_ATTR_LIST_END,           NULL                    }       
136 };
137
138 /* idmap_ldap sambaUnixIdPool */
139
140 ATTRIB_MAP_ENTRY idpool_attr_list[] = {
141         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
142         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
143         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
144         { LDAP_ATTR_LIST_END,           NULL                    }       
145 };
146
147 ATTRIB_MAP_ENTRY sidmap_attr_list[] = {
148         { LDAP_ATTR_SID,                LDAP_ATTRIBUTE_SID      },
149         { LDAP_ATTR_UIDNUMBER,          LDAP_ATTRIBUTE_UIDNUMBER},
150         { LDAP_ATTR_GIDNUMBER,          LDAP_ATTRIBUTE_GIDNUMBER},
151         { LDAP_ATTR_OBJCLASS,           "objectClass"           },
152         { LDAP_ATTR_LIST_END,           NULL                    }       
153 };
154
155 /**********************************************************************
156  perform a simple table lookup and return the attribute name 
157  **********************************************************************/
158  
159  const char* get_attr_key2string( ATTRIB_MAP_ENTRY table[], int key )
160 {
161         int i = 0;
162         
163         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
164                 if ( table[i].attrib == key )
165                         return table[i].name;
166                 i++;
167         }
168         
169         return NULL;
170 }
171
172
173 /**********************************************************************
174  Return the list of attribute names from a mapping table
175  **********************************************************************/
176
177  char** get_attr_list( ATTRIB_MAP_ENTRY table[] )
178 {
179         char **names;
180         int i = 0;
181         
182         while ( table[i].attrib != LDAP_ATTR_LIST_END )
183                 i++;
184         i++;
185
186         names = (char**)malloc( sizeof(char*)*i );
187         if ( !names ) {
188                 DEBUG(0,("get_attr_list: out of memory\n"));
189                 return NULL;
190         }
191
192         i = 0;
193         while ( table[i].attrib != LDAP_ATTR_LIST_END ) {
194                 names[i] = strdup( table[i].name );
195                 i++;
196         }
197         names[i] = NULL;
198         
199         return names;
200 }
201
202 /*********************************************************************
203  Cleanup 
204  ********************************************************************/
205
206  void free_attr_list( char **list )
207 {
208         int i = 0;
209
210         if ( !list )
211                 return; 
212
213         while ( list[i] ) {
214                 SAFE_FREE( list[i] );
215                 i+=1;
216         }
217
218         SAFE_FREE( list );
219 }
220
221 /*******************************************************************
222  find the ldap password
223 ******************************************************************/
224 BOOL fetch_ldap_pw(char **dn, char** pw)
225 {
226         char *key = NULL;
227         size_t size;
228         
229         *dn = smb_xstrdup(lp_ldap_admin_dn());
230         
231         if (asprintf(&key, "%s/%s", SECRETS_LDAP_BIND_PW, *dn) < 0) {
232                 SAFE_FREE(*dn);
233                 DEBUG(0, ("fetch_ldap_pw: asprintf failed!\n"));
234         }
235         
236         *pw=secrets_fetch(key, &size);
237         SAFE_FREE(key);
238
239         if (!size) {
240                 /* Upgrade 2.2 style entry */
241                 char *p;
242                 char* old_style_key = strdup(*dn);
243                 char *data;
244                 fstring old_style_pw;
245                 
246                 if (!old_style_key) {
247                         DEBUG(0, ("fetch_ldap_pw: strdup failed!\n"));
248                         return False;
249                 }
250
251                 for (p=old_style_key; *p; p++)
252                         if (*p == ',') *p = '/';
253         
254                 data=secrets_fetch(old_style_key, &size);
255                 if (!size && size < sizeof(old_style_pw)) {
256                         DEBUG(0,("fetch_ldap_pw: neither ldap secret retrieved!\n"));
257                         SAFE_FREE(old_style_key);
258                         SAFE_FREE(*dn);
259                         return False;
260                 }
261
262                 size = MIN(size, sizeof(fstring)-1);
263                 strncpy(old_style_pw, data, size);
264                 old_style_pw[size] = 0;
265
266                 SAFE_FREE(data);
267
268                 if (!secrets_store_ldap_pw(*dn, old_style_pw)) {
269                         DEBUG(0,("fetch_ldap_pw: ldap secret could not be upgraded!\n"));
270                         SAFE_FREE(old_style_key);
271                         SAFE_FREE(*dn);
272                         return False;                   
273                 }
274                 if (!secrets_delete(old_style_key)) {
275                         DEBUG(0,("fetch_ldap_pw: old ldap secret could not be deleted!\n"));
276                 }
277
278                 SAFE_FREE(old_style_key);
279
280                 *pw = smb_xstrdup(old_style_pw);                
281         }
282         
283         return True;
284 }
285
286 /*******************************************************************
287  Search an attribute and return the first value found.
288 ******************************************************************/
289
290  BOOL smbldap_get_single_attribute (LDAP * ldap_struct, LDAPMessage * entry,
291                                    const char *attribute, pstring value)
292 {
293         char **values;
294         
295         if ( !attribute )
296                 return False;
297                 
298         value[0] = '\0';
299
300         if ((values = ldap_get_values (ldap_struct, entry, attribute)) == NULL) {
301                 DEBUG (10, ("smbldap_get_single_attribute: [%s] = [<does not exist>]\n", attribute));
302                 
303                 return False;
304         }
305         
306         if (convert_string(CH_UTF8, CH_UNIX,values[0], -1, value, sizeof(pstring)) == (size_t)-1) {
307                 DEBUG(1, ("smbldap_get_single_attribute: string conversion of [%s] = [%s] failed!\n", 
308                           attribute, values[0]));
309                 ldap_value_free(values);
310                 return False;
311         }
312         
313         ldap_value_free(values);
314 #ifdef DEBUG_PASSWORDS
315         DEBUG (100, ("smbldap_get_single_attribute: [%s] = [%s]\n", attribute, value));
316 #endif  
317         return True;
318 }
319
320 /************************************************************************
321  Routine to manage the LDAPMod structure array
322  manage memory used by the array, by each struct, and values
323  ***********************************************************************/
324
325  void smbldap_set_mod (LDAPMod *** modlist, int modop, const char *attribute, const char *value)
326 {
327         LDAPMod **mods;
328         int i;
329         int j;
330
331         mods = *modlist;
332
333         /* sanity checks on the mod values */
334
335         if (attribute == NULL || *attribute == '\0')
336                 return; 
337 #if 0   /* commented out after discussion with abartlet.  Do not reenable.
338            left here so other so re-add similar code   --jerry */
339         if (value == NULL || *value == '\0')
340                 return;
341 #endif
342
343         if (mods == NULL) 
344         {
345                 mods = (LDAPMod **) malloc(sizeof(LDAPMod *));
346                 if (mods == NULL)
347                 {
348                         DEBUG(0, ("make_a_mod: out of memory!\n"));
349                         return;
350                 }
351                 mods[0] = NULL;
352         }
353
354         for (i = 0; mods[i] != NULL; ++i) {
355                 if (mods[i]->mod_op == modop && strequal(mods[i]->mod_type, attribute))
356                         break;
357         }
358
359         if (mods[i] == NULL)
360         {
361                 mods = (LDAPMod **) Realloc (mods, (i + 2) * sizeof (LDAPMod *));
362                 if (mods == NULL)
363                 {
364                         DEBUG(0, ("make_a_mod: out of memory!\n"));
365                         return;
366                 }
367                 mods[i] = (LDAPMod *) malloc(sizeof(LDAPMod));
368                 if (mods[i] == NULL)
369                 {
370                         DEBUG(0, ("make_a_mod: out of memory!\n"));
371                         return;
372                 }
373                 mods[i]->mod_op = modop;
374                 mods[i]->mod_values = NULL;
375                 mods[i]->mod_type = strdup(attribute);
376                 mods[i + 1] = NULL;
377         }
378
379         if (value != NULL)
380         {
381                 char *utf8_value = NULL;
382
383                 j = 0;
384                 if (mods[i]->mod_values != NULL) {
385                         for (; mods[i]->mod_values[j] != NULL; j++);
386                 }
387                 mods[i]->mod_values = (char **)Realloc(mods[i]->mod_values,
388                                                (j + 2) * sizeof (char *));
389                                                
390                 if (mods[i]->mod_values == NULL) {
391                         DEBUG (0, ("make_a_mod: Memory allocation failure!\n"));
392                         return;
393                 }
394
395                 if (push_utf8_allocate(&utf8_value, value) == (size_t)-1) {
396                         DEBUG (0, ("make_a_mod: String conversion failure!\n"));
397                         return;
398                 }
399
400                 mods[i]->mod_values[j] = utf8_value;
401
402                 mods[i]->mod_values[j + 1] = NULL;
403         }
404         *modlist = mods;
405 }
406
407 /**********************************************************************
408   Set attribute to newval in LDAP, regardless of what value the
409   attribute had in LDAP before.
410 *********************************************************************/
411
412  void smbldap_make_mod(LDAP *ldap_struct, LDAPMessage *existing,
413                       LDAPMod ***mods,
414                       const char *attribute, const char *newval)
415 {
416         pstring oldval;
417         BOOL existed;
418
419         if (existing != NULL) {
420                 existed = smbldap_get_single_attribute(ldap_struct, existing, attribute, oldval);
421         } else {
422                 existed = False;
423                 *oldval = '\0';
424         }
425
426         /* all of our string attributes are case insensitive */
427         
428         if (existed && (StrCaseCmp(oldval, newval) == 0)) {
429                 
430                 /* Believe it or not, but LDAP will deny a delete and
431                    an add at the same time if the values are the
432                    same... */
433                 return;
434         }
435
436         /* Regardless of the real operation (add or modify)
437            we add the new value here. We rely on deleting
438            the old value, should it exist. */
439
440         if ((newval != NULL) && (strlen(newval) > 0)) {
441                 if (existed) {
442                         /* There has been no value before, so don't delete it.
443                          * Here's a possible race: We might end up with
444                          * duplicate attributes */
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                         /* This will also allow modifying single valued attributes 
450                          * in Novell NDS. In NDS you have to first remove attribute and then
451                          * you could add new value */
452
453                          smbldap_set_mod(mods, LDAP_MOD_DELETE, attribute, oldval);
454                 }
455
456                 smbldap_set_mod(mods, LDAP_MOD_ADD, attribute, newval);
457         }
458 }
459
460 /**********************************************************************
461  Some varients of the LDAP rebind code do not pass in the third 'arg' 
462  pointer to a void*, so we try and work around it by assuming that the 
463  value of the 'LDAP *' pointer is the same as the one we had passed in
464  **********************************************************************/
465
466 struct smbldap_state_lookup {
467         LDAP *ld;
468         struct smbldap_state *smbldap_state;
469         struct smbldap_state_lookup *prev, *next;
470 };
471
472 static struct smbldap_state_lookup *smbldap_state_lookup_list;
473
474 static struct smbldap_state *smbldap_find_state(LDAP *ld) 
475 {
476         struct smbldap_state_lookup *t;
477
478         for (t = smbldap_state_lookup_list; t; t = t->next) {
479                 if (t->ld == ld) {
480                         return t->smbldap_state;
481                 }
482         }
483         return NULL;
484 }
485
486 static void smbldap_delete_state(struct smbldap_state *smbldap_state) 
487 {
488         struct smbldap_state_lookup *t;
489
490         for (t = smbldap_state_lookup_list; t; t = t->next) {
491                 if (t->smbldap_state == smbldap_state) {
492                         DLIST_REMOVE(smbldap_state_lookup_list, t);
493                         SAFE_FREE(t);
494                         return;
495                 }
496         }
497 }
498
499 static void smbldap_store_state(LDAP *ld, struct smbldap_state *smbldap_state) 
500 {
501         struct smbldap_state *tmp_ldap_state;
502         struct smbldap_state_lookup *t;
503         struct smbldap_state_lookup *tmp;
504         
505         if ((tmp_ldap_state = smbldap_find_state(ld))) {
506                 SMB_ASSERT(tmp_ldap_state == smbldap_state);
507                 return;
508         }
509
510         t = smb_xmalloc(sizeof(*t));
511         ZERO_STRUCTP(t);
512         
513         DLIST_ADD_END(smbldap_state_lookup_list, t, tmp);
514         t->ld = ld;
515         t->smbldap_state = smbldap_state;
516 }
517
518 /*******************************************************************
519  open a connection to the ldap server.
520 ******************************************************************/
521 static int smbldap_open_connection (struct smbldap_state *ldap_state)
522
523 {
524         int rc = LDAP_SUCCESS;
525         int version;
526         BOOL ldap_v3 = False;
527         LDAP **ldap_struct = &ldap_state->ldap_struct;
528
529 #ifdef HAVE_LDAP_INITIALIZE
530         DEBUG(10, ("smbldap_open_connection: %s\n", ldap_state->uri));
531         
532         if ((rc = ldap_initialize(ldap_struct, ldap_state->uri)) != LDAP_SUCCESS) {
533                 DEBUG(0, ("ldap_initialize: %s\n", ldap_err2string(rc)));
534                 return rc;
535         }
536 #else 
537
538         /* Parse the string manually */
539
540         {
541                 int port = 0;
542                 fstring protocol;
543                 fstring host;
544                 const char *p = ldap_state->uri; 
545                 SMB_ASSERT(sizeof(protocol)>10 && sizeof(host)>254);
546                 
547                 /* skip leading "URL:" (if any) */
548                 if ( strnequal( p, "URL:", 4 ) ) {
549                         p += 4;
550                 }
551                 
552                 sscanf(p, "%10[^:]://%254[^:/]:%d", protocol, host, &port);
553                 
554                 if (port == 0) {
555                         if (strequal(protocol, "ldap")) {
556                                 port = LDAP_PORT;
557                         } else if (strequal(protocol, "ldaps")) {
558                                 port = LDAPS_PORT;
559                         } else {
560                                 DEBUG(0, ("unrecognised protocol (%s)!\n", protocol));
561                         }
562                 }
563                 
564                 if ((*ldap_struct = ldap_init(host, port)) == NULL)     {
565                         DEBUG(0, ("ldap_init failed !\n"));
566                         return LDAP_OPERATIONS_ERROR;
567                 }
568                 
569                 if (strequal(protocol, "ldaps")) {
570 #ifdef LDAP_OPT_X_TLS
571                         int tls = LDAP_OPT_X_TLS_HARD;
572                         if (ldap_set_option (*ldap_struct, LDAP_OPT_X_TLS, &tls) != LDAP_SUCCESS)
573                         {
574                                 DEBUG(0, ("Failed to setup a TLS session\n"));
575                         }
576                         
577                         DEBUG(3,("LDAPS option set...!\n"));
578 #else
579                         DEBUG(0,("smbldap_open_connection: Secure connection not supported by LDAP client libraries!\n"));
580                         return LDAP_OPERATIONS_ERROR;
581 #endif
582                 }
583         }
584 #endif
585
586         /* Store the LDAP pointer in a lookup list */
587
588         smbldap_store_state(*ldap_struct, ldap_state);
589
590         /* Upgrade to LDAPv3 if possible */
591
592         if (ldap_get_option(*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS)
593         {
594                 if (version != LDAP_VERSION3)
595                 {
596                         version = LDAP_VERSION3;
597                         if (ldap_set_option (*ldap_struct, LDAP_OPT_PROTOCOL_VERSION, &version) == LDAP_OPT_SUCCESS) {
598                                 ldap_v3 = True;
599                         }
600                 } else {
601                         ldap_v3 = True;
602                 }
603         }
604
605         if (lp_ldap_ssl() == LDAP_SSL_START_TLS) {
606 #ifdef LDAP_OPT_X_TLS
607                 if (ldap_v3) {
608                         if ((rc = ldap_start_tls_s (*ldap_struct, NULL, NULL)) != LDAP_SUCCESS)
609                         {
610                                 DEBUG(0,("Failed to issue the StartTLS instruction: %s\n",
611                                          ldap_err2string(rc)));
612                                 return rc;
613                         }
614                         DEBUG (3, ("StartTLS issued: using a TLS connection\n"));
615                 } else {
616                         
617                         DEBUG(0, ("Need LDAPv3 for Start TLS\n"));
618                         return LDAP_OPERATIONS_ERROR;
619                 }
620 #else
621                 DEBUG(0,("smbldap_open_connection: StartTLS not supported by LDAP client libraries!\n"));
622                 return LDAP_OPERATIONS_ERROR;
623 #endif
624         }
625
626         DEBUG(2, ("smbldap_open_connection: connection opened\n"));
627         return rc;
628 }
629
630
631 /*******************************************************************
632  a rebind function for authenticated referrals
633  This version takes a void* that we can shove useful stuff in :-)
634 ******************************************************************/
635 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
636 #else
637 static int rebindproc_with_state  (LDAP * ld, char **whop, char **credp, 
638                                    int *methodp, int freeit, void *arg)
639 {
640         struct smbldap_state *ldap_state = arg;
641         
642         /** @TODO Should we be doing something to check what servers we rebind to?
643             Could we get a referral to a machine that we don't want to give our
644             username and password to? */
645         
646         if (freeit) {
647                 SAFE_FREE(*whop);
648                 memset(*credp, '\0', strlen(*credp));
649                 SAFE_FREE(*credp);
650         } else {
651                 DEBUG(5,("rebind_proc_with_state: Rebinding as \"%s\"\n", 
652                           ldap_state->bind_dn));
653
654                 *whop = strdup(ldap_state->bind_dn);
655                 if (!*whop) {
656                         return LDAP_NO_MEMORY;
657                 }
658                 *credp = strdup(ldap_state->bind_secret);
659                 if (!*credp) {
660                         SAFE_FREE(*whop);
661                         return LDAP_NO_MEMORY;
662                 }
663                 *methodp = LDAP_AUTH_SIMPLE;
664         }
665
666         gettimeofday(&(ldap_state->last_rebind),NULL);
667                 
668         return 0;
669 }
670 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
671
672 /*******************************************************************
673  a rebind function for authenticated referrals
674  This version takes a void* that we can shove useful stuff in :-)
675  and actually does the connection.
676 ******************************************************************/
677 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
678 static int rebindproc_connect_with_state (LDAP *ldap_struct, 
679                                           LDAP_CONST char *url, 
680                                           ber_tag_t request,
681                                           ber_int_t msgid, void *arg)
682 {
683         struct smbldap_state *ldap_state = arg;
684         int rc;
685         DEBUG(5,("rebindproc_connect_with_state: Rebinding as \"%s\"\n", 
686                  ldap_state->bind_dn));
687         
688         /** @TODO Should we be doing something to check what servers we rebind to?
689             Could we get a referral to a machine that we don't want to give our
690             username and password to? */
691
692         rc = ldap_simple_bind_s(ldap_struct, ldap_state->bind_dn, ldap_state->bind_secret);
693         
694         gettimeofday(&(ldap_state->last_rebind),NULL);
695
696         return rc;
697 }
698 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
699
700 /*******************************************************************
701  Add a rebind function for authenticated referrals
702 ******************************************************************/
703 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
704 #else
705 # if LDAP_SET_REBIND_PROC_ARGS == 2
706 static int rebindproc (LDAP *ldap_struct, char **whop, char **credp,
707                        int *method, int freeit )
708 {
709         struct smbldap_state *ldap_state = smbldap_find_state(ldap_struct);
710
711         return rebindproc_with_state(ldap_struct, whop, credp,
712                                      method, freeit, ldap_state);
713         
714 }
715 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
716 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
717
718 /*******************************************************************
719  a rebind function for authenticated referrals
720  this also does the connection, but no void*.
721 ******************************************************************/
722 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
723 # if LDAP_SET_REBIND_PROC_ARGS == 2
724 static int rebindproc_connect (LDAP * ld, LDAP_CONST char *url, int request,
725                                ber_int_t msgid)
726 {
727         struct smbldap_state *ldap_state = smbldap_find_state(ld);
728
729         return rebindproc_connect_with_state(ld, url, (ber_tag_t)request, msgid, 
730                                              ldap_state);
731 }
732 # endif /*LDAP_SET_REBIND_PROC_ARGS == 2*/
733 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
734
735 /*******************************************************************
736  connect to the ldap server under system privilege.
737 ******************************************************************/
738 static int smbldap_connect_system(struct smbldap_state *ldap_state, LDAP * ldap_struct)
739 {
740         int rc;
741         char *ldap_dn;
742         char *ldap_secret;
743
744         /* get the password */
745         if (!fetch_ldap_pw(&ldap_dn, &ldap_secret))
746         {
747                 DEBUG(0, ("ldap_connect_system: Failed to retrieve password from secrets.tdb\n"));
748                 return LDAP_INVALID_CREDENTIALS;
749         }
750
751         ldap_state->bind_dn = ldap_dn;
752         ldap_state->bind_secret = ldap_secret;
753
754         /* removed the sasl_bind_s "EXTERNAL" stuff, as my testsuite 
755            (OpenLDAP) doesnt' seem to support it */
756            
757         DEBUG(10,("ldap_connect_system: Binding to ldap server %s as \"%s\"\n",
758                   ldap_state->uri, ldap_dn));
759
760 #if defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)
761 # if LDAP_SET_REBIND_PROC_ARGS == 2     
762         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect); 
763 # endif
764 # if LDAP_SET_REBIND_PROC_ARGS == 3     
765         ldap_set_rebind_proc(ldap_struct, &rebindproc_connect_with_state, (void *)ldap_state);  
766 # endif
767 #else /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
768 # if LDAP_SET_REBIND_PROC_ARGS == 2     
769         ldap_set_rebind_proc(ldap_struct, &rebindproc); 
770 # endif
771 # if LDAP_SET_REBIND_PROC_ARGS == 3     
772         ldap_set_rebind_proc(ldap_struct, &rebindproc_with_state, (void *)ldap_state);  
773 # endif
774 #endif /*defined(LDAP_API_FEATURE_X_OPENLDAP) && (LDAP_API_VERSION > 2000)*/
775
776         rc = ldap_simple_bind_s(ldap_struct, ldap_dn, ldap_secret);
777
778         if (rc != LDAP_SUCCESS) {
779                 char *ld_error = NULL;
780                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
781                                 &ld_error);
782                 DEBUG(ldap_state->num_failures ? 2 : 0,
783                       ("failed to bind to server with dn= %s Error: %s\n\t%s\n",
784                                ldap_dn ? ldap_dn : "(unknown)", ldap_err2string(rc),
785                                ld_error ? ld_error : "(unknown)"));
786                 SAFE_FREE(ld_error);
787                 ldap_state->num_failures++;
788                 return rc;
789         }
790
791         ldap_state->num_failures = 0;
792
793         DEBUG(3, ("ldap_connect_system: succesful connection to the LDAP server\n"));
794         return rc;
795 }
796
797 /**********************************************************************
798 Connect to LDAP server (called before every ldap operation)
799 *********************************************************************/
800 static int smbldap_open(struct smbldap_state *ldap_state)
801 {
802         int rc;
803         SMB_ASSERT(ldap_state);
804                 
805 #ifndef NO_LDAP_SECURITY
806         if (geteuid() != 0) {
807                 DEBUG(0, ("smbldap_open: cannot access LDAP when not root..\n"));
808                 return  LDAP_INSUFFICIENT_ACCESS;
809         }
810 #endif
811
812         if ((ldap_state->ldap_struct != NULL) && ((ldap_state->last_ping + SMBLDAP_DONT_PING_TIME) < time(NULL))) {
813                 struct sockaddr_un addr;
814                 socklen_t len = sizeof(addr);
815                 int sd;
816                 if (ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_DESC, &sd) == 0 &&
817                     getpeername(sd, (struct sockaddr *) &addr, &len) < 0) {
818                         /* the other end has died. reopen. */
819                         ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
820                         ldap_state->ldap_struct = NULL;
821                         ldap_state->last_ping = (time_t)0;
822                 } else {
823                         ldap_state->last_ping = time(NULL);
824                 } 
825         }
826
827         if (ldap_state->ldap_struct != NULL) {
828                 DEBUG(11,("smbldap_open: already connected to the LDAP server\n"));
829                 return LDAP_SUCCESS;
830         }
831
832         if ((rc = smbldap_open_connection(ldap_state))) {
833                 return rc;
834         }
835
836         if ((rc = smbldap_connect_system(ldap_state, ldap_state->ldap_struct))) {
837                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
838                 ldap_state->ldap_struct = NULL;
839                 return rc;
840         }
841
842
843         ldap_state->last_ping = time(NULL);
844         DEBUG(4,("The LDAP server is succesful connected\n"));
845
846         return LDAP_SUCCESS;
847 }
848
849 /**********************************************************************
850 Disconnect from LDAP server 
851 *********************************************************************/
852 static NTSTATUS smbldap_close(struct smbldap_state *ldap_state)
853 {
854         if (!ldap_state)
855                 return NT_STATUS_INVALID_PARAMETER;
856                 
857         if (ldap_state->ldap_struct != NULL) {
858                 ldap_unbind_ext(ldap_state->ldap_struct, NULL, NULL);
859                 ldap_state->ldap_struct = NULL;
860         }
861
862         smbldap_delete_state(ldap_state);
863         
864         DEBUG(5,("The connection to the LDAP server was closed\n"));
865         /* maybe free the results here --metze */
866         
867         
868
869         return NT_STATUS_OK;
870 }
871
872 int smbldap_retry_open(struct smbldap_state *ldap_state, int *attempts)
873 {
874         int rc;
875
876         SMB_ASSERT(ldap_state && attempts);
877                 
878         if (*attempts != 0) {
879                 unsigned int sleep_time;
880                 uint8 rand_byte;
881
882                 /* Sleep for a random timeout */
883                 rand_byte = (char)(sys_random());
884
885                 sleep_time = (((*attempts)*(*attempts))/2)*rand_byte*2; 
886                 /* we retry after (0.5, 1, 2, 3, 4.5, 6) seconds
887                    on average.  
888                  */
889                 DEBUG(3, ("Sleeping for %u milliseconds before reconnecting\n", 
890                           sleep_time));
891                 msleep(sleep_time);
892         }
893         (*attempts)++;
894
895         if ((rc = smbldap_open(ldap_state))) {
896                 DEBUG(1,("Connection to LDAP Server failed for the %d try!\n",*attempts));
897                 return rc;
898         } 
899         
900         return LDAP_SUCCESS;            
901 }
902
903
904 /*********************************************************************
905  ********************************************************************/
906
907 int smbldap_search(struct smbldap_state *ldap_state, 
908                    const char *base, int scope, const char *filter, 
909                    char *attrs[], int attrsonly, 
910                    LDAPMessage **res)
911 {
912         int             rc = LDAP_SERVER_DOWN;
913         int             attempts = 0;
914         char           *utf8_filter;
915
916         SMB_ASSERT(ldap_state);
917         
918         DEBUG(5,("smbldap_search: base => [%s], filter => [%s], scope => [%d]\n",
919                 base, filter, scope));
920
921         if (ldap_state->last_rebind.tv_sec > 0) {
922                 struct timeval  tval;
923                 int             tdiff = 0;
924                 int             sleep_time = 0;
925
926                 ZERO_STRUCT(tval);
927
928                 gettimeofday(&tval,NULL);
929
930                 tdiff = 1000000 *(tval.tv_sec - ldap_state->last_rebind.tv_sec) + 
931                         (tval.tv_usec - ldap_state->last_rebind.tv_usec);
932
933                 sleep_time = ((1000*lp_ldap_replication_sleep())-tdiff)/1000;
934
935                 if (sleep_time > 0) {
936                         /* we wait for the LDAP replication */
937                         DEBUG(5,("smbldap_search: waiting %d milliseconds for LDAP replication.\n",sleep_time));
938                         msleep(sleep_time);
939                         DEBUG(5,("smbldap_search: go on!\n"));
940                         ZERO_STRUCT(ldap_state->last_rebind);
941                 }
942         }
943
944         if (push_utf8_allocate(&utf8_filter, filter) == (size_t)-1) {
945                 return LDAP_NO_MEMORY;
946         }
947
948         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
949                 
950                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
951                         continue;
952                 
953                 rc = ldap_search_s(ldap_state->ldap_struct, base, scope, 
954                                    utf8_filter, attrs, attrsonly, res);
955         }
956         
957         if (rc == LDAP_SERVER_DOWN) {
958                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
959                 smbldap_close(ldap_state);      
960         }
961
962         ldap_state->last_use = time(NULL);
963
964         SAFE_FREE(utf8_filter);
965         return rc;
966 }
967
968 int smbldap_modify(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
969 {
970         int             rc = LDAP_SERVER_DOWN;
971         int             attempts = 0;
972         char           *utf8_dn;
973
974         SMB_ASSERT(ldap_state);
975
976         DEBUG(5,("smbldap_modify: dn => [%s]\n", dn ));
977
978         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
979                 return LDAP_NO_MEMORY;
980         }
981
982         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
983                 
984                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
985                         continue;
986                 
987                 rc = ldap_modify_s(ldap_state->ldap_struct, utf8_dn, attrs);
988         }
989         
990         if (rc == LDAP_SERVER_DOWN) {
991                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
992                 smbldap_close(ldap_state);      
993         }
994         
995         ldap_state->last_use = time(NULL);
996
997         SAFE_FREE(utf8_dn);
998         return rc;
999 }
1000
1001 int smbldap_add(struct smbldap_state *ldap_state, const char *dn, LDAPMod *attrs[])
1002 {
1003         int             rc = LDAP_SERVER_DOWN;
1004         int             attempts = 0;
1005         char           *utf8_dn;
1006         
1007         SMB_ASSERT(ldap_state);
1008
1009         DEBUG(5,("smbldap_add: dn => [%s]\n", dn ));
1010
1011         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1012                 return LDAP_NO_MEMORY;
1013         }
1014
1015         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1016                 
1017                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1018                         continue;
1019                 
1020                 rc = ldap_add_s(ldap_state->ldap_struct, utf8_dn, attrs);
1021         }
1022         
1023         if (rc == LDAP_SERVER_DOWN) {
1024                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1025                 smbldap_close(ldap_state);      
1026         }
1027                 
1028         ldap_state->last_use = time(NULL);
1029
1030         SAFE_FREE(utf8_dn);
1031         return rc;
1032 }
1033
1034 int smbldap_delete(struct smbldap_state *ldap_state, const char *dn)
1035 {
1036         int             rc = LDAP_SERVER_DOWN;
1037         int             attempts = 0;
1038         char           *utf8_dn;
1039         
1040         SMB_ASSERT(ldap_state);
1041
1042         DEBUG(5,("smbldap_delete: dn => [%s]\n", dn ));
1043
1044         if (push_utf8_allocate(&utf8_dn, dn) == (size_t)-1) {
1045                 return LDAP_NO_MEMORY;
1046         }
1047
1048         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1049                 
1050                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1051                         continue;
1052                 
1053                 rc = ldap_delete_s(ldap_state->ldap_struct, utf8_dn);
1054         }
1055         
1056         if (rc == LDAP_SERVER_DOWN) {
1057                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1058                 smbldap_close(ldap_state);      
1059         }
1060                 
1061         ldap_state->last_use = time(NULL);
1062
1063         SAFE_FREE(utf8_dn);
1064         return rc;
1065 }
1066
1067 int smbldap_extended_operation(struct smbldap_state *ldap_state, 
1068                                LDAP_CONST char *reqoid, struct berval *reqdata, 
1069                                LDAPControl **serverctrls, LDAPControl **clientctrls, 
1070                                char **retoidp, struct berval **retdatap)
1071 {
1072         int             rc = LDAP_SERVER_DOWN;
1073         int             attempts = 0;
1074         
1075         if (!ldap_state)
1076                 return (-1);
1077
1078         while ((rc == LDAP_SERVER_DOWN) && (attempts < SMBLDAP_NUM_RETRIES)) {
1079                 
1080                 if ((rc = smbldap_retry_open(ldap_state,&attempts)) != LDAP_SUCCESS)
1081                         continue;
1082                 
1083                 rc = ldap_extended_operation_s(ldap_state->ldap_struct, reqoid, reqdata, 
1084                                                serverctrls, clientctrls, retoidp, retdatap);
1085         }
1086         
1087         if (rc == LDAP_SERVER_DOWN) {
1088                 DEBUG(0,("%s: LDAP server is down!\n",FUNCTION_MACRO));
1089                 smbldap_close(ldap_state);      
1090         }
1091                 
1092         ldap_state->last_use = time(NULL);
1093
1094         return rc;
1095 }
1096
1097 /*******************************************************************
1098  run the search by name.
1099 ******************************************************************/
1100 int smbldap_search_suffix (struct smbldap_state *ldap_state, const char *filter, 
1101                            char **search_attr, LDAPMessage ** result)
1102 {
1103         int scope = LDAP_SCOPE_SUBTREE;
1104         int rc;
1105
1106         rc = smbldap_search(ldap_state, lp_ldap_suffix(), scope, filter, search_attr, 0, result);
1107
1108         if (rc != LDAP_SUCCESS) {
1109                 char *ld_error = NULL;
1110                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING,
1111                                 &ld_error);
1112                 DEBUG(0,("smbldap_search_suffix: Problem during the LDAP search: %s (%s)\n", 
1113                         ld_error?ld_error:"(unknown)", ldap_err2string (rc)));
1114                 SAFE_FREE(ld_error);
1115         }
1116         
1117         return rc;
1118 }
1119
1120 static void smbldap_idle_fn(void **data, time_t *interval, time_t now)
1121 {
1122         struct smbldap_state *state = (struct smbldap_state *)(*data);
1123
1124         if (state->ldap_struct == NULL) {
1125                 DEBUG(10,("ldap connection not connected...\n"));
1126                 return;
1127         }
1128                 
1129         if ((state->last_use+SMBLDAP_IDLE_TIME) > now) {
1130                 DEBUG(10,("ldap connection not idle...\n"));
1131                 return;
1132         }
1133                 
1134         DEBUG(7,("ldap connection idle...closing connection\n"));
1135         smbldap_close(state);
1136 }
1137
1138 /**********************************************************************
1139  Housekeeping
1140  *********************************************************************/
1141
1142 void smbldap_free_struct(struct smbldap_state **ldap_state) 
1143 {
1144         smbldap_close(*ldap_state);
1145         
1146         if ((*ldap_state)->bind_secret) {
1147                 memset((*ldap_state)->bind_secret, '\0', strlen((*ldap_state)->bind_secret));
1148         }
1149
1150         SAFE_FREE((*ldap_state)->bind_dn);
1151         SAFE_FREE((*ldap_state)->bind_secret);
1152
1153         smb_unregister_idle_event((*ldap_state)->event_id);
1154
1155         *ldap_state = NULL;
1156
1157         /* No need to free any further, as it is talloc()ed */
1158 }
1159
1160
1161 /**********************************************************************
1162  Intitalise the 'general' ldap structures, on which ldap operations may be conducted
1163  *********************************************************************/
1164
1165 NTSTATUS smbldap_init(TALLOC_CTX *mem_ctx, const char *location, struct smbldap_state **smbldap_state) 
1166 {
1167         *smbldap_state = talloc_zero(mem_ctx, sizeof(**smbldap_state));
1168         if (!*smbldap_state) {
1169                 DEBUG(0, ("talloc() failed for ldapsam private_data!\n"));
1170                 return NT_STATUS_NO_MEMORY;
1171         }
1172
1173         if (location) {
1174                 (*smbldap_state)->uri = talloc_strdup(mem_ctx, location);
1175         } else {
1176                 (*smbldap_state)->uri = "ldap://localhost";
1177         }
1178
1179         (*smbldap_state)->event_id =
1180                 smb_register_idle_event(smbldap_idle_fn, (void *)(*smbldap_state),
1181                                         SMBLDAP_IDLE_TIME);
1182
1183         if ((*smbldap_state)->event_id == SMB_EVENT_ID_INVALID) {
1184                 DEBUG(0,("Failed to register LDAP idle event!\n"));
1185                 return NT_STATUS_INVALID_HANDLE;
1186         }
1187
1188         return NT_STATUS_OK;
1189 }
1190
1191 /**********************************************************************
1192  Add the sambaDomain to LDAP, so we don't have to search for this stuff
1193  again.  This is a once-add operation for now.
1194
1195  TODO:  Add other attributes, and allow modification.
1196 *********************************************************************/
1197 static NTSTATUS add_new_domain_info(struct smbldap_state *ldap_state, 
1198                                     const char *domain_name) 
1199 {
1200         fstring sid_string;
1201         fstring algorithmic_rid_base_string;
1202         pstring filter, dn;
1203         LDAPMod **mods = NULL;
1204         int rc;
1205         int ldap_op;
1206         LDAPMessage *result = NULL;
1207         int num_result;
1208         char **attr_list;
1209         uid_t u_low, u_high;
1210         gid_t g_low, g_high;
1211         uint32 rid_low, rid_high;
1212
1213         slprintf (filter, sizeof (filter) - 1, "(&(%s=%s)(objectclass=%s))", 
1214                   get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1215                   domain_name, LDAP_OBJ_DOMINFO);
1216
1217         attr_list = get_attr_list( dominfo_attr_list );
1218         rc = smbldap_search_suffix(ldap_state, filter, attr_list, &result);
1219         free_attr_list( attr_list );
1220
1221         if (rc != LDAP_SUCCESS) {
1222                 return NT_STATUS_UNSUCCESSFUL;
1223         }
1224
1225         num_result = ldap_count_entries(ldap_state->ldap_struct, result);
1226         
1227         if (num_result > 1) {
1228                 DEBUG (0, ("More than domain with that name exists: bailing out!\n"));
1229                 ldap_msgfree(result);
1230                 return NT_STATUS_UNSUCCESSFUL;
1231         }
1232         
1233         /* Check if we need to add an entry */
1234         DEBUG(3,("Adding new domain\n"));
1235         ldap_op = LDAP_MOD_ADD;
1236
1237         pstr_sprintf(dn, "%s=%s,%s", get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN),
1238                 domain_name, lp_ldap_suffix());
1239
1240         /* Free original search */
1241         ldap_msgfree(result);
1242
1243         /* make the changes - the entry *must* not already have samba attributes */
1244         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1245                 domain_name);
1246
1247         /* If we don't have an entry, then ask secrets.tdb for what it thinks.  
1248            It may choose to make it up */
1249
1250         sid_to_string(sid_string, get_global_sam_sid());
1251         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOM_SID), sid_string);
1252
1253         slprintf(algorithmic_rid_base_string, sizeof(algorithmic_rid_base_string) - 1, "%i", algorithmic_rid_base());
1254         smbldap_set_mod(&mods, LDAP_MOD_ADD, get_attr_key2string(dominfo_attr_list, LDAP_ATTR_ALGORITHMIC_RID_BASE), 
1255                         algorithmic_rid_base_string);
1256         smbldap_set_mod(&mods, LDAP_MOD_ADD, "objectclass", LDAP_OBJ_DOMINFO);
1257         
1258         /* add the sambaNext[User|Group]Rid attributes if the idmap ranges are set.
1259            TODO: fix all the places where the line between idmap and normal operations
1260            needed by smbd gets fuzzy   --jerry 2003-08-11                              */
1261         
1262         if ( lp_idmap_uid(&u_low, &u_high) && lp_idmap_gid(&g_low, &g_high)
1263                 && get_free_rid_range(&rid_low, &rid_high) ) 
1264         {
1265                 fstring rid_str;
1266                 
1267                 fstr_sprintf( rid_str, "%i", rid_high|USER_RID_TYPE );
1268                 DEBUG(10,("setting next available user rid [%s]\n", rid_str));
1269                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1270                         get_attr_key2string(dominfo_attr_list, LDAP_ATTR_NEXT_USERRID), 
1271                         rid_str);
1272                         
1273                 fstr_sprintf( rid_str, "%i", rid_high|GROUP_RID_TYPE );
1274                 DEBUG(10,("setting next available group rid [%s]\n", rid_str));
1275                 smbldap_set_mod(&mods, LDAP_MOD_ADD, 
1276                         get_attr_key2string(dominfo_attr_list, LDAP_ATTR_NEXT_GROUPRID), 
1277                         rid_str);
1278                 
1279         }
1280
1281
1282         switch(ldap_op)
1283         {
1284         case LDAP_MOD_ADD: 
1285                 rc = smbldap_add(ldap_state, dn, mods);
1286                 break;
1287         case LDAP_MOD_REPLACE: 
1288                 rc = smbldap_modify(ldap_state, dn, mods);
1289                 break;
1290         default:        
1291                 DEBUG(0,("Wrong LDAP operation type: %d!\n", ldap_op));
1292                 return NT_STATUS_INVALID_PARAMETER;
1293         }
1294         
1295         if (rc!=LDAP_SUCCESS) {
1296                 char *ld_error = NULL;
1297                 ldap_get_option(ldap_state->ldap_struct, LDAP_OPT_ERROR_STRING, &ld_error);
1298                 DEBUG(1,("failed to %s domain dn= %s with: %s\n\t%s\n",
1299                        ldap_op == LDAP_MOD_ADD ? "add" : "modify",
1300                        dn, ldap_err2string(rc),
1301                        ld_error?ld_error:"unknown"));
1302                 SAFE_FREE(ld_error);
1303
1304                 ldap_mods_free(mods, True);
1305                 return NT_STATUS_UNSUCCESSFUL;
1306         }
1307
1308         DEBUG(2,("added: domain = %s in the LDAP database\n", domain_name));
1309         ldap_mods_free(mods, True);
1310         return NT_STATUS_OK;
1311 }
1312
1313 /**********************************************************************
1314 Search for the domain info entry
1315 *********************************************************************/
1316 NTSTATUS smbldap_search_domain_info(struct smbldap_state *ldap_state,
1317                                     LDAPMessage ** result, const char *domain_name,
1318                                     BOOL try_add)
1319 {
1320         NTSTATUS ret = NT_STATUS_UNSUCCESSFUL;
1321         pstring filter;
1322         int rc;
1323         char **attr_list;
1324         int count;
1325
1326         pstr_sprintf(filter, "(&(objectClass=%s)(%s=%s))",
1327                 LDAP_OBJ_DOMINFO,
1328                 get_attr_key2string(dominfo_attr_list, LDAP_ATTR_DOMAIN), 
1329                 domain_name);
1330
1331         DEBUG(2, ("Searching for:[%s]\n", filter));
1332
1333
1334         attr_list = get_attr_list( dominfo_attr_list );
1335         rc = smbldap_search_suffix(ldap_state, filter, attr_list , result);
1336         free_attr_list( attr_list );
1337
1338         if (rc != LDAP_SUCCESS) {
1339                 DEBUG(2,("Problem during LDAPsearch: %s\n", ldap_err2string (rc)));
1340                 DEBUG(2,("Query was: %s, %s\n", lp_ldap_suffix(), filter));
1341         } else if (ldap_count_entries(ldap_state->ldap_struct, *result) < 1) {
1342                 DEBUG(3, ("Got no domain info entries for domain\n"));
1343                 ldap_msgfree(*result);
1344                 *result = NULL;
1345                 if (try_add && NT_STATUS_IS_OK(ret = add_new_domain_info(ldap_state, domain_name))) {
1346                         return smbldap_search_domain_info(ldap_state, result, domain_name, False);
1347                 } 
1348                 else {
1349                         DEBUG(0, ("Adding domain info for %s failed with %s\n", 
1350                                 domain_name, nt_errstr(ret)));
1351                         return ret;
1352                 }
1353         } else if ((count = ldap_count_entries(ldap_state->ldap_struct, *result)) > 1) {
1354                 DEBUG(0, ("Got too many (%d) domain info entries for domain %s\n",
1355                           count, domain_name));
1356                 ldap_msgfree(*result);
1357                 *result = NULL;
1358                 return ret;
1359         } else {
1360                 return NT_STATUS_OK;
1361         }
1362         
1363         return ret;
1364 }
1365
1366 /*******************************************************************
1367  Return a copy of the DN for a LDAPMessage. Convert from utf8 to CH_UNIX.
1368 ********************************************************************/
1369
1370 char *smbldap_get_dn(LDAP *ld, LDAPMessage *entry)
1371 {
1372         char *utf8_dn, *unix_dn;
1373
1374         utf8_dn = ldap_get_dn(ld, entry);
1375         if (!utf8_dn) {
1376                 DEBUG (5, ("smbldap_get_dn: ldap_get_dn failed\n"));
1377                 return NULL;
1378         }
1379         if (pull_utf8_allocate(&unix_dn, utf8_dn) == (size_t)-1) {
1380                 DEBUG (0, ("smbldap_get_dn: String conversion failure utf8 [%s]\n", utf8_dn));
1381                 return NULL;
1382         }
1383         ldap_memfree(utf8_dn);
1384         return unix_dn;
1385 }