当前位置: 首页>>代码示例>>C++>>正文


C++ setgid函数代码示例

本文整理汇总了C++中setgid函数的典型用法代码示例。如果您正苦于以下问题:C++ setgid函数的具体用法?C++ setgid怎么用?C++ setgid使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了setgid函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: pty_open

int pty_open (int *pid, struct winsize *winsize, char **chargv, char **chenvp)
{
	int pty = -1;
	int i;
	char line[20];
	int c;
	int tty, devtty;

	for (c = 'a'; c <= 'z'; c++)
	{
		for (i = 0; i < 16; i++)
		{
			sprintf (line, "/dev/pty%c%x", c, i);
			pty = open (line, O_RDWR | O_NOCTTY);
			if (pty >= 0)
				break;
		}
		if (pty >= 0)
			break;
	}

	if (pty < 0)
	{
		fprintf (stderr, "Out of pty\n");
		return -1;
	}

	ioctl (pty, TIOCEXCL, NULL);

	if ((*pid = fork ()) != 0)
	{
		/* Father */
		return pty;
	}

	/* Child */

	close (pty);

	setenv ("TERM", "linux", 1);

	line[5] = 't';
	tty = open (line, O_RDWR);
	if (tty < 0)
	{
		fprintf (stderr, "Cannot open slave side\n");
		close (pty);
		return -1;
	}
	(void) chown (line, getuid (), getgid ());
	(void) chmod (line, 0600);

	setsid ();					/* will break terminal affiliation */
	ioctl (tty, TIOCSCTTY, (char *) 0);

	setuid (getuid ());
	setgid (getgid ());

	devtty = open ("/dev/tty", O_RDWR);
	if (devtty < 0)
	{
		perror ("cannot open /dev/tty");
		exit (1);
	}

/*      if (ioctl(devtty, TIOCNOTTY, (char *)0)) {
   perror("cannot do iotctl TIOCNOTTY");
   exit(1);
   }
 */
	ioctl (devtty, TIOCSWINSZ, winsize);
	close (tty);
	dup2 (devtty, 0);
	dup2 (devtty, 1);
	dup2 (devtty, 2);
	execve (chargv[0], chargv, chenvp);
	exit (0);
}
开发者ID:ve7fet,项目名称:fpac,代码行数:78,代码来源:fpacshell.c

示例2: _CreateProcessExA

