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