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


C++ endgrent函数代码示例

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


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

示例1: Java_org_tanukisoftware_wrapper_WrapperManager_nativeGetUser

/*#define UVERBOSE*/
JNIEXPORT jobject JNICALL
Java_org_tanukisoftware_wrapper_WrapperManager_nativeGetUser(JNIEnv *env, jclass clazz, jboolean groups) {
    jclass wrapperUserClass;
    jmethodID constructor;
    jmethodID setGroup;
    jmethodID addGroup;
    uid_t uid;
    struct passwd *pw;
    gid_t ugid;
    jbyteArray jUser;
    jbyteArray jRealName;
    jbyteArray jHome;
    jbyteArray jShell;
    jobject wrapperUser = NULL;
    struct group *aGroup;
    int member;
    int i;
    gid_t ggid;
    jbyteArray jGroupName;

    /* Look for the WrapperUser class. Ignore failures as JNI throws an exception. */
    if ((wrapperUserClass = (*env)->FindClass(env, "org/tanukisoftware/wrapper/WrapperUNIXUser")) != NULL) {

        /* Look for the constructor. Ignore failures. */
        if ((constructor = (*env)->GetMethodID(env, wrapperUserClass, "<init>", "(II[B[B[B[B)V")) != NULL) {

            uid = geteuid();
            pw = getpwuid(uid);
            ugid = pw->pw_gid;

            /* Create the arguments to the constructor as java objects */

            /* User byte array */
            jUser = (*env)->NewByteArray(env, strlen(pw->pw_name));
            (*env)->SetByteArrayRegion(env, jUser, 0, strlen(pw->pw_name), (jbyte*)pw->pw_name);

            /* Real Name byte array */
            jRealName = (*env)->NewByteArray(env, strlen(pw->pw_gecos));
            (*env)->SetByteArrayRegion(env, jRealName, 0, strlen(pw->pw_gecos), (jbyte*)pw->pw_gecos);

            /* Home byte array */
            jHome = (*env)->NewByteArray(env, strlen(pw->pw_dir));
            (*env)->SetByteArrayRegion(env, jHome, 0, strlen(pw->pw_dir), (jbyte*)pw->pw_dir);

            /* Shell byte array */
            jShell = (*env)->NewByteArray(env, strlen(pw->pw_shell));
            (*env)->SetByteArrayRegion(env, jShell, 0, strlen(pw->pw_shell), (jbyte*)pw->pw_shell);

            /* Now create the new wrapperUser using the constructor arguments collected above. */
            wrapperUser = (*env)->NewObject(env, wrapperUserClass, constructor, uid, ugid, jUser, jRealName, jHome, jShell);

            /* If the caller requested the user's groups then look them up. */
            if (groups) {
               /* Set the user group. */
               if ((setGroup = (*env)->GetMethodID(env, wrapperUserClass, "setGroup", "(I[B)V")) != NULL) {
                   if ((aGroup = getgrgid(ugid)) != NULL) {
                       ggid = aGroup->gr_gid;

                       /* Group name byte array */
                       jGroupName = (*env)->NewByteArray(env, strlen(aGroup->gr_name));
                       (*env)->SetByteArrayRegion(env, jGroupName, 0, strlen(aGroup->gr_name), (jbyte*)aGroup->gr_name);

                        /* Add the group to the user. */
                       (*env)->CallVoidMethod(env, wrapperUser, setGroup, ggid, jGroupName);
                   }
               }

               /* Look for the addGroup method. Ignore failures. */
               if ((addGroup = (*env)->GetMethodID(env, wrapperUserClass, "addGroup", "(I[B)V")) != NULL) {

                   setgrent();
                   while ((aGroup = getgrent()) != NULL) {
                       /* Search the member list to decide whether or not the user is a member. */
                       member = 0;
                       i = 0;
                       while ((member == 0) && aGroup->gr_mem[i]) {
                           if (strcmp(aGroup->gr_mem[i], pw->pw_name) == 0) {
                               member = 1;
                           }
                           i++;
                       }

                       if (member) {
                           ggid = aGroup->gr_gid;

                           /* Group name byte array */
                           jGroupName = (*env)->NewByteArray(env, strlen(aGroup->gr_name));
                           (*env)->SetByteArrayRegion(env, jGroupName, 0, strlen(aGroup->gr_name), (jbyte*)aGroup->gr_name);

                           /* Add the group to the user. */
                           (*env)->CallVoidMethod(env, wrapperUser, addGroup, ggid, jGroupName);
                       }
                   }
                   endgrent();
                }
            }
        }
    }

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

示例2: userrc_parse


//.........这里部分代码省略.........
	vboxuser->uid		= 0;
	vboxuser->gid		= 0;
	vboxuser->space	= 0;
	vboxuser->umask	= 0;

	strcpy(vboxuser->home, "");
	strcpy(vboxuser->name, "");

	if ((!varusr) || (!*varusr))
	{
		log_line(LOG_E, "You *must* specify a user name or a user id!\n");

		rc_free(rc_user_c);

		return(-1);
	}

	if (*varusr == '#')
		pwdent = getpwuid((uid_t)xstrtol(&varusr[1], 0));
	else
		pwdent = getpwnam(varusr);

	if (!pwdent)
	{
		log_line(LOG_E, "Unable to locate \"%s\" in systems passwd list.\n", varusr);

		rc_free(rc_user_c);

		return(-1);
	}

	vboxuser->uid = pwdent->pw_uid;
	vboxuser->gid = pwdent->pw_gid;

	if ((strlen(home) + strlen(pwdent->pw_name) + 2) < (PATH_MAX - 100))
	{
		xstrncpy(vboxuser->name, pwdent->pw_name, VBOXUSER_USERNAME);

		printstring(vboxuser->home, "%s/%s", home, pwdent->pw_name);
	}
	else
	{
		log_line(LOG_E, "Oops! Spool directory name and user name too long!\n");

		rc_free(rc_user_c);

		return(-1);
	}

	if ((vargrp) && (*vargrp))
	{
		havegroup = 0;

		setgrent();
					
		while ((grpent = getgrent()))
		{
			if (*vargrp == '#')
			{
				if (grpent->gr_gid == (gid_t)xstrtol(&vargrp[1], 0))
				{
					vboxuser->gid = grpent->gr_gid;
					havegroup	  = 1;
								
					break;
				}
			}
			else
			{
				if (strcmp(grpent->gr_name, vargrp) == 0)
				{
					vboxuser->gid = grpent->gr_gid;
					havegroup	  = 1;
								
					break;
				}
			}
		}
					
		endgrent();

		if (!havegroup)
		{
			log_line(LOG_E, "Unable to locate \"%s\" in systems group list.\n", vargrp);

			rc_free(rc_user_c);

			return(-1);
		}
	}

	if (varspc) vboxuser->space = xstrtol(varspc, 0);
	if (varmsk) vboxuser->umask = xstrtoo(varmsk, 0);

	log_line(LOG_D, "User \"%s\" (%d.%d) [%04o] will be used...\n", vboxuser->name, vboxuser->uid, vboxuser->gid, vboxuser->umask);

	rc_free(rc_user_c);

	return(0);
}
开发者ID:marschap,项目名称:isdn4k-utils,代码行数:101,代码来源:vboxgetty.c