BOOL _CreateProcessExA(HANDLE hToken, DWORD dwLogonFlags,
		LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes,
		LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment,
		LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation)
{
	pid_t pid;
	int flags;
	int numArgs;
	LPSTR* pArgs = NULL;
	char** envp = NULL;
	char* filename = NULL;
	HANDLE thread;
	HANDLE process;
	WINPR_ACCESS_TOKEN* token;
	LPTCH lpszEnvironmentBlock;
	BOOL ret = FALSE;

	pid = 0;
	numArgs = 0;
	lpszEnvironmentBlock = NULL;

	pArgs = CommandLineToArgvA(lpCommandLine, &numArgs);

	flags = 0;

	token = (WINPR_ACCESS_TOKEN*) hToken;

	if (lpEnvironment)
	{
		envp = EnvironmentBlockToEnvpA(lpEnvironment);
	}
	else
	{
		lpszEnvironmentBlock = GetEnvironmentStrings();
		envp = EnvironmentBlockToEnvpA(lpszEnvironmentBlock);
	}

	filename = FindApplicationPath(pArgs[0]);
	if (NULL == filename)
		goto finish;

	/* fork and exec */

	pid = fork();

	if (pid < 0)
	{
		/* fork failure */
		goto finish;
	}

	if (pid == 0)
	{
		/* child process */
#ifdef __sun
	closefrom(3);
#else
	int maxfd;
#ifdef F_MAXFD // on some BSD derivates
	maxfd = fcntl(0, F_MAXFD);
#else
	maxfd = sysconf(_SC_OPEN_MAX);
#endif
	int fd;
	for(fd=3; fd<maxfd; fd++)
		close(fd);
#endif // __sun

		if (token)
		{
			if (token->GroupId)
			{
				int rc = setgid((gid_t) token->GroupId);
				if (rc < 0)
				{
				}
				else
				{
					initgroups(token->Username, (gid_t) token->GroupId);
				}
			}

			if (token->UserId)
				setuid((uid_t) token->UserId);

			/* TODO: add better cwd handling and error checking */
			if (lpCurrentDirectory && strlen(lpCurrentDirectory) > 0)
				chdir(lpCurrentDirectory);
		}

		if (execve(filename, pArgs, envp) < 0)
		{
			/* execve failed - end the process */
			_exit(1);
		}
	}
	else
	{
		/* parent process */
	}
//.........这里部分代码省略.........
开发者ID:AMV007,项目名称:FreeRDP,代码行数:101,代码来源:process.c

示例3: startup

int startup(int argc, char* argv[])
{
  const char* tmp;
  const char* end;
  const char* cwdstr;
  char* ptr;
  unsigned long session_timeout;
  unsigned startup_code;

  if ((tmp = getenv("TCPLOCALIP")) == 0) FAIL("Missing $TCPLOCALIP.");
  if (!parse_localip(tmp)) FAIL("Could not parse $TCPLOCALIP.");
  if ((tmp = getenv("TCPREMOTEIP")) == 0) FAIL("Missing $TCPREMOTEIP.");
  if (!parse_remoteip(tmp)) FAIL("Could not parse $TCPREMOTEIP.");
  if ((tmp = getenv("UID")) == 0) FAIL("Missing $UID.");
  if (!(uid = strtou(tmp, &end)) || *end) FAIL("Invalid $UID.");
  if ((tmp = getenv("GID")) == 0) FAIL("Missing $GID.");
  if (!(gid = strtou(tmp, &end)) || *end) FAIL("Invalid $GID.");
  if ((home = getenv("HOME")) == 0) FAIL("Missing $HOME.");
  if ((tmp = getenv("GIDS")) != 0 && !parse_gids(tmp))
    FAIL("Could not parse or set supplementary group IDs.");

  /* Strip off trailing slashes in $HOME */
  ptr = (char*)home + strlen(home)-1;
  while (ptr > home && *ptr == '/') *ptr-- = 0;

  if ((user = getenv("USER")) == 0) FAIL("Missing $USER.");
  if ((group = getenv("GROUP")) == 0) group = "mygroup";
  if (chdir(home)) FAIL("Could not chdir to $HOME.");
  if (!load_tables()) FAIL("Loading startup tables failed.");
  if (getenv("CHROOT") != 0) {
    cwdstr = "/";
    if (chroot(".")) FAIL("Could not chroot.");
  }
  else if (getenv("SOFTCHROOT") != 0) {
    cwdstr = "/";
  }
  else {
    cwdstr = home;
    if (chdir("/")) FAIL("Could not chdir to '/'.");
  }
  if (!str_copys(&cwd, cwdstr)) FAIL("Could not set CWD string");
  if (setgid(gid)) FAIL("Could not set GID.");
  if (setuid(uid)) FAIL("Could not set UID.");
  if ((user_len = strlen(user)) > MAX_NAME_LEN) {
    user_len = MAX_NAME_LEN;
    ((char*)user)[MAX_NAME_LEN] = 0;
  }
  if ((group_len = strlen(group)) > MAX_NAME_LEN) {
    group_len = MAX_NAME_LEN;
    ((char*)group)[MAX_NAME_LEN] = 0;
  }

  lockhome = (getenv("LOCKHOME") != 0);
  nodotfiles = (getenv("NODOTFILES") != 0);
  list_options = (nodotfiles ? 0 : PATH_MATCH_DOTFILES);

  session_timeout = 0;
  if ((tmp = getenv("SESSION_TIMEOUT")) != 0)
    session_timeout = strtou(tmp, &tmp);
  alarm(session_timeout);
  connect_timeout = timeout;
  if ((tmp = getenv("CONNECT_TIMEOUT")) != 0)
    connect_timeout = strtou(tmp, &tmp);

  if ((tmp = getenv("TWOFTPD_BIND_PORT_FD")) != 0) {
    if ((bind_port_fd = strtou(tmp, &end)) == 0 || *end != 0)
      FAIL("Invalid $TWOFTPD_BIND_PORT_FD");
  }
  else
    bind_port_fd = -1;

  startup_code = (getenv("AUTHENTICATED") != 0) ? 230 : 220;
  if ((tmp = getenv("BANNER")) != 0) show_banner(startup_code, tmp);
  message_file = getenv("MESSAGEFILE");
  show_message_file(startup_code);
  return respond(startup_code, 1, "Ready to transfer files.");
  (void)argc;
  (void)argv;
}
开发者ID:bruceg,项目名称:twoftpd,代码行数:79,代码来源:backend.c

示例4: os_server_start_2

int
os_server_start_2(const char *user, int close_stdfiles)
{
     int istat;
     gid_t gid, old_egid, old_gid;
     uid_t uid, old_euid, old_uid;

     /*
      *  Close all open files but stdout & stderr
      */
     if (close_stdfiles)
     {
	  if (stderr)
	  {
	       fflush(stderr);
	       fclose(stderr);
	  }
	  else
	  {
	       fsync(2);
	       close(2);
	  }
	  if (stdout)
	  {
	       fflush(stdout);
	       fclose(stdout);
	  }
	  else
	  {
	       fsync(1);
	       close(1);
	  }
	  if (stdin)
	       fclose(stdin);
	  else
	       close(0);
	  os_close_files(3, 20);
     }

     /*
      *  Change our uid & gid
      */
     if (user && *user)
     {
	  if (os_uinfo(&uid, &gid, user))
	       return(-1);

	  /*
	   *  In case things fail....
	   */
	  old_euid = geteuid();
	  old_uid  = getuid();
	  old_egid = getegid();
	  old_gid  = getgid();

	  /*
	   *  On some platforms you first have to elevate the effective UID to
	   *  root before changing real & effective UID to a non-root UID.
	   */
	  seteuid(0);

	  /*
	   *  Now do an irreversible change of our UID and GID
	   */
	  if (setgid(gid))
	  {
	       int save_errno = errno;
	       seteuid(old_euid);
	       errno = save_errno;
	       return(-1);
	  }

	  if (setuid(uid))
	  {
	       int save_errno = errno;
	       seteuid(old_euid);
	       setgid(old_gid);
	       setegid(old_egid);
	       errno = save_errno;
	       return(-1);
	  }
     }
     return(0);
}
开发者ID:dcnewman,项目名称:ha7netd,代码行数:84,代码来源:os-unix.c

示例5: main

int main(int ac, char *av[])
{
	int ret;
	struct stat buf;
	struct group *group;
	struct passwd *user1;
	char DIR_A[MSGSIZE], DIR_B[MSGSIZE];
	char setgid_A[MSGSIZE], nosetgid_A[MSGSIZE];
	char setgid_B[MSGSIZE], nosetgid_B[MSGSIZE], root_setgid_B[MSGSIZE];
	gid_t group1_gid, group2_gid, mygid;
	uid_t save_myuid, user1_uid;
	pid_t mypid;

	int lc;
	int fail_count = 0;

	tst_parse_opts(ac, av, NULL, NULL);

	setup();

	for (lc = 0; TEST_LOOPING(lc); lc++) {
		local_flag = PASSED;

		save_myuid = getuid();
		mypid = getpid();
		sprintf(DIR_A, DIR_A_TEMP, mypid);
		sprintf(DIR_B, DIR_B_TEMP, mypid);
		sprintf(setgid_A, "%s/%s", DIR_A, SETGID);
		sprintf(nosetgid_A, "%s/%s", DIR_A, NOSETGID);
		sprintf(setgid_B, "%s/%s", DIR_B, SETGID);
		sprintf(nosetgid_B, "%s/%s", DIR_B, NOSETGID);
		sprintf(root_setgid_B, "%s/%s", DIR_B, ROOT_SETGID);

		/* Get the uid of user1 */
		user1 = getpwnam("nobody");
		if (user1 == NULL)
			tst_brkm(TBROK, cleanup, "nobody not in /etc/passwd");

		user1_uid = user1->pw_uid;

		/*
		 * Get the group IDs of group1 and group2.
		 */
		group = getgrnam("nobody");
		if (group == NULL) {
			group = getgrnam("nogroup");
			if (group == NULL) {
				tst_brkm(TBROK, cleanup,
					 "nobody/nogroup not in /etc/group");
			}
		}
		group1_gid = group->gr_gid;
		group = getgrnam("bin");
		if (group == NULL)
			tst_brkm(TBROK, cleanup, "bin not in /etc/group");

		group2_gid = group->gr_gid;

		/*
		 * Create a directory with group id the same as this process
		 * and with no setgid bit.
		 */
		if (mkdir(DIR_A, MODE_RWX) < 0) {
			tst_resm(TFAIL | TERRNO, "mkdir(%s) failed", DIR_A);
			local_flag = FAILED;
		}

		if (chown(DIR_A, user1_uid, group2_gid) < 0) {
			tst_resm(TFAIL | TERRNO, "chown(%s) failed", DIR_A);
			local_flag = FAILED;
		}

		if (stat(DIR_A, &buf) < 0) {
			tst_resm(TFAIL | TERRNO, "stat(%s) failed", DIR_A);
			local_flag = FAILED;
		}

		/* Verify modes */
		if (buf.st_mode & S_ISGID) {
			tst_resm(TFAIL, "%s: Incorrect modes, setgid bit set",
				 DIR_A);
			local_flag = FAILED;
		}

		/* Verify group ID */
		if (buf.st_gid != group2_gid) {
			tst_resm(TFAIL, "%s: Incorrect group (got %d and %d)",
				 DIR_A, buf.st_gid, group2_gid);
			local_flag = FAILED;
		}

		/*
		 * Create a directory with group id different from that of
		 * this process and with the setgid bit set.
		 */
		if (mkdir(DIR_B, MODE_RWX) < 0) {
			tst_resm(TFAIL | TERRNO, "mkdir(%s) failed", DIR_B);
			local_flag = FAILED;
		}

//.........这里部分代码省略.........
开发者ID:1587,项目名称:ltp,代码行数:101,代码来源:open10.c

示例6: ngx_worker_process_init

static void
ngx_worker_process_init(ngx_cycle_t *cycle, ngx_int_t worker)
{
    sigset_t          set;
    uint64_t          cpu_affinity;
    ngx_int_t         n;
    ngx_uint_t        i;
    struct rlimit     rlmt;
    ngx_core_conf_t  *ccf;
    ngx_listening_t  *ls;

    if (ngx_set_environment(cycle, NULL) == NULL) {
        /* fatal */
        exit(2);
    }

    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    if (worker >= 0 && ccf->priority != 0) {
        if (setpriority(PRIO_PROCESS, 0, ccf->priority) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setpriority(%d) failed", ccf->priority);
        }
    }

    if (ccf->rlimit_nofile != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_nofile;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_nofile;

        if (setrlimit(RLIMIT_NOFILE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_NOFILE, %i) failed",
                          ccf->rlimit_nofile);
        }
    }

    if (ccf->rlimit_core != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_core;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_core;

        if (setrlimit(RLIMIT_CORE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_CORE, %O) failed",
                          ccf->rlimit_core);
        }
    }

#ifdef RLIMIT_SIGPENDING
    if (ccf->rlimit_sigpending != NGX_CONF_UNSET) {
        rlmt.rlim_cur = (rlim_t) ccf->rlimit_sigpending;
        rlmt.rlim_max = (rlim_t) ccf->rlimit_sigpending;

        if (setrlimit(RLIMIT_SIGPENDING, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setrlimit(RLIMIT_SIGPENDING, %i) failed",
                          ccf->rlimit_sigpending);
        }
    }
#endif

    if (geteuid() == 0) {
        if (setgid(ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setgid(%d) failed", ccf->group);
            /* fatal */
            exit(2);
        }

        if (initgroups(ccf->username, ccf->group) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "initgroups(%s, %d) failed",
                          ccf->username, ccf->group);
        }

        if (setuid(ccf->user) == -1) {
            ngx_log_error(NGX_LOG_EMERG, cycle->log, ngx_errno,
                          "setuid(%d) failed", ccf->user);
            /* fatal */
            exit(2);
        }
    }

    if (worker >= 0) {
        cpu_affinity = ngx_get_cpu_affinity(worker);

        if (cpu_affinity) {
            ngx_setaffinity(cpu_affinity, cycle->log);
        }
    }

#if (NGX_HAVE_PR_SET_DUMPABLE)

    /* allow coredump after setuid() in Linux 2.4.x */

    if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "prctl(PR_SET_DUMPABLE) failed");
    }

