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