示例3: grp_add

int
grp_add(char *str)
{
	u_int indx;
	GRPT *pt;
	struct group *gr;
	gid_t gid;

	/*
	 * create the table if it doesn't exist
	 */
	if ((str == NULL) || (*str == '\0'))
		return(-1);
	if ((grptb == NULL) &&
 	    ((grptb = (GRPT **)calloc(GRP_TB_SZ, sizeof(GRPT *))) == NULL)) {
		paxwarn(1, "Unable to allocate memory fo group selection table");
		return(-1);
	}

	/*
	 * figure out user spec
	 */
	if (str[0] != '#') {
		/*
		 * it is a group name, \# escapes # as first char in group name
		 */
		if ((str[0] == '\\') && (str[1] == '#'))
			++str;
		if ((gr = getgrnam(str)) == NULL) {
			paxwarn(1,"Cannot determine gid for group name: %s", str);
			return(-1);
		}
		gid = gr->gr_gid;
	} else
#		ifdef NET2_STAT
		gid = (gid_t)atoi(str+1);
#		else
		gid = (gid_t)strtoul(str+1, NULL, 10);
#		endif
	endgrent();

	/*
	 * hash it and go down the hash chain (if any) looking for it
	 */
	indx = ((unsigned)gid) % GRP_TB_SZ;
	if ((pt = grptb[indx]) != NULL) {
		while (pt != NULL) {
			if (pt->gid == gid)
				return(0);
			pt = pt->fow;
		}
	}

	/*
	 * gid not in the table, add it to the front of the chain
	 */
	if ((pt = (GRPT *)malloc(sizeof(GRPT))) != NULL) {
		pt->gid = gid;
		pt->fow = grptb[indx];
		grptb[indx] = pt;
		return(0);
	}
	paxwarn(1, "Group selection table out of memory");
	return(-1);
}
开发者ID:ele7enxxh,项目名称:dtrace-pf,代码行数:65,代码来源:sel_subs.c

