This is the start of a bit of a rewrite of winbindd's connection handling.
[ira/wip.git] / source3 / nsswitch / winbindd.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 2.0
4
5    Winbind daemon for ntdom nss module
6
7    Copyright (C) Tim Potter 2000
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 };
225
226 static struct dispatch_table dispatch_table[] = {
227         
228         /* User functions */
229
230         { WINBINDD_GETPWNAM_FROM_USER, winbindd_getpwnam_from_user },
231         { WINBINDD_GETPWNAM_FROM_UID, winbindd_getpwnam_from_uid },
232
233 #if 0
234
235         { WINBINDD_SETPWENT, winbindd_setpwent },
236         { WINBINDD_ENDPWENT, winbindd_endpwent },
237         { WINBINDD_GETPWENT, winbindd_getpwent },
238
239         { WINBINDD_GETGROUPS, winbindd_getgroups },
240
241         /* Group functions */
242
243         { WINBINDD_GETGRNAM_FROM_GROUP, winbindd_getgrnam_from_group },
244         { WINBINDD_GETGRNAM_FROM_GID, winbindd_getgrnam_from_gid },
245         { WINBINDD_SETGRENT, winbindd_setgrent },
246         { WINBINDD_ENDGRENT, winbindd_endgrent },
247         { WINBINDD_GETGRENT, winbindd_getgrent },
248
249         /* PAM auth functions */
250
251         { WINBINDD_PAM_AUTH, winbindd_pam_auth },
252         { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap },
253         { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok },
254
255         /* Enumeration functions */
256
257         { WINBINDD_LIST_USERS, winbindd_list_users },
258         { WINBINDD_LIST_GROUPS, winbindd_list_groups },
259         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains },
260
261         /* SID related functions */
262
263         { WINBINDD_LOOKUPSID, winbindd_lookupsid },
264         { WINBINDD_LOOKUPNAME, winbindd_lookupname },
265
266         /* S*RS related functions */
267
268         { WINBINDD_SID_TO_UID, winbindd_sid_to_uid },
269         { WINBINDD_SID_TO_GID, winbindd_sid_to_gid },
270         { WINBINDD_GID_TO_SID, winbindd_gid_to_sid },
271         { WINBINDD_UID_TO_SID, winbindd_uid_to_sid },
272
273         /* Miscellaneous */
274
275         { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct },
276
277 #endif
278
279         /* End of list */
280
281         { WINBINDD_NUM_CMDS, NULL }
282 };
283
284 static void process_request(struct winbindd_cli_state *state)
285 {
286         struct dispatch_table *table = dispatch_table;
287
288         /* Free response data - we may be interrupted and receive another
289            command before being able to send this data off. */
290
291         SAFE_FREE(state->response.extra_data);  
292
293         ZERO_STRUCT(state->response);
294
295         state->response.result = WINBINDD_ERROR;
296         state->response.length = sizeof(struct winbindd_response);
297
298         /* Process command */
299
300         for (table = dispatch_table; table->fn; table++) {
301                 if (state->request.cmd == table->cmd) {
302                         state->response.result = table->fn(state);
303                         break;
304                 }
305         }
306
307         /* In case extra data pointer is NULL */
308
309         if (!state->response.extra_data)
310                 state->response.length = sizeof(struct winbindd_response);
311 }
312
313 /* Process a new connection by adding it to the client connection list */
314
315 static void new_connection(int accept_sock)
316 {
317         struct sockaddr_un sunaddr;
318         struct winbindd_cli_state *state;
319         socklen_t len;
320         int sock;
321         
322         /* Accept connection */
323         
324         len = sizeof(sunaddr);
325         if ((sock = accept(accept_sock, (struct sockaddr *)&sunaddr, &len)) 
326             == -1)
327                 return;
328         
329         DEBUG(6,("accepted socket %d\n", sock));
330         
331         /* Create new connection structure */
332         
333         if ((state = (struct winbindd_cli_state *) 
334              malloc(sizeof(*state))) == NULL)
335                 return;
336         
337         ZERO_STRUCTP(state);
338         state->sock = sock;
339         
340         /* Add to connection list */
341         
342         DLIST_ADD(client_list, state);
343         num_clients++;
344 }
345
346 /* Remove a client connection from client connection list */
347
348 static void remove_client(struct winbindd_cli_state *state)
349 {
350         /* It's a dead client - hold a funeral */
351         
352         if (state != NULL) {
353                 
354                 /* Close socket */
355                 
356                 close(state->sock);
357                 
358                 /* Free any getent state */
359                 
360                 free_getent_state(state->getpwent_state);
361                 free_getent_state(state->getgrent_state);
362                 
363                 /* We may have some extra data that was not freed if the
364                    client was killed unexpectedly */
365
366                 SAFE_FREE(state->response.extra_data);
367                 
368                 /* Remove from list and free */
369                 
370                 DLIST_REMOVE(client_list, state);
371                 SAFE_FREE(state);
372                 num_clients--;
373         }
374 }
375
376 /* Process a complete received packet from a client */
377
378 static void process_packet(struct winbindd_cli_state *state)
379 {
380         /* Process request */
381         
382         state->pid = state->request.pid;
383         
384         process_request(state);
385
386         /* Update client state */
387         
388         state->read_buf_len = 0;
389         state->write_buf_len = sizeof(struct winbindd_response);
390 }
391
392 /* Read some data from a client connection */
393
394 static void client_read(struct winbindd_cli_state *state)
395 {
396         int n;
397     
398         /* Read data */
399
400         n = read(state->sock, state->read_buf_len + (char *)&state->request, 
401                  sizeof(state->request) - state->read_buf_len);
402         
403         /* Read failed, kill client */
404         
405         if (n == -1 || n == 0) {
406                 DEBUG(5,("read failed on sock %d, pid %d: %s\n",
407                          state->sock, state->pid, 
408                          (n == -1) ? strerror(errno) : "EOF"));
409                 
410                 state->finished = True;
411                 return;
412         }
413         
414         /* Update client state */
415         
416         state->read_buf_len += n;
417 }
418
419 /* Write some data to a client connection */
420
421 static void client_write(struct winbindd_cli_state *state)
422 {
423         char *data;
424         int num_written;
425         
426         /* Write some data */
427         
428         if (!state->write_extra_data) {
429
430                 /* Write response structure */
431                 
432                 data = (char *)&state->response + sizeof(state->response) - 
433                         state->write_buf_len;
434
435         } else {
436
437                 /* Write extra data */
438                 
439                 data = (char *)state->response.extra_data + 
440                         state->response.length - 
441                         sizeof(struct winbindd_response) - 
442                         state->write_buf_len;
443         }
444         
445         num_written = write(state->sock, data, state->write_buf_len);
446         
447         /* Write failed, kill cilent */
448         
449         if (num_written == -1 || num_written == 0) {
450                 
451                 DEBUG(3,("write failed on sock %d, pid %d: %s\n",
452                          state->sock, state->pid, 
453                          (num_written == -1) ? strerror(errno) : "EOF"));
454                 
455                 state->finished = True;
456
457                 SAFE_FREE(state->response.extra_data);
458
459                 return;
460         }
461         
462         /* Update client state */
463         
464         state->write_buf_len -= num_written;
465         
466         /* Have we written all data? */
467         
468         if (state->write_buf_len == 0) {
469                 
470                 /* Take care of extra data */
471                 
472                 if (state->write_extra_data) {
473
474                         SAFE_FREE(state->response.extra_data);
475
476                         state->write_extra_data = False;
477
478                 } else if (state->response.length > 
479                            sizeof(struct winbindd_response)) {
480                         
481                         /* Start writing extra data */
482
483                         state->write_buf_len = 
484                                 state->response.length -
485                                 sizeof(struct winbindd_response);
486                         
487                         state->write_extra_data = True;
488                 }
489         }
490 }
491
492 /* Process incoming clients on accept_sock.  We use a tricky non-blocking,
493    non-forking, non-threaded model which allows us to handle many
494    simultaneous connections while remaining impervious to many denial of
495    service attacks. */
496
497 static void process_loop(int accept_sock)
498 {
499         /* We'll be doing this a lot */
500
501         while (1) {
502                 struct winbindd_cli_state *state;
503                 fd_set r_fds, w_fds;
504                 int maxfd = accept_sock, selret;
505                 struct timeval timeout;
506
507                 /* Free up temporary memory */
508
509                 lp_talloc_free();
510
511                 /* Initialise fd lists for select() */
512
513                 FD_ZERO(&r_fds);
514                 FD_ZERO(&w_fds);
515                 FD_SET(accept_sock, &r_fds);
516
517                 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
518                 timeout.tv_usec = 0;
519
520                 /* Set up client readers and writers */
521
522                 state = client_list;
523
524                 while (state) {
525
526                         /* Dispose of client connection if it is marked as 
527                            finished */ 
528
529                         if (state->finished) {
530                                 struct winbindd_cli_state *next = state->next;
531
532                                 remove_client(state);
533                                 state = next;
534                                 continue;
535                         }
536
537                         /* Select requires we know the highest fd used */
538
539                         if (state->sock > maxfd) maxfd = state->sock;
540
541                         /* Add fd for reading */
542
543                         if (state->read_buf_len != sizeof(state->request))
544                                 FD_SET(state->sock, &r_fds);
545
546                         /* Add fd for writing */
547
548                         if (state->write_buf_len)
549                                 FD_SET(state->sock, &w_fds);
550
551                         state = state->next;
552                 }
553
554                 /* Check signal handling things */
555
556                 if (do_sighup) {
557
558                         /* Flush winbindd cache */
559
560                         do_flush_caches();
561                         reload_services_file(True);
562
563                         do_sighup = False;
564                 }
565
566                 if (print_winbindd_status) {
567                         do_print_winbindd_status();
568                         print_winbindd_status = False;
569                 }
570
571                 /* Call select */
572         
573                 selret = select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
574
575                 if (selret == 0) continue;
576
577                 if ((selret == -1 && errno != EINTR) || selret == 0) {
578
579                         /* Select error, something is badly wrong */
580
581                         perror("select");
582                         exit(1);
583                 }
584
585                 /* Create a new connection if accept_sock readable */
586
587                 if (selret > 0) {
588
589                         if (FD_ISSET(accept_sock, &r_fds))
590                                 new_connection(accept_sock);
591             
592                         /* Process activity on client connections */
593             
594                         for (state = client_list; state; state = state->next) {
595                 
596                                 /* Data available for reading */
597                 
598                                 if (FD_ISSET(state->sock, &r_fds)) {
599                     
600                                         /* Read data */
601                     
602                                         client_read(state);
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 }
621
622 /* Main function */
623
624 struct winbindd_state server_state;   /* Server state information */
625
626 int main(int argc, char **argv)
627 {
628         extern pstring global_myname;
629         extern pstring debugf;
630         int accept_sock;
631         BOOL interactive = False;
632         int opt, new_debuglevel = -1;
633
634         /* Initialise for running in non-root mode */
635
636         sec_init();
637
638         /* Set environment variable so we don't recursively call ourselves.
639            This may also be useful interactively. */
640
641         SETENV(WINBINDD_DONT_ENV, "1", 1);
642
643         /* Initialise samba/rpc client stuff */
644
645         while ((opt = getopt(argc, argv, "id:s:")) != EOF) {
646                 switch (opt) {
647
648                         /* Don't become a daemon */
649
650                 case 'i':
651                         interactive = True;
652                         break;
653
654                         /* Run with specified debug level */
655
656                 case 'd':
657                         new_debuglevel = atoi(optarg);
658                         break;
659
660                         /* Load a different smb.conf file */
661
662                 case 's':
663                         pstrcpy(servicesf,optarg);
664                         break;
665
666                 default:
667                         printf("Unknown option %c\n", (char)opt);
668                         exit(1);
669                 }
670         }
671
672         snprintf(debugf, sizeof(debugf), "%s/log.winbindd", LOGFILEBASE);
673         setup_logging("winbindd", interactive);
674         reopen_logs();
675
676         if (!*global_myname) {
677                 char *p;
678
679                 fstrcpy(global_myname, myhostname());
680                 p = strchr(global_myname, '.');
681                 if (p)
682                         *p = 0;
683         }
684
685         TimeInit();
686
687         if (!reload_services_file(False)) {
688                 DEBUG(0, ("error opening config file\n"));
689                 exit(1);
690         }
691
692         if (new_debuglevel != -1)
693                 DEBUGLEVEL = new_debuglevel;
694
695         if (!interactive)
696                 become_daemon();
697
698         load_interfaces();
699
700         secrets_init();
701
702         ZERO_STRUCT(server_state);
703
704         /* Winbind daemon initialisation */
705
706         if (!winbindd_param_init())
707                 return 1;
708
709         if (!winbindd_idmap_init())
710                 return 1;
711
712         winbindd_cache_init();
713
714         /* Unblock all signals we are interested in as they may have been
715            blocked by the parent process. */
716
717         BlockSignals(False, SIGINT);
718         BlockSignals(False, SIGQUIT);
719         BlockSignals(False, SIGTERM);
720         BlockSignals(False, SIGUSR1);
721         BlockSignals(False, SIGHUP);
722
723         /* Setup signal handlers */
724         
725         CatchSignal(SIGINT, termination_handler);      /* Exit on these sigs */
726         CatchSignal(SIGQUIT, termination_handler);
727         CatchSignal(SIGTERM, termination_handler);
728
729         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
730
731         CatchSignal(SIGUSR1, sigusr1_handler);         /* Debugging sigs */
732         CatchSignal(SIGHUP, sighup_handler);
733
734         /* Create UNIX domain socket */
735         
736         if ((accept_sock = create_sock()) == -1) {
737                 DEBUG(0, ("failed to create socket\n"));
738                 return 1;
739         }
740
741         /* Loop waiting for requests */
742
743         process_loop(accept_sock);
744
745         return 0;
746 }