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