r23791: found some more v2->v3 conversions
[Samba.git] / source / nsswitch / winbindd.c
blob5af5a789ada0cb7c88051512a5505c91c66031d2
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 3 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, see <http://www.gnu.org/licenses/>.
26 #include "includes.h"
27 #include "winbindd.h"
29 #undef DBGC_CLASS
30 #define DBGC_CLASS DBGC_WINBIND
32 BOOL opt_nocache = False;
34 extern BOOL override_logfile;
36 struct event_context *winbind_event_context(void)
38 static struct event_context *ctx;
40 if (!ctx && !(ctx = event_context_init(NULL))) {
41 smb_panic("Could not init winbind event context");
43 return ctx;
46 struct messaging_context *winbind_messaging_context(void)
48 static struct messaging_context *ctx;
50 if (!ctx && !(ctx = messaging_init(NULL, server_id_self(),
51 winbind_event_context()))) {
52 smb_panic("Could not init winbind messaging context");
54 return ctx;
57 /* Reload configuration */
59 static BOOL reload_services_file(void)
61 BOOL ret;
63 if (lp_loaded()) {
64 pstring fname;
66 pstrcpy(fname,lp_configfile());
67 if (file_exist(fname,NULL) && !strcsequal(fname,dyn_CONFIGFILE)) {
68 pstrcpy(dyn_CONFIGFILE,fname);
72 reopen_logs();
73 ret = lp_load(dyn_CONFIGFILE,False,False,True,True);
75 reopen_logs();
76 load_interfaces();
78 return(ret);
82 /**************************************************************************** **
83 Handle a fault..
84 **************************************************************************** */
86 static void fault_quit(void)
88 dump_core();
91 static void winbindd_status(void)
93 struct winbindd_cli_state *tmp;
95 DEBUG(0, ("winbindd status:\n"));
97 /* Print client state information */
99 DEBUG(0, ("\t%d clients currently active\n", winbindd_num_clients()));
101 if (DEBUGLEVEL >= 2 && winbindd_num_clients()) {
102 DEBUG(2, ("\tclient list:\n"));
103 for(tmp = winbindd_client_list(); tmp; tmp = tmp->next) {
104 DEBUGADD(2, ("\t\tpid %lu, sock %d\n",
105 (unsigned long)tmp->pid, tmp->sock));
110 /* Print winbindd status to log file */
112 static void print_winbindd_status(void)
114 winbindd_status();
117 /* Flush client cache */
119 static void flush_caches(void)
121 /* We need to invalidate cached user list entries on a SIGHUP
122 otherwise cached access denied errors due to restrict anonymous
123 hang around until the sequence number changes. */
125 wcache_invalidate_cache();
128 /* Handle the signal by unlinking socket and exiting */
130 static void terminate(void)
133 winbindd_release_sockets();
134 idmap_close();
136 trustdom_cache_shutdown();
138 #if 0
139 if (interactive) {
140 TALLOC_CTX *mem_ctx = talloc_init("end_description");
141 char *description = talloc_describe_all(mem_ctx);
143 DEBUG(3, ("tallocs left:\n%s\n", description));
144 talloc_destroy(mem_ctx);
146 #endif
148 exit(0);
151 static BOOL do_sigterm;
153 static void termination_handler(int signum)
155 do_sigterm = True;
156 sys_select_signal(signum);
159 static BOOL do_sigusr2;
161 static void sigusr2_handler(int signum)
163 do_sigusr2 = True;
164 sys_select_signal(SIGUSR2);
167 static BOOL do_sighup;
169 static void sighup_handler(int signum)
171 do_sighup = True;
172 sys_select_signal(SIGHUP);
175 static BOOL do_sigchld;
177 static void sigchld_handler(int signum)
179 do_sigchld = True;
180 sys_select_signal(SIGCHLD);
183 /* React on 'smbcontrol winbindd reload-config' in the same way as on SIGHUP*/
184 static void msg_reload_services(struct messaging_context *msg,
185 void *private_data,
186 uint32_t msg_type,
187 struct server_id server_id,
188 DATA_BLOB *data)
190 /* Flush various caches */
191 flush_caches();
192 reload_services_file();
195 /* React on 'smbcontrol winbindd shutdown' in the same way as on SIGTERM*/
196 static void msg_shutdown(struct messaging_context *msg,
197 void *private_data,
198 uint32_t msg_type,
199 struct server_id server_id,
200 DATA_BLOB *data)
202 do_sigterm = True;
205 static struct winbindd_dispatch_table {
206 enum winbindd_cmd cmd;
207 void (*fn)(struct winbindd_cli_state *state);
208 const char *winbindd_cmd_name;
209 } dispatch_table[] = {
211 /* User functions */
213 { WINBINDD_GETPWNAM, winbindd_getpwnam, "GETPWNAM" },
214 { WINBINDD_GETPWUID, winbindd_getpwuid, "GETPWUID" },
216 { WINBINDD_SETPWENT, winbindd_setpwent, "SETPWENT" },
217 { WINBINDD_ENDPWENT, winbindd_endpwent, "ENDPWENT" },
218 { WINBINDD_GETPWENT, winbindd_getpwent, "GETPWENT" },
220 { WINBINDD_GETGROUPS, winbindd_getgroups, "GETGROUPS" },
221 { WINBINDD_GETUSERSIDS, winbindd_getusersids, "GETUSERSIDS" },
222 { WINBINDD_GETUSERDOMGROUPS, winbindd_getuserdomgroups,
223 "GETUSERDOMGROUPS" },
225 /* Group functions */
227 { WINBINDD_GETGRNAM, winbindd_getgrnam, "GETGRNAM" },
228 { WINBINDD_GETGRGID, winbindd_getgrgid, "GETGRGID" },
229 { WINBINDD_SETGRENT, winbindd_setgrent, "SETGRENT" },
230 { WINBINDD_ENDGRENT, winbindd_endgrent, "ENDGRENT" },
231 { WINBINDD_GETGRENT, winbindd_getgrent, "GETGRENT" },
232 { WINBINDD_GETGRLST, winbindd_getgrent, "GETGRLST" },
234 /* PAM auth functions */
236 { WINBINDD_PAM_AUTH, winbindd_pam_auth, "PAM_AUTH" },
237 { WINBINDD_PAM_AUTH_CRAP, winbindd_pam_auth_crap, "AUTH_CRAP" },
238 { WINBINDD_PAM_CHAUTHTOK, winbindd_pam_chauthtok, "CHAUTHTOK" },
239 { WINBINDD_PAM_LOGOFF, winbindd_pam_logoff, "PAM_LOGOFF" },
240 { WINBINDD_PAM_CHNG_PSWD_AUTH_CRAP, winbindd_pam_chng_pswd_auth_crap, "CHNG_PSWD_AUTH_CRAP" },
242 /* Enumeration functions */
244 { WINBINDD_LIST_USERS, winbindd_list_users, "LIST_USERS" },
245 { WINBINDD_LIST_GROUPS, winbindd_list_groups, "LIST_GROUPS" },
246 { WINBINDD_LIST_TRUSTDOM, winbindd_list_trusted_domains,
247 "LIST_TRUSTDOM" },
248 { WINBINDD_SHOW_SEQUENCE, winbindd_show_sequence, "SHOW_SEQUENCE" },
250 /* SID related functions */
252 { WINBINDD_LOOKUPSID, winbindd_lookupsid, "LOOKUPSID" },
253 { WINBINDD_LOOKUPNAME, winbindd_lookupname, "LOOKUPNAME" },
254 { WINBINDD_LOOKUPRIDS, winbindd_lookuprids, "LOOKUPRIDS" },
256 /* Lookup related functions */
258 { WINBINDD_SID_TO_UID, winbindd_sid_to_uid, "SID_TO_UID" },
259 { WINBINDD_SID_TO_GID, winbindd_sid_to_gid, "SID_TO_GID" },
260 { WINBINDD_UID_TO_SID, winbindd_uid_to_sid, "UID_TO_SID" },
261 { WINBINDD_GID_TO_SID, winbindd_gid_to_sid, "GID_TO_SID" },
262 #if 0 /* DISABLED until we fix the interface in Samba 3.0.26 --jerry */
263 { WINBINDD_SIDS_TO_XIDS, winbindd_sids_to_unixids, "SIDS_TO_XIDS" },
264 #endif /* end DISABLED */
265 { WINBINDD_ALLOCATE_UID, winbindd_allocate_uid, "ALLOCATE_UID" },
266 { WINBINDD_ALLOCATE_GID, winbindd_allocate_gid, "ALLOCATE_GID" },
267 { WINBINDD_SET_MAPPING, winbindd_set_mapping, "SET_MAPPING" },
268 { WINBINDD_SET_HWM, winbindd_set_hwm, "SET_HWMS" },
270 /* Miscellaneous */
272 { WINBINDD_DUMP_MAPS, winbindd_dump_maps, "DUMP_MAPS" },
274 { WINBINDD_CHECK_MACHACC, winbindd_check_machine_acct, "CHECK_MACHACC" },
275 { WINBINDD_PING, winbindd_ping, "PING" },
276 { WINBINDD_INFO, winbindd_info, "INFO" },
277 { WINBINDD_INTERFACE_VERSION, winbindd_interface_version,
278 "INTERFACE_VERSION" },
279 { WINBINDD_DOMAIN_NAME, winbindd_domain_name, "DOMAIN_NAME" },
280 { WINBINDD_DOMAIN_INFO, winbindd_domain_info, "DOMAIN_INFO" },
281 { WINBINDD_NETBIOS_NAME, winbindd_netbios_name, "NETBIOS_NAME" },
282 { WINBINDD_PRIV_PIPE_DIR, winbindd_priv_pipe_dir,
283 "WINBINDD_PRIV_PIPE_DIR" },
284 { WINBINDD_GETDCNAME, winbindd_getdcname, "GETDCNAME" },
286 /* Credential cache access */
287 { WINBINDD_CCACHE_NTLMAUTH, winbindd_ccache_ntlm_auth, "NTLMAUTH" },
289 /* WINS functions */
291 { WINBINDD_WINS_BYNAME, winbindd_wins_byname, "WINS_BYNAME" },
292 { WINBINDD_WINS_BYIP, winbindd_wins_byip, "WINS_BYIP" },
294 /* End of list */
296 { WINBINDD_NUM_CMDS, NULL, "NONE" }
299 static void process_request(struct winbindd_cli_state *state)
301 struct winbindd_dispatch_table *table = dispatch_table;
303 /* Free response data - we may be interrupted and receive another
304 command before being able to send this data off. */
306 SAFE_FREE(state->response.extra_data.data);
308 ZERO_STRUCT(state->response);
310 state->response.result = WINBINDD_PENDING;
311 state->response.length = sizeof(struct winbindd_response);
313 state->mem_ctx = talloc_init("winbind request");
314 if (state->mem_ctx == NULL)
315 return;
317 /* Remember who asked us. */
318 state->pid = state->request.pid;
320 /* Process command */
322 for (table = dispatch_table; table->fn; table++) {
323 if (state->request.cmd == table->cmd) {
324 DEBUG(10,("process_request: request fn %s\n",
325 table->winbindd_cmd_name ));
326 table->fn(state);
327 break;
331 if (!table->fn) {
332 DEBUG(10,("process_request: unknown request fn number %d\n",
333 (int)state->request.cmd ));
334 request_error(state);
339 * A list of file descriptors being monitored by select in the main processing
340 * loop. fd_event->handler is called whenever the socket is readable/writable.
343 static struct fd_event *fd_events = NULL;
345 void add_fd_event(struct fd_event *ev)
347 struct fd_event *match;
349 /* only add unique fd_event structs */
351 for (match=fd_events; match; match=match->next ) {
352 #ifdef DEVELOPER
353 SMB_ASSERT( match != ev );
354 #else
355 if ( match == ev )
356 return;
357 #endif
360 DLIST_ADD(fd_events, ev);
363 void remove_fd_event(struct fd_event *ev)
365 DLIST_REMOVE(fd_events, ev);
369 * Handler for fd_events to complete a read/write request, set up by
370 * setup_async_read/setup_async_write.
373 static void rw_callback(struct fd_event *event, int flags)
375 size_t todo;
376 ssize_t done = 0;
378 todo = event->length - event->done;
380 if (event->flags & EVENT_FD_WRITE) {
381 SMB_ASSERT(flags == EVENT_FD_WRITE);
382 done = sys_write(event->fd,
383 &((char *)event->data)[event->done],
384 todo);
386 if (done <= 0) {
387 event->flags = 0;
388 event->finished(event->private_data, False);
389 return;
393 if (event->flags & EVENT_FD_READ) {
394 SMB_ASSERT(flags == EVENT_FD_READ);
395 done = sys_read(event->fd, &((char *)event->data)[event->done],
396 todo);
398 if (done <= 0) {
399 event->flags = 0;
400 event->finished(event->private_data, False);
401 return;
405 event->done += done;
407 if (event->done == event->length) {
408 event->flags = 0;
409 event->finished(event->private_data, True);
414 * Request an async read/write on a fd_event structure. (*finished) is called
415 * when the request is completed or an error had occurred.
418 void setup_async_read(struct fd_event *event, void *data, size_t length,
419 void (*finished)(void *private_data, BOOL success),
420 void *private_data)
422 SMB_ASSERT(event->flags == 0);
423 event->data = data;
424 event->length = length;
425 event->done = 0;
426 event->handler = rw_callback;
427 event->finished = finished;
428 event->private_data = private_data;
429 event->flags = EVENT_FD_READ;
432 void setup_async_write(struct fd_event *event, void *data, size_t length,
433 void (*finished)(void *private_data, BOOL success),
434 void *private_data)
436 SMB_ASSERT(event->flags == 0);
437 event->data = data;
438 event->length = length;
439 event->done = 0;
440 event->handler = rw_callback;
441 event->finished = finished;
442 event->private_data = private_data;
443 event->flags = EVENT_FD_WRITE;
447 * This is the main event loop of winbind requests. It goes through a
448 * state-machine of 3 read/write requests, 4 if you have extra data to send.
450 * An idle winbind client has a read request of 4 bytes outstanding,
451 * finalizing function is request_len_recv, checking the length. request_recv
452 * then processes the packet. The processing function then at some point has
453 * to call request_finished which schedules sending the response.
456 static void request_len_recv(void *private_data, BOOL success);
457 static void request_recv(void *private_data, BOOL success);
458 static void request_main_recv(void *private_data, BOOL success);
459 static void request_finished(struct winbindd_cli_state *state);
460 void request_finished_cont(void *private_data, BOOL success);
461 static void response_main_sent(void *private_data, BOOL success);
462 static void response_extra_sent(void *private_data, BOOL success);
464 static void response_extra_sent(void *private_data, BOOL success)
466 struct winbindd_cli_state *state =
467 talloc_get_type_abort(private_data, struct winbindd_cli_state);
469 if (state->mem_ctx != NULL) {
470 talloc_destroy(state->mem_ctx);
471 state->mem_ctx = NULL;
474 if (!success) {
475 state->finished = True;
476 return;
479 SAFE_FREE(state->request.extra_data.data);
480 SAFE_FREE(state->response.extra_data.data);
482 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
483 request_len_recv, state);
486 static void response_main_sent(void *private_data, BOOL success)
488 struct winbindd_cli_state *state =
489 talloc_get_type_abort(private_data, struct winbindd_cli_state);
491 if (!success) {
492 state->finished = True;
493 return;
496 if (state->response.length == sizeof(state->response)) {
497 if (state->mem_ctx != NULL) {
498 talloc_destroy(state->mem_ctx);
499 state->mem_ctx = NULL;
502 setup_async_read(&state->fd_event, &state->request,
503 sizeof(uint32), request_len_recv, state);
504 return;
507 setup_async_write(&state->fd_event, state->response.extra_data.data,
508 state->response.length - sizeof(state->response),
509 response_extra_sent, state);
512 static void request_finished(struct winbindd_cli_state *state)
514 setup_async_write(&state->fd_event, &state->response,
515 sizeof(state->response), response_main_sent, state);
518 void request_error(struct winbindd_cli_state *state)
520 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
521 state->response.result = WINBINDD_ERROR;
522 request_finished(state);
525 void request_ok(struct winbindd_cli_state *state)
527 SMB_ASSERT(state->response.result == WINBINDD_PENDING);
528 state->response.result = WINBINDD_OK;
529 request_finished(state);
532 void request_finished_cont(void *private_data, BOOL success)
534 struct winbindd_cli_state *state =
535 talloc_get_type_abort(private_data, struct winbindd_cli_state);
537 if (success)
538 request_ok(state);
539 else
540 request_error(state);
543 static void request_len_recv(void *private_data, BOOL success)
545 struct winbindd_cli_state *state =
546 talloc_get_type_abort(private_data, struct winbindd_cli_state);
548 if (!success) {
549 state->finished = True;
550 return;
553 if (*(uint32 *)(&state->request) != sizeof(state->request)) {
554 DEBUG(0,("request_len_recv: Invalid request size received: %d\n",
555 *(uint32 *)(&state->request)));
556 state->finished = True;
557 return;
560 setup_async_read(&state->fd_event, (uint32 *)(&state->request)+1,
561 sizeof(state->request) - sizeof(uint32),
562 request_main_recv, state);
565 static void request_main_recv(void *private_data, BOOL success)
567 struct winbindd_cli_state *state =
568 talloc_get_type_abort(private_data, struct winbindd_cli_state);
570 if (!success) {
571 state->finished = True;
572 return;
575 if (state->request.extra_len == 0) {
576 state->request.extra_data.data = NULL;
577 request_recv(state, True);
578 return;
581 if ((!state->privileged) &&
582 (state->request.extra_len > WINBINDD_MAX_EXTRA_DATA)) {
583 DEBUG(3, ("Got request with %d bytes extra data on "
584 "unprivileged socket\n", (int)state->request.extra_len));
585 state->request.extra_data.data = NULL;
586 state->finished = True;
587 return;
590 state->request.extra_data.data =
591 SMB_MALLOC_ARRAY(char, state->request.extra_len + 1);
593 if (state->request.extra_data.data == NULL) {
594 DEBUG(0, ("malloc failed\n"));
595 state->finished = True;
596 return;
599 /* Ensure null termination */
600 state->request.extra_data.data[state->request.extra_len] = '\0';
602 setup_async_read(&state->fd_event, state->request.extra_data.data,
603 state->request.extra_len, request_recv, state);
606 static void request_recv(void *private_data, BOOL success)
608 struct winbindd_cli_state *state =
609 talloc_get_type_abort(private_data, struct winbindd_cli_state);
611 if (!success) {
612 state->finished = True;
613 return;
616 process_request(state);
619 /* Process a new connection by adding it to the client connection list */
621 static void new_connection(int listen_sock, BOOL privileged)
623 struct sockaddr_un sunaddr;
624 struct winbindd_cli_state *state;
625 socklen_t len;
626 int sock;
628 /* Accept connection */
630 len = sizeof(sunaddr);
632 do {
633 sock = accept(listen_sock, (struct sockaddr *)&sunaddr, &len);
634 } while (sock == -1 && errno == EINTR);
636 if (sock == -1)
637 return;
639 DEBUG(6,("accepted socket %d\n", sock));
641 /* Create new connection structure */
643 if ((state = TALLOC_ZERO_P(NULL, struct winbindd_cli_state)) == NULL) {
644 close(sock);
645 return;
648 state->sock = sock;
650 state->last_access = time(NULL);
652 state->privileged = privileged;
654 state->fd_event.fd = state->sock;
655 state->fd_event.flags = 0;
656 add_fd_event(&state->fd_event);
658 setup_async_read(&state->fd_event, &state->request, sizeof(uint32),
659 request_len_recv, state);
661 /* Add to connection list */
663 winbindd_add_client(state);
666 /* Remove a client connection from client connection list */
668 static void remove_client(struct winbindd_cli_state *state)
670 /* It's a dead client - hold a funeral */
672 if (state == NULL) {
673 return;
676 /* Close socket */
678 close(state->sock);
680 /* Free any getent state */
682 free_getent_state(state->getpwent_state);
683 free_getent_state(state->getgrent_state);
685 /* We may have some extra data that was not freed if the client was
686 killed unexpectedly */
688 SAFE_FREE(state->response.extra_data.data);
690 if (state->mem_ctx != NULL) {
691 talloc_destroy(state->mem_ctx);
692 state->mem_ctx = NULL;
695 remove_fd_event(&state->fd_event);
697 /* Remove from list and free */
699 winbindd_remove_client(state);
700 TALLOC_FREE(state);
703 /* Shutdown client connection which has been idle for the longest time */
705 static BOOL remove_idle_client(void)
707 struct winbindd_cli_state *state, *remove_state = NULL;
708 time_t last_access = 0;
709 int nidle = 0;
711 for (state = winbindd_client_list(); state; state = state->next) {
712 if (state->response.result != WINBINDD_PENDING &&
713 !state->getpwent_state && !state->getgrent_state) {
714 nidle++;
715 if (!last_access || state->last_access < last_access) {
716 last_access = state->last_access;
717 remove_state = state;
722 if (remove_state) {
723 DEBUG(5,("Found %d idle client connections, shutting down sock %d, pid %u\n",
724 nidle, remove_state->sock, (unsigned int)remove_state->pid));
725 remove_client(remove_state);
726 return True;
729 return False;
732 /* Process incoming clients on listen_sock. We use a tricky non-blocking,
733 non-forking, non-threaded model which allows us to handle many
734 simultaneous connections while remaining impervious to many denial of
735 service attacks. */
737 static int process_loop(int listen_sock, int listen_priv_sock)
739 struct winbindd_cli_state *state;
740 struct fd_event *ev;
741 fd_set r_fds, w_fds;
742 int maxfd, selret;
743 struct timeval timeout, ev_timeout;
745 /* We'll be doing this a lot */
747 /* Handle messages */
749 message_dispatch(winbind_messaging_context());
751 run_events(winbind_event_context(), 0, NULL, NULL);
753 /* refresh the trusted domain cache */
755 rescan_trusted_domains();
757 /* Free up temporary memory */
759 lp_TALLOC_FREE();
760 main_loop_TALLOC_FREE();
762 /* Initialise fd lists for select() */
764 maxfd = MAX(listen_sock, listen_priv_sock);
766 FD_ZERO(&r_fds);
767 FD_ZERO(&w_fds);
768 FD_SET(listen_sock, &r_fds);
769 FD_SET(listen_priv_sock, &r_fds);
771 timeout.tv_sec = WINBINDD_ESTABLISH_LOOP;
772 timeout.tv_usec = 0;
774 /* Check for any event timeouts. */
775 if (get_timed_events_timeout(winbind_event_context(), &ev_timeout)) {
776 timeout = timeval_min(&timeout, &ev_timeout);
779 /* Set up client readers and writers */
781 state = winbindd_client_list();
783 while (state) {
785 struct winbindd_cli_state *next = state->next;
787 /* Dispose of client connection if it is marked as
788 finished */
790 if (state->finished)
791 remove_client(state);
793 state = next;
796 for (ev = fd_events; ev; ev = ev->next) {
797 if (ev->flags & EVENT_FD_READ) {
798 FD_SET(ev->fd, &r_fds);
799 maxfd = MAX(ev->fd, maxfd);
801 if (ev->flags & EVENT_FD_WRITE) {
802 FD_SET(ev->fd, &w_fds);
803 maxfd = MAX(ev->fd, maxfd);
807 /* Call select */
809 selret = sys_select(maxfd + 1, &r_fds, &w_fds, NULL, &timeout);
811 if (selret == 0) {
812 goto no_fds_ready;
815 if (selret == -1) {
816 if (errno == EINTR) {
817 goto no_fds_ready;
820 /* Select error, something is badly wrong */
822 perror("select");
823 exit(1);
826 /* selret > 0 */
828 ev = fd_events;
829 while (ev != NULL) {
830 struct fd_event *next = ev->next;
831 int flags = 0;
832 if (FD_ISSET(ev->fd, &r_fds))
833 flags |= EVENT_FD_READ;
834 if (FD_ISSET(ev->fd, &w_fds))
835 flags |= EVENT_FD_WRITE;
836 if (flags)
837 ev->handler(ev, flags);
838 ev = next;
841 if (FD_ISSET(listen_sock, &r_fds)) {
842 while (winbindd_num_clients() >
843 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
844 DEBUG(5,("winbindd: Exceeding %d client "
845 "connections, removing idle "
846 "connection.\n",
847 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
848 if (!remove_idle_client()) {
849 DEBUG(0,("winbindd: Exceeding %d "
850 "client connections, no idle "
851 "connection found\n",
852 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
853 break;
856 /* new, non-privileged connection */
857 new_connection(listen_sock, False);
860 if (FD_ISSET(listen_priv_sock, &r_fds)) {
861 while (winbindd_num_clients() >
862 WINBINDD_MAX_SIMULTANEOUS_CLIENTS - 1) {
863 DEBUG(5,("winbindd: Exceeding %d client "
864 "connections, removing idle "
865 "connection.\n",
866 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
867 if (!remove_idle_client()) {
868 DEBUG(0,("winbindd: Exceeding %d "
869 "client connections, no idle "
870 "connection found\n",
871 WINBINDD_MAX_SIMULTANEOUS_CLIENTS));
872 break;
875 /* new, privileged connection */
876 new_connection(listen_priv_sock, True);
879 no_fds_ready:
881 #if 0
882 winbindd_check_cache_size(time(NULL));
883 #endif
885 /* Check signal handling things */
887 if (do_sigterm)
888 terminate();
890 if (do_sighup) {
892 DEBUG(3, ("got SIGHUP\n"));
894 flush_caches();
895 reload_services_file();
897 do_sighup = False;
900 if (do_sigusr2) {
901 print_winbindd_status();
902 do_sigusr2 = False;
905 if (do_sigchld) {
906 pid_t pid;
908 do_sigchld = False;
910 while ((pid = sys_waitpid(-1, NULL, WNOHANG)) > 0) {
911 winbind_child_died(pid);
916 return winbindd_num_clients();
919 static void winbindd_process_loop(enum smb_server_mode server_mode)
921 int idle_timeout_sec;
922 struct timeval starttime;
923 int listen_public, listen_priv;
925 errno = 0;
926 if (!winbindd_init_sockets(&listen_public, &listen_priv,
927 &idle_timeout_sec)) {
928 terminate();
931 starttime = timeval_current();
933 if (listen_public == -1 || listen_priv == -1) {
934 DEBUG(0, ("failed to open winbindd pipes: %s\n",
935 errno ? strerror(errno) : "unknown error"));
936 terminate();
939 for (;;) {
940 int clients = process_loop(listen_public, listen_priv);
942 /* Don't bother figuring out the idle time if we won't be
943 * timing out anyway.
945 if (idle_timeout_sec < 0) {
946 continue;
949 if (clients == 0 && server_mode == SERVER_MODE_FOREGROUND) {
950 struct timeval now;
952 now = timeval_current();
953 if (timeval_elapsed2(&starttime, &now) >
954 (double)idle_timeout_sec) {
955 DEBUG(0, ("idle for %d secs, exitting\n",
956 idle_timeout_sec));
957 terminate();
959 } else {
960 starttime = timeval_current();
965 /* Main function */
967 int main(int argc, char **argv, char **envp)
969 pstring logfile;
970 BOOL log_stdout = False;
971 BOOL no_process_group = False;
973 enum smb_server_mode server_mode = SERVER_MODE_DAEMON;
975 struct poptOption long_options[] = {
976 POPT_AUTOHELP
977 { "stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
978 { "foreground", 'F', POPT_ARG_VAL, &server_mode, SERVER_MODE_FOREGROUND, "Daemon in foreground mode" },
979 { "no-process-group", 0, POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
980 { "interactive", 'i', POPT_ARG_VAL, &server_mode, SERVER_MODE_INTERACTIVE, "Interactive mode" },
981 { "no-caching", 'n', POPT_ARG_VAL, &opt_nocache, True, "Disable caching" },
982 POPT_COMMON_SAMBA
983 POPT_TABLEEND
985 poptContext pc;
986 int opt;
988 /* glibc (?) likes to print "User defined signal 1" and exit if a
989 SIGUSR[12] is received before a handler is installed */
991 CatchSignal(SIGUSR1, SIG_IGN);
992 CatchSignal(SIGUSR2, SIG_IGN);
994 fault_setup((void (*)(void *))fault_quit );
995 dump_core_setup("winbindd");
997 load_case_tables();
999 /* Initialise for running in non-root mode */
1001 sec_init();
1003 set_remote_machine_name("winbindd", False);
1005 /* Set environment variable so we don't recursively call ourselves.
1006 This may also be useful interactively. */
1008 if ( !winbind_off() ) {
1009 DEBUG(0,("Failed to disable recusive winbindd calls. Exiting.\n"));
1010 exit(1);
1013 /* Initialise samba/rpc client stuff */
1015 pc = poptGetContext("winbindd", argc, (const char **)argv, long_options,
1016 POPT_CONTEXT_KEEP_FIRST);
1018 while ((opt = poptGetNextOpt(pc)) != -1) {}
1020 if (server_mode == SERVER_MODE_INTERACTIVE) {
1021 log_stdout = True;
1022 if (DEBUGLEVEL >= 9) {
1023 talloc_enable_leak_report();
1027 if (log_stdout && server_mode == SERVER_MODE_DAEMON) {
1028 printf("Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n");
1029 poptPrintUsage(pc, stderr, 0);
1030 exit(1);
1033 if (!override_logfile) {
1034 pstr_sprintf(logfile, "%s/log.winbindd", dyn_LOGFILEBASE);
1035 lp_set_logfile(logfile);
1037 setup_logging("winbindd", log_stdout);
1038 reopen_logs();
1040 DEBUG(1, ("winbindd version %s started.\n%s\n",
1041 SAMBA_VERSION_STRING,
1042 COPYRIGHT_STARTUP_MESSAGE) );
1044 if (!reload_services_file()) {
1045 DEBUG(0, ("error opening config file\n"));
1046 exit(1);
1049 if (!directory_exist(lp_lockdir(), NULL)) {
1050 mkdir(lp_lockdir(), 0755);
1053 /* Setup names. */
1055 if (!init_names())
1056 exit(1);
1058 load_interfaces();
1060 if (!secrets_init()) {
1062 DEBUG(0,("Could not initialize domain trust account secrets. Giving up\n"));
1063 return False;
1066 /* Enable netbios namecache */
1068 namecache_enable();
1070 /* Winbind daemon initialisation */
1072 if ( ! NT_STATUS_IS_OK(idmap_init_cache()) ) {
1073 DEBUG(1, ("Could not init idmap cache!\n"));
1076 /* Unblock all signals we are interested in as they may have been
1077 blocked by the parent process. */
1079 BlockSignals(False, SIGINT);
1080 BlockSignals(False, SIGQUIT);
1081 BlockSignals(False, SIGTERM);
1082 BlockSignals(False, SIGUSR1);
1083 BlockSignals(False, SIGUSR2);
1084 BlockSignals(False, SIGHUP);
1085 BlockSignals(False, SIGCHLD);
1087 /* Setup signal handlers */
1089 CatchSignal(SIGINT, termination_handler); /* Exit on these sigs */
1090 CatchSignal(SIGQUIT, termination_handler);
1091 CatchSignal(SIGTERM, termination_handler);
1092 CatchSignal(SIGCHLD, sigchld_handler);
1094 CatchSignal(SIGPIPE, SIG_IGN); /* Ignore sigpipe */
1096 CatchSignal(SIGUSR2, sigusr2_handler); /* Debugging sigs */
1097 CatchSignal(SIGHUP, sighup_handler);
1099 if (server_mode == SERVER_MODE_DAEMON) {
1100 DEBUG( 3, ( "Becoming a daemon.\n" ) );
1101 become_daemon(True, no_process_group);
1102 } else if (server_mode == SERVER_MODE_FOREGROUND) {
1103 become_daemon(False, no_process_group);
1106 pidfile_create("winbindd");
1108 /* Ensure all cache and idmap caches are consistent
1109 before we startup. */
1111 if (winbindd_validate_cache()) {
1112 /* We have a bad cache, but luckily we
1113 just deleted it. Restart ourselves */
1114 int i;
1115 /* Ensure we have no open low fd's. */
1116 for (i = 3; i < 100; i++) {
1117 close(i);
1119 return execve(argv[0], argv, envp);
1122 #if HAVE_SETPGID
1124 * If we're interactive we want to set our own process group for
1125 * signal management.
1127 if (server_mode == SERVER_MODE_INTERACTIVE && !no_process_group) {
1128 setpgid( (pid_t)0, (pid_t)0);
1130 #endif
1132 TimeInit();
1134 /* Initialise messaging system */
1136 if (winbind_messaging_context() == NULL) {
1137 DEBUG(0, ("unable to initialize messaging system\n"));
1138 exit(1);
1141 /* Initialize cache (ensure version is correct). */
1142 if (!initialize_winbindd_cache()) {
1143 exit(1);
1146 /* React on 'smbcontrol winbindd reload-config' in the same way
1147 as to SIGHUP signal */
1148 messaging_register(winbind_messaging_context(), NULL,
1149 MSG_SMB_CONF_UPDATED, msg_reload_services);
1150 messaging_register(winbind_messaging_context(), NULL,
1151 MSG_SHUTDOWN, msg_shutdown);
1153 /* Handle online/offline messages. */
1154 messaging_register(winbind_messaging_context(), NULL,
1155 MSG_WINBIND_OFFLINE, winbind_msg_offline);
1156 messaging_register(winbind_messaging_context(), NULL,
1157 MSG_WINBIND_ONLINE, winbind_msg_online);
1158 messaging_register(winbind_messaging_context(), NULL,
1159 MSG_WINBIND_ONLINESTATUS, winbind_msg_onlinestatus);
1161 messaging_register(winbind_messaging_context(), NULL,
1162 MSG_DUMP_EVENT_LIST, winbind_msg_dump_event_list);
1164 poptFreeContext(pc);
1166 netsamlogon_cache_init(); /* Non-critical */
1168 /* clear the cached list of trusted domains */
1170 wcache_tdc_clear();
1172 if (!init_domain_list()) {
1173 DEBUG(0,("unable to initalize domain list\n"));
1174 exit(1);
1177 init_idmap_child();
1179 smb_nscd_flush_user_cache();
1180 smb_nscd_flush_group_cache();
1182 /* Loop waiting for requests */
1183 winbindd_process_loop(server_mode);
1185 return 0;