#endif
//.........这里部分代码省略.........
开发者ID:RocFang,项目名称:nginx-code-reading,代码行数:101,代码来源:ngx_process_cycle.c

示例7: daemon_start

int	daemon_start(int allow_root, const char* user)
{
	pid_t   		pid;
	struct passwd		*pwd;
	struct sigaction	phan;

	/* running as root ?*/
	if((0 == allow_root) && (0 == getuid() || 0 == getgid()))
	{
		pwd = getpwnam(user);
		if (NULL == pwd)
		{
			zbx_error("User %s does not exist.",
				user);
			zbx_error("Cannot run as root !");
			exit(FAIL);
		}
		if(setgid(pwd->pw_gid) ==-1)
		{
			zbx_error("Cannot setgid to %s [%s].",
				user,
				strerror(errno));
			exit(FAIL);
		}
#ifdef HAVE_FUNCTION_INITGROUPS
		if(initgroups(user, pwd->pw_gid) == -1) 
		{
			zbx_error("Cannot initgroups to %s [%s].",
				user,
				strerror(errno));
			exit(FAIL);
		}
#endif /* HAVE_FUNCTION_INITGROUPS */
		if(setuid(pwd->pw_uid) == -1)
		{
			zbx_error("Cannot setuid to %s [%s].",
				user,
				strerror(errno));
			exit(FAIL);
		}

#ifdef HAVE_FUNCTION_SETEUID
		if( (setegid(pwd->pw_gid) ==-1) || (seteuid(pwd->pw_uid) == -1) )
		{
			zbx_error("Cannot setegid or seteuid to zabbix [%s].", strerror(errno));
			exit(FAIL);
		}
#endif /* HAVE_FUNCTION_SETEUID */

	}

	if( (pid = zbx_fork()) != 0 )	
	{				
		exit( 0 );		
	}				

	setsid();
	
	signal( SIGHUP, SIG_IGN );

	if( (pid = zbx_fork()) !=0 )	
	{				
		exit( 0 );		
	}				

	/* This is to eliminate warning: ignoring return value of chdir */
	if(-1 == chdir("/"))
	{
		assert(0);
	}
	umask(0002);

	redirect_std(CONFIG_LOG_FILE);

#ifdef HAVE_SYS_RESOURCE_SETPRIORITY

	if(setpriority(PRIO_PROCESS,0,5)!=0)
	{
		zbx_error("Unable to set process priority to 5. Leaving default.");
	}

#endif /* HAVE_SYS_RESOURCE_SETPRIORITY */

/*------------------------------------------------*/

	if( FAIL == create_pid_file(APP_PID_FILE))
	{
		exit(FAIL);
	}

	phan.sa_handler = child_signal_handler;
	sigemptyset(&phan.sa_mask);
	phan.sa_flags = 0;

	sigaction(SIGINT,	&phan, NULL);
	sigaction(SIGQUIT,	&phan, NULL);
	sigaction(SIGTERM,	&phan, NULL);
	sigaction(SIGPIPE,	&phan, NULL);

	zbx_setproctitle("main process");
//.........这里部分代码省略.........
开发者ID:Shmuma,项目名称:z,代码行数:101,代码来源:daemon.c

示例8: main


//.........这里部分代码省略.........
		switch(ch) {
		case 'u':
			user = optarg;
			if (*user == '\0')
				usage();
			break;
		case 'g':
			group = optarg;
			if (*group == '\0')
				usage();
			break;
		case 'G':
			grouplist = optarg;
			if (*grouplist == '\0')
				usage();
			break;
		case '?':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (argc < 1)
		usage();

	if (group != NULL) {
		if (isdigit((unsigned char)*group)) {
			gid = (gid_t)strtoul(group, &endp, 0);
			if (*endp != '\0')
				goto getgroup;
		} else {
 getgroup:
			if ((gp = getgrnam(group)) != NULL)
				gid = gp->gr_gid;
			else
				errx(1, "no such group `%s'", group);
		}
	}

	ngroups_max = sysconf(_SC_NGROUPS_MAX) + 1;
	if ((gidlist = malloc(sizeof(gid_t) * ngroups_max)) == NULL)
		err(1, "malloc");
	for (gids = 0;
	    (p = strsep(&grouplist, ",")) != NULL && gids < ngroups_max; ) {
		if (*p == '\0')
			continue;

		if (isdigit((unsigned char)*p)) {
			gidlist[gids] = (gid_t)strtoul(p, &endp, 0);
			if (*endp != '\0')
				goto getglist;
		} else {
 getglist:
			if ((gp = getgrnam(p)) != NULL)
				gidlist[gids] = gp->gr_gid;
			else
				errx(1, "no such group `%s'", p);
		}
		gids++;
	}
	if (p != NULL && gids == ngroups_max)
		errx(1, "too many supplementary groups provided");

	if (user != NULL) {
		if (isdigit((unsigned char)*user)) {
			uid = (uid_t)strtoul(user, &endp, 0);
			if (*endp != '\0')
				goto getuser;
		} else {
 getuser:
			if ((pw = getpwnam(user)) != NULL)
				uid = pw->pw_uid;
			else
				errx(1, "no such user `%s'", user);
		}
	}

	if (chdir(argv[0]) == -1 || chroot(".") == -1)
		err(1, "%s", argv[0]);

	if (gids && setgroups(gids, gidlist) == -1)
		err(1, "setgroups");
	if (group && setgid(gid) == -1)
		err(1, "setgid");
	if (user && setuid(uid) == -1)
		err(1, "setuid");

	if (argv[1]) {
		execvp(argv[1], &argv[1]);
		err(1, "%s", argv[1]);
	}

	if (!(shell = getenv("SHELL")))
		shell = _PATH_BSHELL;
	execlp(shell, shell, "-i", (char *)NULL);
	err(1, "%s", shell);
	/* NOTREACHED */
}
开发者ID:2asoft,项目名称:freebsd,代码行数:101,代码来源:chroot.c

示例9: drop_root

static int drop_root(void) {
    struct passwd *pw;
    struct group * gr;
    int r;
    
    
//Edison modify username 20131023
    char dut_user[128];
    memset(dut_user, 0, 128);
    
    strncpy(dut_user, nvram_safe_get("http_username"), 128);

    if (!(pw = getpwnam(dut_user))) {
	avahi_log_error( "Failed to find user '%s'.",dut_user);
        return -1;
    }

    if (!(gr = getgrnam(AVAHI_GROUP))) {
        avahi_log_error( "Failed to find group '"AVAHI_GROUP"'.");
        return -1;
    }

    avahi_log_info("Found user '%s' (UID %lu) and group '"AVAHI_GROUP"' (GID %lu).",dut_user ,(unsigned long) pw->pw_uid, (unsigned long) gr->gr_gid);

    if (initgroups(dut_user, gr->gr_gid) != 0) {
        avahi_log_error("Failed to change group list: %s", strerror(errno));
        return -1;
    }

#if defined(HAVE_SETRESGID)
    r = setresgid(gr->gr_gid, gr->gr_gid, gr->gr_gid);
#elif defined(HAVE_SETEGID)
    if ((r = setgid(gr->gr_gid)) >= 0)
        r = setegid(gr->gr_gid);
#elif defined(HAVE_SETREGID)
    r = setregid(gr->gr_gid, gr->gr_gid);
#else
#error "No API to drop privileges"
#endif

    if (r < 0) {
        avahi_log_error("Failed to change GID: %s", strerror(errno));
        return -1;
    }

#if defined(HAVE_SETRESUID)
    r = setresuid(pw->pw_uid, pw->pw_uid, pw->pw_uid);
#elif defined(HAVE_SETEUID)
    if ((r = setuid(pw->pw_uid)) >= 0)
        r = seteuid(pw->pw_uid);
#elif defined(HAVE_SETREUID)
    r = setreuid(pw->pw_uid, pw->pw_uid);
#else
#error "No API to drop privileges"
#endif

    if (r < 0) {
        avahi_log_error("Failed to change UID: %s", strerror(errno));
        return -1;
    }

    set_env("USER", pw->pw_name);
    set_env("LOGNAME", pw->pw_name);
    set_env("HOME", pw->pw_dir);

    avahi_log_info("Successfully dropped root privileges.");

    return 0;
}
开发者ID:gonzopancho,项目名称:asuswrt,代码行数:69,代码来源:main.c

示例10: main


//.........这里部分代码省略.........
    bh = 2 * font->head.high;
    bx = (screen->wide - bw) / 2;
    by = screen->high / 6 - bh / 2;
    cutebox(bx, by, bw, bh);
    printstr(bx + font->head.wide, by + bh - font->head.high / 2, hostname);
  }
  /*}}}  */
  /*{{{  draw login box*/
  {
    int bx, bw, by, bh;

    bx = (screen->wide - font->head.wide * 40) / 2;
    by = (screen->high - font->head.high * 8) / 2;
    bw = font->head.wide * 40;
    bh = font->head.high * 8;
    cutebox(bx, by, bw, bh);
  }
  /*}}}  */
  /*{{{  draw login box contents*/
  x = (screen->wide - font->head.wide * 18) / 2;
  login_y = screen->high / 2 - font->head.wide / 6;
  password_y = screen->high / 2 + font->head.high / 6 + font->head.high;
  printstr(x, password_y, "Password:         ");
  printstr((screen->wide - font->head.wide * 28) / 2, login_y - 2 * font->head.high,
      "Press ESC for terminal login");
  /*}}}  */
  while (1) {
    /*{{{  get login and password or escape*/
    printstr(x, login_y, "Login:            ");
    *loginstr = '\0';
    *passwordstr = '\0';
    do {
      ret = edit(x + font->head.wide * 10, login_y, loginstr, 1);
    } while ((ret == '\r' || ret == '\n') && *loginstr == '\0');
    if (ret == '\r' || ret == '\n') {
      ret = edit(x + font->head.wide * 10, password_y, passwordstr, 0);
      if (ret == '\r' || ret == '\n')
        ;
    }
    /*}}}  */
    if (ret == 27)
    /*{{{  exec to usual login -- not implemented yet*/
    {
      bit_destroy(screen);
      reset_tty(0);
      exit(0);
    }
    /*}}}  */
    else
    /*{{{  try login*/
    {
      struct passwd *pw;

      if ((pw = getpwnam(loginstr)) != NULL && strcmp(crypt(passwordstr, pw->pw_passwd), pw->pw_passwd) == 0)
      /*{{{  start window manager*/
      {
        char mgrlogin[_POSIX_PATH_MAX];
        char env_user[_POSIX_PATH_MAX], env_logname[_POSIX_PATH_MAX];
        char env_home[_POSIX_PATH_MAX], env_shell[_POSIX_PATH_MAX];
        char env_path[_POSIX_PATH_MAX], env_mail[_POSIX_PATH_MAX];
        char *login_env[7] = { env_user, env_logname, env_home, env_shell, env_path, env_mail, NULL };
        char *login_argv[2] = { "mgr", NULL };
        int i;

        sprintf(env_user, "USER=%s", pw->pw_name);
        sprintf(env_logname, "LOGNAME=%s", pw->pw_name);
        sprintf(env_home, "HOME=%s", pw->pw_dir);
        sprintf(env_shell, "SHELL=%s", pw->pw_shell == NULL || pw->pw_shell[0] == '\0' ? "/bin/sh" : pw->pw_shell);
        sprintf(env_path, "PATH=%s", PATH);
        sprintf(env_mail, "MAIL=%s/%s", MAILDIR, pw->pw_name);
        if (chdir(pw->pw_dir) != 0)
          chdir("/");
        if (ttyname(0)) {
          chown(ttyname(0), pw->pw_uid, pw->pw_gid);
          chmod(ttyname(0), 0600);
        }
        for (i = 1; i <= _NSIG; i++)
          signal(i, SIG_DFL);
        bit_destroy(screen);
        reset_tty(0);
        initgroups(pw->pw_name, pw->pw_gid);
        setgid(pw->pw_gid);
        setuid(pw->pw_uid);
        sprintf(mgrlogin, "%s/.mgrlogin", pw->pw_dir);
        execve(mgrlogin, login_argv, login_env);
        execve(MGR_BINARY, login_argv, login_env);
        exit(EX_OSFILE);
      }
      /*}}}  */
      else
      /*{{{  incorrect login*/
      {
        printstr((screen->wide - font->head.wide * 16) / 2, login_y + 3 * font->head.high,
            "Login incorrect");
      }
      /*}}}  */
    }
    /*}}}  */
  }
}
开发者ID:waywardmonkeys,项目名称:bellcore-mgr,代码行数:101,代码来源:mgrlogin.c

