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


C++ setuid函数代码示例

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


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

示例1: _on_ckpt_complete

/* a checkpoint completed, process the images files */
static int _on_ckpt_complete(uint32_t group_id, uint32_t user_id,
			     uint32_t job_id, uint32_t step_id,
			     char *image_dir, uint32_t error_code)
{
	int status;
	pid_t cpid;

	if (access(scch_path, R_OK | X_OK) < 0) {
		if (errno == ENOENT)
			debug("checkpoint/blcr: file %s not found", scch_path);
		else
			info("Access denied for %s: %m", scch_path);
		return SLURM_ERROR;
	}

	if ((cpid = fork()) < 0) {
		error ("_on_ckpt_complete: fork: %m");
		return SLURM_ERROR;
	}

	if (cpid == 0) {
		/*
		 * We don't fork and wait the child process because the job
		 * read lock is held. It could take minutes to delete/move
		 * the checkpoint image files. So there is a race condition
		 * of the user requesting another checkpoint before SCCH
		 * finishes.
		 */
		/* fork twice to avoid zombies */
		if ((cpid = fork()) < 0) {
			error("_on_ckpt_complete: second fork: %m");
			exit(127);
		}
		/* grand child execs */
		if (cpid == 0) {
			char *args[6];
			char str_job[11];
			char str_step[11];
			char str_err[11];

			/*
			 * XXX: if slurmctld is running as root, we must setuid here.
			 * But what if slurmctld is running as SlurmUser?
			 * How about we make scch setuid and pass the user/group to it?
			 */
			if (geteuid() == 0) { /* root */
				if (setgid(group_id) < 0) {
					error("_on_ckpt_complete: failed to "
					      "setgid: %m");
					exit(127);
				}
				if (setuid(user_id) < 0) {
					error("_on_ckpt_complete: failed to "
					      "setuid: %m");
					exit(127);
				}
			}
			snprintf(str_job,  sizeof(str_job),  "%u", job_id);
			snprintf(str_step, sizeof(str_step), "%u", step_id);
			snprintf(str_err,  sizeof(str_err),  "%u", error_code);

			args[0] = (char *)scch_path;
			args[1] = str_job;
			args[2] = str_step;
			args[3] = str_err;
			args[4] = image_dir;
			args[5] = NULL;

			execv(scch_path, args);
			error("execv failure: %m");
			exit(127);
		}
		/* child just exits */
		exit(0);
	}

	while(1) {
		if (waitpid(cpid, &status, 0) < 0 && errno == EINTR)
			continue;
		break;
	}

	return SLURM_SUCCESS;
}
开发者ID:edsw,项目名称:slurm,代码行数:85,代码来源:checkpoint_blcr.c

示例2: main

