r23055: Rewrite messages.c to use auto-generated marshalling in the tdb. I'm
[Samba/gebeck_regimport.git] / source3 / nsswitch / winbindd.c
blob8e6d2d0bd2d93ba5734026304eaabc5e4e00cb6d
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 /* Process command */
320 for (table = dispatch_table; table->fn; table++) {
321 if (state->request.cmd == table->cmd) {
322 DEBUG(10,("process_request: request fn %s\n",
323 table->winbindd_cmd_name ));
324 table->fn(state);
325 break;
329 if (!table->fn) {
330 DEBUG(10,("process_request: unknown request fn number %d\n",
331 (int)state->request.cmd ));
332 request_error(state);
337 * A list of file descriptors being monitored by select in the main processing
338 * loop. fd_event->handler is called whenever the socket is readable/writable.
341 static struct fd_event *fd_events = NULL;
343 void add_fd_event(struct fd_event *ev)
345 struct fd_event *match;
347 /* only add unique fd_event structs */
349 for (match=fd_events; match; match=match->next ) {
350 #ifdef DEVELOPER
351 SMB_ASSERT( match != ev );
352 #else
353 if ( match == ev )
354 return;
355 #endif
358 DLIST_ADD(fd_events, ev);
361 void remove_fd_event(struct fd_event *ev)
363 DLIST_REMOVE(fd_events, ev);
367 * Handler for fd_events to complete a read/write request, set up by
368 * setup_async_read/setup_async_write.
371 static void rw_callback(struct fd_event *event, int flags)
373 size_t todo;
374 ssize_t done = 0;
376 todo = event->length - event->done;
378 if (event->flags & EVENT_FD_WRITE) {
379 SMB_ASSERT(flags == EVENT_FD_WRITE);
380 done = sys_write(event->fd,
381 &((char *)event->data)[event->done],
382 todo);
384 if (done <= 0) {
385 event->flags = 0;
386 event->finished(event->private_data, False);
387 return;
391 if (event->flags & EVENT_FD_READ) {
392 SMB_ASSERT(flags == EVENT_FD_READ);
393 done = sys_read(event->fd, &((char *)event->data)[event->done],
394 todo);
396 if (done <= 0) {
397 event->flags = 0;
398 event->finished(event->private_data, False);
399 return;
403 event->done += done;
405 if (event->done == event->length) {
406 event->flags = 0;
407 event->finished(event->private_data, True);
412 * Request an async read/write on a fd_event structure. (*finished) is called
413 * when the request is completed or an error had occurred.
416 void setup_async_read(struct fd_event *event, void *data, size_t length,
417 void (*finished)(void *private_data, BOOL success),
418 void *private_data)
420 SMB_ASSERT(event->flags == 0);
421 event->data = data;
422 event->length = length;
423 event->done = 0;
424 event->handler = rw_callback;
425 event->finished = finished;
426 event->private_data = private_data;
427 event->flags = EVENT_FD_READ;
430 void setup_async_write(struct fd_event *event, void *data, size_t length,
431 void (*finished)(void *private_data, BOOL success),
432 void *private_data)
434 SMB_ASSERT(event->flags == 0);
435 event->data = data;
436 event->length = length;
437 event->done = 0;
438 event->handler = rw_callback;
439 event->finished = finished;
440 event->private_data = private_data;
441 event->flags = EVENT_FD_WRITE;
445 * This is the main event loop of winbind requests. It goes through a
446 * state-machine of 3 read/write requests, 4 if you have extra data to send.
448 * An idle winbind client has a read request of 4 bytes outstanding,
449 * finalizing function is request_len_recv, checking the length. request_recv
450 * then processes the packet. The processing function then at some point has
451 * to call request_finished which schedules sending the response.
454 static void request_len_recv(void *private_data, BOOL success);
455 static void request_recv(void *private_data, BOOL success);
456 static void request_main_recv(void *private_data, BOOL success);
457 static void request_finished(struct winbindd_cli_state *state);
458 void request_finished_cont(void *private_data, BOOL success);
459 static void response_main_sent(void *private_data, BOOL success);
460 static void response_extra_sent(void *private_data, BOOL success);
462 static void response_extra_sent(void *private_data, BOOL success)
464 struct winbindd_cli_state *state =
465 talloc_get_type_abort(private_data, struct winbindd_cli_state);
467 if (state->mem_ctx != NULL) {
468 talloc_destroy(state->mem_ctx);
469 state->mem_ctx = NULL;
472 if (!success) {
473 state->finished = True;
474 return;
477 SAFE_FREE(state->request.extra_data.data);
478 SAFE_FREE(state->response.extra_data.data);
480 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
481 request_len_recv, state);
484 static void response_main_sent(void *private_data, BOOL success)
486 struct winbindd_cli_state *state =
487 talloc_get_type_abort(private_data, struct winbindd_cli_state);
489 if (!success) {
490 state->finished = True;
491 return;
494 if (state->response.length == sizeof(state->response)) {
495 if (state->mem_ctx != NULL) {
496 talloc_destroy(state->mem_ctx);
497 state->mem_ctx = NULL;
500 setup_async_read(&state->fd_event, &state->request,
501 sizeof(uint32), request_len_recv, state);
502 return;
505 setup_async_write(&state->fd_event, state->response.extra_data.data,
506 state->response.length - sizeof(state->response),
507 response_extra_sent, state);
510 static void request_finished(struct winbindd_cli_state *state)
512 setup_async_write(&state->fd_event, &state->response,
513 sizeof(state->response), response_main_sent, state);
516 void request_error(struct winbindd_cli_state *state)
518 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
519 state->response.result = WINBINDD_ERROR;
520 request_finished(state);
523 void request_ok(struct winbindd_cli_state *state)
525 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
526 state->response.result = WINBINDD_OK;
527 request_finished(state);
530 void request_finished_cont(void *private_data, BOOL success)
532 struct winbindd_cli_state *state =
533 talloc_get_type_abort(private_data, struct winbindd_cli_state);
535 if (success)
536 request_ok(state);
537 else
538 request_error(state);
541 static void request_len_recv(void *private_data, BOOL success)
543 struct winbindd_cli_state *state =
544 talloc_get_type_abort(private_data, struct winbindd_cli_state);
546 if (!success) {
547 state->finished = True;
548 return;
551 if (*(uint32 *)(&state->request) != sizeof(state->request)) {
552 DEBUG(0,("request_len_recv: Invalid request size received: %d\n",
553 *(uint32 *)(&state->request)));
554 state->finished = True;
555 return;
558 setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
559 sizeof(state->request) - sizeof(uint32),
560 request_main_recv, state);
563 static void request_main_recv(void *private_data, BOOL success)
565 struct winbindd_cli_state *state =
566 talloc_get_type_abort(private_data, struct winbindd_cli_state);
568 if (!success) {
569 state->finished = True;
570 return;
573 if (state->request.extra_len == 0) {
574 state->request.extra_data.data = NULL;
575 request_recv(state, True);
576 return;
579 if ((!state->privileged) &&
580 (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
581 DEBUG(3, ("Got request with %d bytes extra data on "
582 "unprivileged socket\n", (int)state->request.extra_len));
583 state->request.extra_data.data = NULL;
584 state->finished = True;
585 return;
588 state->request.extra_data.data =
589 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
591 if (state->request.extra_data.data == NULL) {
592 DEBUG(0, ("malloc failed\n"));
593 state->finished = True;
594 return;
597 /* Ensure null termination */
598 state->request.extra_data.data[state->request.extra_len] = '\0';
600 setup_async_read(&state->fd_event, state->request.extra_data.data,
601 state->request.extra_len, request_recv, state);
604 static void request_recv(void *private_data, BOOL success)
606 struct winbindd_cli_state *state =
607 talloc_get_type_abort(private_data, struct winbindd_cli_state);
609 if (!success) {
610 state->finished = True;
611 return;
614 process_request(state);
617 /* Process a new connection by adding it to the client connection list */
619 static void new_connection(int listen_sock, BOOL privileged)
621 struct sockaddr_un sunaddr;
622 struct winbindd_cli_state *state;
623 socklen_t len;
624 int sock;
626 /* Accept connection */
628 len = sizeof(sunaddr);
630 do {
631 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
632 } while (sock == -1 && errno == EINTR);
634 if (sock == -1)
635 return;
637 DEBUG(6,("accepted socket %d\n", sock));
639 /* Create new connection structure */
641 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
642 close(sock);
643 return;
646 state->sock = sock;
648 state->last_access = time(NULL);
650 state->privileged = privileged;
652 state->fd_event.fd = state->sock;
653 state->fd_event.flags = 0;
654 add_fd_event(&state->fd_event);
656 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
657 request_len_recv, state);
659 /* Add to connection list */
661 winbindd_add_client(state);
664 /* Remove a client connection from client connection list */
666 static void remove_client(struct winbindd_cli_state *state)
668 /* It's a dead client - hold a funeral */
670 if (state == NULL) {
671 return;
674 /* Close socket */
676 close(state->sock);
678 /* Free any getent state */
680 free_getent_state(state->getpwent_state);
681 free_getent_state(state->getgrent_state);
683 /* We may have some extra data that was not freed if the client was
684 killed unexpectedly */
686 SAFE_FREE(state->response.extra_data.data);
688 if (state->mem_ctx != NULL) {
689 talloc_destroy(state->mem_ctx);
690 state->mem_ctx = NULL;
693 remove_fd_event(&state->fd_event);
695 /* Remove from list and free */
697 winbindd_remove_client(state);
698 TALLOC_FREE(state);
701 /* Shutdown client connection which has been idle for the longest time */
703 static BOOL remove_idle_client(void)
705 struct winbindd_cli_state *state, *remove_state = NULL;
706 time_t last_access = 0;
707 int nidle = 0;
709 for (state = winbindd_client_list(); state; state = state->next) {
710 if (state->response.result != WINBINDD_PENDING &&
711 !state->getpwent_state && !state->getgrent_state) {
712 nidle++;
713 if (!last_access || state->last_access < last_access) {
714 last_access = state->last_access;
715 remove_state = state;
720 if (remove_state) {
721 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
722 nidle, remove_state->sock, (unsigned int)remove_state->pid));
723 remove_client(remove_state);
724 return True;
727 return False;
730 /* Process incoming clients on listen_sock. We use a tricky non-blocking,
731 non-forking, non-threaded model which allows us to handle many
732 simultaneous connections while remaining impervious to many denial of
733 service attacks. */
735 static int process_loop(int listen_sock, int listen_priv_sock)
737 struct winbindd_cli_state *state;
738 struct fd_event *ev;
739 fd_set r_fds, w_fds;
740 int maxfd, selret;
741 struct timeval timeout, ev_timeout;
743 /* We'll be doing this a lot */
745 /* Handle messages */
747 message_dispatch(winbind_messaging_context());
749 run_events(winbind_event_context(), 0, NULL, NULL);
751 /* refresh the trusted domain cache */
753 rescan_trusted_domains();
755 /* Free up temporary memory */
757 lp_TALLOC_FREE();
758 main_loop_TALLOC_FREE();
760 /* Initialise fd lists for select() */
762 maxfd = MAX(listen_sock, listen_priv_sock);
764 FD_ZERO(&r_fds);
765 FD_ZERO(&w_fds);
766 FD_SET(listen_sock, &r_fds);
767 FD_SET(listen_priv_sock, &r_fds);
769 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
770 timeout.tv_usec = 0;
772 /* Check for any event timeouts. */
773 if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
774 timeout = timeval_min(&timeout, &ev_timeout);
777 /* Set up client readers and writers */
779 state = winbindd_client_list();
781 while (state) {
783 struct winbindd_cli_state *next = state->next;
785 /* Dispose of client connection if it is marked as
786 finished */
788 if (state->finished)
789 remove_client(state);
791 state = next;
794 for (ev = fd_events; ev; ev = ev->next) {
795 if (ev->flags & EVENT_FD_READ) {
796 FD_SET(ev->fd, &r_fds);
797 maxfd = MAX(ev->fd, maxfd);
799 if (ev->flags & EVENT_FD_WRITE) {
800 FD_SET(ev->fd, &w_fds);
801 maxfd = MAX(ev->fd, maxfd);
805 /* Call select */
807 selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
809 if (selret == 0) {
810 goto no_fds_ready;
813 if (selret == -1) {
814 if (errno == EINTR) {
815 goto no_fds_ready;
818 /* Select error, something is badly wrong */
820 perror("select");
821 exit(1);
824 /* selret > 0 */
826 ev = fd_events;
827 while (ev != NULL) {
828 struct fd_event *next = ev->next;
829 int flags = 0;
830 if (FD_ISSET(ev->fd, &r_fds))
831 flags |= EVENT_FD_READ;
832 if (FD_ISSET(ev->fd, &w_fds))
833 flags |= EVENT_FD_WRITE;
834 if (flags)
835 ev->handler(ev, flags);
836 ev = next;
839 if (FD_ISSET(listen_sock, &r_fds)) {
840 while (winbindd_num_clients() >
841 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
842 DEBUG(5,("winbindd: Exceeding %d client "
843 "connections, removing idle "
844 "connection.\n",
845 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
846 if (!remove_idle_client()) {
847 DEBUG(0,("winbindd: Exceeding %d "
848 "client connections, no idle "
849 "connection found\n",
850 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
851 break;
854 /* new, non-privileged connection */
855 new_connection(listen_sock, False);
858 if (FD_ISSET(listen_priv_sock, &r_fds)) {
859 while (winbindd_num_clients() >
860 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
861 DEBUG(5,("winbindd: Exceeding %d client "
862 "connections, removing idle "
863 "connection.\n",
864 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
865 if (!remove_idle_client()) {
866 DEBUG(0,("winbindd: Exceeding %d "
867 "client connections, no idle "
868 "connection found\n",
869 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
870 break;
873 /* new, privileged connection */
874 new_connection(listen_priv_sock, True);
877 no_fds_ready:
879 #if 0
880 winbindd_check_cache_size(time(NULL));
881 #endif
883 /* Check signal handling things */
885 if (do_sigterm)
886 terminate();
888 if (do_sighup) {
890 DEBUG(3, ("got SIGHUP\n"));
892 flush_caches();
893 reload_services_file();
895 do_sighup = False;
898 if (do_sigusr2) {
899 print_winbindd_status();
900 do_sigusr2 = False;
903 if (do_sigchld) {
904 pid_t pid;
906 do_sigchld = False;
908 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
909 winbind_child_died(pid);
914 return winbindd_num_clients();
917 static void winbindd_process_loop(enum smb_server_mode server_mode)
919 int idle_timeout_sec;
920 struct timeval starttime;
921 int listen_public, listen_priv;
923 errno = 0;
924 if (!winbindd_init_sockets(&listen_public, &listen_priv,
925 &idle_timeout_sec)) {
926 terminate();
929 starttime = timeval_current();
931 if (listen_public == -1 || listen_priv == -1) {
932 DEBUG(0, ("failed to open winbindd pipes: %s\n",
933 errno ? strerror(errno) : "unknown error"));
934 terminate();
937 for (;;) {
938 int clients = process_loop(listen_public, listen_priv);
940 /* Don't bother figuring out the idle time if we won't be
941 * timing out anyway.
943 if (idle_timeout_sec < 0) {
944 continue;
947 if (clients == 0 && server_mode == SERVER_MODE_FOREGROUND) {
948 struct timeval now;
950 now = timeval_current();
951 if (timeval_elapsed2(&starttime, &now) >
952 (double)idle_timeout_sec) {
953 DEBUG(0, ("idle for %d secs, exitting\n",
954 idle_timeout_sec));
955 terminate();
957 } else {
958 starttime = timeval_current();
963 /* Main function */
965 int main(int argc, char **argv, char **envp)
967 pstring logfile;
968 BOOL log_stdout = False;
969 BOOL no_process_group = False;
971 enum smb_server_mode server_mode = SERVER_MODE_DAEMON;
973 struct poptOption long_options[] = {
974 POPT_AUTOHELP
975 { "stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
976 { "foreground", 'F', POPT_ARG_VAL, &server_mode, SERVER_MODE_FOREGROUND, "Daemon in foreground mode" },
977 { "no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
978 { "interactive", 'i', POPT_ARG_VAL, &server_mode, SERVER_MODE_INTERACTIVE, "Interactive mode" },
979 { "no-caching", 'n', POPT_ARG_VAL, &opt_nocache, True, "Disable caching" },
980 POPT_COMMON_SAMBA
981 POPT_TABLEEND
983 poptContext pc;
984 int opt;
986 /* glibc (?) likes to print "User defined signal 1" and exit if a
987 SIGUSR[12] is received before a handler is installed */
989 CatchSignal(SIGUSR1, SIG_IGN);
990 CatchSignal(SIGUSR2, SIG_IGN);
992 fault_setup((void (*)(void *))fault_quit );
993 dump_core_setup("winbindd");
995 load_case_tables();
997 /* Initialise for running in non-root mode */
999 sec_init();
1001 set_remote_machine_name("winbindd", False);
1003 /* Set environment variable so we don't recursively call ourselves.
1004 This may also be useful interactively. */
1006 if ( !winbind_off() ) {
1007 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1008 exit(1);
1011 /* Initialise samba/rpc client stuff */
1013 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options,
1014 POPT_CONTEXT_KEEP_FIRST);
1016 while ((opt = poptGetNextOpt(pc)) != -1) {}
1018 if (server_mode == SERVER_MODE_INTERACTIVE) {
1019 log_stdout = True;
1020 if (DEBUGLEVEL >= 9) {
1021 talloc_enable_leak_report();
1025 if (log_stdout && server_mode == SERVER_MODE_DAEMON) {
1026 printf("Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n");
1027 poptPrintUsage(pc, stderr, 0);
1028 exit(1);
1031 if (!override_logfile) {
1032 pstr_sprintf(logfile, "%s/log.winbindd", dyn_LOGFILEBASE);
1033 lp_set_logfile(logfile);
1035 setup_logging("winbindd", log_stdout);
1036 reopen_logs();
1038 DEBUG(1, ("winbindd version %s started.\n%s\n",
1039 SAMBA_VERSION_STRING,
1040 COPYRIGHT_STARTUP_MESSAGE) );
1042 if (!reload_services_file()) {
1043 DEBUG(0, ("error opening config file\n"));
1044 exit(1);
1047 if (!directory_exist(lp_lockdir(), NULL)) {
1048 mkdir(lp_lockdir(), 0755);
1051 /* Setup names. */
1053 if (!init_names())
1054 exit(1);
1056 load_interfaces();
1058 if (!secrets_init()) {
1060 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1061 return False;
1064 /* Enable netbios namecache */
1066 namecache_enable();
1068 /* Winbind daemon initialisation */
1070 if ( ! NT_STATUS_IS_OK(idmap_init_cache()) ) {
1071 DEBUG(1, ("Could not init idmap cache!\n"));
1074 /* Unblock all signals we are interested in as they may have been
1075 blocked by the parent process. */
1077 BlockSignals(False, SIGINT);
1078 BlockSignals(False, SIGQUIT);
1079 BlockSignals(False, SIGTERM);
1080 BlockSignals(False, SIGUSR1);
1081 BlockSignals(False, SIGUSR2);
1082 BlockSignals(False, SIGHUP);
1083 BlockSignals(False, SIGCHLD);
1085 /* Setup signal handlers */
1087 CatchSignal(SIGINT, termination_handler); /* Exit on these sigs */
1088 CatchSignal(SIGQUIT, termination_handler);
1089 CatchSignal(SIGTERM, termination_handler);
1090 CatchSignal(SIGCHLD, sigchld_handler);
1092 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1094 CatchSignal(SIGUSR2, sigusr2_handler); /* Debugging sigs */
1095 CatchSignal(SIGHUP, sighup_handler);
1097 if (server_mode == SERVER_MODE_DAEMON) {
1098 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1099 become_daemon(True, no_process_group);
1100 } else if (server_mode == SERVER_MODE_FOREGROUND) {
1101 become_daemon(False, no_process_group);
1104 pidfile_create("winbindd");
1106 /* Ensure all cache and idmap caches are consistent
1107 before we startup. */
1109 if (winbindd_validate_cache()) {
1110 /* We have a bad cache, but luckily we
1111 just deleted it. Restart ourselves */
1112 int i;
1113 /* Ensure we have no open low fd's. */
1114 for (i = 3; i < 100; i++) {
1115 close(i);
1117 return execve(argv[0], argv, envp);
1120 #if HAVE_SETPGID
1122 * If we're interactive we want to set our own process group for
1123 * signal management.
1125 if (server_mode == SERVER_MODE_INTERACTIVE && !no_process_group) {
1126 setpgid( (pid_t)0, (pid_t)0);
1128 #endif
1130 TimeInit();
1132 /* Initialise messaging system */
1134 if (winbind_messaging_context() == NULL) {
1135 DEBUG(0, ("unable to initialize messaging system\n"));
1136 exit(1);
1139 /* Initialize cache (ensure version is correct). */
1140 if (!initialize_winbindd_cache()) {
1141 exit(1);
1144 /* React on 'smbcontrol winbindd reload-config' in the same way
1145 as to SIGHUP signal */
1146 messaging_register(winbind_messaging_context(), NULL,
1147 MSG_SMB_CONF_UPDATED, msg_reload_services);
1148 messaging_register(winbind_messaging_context(), NULL,
1149 MSG_SHUTDOWN, msg_shutdown);
1151 /* Handle online/offline messages. */
1152 messaging_register(winbind_messaging_context(), NULL,
1153 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1154 messaging_register(winbind_messaging_context(), NULL,
1155 MSG_WINBIND_ONLINE, winbind_msg_online);
1156 messaging_register(winbind_messaging_context(), NULL,
1157 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1159 poptFreeContext(pc);
1161 netsamlogon_cache_init(); /* Non-critical */
1163 /* clear the cached list of trusted domains */
1165 wcache_tdc_clear();
1167 /* clear the cached list of trusted domains */
1169 wcache_tdc_clear();
1171 if (!init_domain_list()) {
1172 DEBUG(0,("unable to initalize domain list\n"));
1173 exit(1);
1176 init_idmap_child();
1178 smb_nscd_flush_user_cache();
1179 smb_nscd_flush_group_cache();
1181 /* Loop waiting for requests */
1182 winbindd_process_loop(server_mode);
1184 return 0;