r15053: fix portabilities issues between 32-bit winbind clients and a 64-bit winbindd...
[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 "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) && (!init_domain_list())) {
65                 smb_panic("Init_domain_list failed\n");
66         }
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         if (sid == NULL)
89                 return False;
90
91         return (sid_check_is_domain(sid) || sid_check_is_builtin(sid));
92 }
93
94 static BOOL is_in_internal_domain(const DOM_SID *sid)
95 {
96         if (sid == NULL)
97                 return False;
98
99         return (sid_check_is_in_our_domain(sid) || sid_check_is_in_builtin(sid));
100 }
101
102
103 /* Add a trusted domain to our list of domains */
104 static struct winbindd_domain *add_trusted_domain(const char *domain_name, const char *alt_name,
105                                                   struct winbindd_methods *methods,
106                                                   const DOM_SID *sid)
107 {
108         struct winbindd_domain *domain;
109         const char *alternative_name = NULL;
110         
111         /* ignore alt_name if we are not in an AD domain */
112         
113         if ( (lp_security() == SEC_ADS) && alt_name && *alt_name) {
114                 alternative_name = alt_name;
115         }
116         
117         /* We can't call domain_list() as this function is called from
118            init_domain_list() and we'll get stuck in a loop. */
119         for (domain = _domain_list; domain; domain = domain->next) {
120                 if (strequal(domain_name, domain->name) ||
121                     strequal(domain_name, domain->alt_name)) {
122                         return domain;
123                 }
124                 if (alternative_name && *alternative_name) {
125                         if (strequal(alternative_name, domain->name) ||
126                             strequal(alternative_name, domain->alt_name)) {
127                                 return domain;
128                         }
129                 }
130                 if (sid) {
131                         if (is_null_sid(sid)) {
132                                 
133                         } else if (sid_equal(sid, &domain->sid)) {
134                                 return domain;
135                         }
136                 }
137         }
138         
139         /* Create new domain entry */
140
141         if ((domain = SMB_MALLOC_P(struct winbindd_domain)) == NULL)
142                 return NULL;
143
144         /* Fill in fields */
145         
146         ZERO_STRUCTP(domain);
147
148         /* prioritise the short name */
149         if (strchr_m(domain_name, '.') && alternative_name && *alternative_name) {
150                 fstrcpy(domain->name, alternative_name);
151                 fstrcpy(domain->alt_name, domain_name);
152         } else {
153                 fstrcpy(domain->name, domain_name);
154                 if (alternative_name) {
155                         fstrcpy(domain->alt_name, alternative_name);
156                 }
157         }
158
159         domain->methods = methods;
160         domain->backend = NULL;
161         domain->internal = is_internal_domain(sid);
162         domain->sequence_number = DOM_SEQUENCE_NONE;
163         domain->last_seq_check = 0;
164         domain->initialized = False;
165         domain->online = False;
166         if (sid) {
167                 sid_copy(&domain->sid, sid);
168         }
169         
170         /* Link to domain list */
171         DLIST_ADD(_domain_list, domain);
172         
173         DEBUG(2,("Added domain %s %s %s\n", 
174                  domain->name, domain->alt_name,
175                  &domain->sid?sid_string_static(&domain->sid):""));
176         
177         return domain;
178 }
179
180 /********************************************************************
181   rescan our domains looking for new trusted domains
182 ********************************************************************/
183
184 struct trustdom_state {
185         TALLOC_CTX *mem_ctx;
186         struct winbindd_response *response;
187 };
188
189 static void trustdom_recv(void *private_data, BOOL success);
190
191 static void add_trusted_domains( struct winbindd_domain *domain )
192 {
193         TALLOC_CTX *mem_ctx;
194         struct winbindd_request *request;
195         struct winbindd_response *response;
196
197         struct trustdom_state *state;
198
199         mem_ctx = talloc_init("add_trusted_domains");
200         if (mem_ctx == NULL) {
201                 DEBUG(0, ("talloc_init failed\n"));
202                 return;
203         }
204
205         request = TALLOC_ZERO_P(mem_ctx, struct winbindd_request);
206         response = TALLOC_P(mem_ctx, struct winbindd_response);
207         state = TALLOC_P(mem_ctx, struct trustdom_state);
208
209         if ((request == NULL) || (response == NULL) || (state == NULL)) {
210                 DEBUG(0, ("talloc failed\n"));
211                 talloc_destroy(mem_ctx);
212                 return;
213         }
214
215         state->mem_ctx = mem_ctx;
216         state->response = response;
217
218         request->length = sizeof(*request);
219         request->cmd = WINBINDD_LIST_TRUSTDOM;
220
221         async_domain_request(mem_ctx, domain, request, response,
222                              trustdom_recv, state);
223 }
224
225 static void trustdom_recv(void *private_data, BOOL success)
226 {
227         extern struct winbindd_methods cache_methods;
228         struct trustdom_state *state =
229                 talloc_get_type_abort(private_data, struct trustdom_state);
230         struct winbindd_response *response = state->response;
231         char *p;
232
233         if ((!success) || (response->result != WINBINDD_OK)) {
234                 DEBUG(1, ("Could not receive trustdoms\n"));
235                 talloc_destroy(state->mem_ctx);
236                 return;
237         }
238
239         p = response->extra_data.data;
240
241         while ((p != NULL) && (*p != '\0')) {
242                 char *q, *sidstr, *alt_name;
243                 DOM_SID sid;
244
245                 alt_name = strchr(p, '\\');
246                 if (alt_name == NULL) {
247                         DEBUG(0, ("Got invalid trustdom response\n"));
248                         break;
249                 }
250
251                 *alt_name = '\0';
252                 alt_name += 1;
253
254                 sidstr = strchr(alt_name, '\\');
255                 if (sidstr == NULL) {
256                         DEBUG(0, ("Got invalid trustdom response\n"));
257                         break;
258                 }
259
260                 *sidstr = '\0';
261                 sidstr += 1;
262
263                 q = strchr(sidstr, '\n');
264                 if (q != NULL)
265                         *q = '\0';
266
267                 if (!string_to_sid(&sid, sidstr)) {
268                         DEBUG(0, ("Got invalid trustdom response\n"));
269                         break;
270                 }
271
272                 if (find_domain_from_name_noinit(p) == NULL) {
273                         struct winbindd_domain *domain;
274                         char *alternate_name = NULL;
275                         
276                         /* use the real alt_name if we have one, else pass in NULL */
277
278                         if ( !strequal( alt_name, "(null)" ) )
279                                 alternate_name = alt_name;
280
281                         domain = add_trusted_domain(p, alternate_name,
282                                                     &cache_methods,
283                                                     &sid);
284                         setup_domain_child(domain, &domain->child, NULL);
285                 }
286                 p=q;
287                 if (p != NULL)
288                         p += 1;
289         }
290
291         SAFE_FREE(response->extra_data.data);
292         talloc_destroy(state->mem_ctx);
293 }
294
295 /********************************************************************
296  Periodically we need to refresh the trusted domain cache for smbd 
297 ********************************************************************/
298
299 void rescan_trusted_domains( void )
300 {
301         time_t now = time(NULL);
302         
303         /* see if the time has come... */
304         
305         if ((now >= last_trustdom_scan) &&
306             ((now-last_trustdom_scan) < WINBINDD_RESCAN_FREQ) )
307                 return;
308                 
309         /* this will only add new domains we didn't already know about */
310         
311         add_trusted_domains( find_our_domain() );
312
313         last_trustdom_scan = now;
314         
315         return; 
316 }
317
318 struct init_child_state {
319         TALLOC_CTX *mem_ctx;
320         struct winbindd_domain *domain;
321         struct winbindd_request *request;
322         struct winbindd_response *response;
323         void (*continuation)(void *private_data, BOOL success);
324         void *private_data;
325 };
326
327 static void init_child_recv(void *private_data, BOOL success);
328 static void init_child_getdc_recv(void *private_data, BOOL success);
329
330 enum winbindd_result init_child_connection(struct winbindd_domain *domain,
331                                            void (*continuation)(void *private_data,
332                                                                 BOOL success),
333                                            void *private_data)
334 {
335         TALLOC_CTX *mem_ctx;
336         struct winbindd_request *request;
337         struct winbindd_response *response;
338         struct init_child_state *state;
339         struct winbindd_domain *request_domain;
340
341         mem_ctx = talloc_init("init_child_connection");
342         if (mem_ctx == NULL) {
343                 DEBUG(0, ("talloc_init failed\n"));
344                 return WINBINDD_ERROR;
345         }
346
347         request = TALLOC_ZERO_P(mem_ctx, struct winbindd_request);
348         response = TALLOC_P(mem_ctx, struct winbindd_response);
349         state = TALLOC_P(mem_ctx, struct init_child_state);
350
351         if ((request == NULL) || (response == NULL) || (state == NULL)) {
352                 DEBUG(0, ("talloc failed\n"));
353                 continuation(private_data, False);
354                 return WINBINDD_ERROR;
355         }
356
357         request->length = sizeof(*request);
358
359         state->mem_ctx = mem_ctx;
360         state->domain = domain;
361         state->request = request;
362         state->response = response;
363         state->continuation = continuation;
364         state->private_data = private_data;
365
366         if (domain->primary) {
367                 /* The primary domain has to find the DC name itself */
368                 request->cmd = WINBINDD_INIT_CONNECTION;
369                 fstrcpy(request->domain_name, domain->name);
370                 request->data.init_conn.is_primary = True;
371                 fstrcpy(request->data.init_conn.dcname, "");
372                 async_request(mem_ctx, &domain->child, request, response,
373                               init_child_recv, state);
374                 return WINBINDD_PENDING;
375         }
376
377         /* This is *not* the primary domain, let's ask our DC about a DC
378          * name */
379
380         request->cmd = WINBINDD_GETDCNAME;
381         fstrcpy(request->domain_name, domain->name);
382
383         /* save online flag */
384         request_domain = find_our_domain();
385         request_domain->online = domain->online;
386         
387         async_domain_request(mem_ctx, request_domain, request, response,
388                              init_child_getdc_recv, state);
389         return WINBINDD_PENDING;
390 }
391
392 static void init_child_getdc_recv(void *private_data, BOOL success)
393 {
394         struct init_child_state *state =
395                 talloc_get_type_abort(private_data, struct init_child_state);
396         const char *dcname = "";
397
398         DEBUG(10, ("Received getdcname response\n"));
399
400         if (success && (state->response->result == WINBINDD_OK)) {
401                 dcname = state->response->data.dc_name;
402         }
403
404         state->request->cmd = WINBINDD_INIT_CONNECTION;
405         fstrcpy(state->request->domain_name, state->domain->name);
406         state->request->data.init_conn.is_primary = False;
407         fstrcpy(state->request->data.init_conn.dcname, dcname);
408
409         async_request(state->mem_ctx, &state->domain->child,
410                       state->request, state->response,
411                       init_child_recv, state);
412 }
413
414 static void init_child_recv(void *private_data, BOOL success)
415 {
416         struct init_child_state *state =
417                 talloc_get_type_abort(private_data, struct init_child_state);
418
419         DEBUG(5, ("Received child initialization response for domain %s\n",
420                   state->domain->name));
421
422         if ((!success) || (state->response->result != WINBINDD_OK)) {
423                 DEBUG(3, ("Could not init child\n"));
424                 state->continuation(state->private_data, False);
425                 talloc_destroy(state->mem_ctx);
426                 return;
427         }
428
429         fstrcpy(state->domain->name,
430                 state->response->data.domain_info.name);
431         fstrcpy(state->domain->alt_name,
432                 state->response->data.domain_info.alt_name);
433         string_to_sid(&state->domain->sid,
434                       state->response->data.domain_info.sid);
435         state->domain->native_mode =
436                 state->response->data.domain_info.native_mode;
437         state->domain->active_directory =
438                 state->response->data.domain_info.active_directory;
439         state->domain->sequence_number =
440                 state->response->data.domain_info.sequence_number;
441
442         state->domain->initialized = 1;
443
444         if (state->continuation != NULL)
445                 state->continuation(state->private_data, True);
446         talloc_destroy(state->mem_ctx);
447 }
448
449 enum winbindd_result winbindd_dual_init_connection(struct winbindd_domain *domain,
450                                                    struct winbindd_cli_state *state)
451 {
452         struct in_addr ipaddr;
453
454         /* Ensure null termination */
455         state->request.domain_name
456                 [sizeof(state->request.domain_name)-1]='\0';
457         state->request.data.init_conn.dcname
458                 [sizeof(state->request.data.init_conn.dcname)-1]='\0';
459
460         if (strlen(state->request.data.init_conn.dcname) > 0) {
461                 fstrcpy(domain->dcname, state->request.data.init_conn.dcname);
462         }
463
464         if (strlen(domain->dcname) > 0) {
465                 if (!resolve_name(domain->dcname, &ipaddr, 0x20)) {
466                         DEBUG(2, ("Could not resolve DC name %s for domain %s\n",
467                                   domain->dcname, domain->name));
468                         return WINBINDD_ERROR;
469                 }
470
471                 domain->dcaddr.sin_family = PF_INET;
472                 putip((char *)&(domain->dcaddr.sin_addr), (char *)&ipaddr);
473                 domain->dcaddr.sin_port = 0;
474         }
475
476         set_dc_type_and_flags(domain);
477
478         if (!domain->initialized) {
479                 DEBUG(1, ("Could not initialize domain %s\n",
480                           state->request.domain_name));
481                 return WINBINDD_ERROR;
482         }
483
484         fstrcpy(state->response.data.domain_info.name, domain->name);
485         fstrcpy(state->response.data.domain_info.alt_name, domain->alt_name);
486         fstrcpy(state->response.data.domain_info.sid,
487                 sid_string_static(&domain->sid));
488         
489         state->response.data.domain_info.native_mode
490                 = domain->native_mode;
491         state->response.data.domain_info.active_directory
492                 = domain->active_directory;
493         state->response.data.domain_info.primary
494                 = domain->primary;
495         state->response.data.domain_info.sequence_number =
496                 domain->sequence_number;
497
498         return WINBINDD_OK;
499 }
500
501 /* Look up global info for the winbind daemon */
502 BOOL init_domain_list(void)
503 {
504         extern struct winbindd_methods cache_methods;
505         extern struct winbindd_methods passdb_methods;
506         struct winbindd_domain *domain;
507         int role = lp_server_role();
508
509         /* Free existing list */
510         free_domain_list();
511
512         /* Add ourselves as the first entry. */
513
514         if ( role == ROLE_DOMAIN_MEMBER ) {
515                 DOM_SID our_sid;
516
517                 if (!secrets_fetch_domain_sid(lp_workgroup(), &our_sid)) {
518                         DEBUG(0, ("Could not fetch our SID - did we join?\n"));
519                         return False;
520                 }
521         
522                 domain = add_trusted_domain( lp_workgroup(), lp_realm(),
523                                              &cache_methods, &our_sid);
524                 domain->primary = True;
525                 setup_domain_child(domain, &domain->child, NULL);
526         }
527
528         /* Local SAM */
529
530         domain = add_trusted_domain(get_global_sam_name(), NULL,
531                                     &passdb_methods, get_global_sam_sid());
532         if ( role != ROLE_DOMAIN_MEMBER ) {
533                 domain->primary = True;
534         }
535         setup_domain_child(domain, &domain->child, NULL);
536
537         /* BUILTIN domain */
538
539         domain = add_trusted_domain("BUILTIN", NULL, &passdb_methods,
540                                     &global_sid_Builtin);
541         setup_domain_child(domain, &domain->child, NULL);
542
543         return True;
544 }
545
546 /** 
547  * Given a domain name, return the struct winbindd domain info for it 
548  *
549  * @note Do *not* pass lp_workgroup() to this function.  domain_list
550  *       may modify it's value, and free that pointer.  Instead, our local
551  *       domain may be found by calling find_our_domain().
552  *       directly.
553  *
554  *
555  * @return The domain structure for the named domain, if it is working.
556  */
557
558 struct winbindd_domain *find_domain_from_name_noinit(const char *domain_name)
559 {
560         struct winbindd_domain *domain;
561
562         /* Search through list */
563
564         for (domain = domain_list(); domain != NULL; domain = domain->next) {
565                 if (strequal(domain_name, domain->name) ||
566                     (domain->alt_name[0] &&
567                      strequal(domain_name, domain->alt_name))) {
568                         return domain;
569                 }
570         }
571
572         /* Not found */
573
574         return NULL;
575 }
576
577 struct winbindd_domain *find_domain_from_name(const char *domain_name)
578 {
579         struct winbindd_domain *domain;
580
581         domain = find_domain_from_name_noinit(domain_name);
582
583         if (domain == NULL)
584                 return NULL;
585
586         if (!domain->initialized)
587                 set_dc_type_and_flags(domain);
588
589         return domain;
590 }
591
592 /* Given a domain sid, return the struct winbindd domain info for it */
593
594 struct winbindd_domain *find_domain_from_sid_noinit(const DOM_SID *sid)
595 {
596         struct winbindd_domain *domain;
597
598         /* Search through list */
599
600         for (domain = domain_list(); domain != NULL; domain = domain->next) {
601                 if (sid_compare_domain(sid, &domain->sid) == 0)
602                         return domain;
603         }
604
605         /* Not found */
606
607         return NULL;
608 }
609
610 /* Given a domain sid, return the struct winbindd domain info for it */
611
612 struct winbindd_domain *find_domain_from_sid(const DOM_SID *sid)
613 {
614         struct winbindd_domain *domain;
615
616         domain = find_domain_from_sid_noinit(sid);
617
618         if (domain == NULL)
619                 return NULL;
620
621         if (!domain->initialized)
622                 set_dc_type_and_flags(domain);
623
624         return domain;
625 }
626
627 struct winbindd_domain *find_our_domain(void)
628 {
629         struct winbindd_domain *domain;
630
631         /* Search through list */
632
633         for (domain = domain_list(); domain != NULL; domain = domain->next) {
634                 if (domain->primary)
635                         return domain;
636         }
637
638         smb_panic("Could not find our domain\n");
639         return NULL;
640 }
641
642 struct winbindd_domain *find_builtin_domain(void)
643 {
644         DOM_SID sid;
645         struct winbindd_domain *domain;
646
647         string_to_sid(&sid, "S-1-5-32");
648         domain = find_domain_from_sid(&sid);
649
650         if (domain == NULL)
651                 smb_panic("Could not find BUILTIN domain\n");
652
653         return domain;
654 }
655
656 /* Find the appropriate domain to lookup a name or SID */
657
658 struct winbindd_domain *find_lookup_domain_from_sid(const DOM_SID *sid)
659 {
660         /* A DC can't ask the local smbd for remote SIDs, here winbindd is the
661          * one to contact the external DC's. On member servers the internal
662          * domains are different: These are part of the local SAM. */
663
664         DEBUG(10, ("find_lookup_domain_from_sid(%s)\n",
665                    sid_string_static(sid)));
666
667         if (IS_DC || is_internal_domain(sid) || is_in_internal_domain(sid)) {
668                 DEBUG(10, ("calling find_domain_from_sid\n"));
669                 return find_domain_from_sid(sid);
670         }
671
672         /* On a member server a query for SID or name can always go to our
673          * primary DC. */
674
675         DEBUG(10, ("calling find_our_domain\n"));
676         return find_our_domain();
677 }
678
679 struct winbindd_domain *find_lookup_domain_from_name(const char *domain_name)
680 {
681         if (IS_DC || strequal(domain_name, "BUILTIN") ||
682             strequal(domain_name, get_global_sam_name()))
683                 return find_domain_from_name_noinit(domain_name);
684
685         return find_our_domain();
686 }
687
688 /* Lookup a sid in a domain from a name */
689
690 BOOL winbindd_lookup_sid_by_name(TALLOC_CTX *mem_ctx,
691                                  struct winbindd_domain *domain, 
692                                  const char *domain_name,
693                                  const char *name, DOM_SID *sid, 
694                                  enum SID_NAME_USE *type)
695 {
696         NTSTATUS result;
697
698         /* Lookup name */
699         result = domain->methods->name_to_sid(domain, mem_ctx, domain_name, name, sid, type);
700
701         /* Return rid and type if lookup successful */
702         if (!NT_STATUS_IS_OK(result)) {
703                 *type = SID_NAME_UNKNOWN;
704         }
705
706         return NT_STATUS_IS_OK(result);
707 }
708
709 /**
710  * @brief Lookup a name in a domain from a sid.
711  *
712  * @param sid Security ID you want to look up.
713  * @param name On success, set to the name corresponding to @p sid.
714  * @param dom_name On success, set to the 'domain name' corresponding to @p sid.
715  * @param type On success, contains the type of name: alias, group or
716  * user.
717  * @retval True if the name exists, in which case @p name and @p type
718  * are set, otherwise False.
719  **/
720 BOOL winbindd_lookup_name_by_sid(TALLOC_CTX *mem_ctx,
721                                  DOM_SID *sid,
722                                  fstring dom_name,
723                                  fstring name,
724                                  enum SID_NAME_USE *type)
725 {
726         char *names;
727         char *dom_names;
728         NTSTATUS result;
729         BOOL rv = False;
730         struct winbindd_domain *domain;
731
732         domain = find_lookup_domain_from_sid(sid);
733
734         if (!domain) {
735                 DEBUG(1,("Can't find domain from sid\n"));
736                 return False;
737         }
738
739         /* Lookup name */
740
741         result = domain->methods->sid_to_name(domain, mem_ctx, sid, &dom_names, &names, type);
742
743         /* Return name and type if successful */
744         
745         if ((rv = NT_STATUS_IS_OK(result))) {
746                 fstrcpy(dom_name, dom_names);
747                 fstrcpy(name, names);
748         } else {
749                 *type = SID_NAME_UNKNOWN;
750                 fstrcpy(name, name_deadbeef);
751         }
752         
753         return rv;
754 }
755
756 /* Free state information held for {set,get,end}{pw,gr}ent() functions */
757
758 void free_getent_state(struct getent_state *state)
759 {
760         struct getent_state *temp;
761
762         /* Iterate over state list */
763
764         temp = state;
765
766         while(temp != NULL) {
767                 struct getent_state *next;
768
769                 /* Free sam entries then list entry */
770
771                 SAFE_FREE(state->sam_entries);
772                 DLIST_REMOVE(state, state);
773                 next = temp->next;
774
775                 SAFE_FREE(temp);
776                 temp = next;
777         }
778 }
779
780 /* Parse winbindd related parameters */
781
782 BOOL winbindd_param_init(void)
783 {
784         /* Parse winbind uid and winbind_gid parameters */
785
786         if (!lp_idmap_uid(&server_state.uid_low, &server_state.uid_high)) {
787                 DEBUG(0, ("winbindd: idmap uid range missing or invalid\n"));
788                 DEBUG(0, ("winbindd: cannot continue, exiting.\n"));
789                 return False;
790         }
791         
792         if (!lp_idmap_gid(&server_state.gid_low, &server_state.gid_high)) {
793                 DEBUG(0, ("winbindd: idmap gid range missing or invalid\n"));
794                 DEBUG(0, ("winbindd: cannot continue, exiting.\n"));
795                 return False;
796         }
797         
798         return True;
799 }
800
801 BOOL is_in_uid_range(uid_t uid)
802 {
803         return ((uid >= server_state.uid_low) &&
804                 (uid <= server_state.uid_high));
805 }
806
807 BOOL is_in_gid_range(gid_t gid)
808 {
809         return ((gid >= server_state.gid_low) &&
810                 (gid <= server_state.gid_high));
811 }
812
813 /* Is this a domain which we may assume no DOMAIN\ prefix? */
814
815 static BOOL assume_domain(const char *domain) {
816         if ((lp_winbind_use_default_domain()  
817                   || lp_winbind_trusted_domains_only()) &&
818             strequal(lp_workgroup(), domain)) 
819                 return True;
820
821         if (strequal(get_global_sam_name(), domain)) 
822                 return True;
823         
824         return False;
825 }
826
827 /* Parse a string of the form DOMAIN\user into a domain and a user */
828
829 BOOL parse_domain_user(const char *domuser, fstring domain, fstring user)
830 {
831         char *p = strchr(domuser,*lp_winbind_separator());
832
833         if ( !p ) {
834                 fstrcpy(user, domuser);
835                 
836                 if ( assume_domain(lp_workgroup())) {
837                         fstrcpy(domain, lp_workgroup());
838                 } else {
839                         return False;
840                 }
841         } else {
842                 fstrcpy(user, p+1);
843                 fstrcpy(domain, domuser);
844                 domain[PTR_DIFF(p, domuser)] = 0;
845         }
846         
847         strupper_m(domain);
848         
849         return True;
850 }
851
852 BOOL parse_domain_user_talloc(TALLOC_CTX *mem_ctx, const char *domuser,
853                               char **domain, char **user)
854 {
855         fstring fstr_domain, fstr_user;
856         if (!parse_domain_user(domuser, fstr_domain, fstr_user)) {
857                 return False;
858         }
859         *domain = talloc_strdup(mem_ctx, fstr_domain);
860         *user = talloc_strdup(mem_ctx, fstr_user);
861         return ((*domain != NULL) && (*user != NULL));
862 }
863
864 /*
865     Fill DOMAIN\\USERNAME entry accounting 'winbind use default domain' and
866     'winbind separator' options.
867     This means:
868         - omit DOMAIN when 'winbind use default domain = true' and DOMAIN is
869         lp_workgroup()
870
871     If we are a PDC or BDC, and this is for our domain, do likewise.
872
873     Also, if omit DOMAIN if 'winbind trusted domains only = true', as the 
874     username is then unqualified in unix
875          
876 */
877 void fill_domain_username(fstring name, const char *domain, const char *user, BOOL can_assume)
878 {
879         fstring tmp_user;
880
881         fstrcpy(tmp_user, user);
882         strlower_m(tmp_user);
883
884         if (can_assume && assume_domain(domain)) {
885                 strlcpy(name, user, sizeof(fstring));
886         } else {
887                 slprintf(name, sizeof(fstring) - 1, "%s%c%s",
888                          domain, *lp_winbind_separator(),
889                          tmp_user);
890         }
891 }
892
893 /*
894  * Winbindd socket accessor functions
895  */
896
897 char *get_winbind_priv_pipe_dir(void) 
898 {
899         return lock_path(WINBINDD_PRIV_SOCKET_SUBDIR);
900 }
901
902 /* Open the winbindd socket */
903
904 static int _winbindd_socket = -1;
905 static int _winbindd_priv_socket = -1;
906
907 int open_winbindd_socket(void)
908 {
909         if (_winbindd_socket == -1) {
910                 _winbindd_socket = create_pipe_sock(
911                         WINBINDD_SOCKET_DIR, WINBINDD_SOCKET_NAME, 0755);
912                 DEBUG(10, ("open_winbindd_socket: opened socket fd %d\n",
913                            _winbindd_socket));
914         }
915
916         return _winbindd_socket;
917 }
918
919 int open_winbindd_priv_socket(void)
920 {
921         if (_winbindd_priv_socket == -1) {
922                 _winbindd_priv_socket = create_pipe_sock(
923                         get_winbind_priv_pipe_dir(), WINBINDD_SOCKET_NAME, 0750);
924                 DEBUG(10, ("open_winbindd_priv_socket: opened socket fd %d\n",
925                            _winbindd_priv_socket));
926         }
927
928         return _winbindd_priv_socket;
929 }
930
931 /* Close the winbindd socket */
932
933 void close_winbindd_socket(void)
934 {
935         if (_winbindd_socket != -1) {
936                 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
937                            _winbindd_socket));
938                 close(_winbindd_socket);
939                 _winbindd_socket = -1;
940         }
941         if (_winbindd_priv_socket != -1) {
942                 DEBUG(10, ("close_winbindd_socket: closing socket fd %d\n",
943                            _winbindd_priv_socket));
944                 close(_winbindd_priv_socket);
945                 _winbindd_priv_socket = -1;
946         }
947 }
948
949 /*
950  * Client list accessor functions
951  */
952
953 static struct winbindd_cli_state *_client_list;
954 static int _num_clients;
955
956 /* Return list of all connected clients */
957
958 struct winbindd_cli_state *winbindd_client_list(void)
959 {
960         return _client_list;
961 }
962
963 /* Add a connection to the list */
964
965 void winbindd_add_client(struct winbindd_cli_state *cli)
966 {
967         DLIST_ADD(_client_list, cli);
968         _num_clients++;
969 }
970
971 /* Remove a client from the list */
972
973 void winbindd_remove_client(struct winbindd_cli_state *cli)
974 {
975         DLIST_REMOVE(_client_list, cli);
976         _num_clients--;
977 }
978
979 /* Demote a client to be the last in the list */
980
981 void winbindd_demote_client(struct winbindd_cli_state *cli)
982 {
983         struct winbindd_cli_state *tmp;
984         DLIST_DEMOTE(_client_list, cli, tmp);
985 }
986
987 /* Close all open clients */
988
989 void winbindd_kill_all_clients(void)
990 {
991         struct winbindd_cli_state *cl = winbindd_client_list();
992
993         DEBUG(10, ("winbindd_kill_all_clients: going postal\n"));
994
995         while (cl) {
996                 struct winbindd_cli_state *next;
997                 
998                 next = cl->next;
999                 winbindd_remove_client(cl);
1000                 cl = next;
1001         }
1002 }
1003
1004 /* Return number of open clients */
1005
1006 int winbindd_num_clients(void)
1007 {
1008         return _num_clients;
1009 }
1010
1011 /*****************************************************************************
1012  For idmap conversion: convert one record to new format
1013  Ancient versions (eg 2.2.3a) of winbindd_idmap.tdb mapped DOMAINNAME/rid
1014  instead of the SID.
1015 *****************************************************************************/
1016 static int convert_fn(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA data, void *state)
1017 {
1018         struct winbindd_domain *domain;
1019         char *p;
1020         DOM_SID sid;
1021         uint32 rid;
1022         fstring keystr;
1023         fstring dom_name;
1024         TDB_DATA key2;
1025         BOOL *failed = (BOOL *)state;
1026
1027         DEBUG(10,("Converting %s\n", key.dptr));
1028
1029         p = strchr(key.dptr, '/');
1030         if (!p)
1031                 return 0;
1032
1033         *p = 0;
1034         fstrcpy(dom_name, key.dptr);
1035         *p++ = '/';
1036
1037         domain = find_domain_from_name(dom_name);
1038         if (domain == NULL) {
1039                 /* We must delete the old record. */
1040                 DEBUG(0,("Unable to find domain %s\n", dom_name ));
1041                 DEBUG(0,("deleting record %s\n", key.dptr ));
1042
1043                 if (tdb_delete(tdb, key) != 0) {
1044                         DEBUG(0, ("Unable to delete record %s\n", key.dptr));
1045                         *failed = True;
1046                         return -1;
1047                 }
1048
1049                 return 0;
1050         }
1051
1052         rid = atoi(p);
1053
1054         sid_copy(&sid, &domain->sid);
1055         sid_append_rid(&sid, rid);
1056
1057         sid_to_string(keystr, &sid);
1058         key2.dptr = keystr;
1059         key2.dsize = strlen(keystr) + 1;
1060
1061         if (tdb_store(tdb, key2, data, TDB_INSERT) != 0) {
1062                 DEBUG(0,("Unable to add record %s\n", key2.dptr ));
1063                 *failed = True;
1064                 return -1;
1065         }
1066
1067         if (tdb_store(tdb, data, key2, TDB_REPLACE) != 0) {
1068                 DEBUG(0,("Unable to update record %s\n", data.dptr ));
1069                 *failed = True;
1070                 return -1;
1071         }
1072
1073         if (tdb_delete(tdb, key) != 0) {
1074                 DEBUG(0,("Unable to delete record %s\n", key.dptr ));
1075                 *failed = True;
1076                 return -1;
1077         }
1078
1079         return 0;
1080 }
1081
1082 /* These definitions are from sam/idmap_tdb.c. Replicated here just
1083    out of laziness.... :-( */
1084
1085 /* High water mark keys */
1086 #define HWM_GROUP  "GROUP HWM"
1087 #define HWM_USER   "USER HWM"
1088
1089 /*****************************************************************************
1090  Convert the idmap database from an older version.
1091 *****************************************************************************/
1092
1093 static BOOL idmap_convert(const char *idmap_name)
1094 {
1095         int32 vers;
1096         BOOL bigendianheader;
1097         BOOL failed = False;
1098         TDB_CONTEXT *idmap_tdb;
1099
1100         if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
1101                                         TDB_DEFAULT, O_RDWR,
1102                                         0600))) {
1103                 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
1104                 return False;
1105         }
1106
1107         bigendianheader = (idmap_tdb->flags & TDB_BIGENDIAN) ? True : False;
1108
1109         vers = tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION");
1110
1111         if (((vers == -1) && bigendianheader) || (IREV(vers) == IDMAP_VERSION)) {
1112                 /* Arrggghh ! Bytereversed or old big-endian - make order independent ! */
1113                 /*
1114                  * high and low records were created on a
1115                  * big endian machine and will need byte-reversing.
1116                  */
1117
1118                 int32 wm;
1119
1120                 wm = tdb_fetch_int32(idmap_tdb, HWM_USER);
1121
1122                 if (wm != -1) {
1123                         wm = IREV(wm);
1124                 }  else {
1125                         wm = server_state.uid_low;
1126                 }
1127
1128                 if (tdb_store_int32(idmap_tdb, HWM_USER, wm) == -1) {
1129                         DEBUG(0, ("idmap_convert: Unable to byteswap user hwm in idmap database\n"));
1130                         tdb_close(idmap_tdb);
1131                         return False;
1132                 }
1133
1134                 wm = tdb_fetch_int32(idmap_tdb, HWM_GROUP);
1135                 if (wm != -1) {
1136                         wm = IREV(wm);
1137                 } else {
1138                         wm = server_state.gid_low;
1139                 }
1140
1141                 if (tdb_store_int32(idmap_tdb, HWM_GROUP, wm) == -1) {
1142                         DEBUG(0, ("idmap_convert: Unable to byteswap group hwm in idmap database\n"));
1143                         tdb_close(idmap_tdb);
1144                         return False;
1145                 }
1146         }
1147
1148         /* the old format stored as DOMAIN/rid - now we store the SID direct */
1149         tdb_traverse(idmap_tdb, convert_fn, &failed);
1150
1151         if (failed) {
1152                 DEBUG(0, ("Problem during conversion\n"));
1153                 tdb_close(idmap_tdb);
1154                 return False;
1155         }
1156
1157         if (tdb_store_int32(idmap_tdb, "IDMAP_VERSION", IDMAP_VERSION) == -1) {
1158                 DEBUG(0, ("idmap_convert: Unable to dtore idmap version in databse\n"));
1159                 tdb_close(idmap_tdb);
1160                 return False;
1161         }
1162
1163         tdb_close(idmap_tdb);
1164         return True;
1165 }
1166
1167 /*****************************************************************************
1168  Convert the idmap database from an older version if necessary
1169 *****************************************************************************/
1170
1171 BOOL winbindd_upgrade_idmap(void)
1172 {
1173         pstring idmap_name;
1174         pstring backup_name;
1175         SMB_STRUCT_STAT stbuf;
1176         TDB_CONTEXT *idmap_tdb;
1177
1178         pstrcpy(idmap_name, lock_path("winbindd_idmap.tdb"));
1179
1180         if (!file_exist(idmap_name, &stbuf)) {
1181                 /* nothing to convert return */
1182                 return True;
1183         }
1184
1185         if (!(idmap_tdb = tdb_open_log(idmap_name, 0,
1186                                         TDB_DEFAULT, O_RDWR,
1187                                         0600))) {
1188                 DEBUG(0, ("idmap_convert: Unable to open idmap database\n"));
1189                 return False;
1190         }
1191
1192         if (tdb_fetch_int32(idmap_tdb, "IDMAP_VERSION") == IDMAP_VERSION) {
1193                 /* nothing to convert return */
1194                 tdb_close(idmap_tdb);
1195                 return True;
1196         }
1197
1198         /* backup_tdb expects the tdb not to be open */
1199         tdb_close(idmap_tdb);
1200
1201         DEBUG(0, ("Upgrading winbindd_idmap.tdb from an old version\n"));
1202
1203         pstrcpy(backup_name, idmap_name);
1204         pstrcat(backup_name, ".bak");
1205
1206         if (backup_tdb(idmap_name, backup_name) != 0) {
1207                 DEBUG(0, ("Could not backup idmap database\n"));
1208                 return False;
1209         }
1210
1211         return idmap_convert(idmap_name);
1212 }
1213
1214 void winbindd_flush_nscd_cache(void)
1215 {
1216 #ifdef HAVE_NSCD_FLUSH_CACHE
1217
1218         /* Flush nscd caches to get accurate new information */
1219         int ret = nscd_flush_cache("passwd");
1220         if (ret) {
1221                 DEBUG(5,("failed to flush nscd cache for 'passwd' service: %s\n",
1222                         strerror(ret)));
1223         }
1224
1225         ret = nscd_flush_cache("group");
1226         if (ret) {
1227                 DEBUG(5,("failed to flush nscd cache for 'group' service: %s\n",
1228                         strerror(ret)));
1229         }
1230 #else
1231         return;
1232 #endif
1233 }
1234