示例4: real_endgrent

void real_endgrent() { endgrent(); }
开发者ID:jklippel,项目名称:smart-snmpd,代码行数:1,代码来源:pwent.cpp

示例5: drop_privs

int drop_privs(void)
{
    struct group *gr;
    struct passwd *pw;
    char *endptr;
    int i;
    int do_setuid = 0;
    int do_setgid = 0;
    unsigned long groupid = 0;
    unsigned long userid = 0;

    if (config.group_name != NULL) {
        do_setgid = 1;
        if (!isdigit(config.group_name[0])) {
            gr = getgrnam(config.group_name);
            if(!gr){
                if(config.chroot_dir){
                    elog("ERROR: you have chrooted and must set numeric group ID.\n");
                    exit(1);
                }else{
                    elog("ERROR: couldn't get ID for group %s, group does not exist.", config.group_name)
                    exit(1);
                }
            }
            groupid = gr->gr_gid;
        } else {
            groupid = strtoul(config.group_name, &endptr, 10);
        }
    }

    if (config.user_name != NULL) {
        do_setuid = 1;
        do_setgid = 1;
        if (isdigit(config.user_name[0]) == 0) {
            pw = getpwnam(config.user_name);
            if (pw != NULL) {
                userid = pw->pw_uid;
            } else {
                printf("[E] User %s not found!\n", config.user_name);
            }
        } else {
            userid = strtoul(config.user_name, &endptr, 10);
            pw = getpwuid(userid);
        }

        if (config.group_name == NULL && pw != NULL) {
            groupid = pw->pw_gid;
        }
    }

    if (do_setgid) {
        if ((i = setgid(groupid)) < 0) {
            printf("Unable to set group ID: %s", strerror(i));
        }
   }

    endgrent();
    endpwent();

    if (do_setuid) {
        if (getuid() == 0 && initgroups(config.user_name, groupid) < 0) {
            printf("Unable to init group names (%s/%lu)", config.user_name,
                   groupid);
        }
        if ((i = setuid(userid)) < 0) {
            printf("Unable to set user ID: %s\n", strerror(i));
        }
    }
    return 0;
}
开发者ID:regit,项目名称:passivedns,代码行数:70,代码来源:passivedns.c

示例6: sysgroup_cleanup

static void
sysgroup_cleanup(void)
{
    if (need_setent)
	endgrent();
}
开发者ID:mer-tools,项目名称:sudo,代码行数:6,代码来源:system_group.c

示例7: main

int main (int argc, char **argv)
{
	struct group *gr;
	int found = 0;
	int num_users, i;

	/* Test getgrent() without setgrent() */

	for (i = 0; i < 100; i++) {
		gr = getgrent();

		/* This is supposed to work */

#if 0
		if (gr != NULL) {
			printf("FAIL: getgrent() with no setgrent()\n");
			return 1;
		}
#endif
	}

	/* Work out how many user till first domain group */

	num_users = 0;
	setgrent();

	while (1) {
		gr = getgrent();
		num_users++;

		if (gr == NULL) break;

		if (strchr(gr->gr_name, '/')) {
			found = 1;
			break;
		}

	}

	if (!found) {
		printf("FAIL: could not find any domain groups\n");
		return 1;
	}

	/* Test stopping getgrent in the middle of a set of users */

	endgrent();

	/* Test setgrent() without any getgrent() calls */

	setgrent();

	for (i = 0; i < (num_users - 1); i++) {
		getgrent();
	}

	endgrent();

	/* Test lots of setgrent() calls */

	for (i = 0; i < 100; i++) {
		setgrent();
	}

	/* Test lots of endgrent() calls */

	for (i = 0; i < 100; i++) {
		endgrent();
	}

	/* Everything's cool */

	printf("PASS\n");
	return 0;
}
开发者ID:AllardJ,项目名称:Tomato,代码行数:75,代码来源:getent_grent.c

