Example #1
0
 int main(int argc,const char *argv[])
{
	/* shall I run as a daemon */
	bool is_daemon = false;
	bool interactive = false;
	bool Fork = true;
	bool no_process_group = false;
	bool log_stdout = false;
	char *ports = NULL;
	char *profile_level = NULL;
	int opt;
	poptContext pc;
	bool print_build_options = False;
        enum {
		OPT_DAEMON = 1000,
		OPT_INTERACTIVE,
		OPT_FORK,
		OPT_NO_PROCESS_GROUP,
		OPT_LOG_STDOUT
	};
	struct poptOption long_options[] = {
	POPT_AUTOHELP
	{"daemon", 'D', POPT_ARG_NONE, NULL, OPT_DAEMON, "Become a daemon (default)" },
	{"interactive", 'i', POPT_ARG_NONE, NULL, OPT_INTERACTIVE, "Run interactive (not a daemon)"},
	{"foreground", 'F', POPT_ARG_NONE, NULL, OPT_FORK, "Run daemon in foreground (for daemontools, etc.)" },
	{"no-process-group", '\0', POPT_ARG_NONE, NULL, OPT_NO_PROCESS_GROUP, "Don't create a new process group" },
	{"log-stdout", 'S', POPT_ARG_NONE, NULL, OPT_LOG_STDOUT, "Log to stdout" },
	{"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
	{"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
	{"profiling-level", 'P', POPT_ARG_STRING, &profile_level, 0, "Set profiling level","PROFILE_LEVEL"},
	POPT_COMMON_SAMBA
	POPT_COMMON_DYNCONFIG
	POPT_TABLEEND
	};
	struct smbd_parent_context *parent = NULL;
	TALLOC_CTX *frame;
	NTSTATUS status;
	uint64_t unique_id;
	struct tevent_context *ev_ctx;
	struct messaging_context *msg_ctx;

	/*
	 * Do this before any other talloc operation
	 */
	talloc_enable_null_tracking();
	frame = talloc_stackframe();

	setup_logging(argv[0], DEBUG_DEFAULT_STDOUT);

	load_case_tables();

	smbd_init_globals();

	TimeInit();

#ifdef HAVE_SET_AUTH_PARAMETERS
	set_auth_parameters(argc,argv);
#endif

	pc = poptGetContext("smbd", argc, argv, long_options, 0);
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt)  {
		case OPT_DAEMON:
			is_daemon = true;
			break;
		case OPT_INTERACTIVE:
			interactive = true;
			break;
		case OPT_FORK:
			Fork = false;
			break;
		case OPT_NO_PROCESS_GROUP:
			no_process_group = true;
			break;
		case OPT_LOG_STDOUT:
			log_stdout = true;
			break;
		case 'b':
			print_build_options = True;
			break;
		default:
			d_fprintf(stderr, "\nInvalid option %s: %s\n\n",
				  poptBadOption(pc, 0), poptStrerror(opt));
			poptPrintUsage(pc, stderr, 0);
			exit(1);
		}
	}
	poptFreeContext(pc);

	if (interactive) {
		Fork = False;
		log_stdout = True;
	}

	if (log_stdout) {
		setup_logging(argv[0], DEBUG_STDOUT);
	} else {
		setup_logging(argv[0], DEBUG_FILE);
	}

	if (print_build_options) {
		build_options(True); /* Display output to screen as well as debug */
		exit(0);
	}

#ifdef HAVE_SETLUID
	/* needed for SecureWare on SCO */
	setluid(0);
#endif

	set_remote_machine_name("smbd", False);

	if (interactive && (DEBUGLEVEL >= 9)) {
		talloc_enable_leak_report();
	}

	if (log_stdout && Fork) {
		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
		exit(1);
	}

	/* we want to re-seed early to prevent time delays causing
           client problems at a later date. (tridge) */
	generate_random_buffer(NULL, 0);

	/* get initial effective uid and gid */
	sec_init();

	/* make absolutely sure we run as root - to handle cases where people
	   are crazy enough to have it setuid */
	gain_root_privilege();
	gain_root_group_privilege();

	fault_setup();
	dump_core_setup("smbd", lp_logfile());

	/* we are never interested in SIGPIPE */
	BlockSignals(True,SIGPIPE);

#if defined(SIGFPE)
	/* we are never interested in SIGFPE */
	BlockSignals(True,SIGFPE);
#endif

#if defined(SIGUSR2)
	/* We are no longer interested in USR2 */
	BlockSignals(True,SIGUSR2);
#endif

	/* POSIX demands that signals are inherited. If the invoking process has
	 * these signals masked, we will have problems, as we won't recieve them. */
	BlockSignals(False, SIGHUP);
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGTERM);

	/* Ensure we leave no zombies until we
	 * correctly set up child handling below. */

	CatchChild();

	/* we want total control over the permissions on created files,
	   so set our umask to 0 */
	umask(0);

	reopen_logs();

	DEBUG(0,("smbd version %s started.\n", samba_version_string()));
	DEBUGADD(0,("%s\n", COPYRIGHT_STARTUP_MESSAGE));

	DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
		 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));

	/* Output the build options to the debug log */ 
	build_options(False);

	if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
		DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
		exit(1);
	}

	if (!lp_load_initial_only(get_dyn_CONFIGFILE())) {
		DEBUG(0, ("error opening config file '%s'\n", get_dyn_CONFIGFILE()));
		exit(1);
	}

	/* Init the security context and global current_user */
	init_sec_ctx();

	/*
	 * Initialize the event context. The event context needs to be
	 * initialized before the messaging context, cause the messaging
	 * context holds an event context.
	 * FIXME: This should be s3_tevent_context_init()
	 */
	ev_ctx = server_event_context();
	if (ev_ctx == NULL) {
		exit(1);
	}

	/*
	 * Init the messaging context
	 * FIXME: This should only call messaging_init()
	 */
	msg_ctx = server_messaging_context();
	if (msg_ctx == NULL) {
		exit(1);
	}

	/*
	 * Reloading of the printers will not work here as we don't have a
	 * server info and rpc services set up. It will be called later.
	 */
	if (!reload_services(NULL, -1, False)) {
		exit(1);
	}

	/* ...NOTE... Log files are working from this point! */

	DEBUG(3,("loaded services\n"));

	init_structs();

#ifdef WITH_PROFILE
	if (!profile_setup(msg_ctx, False)) {
		DEBUG(0,("ERROR: failed to setup profiling\n"));
		return -1;
	}
	if (profile_level != NULL) {
		int pl = atoi(profile_level);
		struct server_id src;

		DEBUG(1, ("setting profiling level: %s\n",profile_level));
		src.pid = getpid();
		set_profile_level(pl, src);
	}
#endif

	if (!is_daemon && !is_a_socket(0)) {
		if (!interactive)
			DEBUG(0,("standard input is not a socket, assuming -D option\n"));

		/*
		 * Setting is_daemon here prevents us from eventually calling
		 * the open_sockets_inetd()
		 */

		is_daemon = True;
	}

	if (is_daemon && !interactive) {
		DEBUG( 3, ( "Becoming a daemon.\n" ) );
		become_daemon(Fork, no_process_group, log_stdout);
	}

        generate_random_buffer((uint8_t *)&unique_id, sizeof(unique_id));
        set_my_unique_id(unique_id);

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for
	 * signal management.
	 */
	if (interactive && !no_process_group)
		setpgid( (pid_t)0, (pid_t)0);
