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