示例11: main

int
main(int argc, char **argv)
{
	int i;
	int rval,ll;
	struct text *kk;

	/* If the user hits start, bail */
	cont_btn_callback(0, CONT_START, (cont_btn_callback_t)arch_exit);

	pvr_init_defaults();
	conio_init(CONIO_TTY_PVR, CONIO_INPUT_LINE);

#if 0
	/* revoke */
	setgid(getgid());
#endif

	init();         /* Initialize everything */
	/* signal(SIGINT,trapdel); */

#if 0
	if (argc > 1)   /* Restore file specified */
	{               /* Restart is label 8305 (Fortran) */
		i = restore(argv[1]);       /* See what we've got */
		switch(i)
		{
		    case 0:     /* The restore worked fine */
			yea=Start();
			k=null;
			unlink(argv[1]);/* Don't re-use the save */
			goto l8;        /* Get where we're going */
		    case 1:             /* Couldn't open it */
			exit(1);        /* So give up */
		    case 2:             /* Oops -- file was altered */
			rspeak(202);    /* You dissolve */
			exit(1);        /* File could be non-adventure */
		}                       /* So don't unlink it. */
	}
#endif

	startup();              /* prepare for a user           */

	for (;;)                        /* main command loop (label 2)  */
	{       if (newloc<9 && newloc!=0 && closng)
		{       rspeak(130);    /* if closing leave only by     */
			newloc=loc;     /*      main office             */
			if (!apanic) clock2=15;
			apanic=TRUE;
		}

		rval=fdwarf();          /* dwarf stuff                  */
		if (rval==99) die(99);

	l2000:  if (loc==0) die(99);    /* label 2000                   */
		kk = &stext[loc];
		if ((abb[loc]%abbnum)==0 || kk->seekadr==0)
			kk = &ltext[loc];
		if (!forced(loc) && dark())
		{       if (wzdark && pct(35))
			{       die(90);
				goto l2000;
			}
			kk = &rtext[16];
		}
		if (toting(bear)) rspeak(141);  /* 2001                 */
		speak(kk);
		k=1;
		if (forced(loc))
			goto l8;
		if (loc==33 && pct(25)&&!closng) rspeak(8);
		if (!dark())
		{       abb[loc]++;
			for (i=atloc[loc]; i!=0; i=linkx[i])     /*2004  */
			{       obj=i;
				if (obj>100) obj -= 100;
				if (obj==steps && toting(nugget)) continue;
				if (prop[obj]<0)
				{       if (closed) continue;
					prop[obj]=0;
					if (obj==rug||obj==chain)
						prop[obj]=1;
					tally--;
					if (tally==tally2 && tally != 0)
						if (limit>35) limit=35;
				}
				ll =  prop[obj];   /* 2006         */
				if (obj==steps && loc==fixed[steps])
					ll = 1;
				pspeak(obj, ll);
			}                                       /* 2008 */
			goto l2012;
	l2009:          k=54;                   /* 2009                 */
	l2010:          spk=k;
	l2011:          rspeak(spk);
		}
	l2012:  verb=0;                         /* 2012                 */
		obj=0;
	l2600:	checkhints();                   /* to 2600-2602         */
		if (closed)
//.........这里部分代码省略.........
开发者ID:zig,项目名称:kos-dcplaya,代码行数:101,代码来源:main.c

示例12: daemon_start

/******************************************************************************
 *                                                                            *
 * Function: daemon_start                                                     *
 *                                                                            *
 * Purpose: init process as daemon                                            *
 *                                                                            *
 * Parameters: allow_root - allow root permission for application             *
 *                                                                            *
 * Author: Alexei Vladishev                                                   *
 *                                                                            *
 * Comments: it doesn't allow running under 'root' if allow_root is zero      *
 *                                                                            *
 ******************************************************************************/
int	daemon_start(int allow_root)
{
	pid_t			pid;
	struct passwd		*pwd;
	struct sigaction	phan;
	char			user[7] = "zabbix";

	/* running as root ? */
	if (0 == allow_root && (0 == getuid() || 0 == getgid()))
	{
		pwd = getpwnam(user);
		if (NULL == pwd)
		{
			zbx_error("user %s does not exist", user);
			zbx_error("Cannot run as root!");
			exit(FAIL);
		}

		if (-1 == setgid(pwd->pw_gid))
		{
			zbx_error("cannot setgid to %s: %s", user, zbx_strerror(errno));
			exit(FAIL);
		}

#ifdef HAVE_FUNCTION_INITGROUPS
		if (-1 == initgroups(user, pwd->pw_gid))
		{
			zbx_error("cannot initgroups to %s: %s", user, zbx_strerror(errno));
			exit(FAIL);
		}
#endif

		if (-1 == setuid(pwd->pw_uid))
		{
			zbx_error("cannot setuid to %s: %s", user, zbx_strerror(errno));
			exit(FAIL);
		}

#ifdef HAVE_FUNCTION_SETEUID
		if (-1 == setegid(pwd->pw_gid) || -1 == seteuid(pwd->pw_uid))
		{
			zbx_error("cannot setegid or seteuid to %s: %s", user, zbx_strerror(errno));
			exit(FAIL);
		}
#endif
	}

	if (0 != (pid = zbx_fork()))
		exit(0);

	setsid();

	signal(SIGHUP, SIG_IGN);

	if (0 != (pid = zbx_fork()))
		exit(0);

	/* this is to eliminate warning: ignoring return value of chdir */
	if (-1 == chdir("/"))
		assert(0);

	umask(0002);

	redirect_std(CONFIG_LOG_FILE);

#ifdef HAVE_SYS_RESOURCE_SETPRIORITY
	if (0 != setpriority(PRIO_PROCESS, 0, 5))
		zbx_error("Unable to set process priority to 5. Leaving default.");
#endif

/*------------------------------------------------*/

	if (FAIL == create_pid_file(CONFIG_PID_FILE))
		exit(FAIL);

	parent_pid = (int)getpid();

	phan.sa_sigaction = child_signal_handler;
	sigemptyset(&phan.sa_mask);
	phan.sa_flags = SA_SIGINFO;

	sigaction(SIGINT, &phan, NULL);
	sigaction(SIGQUIT, &phan, NULL);
	sigaction(SIGTERM, &phan, NULL);
	sigaction(SIGPIPE, &phan, NULL);
	sigaction(SIGILL, &phan, NULL);
	sigaction(SIGFPE, &phan, NULL);
//.........这里部分代码省略.........
开发者ID:baniuyao,项目名称:Zabbix_PPTV,代码行数:101,代码来源:daemon.c

示例13: _run_extcmd

/* Run an external command returning exit status, and optionally filling
 * provided buffer with STDOUT output up to the size provided.
 *
 * Note: XXX: We are not using the timeout parameter at present. We still need
 *       to implement a reliable timeout mechanism.
*/
static int
_run_extcmd(uid_t uid, gid_t gid, const char *cmd, char *so_buf,
        const size_t so_buf_sz, const int cflag, const int timeout,
        const char *substr_search, int *pid_status,
        const fko_srv_options_t * const opts)
{
    char    so_read_buf[IO_READ_BUF_LEN] = {0};
    pid_t   pid=0;
    FILE   *output;
    int     retval = EXTCMD_SUCCESS_ALL_OUTPUT;
    int     line_ctr = 0, found_str = 0, do_break = 0;

    char   *argv_new[MAX_CMDLINE_ARGS]; /* for validation and/or execvpe() */
    int     argc_new=0;

#if HAVE_EXECVPE
    int     pipe_fd[2];
#endif

#if AFL_FUZZING
    /* Don't allow command execution in AFL fuzzing mode
    */
    return 0;
#endif

    *pid_status = 0;

    /* Even without execvpe() we examine the command for basic validity
     * in term of number of args
    */
    memset(argv_new, 0x0, sizeof(argv_new));

    if(strtoargv(cmd, argv_new, &argc_new) != 1)
    {
        log_msg(LOG_ERR,
                "run_extcmd(): Error converting cmd str to argv via strtoargv()");
        return EXTCMD_ARGV_ERROR;
    }

#if !HAVE_EXECVPE
    /* if we are not using execvpe() then free up argv_new unconditionally
     * since was used only for validation
    */
    free_argv(argv_new, &argc_new);
#endif

#if HAVE_EXECVPE
    if(opts->verbose > 1)
        log_msg(LOG_INFO, "run_extcmd() (with execvpe()): running CMD: %s", cmd);

    if(so_buf != NULL || substr_search != NULL)
    {
        if(pipe(pipe_fd) < 0)
        {
            log_msg(LOG_ERR, "run_extcmd(): pipe() failed: %s", strerror(errno));
            free_argv(argv_new, &argc_new);
            return EXTCMD_PIPE_ERROR;
        }
    }

	//在子进程中创建CMD。
    pid = fork();
    if (pid == 0)
    {
        if(chdir("/") != 0)
            exit(EXTCMD_CHDIR_ERROR);

        if(so_buf != NULL || substr_search != NULL)
        {
            close(pipe_fd[0]);
            dup2(pipe_fd[1], STDOUT_FILENO);
            if(cflag & WANT_STDERR)
                dup2(pipe_fd[1], STDERR_FILENO);
            else
                close(STDERR_FILENO);
        }

        /* Take care of gid/uid settings before running the command.
        */
        if(gid > 0)
            if(setgid(gid) < 0)
                exit(EXTCMD_SETGID_ERROR);

        if(uid > 0)
            if(setuid(uid) < 0)
                exit(EXTCMD_SETUID_ERROR);

        /* don't use env
        */
        execvpe(argv_new[0], argv_new, (char * const *)NULL);
    }
    else if(pid == -1)
    {
        log_msg(LOG_ERR, "run_extcmd(): fork() failed: %s", strerror(errno));
//.........这里部分代码省略.........
开发者ID:weizn11,项目名称:fwknop,代码行数:101,代码来源:extcmd.c

示例14: main

int main(int argc, char **argv)
{
	const struct optstruct *opt;
#ifndef	C_WINDOWS
        struct passwd *user = NULL;
#endif
	time_t currtime;
	const char *dbdir, *cfgfile;
	char *pua_cats = NULL, *pt;
	int ret, tcpsock = 0, localsock = 0, i, min_port, max_port;
	unsigned int sigs = 0;
	int lsockets[2], nlsockets = 0;
	unsigned int dboptions = 0;
#ifdef C_LINUX
	struct stat sb;
#endif

#ifdef C_WINDOWS
    if(!pthread_win32_process_attach_np()) {
	mprintf("!Can't start the win32 pthreads layer\n");
        return 1;
    }
#endif

    if((opts = optparse(NULL, argc, argv, 1, OPT_CLAMD, 0, NULL)) == NULL) {
	mprintf("!Can't parse command line options\n");
	return 1;
    }

    if(optget(opts, "help")->enabled) {
    	help();
	optfree(opts);
	return 0;
    }

    if(optget(opts, "debug")->enabled) {
#if defined(C_LINUX)
	    /* [email protected]: create a dump if needed */
	    struct rlimit rlim;

	rlim.rlim_cur = rlim.rlim_max = RLIM_INFINITY;
	if(setrlimit(RLIMIT_CORE, &rlim) < 0)
	    perror("setrlimit");
#endif
	debug_mode = 1;
    }

    /* parse the config file */
    cfgfile = optget(opts, "config-file")->strarg;
    pt = strdup(cfgfile);
    if((opts = optparse(cfgfile, 0, NULL, 1, OPT_CLAMD, 0, opts)) == NULL) {
	fprintf(stderr, "ERROR: Can't open/parse the config file %s\n", pt);
	free(pt);
	return 1;
    }
    free(pt);

    if(optget(opts, "version")->enabled) {
	print_version(optget(opts, "DatabaseDirectory")->strarg);
	optfree(opts);
	return 0;
    }

    umask(0);

    /* drop privileges */
#if (!defined(C_OS2)) && (!defined(C_WINDOWS))
    if(geteuid() == 0 && (opt = optget(opts, "User"))->enabled) {
	if((user = getpwnam(opt->strarg)) == NULL) {
	    fprintf(stderr, "ERROR: Can't get information about user %s.\n", opt->strarg);
	    optfree(opts);
	    return 1;
	}

	if(optget(opts, "AllowSupplementaryGroups")->enabled) {
#ifdef HAVE_INITGROUPS
	    if(initgroups(opt->strarg, user->pw_gid)) {
		fprintf(stderr, "ERROR: initgroups() failed.\n");
		optfree(opts);
		return 1;
	    }
#else
	    mprintf("!AllowSupplementaryGroups: initgroups() is not available, please disable AllowSupplementaryGroups in %s\n", cfgfile);
	    optfree(opts);
	    return 1;
#endif
	} else {
#ifdef HAVE_SETGROUPS
	    if(setgroups(1, &user->pw_gid)) {
		fprintf(stderr, "ERROR: setgroups() failed.\n");
		optfree(opts);
		return 1;
	    }
#endif
	}

	if(setgid(user->pw_gid)) {
	    fprintf(stderr, "ERROR: setgid(%d) failed.\n", (int) user->pw_gid);
	    optfree(opts);
	    return 1;
//.........这里部分代码省略.........
开发者ID:gittestusername,项目名称:uClinux,代码行数:101,代码来源:clamd.c

示例15: start_child

static gboolean
start_child(pcmk_child_t * child)
{
    int lpc = 0;
    uid_t uid = 0;
    gid_t gid = 0;
    struct rlimit oflimits;
    gboolean use_valgrind = FALSE;
    gboolean use_callgrind = FALSE;
    const char *devnull = "/dev/null";
    const char *env_valgrind = getenv("PCMK_valgrind_enabled");
    const char *env_callgrind = getenv("PCMK_callgrind_enabled");
    enum cluster_type_e stack = get_cluster_type();

    child->active_before_startup = FALSE;

    if (child->command == NULL) {
        crm_info("Nothing to do for child \"%s\"", child->name);
        return TRUE;
    }

    if (env_callgrind != NULL && crm_is_true(env_callgrind)) {
        use_callgrind = TRUE;
        use_valgrind = TRUE;

    } else if (env_callgrind != NULL && strstr(env_callgrind, child->name)) {
        use_callgrind = TRUE;
        use_valgrind = TRUE;

    } else if (env_valgrind != NULL && crm_is_true(env_valgrind)) {
        use_valgrind = TRUE;

    } else if (env_valgrind != NULL && strstr(env_valgrind, child->name)) {
        use_valgrind = TRUE;
    }

    if (use_valgrind && strlen(VALGRIND_BIN) == 0) {
        crm_warn("Cannot enable valgrind for %s:"
                 " The location of the valgrind binary is unknown", child->name);
        use_valgrind = FALSE;
    }

    if (child->uid) {
        if (crm_user_lookup(child->uid, &uid, &gid) < 0) {
            crm_err("Invalid user (%s) for %s: not found", child->uid, child->name);
            return FALSE;
        }
        crm_info("Using uid=%u and group=%u for process %s", uid, gid, child->name);
    }

    child->pid = fork();
    CRM_ASSERT(child->pid != -1);

    if (child->pid > 0) {
        /* parent */
        mainloop_child_add(child->pid, 0, child->name, child, pcmk_child_exit);

        crm_info("Forked child %d for process %s%s", child->pid, child->name,
                 use_valgrind ? " (valgrind enabled: " VALGRIND_BIN ")" : "");
        update_node_processes(local_nodeid, NULL, get_process_list());
        return TRUE;

    } else {
        /* Start a new session */
        (void)setsid();

        /* Setup the two alternate arg arrarys */
        opts_vgrind[0] = strdup(VALGRIND_BIN);
        if (use_callgrind) {
            opts_vgrind[1] = strdup("--tool=callgrind");
            opts_vgrind[2] = strdup("--callgrind-out-file=" CRM_STATE_DIR "/callgrind.out.%p");
            opts_vgrind[3] = strdup(child->command);
            opts_vgrind[4] = NULL;
        } else {
            opts_vgrind[1] = strdup(child->command);
            opts_vgrind[2] = NULL;
            opts_vgrind[3] = NULL;
            opts_vgrind[4] = NULL;
        }
        opts_default[0] = strdup(child->command);;

        if(gid) {
            if(stack == pcmk_cluster_corosync) {
                /* Drop root privileges completely
                 *
                 * We can do this because we set uidgid.gid.${gid}=1
                 * via CMAP which allows these processes to connect to
                 * corosync
                 */
                if (setgid(gid) < 0) {
                    crm_perror(LOG_ERR, "Could not set group to %d", gid);
                }

                /* Keep the root group (so we can access corosync), but add the haclient group (so we can access ipc) */
            } else if (initgroups(child->uid, gid) < 0) {
                crm_err("Cannot initalize groups for %s: %s (%d)", child->uid, pcmk_strerror(errno), errno);
            }
        }

        if (uid && setuid(uid) < 0) {
//.........这里部分代码省略.........
开发者ID:HyunKwangYong,项目名称:pacemaker,代码行数:101,代码来源:pacemaker.c


注:本文中的setgid函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。