#endif

	if (!directory_exist(lp_lockdir()))
		mkdir(lp_lockdir(), 0755);

	if (is_daemon)
		pidfile_create("smbd");

	status = reinit_after_fork(msg_ctx,
				   ev_ctx,
				   procid_self(), false);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("reinit_after_fork() failed\n"));
		exit(1);
	}

	smbd_server_conn->msg_ctx = msg_ctx;

	smbd_setup_sig_term_handler();
	smbd_setup_sig_hup_handler(ev_ctx,
				   msg_ctx);

	/* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */

	if (smbd_memcache() == NULL) {
		exit(1);
	}

	memcache_set_global(smbd_memcache());

	/* Initialise the password backed before the global_sam_sid
	   to ensure that we fetch from ldap before we make a domain sid up */

	if(!initialize_password_db(false, ev_ctx))
		exit(1);

	if (!secrets_init()) {
		DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
		exit(1);
	}

	if (lp_server_role() == ROLE_DOMAIN_BDC || lp_server_role() == ROLE_DOMAIN_PDC) {
		struct loadparm_context *lp_ctx = loadparm_init_s3(NULL, loadparm_s3_context());
		if (!open_schannel_session_store(NULL, lp_ctx)) {
			DEBUG(0,("ERROR: Samba cannot open schannel store for secured NETLOGON operations.\n"));
			exit(1);
		}
		TALLOC_FREE(lp_ctx);
	}

	if(!get_global_sam_sid()) {
		DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
		exit(1);
	}

	if (!sessionid_init()) {
		exit(1);
	}

	if (!connections_init(True))
		exit(1);

	if (!locking_init())
		exit(1);

	if (!messaging_tdb_parent_init(ev_ctx)) {
		exit(1);
	}

	if (!notify_internal_parent_init(ev_ctx)) {
		exit(1);
	}

	if (!serverid_parent_init(ev_ctx)) {
		exit(1);
	}

	if (!W_ERROR_IS_OK(registry_init_full()))
		exit(1);

	/* Open the share_info.tdb here, so we don't have to open
	   after the fork on every single connection.  This is a small
	   performance improvment and reduces the total number of system
	   fds used. */
	if (!share_info_db_init()) {
		DEBUG(0,("ERROR: failed to load share info db.\n"));
		exit(1);
	}

	status = init_system_info();
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(1, ("ERROR: failed to setup system user info: %s.\n",
			  nt_errstr(status)));
		return -1;
	}

	if (!init_guest_info()) {
		DEBUG(0,("ERROR: failed to setup guest info.\n"));
		return -1;
	}

	if (!file_init(smbd_server_conn)) {
		DEBUG(0, ("ERROR: file_init failed\n"));
		return -1;
	}

	/* This MUST be done before start_epmd() because otherwise
	 * start_epmd() forks and races against dcesrv_ep_setup() to
	 * call directory_create_or_exist() */
	if (!directory_create_or_exist(lp_ncalrpc_dir(), geteuid(), 0755)) {
		DEBUG(0, ("Failed to create pipe directory %s - %s\n",
			  lp_ncalrpc_dir(), strerror(errno)));
		return -1;
	}

	if (is_daemon && !interactive) {
		if (rpc_epmapper_daemon() == RPC_DAEMON_FORK) {
			start_epmd(ev_ctx, msg_ctx);
		}
	}

	if (!dcesrv_ep_setup(ev_ctx, msg_ctx)) {
		exit(1);
	}

	/* only start other daemons if we are running as a daemon
	 * -- bad things will happen if smbd is launched via inetd
	 *  and we fork a copy of ourselves here */
	if (is_daemon && !interactive) {

		if (rpc_lsasd_daemon() == RPC_DAEMON_FORK) {
			start_lsasd(ev_ctx, msg_ctx);
		}

		if (!_lp_disable_spoolss() &&
		    (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
			bool bgq = lp_parm_bool(-1, "smbd", "backgroundqueue", true);

			if (!printing_subsystem_init(ev_ctx, msg_ctx, true, bgq)) {
				exit(1);
			}
		}
	} else if (!_lp_disable_spoolss() &&
		   (rpc_spoolss_daemon() != RPC_DAEMON_DISABLED)) {
		if (!printing_subsystem_init(ev_ctx, msg_ctx, false, false)) {
			exit(1);
		}
	}

	if (!is_daemon) {
		/* inetd mode */
		TALLOC_FREE(frame);

		/* Started from inetd. fd 0 is the socket. */
		/* We will abort gracefully when the client or remote system
		   goes away */
		smbd_server_conn->sock = dup(0);

		/* close our standard file descriptors */
		if (!debug_get_output_is_stdout()) {
			close_low_fds(False); /* Don't close stderr */
		}

#ifdef HAVE_ATEXIT
		atexit(killkids);
#endif

	        /* Stop zombies */
		smbd_setup_sig_chld_handler(ev_ctx);

		smbd_process(ev_ctx, smbd_server_conn);

		exit_server_cleanly(NULL);
		return(0);
	}

	parent = talloc_zero(ev_ctx, struct smbd_parent_context);
	if (!parent) {
		exit_server("talloc(struct smbd_parent_context) failed");
	}
	parent->interactive = interactive;

	if (!open_sockets_smbd(parent, ev_ctx, msg_ctx, ports))
		exit_server("open_sockets_smbd() failed");

	/* do a printer update now that all messaging has been set up,
	 * before we allow clients to start connecting */
	printing_subsystem_update(ev_ctx, msg_ctx, false);

	TALLOC_FREE(frame);
	/* make sure we always have a valid stackframe */
	frame = talloc_stackframe();

	smbd_parent_loop(ev_ctx, parent);

	exit_server_cleanly(NULL);
	TALLOC_FREE(frame);
	return(0);
}
Example #2
0
/* show the current server status */
void status_page(void)
{
	const char *v;
	int autorefresh=0;
	int refresh_interval=30;
	TDB_CONTEXT *tdb;
	int nr_running=0;
	BOOL waitup = False;

	smbd_pid = pidfile_pid("smbd");

	if (cgi_variable("smbd_restart") || cgi_variable("all_restart")) {
		stop_smbd();
		start_smbd();
		waitup=True;
	}

	if (cgi_variable("smbd_start") || cgi_variable("all_start")) {
		start_smbd();
		waitup=True;
	}

	if (cgi_variable("smbd_stop") || cgi_variable("all_stop")) {
		stop_smbd();
		waitup=True;
	}

	if (cgi_variable("nmbd_restart") || cgi_variable("all_restart")) {
		stop_nmbd();
		start_nmbd();
		waitup=True;
	}
	if (cgi_variable("nmbd_start") || cgi_variable("all_start")) {
		start_nmbd();
		waitup=True;
	}

	if (cgi_variable("nmbd_stop")|| cgi_variable("all_stop")) {
		stop_nmbd();
		waitup=True;
	}

#ifdef WITH_WINBIND
	if (cgi_variable("winbindd_restart") || cgi_variable("all_restart")) {
		stop_winbindd();
		start_winbindd();
		waitup=True;
	}

	if (cgi_variable("winbindd_start") || cgi_variable("all_start")) {
		start_winbindd();
		waitup=True;
	}

	if (cgi_variable("winbindd_stop") || cgi_variable("all_stop")) {
		stop_winbindd();
		waitup=True;
	}
#endif
	/* wait for daemons to start/stop */
	if (waitup)
		sleep(SLEEP_TIME);
	
	if (cgi_variable("autorefresh")) {
		autorefresh = 1;
	} else if (cgi_variable("norefresh")) {
		autorefresh = 0;
	} else if (cgi_variable("refresh")) {
		autorefresh = 1;
	}

	if ((v=cgi_variable("refresh_interval"))) {
		refresh_interval = atoi(v);
	}

	if (cgi_variable("show_client_in_col_1")) {
		PID_or_Machine = 1;
	}

	if (cgi_variable("show_pid_in_col_1")) {
		PID_or_Machine = 0;
	}

	tdb = tdb_open_log(lock_path("connections.tdb"), 0, TDB_DEFAULT, O_RDONLY, 0);
	if (tdb) tdb_traverse(tdb, traverse_fn1, NULL);
 
	initPid2Machine ();

	printf("<H2>%s</H2>\n", _("Server Status"));

	printf("<FORM method=post>\n");

	if (!autorefresh) {
		printf("<input type=submit value=\"%s\" name=\"autorefresh\">\n", _("Auto Refresh"));
		printf("<br>%s", _("Refresh Interval: "));
		printf("<input type=text size=2 name=\"refresh_interval\" value=\"%d\">\n", 
		       refresh_interval);
	} else {
		printf("<input type=submit value=\"%s\" name=\"norefresh\">\n", _("Stop Refreshing"));
		printf("<br>%s%d\n", _("Refresh Interval: "), refresh_interval);
		printf("<input type=hidden name=\"refresh\" value=\"1\">\n");
	}

	printf("<p>\n");

	if (!tdb) {
		/* open failure either means no connections have been
                   made */
	}


	printf("<table>\n");

	printf("<tr><td>%s</td><td>%s</td></tr>", _("version:"), SAMBA_VERSION_STRING);

	fflush(stdout);
	printf("<tr><td>%s</td><td>%s</td>\n", _("smbd:"), smbd_running()?_("running"):_("not running"));
	if (geteuid() == 0) {
	    if (smbd_running()) {
		nr_running++;
		printf("<td><input type=submit name=\"smbd_stop\" value=\"%s\"></td>\n", _("Stop smbd"));
	    } else {
		printf("<td><input type=submit name=\"smbd_start\" value=\"%s\"></td>\n", _("Start smbd"));
	    }
	    printf("<td><input type=submit name=\"smbd_restart\" value=\"%s\"></td>\n", _("Restart smbd"));
	}
	printf("</tr>\n");

	fflush(stdout);
	printf("<tr><td>%s</td><td>%s</td>\n", _("nmbd:"), nmbd_running()?_("running"):_("not running"));
	if (geteuid() == 0) {
	    if (nmbd_running()) {
		nr_running++;
		printf("<td><input type=submit name=\"nmbd_stop\" value=\"%s\"></td>\n", _("Stop nmbd"));
	    } else {
		printf("<td><input type=submit name=\"nmbd_start\" value=\"%s\"></td>\n", _("Start nmbd"));
	    }
	    printf("<td><input type=submit name=\"nmbd_restart\" value=\"%s\"></td>\n", _("Restart nmbd"));    
	}
	printf("</tr>\n");

#ifdef WITH_WINBIND
	fflush(stdout);
	printf("<tr><td>%s</td><td>%s</td>\n", _("winbindd:"), winbindd_running()?_("running"):_("not running"));
	if (geteuid() == 0) {
	    if (winbindd_running()) {
		nr_running++;
		printf("<td><input type=submit name=\"winbindd_stop\" value=\"%s\"></td>\n", _("Stop winbindd"));
	    } else {
		printf("<td><input type=submit name=\"winbindd_start\" value=\"%s\"></td>\n", _("Start winbindd"));
	    }
	    printf("<td><input type=submit name=\"winbindd_restart\" value=\"%s\"></td>\n", _("Restart winbindd"));
	}
	printf("</tr>\n");
#endif

	if (geteuid() == 0) {
	    printf("<tr><td></td><td></td>\n");
	    if (nr_running >= 1) {
	        /* stop, restart all */
		printf("<td><input type=submit name=\"all_stop\" value=\"%s\"></td>\n", _("Stop All"));
		printf("<td><input type=submit name=\"all_restart\" value=\"%s\"></td>\n", _("Restart All"));
	    }
	    else if (nr_running == 0) {
	    	/* start all */
		printf("<td><input type=submit name=\"all_start\" value=\"%s\"></td>\n", _("Start All"));
	    }
	    printf("</tr>\n");
	}
	printf("</table>\n");
	fflush(stdout);

	printf("<p><h3>%s</h3>\n", _("Active Connections"));
	printf("<table border=1>\n");
	printf("<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th>\n", _("PID"), _("Client"), _("IP address"), _("Date"));
	if (geteuid() == 0) {
		printf("<th>%s</th>\n", _("Kill"));
	}
	printf("</tr>\n");

	if (tdb) tdb_traverse(tdb, traverse_fn2, NULL);

	printf("</table><p>\n");

	printf("<p><h3>%s</h3>\n", _("Active Shares"));
	printf("<table border=1>\n");
	printf("<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr>\n\n",
		_("Share"), _("User"), _("Group"), _("PID"), _("Client"), _("Date"));

	if (tdb) tdb_traverse(tdb, traverse_fn3, NULL);

	printf("</table><p>\n");

	printf("<h3>%s</h3>\n", _("Open Files"));
	printf("<table border=1>\n");
	printf("<tr><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th><th>%s</th></tr>\n", _("PID"), _("Sharing"), _("R/W"), _("Oplock"), _("File"), _("Date"));

	locking_init(1);
	share_mode_forall(print_share_mode);
	locking_end();
	printf("</table>\n");

	if (tdb) tdb_close(tdb);

	printf("<br><input type=submit name=\"show_client_in_col_1\" value=\"%s\">\n", _("Show Client in col 1"));
	printf("<input type=submit name=\"show_pid_in_col_1\" value=\"%s\">\n", _("Show PID in col 1"));

	printf("</FORM>\n");

	if (autorefresh) {
		/* this little JavaScript allows for automatic refresh
                   of the page. There are other methods but this seems
                   to be the best alternative */
		printf("<script language=\"JavaScript\">\n");
		printf("<!--\nsetTimeout('window.location.replace(\"%s/status?refresh_interval=%d&refresh=1\")', %d)\n", 
		       cgi_baseurl(),
		       refresh_interval,
		       refresh_interval*1000);
		printf("//-->\n</script>\n");
	}
}
Example #3
0
 int main(int argc, char *argv[])
{
  FILE *f;
  pstring fname;
  int uid, c;
  static pstring servicesf = CONFIGFILE;
  extern char *optarg;
  int verbose = 0, brief =0;
  BOOL processes_only=False;
  int last_pid=0;
  struct session_record *ptr;


  TimeInit();
  setup_logging(argv[0],True);

  charset_initialise();

  DEBUGLEVEL = 0;
  dbf = fopen("/dev/null","w");

  if (getuid() != geteuid()) {
    printf("smbstatus should not be run setuid\n");
    return(1);
  }

  while ((c = getopt(argc, argv, "pds:u:b")) != EOF) {
    switch (c) {
    case 'b':
      brief = 1;
      break;
    case 'd':
      verbose = 1;
      break;
    case 'p':
      processes_only = 1;
      break;
    case 's':
      pstrcpy(servicesf, optarg);
      break;
    case 'u':                                       /* added by OH */
      Ucrit_addUsername(optarg);                    /* added by OH */
      break;
    default:
      fprintf(stderr, "Usage: %s [-d] [-p] [-s configfile] [-u username]\n", *argv); /* changed by OH */
      return (-1);
    }
  }

  get_myname(myhostname, NULL);

  if (!lp_load(servicesf,False)) {
    fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
    return (-1);
  }

  if (verbose) {
    printf("using configfile = %s\n", servicesf);
    printf("lockdir = %s\n", *lp_lockdir() ? lp_lockdir() : "NULL");
  }

  pstrcpy(fname,lp_lockdir());
  standard_sub_basic(fname);
  trim_string(fname,"","/");
  pstrcat(fname,"/STATUS..LCK");

  f = fopen(fname,"r");
  if (!f) {
    printf("Couldn't open status file %s\n",fname);
    if (!lp_status(-1))
      printf("You need to have status=yes in your smb config file\n");
    return(0);
  }
  else if (verbose) {
    printf("Opened status file %s\n", fname);
  }

  uid = getuid();

  if (!processes_only) {
    printf("\nSamba version %s\n",VERSION);

    if (brief)
    {
      printf("PID     Username  Machine                       Time logged in\n");
      printf("-------------------------------------------------------------------\n");
    }
    else
    {
      printf("Service      uid      gid      pid     machine\n");
      printf("----------------------------------------------\n");
    }
  }

  while (!feof(f))
    {
      if (fread(&crec,sizeof(crec),1,f) != 1)
	break;
      if ( crec.magic == 0x280267 && process_exists(crec.pid) 
           && Ucrit_checkUsername(uidtoname(crec.uid))                      /* added by OH */
         )
      {
        if (brief)
        {
	  ptr=srecs;
	  while (ptr!=NULL)
	  {
	    if ((ptr->pid==crec.pid)&&(strncmp(ptr->machine,crec.machine,30)==0)) 
	    {
	      if (ptr->start > crec.start)
		ptr->start=crec.start;
	      break;
	    }
	    ptr=ptr->next;
	  }
	  if (ptr==NULL)
	  {
	    ptr=(struct session_record *) malloc(sizeof(struct session_record));
	    ptr->uid=crec.uid;
	    ptr->pid=crec.pid;
	    ptr->start=crec.start;
	    strncpy(ptr->machine,crec.machine,30);
	    ptr->machine[30]='\0';
	    ptr->next=srecs;
	    srecs=ptr;
	  }
        }
        else
        {
	  Ucrit_addPid(crec.pid);                                             /* added by OH */
	  if (processes_only) {
	    if (last_pid != crec.pid)
	      printf("%d\n",crec.pid);
	    last_pid = crec.pid; /* XXXX we can still get repeats, have to
				    add a sort at some time */
	  }
	  else	  
	    printf("%-10.10s   %-8s %-8s %5d   %-8s (%s) %s",
		   crec.name,uidtoname(crec.uid),gidtoname(crec.gid),crec.pid,
		   crec.machine,crec.addr,
		   asctime(LocalTime(&crec.start)));
        }
      }
    }
  fclose(f);

  if (processes_only) exit(0);
  
  if (brief)
  {
    ptr=srecs;
    while (ptr!=NULL)
    {
      printf("%-8d%-10.10s%-30.30s%s",ptr->pid,uidtoname(ptr->uid),ptr->machine,asctime(LocalTime(&(ptr->start))));
    ptr=ptr->next;
    }
    printf("\n");
    exit(0);
  }

  printf("\n");

  locking_init(1);

  if (share_mode_forall(print_share_mode) <= 0)
    printf("No locked files\n");

  printf("\n");

  share_status(stdout);

  locking_end();

  return (0);
}
Example #4
0
File: status.c Project: aosm/samba
 int main(int argc, char *argv[])
{
	int c;
	int profile_only = 0;
	TDB_CONTEXT *tdb;
	BOOL show_processes, show_locks, show_shares;
	poptContext pc;
	struct poptOption long_options[] = {
		POPT_AUTOHELP
		{"processes",	'p', POPT_ARG_NONE,	&processes_only, 'p', "Show processes only" },
		{"verbose",	'v', POPT_ARG_NONE, &verbose, 'v', "Be verbose" },
		{"locks",	'L', POPT_ARG_NONE,	&locks_only, 'L', "Show locks only" },
		{"shares",	'S', POPT_ARG_NONE,	&shares_only, 'S', "Show shares only" },
		{"user", 	'u', POPT_ARG_STRING,	&username, 'u', "Switch to user" },
		{"brief",	'b', POPT_ARG_NONE, 	&brief, 'b', "Be brief" },
		{"profile",     'P', POPT_ARG_NONE, NULL, 'P', "Do profiling" },
		{"profile-rates", 'R', POPT_ARG_NONE, NULL, 'R', "Show call rates" },
		{"byterange",	'B', POPT_ARG_NONE,	&show_brl, 'B', "Include byte range locks"},
		{"numeric",	'n', POPT_ARG_NONE,	&numeric_only, 'n', "Numeric uid/gid"},
		{"counts",	'C', POPT_ARG_NONE,	&show_counts, 'n', "Show all user op/bytes counts"},
		POPT_COMMON_SAMBA
		POPT_TABLEEND
	};

	sec_init();
	load_case_tables();

	setup_logging(argv[0],True);
	
	dbf = x_stderr;
	
	if (getuid() != geteuid()) {
		d_printf("smbstatus should not be run setuid\n");
		return(1);
	}

	pc = poptGetContext(NULL, argc, (const char **) argv, long_options, 
			    POPT_CONTEXT_KEEP_FIRST);
	
	while ((c = poptGetNextOpt(pc)) != -1) {
		switch (c) {
		case 'u':                                      
			Ucrit_addUid(nametouid(poptGetOptArg(pc)));
			break;
		case 'P':
		case 'R':
			profile_only = c;
		}
	}

	/* setup the flags based on the possible combincations */

	show_processes = !(shares_only || locks_only || profile_only) || processes_only;
	show_locks     = !(shares_only || processes_only || profile_only) || locks_only;
	show_shares    = !(processes_only || locks_only || profile_only) || shares_only;

	if ( username )
		Ucrit_addUid( nametouid(username) );

	if (verbose) {
		d_printf("using configfile = %s\n", dyn_CONFIGFILE);
	}

	if (!lp_load(dyn_CONFIGFILE,False,False,False,True)) {
		fprintf(stderr, "Can't load %s - run testparm to debug it\n", dyn_CONFIGFILE);
		return (-1);
	}

	switch (profile_only) {
		case 'P':
			/* Dump profile data */
			return status_profile_dump(verbose);
		case 'R':
			/* Continuously display rate-converted data */
			return status_profile_rates(verbose);
		default:
			break;
	}

	if ( show_processes ) {
		tdb = tdb_open_log(lock_path("sessionid.tdb"), 0, TDB_DEFAULT, O_RDONLY, 0);
		if (!tdb) {
			d_printf("sessionid.tdb not initialised\n");
		} else {
			d_printf("\nSamba version %s\n",SAMBA_VERSION_STRING);
			d_printf("PID     Username      Group         Machine                        \n");
			d_printf("-------------------------------------------------------------------\n");

			tdb_traverse(tdb, traverse_sessionid, NULL);
			tdb_close(tdb);
		}

		if (processes_only) 
			exit(0);	
	}
  
#if WITH_DARWIN_STATS
	if ( show_counts) {
		dump_user_stats();
		dump_service_stats();
		exit(0);
	}
#endif /*WITH_DARWIN_STATS*/

	if ( show_shares ) {
		tdb = tdb_open_log(lock_path("connections.tdb"), 0, TDB_DEFAULT, O_RDONLY, 0);
		if (!tdb) {
			d_printf("%s not initialised\n", lock_path("connections.tdb"));
			d_printf("This is normal if an SMB client has never connected to your server.\n");
		}  else  {
			if (verbose) {
				d_printf("Opened %s\n", lock_path("connections.tdb"));
			}

			if (brief) 
				exit(0);
		
			d_printf("\nService      pid     machine       Connected at\n");
			d_printf("-------------------------------------------------------\n");
	
			tdb_traverse(tdb, traverse_fn1, NULL);
			tdb_close(tdb);

			d_printf("\n");
		}

		if ( shares_only )
			exit(0);
	}

	if ( show_locks ) {
		int ret;

		tdb = tdb_open_log(lock_path("locking.tdb"), 0, TDB_DEFAULT, O_RDONLY, 0);

		if (!tdb) {
			d_printf("%s not initialised\n", lock_path("locking.tdb"));
			d_printf("This is normal if an SMB client has never connected to your server.\n");
			exit(0);
		} else {
			tdb_close(tdb);
		}

		if (!locking_init(1)) {
			d_printf("Can't initialise locking module - exiting\n");
			exit(1);
		}
		
		ret = share_mode_forall(print_share_mode, NULL);

		if (ret == 0) {
			d_printf("No locked files\n");
		} else if (ret == -1) {
			d_printf("locked file list truncated\n");
		}
		
		d_printf("\n");

		if (show_brl) {
			brl_forall(print_brl);
		}
		
		locking_end();
	}

	return (0);
}
Example #5
0
/****************************************************************************
main thread of the background lpq updater
****************************************************************************/
pid_t start_background_queue(struct tevent_context *ev,
			     struct messaging_context *msg_ctx,
			     char *logfile)
{
	pid_t pid;

	/* Use local variables for this as we don't
	 * need to save the parent side of this, just
	 * ensure it closes when the process exits.
	 */
	int pause_pipe[2];

	DEBUG(3,("start_background_queue: Starting background LPQ thread\n"));

	if (pipe(pause_pipe) == -1) {
		DEBUG(5,("start_background_queue: cannot create pipe. %s\n", strerror(errno) ));
		exit(1);
	}

	/*
	 * Block signals before forking child as it will have to
	 * set its own handlers. Child will re-enable SIGHUP as
	 * soon as the handlers are set up.
	 */
	BlockSignals(true, SIGTERM);
	BlockSignals(true, SIGHUP);

	pid = sys_fork();

	/* parent or error */
	if (pid != 0) {
		/* Re-enable SIGHUP before returnig */
		BlockSignals(false, SIGTERM);
		BlockSignals(false, SIGHUP);
		return pid;
	}

	if (pid == -1) {
		DEBUG(5,("start_background_queue: background LPQ thread failed to start. %s\n", strerror(errno) ));
		exit(1);
	}

	if (pid == 0) {
		struct tevent_fd *fde;
		int ret;
		NTSTATUS status;

		/* Child. */
		DEBUG(5,("start_background_queue: background LPQ thread started\n"));

		close(pause_pipe[0]);
		pause_pipe[0] = -1;

		status = reinit_after_fork(msg_ctx, ev, true);

		if (!NT_STATUS_IS_OK(status)) {
			DEBUG(0,("reinit_after_fork() failed\n"));
			smb_panic("reinit_after_fork() failed");
		}

		bq_reopen_logs(logfile);
		bq_setup_sig_term_handler();
		bq_setup_sig_hup_handler(ev, msg_ctx);
		bq_setup_sig_chld_handler(ev);

		BlockSignals(false, SIGTERM);
		BlockSignals(false, SIGHUP);

		if (!printing_subsystem_queue_tasks(ev, msg_ctx)) {
			exit(1);
		}

		if (!serverid_register(messaging_server_id(msg_ctx),
				       FLAG_MSG_GENERAL |
				       FLAG_MSG_PRINT_GENERAL)) {
			exit(1);
		}

		if (!locking_init()) {
			exit(1);
		}
		messaging_register(msg_ctx, ev, MSG_SMB_CONF_UPDATED,
				   bq_smb_conf_updated);
		messaging_register(msg_ctx, NULL, MSG_PRINTER_UPDATE,
				   print_queue_receive);

		fde = tevent_add_fd(ev, ev, pause_pipe[1], TEVENT_FD_READ,
				    printing_pause_fd_handler,
				    NULL);
		if (!fde) {
			DEBUG(0,("tevent_add_fd() failed for pause_pipe\n"));
			smb_panic("tevent_add_fd() failed for pause_pipe");
		}

		pcap_cache_reload(ev, msg_ctx, &reload_pcap_change_notify);

		DEBUG(5,("start_background_queue: background LPQ thread waiting for messages\n"));
		ret = tevent_loop_wait(ev);
		/* should not be reached */
		DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
			 ret, (ret == 0) ? "out of events" : strerror(errno)));
		exit(1);
	}

	close(pause_pipe[1]);

	return pid;
}
Example #6
0
/****************************************************************************
  main program
****************************************************************************/
 int main(int argc,char *argv[])
{
	char *share1, *share2, *nfspath1, *nfspath2;
	extern char *optarg;
	extern int optind;
	int opt;
	char *p;
	int seed;

	setlinebuf(stdout);

	dbf = x_stderr;

	if (argc < 5 || argv[1][0] == '-') {
		usage();
		exit(1);
	}

	share1 = argv[1];
	share2 = argv[2];
	nfspath1 = argv[3];
	nfspath2 = argv[4];

	all_string_sub(share1,"/","\\",0);
	all_string_sub(share2,"/","\\",0);

	setup_logging(argv[0], DEBUG_STDOUT);

	argc -= 4;
	argv += 4;

	lp_load();

	if (getenv("USER")) {
		fstrcpy(username,getenv("USER"));
	}

	seed = time(NULL);

	while ((opt = getopt(argc, argv, "U:s:ho:aAW:O")) != EOF) {
		switch (opt) {
		case 'U':
			fstrcpy(username,optarg);
			p = strchr_m(username,'%');
			if (p) {
				*p = 0;
				fstrcpy(password, p+1);
				got_pass = 1;
			}
			break;
		case 's':
			seed = atoi(optarg);
			break;
		case 'u':
			hide_unlock_fails = True;
			break;
		case 'o':
			numops = atoi(optarg);
			break;
		case 'O':
			use_oplocks = True;
			break;
		case 'a':
			showall = True;
			break;
		case 'A':
			analyze = True;
			break;
		case 'h':
			usage();
			exit(1);
		default:
			printf("Unknown option %c (%d)\n", (char)opt, opt);
			exit(1);
		}
	}

	argc -= optind;
	argv += optind;

	DEBUG(0,("seed=%u\n", seed));
	srandom(seed);

	locking_init(1);
	test_locks(share1, share2, nfspath1, nfspath2);

	return(0);
}
Example #7
0
int main(int argc, char *argv[])
{
    int c;
    static int profile_only = 0;
    TDB_CONTEXT *tdb;
    poptContext pc;
    struct poptOption long_options[] = {
        POPT_AUTOHELP
        {"processes",	'p', POPT_ARG_NONE,	&processes_only, 'p', "Show processes only" },
        {"verbose",	'v', POPT_ARG_NONE, &verbose, 'v', "Be verbose" },
        {"locks",	'L', POPT_ARG_NONE,	&locks_only, 'L', "Show locks only" },
        {"shares",	'S', POPT_ARG_NONE,	&shares_only, 'S', "Show shares only" },
        {"user", 'u', POPT_ARG_STRING,	0, 'u', "Switch to user" },
        {"brief",	'b', POPT_ARG_NONE, 	&brief, 'b', "Be brief" },
#ifdef WITH_PROFILE
        {"profile",	'P', POPT_ARG_NONE,	&profile_only, 'P', "Do profiling" },
#endif /* WITH_PROFILE */
        {"byterange",	'B', POPT_ARG_NONE,	&show_brl, 'B', "Include byte range locks"},
        POPT_COMMON_SAMBA
        POPT_TABLEEND
    };

    setup_logging(argv[0],True);

    dbf = x_stderr;

    if (getuid() != geteuid()) {
        d_printf("smbstatus should not be run setuid\n");
        return(1);
    }

    pc = poptGetContext(NULL, argc, (const char **) argv, long_options,
                        POPT_CONTEXT_KEEP_FIRST);

    while ((c = poptGetNextOpt(pc)) != -1) {
        switch (c) {
        case 'u':
            Ucrit_addUsername(poptGetOptArg(pc));
            break;
        }
    }

    if (verbose) {
        d_printf("using configfile = %s\n", dyn_CONFIGFILE);
    }

    if (!lp_load(dyn_CONFIGFILE,False,False,False)) {
        fprintf(stderr, "Can't load %s - run testparm to debug it\n", dyn_CONFIGFILE);
        return (-1);
    }

    if (profile_only) {
        return profile_dump();
    }

    tdb = tdb_open_log(lock_path("sessionid.tdb"), 0, TDB_DEFAULT, O_RDONLY, 0);
    if (!tdb) {
        d_printf("sessionid.tdb not initialised\n");
    } else {
        if (locks_only) goto locks;

        d_printf("\nSamba version %s\n",SAMBA_VERSION_STRING);
        d_printf("PID     Username      Group         Machine                        \n");
        d_printf("-------------------------------------------------------------------\n");

        tdb_traverse(tdb, traverse_sessionid, NULL);
        tdb_close(tdb);
    }

    tdb = tdb_open_log(lock_path("connections.tdb"), 0, TDB_DEFAULT, O_RDONLY, 0);
    if (!tdb) {
        d_printf("%s not initialised\n", lock_path("connections.tdb"));
        d_printf("This is normal if an SMB client has never connected to your server.\n");
    }  else  {
        if (verbose) {
            d_printf("Opened %s\n", lock_path("connections.tdb"));
        }

        if (brief)
            exit(0);

        d_printf("\nService      pid     machine       Connected at\n");
        d_printf("-------------------------------------------------------\n");

        tdb_traverse(tdb, traverse_fn1, NULL);
        tdb_close(tdb);
    }

locks:
    if (processes_only) exit(0);

    if (!shares_only) {
        int ret;

        if (!locking_init(1)) {
            d_printf("Can't initialise locking module - exiting\n");
            exit(1);
        }

        ret = share_mode_forall(print_share_mode);

        if (ret == 0) {
            d_printf("No locked files\n");
        } else if (ret == -1) {
            d_printf("locked file list truncated\n");
        }

        d_printf("\n");

        if (show_brl) {
            brl_forall(print_brl);
        }

        locking_end();
    }

    return (0);
}
Example #8
0
bool run_cleanup3(int dummy)
{
	struct cli_state *cli;
	const char *fname = "cleanup3";
	uint16_t fnum;
	NTSTATUS status;
	struct share_mode_lock *lck;
	struct file_id id;
	size_t i;

	struct corruption_fns fns[] = {
		{ corrupt_dummy, "no corruption" },
		{ invalidate_sharemode, "invalidate_sharemode" },
		{ create_duplicate_batch, "create_duplicate_batch" },
	};

	printf("CLEANUP3: Checking that a share mode is cleaned up on "
	       "conflict\n");

	for (i=0; i<ARRAY_SIZE(fns); i++) {

		printf("testing %s\n", fns[i].descr);

		if (!create_stale_share_mode_entry(fname, &id)) {
			printf("create_stale_entry failed\n");
			return false;
		}

		printf("%d %d %d\n", (int)id.devid, (int)id.inode,
		       (int)id.extid);

		if (!locking_init()) {
			printf("locking_init failed\n");
			return false;
		}
		lck = get_existing_share_mode_lock(talloc_tos(), id);
		if (lck == NULL) {
			printf("get_existing_share_mode_lock failed\n");
			return false;
		}
		if (lck->data->num_share_modes != 1) {
			printf("get_existing_share_mode_lock did clean up\n");
			return false;
		}

		fns[i].fn(lck->data);

		TALLOC_FREE(lck);

		if (!torture_open_connection(&cli, 0)) {
			return false;
		}
		status = cli_openx(cli, fname, O_RDWR|O_CREAT, DENY_ALL,
				   &fnum);
		if (!NT_STATUS_IS_OK(status)) {
			printf("open of %s failed (%s)\n", fname,
			       nt_errstr(status));
			return false;
		}
		lck = get_existing_share_mode_lock(talloc_tos(), id);
		if (lck == NULL) {
			printf("get_existing_share_mode_lock failed\n");
			return false;
		}
		if (lck->data->num_share_modes != 1) {
			printf("conflicting open did not clean up\n");
			return false;
		}
		TALLOC_FREE(lck);

		torture_close_connection(cli);
	}

	return true;
}
Example #9
0
void start_spoolssd(struct tevent_context *ev_ctx,
		    struct messaging_context *msg_ctx)
{
	struct rpc_srv_callbacks spoolss_cb;
	pid_t pid;
	NTSTATUS status;
	int ret;

