r139: Apply some const
[kai/samba-autobuild/.git] / source / nsswitch / winbindd_util.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon for ntdom nss module
5
6    Copyright (C) Tim Potter 2000-2001
7    Copyright (C) 2001 by Martin Pool <mbp@samba.org>
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25 #include "winbindd.h"
26
27 #undef DBGC_CLASS
28 #define DBGC_CLASS DBGC_WINBIND
29
30 /**
31  * @file winbindd_util.c
32  *
33  * Winbind daemon for NT domain authentication nss module.
34  **/
35
36
37 /**
38  * Used to clobber name fields that have an undefined value.
39  *
40  * Correct code should never look at a field that has this value.
41  **/
42
43 static const fstring name_deadbeef = "<deadbeef>";
44
45 /* The list of trusted domains.  Note that the list can be deleted and
46    recreated using the init_domain_list() function so pointers to
47    individual winbindd_domain structures cannot be made.  Keep a copy of
48    the domain name instead. */
49
50 static struct winbindd_domain *_domain_list;
51
52 /**
53    When was the last scan of trusted domains done?
54    
55    0 == not ever
56 */
57
58 static time_t last_trustdom_scan;
59
60 struct winbindd_domain *domain_list(void)
61 {
62         /* Initialise list */
63
64         if (!_domain_list) 
65                 if (!init_domain_list()) 
66                         return NULL;
67
68         return _domain_list;
69 }
70
71 /* Free all entries in the trusted domain list */
72
73 void free_domain_list(void)
74 {
75         struct winbindd_domain *domain = _domain_list;
76
77         while(domain) {
78                 struct winbindd_domain *next = domain->next;
79                 
80                 DLIST_REMOVE(_domain_list, domain);
81                 SAFE_FREE(domain);
82                 domain = next;
83         }
84 }
85
86 static BOOL is_internal_domain(const DOM_SID *sid)
87 {
88         DOM_SID tmp_sid;
89
90         if (sid_equal(sid, get_global_sam_sid()))
91                 return True;
92
93         string_to_sid(&tmp_sid, "S-1-5-32");
94         if (sid_equal(sid, &tmp_sid))
95                 return True;
96
97         return False;
98 }
99
100
101 /* Add a trusted domain to our list of domains */
102 static struct winbindd_domain *add_trusted_domain(const char *domain_name, const char *alt_name,
103                                                   struct winbindd_methods *methods,
104                                                   DOM_SID *sid)
105 {
106         struct winbindd_domain *domain;
107         const char *alternative_name = NULL;
108         static const DOM_SID null_sid;
109         
110         /* ignore alt_name if we are not in an AD domain */
111         
112         if ( (lp_security() == SEC_ADS) && alt_name && *alt_name) {
113                 alternative_name = alt_name;
114         }
115         
116         /* We can't call domain_list() as this function is called from
117            init_domain_list() and we'll get stuck in a loop. */
118         for (domain = _domain_list; domain; domain = domain->next) {
119                 if (strequal(domain_name, domain->name) ||
120                     strequal(domain_name, domain->alt_name)) {
121                         return domain;
122                 }
123                 if (alternative_name && *alternative_name) {
124                         if (strequal(alternative_name, domain->name) ||
125                             strequal(alternative_name, domain->alt_name)) {
126                                 return domain;
127                         }
128                 }
129                 if (sid) {
130                         if (sid_equal(sid, &null_sid) ) {
131                                 
132                         } else if (sid_equal(sid, &domain->sid)) {
133                                 return domain;
134                         }
135                 }
136         }
137         
138         /* Create new domain entry */
139
140         if ((domain = (struct winbindd_domain *)malloc(sizeof(*domain))) == NULL)
141                 return NULL;
142
143         /* Fill in fields */
144         
145         ZERO_STRUCTP(domain);
146
147         /* prioritise the short name */
148         if (strchr_m(domain_name, '.') && alternative_name && *alternative_name) {
149                 fstrcpy(domain->name, alternative_name);
150                 fstrcpy(domain->alt_name, domain_name);
151         } else {
152                 fstrcpy(domain->name, domain_name);
153                 if (alternative_name) {
154                         fstrcpy(domain->alt_name, alternative_name);
155                 }
156         }
157
158         domain->methods = methods;
159         domain->backend = NULL;
160         domain->internal = is_internal_domain(sid);
161         domain->sequence_number = DOM_SEQUENCE_NONE;
162         domain->last_seq_check = 0;
163         if (sid) {
164                 sid_copy(&domain->sid, sid);
165         }
166         
167         /* set flags about native_mode, active_directory */
168
169         if (!domain->internal)
170                 set_dc_type_and_flags( domain );
171         
172         DEBUG(3,("add_trusted_domain: %s is an %s %s domain\n", domain->name,
173                  domain->active_directory ? "ADS" : "NT4", 
174                  domain->native_mode ? "native mode" : 
175                  ((domain->active_directory && !domain->native_mode) ? "mixed mode" : "")));
176
177         /* Link to domain list */
178         DLIST_ADD(_domain_list, domain);
179         
180         DEBUG(1,("Added domain %s %s %s\n", 
181                  domain->name, domain->alt_name,
182                  &domain->sid?sid_string_static(&domain->sid):""));
183         
184         return domain;
185 }
186
187 /********************************************************************
188   rescan our domains looking for new trusted domains
189 ********************************************************************/
190
191 static void add_trusted_domains( struct winbindd_domain *domain )
192 {
193         TALLOC_CTX *mem_ctx;
194         NTSTATUS result;
195         time_t t;
196         char **names;
197         char **alt_names;
198         int num_domains = 0;
199         DOM_SID *dom_sids, null_sid;
200         int i;
201         struct winbindd_domain *new_domain;
202
203         /* trusted domains might be disabled */
204         if (!lp_allow_trusted_domains()) {
205                 return;
206         }
207
208         DEBUG(5, ("scanning trusted domain list\n"));
209
210         if (!(mem_ctx = talloc_init("init_domain_list")))
211                 return;
212            
213         ZERO_STRUCTP(&null_sid);
214
215         t = time(NULL);
216         
217         /* ask the DC what domains it trusts */
218         
219         result = domain->methods->trusted_domains(domain, mem_ctx, (unsigned int *)&num_domains,
220                 &names, &alt_names, &dom_sids);
221                 
222         if ( NT_STATUS_IS_OK(result) ) {
223
224                 /* Add each domain to the trusted domain list */
225                 
226                 for(i = 0; i < num_domains; i++) {
227                         DEBUG(10,("Found domain %s\n", names[i]));
228                         add_trusted_domain(names[i], alt_names?alt_names[i]:NULL,
229                                            domain->methods, &dom_sids[i]);
230                                            
231                         /* if the SID was empty, we better set it now */
232                         
233                         if ( sid_equal(&dom_sids[i], &null_sid) ) {
234                         
235                                 new_domain = find_domain_from_name(names[i]);
236                                  
237                                 /* this should never happen */
238                                 if ( !new_domain ) {    
239                                         DEBUG(0,("rescan_trust_domains: can't find the domain I just added! [%s]\n",
240                                                 names[i]));
241                                         break;
242                                 }
243                                  
244                                 /* call the cache method; which will operate on the winbindd_domain \
245                                    passed in and choose either rpc or ads as appropriate */
246
247                                 result = domain->methods->domain_sid( new_domain, &new_domain->sid );
248                                  
249                                 if ( NT_STATUS_IS_OK(result) )
250                                         sid_copy( &dom_sids[i], &new_domain->sid );
251                         }
252                         
253                         /* store trusted domain in the cache */
254                         trustdom_cache_store(names[i], alt_names ? alt_names[i] : NULL,
255                                              &dom_sids[i], t + WINBINDD_RESCAN_FREQ);
256                 }
257         }
258
259         talloc_destroy(mem_ctx);
260 }
261
262 /********************************************************************
263  Periodically we need to refresh the trusted domain cache for smbd 
264 ********************************************************************/
265
266 void rescan_trusted_domains( void )
267 {
268         time_t now = time(NULL);
269         struct winbindd_domain *mydomain = NULL;
270         
271         /* see if the time has come... */
272         
273         if ( (now > last_trustdom_scan) && ((now-last_trustdom_scan) < WINBINDD_RESCAN_FREQ) )
274                 return;
275                 
276         if ( (mydomain = find_our_domain()) == NULL ) {
277                 DEBUG(0,("rescan_trusted_domains: Can't find my own domain!\n"));
278                 return;
279         }
280         
281         /* this will only add new domains we didn't already know about */
282         
283         add_trusted_domains( mydomain );
284
285         last_trustdom_scan = now;
286         
287         return; 
288 }
289
290 /* Look up global info for the winbind daemon */
291 BOOL init_domain_list(void)
292 {
293         extern struct winbindd_methods cache_methods;
294         struct winbindd_domain *domain;
295
296         /* Free existing list */
297         free_domain_list();
298
299         /* Add ourselves as the first entry. */
300         
301         domain = add_trusted_domain( lp_workgroup(), lp_realm(), &cache_methods, NULL);
302         
303         domain->primary = True;
304
305         /* get any alternate name for the primary domain */
306         
307         cache_methods.alternate_name(domain);
308         
309         /* now we have the correct netbios (short) domain name */
310         
311         if ( *domain->name )
312                 set_global_myworkgroup( domain->name );
313                 
314         if (!secrets_fetch_domain_sid(domain->name, &domain->sid)) {
315                 DEBUG(1, ("Could not fetch sid for our domain %s\n",
316                           domain->name));
317                 return False;
318         }
319
320         /* do an initial scan for trusted domains */
321         add_trusted_domains(domain);
322
323         /* Don't expand aliases if not explicitly activated -- for now */
324         /* we don't support windows local nested groups if we are a DC.
325            refer to to sid_to_gid() in the smbd server code to see why
326            -- jerry */
327
328
329         if (lp_winbind_nested_groups() || IS_DC) {
330
331                 /* Add our local SAM domains */
332                 DOM_SID sid;
333                 extern struct winbindd_methods passdb_methods;
334                 struct winbindd_domain *dom;
335
336                 string_to_sid(&sid, "S-1-5-32");
337
338                 dom = add_trusted_domain("BUILTIN", NULL, &passdb_methods,
339                                          &sid);
340
341                 dom = add_trusted_domain(get_global_sam_name(), NULL,
342                                          &passdb_methods,
343                                          get_global_sam_sid());
344         }
345         
346         /* avoid rescanning this right away */
347         last_trustdom_scan = time(NULL);
348         return True;
349 }
350
351 /** 
352  * Given a domain name, return the struct winbindd domain info for it 
353  *
354  * @note Do *not* pass lp_workgroup() to this function.  domain_list
355  *       may modify it's value, and free that pointer.  Instead, our local
356  *       domain may be found by calling find_our_domain().
357  *       directly.
358  *
359  *
360  * @return The domain structure for the named domain, if it is working.
361  */
362
363 struct winbindd_domain *find_domain_from_name(const char *domain_name)
364 {
365         struct winbindd_domain *domain;
366
367         /* Search through list */
368
369         for (domain = domain_list(); domain != NULL; domain = domain->next) {
370                 if (strequal(domain_name, domain->name) ||
371                     (domain->alt_name[0] && strequal(domain_name, domain->alt_name))) {
372                         return domain;
373                 }
374         }
375
376         /* Not found */
377
378         return NULL;
379 }
380
381 /* Given a domain sid, return the struct winbindd domain info for it */
382
383 struct winbindd_domain *find_domain_from_sid(const DOM_SID *sid)
384 {
385         struct winbindd_domain *domain;
386
387         /* Search through list */
388
389         for (domain = domain_list(); domain != NULL; domain = domain->next) {
390                 if (sid_compare_domain(sid, &domain->sid) == 0)
391                         return domain;
392         }
393
394         /* Not found */
395
396         return NULL;
397 }
398
399 /* Given a domain sid, return the struct winbindd domain info for it */
400
401 struct winbindd_domain *find_our_domain(void)
402 {
403         struct winbindd_domain *domain;
404
405         /* Search through list */
406
407         for (domain = domain_list(); domain != NULL; domain = domain->next) {
408                 if (domain->primary)
409                         return domain;
410         }
411
412         /* Not found */
413
414         return NULL;
415 }
416
417 /* Lookup a sid in a domain from a name */
418
419 BOOL winbindd_lookup_sid_by_name(struct winbindd_domain *domain, 
420                                  const char *name, DOM_SID *sid, 
421                                  enum SID_NAME_USE *type)
422 {
423         NTSTATUS result;
424         TALLOC_CTX *mem_ctx;
425
426         mem_ctx = talloc_init("lookup_sid_by_name for %s\n", name);
427         if (!mem_ctx) 
428                 return False;
429         
430         /* Lookup name */
431         result = domain->methods->name_to_sid(domain, mem_ctx, name, sid, type);
432
433         talloc_destroy(mem_ctx);
434         
435         /* Return rid and type if lookup successful */
436         if (!NT_STATUS_IS_OK(result)) {
437                 *type = SID_NAME_UNKNOWN;
438         }
439
440         return NT_STATUS_IS_OK(result);
441 }
442
443 /**
444  * @brief Lookup a name in a domain from a sid.
445  *
446  * @param sid Security ID you want to look up.
447  * @param name On success, set to the name corresponding to @p sid.
448  * @param dom_name On success, set to the 'domain name' corresponding to @p sid.
449  * @param type On success, contains the type of name: alias, group or
450  * user.
451  * @retval True if the name exists, in which case @p name and @p type
452  * are set, otherwise False.
453  **/
454 BOOL winbindd_lookup_name_by_sid(DOM_SID *sid,
455                                  fstring dom_name,
456                                  fstring name,
457                                  enum SID_NAME_USE *type)
458 {
459         char *names;
460         NTSTATUS result;
461         TALLOC_CTX *mem_ctx;
462         BOOL rv = False;
463         struct winbindd_domain *domain;
464
465         domain = find_domain_from_sid(sid);
466
467         if (!domain) {
468                 DEBUG(1,("Can't find domain from sid\n"));
469                 return False;
470         }
471
472         /* Lookup name */
473
474         if (!(mem_ctx = talloc_init("winbindd_lookup_name_by_sid")))
475                 return False;
476         
477         result = domain->methods->sid_to_name(domain, mem_ctx, sid, &names, type);
478
479         /* Return name and type if successful */
480         
481         if ((rv = NT_STATUS_IS_OK(result))) {
482                 fstrcpy(dom_name, domain->name);
483                 fstrcpy(name, names);
484         } else {
485                 *type = SID_NAME_UNKNOWN;
486                 fstrcpy(name, name_deadbeef);
487         }
488         
489         talloc_destroy(mem_ctx);
490
491         return rv;
492 }
493
494
495 /* Free state information held for {set,get,end}{pw,gr}ent() functions */
496
497 void free_getent_state(struct getent_state *state)
498 {
499         struct getent_state *temp;
500
501         /* Iterate over state list */
502
503         temp = state;
504
505         while(temp != NULL) {
506                 struct getent_state *next;
507
508                 /* Free sam entries then list entry */
509
510                 SAFE_FREE(state->sam_entries);
511                 DLIST_REMOVE(state, state);
512                 next = temp->next;
513
514                 SAFE_FREE(temp);
515                 temp = next;
516         }
517 }
518
519 /* Parse winbindd related parameters */
520
521 BOOL winbindd_param_init(void)
522 {
523         /* Parse winbind uid and winbind_gid parameters */
524
525         if (!lp_idmap_uid(&server_state.uid_low, &server_state.uid_high)) {
526                 DEBUG(0, ("winbindd: idmap uid range missing or invalid\n"));
527                 DEBUG(0, ("winbindd: cannot continue, exiting.\n"));
528                 return False;
529         }
530         
531         if (!lp_idmap_gid(&server_state.gid_low, &server_state.gid_high)) {
532                 DEBUG(0, ("winbindd: idmap gid range missing or invalid\n"));
533                 DEBUG(0, ("winbindd: cannot continue, exiting.\n"));
534                 return False;
535         }
536         
537         return True;
538 }
539
540 /* Check if a domain is present in a comma-separated list of domains */
541
542 BOOL check_domain_env(char *domain_env, char *domain)
543 {
544         fstring name;
545         const char *tmp = domain_env;
546
547         while(next_token(&tmp, name, ",", sizeof(fstring))) {
548                 if (strequal(name, domain))
549                         return True;
550         }
551
552         return False;
553 }
554
555 /* Is this a domain which we may assume no DOMAIN\ prefix? */
556
557 static BOOL assume_domain(const char *domain) {
558         if ((lp_winbind_use_default_domain()  
559                   || lp_winbind_trusted_domains_only()) &&
560             strequal(lp_workgroup(), domain)) 
561                 return True;
562
563         if (strequal(get_global_sam_name(), domain)) 
564                 return True;
565         
566         return False;
567 }
568
569 /* Parse a string of the form DOMAIN/user into a domain and a user */
570
571 BOOL parse_domain_user(const char *domuser, fstring domain, fstring user)
572 {
573         char *p = strchr(domuser,*lp_winbind_separator());
574
575         if ( !p ) {
576                 fstrcpy(user, domuser);
577                 
578                 if ( assume_domain(lp_workgroup())) {
579                         fstrcpy(domain, lp_workgroup());
580                 } else {
581                         fstrcpy( domain, get_global_sam_name() ); 
582                 }
583         } 
584         else {
585                 fstrcpy(user, p+1);
586                 fstrcpy(domain, domuser);
587                 domain[PTR_DIFF(p, domuser)] = 0;
588         }
589         
590         strupper_m(domain);
591         
592         return True;
593 }
594
595 /*
596     Fill DOMAIN\\USERNAME entry accounting 'winbind use default domain' and
597     'winbind separator' options.
598     This means:
599         - omit DOMAIN when 'winbind use default domain = true' and DOMAIN is
600         lp_workgroup()
601
602     If we are a PDC or BDC, and this is for our domain, do likewise.
603
604     Also, if omit DOMAIN if 'winbind trusted domains only = true', as the 
605     username is then unqualified in unix
606          
607 */
608 void fill_domain_username(fstring name, const char *domain, const char *user)
609 {
610         if (assume_domain(domain)) {
611                 strlcpy(name, user, sizeof(fstring));
612         } else {
613                 slprintf(name, sizeof(fstring) - 1, "%s%s%s",
614                          domain, lp_winbind_separator(),
615                          user);
616         }
617 }
618
619 /*
620  * Winbindd socket accessor functions
621  */
622
623 char *get_winbind_priv_pipe_dir(void) 
624 {
625         return lock_path(WINBINDD_PRIV_SOCKET_SUBDIR);
626 }
627
628 /* Open the winbindd socket */
629
630 static int _winbindd_socket = -1;
631 static int _winbindd_priv_socket = -1;
632
633 int open_winbindd_socket(void)
634 {
635         if (_winbindd_socket == -1) {
636                 _winbindd_socket = create_pipe_sock(
637                         WINBINDD_SOCKET_DIR, WINBINDD_SOCKET_NAME, 0755);
638                 DEBUG(10, ("open_winbindd_socket: opened socket fd %d\n",
639                            _winbindd_socket));
640         }
641
642         return _winbindd_socket;
643 }
644
645 int open_winbindd_priv_socket(void)
646 {
647         if (_winbindd_priv_socket == -1) {
648                 _winbindd_priv_socket = create_pipe_sock(
649                         get_winbind_priv_pipe_dir(), WINBINDD_SOCKET_NAME, 0750);
650                 DEBUG(10, ("open_winbindd_priv_socket: opened socket fd %d\n",
651                            _winbindd_priv_socket));
652         }
653
654         return _winbindd_priv_socket;
655 }
656
657 /* Close the winbindd socket */
658
659 void close_winbindd_socket(void)
660 {
661         if (_winbindd_socket != -1) {
662                 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
663                            _winbindd_socket));
664                 close(_winbindd_socket);
665                 _winbindd_socket = -1;
666         }
667         if (_winbindd_priv_socket != -1) {
668                 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
669                            _winbindd_priv_socket));
670                 close(_winbindd_priv_socket);
671                 _winbindd_priv_socket = -1;
672         }
673 }
674
675 /*
676  * Client list accessor functions
677  */
678
679 static struct winbindd_cli_state *_client_list;
680 static int _num_clients;
681
682 /* Return list of all connected clients */
683
684 struct winbindd_cli_state *winbindd_client_list(void)
685 {
686         return _client_list;
687 }
688
689 /* Add a connection to the list */
690
691 void winbindd_add_client(struct winbindd_cli_state *cli)
692 {
693         DLIST_ADD(_client_list, cli);
694         _num_clients++;
695 }
696
697 /* Remove a client from the list */
698
699 void winbindd_remove_client(struct winbindd_cli_state *cli)
700 {
701         DLIST_REMOVE(_client_list, cli);
702         _num_clients--;
703 }
704
705 /* Close all open clients */
706
707 void winbindd_kill_all_clients(void)
708 {
709         struct winbindd_cli_state *cl = winbindd_client_list();
710
711         DEBUG(10, ("winbindd_kill_all_clients: going postal\n"));
712
713         while (cl) {
714                 struct winbindd_cli_state *next;
715                 
716                 next = cl->next;
717                 winbindd_remove_client(cl);
718                 cl = next;
719         }
720 }
721
722 /* Return number of open clients */
723
724 int winbindd_num_clients(void)
725 {
726         return _num_clients;
727 }
728
729 /* Help with RID -> SID conversion */
730
731 DOM_SID *rid_to_talloced_sid(struct winbindd_domain *domain,
732                                     TALLOC_CTX *mem_ctx,
733                                     uint32 rid) 
734 {
735         DOM_SID *sid;
736         sid = talloc(mem_ctx, sizeof(*sid));
737         if (!sid) {
738                 smb_panic("rid_to_to_talloced_sid: talloc for DOM_SID failed!\n");
739         }
740         sid_copy(sid, &domain->sid);
741         sid_append_rid(sid, rid);
742         return sid;
743 }
744         
745 /*****************************************************************************
746  For idmap conversion: convert one record to new format
747  Ancient versions (eg 2.2.3a) of winbindd_idmap.tdb mapped DOMAINNAME/rid
748  instead of the SID.
749 *****************************************************************************/
750 static int convert_fn(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA data, void *state)
751 {
752         struct winbindd_domain *domain;
753         char *p;
754         DOM_SID sid;
755         uint32 rid;
756         fstring keystr;
757         fstring dom_name;
758         TDB_DATA key2;
759         BOOL *failed = (BOOL *)state;
760
761         DEBUG(10,("Converting %s\n", key.dptr));
762
763         p = strchr(key.dptr, '/');
764         if (!p)
765                 return 0;
766
767         *p = 0;
768         fstrcpy(dom_name, key.dptr);
769         *p++ = '/';
770
771         domain = find_domain_from_name(dom_name);
772         if (domain == NULL) {
773                 /* We must delete the old record. */
774                 DEBUG(0,("Unable to find domain %s\n", dom_name ));
775                 DEBUG(0,("deleting record %s\n", key.dptr ));
776
777                 if (tdb_delete(tdb, key) != 0) {
778                         DEBUG(0, ("Unable to delete record %s\n", key.dptr));
779                         *failed = True;
780                         return -1;
781                 }
782
783                 return 0;
784         }
785
786         rid = atoi(p);
787
788         sid_copy(&sid, &domain->sid);
789         sid_append_rid(&sid, rid);
790
791         sid_to_string(keystr, &sid);
792         key2.dptr = keystr;
793         key2.dsize = strlen(keystr) + 1;
794
795         if (tdb_store(tdb, key2, data, TDB_INSERT) != 0) {
796                 DEBUG(0,("Unable to add record %s\n", key2.dptr ));
797                 *failed = True;
798                 return -1;
799         }
800
801         if (tdb_store(tdb, data, key2, TDB_REPLACE) != 0) {
802                 DEBUG(0,("Unable to update record %s\n", data.dptr ));
803                 *failed = True;
804                 return -1;
805         }
806
807         if (tdb_delete(tdb, key) != 0) {
808                 DEBUG(0,("Unable to delete record %s\n", key.dptr ));
809                 *failed = True;
810                 return -1;
811         }
812
813         return 0;
814 }
815
816 /* These definitions are from sam/idmap_tdb.c. Replicated here just
817    out of laziness.... :-( */
818
819 /* High water mark keys */
820 #define HWM_GROUP  "GROUP HWM"
821 #define HWM_USER   "USER HWM"
822
823 /* idmap version determines auto-conversion */
824 #define IDMAP_VERSION 2
825
826
827 /*****************************************************************************
828  Convert the idmap database from an older version.
829 *****************************************************************************/
830
831 static BOOL idmap_convert(const char *idmap_name)
832 {
833         int32 vers;
834         BOOL bigendianheader;
835         BOOL failed = False;
836         TDB_CONTEXT *idmap_tdb;
837
838         if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
839                                         TDB_DEFAULT, O_RDWR,
840                                         0600))) {
841                 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
842                 return False;
843         }
844
845         bigendianheader = (idmap_tdb->flags & TDB_BIGENDIAN) ? True : False;
846
847         vers = tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION");
848
849         if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
850                 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
851                 /*
852                  * high and low records were created on a
853                  * big endian machine and will need byte-reversing.
854                  */
855
856                 int32 wm;
857
858                 wm = tdb_fetch_int32(idmap_tdb, HWM_USER);
859
860                 if (wm != -1) {
861                         wm = IREV(wm);
862                 }  else {
863                         wm = server_state.uid_low;
864                 }
865
866                 if (tdb_store_int32(idmap_tdb, HWM_USER, wm) == -1) {
867                         DEBUG(0, ("idmap_convert: Unable to byteswap user hwm in idmap database\n"));
868                         tdb_close(idmap_tdb);
869                         return False;
870                 }
871
872                 wm = tdb_fetch_int32(idmap_tdb, HWM_GROUP);
873                 if (wm != -1) {
874                         wm = IREV(wm);
875                 } else {
876                         wm = server_state.gid_low;
877                 }
878
879                 if (tdb_store_int32(idmap_tdb, HWM_GROUP, wm) == -1) {
880                         DEBUG(0, ("idmap_convert: Unable to byteswap group hwm in idmap database\n"));
881                         tdb_close(idmap_tdb);
882                         return False;
883                 }
884         }
885
886         /* the old format stored as DOMAIN/rid - now we store the SID direct */
887         tdb_traverse(idmap_tdb, convert_fn, &failed);
888
889         if (failed) {
890                 DEBUG(0, ("Problem during conversion\n"));
891                 tdb_close(idmap_tdb);
892                 return False;
893         }
894
895         if (tdb_store_int32(idmap_tdb, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
896                 DEBUG(0, ("idmap_convert: Unable to dtore idmap version in databse\n"));
897                 tdb_close(idmap_tdb);
898                 return False;
899         }
900
901         tdb_close(idmap_tdb);
902         return True;
903 }
904
905 /*****************************************************************************
906  Convert the idmap database from an older version if necessary
907 *****************************************************************************/
908
909 BOOL winbindd_upgrade_idmap(void)
910 {
911         pstring idmap_name;
912         pstring backup_name;
913         SMB_STRUCT_STAT stbuf;
914         TDB_CONTEXT *idmap_tdb;
915
916         pstrcpy(idmap_name, lock_path("winbindd_idmap.tdb"));
917
918         if (!file_exist(idmap_name, &stbuf)) {
919                 /* nothing to convert return */
920                 return True;
921         }
922
923         if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
924                                         TDB_DEFAULT, O_RDWR,
925                                         0600))) {
926                 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
927                 return False;
928         }
929
930         if (tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION") == IDMAP_VERSION) {
931                 /* nothing to convert return */
932                 tdb_close(idmap_tdb);
933                 return True;
934         }
935
936         /* backup_tdb expects the tdb not to be open */
937         tdb_close(idmap_tdb);
938
939         DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
940
941         pstrcpy(backup_name, idmap_name);
942         pstrcat(backup_name, ".bak");
943
944         if (backup_tdb(idmap_name, backup_name) != 0) {
945                 DEBUG(0, ("Could not backup idmap database\n"));
946                 return False;
947         }
948
949         return idmap_convert(idmap_name);
950 }
951
952 /*******************************************************************
953  wrapper around retrieving the trust account password
954 *******************************************************************/
955
956 BOOL get_trust_pw(const char *domain, uint8 ret_pwd[16],
957                           time_t *pass_last_set_time, uint32 *channel)
958 {
959         DOM_SID sid;
960         char *pwd;
961
962         /* if we are a DC and this is not our domain, then lookup an account
963            for the domain trust */
964            
965         if ( IS_DC && !strequal(domain, lp_workgroup()) && lp_allow_trusted_domains() ) 
966         {
967                 if ( !secrets_fetch_trusted_domain_password(domain, &pwd, &sid, 
968                         pass_last_set_time) ) 
969                 {
970                         DEBUG(0, ("get_trust_pw: could not fetch trust account "
971                                   "password for trusted domain %s\n", domain));
972                         return False;
973                 }
974                 
975                 *channel = SEC_CHAN_DOMAIN;
976                 E_md4hash(pwd, ret_pwd);
977                 SAFE_FREE(pwd);
978
979                 return True;
980         }
981         else    /* just get the account for our domain (covers 
982                    ROLE_DOMAIN_MEMBER as well */
983         {
984                 /* get the machine trust account for our domain */
985
986                 if ( !secrets_fetch_trust_account_password (lp_workgroup(), ret_pwd,
987                         pass_last_set_time, channel) ) 
988                 {
989                         DEBUG(0, ("get_trust_pw: could not fetch trust account "
990                                   "password for my domain %s\n", domain));
991                         return False;
992                 }
993                 
994                 return True;
995         }
996         
997         /* Failure */
998 }
999