int main(int argc, char **argv) {
  char *gidmap = NULL, *inside = NULL, *outside = NULL, *uidmap = NULL;
  char *bind = NULL;
  int hostnet = 0, master, option, stdio = 0;
  pid_t child, parent;

  while ((option = getopt(argc, argv, "+:b:cg:i:no:u:")) > 0)
    switch (option) {
      case 'b':
        bind = optarg;
        break;
      case 'c':
        stdio++;
        break;
      case 'g':
        gidmap = optarg;
        break;
      case 'i':
        inside = optarg;
        break;
      case 'n':
        hostnet++;
        break;
      case 'o':
        outside = optarg;
        break;
      case 'u':
        uidmap = optarg;
        break;
      default:
        usage(argv[0]);
    }

  if (argc <= optind)
    usage(argv[0]);

  parent = getpid();
  switch (child = fork()) {
    case -1:
      error(1, errno, "fork");
    case 0:
      raise(SIGSTOP);
//      if (geteuid() != 0)
//        denysetgroups(parent);
      writemap(parent, GID, gidmap);
      writemap(parent, UID, uidmap);

      if (outside) {
        if (setgid(getgid()) < 0 || setuid(getuid()) < 0)
          error(1, 0, "Failed to drop privileges");
        execlp(SHELL, SHELL, "-c", outside, NULL);
        error(1, errno, "exec %s", outside);
      }

      exit(EXIT_SUCCESS);
  }

  if (setgid(getgid()) < 0 || setuid(getuid()) < 0)
    error(1, 0, "Failed to drop privileges");

  if (unshare(CLONE_NEWIPC | CLONE_NEWNS | CLONE_NEWUSER | CLONE_NEWUTS) < 0)
    error(1, 0, "Failed to unshare namespaces");

  if (!hostnet && unshare(CLONE_NEWNET) < 0)
      error(1, 0, "Failed to unshare network namespace");

  waitforstop(child);
  kill(child, SIGCONT);
  waitforexit(child);

  setgid(0);
  setgroups(0, NULL);
  setuid(0);

  master = stdio ? -1 : getconsole();
  createroot(argv[optind], master, inside, bind);

  unshare(CLONE_NEWPID);
  switch (child = fork()) {
    case -1:
      error(1, errno, "fork");
    case 0:
      mountproc();
      if (!hostnet)
        mountsys();
      enterroot();

      if (master >= 0) {
        close(master);
        setconsole("/dev/console");
      }

      clearenv();
      putenv("container=contain");

      if (argv[optind + 1])
        execv(argv[optind + 1], argv + optind + 1);
      else
        execl(SHELL, SHELL, NULL);
      error(1, errno, "exec");
//.........这里部分代码省略.........
开发者ID:YustasSwamp,项目名称:containers,代码行数:101,代码来源:contain.c

示例3: attach_child_main

static int attach_child_main(void* data)
{
	struct attach_clone_payload* payload = (struct attach_clone_payload*)data;
	int ipc_socket = payload->ipc_socket;
	lxc_attach_options_t* options = payload->options;
	struct lxc_proc_context_info* init_ctx = payload->init_ctx;
#if HAVE_SYS_PERSONALITY_H
	long new_personality;
#endif
	int ret;
	int status;
	int expected;
	long flags;
	int fd;
	uid_t new_uid;
	gid_t new_gid;

	/* wait for the initial thread to signal us that it's ready
	 * for us to start initializing
	 */
	expected = 0;
	status = -1;
	ret = lxc_read_nointr_expect(ipc_socket, &status, sizeof(status), &expected);
	if (ret <= 0) {
		ERROR("error using IPC to receive notification from initial process (0)");
		shutdown(ipc_socket, SHUT_RDWR);
		rexit(-1);
	}

	/* A description of the purpose of this functionality is
	 * provided in the lxc-attach(1) manual page. We have to
	 * remount here and not in the parent process, otherwise
	 * /proc may not properly reflect the new pid namespace.
	 */
	if (!(options->namespaces & CLONE_NEWNS) && (options->attach_flags & LXC_ATTACH_REMOUNT_PROC_SYS)) {
		ret = lxc_attach_remount_sys_proc();
		if (ret < 0) {
			shutdown(ipc_socket, SHUT_RDWR);
			rexit(-1);
		}
	}

	/* now perform additional attachments*/
#if HAVE_SYS_PERSONALITY_H
	if (options->personality < 0)
		new_personality = init_ctx->personality;
	else
		new_personality = options->personality;

	if (options->attach_flags & LXC_ATTACH_SET_PERSONALITY) {
		ret = personality(new_personality);
		if (ret < 0) {
			SYSERROR("could not ensure correct architecture");
			shutdown(ipc_socket, SHUT_RDWR);
			rexit(-1);
		}
	}
#endif

	if (options->attach_flags & LXC_ATTACH_DROP_CAPABILITIES) {
		ret = lxc_attach_drop_privs(init_ctx);
		if (ret < 0) {
			ERROR("could not drop privileges");
			shutdown(ipc_socket, SHUT_RDWR);
			rexit(-1);
		}
	}

	/* always set the environment (specify (LXC_ATTACH_KEEP_ENV, NULL, NULL) if you want this to be a no-op) */
	ret = lxc_attach_set_environment(options->env_policy, options->extra_env_vars, options->extra_keep_env);
	if (ret < 0) {
		ERROR("could not set initial environment for attached process");
		shutdown(ipc_socket, SHUT_RDWR);
		rexit(-1);
	}

	/* set user / group id */
	new_uid = 0;
	new_gid = 0;
	/* ignore errors, we will fall back to root in that case
	 * (/proc was not mounted etc.)
	 */
	if (options->namespaces & CLONE_NEWUSER)
		lxc_attach_get_init_uidgid(&new_uid, &new_gid);

	if (options->uid != (uid_t)-1)
		new_uid = options->uid;
	if (options->gid != (gid_t)-1)
		new_gid = options->gid;

	/* try to set the uid/gid combination */
	if ((new_gid != 0 || options->namespaces & CLONE_NEWUSER)) {
		if (setgid(new_gid) || setgroups(0, NULL)) {
			SYSERROR("switching to container gid");
			shutdown(ipc_socket, SHUT_RDWR);
			rexit(-1);
		}
	}
	if ((new_uid != 0 || options->namespaces & CLONE_NEWUSER) && setuid(new_uid)) {
		SYSERROR("switching to container uid");
//.........这里部分代码省略.........
开发者ID:Red54,项目名称:lxc,代码行数:101,代码来源:attach.c

示例4: edit_file

void
edit_file(char *buf)
    /* copy file to a temp file, edit that file, and install it
       if necessary */
{
    char *cureditor = NULL;
    char editorcmd[PATH_LEN];
    pid_t pid;
    int status;
    struct stat st;
    time_t mtime = 0;
    char *tmp_str;
    FILE *f, *fi;
    int file = 0;
    int c;
    char correction = 0;
    short return_val = EXIT_OK;

    explain("fcrontab : editing %s's fcrontab", user);	

    if ((cureditor=getenv("VISUAL")) == NULL || strcmp(cureditor, "\0") == 0 )
	if((cureditor=getenv("EDITOR"))==NULL || strcmp(cureditor, "\0") == 0 )
	    cureditor = editor;
	
    file = temp_file(&tmp_str);
    if ( (fi = fdopen(file, "w")) == NULL ) {
	error_e("could not fdopen");
	goto exiterr;
    }
#ifndef USE_SETE_ID
    if (fchown(file, asuid, asgid) != 0) {
	error_e("Could not fchown %s to asuid and asgid", tmp_str);
	goto exiterr;
    }
#endif
    /* copy user's fcrontab (if any) to a temp file */
    if ( (f = fopen(buf, "r")) == NULL ) {
	if ( errno != ENOENT ) {
	    error_e("could not open file %s", buf);
	    goto exiterr;
	}
	else
	    fprintf(stderr, "no fcrontab for %s - using an empty one\n",
		    user);
    }
    else { 
	/* copy original file to temp file */
	while ( (c=getc(f)) != EOF )
	    putc(c, fi);
	fclose(f);
    }

    fclose(fi);
    close(file);

    do {

	if ( stat(tmp_str, &st) == 0 )
	    mtime = st.st_mtime;
	else {
	    error_e("could not stat \"%s\"", buf);
	    goto exiterr;
	}

	switch ( pid = fork() ) {
	case 0:
	    /* child */
	    if ( uid != ROOTUID ) {
		if (setgid(asgid) < 0) {
		    error_e("setgid(asgid)");
		    goto exiterr;
		}
		if (setuid(asuid) < 0) {
		    error_e("setuid(asuid)");
		    goto exiterr;
		}
	    }
	    else {
		/* Some programs, like perl, require gid=egid : */
		if ( setgid(getgid()) < 0 ) {
		    error_e("setgid(getgid())");
		    goto exiterr;
		}
	    }
	    snprintf(editorcmd, sizeof(editorcmd), "%s %s", cureditor, tmp_str);
	    execlp(shell, shell, "-c", editorcmd, tmp_str, NULL);
	    error_e("Error while running \"%s\"", cureditor);
	    goto exiterr;

	case -1:
	    error_e("fork");
	    goto exiterr;

	default:
	    /* parent */
	    break ;
	}
	    
	/* only reached by parent */
	waitpid(pid, &status, 0);
//.........这里部分代码省略.........
开发者ID:yangyan,项目名称:RV_XJTU_CS,代码行数:101,代码来源:fcrontab.c

示例5: main


//.........这里部分代码省略.........
	mreq.imr_interface.s_addr = htonl(INADDR_ANY);
	if (setsockopt(mcast_s, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &mreq,
		       sizeof(mreq)) == -1) {
	    PosixError("unable to join multicast group");
	    close(mcast_s);
	    mcast_s = -1;
	}
    }

#ifdef SO_REUSEADDR
    if (mcast_s > 0) {
	setsockopt(mcast_s, SOL_SOCKET, SO_REUSEADDR, 
		   (char *) &on, sizeof(on));
    }
#endif

    if (mcast_s > 0) {
        struct sockaddr_in maddr;
        maddr.sin_family = AF_INET;
	maddr.sin_port = htons(port);
	maddr.sin_addr.s_addr = htonl(INADDR_ANY);
	if (bind(mcast_s, (struct sockaddr*) &maddr, sizeof(maddr)) == -1) {
	    PosixError("unable to bind multicast trap socket");
	    close(mcast_s);
	    mcast_s = -1;
	}
    }
#endif

    /* 
     * Switch back to normal user rights: 
     */

    setuid(getuid ());

    if ((serv_s = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
	PosixError("unable to open server socket");
	exit(1);
    }

    memset((char *) &saddr, 0, sizeof(saddr));

    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(SNMP_FRWD_PORT);
    saddr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(serv_s, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) {
	PosixError("unable to bind server socket");
	exit(1);
    }

    if (listen(serv_s, 5) < 0) {
	PosixError("unable to listen on server socket");
	exit(1);
    }

#ifdef SIGPIPE
    signal(SIGPIPE, IgnorePipe);
#endif
    
    /*
     * If there is a steady stream of traps bound for this host, we
     * need to allow some time for the client (scotty) to connect to
     * us. Otherwise, nmtrapd will just exit when the first trap
     * message arrives. The client does 5 retries with 1 second
     * in-between, so sleeping for 3 should be enough to let the
开发者ID:flightaware,项目名称:scotty,代码行数:67,代码来源:nmtrapd.c

示例6: NGIRCd_Init

/**
 * Initialize ngIRCd daemon.
 *
 * @param NGIRCd_NoDaemon Set to true if ngIRCd should run in the
 *		foreground (and not as a daemon).
 * @return true on success.
 */
static bool
NGIRCd_Init(bool NGIRCd_NoDaemon)
{
	static bool initialized;
	bool chrooted = false;
	struct passwd *pwd;
	struct group *grp;
	int real_errno, fd = -1;
	pid_t pid;

	if (initialized)
		return true;

	if (!NGIRCd_NoDaemon) {
		/* open /dev/null before chroot() */
		fd = open( "/dev/null", O_RDWR);
		if (fd < 0)
			Log(LOG_WARNING, "Could not open /dev/null: %s",
			    strerror(errno));
	}

	/* SSL initialization */
	if (!ConnSSL_InitLibrary()) {
		Log(LOG_ERR, "Error during SSL initialization!");
		goto out;
	}

	/* Change root */
	if (Conf_Chroot[0]) {
		if (chdir(Conf_Chroot) != 0) {
			Log(LOG_ERR, "Can't chdir() in ChrootDir (%s): %s!",
			    Conf_Chroot, strerror(errno));
			goto out;
		}

		if (chroot(Conf_Chroot) != 0) {
			Log(LOG_ERR,
			    "Can't change root directory to \"%s\": %s!",
			    Conf_Chroot, strerror(errno));
			goto out;
		} else {
			chrooted = true;
			Log(LOG_INFO,
			    "Changed root and working directory to \"%s\".",
			    Conf_Chroot);
		}
	}

#if !defined(SINGLE_USER_OS)
	/* Check user ID */
	if (Conf_UID == 0) {
		pwd = getpwuid(0);
		Log(LOG_INFO,
		    "ServerUID must not be %s(0), using \"nobody\" instead.",
		    pwd ? pwd->pw_name : "?");
		if (!NGIRCd_getNobodyID(&Conf_UID, &Conf_GID)) {
			Log(LOG_WARNING,
			    "Could not get user/group ID of user \"nobody\": %s",
			    errno ? strerror(errno) : "not found" );
			goto out;
		}
	}

	/* Change group ID */
	if (getgid() != Conf_GID) {
		if (setgid(Conf_GID) != 0) {
			real_errno = errno;
			grp = getgrgid(Conf_GID);
			Log(LOG_ERR, "Can't change group ID to %s(%u): %s!",
			    grp ? grp->gr_name : "?", Conf_GID,
			    strerror(real_errno));
			if (real_errno != EPERM)
				goto out;
		}
#ifdef HAVE_SETGROUPS
		if (setgroups(0, NULL) != 0) {
			real_errno = errno;
			Log(LOG_ERR, "Can't drop supplementary group IDs: %s!",
					strerror(errno));
			if (real_errno != EPERM)
				goto out;
		}
#else
		Log(LOG_WARNING,
		    "Can't drop supplementary group IDs: setgroups(3) missing!");
#endif
	}
#endif

	/* Change user ID */
	if (getuid() != Conf_UID) {
		if (setuid(Conf_UID) != 0) {
			real_errno = errno;
//.........这里部分代码省略.........
开发者ID:LucentW,项目名称:ngircd,代码行数:101,代码来源:ngircd.c

示例7: ds_daemon

int ds_daemon(http_conf * conf, int t)
{  
    int uid = getuid();
    int gid = getgid();
    int status = 0;


    if(conf->user && strlen(conf->user)) {
        struct passwd * pw  = getpwnam(conf->user);
        if(!pw) {
            printf(" user[%s] no found\n", conf->user);
            exit(0);
        }
        uid = pw->pw_uid;
        gid = pw->pw_gid;
        printf("\n user:%s\n", conf->user);
    }


    if(t == 0 ) {
        ds_init_daemon(conf);
    }
   

   if( t == 0 || t == 1) {
       ds_init_children(conf);

       //ds_pid = getpid();

        if(setsid() == -1) {  //setsid创建一个新会话
            printf("setsid() failed!" DS_LINEEND);
            exit(0);
        }
        
        umask(0);
        setuid(uid);
        setgid(gid);
        ds_init(conf);
   }

   /*if( t == 2) {
       conf->work_mode = FORK_PROCESS_WORK_HTTP_MODE;
   }*/
   if(t == 2) {
       //使用两个pipe 完成accept 和cgi进程的通信,pipe 0read, 1write
       int pipHttp[2], pipCgi[2];
       pipe(pipHttp);
       pipe(pipCgi);
       int forkCgiPid = fork();
       if(forkCgiPid == 0) {
            conf->child_pip.in = pipCgi[0];
            conf->child_pip.out = pipHttp[1];
            close(pipHttp[0]);
            close(pipCgi[1]);
            conf->work_mode = FORK_PROCESS_WORK_CGI_MODE;
        } else {
            conf->child_pip.in = pipHttp[0];
            conf->child_pip.out = pipCgi[1];
            close(pipHttp[1]);
            close(pipCgi[0]);
            conf->work_mode = FORK_PROCESS_WORK_HTTP_MODE;
        }
   }
 

    


    return OK;
}
开发者ID:rentiansheng,项目名称:devSync,代码行数:70,代码来源:ds_daemon.c

示例8: main

int main(int argc, char *argv[]) {
  char *user, *dirname, *spoolfile, *outfile, *gscall, *ppcall;
  cp_string title;
  int size;
  mode_t mode;
  struct passwd *passwd;
  gid_t *groups;
  int ngroups;
  pid_t pid;
/*
  puts("s0");
  int ff = open("/home/cww/t3", O_CREAT | O_RDWR, 0777);
  if (ff == -1) {
	  perror("13");
  }*/
  //close(ff);
  //printf("uid = %d, euid = %d\n", getuid(), geteuid());
//	puts("s1");
  if (freopen("/tmp/cups-pdf.stderr", "w", stderr) == NULL) {
	  printf("%d %s\n", errno, strerror(errno));
	return 5;
  }
  int f1 = open("/var/log/cups/cups-test", O_CREAT | O_RDWR, 0777);
  if (f1 == -1) {
	cwwdebug(strerror(errno));
	cwwdebug("open /var/log/cups/cups-test fail!");
  }
  close(f1);
  cwwdebug("freopen success!");
  int ff = open("/tmp/tt", O_CREAT | O_RDWR, 0777);
  close(ff);
  if (setuid(0)) {
    (void) fputs("CUPS-PDF cannot be called without root privileges!\n", stderr);
    return 0;
  }
  cwwdebug("setuid success!");
  if (argc==1) {
	  cwwdebug("argc = 1");
    announce_printers();
    return 0;
  }
  cwwdebug("argc != 1");
  if (argc<6 || argc>7) {
    (void) fputs("Usage: cups-pdf job-id user title copies options [file]\n", stderr);
    return 0;
  }

  if (init(argv)) {          
	  cwwdebug("init failed!");
    return 5;
  }
  cwwdebug("init success!");
  log_event(CPDEBUG, "initialization finished: %s", CPVERSION);

  size=strlen(Conf_UserPrefix)+strlen(argv[2])+1;
  user=calloc(size, sizeof(char));
  if (user == NULL) {
    (void) fputs("CUPS-PDF: failed to allocate memory\n", stderr);
    return 5;
  }  
  snprintf(user, size, "%s%s", Conf_UserPrefix, argv[2]);
  cwwdebug(user);
  passwd=getpwnam(user);
  if (passwd == NULL && Conf_LowerCase) {
    log_event(CPDEBUG, "unknown user: %s", user);
    for (size=0;size<(int) strlen(argv[2]);size++) 
      argv[2][size]=tolower(argv[2][size]);
    log_event(CPDEBUG, "trying lower case user name: %s", argv[2]);
    size=strlen(Conf_UserPrefix)+strlen(argv[2])+1;
    snprintf(user, size, "%s%s", Conf_UserPrefix, argv[2]);
    passwd=getpwnam(user);
  }  
  if (passwd == NULL) {
    if (strlen(Conf_AnonUser)) {
      passwd=getpwnam(Conf_AnonUser);
      if (passwd == NULL) {
        log_event(CPERROR, "username for anonymous access unknown: %s", Conf_AnonUser);
        free(user);
        if (logfp!=NULL)
          (void) fclose(logfp);
        return 5;
      }
      log_event(CPDEBUG, "unknown user: %s", user);
      size=strlen(Conf_AnonDirName)+4;
      dirname=calloc(size, sizeof(char));
      if (dirname == NULL) {
        (void) fputs("CUPS-PDF: failed to allocate memory\n", stderr);
        free(user);
        if (logfp!=NULL)
          (void) fclose(logfp);
        return 5;
      }  
      snprintf(dirname, size, "%s", Conf_AnonDirName);
      while (strlen(dirname) && ((dirname[strlen(dirname)-1] == '\n') ||
             (dirname[strlen(dirname)-1] == '\r')))
        dirname[strlen(dirname)-1]='\0';
      log_event(CPDEBUG, "output directory name generated: %s", dirname);
    }
    else {
      log_event(CPSTATUS, "anonymous access denied: %s", user);
//.........这里部分代码省略.........
开发者ID:caiweiwenjs,项目名称:cfilter,代码行数:101,代码来源:cups-pdf-cww-dubug.c

示例9: service_start


//.........这里部分代码省略.........
                                  si->perm, si->uid, si->gid, si->socketcon ?: scon);
            if (s >= 0) {
                publish_socket(si->name, s);
            }
        }

        freecon(scon);
        scon = NULL;

        if (svc->ioprio_class != IoSchedClass_NONE) {
            if (android_set_ioprio(getpid(), svc->ioprio_class, svc->ioprio_pri)) {
                ERROR("Failed to set pid %d ioprio = %d,%d: %s\n",
                      getpid(), svc->ioprio_class, svc->ioprio_pri, strerror(errno));
            }
        }

        if (needs_console) {
            setsid();
            open_console();
        } else {
            zap_stdio();
        }

#if 0
        for (n = 0; svc->args[n]; n++) {
            INFO("args[%d] = '%s'\n", n, svc->args[n]);
        }
        for (n = 0; ENV[n]; n++) {
            INFO("env[%d] = '%s'\n", n, ENV[n]);
        }
#endif

        setpgid(0, getpid());

    /* as requested, set our gid, supplemental gids, and uid */
        if (svc->gid) {
            if (setgid(svc->gid) != 0) {
                ERROR("setgid failed: %s\n", strerror(errno));
                _exit(127);
            }
        }
        if (svc->nr_supp_gids) {
            if (setgroups(svc->nr_supp_gids, svc->supp_gids) != 0) {
                ERROR("setgroups failed: %s\n", strerror(errno));
                _exit(127);
            }
        }
        if (svc->uid) {
            if (setuid(svc->uid) != 0) {
                ERROR("setuid failed: %s\n", strerror(errno));
                _exit(127);
            }
        }
        if (svc->seclabel) {
            if (is_selinux_enabled() > 0 && setexeccon(svc->seclabel) < 0) {
                ERROR("cannot setexeccon('%s'): %s\n", svc->seclabel, strerror(errno));
                _exit(127);
            }
        }

        if (!dynamic_args) {
            if (execve(svc->args[0], (char**) svc->args, (char**) ENV) < 0) {
                ERROR("cannot execve('%s'): %s\n", svc->args[0], strerror(errno));
            }
        } else {
            char *arg_ptrs[INIT_PARSER_MAXARGS+1];
            int arg_idx = svc->nargs;
            char *tmp = strdup(dynamic_args);
            char *next = tmp;
            char *bword;

            /* Copy the static arguments */
            memcpy(arg_ptrs, svc->args, (svc->nargs * sizeof(char *)));

            while((bword = strsep(&next, " "))) {
                arg_ptrs[arg_idx++] = bword;
                if (arg_idx == INIT_PARSER_MAXARGS)
                    break;
            }
            arg_ptrs[arg_idx] = '\0';
            execve(svc->args[0], (char**) arg_ptrs, (char**) ENV);
        }
        _exit(127);
    }

    freecon(scon);

    if (pid < 0) {
        ERROR("failed to start '%s'\n", svc->name);
        svc->pid = 0;
        return;
    }

    svc->time_started = gettime();
    svc->pid = pid;
    svc->flags |= SVC_RUNNING;

    if (properties_inited())
        notify_service_state(svc->name, "running");
}
开发者ID:2Habibie,项目名称:platform_system_core,代码行数:101,代码来源:init.c

示例10: pw_edit

/*
 * Edit the temp file.  Return -1 on error, >0 if the file was modified, 0
 * if it was not.
 */
int
pw_edit(int notsetuid)
{
    struct sigaction sa, sa_int, sa_quit;
    sigset_t oldsigset, nsigset;
    struct stat st1, st2;
    const char *editor;
    int pstat;

    if ((editor = getenv("EDITOR")) == NULL)
        editor = _PATH_VI;
    if (stat(tempname, &st1) == -1)
        return (-1);
    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    sigaction(SIGINT, &sa, &sa_int);
    sigaction(SIGQUIT, &sa, &sa_quit);
    sigemptyset(&nsigset);
    sigaddset(&nsigset, SIGCHLD);
    sigprocmask(SIG_BLOCK, &nsigset, &oldsigset);
    switch ((editpid = fork())) {
    case -1:
        return (-1);
    case 0:
        sigaction(SIGINT, &sa_int, NULL);
        sigaction(SIGQUIT, &sa_quit, NULL);
        sigprocmask(SIG_SETMASK, &oldsigset, NULL);
        if (notsetuid) {
            (void)setgid(getgid());
            (void)setuid(getuid());
        }
        errno = 0;
        execlp(editor, editor, tempname, (char *)NULL);
        _exit(errno);
    default:
        /* parent */
        break;
    }
    for (;;) {
        if (waitpid(editpid, &pstat, WUNTRACED) == -1) {
            if (errno == EINTR)
                continue;
            unlink(tempname);
            editpid = -1;
            break;
        } else if (WIFSTOPPED(pstat)) {
            raise(WSTOPSIG(pstat));
        } else if (WIFEXITED(pstat) && WEXITSTATUS(pstat) == 0) {
            editpid = -1;
            break;
        } else {
            unlink(tempname);
            editpid = -1;
            break;
        }
    }
    sigaction(SIGINT, &sa_int, NULL);
    sigaction(SIGQUIT, &sa_quit, NULL);
    sigprocmask(SIG_SETMASK, &oldsigset, NULL);
    if (stat(tempname, &st2) == -1)
        return (-1);
    return (st1.st_mtim.tv_sec != st2.st_mtim.tv_sec ||
            st1.st_mtim.tv_nsec != st2.st_mtim.tv_nsec);
}
开发者ID:hmatyschok,项目名称:MeshBSD,代码行数:69,代码来源:pw_util.c

示例11: main


//.........这里部分代码省略.........
          char buf[256] = "";
          int i;
          for (i = 0; i < gnum; i++)
            snprintf(buf + strlen(buf), sizeof(buf) - 1 - strlen(buf),
                     ",%d", glist[i]);
          tvhlog(LOG_ALERT, "START",
                 "setgroups(%s) failed, do you have permission?", buf+1);
          return 1;
        }
      }
      uid     = pw->pw_uid;
      homedir = pw->pw_dir;
      setenv("HOME", homedir, 1);
    } else {
      uid = 1;
    }
  }

  uuid_init();
  config_boot(opt_config, gid, uid);
  tcp_server_preinit(opt_ipv6);
  http_server_init(opt_bindaddr);    // bind to ports only
  htsp_init(opt_bindaddr);	     // bind to ports only
  satip_server_init(opt_satip_rtsp); // bind to ports only

  if (opt_fork)
    pidfile = tvh_fopen(opt_pidpath, "w+");

  if (gid != -1 && (getgid() != gid) && setgid(gid)) {
    tvhlog(LOG_ALERT, "START",
           "setgid(%d) failed, do you have permission?", gid);
    return 1;
  }
  if (uid != -1 && (getuid() != uid) && setuid(uid)) {
    tvhlog(LOG_ALERT, "START",
           "setuid(%d) failed, do you have permission?", uid);
    return 1;
  }

  /* Daemonise */
  if(opt_fork) {
    if(daemon(0, 0)) {
      exit(2);
    }
    if(pidfile != NULL) {
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    }

    /* Make dumpable */
    if (opt_dump) {
#ifdef PLATFORM_LINUX
      if (chdir("/tmp"))
        tvhwarn("START", "failed to change cwd to /tmp");
      prctl(PR_SET_DUMPABLE, 1);
#else
      tvhwarn("START", "Coredumps not implemented on your platform");
#endif
    }

    umask(0);
  }

  tvheadend_running = 1;

  /* Start log thread (must be done post fork) */
开发者ID:dreamcat4,项目名称:tvheadend,代码行数:67,代码来源:main.c

示例12: seed_rng

void
seed_rng(void)
{
#ifndef OPENSSL_PRNG_ONLY
	int devnull;
	int p[2];
	pid_t pid;
	int ret;
	unsigned char buf[RANDOM_SEED_SIZE];
	mysig_t old_sigchld;

	if (RAND_status() == 1) {
		debug3("RNG is ready, skipping seeding");
		return;
	}

	debug3("Seeding PRNG from %s", SSH_RAND_HELPER);

	if ((devnull = open("/dev/null", O_RDWR)) == -1)
		fatal("Couldn't open /dev/null: %s", strerror(errno));
	if (pipe(p) == -1)
		fatal("pipe: %s", strerror(errno));

	old_sigchld = signal(SIGCHLD, SIG_DFL);
	if ((pid = fork()) == -1)
		fatal("Couldn't fork: %s", strerror(errno));
	if (pid == 0) {
		dup2(devnull, STDIN_FILENO);
		dup2(p[1], STDOUT_FILENO);
		/* Keep stderr open for errors */
		close(p[0]);
		close(p[1]);
		close(devnull);

		if (original_uid != original_euid &&
		    ( seteuid(getuid()) == -1 ||
		      setuid(original_uid) == -1) ) {
			fprintf(stderr, "(rand child) setuid(%li): %s\n",
			    (long int)original_uid, strerror(errno));
			_exit(1);
		}

		execl(SSH_RAND_HELPER, "ssh-rand-helper", NULL);
		fprintf(stderr, "(rand child) Couldn't exec '%s': %s\n",
		    SSH_RAND_HELPER, strerror(errno));
		_exit(1);
	}

	close(devnull);
	close(p[1]);

	memset(buf, '\0', sizeof(buf));
	ret = atomicio(read, p[0], buf, sizeof(buf));
	if (ret == -1)
		fatal("Couldn't read from ssh-rand-helper: %s",
		    strerror(errno));
	if (ret != sizeof(buf))
		fatal("ssh-rand-helper child produced insufficient data");

	close(p[0]);

	if (waitpid(pid, &ret, 0) == -1)
	       fatal("Couldn't wait for ssh-rand-helper completion: %s",
		   strerror(errno));
	signal(SIGCHLD, old_sigchld);

	/* We don't mind if the child exits upon a SIGPIPE */
	if (!WIFEXITED(ret) &&
	    (!WIFSIGNALED(ret) || WTERMSIG(ret) != SIGPIPE))
		fatal("ssh-rand-helper terminated abnormally");
	if (WEXITSTATUS(ret) != 0)
		fatal("ssh-rand-helper exit with exit status %d", ret);

	RAND_add(buf, sizeof(buf), sizeof(buf));
	memset(buf, '\0', sizeof(buf));

#endif /* OPENSSL_PRNG_ONLY */
	if (RAND_status() != 1)
		fatal("PRNG is not seeded");
}
开发者ID:OpenDarwin-CVS,项目名称:SEDarwin,代码行数:80,代码来源:entropy.c

示例13: main


//.........这里部分代码省略.........

  // Create fifo if prefork is set
  if (handlingMethod == _FORK) {
      // Create the named fifo pipe
      mkfifo(config.fifoPath, 0666);
      // Try opening the pipe
      if((fifo = open(config.fifoPath, O_RDWR)) == -1) {
        sprintf(error, "Unable to open FIFO-pipe, %s", strerror(errno));
        log_server(LOG_CRIT, error);
        execute = false;    // Terminate
      }
  }

  // Check super user
  if (getuid() != 0) {
    perror("You have to be root to run this program");
    exit(-1);
  }

  // Set root directory to document root
  chdir(config.basedir);
  if (chroot(config.basedir) == -1) {
    sprintf(error, "Unable to change root directory, %s", strerror(errno));
    log_server(LOG_ERR, error);
    execute = false;  // Terminate
  }

  // Drop root privileges
  if (setgid(getgid()) == -1) {
    sprintf(error, "Unable to change user, %s", strerror(errno));
    log_server(LOG_ERR, error);
    execute = false;  // Terminate
  }
  if (setuid(getuid()) == -1) {
    sprintf(error, "Unable to change user, %s", strerror(errno));
    log_server(LOG_ERR, error);
    execute = false;  // Terminate
  }

  // Create listening socket
  // Domain -> AF_INET = IPV4
  // Type -> SOCK_STREAM = TCP
  if((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
      sprintf(error, "Unable to open socket, %s", strerror(errno));
      log_server(LOG_ERR, error);
      execute = false;  // Terminate
  }

  // Zeroize sin
  memset(&sin, 0, sizeof(sin));
  // Set domain
  sin.sin_family = AF_INET;
  // Set any in address
  sin.sin_addr.s_addr = INADDR_ANY;
  // Set port, hton converts byteorder
  sin.sin_port = htons(config.listenPort);

  // Try binding the socket
	if(bind(sd, (struct sockaddr*) &sin, sizeof(sin)) == -1) {
    sprintf(error, "Unable to bind socket, %s", strerror(errno));
    log_server(LOG_ERR, error);
    execute = false;  // Terminate
	}

  // Start to listen for requests
  if(listen(sd, config.backlog) == -1) {
开发者ID:K1N62,项目名称:Rhino,代码行数:67,代码来源:httpd.c

示例14: become_user

int become_user(const char *username, int access_fd, int output_fd, int error_fd, int pid_fd)
{
    struct passwd *pw = getpwnam(username);
    if(!pw) {
        error("User %s is not present.", username);
        return -1;
    }

    uid_t uid = pw->pw_uid;
    gid_t gid = pw->pw_gid;

    int ngroups =  sysconf(_SC_NGROUPS_MAX);
    gid_t *supplementary_groups = NULL;
    if(ngroups) {
        supplementary_groups = malloc(sizeof(gid_t) * ngroups);
        if(supplementary_groups) {
            if(getgrouplist(username, gid, supplementary_groups, &ngroups) == -1) {
                error("Cannot get supplementary groups of user '%s'.", username);
                free(supplementary_groups);
                supplementary_groups = NULL;
                ngroups = 0;
            }
        }
        else fatal("Cannot allocate memory for %d supplementary groups", ngroups);
    }

    properly_chown_netdata_generated_file(access_fd, uid, gid);
    properly_chown_netdata_generated_file(output_fd, uid, gid);
    properly_chown_netdata_generated_file(error_fd, uid, gid);
    properly_chown_netdata_generated_file(pid_fd, uid, gid);

    if(supplementary_groups && ngroups) {
        if(setgroups(ngroups, supplementary_groups) == -1)
            error("Cannot set supplementary groups for user '%s'", username);

        free(supplementary_groups);
        supplementary_groups = NULL;
        ngroups = 0;
    }

    if(setresgid(gid, gid, gid) != 0) {
        error("Cannot switch to user's %s group (gid: %u).", username, gid);
        return -1;
    }

    if(setresuid(uid, uid, uid) != 0) {
        error("Cannot switch to user %s (uid: %u).", username, uid);
        return -1;
    }

    if(setgid(gid) != 0) {
        error("Cannot switch to user's %s group (gid: %u).", username, gid);
        return -1;
    }
    if(setegid(gid) != 0) {
        error("Cannot effectively switch to user's %s group (gid: %u).", username, gid);
        return -1;
    }
    if(setuid(uid) != 0) {
        error("Cannot switch to user %s (uid: %u).", username, uid);
        return -1;
    }
    if(seteuid(uid) != 0) {
        error("Cannot effectively switch to user %s (uid: %u).", username, uid);
        return -1;
    }

    return(0);
}
开发者ID:yacloud-io,项目名称:netdata,代码行数:69,代码来源:daemon.c

示例15: main

/*
 * Open device and perform command
 */
int
main(int argc, char **argv)
{
	char *execdup, *execname;
	int rc = EX_OK;

	/* Get exec name */
	execdup = (char *)strdup(argv[0]);
	if (execdup == NULL) {
		printf("%s: fatal error: strdup failed\n", __func__);
		io_exit(EX_OSERR); /* Panic */
	}
	execname = basename(execdup);
	if (execname == NULL) {
		printf("%s: fatal error: basename failed\n", __func__);
		io_exit(EX_OSERR); /* Panic */
	}

	/* Get configuration */
	getconf();
	
	/* Determine back-end */
	if (io_backend() == 0)
		usage(execname, "Unsupported I/O");

	/* Open device */
	if (io_open() < 0)
		usage(execname, io_error());

	/* Raise priority */
	setpriority(PRIO_PROCESS, 0, -20);

	/* Reset uid */
	if (getuid() != geteuid()) {
		if (setuid(getuid()) < 0) {
			printf("%s: fatal error: setuid failed\n", __func__);
			io_exit(EX_OSERR); /* Panic */
		}
	}

	/* Determine arch: 12 | 14 | 16 | 24 | 32 */
	if (pic_arch(execname) == 0)
		usage_pickle();

	/* Perform operation */
	if (argc < 2)
		usage(execname, "Missing arg(s)");

	/* Device selection and partition */
	int argv1 = tolower((int)argv[1][0]);
	int argv11 = tolower((int)argv[1][1]);
	if (argv1 == 's' || (argv1 == 'p' && argv11 == 'a')) {
		/* Select or partition device */
		if (argc < 3) {
			pic_selector();
			io_exit(EX_OK);
		}
		p.partition = (argv1 == 'p') ? TRUE : FALSE;
		if (mystrcasestr(argv[2], "dspic") == argv[2]) {
			strncpy(p.devicename, argv[2], STRLEN);
		} else if (mystrcasestr(argv[2], "pic") == argv[2]) {
			strncpy(p.devicename, argv[2], STRLEN);
		} else {
			int32_t temp = strtol(argv[2], NULL, 0);
			if (temp < 10 || temp > 33) {
				usage(execname, "Invalid arg [select]");
			}
			if (temp == 30 || temp == 33) {
				strcpy(p.devicename, "dspic");
				strncpy(&p.devicename[5], argv[2], STRLEN - 5);
			} else {
				strcpy(p.devicename, "pic");
				strncpy(&p.devicename[3], argv[2], STRLEN - 3);
			}
		}
		argc -= 2;
		argv += 2;
		if (argc < 2)
			usage(execname, "Missing arg(s)");
	} else if (p.pic->arch == ARCH12BIT) {
		usage(execname, "Missing select");
	}

	/* Key entry or loader output */
	argv1 = tolower((int)argv[1][0]);
	if (argv1 == 'l') {			/* LVP 32-bit key entry or loader output */
#ifdef LOADER
		if (argv11 == 'o') {		/* LOADER OUTPUT */
			if (argc > 2)
				usage(execname, "Too many args [loader]");
			pic_bootloader();
			io_exit(EX_OK);
		}
#endif
		if (p.pic->arch == ARCH12BIT) {
			/* NOT SUPPORTED */
			usage(execname, "Invalid arg [lvp]");
//.........这里部分代码省略.........
开发者ID:GBert,项目名称:openwrt-files,代码行数:101,代码来源:pickle.c


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