Removed version number from file header.
[kai/samba.git] / source3 / nsswitch / winbindd.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon for ntdom nss module
5
6    Copyright (C) by Tim Potter 2000, 2001
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "winbindd.h"
24
25 /* List of all connected clients */
26
27 struct winbindd_cli_state *client_list;
28 static int num_clients;
29 BOOL opt_nocache;
30
31 /* Reload configuration */
32
33 static BOOL reload_services_file(BOOL test)
34 {
35         BOOL ret;
36         pstring logfile;
37
38         if (lp_loaded()) {
39                 pstring fname;
40
41                 pstrcpy(fname,lp_configfile());
42                 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
43                         pstrcpy(dyn_CONFIGFILE,fname);
44                         test = False;
45                 }
46         }
47
48         snprintf(logfile, sizeof(logfile), "%s/log.winbindd", dyn_LOGFILEBASE);
49         lp_set_logfile(logfile);
50
51         reopen_logs();
52         ret = lp_load(dyn_CONFIGFILE,False,False,True);
53
54         snprintf(logfile, sizeof(logfile), "%s/log.winbindd", dyn_LOGFILEBASE);
55         lp_set_logfile(logfile);
56
57         reopen_logs();
58         load_interfaces();
59
60         return(ret);
61 }
62
63 #if DUMP_CORE
64
65 /**************************************************************************** **
66  Prepare to dump a core file - carefully!
67  **************************************************************************** */
68
69 static BOOL dump_core(void)
70 {
71         char *p;
72         pstring dname;
73         pstrcpy( dname, lp_logfile() );
74         if ((p=strrchr(dname,'/')))
75                 *p=0;
76         pstrcat( dname, "/corefiles" );
77         mkdir( dname, 0700 );
78         sys_chown( dname, getuid(), getgid() );
79         chmod( dname, 0700 );
80         if ( chdir(dname) )
81                 return( False );
82         umask( ~(0700) );
83  
84 #ifdef HAVE_GETRLIMIT
85 #ifdef RLIMIT_CORE
86         {
87                 struct rlimit rlp;
88                 getrlimit( RLIMIT_CORE, &rlp );
89                 rlp.rlim_cur = MAX( 4*1024*1024, rlp.rlim_cur );
90                 setrlimit( RLIMIT_CORE, &rlp );
91                 getrlimit( RLIMIT_CORE, &rlp );
92                 DEBUG( 3, ( "Core limits now %d %d\n", (int)rlp.rlim_cur, (int)rlp.rlim_max ) );
93         }
94 #endif
95 #endif
96  
97         DEBUG(0,("Dumping core in %s\n",dname));
98         abort();
99         return( True );
100 } /* dump_core */
101 #endif
102
103 /**************************************************************************** **
104  Handle a fault..
105  **************************************************************************** */
106
107 static void fault_quit(void)
108 {
109 #if DUMP_CORE
110         dump_core();
111 #endif
112 }
113
114 static void winbindd_status(void)
115 {
116         struct winbindd_cli_state *tmp;
117
118         DEBUG(0, ("winbindd status:\n"));
119
120         /* Print client state information */
121         
122         DEBUG(0, ("\t%d clients currently active\n", num_clients));
123         
124         if (DEBUGLEVEL >= 2 && num_clients) {
125                 DEBUG(2, ("\tclient list:\n"));
126                 for(tmp = client_list; tmp; tmp = tmp->next) {
127                         DEBUG(2, ("\t\tpid %d, sock %d, rbl %d, wbl %d\n",
128                                   tmp->pid, tmp->sock, tmp->read_buf_len, 
129                                   tmp->write_buf_len));
130                 }
131         }
132 }
133
134 /* Print winbindd status to log file */
135
136 static void print_winbindd_status(void)
137 {
138         winbindd_status();
139         winbindd_idmap_status();
140         winbindd_cm_status();
141 }
142
143 /* Flush client cache */
144
145 static void flush_caches(void)
146 {
147         /* Clear cached user and group enumation info */        
148         wcache_flush_cache();
149 }
150
151 /* Handle the signal by unlinking socket and exiting */
152
153 static void terminate(void)
154 {
155         pstring path;
156
157         winbindd_idmap_close();
158         
159         /* Remove socket file */
160         snprintf(path, sizeof(path), "%s/%s", 
161                  WINBINDD_SOCKET_DIR, WINBINDD_SOCKET_NAME);
162         unlink(path);
163         exit(0);
164 }
165
166 static BOOL do_sigterm;
167
168 static void termination_handler(int signum)
169 {
170         do_sigterm = True;
171 }
172
173 static BOOL do_sigusr2;
174
175 static void sigusr2_handler(int signum)
176 {
177         do_sigusr2 = True;
178 }
179
180 static BOOL do_sighup;
181
182 static void sighup_handler(int signum)
183 {
184         do_sighup = True;
185 }
186
187 /* Create winbindd socket */
188
189 static int create_sock(void)
190 {
191         return create_pipe_sock( WINBINDD_SOCKET_DIR,
192                                  WINBINDD_SOCKET_NAME, 0755);
193 }
194
195 struct dispatch_table {
196         enum winbindd_cmd cmd;
197         enum winbindd_result (*fn)(struct winbindd_cli_state *state);
198         char *winbindd_cmd_name;
199 };
200
201 static struct dispatch_table dispatch_table[] = {
202         
203         /* User functions */
204
205         { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
206         { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
207
208         { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
209         { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
210         { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
211
212         { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
213
214         /* Group functions */
215
216         { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
217         { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
218         { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
219         { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
220         { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
221
222         /* PAM auth functions */
223
224         { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
225         { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
226         { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
227
228         /* Enumeration functions */
229
230         { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
231         { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
232         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains, "LIST_TRUSTDOM" },
233
234         /* SID related functions */
235
236         { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
237         { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
238
239         /* Lookup related functions */
240
241         { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
242         { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
243         { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
244         { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
245
246         /* Miscellaneous */
247
248         { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
249         { WINBINDD_PING, winbindd_ping, "PING" },
250         { WINBINDD_INFO, winbindd_info, "INFO" },
251         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version, "INTERFACE_VERSION" },
252         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
253
254         /* End of list */
255
256         { WINBINDD_NUM_CMDS, NULL, "NONE" }
257 };
258
259 static void process_request(struct winbindd_cli_state *state)
260 {
261         struct dispatch_table *table = dispatch_table;
262
263         /* Free response data - we may be interrupted and receive another
264            command before being able to send this data off. */
265
266         SAFE_FREE(state->response.extra_data);  
267
268         ZERO_STRUCT(state->response);
269
270         state->response.result = WINBINDD_ERROR;
271         state->response.length = sizeof(struct winbindd_response);
272
273         /* Process command */
274
275         for (table = dispatch_table; table->fn; table++) {
276                 if (state->request.cmd == table->cmd) {
277                         DEBUG(10,("process_request: request fn %s\n", table->winbindd_cmd_name ));
278                         state->response.result = table->fn(state);
279                         break;
280                 }
281         }
282
283         if (!table->fn)
284                 DEBUG(10,("process_request: unknown request fn number %d\n", (int)state->request.cmd ));
285
286         /* In case extra data pointer is NULL */
287
288         if (!state->response.extra_data)
289                 state->response.length = sizeof(struct winbindd_response);
290 }
291
292 /* Process a new connection by adding it to the client connection list */
293
294 static void new_connection(int accept_sock)
295 {
296         struct sockaddr_un sunaddr;
297         struct winbindd_cli_state *state;
298         socklen_t len;
299         int sock;
300         
301         /* Accept connection */
302         
303         len = sizeof(sunaddr);
304
305         do {
306                 sock = accept(accept_sock, (struct sockaddr *)&sunaddr, &len);
307         } while (sock == -1 && errno == EINTR);
308
309         if (sock == -1)
310                 return;
311         
312         DEBUG(6,("accepted socket %d\n", sock));
313         
314         /* Create new connection structure */
315         
316         if ((state = (struct winbindd_cli_state *) 
317              malloc(sizeof(*state))) == NULL)
318                 return;
319         
320         ZERO_STRUCTP(state);
321         state->sock = sock;
322         
323         /* Add to connection list */
324         
325         DLIST_ADD(client_list, state);
326         num_clients++;
327 }
328
329 /* Remove a client connection from client connection list */
330
331 static void remove_client(struct winbindd_cli_state *state)
332 {
333         /* It's a dead client - hold a funeral */
334         
335         if (state != NULL) {
336                 
337                 /* Close socket */
338                 
339                 close(state->sock);
340                 
341                 /* Free any getent state */
342                 
343                 free_getent_state(state->getpwent_state);
344                 free_getent_state(state->getgrent_state);
345                 
346                 /* We may have some extra data that was not freed if the
347                    client was killed unexpectedly */
348
349                 SAFE_FREE(state->response.extra_data);
350                 
351                 /* Remove from list and free */
352                 
353                 DLIST_REMOVE(client_list, state);
354                 SAFE_FREE(state);
355                 num_clients--;
356         }
357 }
358
359 /* Process a complete received packet from a client */
360
361 static void process_packet(struct winbindd_cli_state *state)
362 {
363         /* Process request */
364         
365         state->pid = state->request.pid;
366         
367         process_request(state);
368
369         /* Update client state */
370         
371         state->read_buf_len = 0;
372         state->write_buf_len = sizeof(struct winbindd_response);
373 }
374
375 /* Read some data from a client connection */
376
377 static void client_read(struct winbindd_cli_state *state)
378 {
379         int n;
380     
381         /* Read data */
382
383         do {
384
385                 n = read(state->sock, state->read_buf_len + 
386                          (char *)&state->request, 
387                          sizeof(state->request) - state->read_buf_len);
388
389         } while (n == -1 && errno == EINTR);
390         
391         DEBUG(10,("client_read: read %d bytes. Need %d more for a full request.\n", n, sizeof(state->request) - n - state->read_buf_len ));
392
393         /* Read failed, kill client */
394         
395         if (n == -1 || n == 0) {
396                 DEBUG(5,("read failed on sock %d, pid %d: %s\n",
397                          state->sock, state->pid, 
398                          (n == -1) ? strerror(errno) : "EOF"));
399                 
400                 state->finished = True;
401                 return;
402         }
403         
404         /* Update client state */
405         
406         state->read_buf_len += n;
407 }
408
409 /* Write some data to a client connection */
410
411 static void client_write(struct winbindd_cli_state *state)
412 {
413         char *data;
414         int num_written;
415         
416         /* Write some data */
417         
418         if (!state->write_extra_data) {
419
420                 /* Write response structure */
421                 
422                 data = (char *)&state->response + sizeof(state->response) - 
423                         state->write_buf_len;
424
425         } else {
426
427                 /* Write extra data */
428                 
429                 data = (char *)state->response.extra_data + 
430                         state->response.length - 
431                         sizeof(struct winbindd_response) - 
432                         state->write_buf_len;
433         }
434         
435         do {
436                 num_written = write(state->sock, data, state->write_buf_len);
437         } while (num_written == -1 && errno == EINTR);
438         
439         DEBUG(10,("client_write: wrote %d bytes.\n", num_written ));
440
441         /* Write failed, kill cilent */
442         
443         if (num_written == -1 || num_written == 0) {
444                 
445                 DEBUG(3,("write failed on sock %d, pid %d: %s\n",
446                          state->sock, state->pid, 
447                          (num_written == -1) ? strerror(errno) : "EOF"));
448                 
449                 state->finished = True;
450
451                 SAFE_FREE(state->response.extra_data);
452
453                 return;
454         }
455         
456         /* Update client state */
457         
458         state->write_buf_len -= num_written;
459         
460         /* Have we written all data? */
461         
462         if (state->write_buf_len == 0) {
463                 
464                 /* Take care of extra data */
465                 
466                 if (state->write_extra_data) {
467
468                         SAFE_FREE(state->response.extra_data);
469
470                         state->write_extra_data = False;
471
472                         DEBUG(10,("client_write: client_write: complete response written.\n"));
473
474                 } else if (state->response.length > 
475                            sizeof(struct winbindd_response)) {
476                         
477                         /* Start writing extra data */
478
479                         state->write_buf_len = 
480                                 state->response.length -
481                                 sizeof(struct winbindd_response);
482                         
483                         DEBUG(10,("client_write: need to write %d extra data bytes.\n", (int)state->write_buf_len));
484
485                         state->write_extra_data = True;
486                 }
487         }
488 }
489
490 /* Process incoming clients on accept_sock.  We use a tricky non-blocking,
491    non-forking, non-threaded model which allows us to handle many
492    simultaneous connections while remaining impervious to many denial of
493    service attacks. */
494
495 static void process_loop(int accept_sock)
496 {
497         /* We'll be doing this a lot */
498
499         while (1) {
500                 struct winbindd_cli_state *state;
501                 fd_set r_fds, w_fds;
502                 int maxfd = accept_sock, selret;
503                 struct timeval timeout;
504
505                 /* Free up temporary memory */
506
507                 lp_talloc_free();
508
509                 /* Initialise fd lists for select() */
510
511                 FD_ZERO(&r_fds);
512                 FD_ZERO(&w_fds);
513                 FD_SET(accept_sock, &r_fds);
514
515                 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
516                 timeout.tv_usec = 0;
517
518                 /* Set up client readers and writers */
519
520                 state = client_list;
521
522                 while (state) {
523
524                         /* Dispose of client connection if it is marked as 
525                            finished */ 
526
527                         if (state->finished) {
528                                 struct winbindd_cli_state *next = state->next;
529
530                                 remove_client(state);
531                                 state = next;
532                                 continue;
533                         }
534
535                         /* Select requires we know the highest fd used */
536
537                         if (state->sock > maxfd)
538                                 maxfd = state->sock;
539
540                         /* Add fd for reading */
541
542                         if (state->read_buf_len != sizeof(state->request))
543                                 FD_SET(state->sock, &r_fds);
544
545                         /* Add fd for writing */
546
547                         if (state->write_buf_len)
548                                 FD_SET(state->sock, &w_fds);
549
550                         state = state->next;
551                 }
552
553                 /* Call select */
554         
555                 selret = select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
556
557                 if (selret == 0)
558                         continue;
559
560                 if ((selret == -1 && errno != EINTR) || selret == 0) {
561
562                         /* Select error, something is badly wrong */
563
564                         perror("select");
565                         exit(1);
566                 }
567
568                 /* Create a new connection if accept_sock readable */
569
570                 if (selret > 0) {
571
572                         if (FD_ISSET(accept_sock, &r_fds))
573                                 new_connection(accept_sock);
574             
575                         /* Process activity on client connections */
576             
577                         for (state = client_list; state; state = state->next) {
578                 
579                                 /* Data available for reading */
580                 
581                                 if (FD_ISSET(state->sock, &r_fds)) {
582                     
583                                         /* Read data */
584                     
585                                         client_read(state);
586
587                                         /* 
588                                          * If we have the start of a
589                                          * packet, then check the
590                                          * length field to make sure
591                                          * the client's not talking
592                                          * Mock Swedish.
593                                          */
594
595                                         if (state->read_buf_len >= sizeof(uint32)
596                                             && *(uint32 *) &state->request != sizeof(state->request)) {
597                                                 DEBUG(0,("process_loop: Invalid request size (%d) send, should be (%d)\n",
598                                                                 *(uint32 *) &state->request, sizeof(state->request)));
599
600                                                 remove_client(state);
601                                                 break;
602                                         }
603
604                                         /* A request packet might be 
605                                            complete */
606                     
607                                         if (state->read_buf_len == 
608                                             sizeof(state->request)) {
609                                                 process_packet(state);
610                                         }
611                                 }
612                 
613                                 /* Data available for writing */
614                 
615                                 if (FD_ISSET(state->sock, &w_fds))
616                                         client_write(state);
617                         }
618                 }
619
620                 /* Check signal handling things */
621
622                 if (do_sigterm)
623                         terminate();
624
625                 if (do_sighup) {
626
627                         /* Flush winbindd cache */
628
629                         flush_caches();
630                         reload_services_file(True);
631                         do_sighup = False;
632                 }
633
634                 if (do_sigusr2) {
635                         print_winbindd_status();
636                         do_sigusr2 = False;
637                 }
638         }
639 }
640
641 /* Main function */
642
643 struct winbindd_state server_state;   /* Server state information */
644
645 int main(int argc, char **argv)
646 {
647         extern pstring global_myname;
648         extern fstring global_myworkgroup;
649         extern BOOL append_log;
650         pstring logfile;
651         int accept_sock;
652         BOOL interactive = False;
653         int opt, new_debuglevel = -1;
654
655         /* glibc (?) likes to print "User defined signal 1" and exit if a
656            SIGUSR2 is received before a handler is installed */
657
658         CatchSignal(SIGUSR2, SIG_IGN);
659
660         fault_setup((void (*)(void *))fault_quit );
661
662         /* Append to log file by default as we are a single process daemon
663            program. */
664
665         append_log = True;
666
667         snprintf(logfile, sizeof(logfile), "%s/log.winbindd", dyn_LOGFILEBASE);
668         lp_set_logfile(logfile);
669
670         /* Initialise for running in non-root mode */
671
672         sec_init();
673
674         /* Set environment variable so we don't recursively call ourselves.
675            This may also be useful interactively. */
676
677         SETENV(WINBINDD_DONT_ENV, "1", 1);
678
679         /* Initialise samba/rpc client stuff */
680
681         while ((opt = getopt(argc, argv, "id:s:n")) != EOF) {
682                 switch (opt) {
683
684                         /* Don't become a daemon */
685                 case 'i':
686                         interactive = True;
687                         break;
688
689                         /* disable cacheing */
690                 case 'n':
691                         opt_nocache = True;
692                         break;
693
694                         /* Run with specified debug level */
695                 case 'd':
696                         new_debuglevel = atoi(optarg);
697                         break;
698
699                         /* Load a different smb.conf file */
700                 case 's':
701                         pstrcpy(dyn_CONFIGFILE,optarg);
702                         break;
703
704                 default:
705                         printf("Unknown option %c\n", (char)opt);
706                         exit(1);
707                 }
708         }
709
710         snprintf(logfile, sizeof(logfile), "%s/log.winbindd", dyn_LOGFILEBASE);
711         lp_set_logfile(logfile);
712         setup_logging("winbindd", interactive);
713         reopen_logs();
714
715         DEBUG(1, ("winbindd version %s started.\n", VERSION ) );
716         DEBUGADD( 1, ( "Copyright The Samba Team 2000-2001\n" ) );
717
718         if (!reload_services_file(False)) {
719                 DEBUG(0, ("error opening config file\n"));
720                 exit(1);
721         }
722
723         pidfile_create("winbindd");
724
725         /* Setup names. */
726
727         if (!*global_myname) {
728                 char *p;
729
730                 fstrcpy(global_myname, myhostname());
731                 p = strchr(global_myname, '.');
732                 if (p)
733                         *p = 0;
734         }
735
736         fstrcpy(global_myworkgroup, lp_workgroup());
737
738         if (new_debuglevel != -1)
739                 DEBUGLEVEL = new_debuglevel;
740
741         if (!interactive)
742                 become_daemon();
743
744 #if HAVE_SETPGID
745         /*
746          * If we're interactive we want to set our own process group for
747          * signal management.
748          */
749         if (interactive)
750                 setpgid( (pid_t)0, (pid_t)0);
751 #endif
752
753         load_interfaces();
754
755         secrets_init();
756
757         /* Get list of domains we look up requests for.  This includes the
758            domain which we are a member of as well as any trusted
759            domains. */ 
760
761         init_domain_list();
762
763         ZERO_STRUCT(server_state);
764
765         /* Winbind daemon initialisation */
766
767         if (!winbindd_param_init())
768                 return 1;
769
770         if (!winbindd_idmap_init())
771                 return 1;
772
773         /* Unblock all signals we are interested in as they may have been
774            blocked by the parent process. */
775
776         BlockSignals(False, SIGINT);
777         BlockSignals(False, SIGQUIT);
778         BlockSignals(False, SIGTERM);
779         BlockSignals(False, SIGUSR2);
780         BlockSignals(False, SIGHUP);
781
782         /* Setup signal handlers */
783         
784         CatchSignal(SIGINT, termination_handler);      /* Exit on these sigs */
785         CatchSignal(SIGQUIT, termination_handler);
786         CatchSignal(SIGTERM, termination_handler);
787
788         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
789         CatchSignal(SIGUSR1, SIG_IGN);                 /* Samba messages */
790
791         CatchSignal(SIGUSR2, sigusr2_handler);         /* Debugging sigs */
792         CatchSignal(SIGHUP, sighup_handler);
793
794         /* Create UNIX domain socket */
795         
796         if ((accept_sock = create_sock()) == -1) {
797                 DEBUG(0, ("failed to create socket\n"));
798                 return 1;
799         }
800
801         /* Loop waiting for requests */
802
803         process_loop(accept_sock);
804
805         uni_group_cache_shutdown();
806         return 0;
807 }