예제 #1
0
파일: center.cpp 프로젝트: arhunn/pvbaddon
static void *centerMain(void *arg)
{
  int cnt;

  processlist = NULL; // processlist = empty
  cnt = 99999;        // cnt = expired
  do_reload(0);       // reload speadsheat
  while(1)
  {
    if(toCenter.poll() == rlFifo::DATA_AVAILABLE)
    {
      toCenter.read(interpreter.line,rl_PRINTF_LENGTH-1);
      if     (interpreter.isCommand("sigterm(")) do_sigterm();
      else if(interpreter.isCommand("sigkill(")) do_sigkill();
      else if(interpreter.isCommand("reload("))  do_reload(1);
      else if(interpreter.isCommand("remove("))  do_remove();
      else if(interpreter.isCommand("save("))    do_save();
      if(processes_have_been_modified)           do_save();
    }
    else if(cnt++ >= WATCHDOG_CYCLE_TIME)
    {
      cnt = 0;
      watchdog();
      if(processes_have_been_modified)           do_save();
    }
    else
    {
      rlsleep(1000); // 1 second
    }
    if(arg == NULL) return NULL; // just to fool the compiler
  }
}
예제 #2
0
파일: center.cpp 프로젝트: arhunn/pvbaddon
static void do_remove()
{
  char candidate_name[100],name[100];
  long pid;

  interpreter.copyStringParam(candidate_name,0);
  center.lock();
  for(int irow=FIRST_ROW; spreadsheat.exists(irow,1); irow++)
  {
    rlstrncpy(name,spreadsheat.text(T_name,irow), sizeof(name)-1);
    if(strcmp(name,candidate_name) == 0)
    {
#ifdef __VMS
      sscanf(spreadsheat.text(T_pid,irow),"%x",&pid);
#else
      sscanf(spreadsheat.text(T_pid,irow),"%ld",&pid);
#endif
      spreadsheat.printf(T_state,          irow,"");
      spreadsheat.printf(T_pid,            irow,"");
      spreadsheat.printf(T_name,           irow,"");
      spreadsheat.printf(T_credit,         irow,"");
      spreadsheat.printf(T_interval,       irow,"");
      spreadsheat.printf(T_priority,       irow,"");
      spreadsheat.printf(T_startup_command,irow,"");
      spreadsheat.printf(T_input,          irow,"");
      spreadsheat.printf(T_output,         irow,"");
      spreadsheat.printf(T_error,          irow,"");
      spreadsheat.printf(T_initial_credit, irow,"");
      spreadsheat.printf(T_time,           irow,"");
      break;
    }
  }
  center.unlock();
  do_reload(1);
}
예제 #3
0
파일: rbldnsd.c 프로젝트: 0xxon/rbldnsd
static void do_signalled(void) {
  sigprocmask(SIG_SETMASK, &ssblock, NULL);
  if (signalled & SIGNALLED_TERM) {
    if (fork_on_reload < 0) { /* this is a temp child; dump stats and exit */
      ipc_write_stats(1);
      if (flog && !flushlog)
        fflush(flog);
      _exit(0);
    }
    dslog(LOG_INFO, 0, "terminating");
#ifndef NO_STATS
    if (statsfile)
      dumpstats();
    logstats(0);
    if (statsfile)
      dumpstats_z();
#endif
    exit(0);
  }
#ifndef NO_STATS
  if (signalled & SIGNALLED_SSTATS && statsfile)
    dumpstats();
  if (signalled & SIGNALLED_LSTATS) {
    logstats(signalled & SIGNALLED_ZSTATS);
    if (signalled & SIGNALLED_ZSTATS && statsfile)
      dumpstats_z();
  }
#endif
  if (signalled & SIGNALLED_RELOG)
    reopenlog();
  if (signalled & SIGNALLED_RELOAD)
    do_reload(fork_on_reload);
  signalled = 0;
  sigprocmask(SIG_SETMASK, &ssempty, NULL);
}
예제 #4
0
파일: lxcfs.c 프로젝트: Blub/lxcfs
static void up_users(void)
{
	users_lock();
	if (users_count == 0 && need_reload)
		do_reload();
	users_count++;
	users_unlock();
}
예제 #5
0
파일: cel.c 프로젝트: RoyalG41/Asterisk
int ast_cel_engine_init(void)
{
	if (!(appset = ao2_container_alloc(NUM_APP_BUCKETS, app_hash, app_cmp))) {
		return -1;
	}

	if (do_reload()) {
		ao2_ref(appset, -1);
		appset = NULL;
		return -1;
	}

	if (ast_cli_register(&cli_status)) {
		ao2_ref(appset, -1);
		appset = NULL;
		return -1;
	}

	ast_register_atexit(ast_cel_engine_term);

	return 0;
}
예제 #6
0
bool courier::auth::config_file::load(bool reload)
{
    struct stat stat_buf;

    if (stat(filename, &stat_buf) < 0)
    {
        courier_auth_err("stat(%s) failed", filename);
        return false;
    }

    if (loaded)
    {
        if (stat_buf.st_mtime != config_timestamp)
            do_reload();
        return true;
    }

    loaded=open_and_load_file(reload);

    if (loaded)
        config_timestamp=stat_buf.st_mtime;
    return loaded;
}
예제 #7
0
파일: main.c 프로젝트: TangYang798/lcdproc
static void
do_mainloop(void)
{
	Screen *s;
	struct timeval t;
	struct timeval last_t;
	int sleeptime;
	long int process_lag = 0;
	long int render_lag = 0;
	long int t_diff;

	debug(RPT_DEBUG, "%s()", __FUNCTION__);

	gettimeofday(&t, NULL); /* Get initial time */

	while (1) {
		/* Get current time */
		last_t = t;
		gettimeofday(&t, NULL);
		t_diff = t.tv_sec - last_t.tv_sec;
		if ( ((t_diff + 1) > (LONG_MAX / 1e6)) || (t_diff < 0) ) {
			/* We're going to overflow the calculation - probably been to sleep, fudge the values */
			t_diff = 0;
			process_lag = 1;
			render_lag = (1e6/RENDER_FREQ);
		} else {
			t_diff *= 1e6;
			t_diff += t.tv_usec - last_t.tv_usec;
		}
                process_lag += t_diff;
		if (process_lag > 0) {
			/* Time for a processing stroke */
			sock_poll_clients();		/* poll clients for input*/
			parse_all_client_messages();	/* analyze input from network clients*/
			handle_input();		/* handle key input from devices*/

			/* We've done the job... */
			process_lag = 0 - (1e6/PROCESS_FREQ);
			/* Note : this does not make a fixed frequency */
		}

		render_lag += t_diff;
		if (render_lag > 0) {
			/* Time for a rendering stroke */
			timer ++;
			screenlist_process();
			s = screenlist_current();

			/* TODO: Move this call to every client connection
			 *       and every screen add...
			 */
			if (s == server_screen) {
				update_server_screen();
			}
			render_screen(s, timer);

			/* We've done the job... */
			if (render_lag > (1e6/RENDER_FREQ) * MAX_RENDER_LAG_FRAMES) {
				/* Cause rendering slowdown because too much lag */
				render_lag = (1e6/RENDER_FREQ) * MAX_RENDER_LAG_FRAMES;
			}
			render_lag -= (1e6/RENDER_FREQ);
			/* Note: this DOES make a fixed frequency (except with slowdown) */
		}

		/* Sleep just as long as needed */
		sleeptime = min(0-process_lag, 0-render_lag);
		if (sleeptime > 0) {
			usleep(sleeptime);
		}

		/* Check if a SIGHUP has been caught */
		if (got_reload_signal) {
			got_reload_signal = 0;
			do_reload();
		}
	}

	/* Quit! */
	exit_program(0);
}
예제 #8
0
파일: cel.c 프로젝트: RoyalG41/Asterisk
int ast_cel_engine_reload(void)
{
	return do_reload();
}
예제 #9
0
파일: rbldnsd.c 프로젝트: 0xxon/rbldnsd
static void init(int argc, char **argv) {
  int c;
  char *p;
  const char *user = NULL;
  const char *rootdir = NULL, *workdir = NULL, *pidfile = NULL;
  const char *bindaddr[MAXSOCK];
  int nba = 0;
  uid_t uid = 0;
  gid_t gid = 0;
  int nodaemon = 0, quickstart = 0, dump = 0, nover = 0, forkon = 0;
  int family = AF_UNSPEC;
  int cfd = -1;
  const struct zone *z;
#ifndef NO_DSO
  char *ext = NULL, *extarg = NULL;
  int (*extinit)(const char *arg, struct zone *zonelist) = NULL;
#endif

  if ((progname = strrchr(argv[0], '/')) != NULL)
    argv[0] = ++progname;
  else
    progname = argv[0];

  if (argc <= 1) usage(1);

  const char *const getopt_fmt = "u:r:b:w:t:c:p:nel:Lqs:h46dvaAfCx:X:zg";
  while((c = getopt(argc, argv, getopt_fmt)) != EOF)
    switch(c) {
    case 'u': user = optarg; break;
    case 'r': rootdir = optarg; break;
    case 'b':
      if (nba >= MAXSOCK)
        error(0, "too many addresses to listen on (%d max)", MAXSOCK);
      bindaddr[nba++] = optarg;
      break;
#ifndef NO_IPv6
    case '4': family = AF_INET; break;
    case '6': family = AF_INET6; break;
#else
    case '4': break;
    case '6': error(0, "IPv6 support isn't compiled in");
#endif
    case 'w': workdir = optarg; break;
    case 'p': pidfile = optarg; break;
    case 't':
      p = optarg;
      if (*p == ':') ++p;
      else {
        if (!(p = parse_time(p, &def_ttl)) || !def_ttl ||
            (*p && *p++ != ':'))
          error(0, "invalid ttl (-t) value `%.50s'", optarg);
      }
      if (*p == ':') ++p;
      else if (*p) {
        if (!(p = parse_time(p, &min_ttl)) || (*p && *p++ != ':'))
          error(0, "invalid minttl (-t) value `%.50s'", optarg);
      }
      if (*p == ':') ++p;
      else if (*p) {
        if (!(p = parse_time(p, &max_ttl)) || (*p && *p++ != ':'))
          error(0, "invalid maxttl (-t) value `%.50s'", optarg);
      }
      if (*p)
        error(0, "invalid value for -t (ttl) option: `%.50s'", optarg);
      if ((min_ttl && max_ttl && min_ttl > max_ttl) ||
          (min_ttl && def_ttl < min_ttl) ||
          (max_ttl && def_ttl > max_ttl))
        error(0, "inconsistent def:min:max ttl: %u:%u:%u",
              def_ttl, min_ttl, max_ttl);
      break;
    case 'c':
      if (!(p = parse_time(optarg, &recheck)) || *p)
        error(0, "invalid check interval (-c) value `%.50s'", optarg);
      break;
    case 'n': nodaemon = 1; break;
    case 'e': accept_in_cidr = 1; break;
    case 'l':
      logfile = optarg;
      if (*logfile != '+') flushlog = 0;
      else ++logfile, flushlog = 1;
      if (!*logfile) logfile = NULL, flushlog = 0;
      else if (logfile[0] == '-' && logfile[1] == '\0')
        logfile = NULL, flog = stdout;
      break;
    case 'L':
      verbose = 1; break;
break;
    case 's':
#ifdef NO_STATS
      fprintf(stderr,
        "%s: warning: no statistics counters support is compiled in\n",
        progname);
#else
      statsfile = optarg;
      if (*statsfile != '+') stats_relative = 0;
      else ++statsfile, stats_relative = 1;
      if (!*statsfile) statsfile = NULL;
#endif
      break;
    case 'q': quickstart = 1; break;
    case 'd':
#ifdef NO_MASTER_DUMP
      error(0, "master-format dump option (-d) isn't compiled in");
#endif
      dump = 1;
      break;
    case 'v': show_version = nover++ ? NULL : "rbldnsd"; break;
    case 'a': lazy = 1; break;
    case 'A': lazy = 0; break;
    case 'f': forkon = 1; break;
    case 'C': nouncompress = 1; break;
#ifndef NO_DSO
    case 'x': ext = optarg; break;
    case 'X': extarg = optarg; break;
#else
    case 'x':
    case 'X':
      error(0, "extension support is not compiled in");
#endif
#ifndef NO_ANONYMIZE
    case 'z': anonymize = 1; break;
#else
    case 'z':
      error(0, "anonymization support is not compiled in");
#endif
#ifndef NO_GEOIP
    case 'g': geoip = 1; break;
    case 'G': geoip = 1; geoip_path = optarg; break;

#else
    case 'g':
    case 'G':
      error(0, "geoip support is not compiled in");
#endif
    case 'h': usage(0);
    default: error(0, "type `%.50s -h' for help", progname);
    }

  if (!(argc -= optind))
    error(0, "no zone(s) to service specified (-h for help)");
  argv += optind;

#ifndef NO_MASTER_DUMP
  if (dump) {
    time_t now;
    logto = LOGTO_STDERR;
    for(c = 0; c < argc; ++c)
      zonelist = addzone(zonelist, argv[c]);
    init_zones_caches(zonelist);
    if (rootdir && (chdir(rootdir) < 0 || chroot(rootdir) < 0))
      error(errno, "unable to chroot to %.50s", rootdir);
    if (workdir && chdir(workdir) < 0)
      error(errno, "unable to chdir to %.50s", workdir);
    if (!do_reload(0))
      error(0, "zone loading errors, aborting");
    now = time(NULL);
    printf("; zone dump made %s", ctime(&now));
    printf("; rbldnsd version %s\n", version);
    for (z = zonelist; z; z = z->z_next)
      dumpzone(z, stdout);
    fflush(stdout);
    exit(ferror(stdout) ? 1 : 0);
  }
#endif

  if (!nba)
    error(0, "no address to listen on (-b option) specified");

  tzset();
  if (nodaemon)
    logto = LOGTO_STDOUT|LOGTO_STDERR;
  else {
    /* fork early so that logging will be from right pid */
    int pfd[2];
    if (pipe(pfd) < 0) error(errno, "pipe() failed");
    c = fork();
    if (c < 0) error(errno, "fork() failed");
    if (c > 0) {
      close(pfd[1]);
      if (read(pfd[0], &c, 1) < 1) exit(1);
      else exit(0);
    }
    cfd = pfd[1];
    close(pfd[0]);
    openlog(progname, LOG_PID|LOG_NDELAY, LOG_DAEMON);
    logto = LOGTO_STDERR|LOGTO_SYSLOG;
    if (!quickstart && !flog) logto |= LOGTO_STDOUT;
  }

  initsockets(bindaddr, nba, family);

#ifndef NO_DSO
  if (ext) {
    void *handle = dlopen(ext, RTLD_NOW);
    if (!handle)
      error(0, "unable to load extension `%s': %s", ext, dlerror());
    extinit = dlsym(handle, "rbldnsd_extension_init");
    if (!extinit)
      error(0, "unable to find extension init routine in `%s'", ext);
  }
#endif

  if (!user && !(uid = getuid()))
    user = "******";

  if (!user)
    p = NULL;
  else {
    if ((p = strchr(user, ':')) != NULL)
      *p++ = '\0';
    if ((c = satoi(user)) >= 0)
      uid = c, gid = c;
    else {
      struct passwd *pw = getpwnam(user);
      if (!pw)
        error(0, "unknown user `%s'", user);
      uid = pw->pw_uid;
      gid = pw->pw_gid;
      endpwent();
    }
  }
  if (!uid)
    error(0, "daemon should not run as root, specify -u option");
  if (p) {
    if ((c = satoi(p)) >= 0)
      gid = c;
    else {
      struct group *gr = getgrnam(p);
      if (!gr)
        error(0, "unknown group `%s'", p);
      gid = gr->gr_gid;
      endgrent();
    }
    p[-1] = ':';
  }

  if (pidfile) {
    int fdpid;
    char buf[40];
    c = sprintf(buf, "%ld\n", (long)getpid());
    fdpid = open(pidfile, O_CREAT|O_WRONLY|O_TRUNC, 0644);
    if (fdpid < 0 || write(fdpid, buf, c) < c)
      error(errno, "unable to write pidfile");
    close(fdpid);
  }

  if (rootdir && (chdir(rootdir) < 0 || chroot(rootdir) < 0))
    error(errno, "unable to chroot to %.50s", rootdir);
  if (workdir && chdir(workdir) < 0)
    error(errno, "unable to chdir to %.50s", workdir);

  if (user)
    if (setgroups(1, &gid) < 0 || setgid(gid) < 0 || setuid(uid) < 0)
      error(errno, "unable to setuid(%d:%d)", (int)uid, (int)gid);

  for(c = 0; c < argc; ++c)
    zonelist = addzone(zonelist, argv[c]);
  init_zones_caches(zonelist);

#ifndef NO_DSO
  if (extinit && extinit(extarg, zonelist) != 0)
    error(0, "unable to iniitialize extension `%s'", ext);
#endif

  if (!quickstart && !do_reload(0))
    error(0, "zone loading errors, aborting");

  /* count number of zones */
  for(c = 0, z = zonelist; z; z = z->z_next)
    ++c;
  numzones = c;

#if STATS_IPC_IOVEC
  stats_iov = (struct iovec *)emalloc(numzones * sizeof(struct iovec));
  for(c = 0, z = zonelist; z; z = z->z_next, ++c) {
    stats_iov[c].iov_base = (char*)&z->z_stats;
    stats_iov[c].iov_len = sizeof(z->z_stats);
  }
#endif
  dslog(LOG_INFO, 0, "rbldnsd version %s started (%d socket(s), %d zone(s))",
        version, numsock, numzones);
  initialized = 1;

  if (cfd >= 0) {
    write(cfd, "", 1);
    close(cfd);
    close(0); close(2);
    if (!flog) close(1);
    setsid();
    logto = LOGTO_SYSLOG;
  }

  if (quickstart)
    do_reload(0);

  /* only set "main" fork_on_reload after first reload */
  fork_on_reload = forkon;
}
예제 #10
0
파일: lxcfs.c 프로젝트: Blub/lxcfs
int main(int argc, char *argv[])
{
	int ret = -1, pidfd;
	char *pidfile = NULL, *v = NULL;
	size_t pidfile_len;
	/*
	 * what we pass to fuse_main is:
	 * argv[0] -s -f -o allow_other,directio argv[1] NULL
	 */
	int nargs = 5, cnt = 0;
	char *newargv[6];

	/* accomodate older init scripts */
	swallow_arg(&argc, argv, "-s");
	swallow_arg(&argc, argv, "-f");
	if (swallow_option(&argc, argv, "-o", &v)) {
		if (strcmp(v, "allow_other") != 0) {
			fprintf(stderr, "Warning: unexpected fuse option %s\n", v);
			exit(1);
		}
		free(v);
		v = NULL;
	}
	if (swallow_option(&argc, argv, "-p", &v))
		pidfile = v;

	if (argc == 2  && strcmp(argv[1], "--version") == 0) {
		fprintf(stderr, "%s\n", VERSION);
		exit(0);
	}
	if (argc != 2 || is_help(argv[1]))
		usage(argv[0]);

	do_reload();
	signal(SIGUSR1, reload_handler);

	newargv[cnt++] = argv[0];
	newargv[cnt++] = "-f";
	newargv[cnt++] = "-o";
	newargv[cnt++] = "allow_other,direct_io,entry_timeout=0.5,attr_timeout=0.5";
	newargv[cnt++] = argv[1];
	newargv[cnt++] = NULL;

	if (!cgfs_setup_controllers())
		goto out;

	if (!pidfile) {
		pidfile_len = strlen(RUNTIME_PATH) + strlen("/lxcfs.pid") + 1;
		pidfile = alloca(pidfile_len);
		snprintf(pidfile, pidfile_len, "%s/lxcfs.pid", RUNTIME_PATH);
	}
	if ((pidfd = set_pidfile(pidfile)) < 0)
		goto out;

	ret = fuse_main(nargs, newargv, &lxcfs_ops, NULL);

	dlclose(dlopen_handle);
	unlink(pidfile);
	close(pidfd);

out:
	return ret;
}
예제 #11
0
struct vsf_client_launch
vsf_standalone_main(void)
{
  struct vsf_sysutil_sockaddr* p_sockaddr = 0;
  struct vsf_sysutil_ipv4addr listen_ipaddr;
  int listen_sock = vsf_sysutil_get_ipv4_sock();
  int retval;
  s_p_ip_count_hash = hash_alloc(256, sizeof(struct vsf_sysutil_ipv4addr),
                                 sizeof(unsigned int), hash_ip);
  s_p_pid_ip_hash = hash_alloc(256, sizeof(int),
                               sizeof(struct vsf_sysutil_ipv4addr), hash_pid);
  if (tunable_setproctitle_enable)
  {
    vsf_sysutil_setproctitle("LISTENER");
  }
  vsf_sysutil_install_sighandler(kVSFSysUtilSigCHLD, handle_sigchld, 0);
  vsf_sysutil_install_async_sighandler(kVSFSysUtilSigHUP, handle_sighup);

  vsf_sysutil_activate_reuseaddr(listen_sock);
  vsf_sysutil_sockaddr_alloc_ipv4(&p_sockaddr);
  vsf_sysutil_sockaddr_set_port(
      p_sockaddr, vsf_sysutil_ipv4port_from_int(tunable_listen_port));
  if (!tunable_listen_address ||
      vsf_sysutil_inet_aton(tunable_listen_address, &listen_ipaddr) == 0)
  {
    listen_ipaddr = vsf_sysutil_sockaddr_get_any();
  }
  vsf_sysutil_sockaddr_set_ipaddr(p_sockaddr, listen_ipaddr);
  retval = vsf_sysutil_bind(listen_sock, p_sockaddr);
  
  vsf_sysutil_free(p_sockaddr);

  if (vsf_sysutil_retval_is_error(retval))
  {
    die("could not bind listening socket");
  }
  vsf_sysutil_listen(listen_sock, VSFTP_LISTEN_BACKLOG);

  while (1)
  {
    struct vsf_client_launch child_info;
    static struct vsf_sysutil_sockaddr* p_accept_addr;
    int new_child;
    struct vsf_sysutil_ipv4addr ip_addr;
    /* NOTE - wake up every 10 seconds to make sure we notice child exit
     * in a timely manner (the sync signal framework race)
     */
    int new_client_sock = vsf_sysutil_accept_timeout(
        listen_sock, &p_accept_addr, 10);
    if (s_reload_needed)
    {
      s_reload_needed = 0;
      do_reload();
    }
    if (vsf_sysutil_retval_is_error(new_client_sock))
    {
      continue;
    }
    ip_addr = vsf_sysutil_sockaddr_get_ipaddr(p_accept_addr);
    ++s_children;
    child_info.num_children = s_children;
    child_info.num_this_ip = handle_ip_count(&ip_addr);
    new_child = vsf_sysutil_fork_failok();
    if (new_child != 0)
    {
      /* Parent context */
      vsf_sysutil_close(new_client_sock);
      if (new_child > 0)
      {
        hash_add_entry(s_p_pid_ip_hash, (void*)&new_child, (void*)&ip_addr);
      }
      else
      {
        /* fork() failed, clear up! */
        --s_children;
        drop_ip_count(&ip_addr);
      }
      /* Fall through to while() loop and accept() again */
    }
    else
    {
      /* Child context */
      vsf_sysutil_close(listen_sock);
      prepare_child(new_client_sock);
      /* By returning here we "launch" the child process with the same
       * contract as xinetd would provide.
       */
      return child_info;
    }
  }
}
예제 #12
0
void MainWindow::on_action_Reload_triggered()
{
	do_reload();
}
int
main(int argc, char **argv)
{
	static struct option long_options[] = {
		{"help", no_argument, NULL, '?'},
		{"version", no_argument, NULL, 'V'},
		{"log", required_argument, NULL, 'l'},
		{"mode", required_argument, NULL, 'm'},
		{"pgdata", required_argument, NULL, 'D'},
		{"silent", no_argument, NULL, 's'},
		{"timeout", required_argument, NULL, 't'},
		{"core-files", no_argument, NULL, 'c'},
		{NULL, 0, NULL, 0}
	};

	int			option_index;
	int			c;
	pgpid_t		killproc = 0;

#if defined(WIN32) || defined(__CYGWIN__)
	setvbuf(stderr, NULL, _IONBF, 0);
#endif

	progname = get_progname(argv[0]);
	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_ctl"));

	/*
	 * save argv[0] so do_start() can look for the postmaster if necessary. we
	 * don't look for postmaster here because in many cases we won't need it.
	 */
	argv0 = argv[0];

	umask(077);

	/* support --help and --version even if invoked as root */
	if (argc > 1)
	{
		if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0 ||
			strcmp(argv[1], "-?") == 0)
		{
			do_help();
			exit(0);
		}
		else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0)
		{
			puts("pg_ctl (PostgreSQL) " PG_VERSION);
			exit(0);
		}
	}

	/*
	 * Disallow running as root, to forestall any possible security holes.
	 */
