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