Fix a race condition in winbind leading to a panic
[ira/wip.git] / source3 / winbindd / winbindd.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    Winbind daemon for ntdom nss module
5
6    Copyright (C) by Tim Potter 2000-2002
7    Copyright (C) Andrew Tridgell 2002
8    Copyright (C) Jelmer Vernooij 2003
9    Copyright (C) Volker Lendecke 2004
10
11    This program is free software; you can redistribute it and/or modify
12    it under the terms of the GNU General Public License as published by
13    the Free Software Foundation; either version 3 of the License, or
14    (at your option) any later version.
15
16    This program is distributed in the hope that it will be useful,
17    but WITHOUT ANY WARRANTY; without even the implied warranty of
18    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19    GNU General Public License for more details.
20
21    You should have received a copy of the GNU General Public License
22    along with this program.  If not, see <http://www.gnu.org/licenses/>.
23 */
24
25 #include "includes.h"
26 #include "winbindd.h"
27
28 #undef DBGC_CLASS
29 #define DBGC_CLASS DBGC_WINBIND
30
31 static bool opt_nocache = False;
32 static bool interactive = False;
33
34 extern bool override_logfile;
35
36 struct event_context *winbind_event_context(void)
37 {
38         static struct event_context *ctx;
39
40         if (!ctx && !(ctx = event_context_init(NULL))) {
41                 smb_panic("Could not init winbind event context");
42         }
43         return ctx;
44 }
45
46 struct messaging_context *winbind_messaging_context(void)
47 {
48         static struct messaging_context *ctx;
49
50         if (ctx == NULL) {
51                 ctx = messaging_init(NULL, server_id_self(),
52                                      winbind_event_context());
53         }
54         if (ctx == NULL) {
55                 DEBUG(0, ("Could not init winbind messaging context.\n"));
56         }
57         return ctx;
58 }
59
60 /* Reload configuration */
61
62 static bool reload_services_file(const char *lfile)
63 {
64         bool ret;
65
66         if (lp_loaded()) {
67                 const char *fname = lp_configfile();
68
69                 if (file_exist(fname) && !strcsequal(fname,get_dyn_CONFIGFILE())) {
70                         set_dyn_CONFIGFILE(fname);
71                 }
72         }
73
74         /* if this is a child, restore the logfile to the special
75            name - <domain>, idmap, etc. */
76         if (lfile && *lfile) {
77                 lp_set_logfile(lfile);
78         }
79
80         reopen_logs();
81         ret = lp_load(get_dyn_CONFIGFILE(),False,False,True,True);
82
83         reopen_logs();
84         load_interfaces();
85
86         return(ret);
87 }
88
89
90 /**************************************************************************** **
91  Handle a fault..
92  **************************************************************************** */
93
94 static void fault_quit(void)
95 {
96         dump_core();
97 }
98
99 static void winbindd_status(void)
100 {
101         struct winbindd_cli_state *tmp;
102
103         DEBUG(0, ("winbindd status:\n"));
104
105         /* Print client state information */
106
107         DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
108
109         if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
110                 DEBUG(2, ("\tclient list:\n"));
111                 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
112                         DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
113                                   (unsigned long)tmp->pid, tmp->sock));
114                 }
115         }
116 }
117
118 /* Print winbindd status to log file */
119
120 static void print_winbindd_status(void)
121 {
122         winbindd_status();
123 }
124
125 /* Flush client cache */
126
127 static void flush_caches(void)
128 {
129         /* We need to invalidate cached user list entries on a SIGHUP 
130            otherwise cached access denied errors due to restrict anonymous
131            hang around until the sequence number changes. */
132
133         if (!wcache_invalidate_cache()) {
134                 DEBUG(0, ("invalidating the cache failed; revalidate the cache\n"));
135                 if (!winbindd_cache_validate_and_initialize()) {
136                         exit(1);
137                 }
138         }
139 }
140
141 /* Handle the signal by unlinking socket and exiting */
142
143 static void terminate(bool is_parent)
144 {
145         if (is_parent) {
146                 /* When parent goes away we should
147                  * remove the socket file. Not so
148                  * when children terminate.
149                  */ 
150                 char *path = NULL;
151
152                 if (asprintf(&path, "%s/%s",
153                         get_winbind_pipe_dir(), WINBINDD_SOCKET_NAME) > 0) {
154                         unlink(path);
155                         SAFE_FREE(path);
156                 }
157         }
158
159         idmap_close();
160
161         trustdom_cache_shutdown();
162
163 #if 0
164         if (interactive) {
165                 TALLOC_CTX *mem_ctx = talloc_init("end_description");
166                 char *description = talloc_describe_all(mem_ctx);
167
168                 DEBUG(3, ("tallocs left:\n%s\n", description));
169                 talloc_destroy(mem_ctx);
170         }
171 #endif
172
173         exit(0);
174 }
175
176 static void winbindd_sig_term_handler(struct tevent_context *ev,
177                                       struct tevent_signal *se,
178                                       int signum,
179                                       int count,
180                                       void *siginfo,
181                                       void *private_data)
182 {
183         bool *is_parent = talloc_get_type_abort(private_data, bool);
184
185         DEBUG(0,("Got sig[%d] terminate (is_parent=%d)\n",
186                  signum, (int)*is_parent));
187         terminate(*is_parent);
188 }
189
190 bool winbindd_setup_sig_term_handler(bool parent)
191 {
192         struct tevent_signal *se;
193         bool *is_parent;
194
195         is_parent = talloc(winbind_event_context(), bool);
196         if (!is_parent) {
197                 return false;
198         }
199
200         *is_parent = parent;
201
202         se = tevent_add_signal(winbind_event_context(),
203                                is_parent,
204                                SIGTERM, 0,
205                                winbindd_sig_term_handler,
206                                is_parent);
207         if (!se) {
208                 DEBUG(0,("failed to setup SIGTERM handler"));
209                 talloc_free(is_parent);
210                 return false;
211         }
212
213         se = tevent_add_signal(winbind_event_context(),
214                                is_parent,
215                                SIGINT, 0,
216                                winbindd_sig_term_handler,
217                                is_parent);
218         if (!se) {
219                 DEBUG(0,("failed to setup SIGINT handler"));
220                 talloc_free(is_parent);
221                 return false;
222         }
223
224         se = tevent_add_signal(winbind_event_context(),
225                                is_parent,
226                                SIGQUIT, 0,
227                                winbindd_sig_term_handler,
228                                is_parent);
229         if (!se) {
230                 DEBUG(0,("failed to setup SIGINT handler"));
231                 talloc_free(is_parent);
232                 return false;
233         }
234
235         return true;
236 }
237
238 static void winbindd_sig_hup_handler(struct tevent_context *ev,
239                                      struct tevent_signal *se,
240                                      int signum,
241                                      int count,
242                                      void *siginfo,
243                                      void *private_data)
244 {
245         const char *file = (const char *)private_data;
246
247         DEBUG(1,("Reloading services after SIGHUP\n"));
248         flush_caches();
249         reload_services_file(file);
250 }
251
252 bool winbindd_setup_sig_hup_handler(const char *lfile)
253 {
254         struct tevent_signal *se;
255         char *file = NULL;
256
257         if (lfile) {
258                 file = talloc_strdup(winbind_event_context(),
259                                      lfile);
260                 if (!file) {
261                         return false;
262                 }
263         }
264
265         se = tevent_add_signal(winbind_event_context(),
266                                winbind_event_context(),
267                                SIGHUP, 0,
268                                winbindd_sig_hup_handler,
269                                file);
270         if (!se) {
271                 return false;
272         }
273
274         return true;
275 }
276
277 static void winbindd_sig_chld_handler(struct tevent_context *ev,
278                                       struct tevent_signal *se,
279                                       int signum,
280                                       int count,
281                                       void *siginfo,
282                                       void *private_data)
283 {
284         pid_t pid;
285
286         while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
287                 winbind_child_died(pid);
288         }
289 }
290
291 static bool winbindd_setup_sig_chld_handler(void)
292 {
293         struct tevent_signal *se;
294
295         se = tevent_add_signal(winbind_event_context(),
296                                winbind_event_context(),
297                                SIGCHLD, 0,
298                                winbindd_sig_chld_handler,
299                                NULL);
300         if (!se) {
301                 return false;
302         }
303
304         return true;
305 }
306
307 static void winbindd_sig_usr2_handler(struct tevent_context *ev,
308                                       struct tevent_signal *se,
309                                       int signum,
310                                       int count,
311                                       void *siginfo,
312                                       void *private_data)
313 {
314         print_winbindd_status();
315 }
316
317 static bool winbindd_setup_sig_usr2_handler(void)
318 {
319         struct tevent_signal *se;
320
321         se = tevent_add_signal(winbind_event_context(),
322                                winbind_event_context(),
323                                SIGUSR2, 0,
324                                winbindd_sig_usr2_handler,
325                                NULL);
326         if (!se) {
327                 return false;
328         }
329
330         return true;
331 }
332
333 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
334 static void msg_reload_services(struct messaging_context *msg,
335                                 void *private_data,
336                                 uint32_t msg_type,
337                                 struct server_id server_id,
338                                 DATA_BLOB *data)
339 {
340         /* Flush various caches */
341         flush_caches();
342         reload_services_file((const char *) private_data);
343 }
344
345 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
346 static void msg_shutdown(struct messaging_context *msg,
347                          void *private_data,
348                          uint32_t msg_type,
349                          struct server_id server_id,
350                          DATA_BLOB *data)
351 {
352         /* only the parent waits for this message */
353         DEBUG(0,("Got shutdown message\n"));
354         terminate(true);
355 }
356
357
358 static void winbind_msg_validate_cache(struct messaging_context *msg_ctx,
359                                        void *private_data,
360                                        uint32_t msg_type,
361                                        struct server_id server_id,
362                                        DATA_BLOB *data)
363 {
364         uint8 ret;
365         pid_t child_pid;
366         struct sigaction act;
367         struct sigaction oldact;
368
369         DEBUG(10, ("winbindd_msg_validate_cache: got validate-cache "
370                    "message.\n"));
371
372         /*
373          * call the validation code from a child:
374          * so we don't block the main winbindd and the validation
375          * code can safely use fork/waitpid...
376          */
377         CatchChild();
378         child_pid = sys_fork();
379
380         if (child_pid == -1) {
381                 DEBUG(1, ("winbind_msg_validate_cache: Could not fork: %s\n",
382                           strerror(errno)));
383                 return;
384         }
385
386         if (child_pid != 0) {
387                 /* parent */
388                 DEBUG(5, ("winbind_msg_validate_cache: child created with "
389                           "pid %d.\n", (int)child_pid));
390                 return;
391         }
392
393         /* child */
394
395         /* install default SIGCHLD handler: validation code uses fork/waitpid */
396         ZERO_STRUCT(act);
397         act.sa_handler = SIG_DFL;
398 #ifdef SA_RESTART
399         /* We *want* SIGALRM to interrupt a system call. */
400         act.sa_flags = SA_RESTART;
401 #endif
402         sigemptyset(&act.sa_mask);
403         sigaddset(&act.sa_mask,SIGCHLD);
404         sigaction(SIGCHLD,&act,&oldact);
405
406         ret = (uint8)winbindd_validate_cache_nobackup();
407         DEBUG(10, ("winbindd_msg_validata_cache: got return value %d\n", ret));
408         messaging_send_buf(msg_ctx, server_id, MSG_WINBIND_VALIDATE_CACHE, &ret,
409                            (size_t)1);
410         _exit(0);
411 }
412
413 static struct winbindd_dispatch_table {
414         enum winbindd_cmd cmd;
415         void (*fn)(struct winbindd_cli_state *state);
416         const char *winbindd_cmd_name;
417 } dispatch_table[] = {
418
419         /* User functions */
420
421         { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
422         { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
423         { WINBINDD_GETPWSID, winbindd_getpwsid, "GETPWSID" },
424
425         { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
426         { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
427         { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
428
429         { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
430         { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
431         { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
432           "GETUSERDOMGROUPS" },
433         { WINBINDD_GETSIDALIASES, winbindd_getsidaliases,
434            "LOOKUPUSERALIASES" },
435
436         /* Group functions */
437
438         { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
439         { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
440         { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
441         { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
442         { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
443         { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
444
445         /* PAM auth functions */
446
447         { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
448         { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
449         { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
450         { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
451         { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
452
453         /* Enumeration functions */
454
455         { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
456         { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
457         { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
458           "LIST_TRUSTDOM" },
459         { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
460
461         /* SID related functions */
462
463         { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
464         { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
465         { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
466
467         /* Lookup related functions */
468
469         { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
470         { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
471         { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
472         { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
473         { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
474         { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
475         { WINBINDD_SET_MAPPING, winbindd_set_mapping, "SET_MAPPING" },
476         { WINBINDD_REMOVE_MAPPING, winbindd_remove_mapping, "REMOVE_MAPPING" },
477         { WINBINDD_SET_HWM, winbindd_set_hwm, "SET_HWMS" },
478
479         /* Miscellaneous */
480
481         { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
482         { WINBINDD_PING, winbindd_ping, "PING" },
483         { WINBINDD_INFO, winbindd_info, "INFO" },
484         { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
485           "INTERFACE_VERSION" },
486         { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
487         { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
488         { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
489         { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
490           "WINBINDD_PRIV_PIPE_DIR" },
491         { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
492         { WINBINDD_DSGETDCNAME, winbindd_dsgetdcname, "DSGETDCNAME" },
493
494         /* Credential cache access */
495         { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
496
497         /* WINS functions */
498
499         { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
500         { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
501
502         /* End of list */
503
504         { WINBINDD_NUM_CMDS, NULL, "NONE" }
505 };
506
507 static void process_request(struct winbindd_cli_state *state)
508 {
509         struct winbindd_dispatch_table *table = dispatch_table;
510
511         ZERO_STRUCT(state->response);
512
513         state->response.result = WINBINDD_PENDING;
514         state->response.length = sizeof(struct winbindd_response);
515
516         state->mem_ctx = talloc_init("winbind request");
517         if (state->mem_ctx == NULL)
518                 return;
519
520         /* Remember who asked us. */
521         state->pid = state->request.pid;
522
523         /* Process command */
524
525         for (table = dispatch_table; table->fn; table++) {
526                 if (state->request.cmd == table->cmd) {
527                         DEBUG(10,("process_request: request fn %s\n",
528                                   table->winbindd_cmd_name ));
529                         table->fn(state);
530                         break;
531                 }
532         }
533
534         if (!table->fn) {
535                 DEBUG(10,("process_request: unknown request fn number %d\n",
536                           (int)state->request.cmd ));
537                 request_error(state);
538         }
539 }
540
541 /*
542  * A list of file descriptors being monitored by select in the main processing
543  * loop. winbindd_fd_event->handler is called whenever the socket is readable/writable.
544  */
545
546 static struct winbindd_fd_event *fd_events = NULL;
547
548 void add_fd_event(struct winbindd_fd_event *ev)
549 {
550         struct winbindd_fd_event *match;
551
552         /* only add unique winbindd_fd_event structs */
553
554         for (match=fd_events; match; match=match->next ) {
555 #ifdef DEVELOPER
556                 SMB_ASSERT( match != ev );
557 #else
558                 if ( match == ev )
559                         return;
560 #endif
561         }
562
563         DLIST_ADD(fd_events, ev);
564 }
565
566 void remove_fd_event(struct winbindd_fd_event *ev)
567 {
568         DLIST_REMOVE(fd_events, ev);
569 }
570
571 /*
572  * Handler for winbindd_fd_events to complete a read/write request, set up by
573  * setup_async_read/setup_async_write.
574  */
575
576 static void rw_callback(struct winbindd_fd_event *event, int flags)
577 {
578         size_t todo;
579         ssize_t done = 0;
580
581         todo = event->length - event->done;
582
583         if (event->flags & EVENT_FD_WRITE) {
584                 SMB_ASSERT(flags == EVENT_FD_WRITE);
585                 done = sys_write(event->fd,
586                                  &((char *)event->data)[event->done],
587                                  todo);
588
589                 if (done <= 0) {
590                         event->flags = 0;
591                         event->finished(event->private_data, False);
592                         return;
593                 }
594         }
595
596         if (event->flags & EVENT_FD_READ) {
597                 SMB_ASSERT(flags == EVENT_FD_READ);
598                 done = sys_read(event->fd, &((char *)event->data)[event->done],
599                                 todo);
600
601                 if (done <= 0) {
602                         event->flags = 0;
603                         event->finished(event->private_data, False);
604                         return;
605                 }
606         }
607
608         event->done += done;
609
610         if (event->done == event->length) {
611                 event->flags = 0;
612                 event->finished(event->private_data, True);
613         }
614 }
615
616 /*
617  * Request an async read/write on a winbindd_fd_event structure. (*finished) is called
618  * when the request is completed or an error had occurred.
619  */
620
621 void setup_async_read(struct winbindd_fd_event *event, void *data, size_t length,
622                       void (*finished)(void *private_data, bool success),
623                       void *private_data)
624 {
625         SMB_ASSERT(event->flags == 0);
626         event->data = data;
627         event->length = length;
628         event->done = 0;
629         event->handler = rw_callback;
630         event->finished = finished;
631         event->private_data = private_data;
632         event->flags = EVENT_FD_READ;
633 }
634
635 void setup_async_write(struct winbindd_fd_event *event, void *data, size_t length,
636                        void (*finished)(void *private_data, bool success),
637                        void *private_data)
638 {
639         SMB_ASSERT(event->flags == 0);
640         event->data = data;
641         event->length = length;
642         event->done = 0;
643         event->handler = rw_callback;
644         event->finished = finished;
645         event->private_data = private_data;
646         event->flags = EVENT_FD_WRITE;
647 }
648
649 /*
650  * This is the main event loop of winbind requests. It goes through a
651  * state-machine of 3 read/write requests, 4 if you have extra data to send.
652  *
653  * An idle winbind client has a read request of 4 bytes outstanding,
654  * finalizing function is request_len_recv, checking the length. request_recv
655  * then processes the packet. The processing function then at some point has
656  * to call request_finished which schedules sending the response.
657  */
658
659 static void request_len_recv(void *private_data, bool success);
660 static void request_recv(void *private_data, bool success);
661 static void request_main_recv(void *private_data, bool success);
662 static void request_finished(struct winbindd_cli_state *state);
663 static void response_main_sent(void *private_data, bool success);
664 static void response_extra_sent(void *private_data, bool success);
665
666 static void response_extra_sent(void *private_data, bool success)
667 {
668         struct winbindd_cli_state *state =
669                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
670
671         TALLOC_FREE(state->mem_ctx);
672
673         if (!success) {
674                 state->finished = True;
675                 return;
676         }
677
678         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
679                          request_len_recv, state);
680 }
681
682 static void response_main_sent(void *private_data, bool success)
683 {
684         struct winbindd_cli_state *state =
685                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
686
687         if (!success) {
688                 state->finished = True;
689                 return;
690         }
691
692         if (state->response.length == sizeof(state->response)) {
693                 TALLOC_FREE(state->mem_ctx);
694
695                 setup_async_read(&state->fd_event, &state->request,
696                                  sizeof(uint32), request_len_recv, state);
697                 return;
698         }
699
700         setup_async_write(&state->fd_event, state->response.extra_data.data,
701                           state->response.length - sizeof(state->response),
702                           response_extra_sent, state);
703 }
704
705 static void request_finished(struct winbindd_cli_state *state)
706 {
707         /* Make sure request.extra_data is freed when finish processing a request */
708         SAFE_FREE(state->request.extra_data.data);
709         setup_async_write(&state->fd_event, &state->response,
710                           sizeof(state->response), response_main_sent, state);
711 }
712
713 void request_error(struct winbindd_cli_state *state)
714 {
715         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
716         state->response.result = WINBINDD_ERROR;
717         request_finished(state);
718 }
719
720 void request_ok(struct winbindd_cli_state *state)
721 {
722         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
723         state->response.result = WINBINDD_OK;
724         request_finished(state);
725 }
726
727 static void request_len_recv(void *private_data, bool success)
728 {
729         struct winbindd_cli_state *state =
730                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
731
732         if (!success) {
733                 state->finished = True;
734                 return;
735         }
736
737         if (*(uint32 *)(void *)(&state->request) != sizeof(state->request)) {
738                 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
739                          *(uint32_t *)(void *)(&state->request),
740                          (uint32_t)sizeof(state->request)));
741                 state->finished = True;
742                 return;
743         }
744
745         setup_async_read(&state->fd_event,
746                          (uint32 *)(void *)(&state->request)+1,
747                          sizeof(state->request) - sizeof(uint32),
748                          request_main_recv, state);
749 }
750
751 static void request_main_recv(void *private_data, bool success)
752 {
753         struct winbindd_cli_state *state =
754                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
755
756         if (!success) {
757                 state->finished = True;
758                 return;
759         }
760
761         if (state->request.extra_len == 0) {
762                 state->request.extra_data.data = NULL;
763                 request_recv(state, True);
764                 return;
765         }
766
767         if ((!state->privileged) &&
768             (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
769                 DEBUG(3, ("Got request with %d bytes extra data on "
770                           "unprivileged socket\n", (int)state->request.extra_len));
771                 state->request.extra_data.data = NULL;
772                 state->finished = True;
773                 return;
774         }
775
776         state->request.extra_data.data =
777                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
778
779         if (state->request.extra_data.data == NULL) {
780                 DEBUG(0, ("malloc failed\n"));
781                 state->finished = True;
782                 return;
783         }
784
785         /* Ensure null termination */
786         state->request.extra_data.data[state->request.extra_len] = '\0';
787
788         setup_async_read(&state->fd_event, state->request.extra_data.data,
789                          state->request.extra_len, request_recv, state);
790 }
791
792 static void request_recv(void *private_data, bool success)
793 {
794         struct winbindd_cli_state *state =
795                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
796
797         if (!success) {
798                 state->finished = True;
799                 return;
800         }
801
802         process_request(state);
803 }
804
805 /* Process a new connection by adding it to the client connection list */
806
807 static void new_connection(int listen_sock, bool privileged)
808 {
809         struct sockaddr_un sunaddr;
810         struct winbindd_cli_state *state;
811         socklen_t len;
812         int sock;
813
814         /* Accept connection */
815
816         len = sizeof(sunaddr);
817
818         do {
819                 sock = accept(listen_sock, (struct sockaddr *)(void *)&sunaddr,
820                               &len);
821         } while (sock == -1 && errno == EINTR);
822
823         if (sock == -1)
824                 return;
825
826         DEBUG(6,("accepted socket %d\n", sock));
827
828         /* Create new connection structure */
829
830         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
831                 close(sock);
832                 return;
833         }
834
835         state->sock = sock;
836
837         state->last_access = time(NULL);        
838
839         state->privileged = privileged;
840
841         state->fd_event.fd = state->sock;
842         state->fd_event.flags = 0;
843         add_fd_event(&state->fd_event);
844
845         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
846                          request_len_recv, state);
847
848         /* Add to connection list */
849
850         winbindd_add_client(state);
851 }
852
853 /* Remove a client connection from client connection list */
854
855 static void remove_client(struct winbindd_cli_state *state)
856 {
857         char c = 0;
858         int nwritten;
859
860         /* It's a dead client - hold a funeral */
861
862         if (state == NULL) {
863                 return;
864         }
865
866         /* tell client, we are closing ... */
867         nwritten = write(state->sock, &c, sizeof(c));
868         if (nwritten == -1) {
869                 /* 
870                  * ignore EPIPE error here, because the other end might
871                  * have already closed the socket.
872                  */
873                 if (errno != EPIPE) {
874                         DEBUG(2, ("final write to client failed: %s\n",
875                                 strerror(errno)));
876                 }
877         }
878
879         /* Close socket */
880
881         close(state->sock);
882
883         /* Free any getent state */
884
885         free_getent_state(state->getpwent_state);
886         free_getent_state(state->getgrent_state);
887
888         TALLOC_FREE(state->mem_ctx);
889
890         remove_fd_event(&state->fd_event);
891
892         /* Remove from list and free */
893
894         winbindd_remove_client(state);
895         TALLOC_FREE(state);
896 }
897
898 /* Shutdown client connection which has been idle for the longest time */
899
900 static bool remove_idle_client(void)
901 {
902         struct winbindd_cli_state *state, *remove_state = NULL;
903         time_t last_access = 0;
904         int nidle = 0;
905
906         for (state = winbindd_client_list(); state; state = state->next) {
907                 if (state->response.result != WINBINDD_PENDING &&
908                     state->fd_event.flags == EVENT_FD_READ &&
909                     !state->getpwent_state && !state->getgrent_state) {
910                         nidle++;
911                         if (!last_access || state->last_access < last_access) {
912                                 last_access = state->last_access;
913                                 remove_state = state;
914                         }
915                 }
916         }
917
918         if (remove_state) {
919                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
920                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
921                 remove_client(remove_state);
922                 return True;
923         }
924
925         return False;
926 }
927
928 struct winbindd_listen_state {
929         bool privileged;
930         int fd;
931         struct tevent_fd *fde;
932 };
933
934 static void winbindd_listen_fde_handler(struct tevent_context *ev,
935                                         struct tevent_fd *fde,
936                                         uint16_t flags,
937                                         void *private_data)
938 {
939         struct winbindd_listen_state *s = talloc_get_type_abort(private_data,
940                                           struct winbindd_listen_state);
941
942         while (winbindd_num_clients() >
943                WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
944                 DEBUG(5,("winbindd: Exceeding %d client "
945                          "connections, removing idle "
946                          "connection.\n",
947                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
948                 if (!remove_idle_client()) {
949                         DEBUG(0,("winbindd: Exceeding %d "
950                                  "client connections, no idle "
951                                  "connection found\n",
952                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
953                         break;
954                 }
955         }
956         new_connection(s->fd, s->privileged);
957 }
958
959 static bool winbindd_setup_listeners(void)
960 {
961         struct winbindd_listen_state *pub_state = NULL;
962         struct winbindd_listen_state *priv_state = NULL;
963
964         pub_state = talloc(winbind_event_context(),
965                            struct winbindd_listen_state);
966         if (!pub_state) {
967                 goto failed;
968         }
969
970         pub_state->privileged = false;
971         pub_state->fd = open_winbindd_socket();
972         if (pub_state->fd == -1) {
973                 goto failed;
974         }
975
976         pub_state->fde = tevent_add_fd(winbind_event_context(),
977                                        pub_state, pub_state->fd,
978                                        TEVENT_FD_READ,
979                                        winbindd_listen_fde_handler,
980                                        pub_state);
981         if (!pub_state->fde) {
982                 close(pub_state->fd);
983                 goto failed;
984         }
985         tevent_fd_set_auto_close(pub_state->fde);
986
987         priv_state = talloc(winbind_event_context(),
988                             struct winbindd_listen_state);
989         if (!priv_state) {
990                 goto failed;
991         }
992
993         priv_state->privileged = true;
994         priv_state->fd = open_winbindd_priv_socket();
995         if (priv_state->fd == -1) {
996                 goto failed;
997         }
998
999         priv_state->fde = tevent_add_fd(winbind_event_context(),
1000                                         priv_state, priv_state->fd,
1001                                         TEVENT_FD_READ,
1002                                         winbindd_listen_fde_handler,
1003                                         priv_state);
1004         if (!priv_state->fde) {
1005                 close(priv_state->fd);
1006                 goto failed;
1007         }
1008         tevent_fd_set_auto_close(priv_state->fde);
1009
1010         return true;
1011 failed:
1012         TALLOC_FREE(pub_state);
1013         TALLOC_FREE(priv_state);
1014         return false;
1015 }
1016
1017 /* Process incoming clients on listen_sock.  We use a tricky non-blocking,
1018    non-forking, non-threaded model which allows us to handle many
1019    simultaneous connections while remaining impervious to many denial of
1020    service attacks. */
1021
1022 static void process_loop(void)
1023 {
1024         struct winbindd_fd_event *ev;
1025         fd_set r_fds, w_fds;
1026         int maxfd = 0, selret;
1027         struct timeval timeout, ev_timeout;
1028
1029         run_events(winbind_event_context(), 0, NULL, NULL);
1030
1031         /* Initialise fd lists for select() */
1032
1033         FD_ZERO(&r_fds);
1034         FD_ZERO(&w_fds);
1035
1036         timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
1037         timeout.tv_usec = 0;
1038
1039         /* Check for any event timeouts. */
1040         {
1041                 struct timeval now;
1042                 GetTimeOfDay(&now);
1043
1044                 event_add_to_select_args(winbind_event_context(), &now,
1045                                          &r_fds, &w_fds, &ev_timeout, &maxfd);
1046         }
1047         if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
1048                 timeout = timeval_min(&timeout, &ev_timeout);
1049         }
1050
1051         for (ev = fd_events; ev; ev = ev->next) {
1052                 if (ev->flags & EVENT_FD_READ) {
1053                         FD_SET(ev->fd, &r_fds);
1054                         maxfd = MAX(ev->fd, maxfd);
1055                 }
1056                 if (ev->flags & EVENT_FD_WRITE) {
1057                         FD_SET(ev->fd, &w_fds);
1058                         maxfd = MAX(ev->fd, maxfd);
1059                 }
1060         }
1061
1062         /* Call select */
1063
1064         selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
1065
1066         if (selret == 0) {
1067                 goto no_fds_ready;
1068         }
1069
1070         if (selret == -1) {
1071                 if (errno == EINTR) {
1072                         goto no_fds_ready;
1073                 }
1074
1075                 /* Select error, something is badly wrong */
1076
1077                 perror("select");
1078                 exit(1);
1079         }
1080
1081         /* selret > 0 */
1082
1083         run_events(winbind_event_context(), selret, &r_fds, &w_fds);
1084
1085         ev = fd_events;
1086         while (ev != NULL) {
1087                 struct winbindd_fd_event *next = ev->next;
1088                 int flags = 0;
1089                 if (FD_ISSET(ev->fd, &r_fds))
1090                         flags |= EVENT_FD_READ;
1091                 if (FD_ISSET(ev->fd, &w_fds))
1092                         flags |= EVENT_FD_WRITE;
1093                 if (flags)
1094                         ev->handler(ev, flags);
1095                 ev = next;
1096         }
1097
1098         return;
1099
1100  no_fds_ready:
1101
1102         run_events(winbind_event_context(), selret, &r_fds, &w_fds);
1103
1104 #if 0
1105         winbindd_check_cache_size(time(NULL));
1106 #endif
1107 }
1108
1109 bool winbindd_use_idmap_cache(void)
1110 {
1111         return !opt_nocache;
1112 }
1113
1114 bool winbindd_use_cache(void)
1115 {
1116         return !opt_nocache;
1117 }
1118
1119 /* Main function */
1120
1121 int main(int argc, char **argv, char **envp)
1122 {
1123         static bool is_daemon = False;
1124         static bool Fork = True;
1125         static bool log_stdout = False;
1126         static bool no_process_group = False;
1127         enum {
1128                 OPT_DAEMON = 1000,
1129                 OPT_FORK,
1130                 OPT_NO_PROCESS_GROUP,
1131                 OPT_LOG_STDOUT
1132         };
1133         struct poptOption long_options[] = {
1134                 POPT_AUTOHELP
1135                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1136                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1137                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1138                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1139                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1140                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1141                 POPT_COMMON_SAMBA
1142                 POPT_TABLEEND
1143         };
1144         poptContext pc;
1145         int opt;
1146         TALLOC_CTX *frame = talloc_stackframe();
1147
1148         /* glibc (?) likes to print "User defined signal 1" and exit if a
1149            SIGUSR[12] is received before a handler is installed */
1150
1151         CatchSignal(SIGUSR1, SIG_IGN);
1152         CatchSignal(SIGUSR2, SIG_IGN);
1153
1154         fault_setup((void (*)(void *))fault_quit );
1155         dump_core_setup("winbindd");
1156
1157         load_case_tables();
1158
1159         /* Initialise for running in non-root mode */
1160
1161         sec_init();
1162
1163         set_remote_machine_name("winbindd", False);
1164
1165         /* Set environment variable so we don't recursively call ourselves.
1166            This may also be useful interactively. */
1167
1168         if ( !winbind_off() ) {
1169                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1170                 exit(1);
1171         }
1172
1173         /* Initialise samba/rpc client stuff */
1174
1175         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1176
1177         while ((opt = poptGetNextOpt(pc)) != -1) {
1178                 switch (opt) {
1179                         /* Don't become a daemon */
1180                 case OPT_DAEMON:
1181                         is_daemon = True;
1182                         break;
1183                 case 'i':
1184                         interactive = True;
1185                         log_stdout = True;
1186                         Fork = False;
1187                         break;
1188                 case OPT_FORK:
1189                         Fork = false;
1190                         break;
1191                 case OPT_NO_PROCESS_GROUP:
1192                         no_process_group = true;
1193                         break;
1194                 case OPT_LOG_STDOUT:
1195                         log_stdout = true;
1196                         break;
1197                 case 'n':
1198                         opt_nocache = true;
1199                         break;
1200                 default:
1201                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1202                                   poptBadOption(pc, 0), poptStrerror(opt));
1203                         poptPrintUsage(pc, stderr, 0);
1204                         exit(1);
1205                 }
1206         }
1207
1208         if (is_daemon && interactive) {
1209                 d_fprintf(stderr,"\nERROR: "
1210                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1211                 poptPrintUsage(pc, stderr, 0);
1212                 exit(1);
1213         }
1214
1215         if (log_stdout && Fork) {
1216                 d_fprintf(stderr, "\nERROR: "
1217                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1218                 poptPrintUsage(pc, stderr, 0);
1219                 exit(1);
1220         }
1221
1222         poptFreeContext(pc);
1223
1224         if (!override_logfile) {
1225                 char *lfile = NULL;
1226                 if (asprintf(&lfile,"%s/log.winbindd",
1227                                 get_dyn_LOGFILEBASE()) > 0) {
1228                         lp_set_logfile(lfile);
1229                         SAFE_FREE(lfile);
1230                 }
1231         }
1232         setup_logging("winbindd", log_stdout);
1233         reopen_logs();
1234
1235         DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1236         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1237
1238         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1239                 DEBUG(0, ("error opening config file\n"));
1240                 exit(1);
1241         }
1242
1243         /* Initialise messaging system */
1244
1245         if (winbind_messaging_context() == NULL) {
1246                 exit(1);
1247         }
1248
1249         if (!reload_services_file(NULL)) {
1250                 DEBUG(0, ("error opening config file\n"));
1251                 exit(1);
1252         }
1253
1254         if (!directory_exist(lp_lockdir())) {
1255                 mkdir(lp_lockdir(), 0755);
1256         }
1257
1258         /* Setup names. */
1259
1260         if (!init_names())
1261                 exit(1);
1262
1263         load_interfaces();
1264
1265         if (!secrets_init()) {
1266
1267                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1268                 return False;
1269         }
1270
1271         /* Enable netbios namecache */
1272
1273         namecache_enable();
1274
1275         /* Unblock all signals we are interested in as they may have been
1276            blocked by the parent process. */
1277
1278         BlockSignals(False, SIGINT);
1279         BlockSignals(False, SIGQUIT);
1280         BlockSignals(False, SIGTERM);
1281         BlockSignals(False, SIGUSR1);
1282         BlockSignals(False, SIGUSR2);
1283         BlockSignals(False, SIGHUP);
1284         BlockSignals(False, SIGCHLD);
1285
1286         if (!interactive)
1287                 become_daemon(Fork, no_process_group);
1288
1289         pidfile_create("winbindd");
1290
1291 #if HAVE_SETPGID
1292         /*
1293          * If we're interactive we want to set our own process group for
1294          * signal management.
1295          */
1296         if (interactive && !no_process_group)
1297                 setpgid( (pid_t)0, (pid_t)0);
1298 #endif
1299
1300         TimeInit();
1301
1302         /* Don't use winbindd_reinit_after_fork here as
1303          * we're just starting up and haven't created any
1304          * winbindd-specific resources we must free yet. JRA.
1305          */
1306
1307         if (!reinit_after_fork(winbind_messaging_context(),
1308                                winbind_event_context(), false)) {
1309                 DEBUG(0,("reinit_after_fork() failed\n"));
1310                 exit(1);
1311         }
1312
1313         /* Setup signal handlers */
1314
1315         if (!winbindd_setup_sig_term_handler(true))
1316                 exit(1);
1317         if (!winbindd_setup_sig_hup_handler(NULL))
1318                 exit(1);
1319         if (!winbindd_setup_sig_chld_handler())
1320                 exit(1);
1321         if (!winbindd_setup_sig_usr2_handler())
1322                 exit(1);
1323
1324         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1325
1326         /*
1327          * Ensure all cache and idmap caches are consistent
1328          * and initialized before we startup.
1329          */
1330         if (!winbindd_cache_validate_and_initialize()) {
1331                 exit(1);
1332         }
1333
1334         /* get broadcast messages */
1335         claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP);
1336
1337         /* React on 'smbcontrol winbindd reload-config' in the same way
1338            as to SIGHUP signal */
1339         messaging_register(winbind_messaging_context(), NULL,
1340                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1341         messaging_register(winbind_messaging_context(), NULL,
1342                            MSG_SHUTDOWN, msg_shutdown);
1343
1344         /* Handle online/offline messages. */
1345         messaging_register(winbind_messaging_context(), NULL,
1346                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1347         messaging_register(winbind_messaging_context(), NULL,
1348                            MSG_WINBIND_ONLINE, winbind_msg_online);
1349         messaging_register(winbind_messaging_context(), NULL,
1350                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1351
1352         messaging_register(winbind_messaging_context(), NULL,
1353                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1354
1355         messaging_register(winbind_messaging_context(), NULL,
1356                            MSG_WINBIND_VALIDATE_CACHE,
1357                            winbind_msg_validate_cache);
1358
1359         messaging_register(winbind_messaging_context(), NULL,
1360                            MSG_WINBIND_DUMP_DOMAIN_LIST,
1361                            winbind_msg_dump_domain_list);
1362
1363         /* Register handler for MSG_DEBUG. */
1364         messaging_register(winbind_messaging_context(), NULL,
1365                            MSG_DEBUG,
1366                            winbind_msg_debug);
1367
1368         netsamlogon_cache_init(); /* Non-critical */
1369
1370         /* clear the cached list of trusted domains */
1371
1372         wcache_tdc_clear();     
1373
1374         if (!init_domain_list()) {
1375                 DEBUG(0,("unable to initialize domain list\n"));
1376                 exit(1);
1377         }
1378
1379         init_idmap_child();
1380         init_locator_child();
1381
1382         smb_nscd_flush_user_cache();
1383         smb_nscd_flush_group_cache();
1384
1385         /* setup listen sockets */
1386
1387         if (!winbindd_setup_listeners()) {
1388                 DEBUG(0,("winbindd_setup_listeners() failed\n"));
1389                 exit(1);
1390         }
1391
1392         TALLOC_FREE(frame);
1393         /* Loop waiting for requests */
1394         while (1) {
1395                 struct winbindd_cli_state *state;
1396
1397                 frame = talloc_stackframe();
1398
1399                 /* refresh the trusted domain cache */
1400
1401                 rescan_trusted_domains();
1402
1403                 /* Dispose of client connection if it is marked as
1404                    finished */
1405                 state = winbindd_client_list();
1406                 while (state) {
1407                         struct winbindd_cli_state *next = state->next;
1408
1409                         if (state->finished) {
1410                                 remove_client(state);
1411                         }
1412
1413                         state = next;
1414                 }
1415
1416                 process_loop();
1417
1418                 TALLOC_FREE(frame);
1419         }
1420
1421         return 0;
1422 }