	DEBUG(1, ("Forking SPOOLSS Daemon\n"));

	pid = sys_fork();

	if (pid == -1) {
		DEBUG(0, ("Failed to fork SPOOLSS [%s], aborting ...\n",
			   strerror(errno)));
		exit(1);
	}

	if (pid) {
		/* parent */
		return;
	}

	/* child */
	close_low_fds(false);

	status = reinit_after_fork(msg_ctx,
				   ev_ctx,
				   procid_self(), true);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("reinit_after_fork() failed\n"));
		smb_panic("reinit_after_fork() failed");
	}

	spoolss_reopen_logs();

	spoolss_setup_sig_term_handler(ev_ctx);
	spoolss_setup_sig_hup_handler(ev_ctx, msg_ctx);

	if (!serverid_register(procid_self(),
				FLAG_MSG_GENERAL|FLAG_MSG_SMBD
				|FLAG_MSG_PRINT_GENERAL)) {
		exit(1);
	}

	if (!locking_init()) {
		exit(1);
	}

	messaging_register(msg_ctx, NULL,
			   MSG_PRINTER_UPDATE, print_queue_receive);
	messaging_register(msg_ctx, ev_ctx,
			   MSG_SMB_CONF_UPDATED, smb_conf_updated);

	/*
	 * Initialize spoolss with an init function to convert printers first.
	 * static_init_rpc will try to initialize the spoolss server too but you
	 * can't register it twice.
	 */
	spoolss_cb.init = spoolss_init_cb;
	spoolss_cb.shutdown = spoolss_shutdown_cb;
	spoolss_cb.private_data = msg_ctx;

	status = rpc_winreg_init(NULL);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0, ("Failed to register winreg rpc inteface! (%s)\n",
			  nt_errstr(status)));
		exit(1);
	}

	status = rpc_spoolss_init(&spoolss_cb);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0, ("Failed to register spoolss rpc inteface! (%s)\n",
			  nt_errstr(status)));
		exit(1);
	}

	if (!setup_named_pipe_socket(SPOOLSS_PIPE_NAME, ev_ctx)) {
		exit(1);
	}

	status = rpc_ep_setup_register(ev_ctx, msg_ctx, &ndr_table_spoolss, NULL, 0);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0, ("Failed to register spoolss endpoint! (%s)\n",
			  nt_errstr(status)));
		exit(1);
	}

	DEBUG(1, ("SPOOLSS Daemon Started (%d)\n", getpid()));

	/* loop forever */
	ret = tevent_loop_wait(ev_ctx);

	/* should not be reached */
	DEBUG(0,("background_queue: tevent_loop_wait() exited with %d - %s\n",
		 ret, (ret == 0) ? "out of events" : strerror(errno)));
	exit(1);
}
Example #10
0
/* show the current server status */
void status_page(void)
{
	const char *v;
	int autorefresh=0;
	int refresh_interval=30;
	TDB_CONTEXT *tdb;

	smbd_pid = pidfile_pid("smbd");

	if (cgi_variable("smbd_restart")) {
		stop_smbd();
		start_smbd();
	}

	if (cgi_variable("smbd_start")) {
		start_smbd();
	}

	if (cgi_variable("smbd_stop")) {
		stop_smbd();
	}

	if (cgi_variable("nmbd_restart")) {
		stop_nmbd();
		start_nmbd();
	}
	if (cgi_variable("nmbd_start")) {
		start_nmbd();
	}

	if (cgi_variable("nmbd_stop")) {
		stop_nmbd();
	}

	if (cgi_variable("autorefresh")) {
		autorefresh = 1;
	} else if (cgi_variable("norefresh")) {
		autorefresh = 0;
	} else if (cgi_variable("refresh")) {
		autorefresh = 1;
	}

	if ((v=cgi_variable("refresh_interval"))) {
		refresh_interval = atoi(v);
	}

	if (cgi_variable("show_client_in_col_1")) {
		PID_or_Machine = 1;
	}

	tdb = tdb_open_log(lock_path("connections.tdb"), 0, TDB_DEFAULT, O_RDONLY, 0);
	if (tdb) tdb_traverse(tdb, traverse_fn1, NULL);

	initPid2Machine ();

	printf("<H2>Server Status</H2>\n");

	printf("<FORM method=post>\n");

	if (!autorefresh) {
		printf("<input type=submit value=\"Auto Refresh\" name=autorefresh>\n");
		printf("<br>Refresh Interval: ");
		printf("<input type=text size=2 name=\"refresh_interval\" value=%d>\n", 
		       refresh_interval);
	} else {
		printf("<input type=submit value=\"Stop Refreshing\" name=norefresh>\n");
		printf("<br>Refresh Interval: %d\n", refresh_interval);
		printf("<input type=hidden name=refresh value=1>\n");
	}

	printf("<p>\n");

	if (!tdb) {
		/* open failure either means no connections have been
                   made or status=no */
		if (!lp_status(-1))
			printf("You need to have status=yes in your smb config file\n");
	}


	printf("<table>\n");

	printf("<tr><td>version:</td><td>%s</td></tr>",VERSION);

	fflush(stdout);
	printf("<tr><td>smbd:</td><td>%srunning</td>\n",smbd_running()?"":"not ");
	if (geteuid() == 0) {
	    if (smbd_running()) {
		printf("<td><input type=submit name=\"smbd_stop\" value=\"Stop smbd\"></td>\n");
	    } else {
		printf("<td><input type=submit name=\"smbd_start\" value=\"Start smbd\"></td>\n");
	    }
	    printf("<td><input type=submit name=\"smbd_restart\" value=\"Restart smbd\"></td>\n");
	}
	printf("</tr>\n");

	fflush(stdout);
	printf("<tr><td>nmbd:</td><td>%srunning</td>\n",nmbd_running()?"":"not ");
	if (geteuid() == 0) {
	    if (nmbd_running()) {
		printf("<td><input type=submit name=\"nmbd_stop\" value=\"Stop nmbd\"></td>\n");
	    } else {
		printf("<td><input type=submit name=\"nmbd_start\" value=\"Start nmbd\"></td>\n");
	    }
	    printf("<td><input type=submit name=\"nmbd_restart\" value=\"Restart nmbd\"></td>\n");
	}
	printf("</tr>\n");

	printf("</table>\n");
	fflush(stdout);

	printf("<p><h3>Active Connections</h3>\n");
	printf("<table border=1>\n");
	printf("<tr><th>PID</th><th>Client</th><th>IP address</th><th>Date</th>\n");
	if (geteuid() == 0) {
		printf("<th>Kill</th>\n");
	}
	printf("</tr>\n");

	if (tdb) tdb_traverse(tdb, traverse_fn2, NULL);

	printf("</table><p>\n");

	printf("<p><h3>Active Shares</h3>\n");
	printf("<table border=1>\n");
	printf("<tr><th>Share</th><th>User</th><th>Group</th><th>PID</th><th>Client</th><th>Date</th></tr>\n\n");

	if (tdb) tdb_traverse(tdb, traverse_fn3, NULL);

	printf("</table><p>\n");

	printf("<h3>Open Files</h3>\n");
	printf("<table border=1>\n");
	printf("<tr><th>%s</th><th>Sharing</th><th>R/W</th><th>Oplock</th><th>File</th><th>Date</th></tr>\n", PID_or_Machine ? "Client" : "PID");

	locking_init(1);
	share_mode_forall(print_share_mode);
	locking_end();
	printf("</table>\n");

	if (tdb) tdb_close(tdb);

	printf("<br><input type=submit name=\"show_client_in_col_1\" value=\"Show Client in col 1\">\n");
	printf("<input type=submit name=\"show_pid_in_col_1\" value=\"Show PID in col 1\">\n");

	printf("</FORM>\n");

	if (autorefresh) {
		/* this little JavaScript allows for automatic refresh
                   of the page. There are other methods but this seems
                   to be the best alternative */
		printf("<script language=\"JavaScript\">\n");
		printf("<!--\nsetTimeout('window.location.replace(\"%s/status?refresh_interval=%d&refresh=1\")', %d)\n", 
		       cgi_baseurl(),
		       refresh_interval,
		       refresh_interval*1000);
		printf("//-->\n</script>\n");
	}
}
Example #11
0
static bool spoolss_child_init(struct tevent_context *ev_ctx,
			       int child_id, struct pf_worker_data *pf)
{
	NTSTATUS status;
	struct rpc_srv_callbacks spoolss_cb;
	struct messaging_context *msg_ctx = messaging_init(NULL, ev_ctx);
	bool ok;

	status = reinit_after_fork(msg_ctx, ev_ctx,
				   true);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0,("reinit_after_fork() failed\n"));
		smb_panic("reinit_after_fork() failed");
	}

	prctl_set_comment("spoolssd-child");

	spoolss_child_id = child_id;
	spoolss_reopen_logs(child_id);

	ok = spoolss_setup_chld_hup_handler(ev_ctx, msg_ctx, pf);
	if (!ok) {
		return false;
	}

	if (!serverid_register(messaging_server_id(msg_ctx),
				FLAG_MSG_GENERAL |
				FLAG_MSG_PRINT_GENERAL)) {
		return false;
	}

	if (!locking_init()) {
		return false;
	}

	messaging_register(msg_ctx, ev_ctx,
			   MSG_SMB_CONF_UPDATED, smb_conf_updated);
	messaging_register(msg_ctx, ev_ctx,
			   MSG_PREFORK_PARENT_EVENT, parent_ping);

	/* As soon as messaging is up check if pcap has been loaded already.
	 * If so then we probably missed a message and should load_printers()
	 * ourselves. If pcap has not been loaded yet, then ignore, we will get
	 * a message as soon as the bq process completes the reload. */
	if (pcap_cache_loaded(NULL)) {
		load_printers(ev_ctx, msg_ctx);
	}

	/* try to reinit rpc queues */
	spoolss_cb.init = spoolss_init_cb;
	spoolss_cb.shutdown = spoolss_shutdown_cb;
	spoolss_cb.private_data = msg_ctx;

	status = rpc_winreg_init(NULL);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0, ("Failed to register winreg rpc inteface! (%s)\n",
			  nt_errstr(status)));
		return false;
	}

	status = rpc_spoolss_init(&spoolss_cb);
	if (!NT_STATUS_IS_OK(status)) {
		DEBUG(0, ("Failed to register spoolss rpc inteface! (%s)\n",
			  nt_errstr(status)));
		return false;
	}

	return true;
}
Example #12
0
 int main2(int argc,const char *argv[])
{
	/* shall I run as a daemon */
	static BOOL is_daemon = False;
	static BOOL interactive = False;
	static BOOL Fork = True;
	static BOOL no_process_group = False;
	static BOOL log_stdout = False;
	static char *ports = NULL;
	int opt;
#ifndef _XBOX
	poptContext pc;

	struct poptOption long_options[] = {
	POPT_AUTOHELP
	{"daemon", 'D', POPT_ARG_VAL, &is_daemon, True, "Become a daemon (default)" },
	{"interactive", 'i', POPT_ARG_VAL, &interactive, True, "Run interactive (not a daemon)"},
	{"foreground", 'F', POPT_ARG_VAL, &Fork, False, "Run daemon in foreground (for daemontools, etc.)" },
	{"no-process-group", '\0', POPT_ARG_VAL, &no_process_group, True, "Don't create a new process group" },
	{"log-stdout", 'S', POPT_ARG_VAL, &log_stdout, True, "Log to stdout" },
	{"build-options", 'b', POPT_ARG_NONE, NULL, 'b', "Print build options" },
	{"port", 'p', POPT_ARG_STRING, &ports, 0, "Listen on the specified ports"},
	POPT_COMMON_SAMBA
	POPT_COMMON_DYNCONFIG
	POPT_TABLEEND
	};
#else
	interactive = True;
	log_stdout = True;
#endif

	load_case_tables();

#ifdef HAVE_SET_AUTH_PARAMETERS
	set_auth_parameters(argc,argv);
#endif

#ifndef _XBOX
	pc = poptGetContext("smbd", argc, argv, long_options, 0);
	
	while((opt = poptGetNextOpt(pc)) != -1) {
		switch (opt)  {
		case 'b':
			build_options(True); /* Display output to screen as well as debug */ 
			exit(0);
			break;
		}
	}

	poptFreeContext(pc);
#endif

#ifdef HAVE_SETLUID
	/* needed for SecureWare on SCO */
	setluid(0);
#endif

	sec_init();

	set_remote_machine_name("smbd", False);

	if (interactive) {
		Fork = False;
		log_stdout = True;
	}

	if (interactive && (DEBUGLEVEL >= 9)) {
		talloc_enable_leak_report();
	}

	if (log_stdout && Fork) {
		DEBUG(0,("ERROR: Can't log to stdout (-S) unless daemon is in foreground (-F) or interactive (-i)\n"));
		exit(1);
	}

	setup_logging(argv[0],log_stdout);

	/* we want to re-seed early to prevent time delays causing
           client problems at a later date. (tridge) */
	generate_random_buffer(NULL, 0);

	/* make absolutely sure we run as root - to handle cases where people
	   are crazy enough to have it setuid */

	gain_root_privilege();
	gain_root_group_privilege();

#ifndef _XBOX
	fault_setup((void (*)(void *))exit_server_fault);
	dump_core_setup("smbd");
#endif

	CatchSignal(SIGTERM , SIGNAL_CAST sig_term);
#ifndef _XBOX
	CatchSignal(SIGHUP,SIGNAL_CAST sig_hup);
	
	/* we are never interested in SIGPIPE */
	BlockSignals(True,SIGPIPE);
#endif

#if defined(SIGFPE)
	/* we are never interested in SIGFPE */
	BlockSignals(True,SIGFPE);
#endif

#if defined(SIGUSR2)
	/* We are no longer interested in USR2 */
	BlockSignals(True,SIGUSR2);
#endif

	/* POSIX demands that signals are inherited. If the invoking process has
	 * these signals masked, we will have problems, as we won't recieve them. */
#ifndef _XBOX
	BlockSignals(False, SIGHUP);
#endif
	BlockSignals(False, SIGUSR1);
	BlockSignals(False, SIGTERM);

	/* we want total control over the permissions on created files,
	   so set our umask to 0 */
	umask(0);

	init_sec_ctx();

	reopen_logs();

	DEBUG(0,( "smbd version %s started.\n", SAMBA_VERSION_STRING));
	DEBUGADD( 0, ( "%s\n", COPYRIGHT_STARTUP_MESSAGE ) );

	DEBUG(2,("uid=%d gid=%d euid=%d egid=%d\n",
		 (int)getuid(),(int)getgid(),(int)geteuid(),(int)getegid()));

	/* Output the build options to the debug log */ 
	build_options(False);

	if (sizeof(uint16) < 2 || sizeof(uint32) < 4) {
		DEBUG(0,("ERROR: Samba is not configured correctly for the word size on your machine\n"));
		exit(1);
	}

	/*
	 * Do this before reload_services.
	 */

	if (!reload_services(False))
		return(-1);	

	init_structs();

#ifdef WITH_PROFILE
	if (!profile_setup(False)) {
		DEBUG(0,("ERROR: failed to setup profiling\n"));
		return -1;
	}
#endif

	DEBUG(3,( "loaded services\n"));

	if (!is_daemon && !is_a_socket(0)) {
		if (!interactive)
			DEBUG(0,("standard input is not a socket, assuming -D option\n"));

		/*
		 * Setting is_daemon here prevents us from eventually calling
		 * the open_sockets_inetd()
		 */

		is_daemon = True;
	}

	if (is_daemon && !interactive) {
		DEBUG( 3, ( "Becoming a daemon.\n" ) );
		become_daemon(Fork, no_process_group);
	}

#if HAVE_SETPGID
	/*
	 * If we're interactive we want to set our own process group for
	 * signal management.
	 */
	if (interactive && !no_process_group)
		setpgid( (pid_t)0, (pid_t)0);
#endif

	if (!directory_exist(lp_lockdir(), NULL))
		mkdir(lp_lockdir(), 0755);

#ifndef _XBOX
	if (is_daemon)
		pidfile_create("smbd");
#endif

	/* Setup all the TDB's - including CLEAR_IF_FIRST tdb's. */
	if (!message_init())
		exit(1);

	/* Initialize our global sam sid first -- quite a lot of the other
	 * initialization routines further down depend on it.
	 */

	/* Initialise the password backed before the global_sam_sid
	   to ensure that we fetch from ldap before we make a domain sid up */

	if(!initialize_password_db(False))
		exit(1);

	/* Fail gracefully if we can't open secrets.tdb */

	if (!secrets_init()) {
		DEBUG(0, ("ERROR: smbd can not open secrets.tdb\n"));
		exit(1);
	}

	if(!get_global_sam_sid()) {
		DEBUG(0,("ERROR: Samba cannot create a SAM SID.\n"));
		exit(1);
	}

	if (!session_init())
		exit(1);

	if (conn_tdb_ctx() == NULL)
		exit(1);

	if (!locking_init(0))
		exit(1);

	namecache_enable();

	if (!init_registry())
		exit(1);

#if 0
	if (!init_svcctl_db())
                exit(1);
#endif

#ifndef _XBOX
	if (!print_backend_init())
		exit(1);
#endif

	if (!init_guest_info()) {
		DEBUG(0,("ERROR: failed to setup guest info.\n"));
		return -1;
	}

	/* Setup the main smbd so that we can get messages. */
	/* don't worry about general printing messages here */

	claim_connection(NULL,"",0,True,FLAG_MSG_GENERAL|FLAG_MSG_SMBD);

	/* only start the background queue daemon if we are 
	   running as a daemon -- bad things will happen if
	   smbd is launched via inetd and we fork a copy of 
	   ourselves here */
#ifndef _XBOX
	if ( is_daemon && !interactive )
		start_background_queue(); 
#endif
	/* Always attempt to initialize DMAPI. We will only use it later if
	 * lp_dmapi_support is set on the share, but we need a single global
	 * session to work with.
	 */
	dmapi_init_session();

	if (!open_sockets_smbd(is_daemon, interactive, ports))
		exit(1);

	/*
	 * everything after this point is run after the fork()
	 */ 

	static_init_rpc;

	init_modules();

	/* possibly reload the services file. */
	reload_services(True);

	if (!init_account_policy()) {
		DEBUG(0,("Could not open account policy tdb.\n"));
		exit(1);
	}

	if (*lp_rootdir()) {
		if (sys_chroot(lp_rootdir()) == 0)
			DEBUG(2,("Changed root to %s\n", lp_rootdir()));
	}

	/* Setup oplocks */
	if (!init_oplocks())
		exit(1);
	
	/* Setup change notify */
	if (!init_change_notify())
		exit(1);

	/* Setup aio signal handler. */
	initialize_async_io_handler();

	/* re-initialise the timezone */
	TimeInit();

	/* register our message handlers */
	message_register(MSG_SMB_FORCE_TDIS, msg_force_tdis);

	smbd_process();

#ifdef _XBOX
	xb_DecClientCount();
#endif

	namecache_shutdown();

	exit_server_cleanly(NULL);
	return(0);
}