示例8: main


//.........这里部分代码省略.........
        case 'd':
            netsnmp_ds_set_boolean(NETSNMP_DS_LIBRARY_ID,
                                   NETSNMP_DS_LIB_DUMP_PACKET,
                                   ++snmp_dump_packet);
            break;

        case 'D':
#ifdef NETSNMP_DISABLE_DEBUGGING
            fprintf(stderr, "Debugging not configured\n");
            exit(1);
#else
            debug_register_tokens(optarg);
            snmp_set_do_debugging(1);
#endif
            break;

        case 'f':
            dont_fork = 1;
            break;

#if HAVE_UNISTD_H
        case 'g':
            if (optarg != NULL) {
                char           *ecp;
                int             gid;

                gid = strtoul(optarg, &ecp, 10);
#if HAVE_GETGRNAM && HAVE_PWD_H
                if (*ecp) {
                    struct group  *info;

                    info = getgrnam(optarg);
                    gid = info ? info->gr_gid : -1;
                    endgrent();
                }
#endif
                if (gid < 0) {
                    fprintf(stderr, "Bad group id: %s\n", optarg);
                    exit(1);
                }
                netsnmp_ds_set_int(NETSNMP_DS_APPLICATION_ID, 
				   NETSNMP_DS_AGENT_GROUPID, gid);
            } else {
                usage(argv[0]);
            }
            break;
#endif

        case 'h':
            usage(argv[0]);
            break;

        case 'H':
            do_help = 1;
            break;

        case 'I':
            if (optarg != NULL) {
                add_to_init_list(optarg);
            } else {
                usage(argv[0]);
            }
            break;

#ifndef NETSNMP_FEATURE_REMOVE_LOGGING_FILE
        case 'l':
开发者ID:sevennothing,项目名称:lros,代码行数:67,代码来源:snmpd.c

示例9: make_subpackage


