s3: Implement wbcGetSidAliases
[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 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                                SIGCHLD, 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", 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         /* Free response data - we may be interrupted and receive another
512            command before being able to send this data off. */
513
514         SAFE_FREE(state->response.extra_data.data);  
515
516         ZERO_STRUCT(state->response);
517
518         state->response.result = WINBINDD_PENDING;
519         state->response.length = sizeof(struct winbindd_response);
520
521         state->mem_ctx = talloc_init("winbind request");
522         if (state->mem_ctx == NULL)
523                 return;
524
525         /* Remember who asked us. */
526         state->pid = state->request.pid;
527
528         /* Process command */
529
530         for (table = dispatch_table; table->fn; table++) {
531                 if (state->request.cmd == table->cmd) {
532                         DEBUG(10,("process_request: request fn %s\n",
533                                   table->winbindd_cmd_name ));
534                         table->fn(state);
535                         break;
536                 }
537         }
538
539         if (!table->fn) {
540                 DEBUG(10,("process_request: unknown request fn number %d\n",
541                           (int)state->request.cmd ));
542                 request_error(state);
543         }
544 }
545
546 /*
547  * A list of file descriptors being monitored by select in the main processing
548  * loop. winbindd_fd_event->handler is called whenever the socket is readable/writable.
549  */
550
551 static struct winbindd_fd_event *fd_events = NULL;
552
553 void add_fd_event(struct winbindd_fd_event *ev)
554 {
555         struct winbindd_fd_event *match;
556
557         /* only add unique winbindd_fd_event structs */
558
559         for (match=fd_events; match; match=match->next ) {
560 #ifdef DEVELOPER
561                 SMB_ASSERT( match != ev );
562 #else
563                 if ( match == ev )
564                         return;
565 #endif
566         }
567
568         DLIST_ADD(fd_events, ev);
569 }
570
571 void remove_fd_event(struct winbindd_fd_event *ev)
572 {
573         DLIST_REMOVE(fd_events, ev);
574 }
575
576 /*
577  * Handler for winbindd_fd_events to complete a read/write request, set up by
578  * setup_async_read/setup_async_write.
579  */
580
581 static void rw_callback(struct winbindd_fd_event *event, int flags)
582 {
583         size_t todo;
584         ssize_t done = 0;
585
586         todo = event->length - event->done;
587
588         if (event->flags & EVENT_FD_WRITE) {
589                 SMB_ASSERT(flags == EVENT_FD_WRITE);
590                 done = sys_write(event->fd,
591                                  &((char *)event->data)[event->done],
592                                  todo);
593
594                 if (done <= 0) {
595                         event->flags = 0;
596                         event->finished(event->private_data, False);
597                         return;
598                 }
599         }
600
601         if (event->flags & EVENT_FD_READ) {
602                 SMB_ASSERT(flags == EVENT_FD_READ);
603                 done = sys_read(event->fd, &((char *)event->data)[event->done],
604                                 todo);
605
606                 if (done <= 0) {
607                         event->flags = 0;
608                         event->finished(event->private_data, False);
609                         return;
610                 }
611         }
612
613         event->done += done;
614
615         if (event->done == event->length) {
616                 event->flags = 0;
617                 event->finished(event->private_data, True);
618         }
619 }
620
621 /*
622  * Request an async read/write on a winbindd_fd_event structure. (*finished) is called
623  * when the request is completed or an error had occurred.
624  */
625
626 void setup_async_read(struct winbindd_fd_event *event, void *data, size_t length,
627                       void (*finished)(void *private_data, bool success),
628                       void *private_data)
629 {
630         SMB_ASSERT(event->flags == 0);
631         event->data = data;
632         event->length = length;
633         event->done = 0;
634         event->handler = rw_callback;
635         event->finished = finished;
636         event->private_data = private_data;
637         event->flags = EVENT_FD_READ;
638 }
639
640 void setup_async_write(struct winbindd_fd_event *event, void *data, size_t length,
641                        void (*finished)(void *private_data, bool success),
642                        void *private_data)
643 {
644         SMB_ASSERT(event->flags == 0);
645         event->data = data;
646         event->length = length;
647         event->done = 0;
648         event->handler = rw_callback;
649         event->finished = finished;
650         event->private_data = private_data;
651         event->flags = EVENT_FD_WRITE;
652 }
653
654 /*
655  * This is the main event loop of winbind requests. It goes through a
656  * state-machine of 3 read/write requests, 4 if you have extra data to send.
657  *
658  * An idle winbind client has a read request of 4 bytes outstanding,
659  * finalizing function is request_len_recv, checking the length. request_recv
660  * then processes the packet. The processing function then at some point has
661  * to call request_finished which schedules sending the response.
662  */
663
664 static void request_len_recv(void *private_data, bool success);
665 static void request_recv(void *private_data, bool success);
666 static void request_main_recv(void *private_data, bool success);
667 static void request_finished(struct winbindd_cli_state *state);
668 static void response_main_sent(void *private_data, bool success);
669 static void response_extra_sent(void *private_data, bool success);
670
671 static void response_extra_sent(void *private_data, bool success)
672 {
673         struct winbindd_cli_state *state =
674                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
675
676         TALLOC_FREE(state->mem_ctx);
677
678         if (!success) {
679                 state->finished = True;
680                 return;
681         }
682
683         SAFE_FREE(state->response.extra_data.data);
684
685         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
686                          request_len_recv, state);
687 }
688
689 static void response_main_sent(void *private_data, bool success)
690 {
691         struct winbindd_cli_state *state =
692                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
693
694         if (!success) {
695                 state->finished = True;
696                 return;
697         }
698
699         if (state->response.length == sizeof(state->response)) {
700                 TALLOC_FREE(state->mem_ctx);
701
702                 setup_async_read(&state->fd_event, &state->request,
703                                  sizeof(uint32), request_len_recv, state);
704                 return;
705         }
706
707         setup_async_write(&state->fd_event, state->response.extra_data.data,
708                           state->response.length - sizeof(state->response),
709                           response_extra_sent, state);
710 }
711
712 static void request_finished(struct winbindd_cli_state *state)
713 {
714         /* Make sure request.extra_data is freed when finish processing a request */
715         SAFE_FREE(state->request.extra_data.data);
716         setup_async_write(&state->fd_event, &state->response,
717                           sizeof(state->response), response_main_sent, state);
718 }
719
720 void request_error(struct winbindd_cli_state *state)
721 {
722         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
723         state->response.result = WINBINDD_ERROR;
724         request_finished(state);
725 }
726
727 void request_ok(struct winbindd_cli_state *state)
728 {
729         SMB_ASSERT(state->response.result == WINBINDD_PENDING);
730         state->response.result = WINBINDD_OK;
731         request_finished(state);
732 }
733
734 static void request_len_recv(void *private_data, bool success)
735 {
736         struct winbindd_cli_state *state =
737                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
738
739         if (!success) {
740                 state->finished = True;
741                 return;
742         }
743
744         if (*(uint32 *)(&state->request) != sizeof(state->request)) {
745                 DEBUG(0,("request_len_recv: Invalid request size received: %d (expected %u)\n",
746                          *(uint32_t *)(&state->request), (uint32_t)sizeof(state->request)));
747                 state->finished = True;
748                 return;
749         }
750
751         setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
752                          sizeof(state->request) - sizeof(uint32),
753                          request_main_recv, state);
754 }
755
756 static void request_main_recv(void *private_data, bool success)
757 {
758         struct winbindd_cli_state *state =
759                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
760
761         if (!success) {
762                 state->finished = True;
763                 return;
764         }
765
766         if (state->request.extra_len == 0) {
767                 state->request.extra_data.data = NULL;
768                 request_recv(state, True);
769                 return;
770         }
771
772         if ((!state->privileged) &&
773             (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
774                 DEBUG(3, ("Got request with %d bytes extra data on "
775                           "unprivileged socket\n", (int)state->request.extra_len));
776                 state->request.extra_data.data = NULL;
777                 state->finished = True;
778                 return;
779         }
780
781         state->request.extra_data.data =
782                 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
783
784         if (state->request.extra_data.data == NULL) {
785                 DEBUG(0, ("malloc failed\n"));
786                 state->finished = True;
787                 return;
788         }
789
790         /* Ensure null termination */
791         state->request.extra_data.data[state->request.extra_len] = '\0';
792
793         setup_async_read(&state->fd_event, state->request.extra_data.data,
794                          state->request.extra_len, request_recv, state);
795 }
796
797 static void request_recv(void *private_data, bool success)
798 {
799         struct winbindd_cli_state *state =
800                 talloc_get_type_abort(private_data, struct winbindd_cli_state);
801
802         if (!success) {
803                 state->finished = True;
804                 return;
805         }
806
807         process_request(state);
808 }
809
810 /* Process a new connection by adding it to the client connection list */
811
812 static void new_connection(int listen_sock, bool privileged)
813 {
814         struct sockaddr_un sunaddr;
815         struct winbindd_cli_state *state;
816         socklen_t len;
817         int sock;
818
819         /* Accept connection */
820
821         len = sizeof(sunaddr);
822
823         do {
824                 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
825         } while (sock == -1 && errno == EINTR);
826
827         if (sock == -1)
828                 return;
829
830         DEBUG(6,("accepted socket %d\n", sock));
831
832         /* Create new connection structure */
833
834         if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
835                 close(sock);
836                 return;
837         }
838
839         state->sock = sock;
840
841         state->last_access = time(NULL);        
842
843         state->privileged = privileged;
844
845         state->fd_event.fd = state->sock;
846         state->fd_event.flags = 0;
847         add_fd_event(&state->fd_event);
848
849         setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
850                          request_len_recv, state);
851
852         /* Add to connection list */
853
854         winbindd_add_client(state);
855 }
856
857 /* Remove a client connection from client connection list */
858
859 static void remove_client(struct winbindd_cli_state *state)
860 {
861         char c = 0;
862         int nwritten;
863
864         /* It's a dead client - hold a funeral */
865
866         if (state == NULL) {
867                 return;
868         }
869
870         /* tell client, we are closing ... */
871         nwritten = write(state->sock, &c, sizeof(c));
872         if (nwritten == -1) {
873                 DEBUG(2, ("final write to client failed: %s\n",
874                           strerror(errno)));
875         }
876
877         /* Close socket */
878
879         close(state->sock);
880
881         /* Free any getent state */
882
883         free_getent_state(state->getpwent_state);
884         free_getent_state(state->getgrent_state);
885
886         /* We may have some extra data that was not freed if the client was
887            killed unexpectedly */
888
889         SAFE_FREE(state->response.extra_data.data);
890
891         TALLOC_FREE(state->mem_ctx);
892
893         remove_fd_event(&state->fd_event);
894
895         /* Remove from list and free */
896
897         winbindd_remove_client(state);
898         TALLOC_FREE(state);
899 }
900
901 /* Shutdown client connection which has been idle for the longest time */
902
903 static bool remove_idle_client(void)
904 {
905         struct winbindd_cli_state *state, *remove_state = NULL;
906         time_t last_access = 0;
907         int nidle = 0;
908
909         for (state = winbindd_client_list(); state; state = state->next) {
910                 if (state->response.result != WINBINDD_PENDING &&
911                     !state->getpwent_state && !state->getgrent_state) {
912                         nidle++;
913                         if (!last_access || state->last_access < last_access) {
914                                 last_access = state->last_access;
915                                 remove_state = state;
916                         }
917                 }
918         }
919
920         if (remove_state) {
921                 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
922                         nidle, remove_state->sock, (unsigned int)remove_state->pid));
923                 remove_client(remove_state);
924                 return True;
925         }
926
927         return False;
928 }
929
930 /* Process incoming clients on listen_sock.  We use a tricky non-blocking,
931    non-forking, non-threaded model which allows us to handle many
932    simultaneous connections while remaining impervious to many denial of
933    service attacks. */
934
935 static void process_loop(void)
936 {
937         struct winbindd_cli_state *state;
938         struct winbindd_fd_event *ev;
939         fd_set r_fds, w_fds;
940         int maxfd, listen_sock, listen_priv_sock, selret;
941         struct timeval timeout, ev_timeout;
942
943         /* Open Sockets here to get stuff going ASAP */
944         listen_sock = open_winbindd_socket();
945         listen_priv_sock = open_winbindd_priv_socket();
946
947         if (listen_sock == -1 || listen_priv_sock == -1) {
948                 perror("open_winbind_socket");
949                 exit(1);
950         }
951
952         run_events(winbind_event_context(), 0, NULL, NULL);
953
954         /* refresh the trusted domain cache */
955
956         rescan_trusted_domains();
957
958         /* Initialise fd lists for select() */
959
960         maxfd = MAX(listen_sock, listen_priv_sock);
961
962         FD_ZERO(&r_fds);
963         FD_ZERO(&w_fds);
964         FD_SET(listen_sock, &r_fds);
965         FD_SET(listen_priv_sock, &r_fds);
966
967         timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
968         timeout.tv_usec = 0;
969
970         /* Check for any event timeouts. */
971         {
972                 struct timeval now;
973                 GetTimeOfDay(&now);
974
975                 event_add_to_select_args(winbind_event_context(), &now,
976                                          &r_fds, &w_fds, &ev_timeout, &maxfd);
977         }
978         if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
979                 timeout = timeval_min(&timeout, &ev_timeout);
980         }
981
982         /* Set up client readers and writers */
983
984         state = winbindd_client_list();
985
986         while (state) {
987
988                 struct winbindd_cli_state *next = state->next;
989
990                 /* Dispose of client connection if it is marked as 
991                    finished */ 
992
993                 if (state->finished)
994                         remove_client(state);
995
996                 state = next;
997         }
998
999         for (ev = fd_events; ev; ev = ev->next) {
1000                 if (ev->flags & EVENT_FD_READ) {
1001                         FD_SET(ev->fd, &r_fds);
1002                         maxfd = MAX(ev->fd, maxfd);
1003                 }
1004                 if (ev->flags & EVENT_FD_WRITE) {
1005                         FD_SET(ev->fd, &w_fds);
1006                         maxfd = MAX(ev->fd, maxfd);
1007                 }
1008         }
1009
1010         /* Call select */
1011
1012         selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
1013
1014         if (selret == 0) {
1015                 goto no_fds_ready;
1016         }
1017
1018         if (selret == -1) {
1019                 if (errno == EINTR) {
1020                         goto no_fds_ready;
1021                 }
1022
1023                 /* Select error, something is badly wrong */
1024
1025                 perror("select");
1026                 exit(1);
1027         }
1028
1029         /* selret > 0 */
1030
1031         run_events(winbind_event_context(), selret, &r_fds, &w_fds);
1032
1033         ev = fd_events;
1034         while (ev != NULL) {
1035                 struct winbindd_fd_event *next = ev->next;
1036                 int flags = 0;
1037                 if (FD_ISSET(ev->fd, &r_fds))
1038                         flags |= EVENT_FD_READ;
1039                 if (FD_ISSET(ev->fd, &w_fds))
1040                         flags |= EVENT_FD_WRITE;
1041                 if (flags)
1042                         ev->handler(ev, flags);
1043                 ev = next;
1044         }
1045
1046         if (FD_ISSET(listen_sock, &r_fds)) {
1047                 while (winbindd_num_clients() >
1048                        WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
1049                         DEBUG(5,("winbindd: Exceeding %d client "
1050                                  "connections, removing idle "
1051                                  "connection.\n",
1052                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
1053                         if (!remove_idle_client()) {
1054                                 DEBUG(0,("winbindd: Exceeding %d "
1055                                          "client connections, no idle "
1056                                          "connection found\n",
1057                                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
1058                                 break;
1059                         }
1060                 }
1061                 /* new, non-privileged connection */
1062                 new_connection(listen_sock, False);
1063         }
1064
1065         if (FD_ISSET(listen_priv_sock, &r_fds)) {
1066                 while (winbindd_num_clients() >
1067                        WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
1068                         DEBUG(5,("winbindd: Exceeding %d client "
1069                                  "connections, removing idle "
1070                                  "connection.\n",
1071                                  WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
1072                         if (!remove_idle_client()) {
1073                                 DEBUG(0,("winbindd: Exceeding %d "
1074                                          "client connections, no idle "
1075                                          "connection found\n",
1076                                          WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
1077                                 break;
1078                         }
1079                 }
1080                 /* new, privileged connection */
1081                 new_connection(listen_priv_sock, True);
1082         }
1083
1084  no_fds_ready:
1085
1086         run_events(winbind_event_context(), selret, &r_fds, &w_fds);
1087
1088 #if 0
1089         winbindd_check_cache_size(time(NULL));
1090 #endif
1091 }
1092
1093 /* Main function */
1094
1095 int main(int argc, char **argv, char **envp)
1096 {
1097         static bool is_daemon = False;
1098         static bool Fork = True;
1099         static bool log_stdout = False;
1100         static bool no_process_group = False;
1101         enum {
1102                 OPT_DAEMON = 1000,
1103                 OPT_FORK,
1104                 OPT_NO_PROCESS_GROUP,
1105                 OPT_LOG_STDOUT
1106         };
1107         struct poptOption long_options[] = {
1108                 POPT_AUTOHELP
1109                 { "stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
1110                 { "foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Daemon in foreground mode" },
1111                 { "no-process-group", 0, POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
1112                 { "daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
1113                 { "interactive", 'i', POPT_ARG_NONE, NULL, 'i', "Interactive mode" },
1114                 { "no-caching", 'n', POPT_ARG_NONE, NULL, 'n', "Disable caching" },
1115                 POPT_COMMON_SAMBA
1116                 POPT_TABLEEND
1117         };
1118         poptContext pc;
1119         int opt;
1120         TALLOC_CTX *frame = talloc_stackframe();
1121
1122         /* glibc (?) likes to print "User defined signal 1" and exit if a
1123            SIGUSR[12] is received before a handler is installed */
1124
1125         CatchSignal(SIGUSR1, SIG_IGN);
1126         CatchSignal(SIGUSR2, SIG_IGN);
1127
1128         fault_setup((void (*)(void *))fault_quit );
1129         dump_core_setup("winbindd");
1130
1131         load_case_tables();
1132
1133         /* Initialise for running in non-root mode */
1134
1135         sec_init();
1136
1137         set_remote_machine_name("winbindd", False);
1138
1139         /* Set environment variable so we don't recursively call ourselves.
1140            This may also be useful interactively. */
1141
1142         if ( !winbind_off() ) {
1143                 DEBUG(0,("Failed to disable recusive winbindd calls.  Exiting.\n"));
1144                 exit(1);
1145         }
1146
1147         /* Initialise samba/rpc client stuff */
1148
1149         pc = poptGetContext("winbindd", argc, (const char **)argv, long_options, 0);
1150
1151         while ((opt = poptGetNextOpt(pc)) != -1) {
1152                 switch (opt) {
1153                         /* Don't become a daemon */
1154                 case OPT_DAEMON:
1155                         is_daemon = True;
1156                         break;
1157                 case 'i':
1158                         interactive = True;
1159                         log_stdout = True;
1160                         Fork = False;
1161                         break;
1162                 case OPT_FORK:
1163                         Fork = false;
1164                         break;
1165                 case OPT_NO_PROCESS_GROUP:
1166                         no_process_group = true;
1167                         break;
1168                 case OPT_LOG_STDOUT:
1169                         log_stdout = true;
1170                         break;
1171                 case 'n':
1172                         opt_nocache = true;
1173                         break;
1174                 default:
1175                         d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
1176                                   poptBadOption(pc, 0), poptStrerror(opt));
1177                         poptPrintUsage(pc, stderr, 0);
1178                         exit(1);
1179                 }
1180         }
1181
1182         if (is_daemon && interactive) {
1183                 d_fprintf(stderr,"\nERROR: "
1184                           "Option -i|--interactive is not allowed together with -D|--daemon\n\n");
1185                 poptPrintUsage(pc, stderr, 0);
1186                 exit(1);
1187         }
1188
1189         if (log_stdout && Fork) {
1190                 d_fprintf(stderr, "\nERROR: "
1191                           "Can't log to stdout (-S) unless daemon is in foreground +(-F) or interactive (-i)\n\n");
1192                 poptPrintUsage(pc, stderr, 0);
1193                 exit(1);
1194         }
1195
1196         poptFreeContext(pc);
1197
1198         if (!override_logfile) {
1199                 char *lfile = NULL;
1200                 if (asprintf(&lfile,"%s/log.winbindd",
1201                                 get_dyn_LOGFILEBASE()) > 0) {
1202                         lp_set_logfile(lfile);
1203                         SAFE_FREE(lfile);
1204                 }
1205         }
1206         setup_logging("winbindd", log_stdout);
1207         reopen_logs();
1208
1209         DEBUG(0,("winbindd version %s started.\n", samba_version_string()));
1210         DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));
1211
1212         if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
1213                 DEBUG(0, ("error opening config file\n"));
1214                 exit(1);
1215         }
1216
1217         /* Initialise messaging system */
1218
1219         if (winbind_messaging_context() == NULL) {
1220                 exit(1);
1221         }
1222
1223         if (!reload_services_file(NULL)) {
1224                 DEBUG(0, ("error opening config file\n"));
1225                 exit(1);
1226         }
1227
1228         if (!directory_exist(lp_lockdir())) {
1229                 mkdir(lp_lockdir(), 0755);
1230         }
1231
1232         /* Setup names. */
1233
1234         if (!init_names())
1235                 exit(1);
1236
1237         load_interfaces();
1238
1239         if (!secrets_init()) {
1240
1241                 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1242                 return False;
1243         }
1244
1245         /* Enable netbios namecache */
1246
1247         namecache_enable();
1248
1249         /* Unblock all signals we are interested in as they may have been
1250            blocked by the parent process. */
1251
1252         BlockSignals(False, SIGINT);
1253         BlockSignals(False, SIGQUIT);
1254         BlockSignals(False, SIGTERM);
1255         BlockSignals(False, SIGUSR1);
1256         BlockSignals(False, SIGUSR2);
1257         BlockSignals(False, SIGHUP);
1258         BlockSignals(False, SIGCHLD);
1259
1260         if (!interactive)
1261                 become_daemon(Fork, no_process_group);
1262
1263         pidfile_create("winbindd");
1264
1265 #if HAVE_SETPGID
1266         /*
1267          * If we're interactive we want to set our own process group for
1268          * signal management.
1269          */
1270         if (interactive && !no_process_group)
1271                 setpgid( (pid_t)0, (pid_t)0);
1272 #endif
1273
1274         TimeInit();
1275
1276         /* Don't use winbindd_reinit_after_fork here as
1277          * we're just starting up and haven't created any
1278          * winbindd-specific resources we must free yet. JRA.
1279          */
1280
1281         if (!reinit_after_fork(winbind_messaging_context(),
1282                                winbind_event_context(), false)) {
1283                 DEBUG(0,("reinit_after_fork() failed\n"));
1284                 exit(1);
1285         }
1286
1287         /* Setup signal handlers */
1288
1289         if (!winbindd_setup_sig_term_handler(true))
1290                 exit(1);
1291         if (!winbindd_setup_sig_hup_handler(NULL))
1292                 exit(1);
1293         if (!winbindd_setup_sig_chld_handler())
1294                 exit(1);
1295         if (!winbindd_setup_sig_usr2_handler())
1296                 exit(1);
1297
1298         CatchSignal(SIGPIPE, SIG_IGN);                 /* Ignore sigpipe */
1299
1300         /*
1301          * Ensure all cache and idmap caches are consistent
1302          * and initialized before we startup.
1303          */
1304         if (!winbindd_cache_validate_and_initialize()) {
1305                 exit(1);
1306         }
1307
1308         /* get broadcast messages */
1309         claim_connection(NULL,"",FLAG_MSG_GENERAL|FLAG_MSG_DBWRAP);
1310
1311         /* React on 'smbcontrol winbindd reload-config' in the same way
1312            as to SIGHUP signal */
1313         messaging_register(winbind_messaging_context(), NULL,
1314                            MSG_SMB_CONF_UPDATED, msg_reload_services);
1315         messaging_register(winbind_messaging_context(), NULL,
1316                            MSG_SHUTDOWN, msg_shutdown);
1317
1318         /* Handle online/offline messages. */
1319         messaging_register(winbind_messaging_context(), NULL,
1320                            MSG_WINBIND_OFFLINE, winbind_msg_offline);
1321         messaging_register(winbind_messaging_context(), NULL,
1322                            MSG_WINBIND_ONLINE, winbind_msg_online);
1323         messaging_register(winbind_messaging_context(), NULL,
1324                            MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1325
1326         messaging_register(winbind_messaging_context(), NULL,
1327                            MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1328
1329         messaging_register(winbind_messaging_context(), NULL,
1330                            MSG_WINBIND_VALIDATE_CACHE,
1331                            winbind_msg_validate_cache);
1332
1333         messaging_register(winbind_messaging_context(), NULL,
1334                            MSG_WINBIND_DUMP_DOMAIN_LIST,
1335                            winbind_msg_dump_domain_list);
1336
1337         /* Register handler for MSG_DEBUG. */
1338         messaging_register(winbind_messaging_context(), NULL,
1339                            MSG_DEBUG,
1340                            winbind_msg_debug);
1341
1342         netsamlogon_cache_init(); /* Non-critical */
1343
1344         /* clear the cached list of trusted domains */
1345
1346         wcache_tdc_clear();     
1347
1348         if (!init_domain_list()) {
1349                 DEBUG(0,("unable to initialize domain list\n"));
1350                 exit(1);
1351         }
1352
1353         init_idmap_child();
1354         init_locator_child();
1355
1356         smb_nscd_flush_user_cache();
1357         smb_nscd_flush_group_cache();
1358
1359         /* Loop waiting for requests */
1360
1361         TALLOC_FREE(frame);
1362         while (1) {
1363                 frame = talloc_stackframe();
1364                 process_loop();
1365                 TALLOC_FREE(frame);
1366         }
1367
1368         return 0;
1369 }