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