//.........这里部分代码省略.........
    fprintf(stderr, "epm: Unable to create script file \"%s\" - %s\n", filename,
            strerror(errno));
    return (1);
  }

  for (i = dist->num_files, file = dist->files; i > 0; i --, file ++)
    if (tolower(file->type) == 'c' && file->subpackage == subpackage)
      fprintf(fp, "%s\n", file->dst);
    else if (tolower(file->type) == 'i' && file->subpackage == subpackage)
      fprintf(fp, "/etc/init.d/%s\n", file->dst);

  fclose(fp);

 /*
  * Copy the files over...
  */

  if (Verbosity)
    puts("Copying temporary distribution files...");

  for (i = dist->num_files, file = dist->files; i > 0; i --, file ++)
  {
    if (file->subpackage != subpackage)
      continue;

   /*
    * Find the username and groupname IDs...
    */

    pwd = getpwnam(file->user);
    grp = getgrnam(file->group);

    endpwent();
    endgrent();

   /*
    * Copy the file or make the directory or make the symlink as needed...
    */

    switch (tolower(file->type))
    {
      case 'c' :
      case 'f' :
          snprintf(filename, sizeof(filename), "%s/%s%s", directory, name,
	           file->dst);

	  if (Verbosity > 1)
	    printf("%s -> %s...\n", file->src, filename);

	  if (copy_file(filename, file->src, file->mode, pwd ? pwd->pw_uid : 0,
			grp ? grp->gr_gid : 0))
	    return (1);
          break;
      case 'i' :
          snprintf(filename, sizeof(filename), "%s/%s/etc/init.d/%s",
	           directory, name, file->dst);

	  if (Verbosity > 1)
	    printf("%s -> %s...\n", file->src, filename);

	  if (copy_file(filename, file->src, file->mode, pwd ? pwd->pw_uid : 0,
			grp ? grp->gr_gid : 0))
	    return (1);
          break;
      case 'd' :
          snprintf(filename, sizeof(filename), "%s/%s%s", directory, name,
开发者ID:brandongooch,项目名称:epm,代码行数:67,代码来源:deb.c

示例10: main


//.........这里部分代码省略.........
#endif				/* ! USE_PAM */
	assert (NULL != username);
	assert (NULL != pwd);

	(void) alarm (0);		/* turn off alarm clock */

#ifndef USE_PAM			/* PAM does this */
	/*
	 * porttime checks moved here, after the user has been
	 * authenticated. now prints a message, as suggested
	 * by Ivan Nejgebauer <[email protected]>.  --marekm
	 */
	if (   getdef_bool ("PORTTIME_CHECKS_ENAB")
	    && !isttytime (username, tty, time ((time_t *) 0))) {
		SYSLOG ((LOG_WARN, "invalid login time for '%s'%s",
		         username, fromhost));
		closelog ();
		bad_time_notify ();
		exit (1);
	}

	check_nologin (pwd->pw_uid == 0);
#endif

	if (getenv ("IFS")) {	/* don't export user IFS ... */
		addenv ("IFS= \t\n", NULL);	/* ... instead, set a safe IFS */
	}

	if (pwd->pw_shell[0] == '*') {	/* subsystem root */
		pwd->pw_shell++;	/* skip the '*' */
		subsystem (pwd);	/* figure out what to execute */
		subroot = true;	/* say I was here again */
		endpwent ();	/* close all of the file which were */
		endgrent ();	/* open in the original rooted file */
		endspent ();	/* system. they will be re-opened */
#ifdef	SHADOWGRP
		endsgent ();	/* in the new rooted file system */
#endif
		goto top;	/* go do all this all over again */
	}

#ifdef WITH_AUDIT
	audit_fd = audit_open ();
	audit_log_acct_message (audit_fd,
	                        AUDIT_USER_LOGIN,
	                        NULL,    /* Prog. name */
	                        "login",
	                        username,
	                        AUDIT_NO_ID,
	                        hostname,
	                        NULL,    /* addr */
	                        tty,
	                        1);      /* result */
	close (audit_fd);
#endif				/* WITH_AUDIT */

#ifndef USE_PAM			/* pam_lastlog handles this */
	if (getdef_bool ("LASTLOG_ENAB")) {	/* give last login and log this one */
		dolastlog (&ll, pwd, tty, hostname);
	}
#endif

#ifndef USE_PAM			/* PAM handles this as well */
	/*
	 * Have to do this while we still have root privileges, otherwise we
	 * don't have access to /etc/shadow.
开发者ID:justinc1985,项目名称:IntelRangeley,代码行数:67,代码来源:login.c

示例11: read_mtree

fsnode *
read_mtree(const char *fname, fsnode *node)
{
	struct mtree_fileinfo *fi;
	FILE *fp;
	int c, error;

	/* We do not yet support nesting... */
	assert(node == NULL);

	if (strcmp(fname, "-") == 0)
		fp = stdin;
	else {
		fp = fopen(fname, "r");
		if (fp == NULL)
			err(1, "Can't open `%s'", fname);
	}

	error = mtree_file_push(fname, fp);
	if (error)
		goto out;

	bzero(&mtree_global, sizeof(mtree_global));
	bzero(&mtree_global_inode, sizeof(mtree_global_inode));
	mtree_global.inode = &mtree_global_inode;
	mtree_global_inode.nlink = 1;
	mtree_global_inode.st.st_nlink = 1;
	mtree_global_inode.st.st_atime = mtree_global_inode.st.st_ctime =
	    mtree_global_inode.st.st_mtime = time(NULL);
	errors = warnings = 0;

	setgroupent(1);
	setpassent(1);

	mtree_root = node;
	mtree_current = node;
	do {
		/* Start of a new line... */
		fi = SLIST_FIRST(&mtree_fileinfo);
		fi->line++;

		error = skip_over(fp, " \t");
		if (error)
			break;

		c = getc(fp);
		if (c == EOF) {
			error = ferror(fp) ? errno : -1;
			break;
		}

		switch (c) {
		case '\n':		/* empty line */
			error = 0;
			break;
		case '#':		/* comment -- skip to end of line. */
			error = skip_to(fp, "\n");
			if (!error)
				(void)getc(fp);
			break;
		case '/':		/* special commands */
			error = read_mtree_command(fp);
			break;
		default:		/* specification */
			ungetc(c, fp);
			error = read_mtree_spec(fp);
			break;
		}
	} while (!error);

	endpwent();
	endgrent();

	if (error <= 0 && (errors || warnings)) {
		warnx("%u error(s) and %u warning(s) in mtree manifest",
		    errors, warnings);
		if (errors)
			exit(1);
	}

 out:
	if (error > 0)
		errc(1, error, "Error reading mtree file");

	if (fp != stdin)
		fclose(fp);

	if (mtree_root != NULL)
		return (mtree_root);

	/* Handle empty specifications. */
	node = create_node(".", S_IFDIR, NULL, &mtree_global);
	node->first = node;
	return (node);
}
开发者ID:hmatyschok,项目名称:MeshBSD,代码行数:95,代码来源:mtree.c

示例12: drop_privs

static bool drop_privs() {
#ifdef HAVE_MINGW

	if(switchuser) {
		logger(LOG_ERR, "%s not supported on this platform", "-U");
		return false;
	}

	if(do_chroot) {
		logger(LOG_ERR, "%s not supported on this platform", "-R");
		return false;
	}

#else
	uid_t uid = 0;

	if(switchuser) {
		struct passwd *pw = getpwnam(switchuser);

		if(!pw) {
			logger(LOG_ERR, "unknown user `%s'", switchuser);
			return false;
		}

		uid = pw->pw_uid;

		if(initgroups(switchuser, pw->pw_gid) != 0 ||
						setgid(pw->pw_gid) != 0) {
			logger(LOG_ERR, "System call `%s' failed: %s",
				   "initgroups", strerror(errno));
			return false;
		}

#ifndef ANDROID
// Not supported in android NDK
		endgrent();
		endpwent();
#endif
	}

	if(do_chroot) {
		tzset();        /* for proper timestamps in logs */

		if(chroot(confbase) != 0 || chdir("/") != 0) {
			logger(LOG_ERR, "System call `%s' failed: %s",
				   "chroot", strerror(errno));
			return false;
		}

		free(confbase);
		confbase = xstrdup("");
	}

	if(switchuser)
		if(setuid(uid) != 0) {
			logger(LOG_ERR, "System call `%s' failed: %s",
				   "setuid", strerror(errno));
			return false;
		}

#endif
	return true;
}
开发者ID:seehuhn,项目名称:tinc,代码行数:63,代码来源:tincd.c

示例13: drop_privileges

int drop_privileges()
{
	struct group* perm_group = 0;
	struct passwd* perm_user = 0;
	gid_t perm_gid = 0;
	uid_t perm_uid = 0;
	int gid_ok = 0;
	int ret = 0;

	if (arg_gid)
	{
		ret = 0;
		while ((perm_group = getgrent()) != NULL)
		{
			if (strcmp(perm_group->gr_name, arg_gid) == 0)
			{
				perm_gid = perm_group->gr_gid;
				ret = 1;
				break;
			}
		}

		endgrent();

		if (!ret)
		{
			LOG_FATAL("Unable to determine group id, check group name.");
			return -1;
		}

		LOG_TRACE("Setting group id %d (%s)", (int) perm_gid, arg_gid);
		ret = setgid(perm_gid);
		if (ret == -1)
		{
			LOG_FATAL("Unable to change group id, permission denied.");
			return -1;
		}
		gid_ok = 1;
	}

	if (arg_uid)
	{
		ret = 0;
		while ((perm_user = getpwent()) != NULL)
		{
			if (strcmp(perm_user->pw_name, arg_uid) == 0)
			{
				perm_uid = perm_user->pw_uid;
				if (!gid_ok)
					perm_gid = perm_user->pw_gid;
				ret = 1;
				break;
			}
		}

		endpwent();

		if (!ret)
		{
			LOG_FATAL("Unable to determine user id, check user name.");
			return -1;
		}

		if (!gid_ok) {
			LOG_TRACE("Setting group id %d (%s)", (int) perm_gid, arg_gid);
			ret = setgid(perm_gid);
			if (ret == -1)
			{
				LOG_FATAL("Unable to change group id, permission denied.");
				return -1;
			}
		}

		LOG_TRACE("Setting user id %d (%s)", (int) perm_uid, arg_uid);
		ret = setuid(perm_uid);
		if (ret == -1)
		{
			LOG_FATAL("Unable to change user id, permission denied.");
			return -1;
		}
	}

	return 0;
}
开发者ID:CoiLock,项目名称:uhub,代码行数:84,代码来源:main.c

示例14: listGroupsForUser

static void listGroupsForUser(const char *name, gid_t gid, uint maxCount, Func handleNextGroup)
{
    if (Q_UNLIKELY(maxCount == 0)) {
        return;
    }
    uint found = 0;
#if HAVE_GETGROUPLIST
    QVarLengthArray<gid_t, 100> gid_buffer;
    gid_buffer.resize(100);
    int numGroups = gid_buffer.size();
    int result = getgrouplist(name, gid, gid_buffer.data(), &numGroups);
    if (result < 0 && uint(numGroups) < maxCount) {
        // getgrouplist returns -1 if the buffer was too small to store all entries, the required size is in numGroups
        qDebug("Buffer was too small: %d, need %d", gid_buffer.size(), numGroups);
        gid_buffer.resize(numGroups);
        numGroups = gid_buffer.size();
        getgrouplist(name, gid, gid_buffer.data(), &numGroups);
    }
    for (int i = 0; i < numGroups && found < maxCount; ++i) {
        struct group *g = getgrgid(gid_buffer[i]);
        // should never be null, but better be safe than crash
        if (g) {
            found++;
            handleNextGroup(g);
        }
    }
#else
    // fall back to getgrent() and reading gr->gr_mem
    // This is slower than getgrouplist, but works as well
    // add the current gid, this is often not part of g->gr_mem (e.g. build.kde.org or my openSuSE 13.1 system)
    struct group *g = getgrgid(gid);
    if (g) {
        handleNextGroup(g);
        found++;
        if (found >= maxCount) {
            return;
        }
    }

    static const auto groupContainsUser = [](struct group * g, const char *name) -> bool {
        for (char **user = g->gr_mem; *user; user++)
        {
            if (strcmp(name, *user) == 0) {
                return true;
            }
        }
        return false;
    };

    setgrent();
    while ((g = getgrent())) {
        // don't add the current gid again
        if (g->gr_gid != gid && groupContainsUser(g, name)) {
            handleNextGroup(g);
            found++;
            if (found >= maxCount) {
                break;
            }
        }
    }
    endgrent();
#endif
}
开发者ID:mathieusab,项目名称:kcoreaddons,代码行数:63,代码来源:kuser_unix.cpp

示例15: drop_privileges

/* drops privileges */
int drop_privileges(char *user, char *group){
	uid_t uid=-1;
	gid_t gid=-1;
	struct group *grp;
	struct passwd *pw;

	/* set effective group ID */
	if(group!=NULL){
		
		/* see if this is a group name */
		if(strspn(group,"0123456789")<strlen(group)){
			grp=(struct group *)getgrnam(group);
			if(grp!=NULL)
				gid=(gid_t)(grp->gr_gid);
			else
				syslog(LOG_ERR,"Warning: Could not get group entry for '%s'",group);
			endgrent();
		        }

		/* else we were passed the GID */
		else
			gid=(gid_t)atoi(group);

		/* set effective group ID if other than current EGID */
		if(gid!=getegid()){

			if(setgid(gid)==-1)
				syslog(LOG_ERR,"Warning: Could not set effective GID=%d",(int)gid);
		        }
	        }


	/* set effective user ID */
	if(user!=NULL){
		
		/* see if this is a user name */
		if(strspn(user,"0123456789")<strlen(user)){
			pw=(struct passwd *)getpwnam(user);
			if(pw!=NULL)
				uid=(uid_t)(pw->pw_uid);
			else
				syslog(LOG_ERR,"Warning: Could not get passwd entry for '%s'",user);
			endpwent();
		        }

		/* else we were passed the UID */
		else
			uid=(uid_t)atoi(user);
			
		/* set effective user ID if other than current EUID */
		if(uid!=geteuid()){

#ifdef HAVE_INITGROUPS
			/* initialize supplementary groups */
			if(initgroups(user,gid)==-1){
				if(errno==EPERM)
					syslog(LOG_ERR,"Warning: Unable to change supplementary groups using initgroups()");
				else{
					syslog(LOG_ERR,"Warning: Possibly root user failed dropping privileges with initgroups()");
					return ERROR;
			                }
	                        }
#endif

			if(setuid(uid)==-1)
				syslog(LOG_ERR,"Warning: Could not set effective UID=%d",(int)uid);
		        }
	        }

	return OK;
        }
开发者ID:Honwhy,项目名称:icinga-nrpe-ipv6,代码行数:72,代码来源:nrpe.c


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