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