#ifndef WIN32
	if (geteuid() == 0)
	{
		write_stderr(_("%s: cannot be run as root\n"
					   "Please log in (using, e.g., \"su\") as the "
					   "(unprivileged) user that will\n"
					   "own the server process.\n"),
					 progname);
		exit(1);
	}
#endif

	/*
	 * 'Action' can be before or after args so loop over both. Some
	 * getopt_long() implementations will reorder argv[] to place all flags
	 * first (GNU?), but we don't rely on it. Our /port version doesn't do
	 * that.
	 */
	optind = 1;

	/* process command-line options */
	while (optind < argc)
	{
		while ((c = getopt_long(argc, argv, "cD:l:m:N:o:p:P:st:U:wW", long_options, &option_index)) != -1)
		{
			switch (c)
			{
				case 'D':
					{
						char	   *pgdata_D;
						char	   *env_var = pg_malloc(strlen(optarg) + 8);

						pgdata_D = xstrdup(optarg);
						canonicalize_path(pgdata_D);
						snprintf(env_var, strlen(optarg) + 8, "PGDATA=%s",
								 pgdata_D);
						putenv(env_var);

						/*
						 * We could pass PGDATA just in an environment
						 * variable but we do -D too for clearer postmaster
						 * 'ps' display
						 */
						pgdata_opt = pg_malloc(strlen(pgdata_D) + 7);
						snprintf(pgdata_opt, strlen(pgdata_D) + 7,
								 "-D \"%s\" ",
								 pgdata_D);
						break;
					}
				case 'l':
					log_file = xstrdup(optarg);
					break;
				case 'm':
					set_mode(optarg);
					break;
				case 'N':
					register_servicename = xstrdup(optarg);
					break;
				case 'o':
					post_opts = xstrdup(optarg);
					break;
				case 'p':
					exec_path = xstrdup(optarg);
					break;
				case 'P':
					register_password = xstrdup(optarg);
					break;
				case 's':
					silent_mode = true;
					break;
				case 't':
					wait_seconds = atoi(optarg);
					break;
				case 'U':
					if (strchr(optarg, '\\'))
						register_username = xstrdup(optarg);
					else
						/* Prepend .\ for local accounts */
					{
						register_username = malloc(strlen(optarg) + 3);
						if (!register_username)
						{
							write_stderr(_("%s: out of memory\n"), progname);
							exit(1);
						}
						strcpy(register_username, ".\\");
						strcat(register_username, optarg);
					}
					break;
				case 'w':
					do_wait = true;
					wait_set = true;
					break;
				case 'W':
					do_wait = false;
					wait_set = true;
					break;
				case 'c':
					allow_core_files = true;
					break;
				default:
					/* getopt_long already issued a suitable error message */
					do_advice();
					exit(1);
			}
		}

		/* Process an action */
		if (optind < argc)
		{
			if (ctl_command != NO_COMMAND)
			{
				write_stderr(_("%s: too many command-line arguments (first is \"%s\")\n"), progname, argv[optind]);
				do_advice();
				exit(1);
			}

			if (strcmp(argv[optind], "init") == 0
				|| strcmp(argv[optind], "initdb") == 0)
				ctl_command = INIT_COMMAND;
			else if (strcmp(argv[optind], "start") == 0)
				ctl_command = START_COMMAND;
			else if (strcmp(argv[optind], "stop") == 0)
				ctl_command = STOP_COMMAND;
			else if (strcmp(argv[optind], "restart") == 0)
				ctl_command = RESTART_COMMAND;
			else if (strcmp(argv[optind], "reload") == 0)
				ctl_command = RELOAD_COMMAND;
			else if (strcmp(argv[optind], "status") == 0)
				ctl_command = STATUS_COMMAND;
			else if (strcmp(argv[optind], "kill") == 0)
			{
				if (argc - optind < 3)
				{
					write_stderr(_("%s: missing arguments for kill mode\n"), progname);
					do_advice();
					exit(1);
				}
				ctl_command = KILL_COMMAND;
				set_sig(argv[++optind]);
				killproc = atol(argv[++optind]);
			}
#if defined(WIN32) || defined(__CYGWIN__)
			else if (strcmp(argv[optind], "register") == 0)
				ctl_command = REGISTER_COMMAND;
			else if (strcmp(argv[optind], "unregister") == 0)
				ctl_command = UNREGISTER_COMMAND;
			else if (strcmp(argv[optind], "runservice") == 0)
				ctl_command = RUN_AS_SERVICE_COMMAND;
#endif
			else
			{
				write_stderr(_("%s: unrecognized operation mode \"%s\"\n"), progname, argv[optind]);
				do_advice();
				exit(1);
			}
			optind++;
		}
	}

	if (ctl_command == NO_COMMAND)
	{
		write_stderr(_("%s: no operation specified\n"), progname);
		do_advice();
		exit(1);
	}

	/* Note we put any -D switch into the env var above */
	pg_data = getenv("PGDATA");
	if (pg_data)
	{
		pg_data = xstrdup(pg_data);
		canonicalize_path(pg_data);
	}

	if (pg_data == NULL &&
		ctl_command != KILL_COMMAND && ctl_command != UNREGISTER_COMMAND)
	{
		write_stderr(_("%s: no database directory specified "
					   "and environment variable PGDATA unset\n"),
					 progname);
		do_advice();
		exit(1);
	}

	if (!wait_set)
	{
		switch (ctl_command)
		{
			case RESTART_COMMAND:
			case START_COMMAND:
				do_wait = false;
				break;
			case STOP_COMMAND:
				do_wait = true;
				break;
			default:
				break;
		}
	}

	if (ctl_command == RELOAD_COMMAND)
	{
		sig = SIGHUP;
		do_wait = false;
	}

	if (pg_data)
	{
		snprintf(postopts_file, MAXPGPATH, "%s/postmaster.opts", pg_data);
		snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", pg_data);
		snprintf(conf_file, MAXPGPATH, "%s/postgresql.conf", pg_data);
		snprintf(backup_file, MAXPGPATH, "%s/backup_label", pg_data);
		snprintf(recovery_file, MAXPGPATH, "%s/recovery.conf", pg_data);
	}

	switch (ctl_command)
	{
		case INIT_COMMAND:
			do_init();
			break;
		case STATUS_COMMAND:
			do_status();
			break;
		case START_COMMAND:
			do_start();
			break;
		case STOP_COMMAND:
			do_stop();
			break;
		case RESTART_COMMAND:
			do_restart();
			break;
		case RELOAD_COMMAND:
			do_reload();
			break;
		case KILL_COMMAND:
			do_kill(killproc);
			break;
#if defined(WIN32) || defined(__CYGWIN__)
		case REGISTER_COMMAND:
			pgwin32_doRegister();
			break;
		case UNREGISTER_COMMAND:
			pgwin32_doUnregister();
			break;
		case RUN_AS_SERVICE_COMMAND:
			pgwin32_doRunAsService();
			break;
#endif
		default:
			break;
	}

	exit(0);
}
예제 #14
0
int Snapp_control_worker::handle_connection(){
   char recv_buf[CONTROL_BUF_SIZE];
   char send_buf[CONTROL_BUF_SIZE];
   int done=0;
   int rvalue;   
   int command;
   char *arg;
   int i;   


   //set conn state
   connection_state=CONTROL_CONNECTION_STATE_CONNECTED;

   //send hello!
   snprintf(send_buf,CONTROL_BUF_SIZE-1,"220 SNAPP server (%s) ready\r\n",VERSION);
   rvalue=send(fd,send_buf,strlen(send_buf),0);
   if(rvalue!=strlen(send_buf)){
      return 0;
   }
   while(0==done){
       //write snapp shell line:
       snprintf(send_buf,CONTROL_BUF_SIZE-1,"snapp> ");
       rvalue=send(fd,send_buf,strlen(send_buf),0);
       if(rvalue!=strlen(send_buf)){
           return 0;
       } 

       //read command
       command=-1;
       memset(recv_buf,0x00,CONTROL_BUF_SIZE);
       rvalue=recv(fd,recv_buf,CONTROL_BUF_SIZE-1,0);
       if(rvalue<=0){
          return 0;
       }
       //remove trailing chars(\n and \r)?
       for(i=0;i<rvalue;i++){
         if (recv_buf[i]=='\n' || recv_buf[i]=='\r' ){
            recv_buf[i]=0x00;
         }
       }    

       //do a 'switch like' on the command.
       if(recv_buf==strcasestr(recv_buf,"quit")){
         command=CONTROL_COMMAND_QUIT;
       }
       else if(0==strcasecmp(recv_buf,"reload")) {
         command=CONTROL_COMMAND_RELOAD;
       }
       else if(recv_buf==strcasestr(recv_buf,"status")){
         command=CONTROL_COMMAND_STATUS;
       }
       else if(recv_buf==strcasestr(recv_buf,"help")){
         command=CONTROL_COMMAND_HELP;
       }
       else if(recv_buf==strcasestr(recv_buf,"user ")){
         if(strlen(recv_buf)>=8){
           command=CONTROL_COMMAND_USER;
           arg=&recv_buf[5];   
         }
       }
       else if(recv_buf==strcasestr(recv_buf,"pass ")){
         if(strlen(recv_buf)>=8){
           command=CONTROL_COMMAND_PASS;
           arg=&recv_buf[5];
         }
       }
       else if(recv_buf==strcasestr(recv_buf,"logregexp ")){
         if(strlen(recv_buf)>=10){
           command=CONTROL_COMMAND_LOGREGEXP;
           arg=&recv_buf[10];
         }
       }
       // now actually do work
       switch(command <<8 |connection_state){
          case CONTROL_COMMAND_QUIT<<8 | CONTROL_CONNECTION_STATE_CONNECTED:
          case CONTROL_COMMAND_QUIT<<8 | CONTROL_CONNECTION_STATE_USERNAME_RECEIVED:
          case CONTROL_COMMAND_QUIT<<8 | CONTROL_CONNECTION_STATE_AUTHENTICATED:
              snprintf(send_buf,CONTROL_BUF_SIZE-1,"200 Goodbye\r\n");
              rvalue=send(fd,send_buf,strlen(send_buf),0);
              return 0;
              break;
          case CONTROL_COMMAND_USER<<8 | CONTROL_CONNECTION_STATE_CONNECTED:
              connection_state=CONTROL_CONNECTION_STATE_USERNAME_RECEIVED;
              snprintf(send_buf,CONTROL_BUF_SIZE-1,"331 Please specify the password\r\n");
              rvalue=send(fd,send_buf,strlen(send_buf),0);
              break;
          case CONTROL_COMMAND_PASS<<8 | CONTROL_CONNECTION_STATE_USERNAME_RECEIVED:
              if(0==parent->enable_password.compare(arg)){
                 connection_state=CONTROL_CONNECTION_STATE_AUTHENTICATED;
                 snprintf(send_buf,CONTROL_BUF_SIZE-1,"230 Login Sucessful\r\n");
                 rvalue=send(fd,send_buf,strlen(send_buf),0);
              }
              else{
                 snprintf(send_buf,CONTROL_BUF_SIZE-1,"530 Login Failure\r\n");
                 rvalue=send(fd,send_buf,strlen(send_buf),0);
              }
              break;
          
          case CONTROL_COMMAND_RELOAD<<8 | CONTROL_CONNECTION_STATE_AUTHENTICATED:
              rvalue=do_reload();
              if(rvalue<0){
                 return 0;
              }
              break;
          case CONTROL_COMMAND_LOGREGEXP<<8 | CONTROL_CONNECTION_STATE_AUTHENTICATED:
              rvalue=do_regexp(arg);
              if(rvalue<0){
                 return 0;
              }
              else{
                 //send failure!
              }

              break;

          case CONTROL_COMMAND_STATUS<<8 | CONTROL_CONNECTION_STATE_CONNECTED:
          case CONTROL_COMMAND_STATUS<<8 | CONTROL_CONNECTION_STATE_USERNAME_RECEIVED:
          case CONTROL_COMMAND_STATUS<<8 | CONTROL_CONNECTION_STATE_AUTHENTICATED:
              rvalue=send_status();
              if(rvalue<0){
                 return 0;
              }
              break;
          case CONTROL_COMMAND_HELP<<8 | CONTROL_CONNECTION_STATE_CONNECTED:
          case CONTROL_COMMAND_HELP<<8 | CONTROL_CONNECTION_STATE_USERNAME_RECEIVED:
          case CONTROL_COMMAND_HELP<<8 | CONTROL_CONNECTION_STATE_AUTHENTICATED:
              rvalue=send_help();
              if(rvalue<0){
                 return 0;
              }
              break;


          case CONTROL_COMMAND_RELOAD<<8 | CONTROL_CONNECTION_STATE_CONNECTED:
          case CONTROL_COMMAND_RELOAD<<8 | CONTROL_CONNECTION_STATE_USERNAME_RECEIVED:
              snprintf(send_buf,CONTROL_BUF_SIZE-1,"530 Not logged in\r\n");
              rvalue=send(fd,send_buf,strlen(send_buf),0);
              break;


          default:
              snprintf(send_buf,CONTROL_BUF_SIZE-1,"500 Command not recognized\r\n");
              rvalue=send(fd,send_buf,strlen(send_buf),0);
              if(rvalue!=strlen(send_buf)){
                 return 0;
              }

       }
       
    }

   
   return 0;
};