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