r23348: Fix connection reporting on SIGUSR2 (noticed by
[Samba/nascimento.git] / source3 / nsswitch / winbindd.c
blob94a4b7f115c5dd954db637ae044d46707b00cc14
1 /*
2 Unix SMB/CIFS implementation.
4 Winbind daemon for ntdom nss module
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 Copyright (C) James Peach 2007
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 GNU General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
27 #include "includes.h"
28 #include "winbindd.h"
30 #undef DBGC_CLASS
31 #define DBGC_CLASS DBGC_WINBIND
33 BOOL opt_nocache = False;
35 extern BOOL override_logfile;
37 struct event_context *winbind_event_context(void)
39 static struct event_context *ctx;
41 if (!ctx && !(ctx = event_context_init(NULL))) {
42 smb_panic("Could not init winbind event context\n");
44 return ctx;
47 struct messaging_context *winbind_messaging_context(void)
49 static struct messaging_context *ctx;
51 if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
52 winbind_event_context()))) {
53 smb_panic("Could not init winbind messaging context\n");
55 return ctx;
58 /* Reload configuration */
60 static BOOL reload_services_file(void)
62 BOOL ret;
64 if (lp_loaded()) {
65 pstring fname;
67 pstrcpy(fname,lp_configfile());
68 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
69 pstrcpy(dyn_CONFIGFILE,fname);
73 reopen_logs();
74 ret = lp_load(dyn_CONFIGFILE,False,False,True,True);
76 reopen_logs();
77 load_interfaces();
79 return(ret);
83 /**************************************************************************** **
84 Handle a fault..
85 **************************************************************************** */
87 static void fault_quit(void)
89 dump_core();
92 static void winbindd_status(void)
94 struct winbindd_cli_state *tmp;
96 DEBUG(0, ("winbindd status:\n"));
98 /* Print client state information */
100 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
102 if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
103 DEBUG(2, ("\tclient list:\n"));
104 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
105 DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
106 (unsigned long)tmp->pid, tmp->sock));
111 /* Print winbindd status to log file */
113 static void print_winbindd_status(void)
115 winbindd_status();
118 /* Flush client cache */
120 static void flush_caches(void)
122 /* We need to invalidate cached user list entries on a SIGHUP
123 otherwise cached access denied errors due to restrict anonymous
124 hang around until the sequence number changes. */
126 wcache_invalidate_cache();
129 /* Handle the signal by unlinking socket and exiting */
131 static void terminate(void)
134 winbindd_release_sockets();
135 idmap_close();
137 trustdom_cache_shutdown();
139 #if 0
140 if (interactive) {
141 TALLOC_CTX *mem_ctx = talloc_init("end_description");
142 char *description = talloc_describe_all(mem_ctx);
144 DEBUG(3, ("tallocs left:\n%s\n", description));
145 talloc_destroy(mem_ctx);
147 #endif
149 exit(0);
152 static BOOL do_sigterm;
154 static void termination_handler(int signum)
156 do_sigterm = True;
157 sys_select_signal(signum);
160 static BOOL do_sigusr2;
162 static void sigusr2_handler(int signum)
164 do_sigusr2 = True;
165 sys_select_signal(SIGUSR2);
168 static BOOL do_sighup;
170 static void sighup_handler(int signum)
172 do_sighup = True;
173 sys_select_signal(SIGHUP);
176 static BOOL do_sigchld;
178 static void sigchld_handler(int signum)
180 do_sigchld = True;
181 sys_select_signal(SIGCHLD);
184 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
185 static void msg_reload_services(struct messaging_context *msg,
186 void *private_data,
187 uint32_t msg_type,
188 struct server_id server_id,
189 DATA_BLOB *data)
191 /* Flush various caches */
192 flush_caches();
193 reload_services_file();
196 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
197 static void msg_shutdown(struct messaging_context *msg,
198 void *private_data,
199 uint32_t msg_type,
200 struct server_id server_id,
201 DATA_BLOB *data)
203 do_sigterm = True;
206 static struct winbindd_dispatch_table {
207 enum winbindd_cmd cmd;
208 void (*fn)(struct winbindd_cli_state *state);
209 const char *winbindd_cmd_name;
210 } dispatch_table[] = {
212 /* User functions */
214 { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
215 { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
217 { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
218 { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
219 { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
221 { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
222 { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
223 { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
224 "GETUSERDOMGROUPS" },
226 /* Group functions */
228 { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
229 { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
230 { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
231 { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
232 { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
233 { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
235 /* PAM auth functions */
237 { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
238 { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
239 { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
240 { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
241 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
243 /* Enumeration functions */
245 { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
246 { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
247 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
248 "LIST_TRUSTDOM" },
249 { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
251 /* SID related functions */
253 { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
254 { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
255 { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
257 /* Lookup related functions */
259 { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
260 { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
261 { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
262 { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
263 #if 0 /* DISABLED until we fix the interface in Samba 3.0.26 --jerry */
264 { WINBINDD_SIDS_TO_XIDS, winbindd_sids_to_unixids, "SIDS_TO_XIDS" },
265 #endif /* end DISABLED */
266 { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
267 { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
268 { WINBINDD_SET_MAPPING, winbindd_set_mapping, "SET_MAPPING" },
269 { WINBINDD_SET_HWM, winbindd_set_hwm, "SET_HWMS" },
271 /* Miscellaneous */
273 { WINBINDD_DUMP_MAPS, winbindd_dump_maps, "DUMP_MAPS" },
275 { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
276 { WINBINDD_PING, winbindd_ping, "PING" },
277 { WINBINDD_INFO, winbindd_info, "INFO" },
278 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
279 "INTERFACE_VERSION" },
280 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
281 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
282 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
283 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
284 "WINBINDD_PRIV_PIPE_DIR" },
285 { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
287 /* Credential cache access */
288 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
290 /* WINS functions */
292 { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
293 { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
295 /* End of list */
297 { WINBINDD_NUM_CMDS, NULL, "NONE" }
300 static void process_request(struct winbindd_cli_state *state)
302 struct winbindd_dispatch_table *table = dispatch_table;
304 /* Free response data - we may be interrupted and receive another
305 command before being able to send this data off. */
307 SAFE_FREE(state->response.extra_data.data);
309 ZERO_STRUCT(state->response);
311 state->response.result = WINBINDD_PENDING;
312 state->response.length = sizeof(struct winbindd_response);
314 state->mem_ctx = talloc_init("winbind request");
315 if (state->mem_ctx == NULL)
316 return;
318 /* Remember who asked us. */
319 state->pid = state->request.pid;
321 /* Process command */
323 for (table = dispatch_table; table->fn; table++) {
324 if (state->request.cmd == table->cmd) {
325 DEBUG(10,("process_request: request fn %s\n",
326 table->winbindd_cmd_name ));
327 table->fn(state);
328 break;
332 if (!table->fn) {
333 DEBUG(10,("process_request: unknown request fn number %d\n",
334 (int)state->request.cmd ));
335 request_error(state);
340 * A list of file descriptors being monitored by select in the main processing
341 * loop. fd_event->handler is called whenever the socket is readable/writable.
344 static struct fd_event *fd_events = NULL;
346 void add_fd_event(struct fd_event *ev)
348 struct fd_event *match;
350 /* only add unique fd_event structs */
352 for (match=fd_events; match; match=match->next ) {
353 #ifdef DEVELOPER
354 SMB_ASSERT( match != ev );
355 #else
356 if ( match == ev )
357 return;
358 #endif
361 DLIST_ADD(fd_events, ev);
364 void remove_fd_event(struct fd_event *ev)
366 DLIST_REMOVE(fd_events, ev);
370 * Handler for fd_events to complete a read/write request, set up by
371 * setup_async_read/setup_async_write.
374 static void rw_callback(struct fd_event *event, int flags)
376 size_t todo;
377 ssize_t done = 0;
379 todo = event->length - event->done;
381 if (event->flags & EVENT_FD_WRITE) {
382 SMB_ASSERT(flags == EVENT_FD_WRITE);
383 done = sys_write(event->fd,
384 &((char *)event->data)[event->done],
385 todo);
387 if (done <= 0) {
388 event->flags = 0;
389 event->finished(event->private_data, False);
390 return;
394 if (event->flags & EVENT_FD_READ) {
395 SMB_ASSERT(flags == EVENT_FD_READ);
396 done = sys_read(event->fd, &((char *)event->data)[event->done],
397 todo);
399 if (done <= 0) {
400 event->flags = 0;
401 event->finished(event->private_data, False);
402 return;
406 event->done += done;
408 if (event->done == event->length) {
409 event->flags = 0;
410 event->finished(event->private_data, True);
415 * Request an async read/write on a fd_event structure. (*finished) is called
416 * when the request is completed or an error had occurred.
419 void setup_async_read(struct fd_event *event, void *data, size_t length,
420 void (*finished)(void *private_data, BOOL success),
421 void *private_data)
423 SMB_ASSERT(event->flags == 0);
424 event->data = data;
425 event->length = length;
426 event->done = 0;
427 event->handler = rw_callback;
428 event->finished = finished;
429 event->private_data = private_data;
430 event->flags = EVENT_FD_READ;
433 void setup_async_write(struct fd_event *event, void *data, size_t length,
434 void (*finished)(void *private_data, BOOL success),
435 void *private_data)
437 SMB_ASSERT(event->flags == 0);
438 event->data = data;
439 event->length = length;
440 event->done = 0;
441 event->handler = rw_callback;
442 event->finished = finished;
443 event->private_data = private_data;
444 event->flags = EVENT_FD_WRITE;
448 * This is the main event loop of winbind requests. It goes through a
449 * state-machine of 3 read/write requests, 4 if you have extra data to send.
451 * An idle winbind client has a read request of 4 bytes outstanding,
452 * finalizing function is request_len_recv, checking the length. request_recv
453 * then processes the packet. The processing function then at some point has
454 * to call request_finished which schedules sending the response.
457 static void request_len_recv(void *private_data, BOOL success);
458 static void request_recv(void *private_data, BOOL success);
459 static void request_main_recv(void *private_data, BOOL success);
460 static void request_finished(struct winbindd_cli_state *state);
461 void request_finished_cont(void *private_data, BOOL success);
462 static void response_main_sent(void *private_data, BOOL success);
463 static void response_extra_sent(void *private_data, BOOL success);
465 static void response_extra_sent(void *private_data, BOOL success)
467 struct winbindd_cli_state *state =
468 talloc_get_type_abort(private_data, struct winbindd_cli_state);
470 if (state->mem_ctx != NULL) {
471 talloc_destroy(state->mem_ctx);
472 state->mem_ctx = NULL;
475 if (!success) {
476 state->finished = True;
477 return;
480 SAFE_FREE(state->request.extra_data.data);
481 SAFE_FREE(state->response.extra_data.data);
483 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
484 request_len_recv, state);
487 static void response_main_sent(void *private_data, BOOL success)
489 struct winbindd_cli_state *state =
490 talloc_get_type_abort(private_data, struct winbindd_cli_state);
492 if (!success) {
493 state->finished = True;
494 return;
497 if (state->response.length == sizeof(state->response)) {
498 if (state->mem_ctx != NULL) {
499 talloc_destroy(state->mem_ctx);
500 state->mem_ctx = NULL;
503 setup_async_read(&state->fd_event, &state->request,
504 sizeof(uint32), request_len_recv, state);
505 return;
508 setup_async_write(&state->fd_event, state->response.extra_data.data,
509 state->response.length - sizeof(state->response),
510 response_extra_sent, state);
513 static void request_finished(struct winbindd_cli_state *state)
515 setup_async_write(&state->fd_event, &state->response,
516 sizeof(state->response), response_main_sent, state);
519 void request_error(struct winbindd_cli_state *state)
521 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
522 state->response.result = WINBINDD_ERROR;
523 request_finished(state);
526 void request_ok(struct winbindd_cli_state *state)
528 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
529 state->response.result = WINBINDD_OK;
530 request_finished(state);
533 void request_finished_cont(void *private_data, BOOL success)
535 struct winbindd_cli_state *state =
536 talloc_get_type_abort(private_data, struct winbindd_cli_state);
538 if (success)
539 request_ok(state);
540 else
541 request_error(state);
544 static void request_len_recv(void *private_data, BOOL success)
546 struct winbindd_cli_state *state =
547 talloc_get_type_abort(private_data, struct winbindd_cli_state);
549 if (!success) {
550 state->finished = True;
551 return;
554 if (*(uint32 *)(&state->request) != sizeof(state->request)) {
555 DEBUG(0,("request_len_recv: Invalid request size received: %d\n",
556 *(uint32 *)(&state->request)));
557 state->finished = True;
558 return;
561 setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
562 sizeof(state->request) - sizeof(uint32),
563 request_main_recv, state);
566 static void request_main_recv(void *private_data, BOOL success)
568 struct winbindd_cli_state *state =
569 talloc_get_type_abort(private_data, struct winbindd_cli_state);
571 if (!success) {
572 state->finished = True;
573 return;
576 if (state->request.extra_len == 0) {
577 state->request.extra_data.data = NULL;
578 request_recv(state, True);
579 return;
582 if ((!state->privileged) &&
583 (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
584 DEBUG(3, ("Got request with %d bytes extra data on "
585 "unprivileged socket\n", (int)state->request.extra_len));
586 state->request.extra_data.data = NULL;
587 state->finished = True;
588 return;
591 state->request.extra_data.data =
592 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
594 if (state->request.extra_data.data == NULL) {
595 DEBUG(0, ("malloc failed\n"));
596 state->finished = True;
597 return;
600 /* Ensure null termination */
601 state->request.extra_data.data[state->request.extra_len] = '\0';
603 setup_async_read(&state->fd_event, state->request.extra_data.data,
604 state->request.extra_len, request_recv, state);
607 static void request_recv(void *private_data, BOOL success)
609 struct winbindd_cli_state *state =
610 talloc_get_type_abort(private_data, struct winbindd_cli_state);
612 if (!success) {
613 state->finished = True;
614 return;
617 process_request(state);
620 /* Process a new connection by adding it to the client connection list */
622 static void new_connection(int listen_sock, BOOL privileged)
624 struct sockaddr_un sunaddr;
625 struct winbindd_cli_state *state;
626 socklen_t len;
627 int sock;
629 /* Accept connection */
631 len = sizeof(sunaddr);
633 do {
634 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
635 } while (sock == -1 && errno == EINTR);
637 if (sock == -1)
638 return;
640 DEBUG(6,("accepted socket %d\n", sock));
642 /* Create new connection structure */
644 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
645 close(sock);
646 return;
649 state->sock = sock;
651 state->last_access = time(NULL);
653 state->privileged = privileged;
655 state->fd_event.fd = state->sock;
656 state->fd_event.flags = 0;
657 add_fd_event(&state->fd_event);
659 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
660 request_len_recv, state);
662 /* Add to connection list */
664 winbindd_add_client(state);
667 /* Remove a client connection from client connection list */
669 static void remove_client(struct winbindd_cli_state *state)
671 /* It's a dead client - hold a funeral */
673 if (state == NULL) {
674 return;
677 /* Close socket */
679 close(state->sock);
681 /* Free any getent state */
683 free_getent_state(state->getpwent_state);
684 free_getent_state(state->getgrent_state);
686 /* We may have some extra data that was not freed if the client was
687 killed unexpectedly */
689 SAFE_FREE(state->response.extra_data.data);
691 if (state->mem_ctx != NULL) {
692 talloc_destroy(state->mem_ctx);
693 state->mem_ctx = NULL;
696 remove_fd_event(&state->fd_event);
698 /* Remove from list and free */
700 winbindd_remove_client(state);
701 TALLOC_FREE(state);
704 /* Shutdown client connection which has been idle for the longest time */
706 static BOOL remove_idle_client(void)
708 struct winbindd_cli_state *state, *remove_state = NULL;
709 time_t last_access = 0;
710 int nidle = 0;
712 for (state = winbindd_client_list(); state; state = state->next) {
713 if (state->response.result != WINBINDD_PENDING &&
714 !state->getpwent_state && !state->getgrent_state) {
715 nidle++;
716 if (!last_access || state->last_access < last_access) {
717 last_access = state->last_access;
718 remove_state = state;
723 if (remove_state) {
724 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
725 nidle, remove_state->sock, (unsigned int)remove_state->pid));
726 remove_client(remove_state);
727 return True;
730 return False;
733 /* Process incoming clients on listen_sock. We use a tricky non-blocking,
734 non-forking, non-threaded model which allows us to handle many
735 simultaneous connections while remaining impervious to many denial of
736 service attacks. */
738 static int process_loop(int listen_sock, int listen_priv_sock)
740 struct winbindd_cli_state *state;
741 struct fd_event *ev;
742 fd_set r_fds, w_fds;
743 int maxfd, selret;
744 struct timeval timeout, ev_timeout;
746 /* We'll be doing this a lot */
748 /* Handle messages */
750 message_dispatch(winbind_messaging_context());
752 run_events(winbind_event_context(), 0, NULL, NULL);
754 /* refresh the trusted domain cache */
756 rescan_trusted_domains();
758 /* Free up temporary memory */
760 lp_TALLOC_FREE();
761 main_loop_TALLOC_FREE();
763 /* Initialise fd lists for select() */
765 maxfd = MAX(listen_sock, listen_priv_sock);
767 FD_ZERO(&r_fds);
768 FD_ZERO(&w_fds);
769 FD_SET(listen_sock, &r_fds);
770 FD_SET(listen_priv_sock, &r_fds);
772 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
773 timeout.tv_usec = 0;
775 /* Check for any event timeouts. */
776 if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
777 timeout = timeval_min(&timeout, &ev_timeout);
780 /* Set up client readers and writers */
782 state = winbindd_client_list();
784 while (state) {
786 struct winbindd_cli_state *next = state->next;
788 /* Dispose of client connection if it is marked as
789 finished */
791 if (state->finished)
792 remove_client(state);
794 state = next;
797 for (ev = fd_events; ev; ev = ev->next) {
798 if (ev->flags & EVENT_FD_READ) {
799 FD_SET(ev->fd, &r_fds);
800 maxfd = MAX(ev->fd, maxfd);
802 if (ev->flags & EVENT_FD_WRITE) {
803 FD_SET(ev->fd, &w_fds);
804 maxfd = MAX(ev->fd, maxfd);
808 /* Call select */
810 selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
812 if (selret == 0) {
813 goto no_fds_ready;
816 if (selret == -1) {
817 if (errno == EINTR) {
818 goto no_fds_ready;
821 /* Select error, something is badly wrong */
823 perror("select");
824 exit(1);
827 /* selret > 0 */
829 ev = fd_events;
830 while (ev != NULL) {
831 struct fd_event *next = ev->next;
832 int flags = 0;
833 if (FD_ISSET(ev->fd, &r_fds))
834 flags |= EVENT_FD_READ;
835 if (FD_ISSET(ev->fd, &w_fds))
836 flags |= EVENT_FD_WRITE;
837 if (flags)
838 ev->handler(ev, flags);
839 ev = next;
842 if (FD_ISSET(listen_sock, &r_fds)) {
843 while (winbindd_num_clients() >
844 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
845 DEBUG(5,("winbindd: Exceeding %d client "
846 "connections, removing idle "
847 "connection.\n",
848 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
849 if (!remove_idle_client()) {
850 DEBUG(0,("winbindd: Exceeding %d "
851 "client connections, no idle "
852 "connection found\n",
853 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
854 break;
857 /* new, non-privileged connection */
858 new_connection(listen_sock, False);
861 if (FD_ISSET(listen_priv_sock, &r_fds)) {
862 while (winbindd_num_clients() >
863 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
864 DEBUG(5,("winbindd: Exceeding %d client "
865 "connections, removing idle "
866 "connection.\n",
867 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
868 if (!remove_idle_client()) {
869 DEBUG(0,("winbindd: Exceeding %d "
870 "client connections, no idle "
871 "connection found\n",
872 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
873 break;
876 /* new, privileged connection */
877 new_connection(listen_priv_sock, True);
880 no_fds_ready:
882 #if 0
883 winbindd_check_cache_size(time(NULL));
884 #endif
886 /* Check signal handling things */
888 if (do_sigterm)
889 terminate();
891 if (do_sighup) {
893 DEBUG(3, ("got SIGHUP\n"));
895 flush_caches();
896 reload_services_file();
898 do_sighup = False;
901 if (do_sigusr2) {
902 print_winbindd_status();
903 do_sigusr2 = False;
906 if (do_sigchld) {
907 pid_t pid;
909 do_sigchld = False;
911 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
912 winbind_child_died(pid);
917 return winbindd_num_clients();
920 static void winbindd_process_loop(enum smb_server_mode server_mode)
922 int idle_timeout_sec;
923 struct timeval starttime;
924 int listen_public, listen_priv;
926 errno = 0;
927 if (!winbindd_init_sockets(&listen_public, &listen_priv,
928 &idle_timeout_sec)) {
929 terminate();
932 starttime = timeval_current();
934 if (listen_public == -1 || listen_priv == -1) {
935 DEBUG(0, ("failed to open winbindd pipes: %s\n",
936 errno ? strerror(errno) : "unknown error"));
937 terminate();
940 for (;;) {
941 int clients = process_loop(listen_public, listen_priv);
943 /* Don't bother figuring out the idle time if we won't be
944 * timing out anyway.
946 if (idle_timeout_sec < 0) {
947 continue;
950 if (clients == 0 && server_mode == SERVER_MODE_FOREGROUND) {
951 struct timeval now;
953 now = timeval_current();
954 if (timeval_elapsed2(&starttime, &now) >
955 (double)idle_timeout_sec) {
956 DEBUG(0, ("idle for %d secs, exitting\n",
957 idle_timeout_sec));
958 terminate();
960 } else {
961 starttime = timeval_current();
966 /* Main function */
968 int main(int argc, char **argv, char **envp)
970 pstring logfile;
971 BOOL log_stdout = False;
972 BOOL no_process_group = False;
974 enum smb_server_mode server_mode = SERVER_MODE_DAEMON;
976 struct poptOption long_options[] = {
977 POPT_AUTOHELP
978 { "stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
979 { "foreground", 'F', POPT_ARG_VAL, &server_mode, SERVER_MODE_FOREGROUND, "Daemon in foreground mode" },
980 { "no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
981 { "interactive", 'i', POPT_ARG_VAL, &server_mode, SERVER_MODE_INTERACTIVE, "Interactive mode" },
982 { "no-caching", 'n', POPT_ARG_VAL, &opt_nocache, True, "Disable caching" },
983 POPT_COMMON_SAMBA
984 POPT_TABLEEND
986 poptContext pc;
987 int opt;
989 /* glibc (?) likes to print "User defined signal 1" and exit if a
990 SIGUSR[12] is received before a handler is installed */
992 CatchSignal(SIGUSR1, SIG_IGN);
993 CatchSignal(SIGUSR2, SIG_IGN);
995 fault_setup((void (*)(void *))fault_quit );
996 dump_core_setup("winbindd");
998 load_case_tables();
1000 /* Initialise for running in non-root mode */
1002 sec_init();
1004 set_remote_machine_name("winbindd", False);
1006 /* Set environment variable so we don't recursively call ourselves.
1007 This may also be useful interactively. */
1009 if ( !winbind_off() ) {
1010 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1011 exit(1);
1014 /* Initialise samba/rpc client stuff */
1016 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options,
1017 POPT_CONTEXT_KEEP_FIRST);
1019 while ((opt = poptGetNextOpt(pc)) != -1) {}
1021 if (server_mode == SERVER_MODE_INTERACTIVE) {
1022 log_stdout = True;
1023 if (DEBUGLEVEL >= 9) {
1024 talloc_enable_leak_report();
1028 if (log_stdout && server_mode == SERVER_MODE_DAEMON) {
1029 printf("Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n");
1030 poptPrintUsage(pc, stderr, 0);
1031 exit(1);
1034 if (!override_logfile) {
1035 pstr_sprintf(logfile, "%s/log.winbindd", dyn_LOGFILEBASE);
1036 lp_set_logfile(logfile);
1038 setup_logging("winbindd", log_stdout);
1039 reopen_logs();
1041 DEBUG(1, ("winbindd version %s started.\n%s\n",
1042 SAMBA_VERSION_STRING,
1043 COPYRIGHT_STARTUP_MESSAGE) );
1045 if (!reload_services_file()) {
1046 DEBUG(0, ("error opening config file\n"));
1047 exit(1);
1050 if (!directory_exist(lp_lockdir(), NULL)) {
1051 mkdir(lp_lockdir(), 0755);
1054 /* Setup names. */
1056 if (!init_names())
1057 exit(1);
1059 load_interfaces();
1061 if (!secrets_init()) {
1063 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1064 return False;
1067 /* Enable netbios namecache */
1069 namecache_enable();
1071 /* Winbind daemon initialisation */
1073 if ( ! NT_STATUS_IS_OK(idmap_init_cache()) ) {
1074 DEBUG(1, ("Could not init idmap cache!\n"));
1077 /* Unblock all signals we are interested in as they may have been
1078 blocked by the parent process. */
1080 BlockSignals(False, SIGINT);
1081 BlockSignals(False, SIGQUIT);
1082 BlockSignals(False, SIGTERM);
1083 BlockSignals(False, SIGUSR1);
1084 BlockSignals(False, SIGUSR2);
1085 BlockSignals(False, SIGHUP);
1086 BlockSignals(False, SIGCHLD);
1088 /* Setup signal handlers */
1090 CatchSignal(SIGINT, termination_handler); /* Exit on these sigs */
1091 CatchSignal(SIGQUIT, termination_handler);
1092 CatchSignal(SIGTERM, termination_handler);
1093 CatchSignal(SIGCHLD, sigchld_handler);
1095 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1097 CatchSignal(SIGUSR2, sigusr2_handler); /* Debugging sigs */
1098 CatchSignal(SIGHUP, sighup_handler);
1100 if (server_mode == SERVER_MODE_DAEMON) {
1101 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1102 become_daemon(True, no_process_group);
1103 } else if (server_mode == SERVER_MODE_FOREGROUND) {
1104 become_daemon(False, no_process_group);
1107 pidfile_create("winbindd");
1109 /* Ensure all cache and idmap caches are consistent
1110 before we startup. */
1112 if (winbindd_validate_cache()) {
1113 /* We have a bad cache, but luckily we
1114 just deleted it. Restart ourselves */
1115 int i;
1116 /* Ensure we have no open low fd's. */
1117 for (i = 3; i < 100; i++) {
1118 close(i);
1120 return execve(argv[0], argv, envp);
1123 #if HAVE_SETPGID
1125 * If we're interactive we want to set our own process group for
1126 * signal management.
1128 if (server_mode == SERVER_MODE_INTERACTIVE && !no_process_group) {
1129 setpgid( (pid_t)0, (pid_t)0);
1131 #endif
1133 TimeInit();
1135 /* Initialise messaging system */
1137 if (winbind_messaging_context() == NULL) {
1138 DEBUG(0, ("unable to initialize messaging system\n"));
1139 exit(1);
1142 /* Initialize cache (ensure version is correct). */
1143 if (!initialize_winbindd_cache()) {
1144 exit(1);
1147 /* React on 'smbcontrol winbindd reload-config' in the same way
1148 as to SIGHUP signal */
1149 messaging_register(winbind_messaging_context(), NULL,
1150 MSG_SMB_CONF_UPDATED, msg_reload_services);
1151 messaging_register(winbind_messaging_context(), NULL,
1152 MSG_SHUTDOWN, msg_shutdown);
1154 /* Handle online/offline messages. */
1155 messaging_register(winbind_messaging_context(), NULL,
1156 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1157 messaging_register(winbind_messaging_context(), NULL,
1158 MSG_WINBIND_ONLINE, winbind_msg_online);
1159 messaging_register(winbind_messaging_context(), NULL,
1160 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1162 poptFreeContext(pc);
1164 netsamlogon_cache_init(); /* Non-critical */
1166 /* clear the cached list of trusted domains */
1168 wcache_tdc_clear();
1170 if (!init_domain_list()) {
1171 DEBUG(0,("unable to initalize domain list\n"));
1172 exit(1);
1175 init_idmap_child();
1177 smb_nscd_flush_user_cache();
1178 smb_nscd_flush_group_cache();
1180 /* Loop waiting for requests */
1181 winbindd_process_loop(server_mode);
1183 return 0;