• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ endgrent函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: slap_init_user

void
slap_init_user( char *user, char *group )
{
    uid_t	uid = 0;
    gid_t	gid = 0;
    int		got_uid = 0, got_gid = 0;

    if ( user ) {
	struct passwd *pwd;
	if ( isdigit( (unsigned char) *user ) ) {
	    unsigned u;

	    got_uid = 1;
	    if ( lutil_atou( &u, user ) != 0 ) {
		Debug( LDAP_DEBUG_ANY, "Unble to parse user %s\n",
		       user, 0, 0 );

		exit( EXIT_FAILURE );
	    }
	    uid = (uid_t)u;
#ifdef HAVE_GETPWUID
	    pwd = getpwuid( uid );
	    goto did_getpw;
#else
	    free( user );
	    user = NULL;
#endif
	} else {
	    pwd = getpwnam( user );
	did_getpw:
	    if ( pwd == NULL ) {
		Debug( LDAP_DEBUG_ANY, "No passwd entry for user %s\n",
		       user, 0, 0 );

		exit( EXIT_FAILURE );
	    }
	    if ( got_uid ) {
		free( user );
		user = (pwd != NULL ? ch_strdup( pwd->pw_name ) : NULL);
	    } else {
		got_uid = 1;
		uid = pwd->pw_uid;
	    }
	    got_gid = 1;
	    gid = pwd->pw_gid;
#ifdef HAVE_ENDPWENT
	    endpwent();
#endif
	}
    }

    if ( group ) {
	struct group *grp;
	if ( isdigit( (unsigned char) *group )) {
	    unsigned g;

	    if ( lutil_atou( &g, group ) != 0 ) {
		Debug( LDAP_DEBUG_ANY, "Unble to parse group %s\n",
		       group, 0, 0 );

		exit( EXIT_FAILURE );
	    }
	    gid = (uid_t)g;
#ifdef HAVE_GETGRGID
	    grp = getgrgid( gid );
	    goto did_group;
#endif
	} else {
	    grp = getgrnam( group );
	    if ( grp != NULL )
		gid = grp->gr_gid;
	did_group:
	    if ( grp == NULL ) {
		Debug( LDAP_DEBUG_ANY, "No group entry for group %s\n",
		       group, 0, 0 );

		exit( EXIT_FAILURE );
	    }
	}
	free( group );
	got_gid = 1;
    }

    if ( user ) {
	if ( getuid() == 0 && initgroups( user, gid ) != 0 ) {
	    Debug( LDAP_DEBUG_ANY,
		   "Could not set the group access (gid) list\n", 0, 0, 0 );

	    exit( EXIT_FAILURE );
	}
	free( user );
    }

#ifdef HAVE_ENDGRENT
    endgrent();
#endif

    if ( got_gid ) {
	if ( setgid( gid ) != 0 ) {
	    Debug( LDAP_DEBUG_ANY, "Could not set real group id to %d\n",
//.........这里部分代码省略.........
开发者ID:Joywar,项目名称:openldap,代码行数:101,代码来源:user.c


示例17: process_flags


//.........这里部分代码省略.........
	if (uflg && !oflg && getpwuid (user_newid)) {
		fprintf (stderr, _("%s: uid %lu is not unique\n"),
			 Prog, (unsigned long) user_newid);
		exit (E_UID_IN_USE);
	}
}

/*
 * close_files - close all of the files that were opened
 *
 *	close_files() closes all of the files that were opened for this new
 *	user. This causes any modified entries to be written out.
 */
static void close_files (void)
{
	if (!pw_close ()) {
		fprintf (stderr, _("%s: cannot rewrite password file\n"), Prog);
		fail_exit (E_PW_UPDATE);
	}
	if (is_shadow_pwd && !spw_close ()) {
		fprintf (stderr,
			 _("%s: cannot rewrite shadow password file\n"), Prog);
		fail_exit (E_PW_UPDATE);
	}
	if (is_shadow_pwd)
		spw_unlock ();
	(void) pw_unlock ();

	/*
	 * Close the DBM and/or flat files
	 */
	endpwent ();
	endspent ();
	endgrent ();
#ifdef	SHADOWGRP
	endsgent ();
#endif
}

/*
 * open_files - lock and open the password files
 *
 *	open_files() opens the two password files.
 */
static void open_files (void)
{
	if (!pw_lock ()) {
		fprintf (stderr, _("%s: unable to lock password file\n"), Prog);
		exit (E_PW_UPDATE);
	}
	if (!pw_open (O_RDWR)) {
		fprintf (stderr, _("%s: unable to open password file\n"), Prog);
		fail_exit (E_PW_UPDATE);
	}
	if (is_shadow_pwd && !spw_lock ()) {
		fprintf (stderr,
			 _("%s: cannot lock shadow password file\n"), Prog);
		fail_exit (E_PW_UPDATE);
	}
	if (is_shadow_pwd && !spw_open (O_RDWR)) {
		fprintf (stderr,
			 _("%s: cannot open shadow password file\n"), Prog);
		fail_exit (E_PW_UPDATE);
	}
}
开发者ID:OPSF,项目名称:uClinux,代码行数:66,代码来源:usermod.c


示例18: scap_create_userlist

//
// Allocate and return the list of users on this system
//
int32_t scap_create_userlist(scap_t* handle)
{
	uint32_t usercnt;
	uint32_t grpcnt;
	struct passwd *p;
	struct group *g;

	//
	// If the list of users was already allocated for this handle (for example because this is
	// not the first user list block), free it
	//
	if(handle->m_userlist != NULL)
	{
		scap_free_userlist(handle->m_userlist);
		handle->m_userlist = NULL;
	}

	//
	// First pass: count the number of users and the number of groups
	//
	setpwent();
	p = getpwent();
	for(usercnt = 0; p; p = getpwent(), usercnt++); 
	endpwent();

	setgrent();
	g = getgrent();
	for(grpcnt = 0; g; g = getgrent(), grpcnt++);
	endgrent();

	//
	// Memory allocations
	//
	handle->m_userlist = (scap_userlist*)malloc(sizeof(scap_userlist));
	if(handle->m_userlist == NULL)
	{
		snprintf(handle->m_lasterr,	SCAP_LASTERR_SIZE, "userlist allocation failed(1)");
		return SCAP_FAILURE;
	}

	handle->m_userlist->nusers = usercnt;
	handle->m_userlist->ngroups = grpcnt;
	handle->m_userlist->totsavelen = 0;
	handle->m_userlist->users = (scap_userinfo*)malloc(usercnt * sizeof(scap_userinfo));
	if(handle->m_userlist->users == NULL)
	{
		snprintf(handle->m_lasterr,	SCAP_LASTERR_SIZE, "userlist allocation failed(2)");
		free(handle->m_userlist);
		return SCAP_FAILURE;		
	}

	handle->m_userlist->groups = (scap_groupinfo*)malloc(grpcnt * sizeof(scap_groupinfo));
	if(handle->m_userlist->groups == NULL)
	{
		snprintf(handle->m_lasterr,	SCAP_LASTERR_SIZE, "grouplist allocation failed(2)");
		free(handle->m_userlist->users);
		free(handle->m_userlist);
		return SCAP_FAILURE;		
	}

	//
	// Second pass: copy the data
	//

	//users
	setpwent();
	p = getpwent();

	for(usercnt = 0; p; p = getpwent(), usercnt++)
	{
		handle->m_userlist->users[usercnt].uid = p->pw_uid;
		handle->m_userlist->users[usercnt].gid = p->pw_gid;
		
		if(p->pw_name)
		{
			strncpy(handle->m_userlist->users[usercnt].name, p->pw_name, sizeof(handle->m_userlist->users[usercnt].name));
		}
		else
		{
			*handle->m_userlist->users[usercnt].name = '\0';
		}

		if(p->pw_dir)
		{
			strncpy(handle->m_userlist->users[usercnt].homedir, p->pw_dir, sizeof(handle->m_userlist->users[usercnt].homedir));
		}
		else
		{
			*handle->m_userlist->users[usercnt].homedir = '\0';	
		}

		if(p->pw_shell)
		{
			strncpy(handle->m_userlist->users[usercnt].shell, p->pw_shell, sizeof(handle->m_userlist->users[usercnt].shell));
		}
		else
		{
//.........这里部分代码省略.........
开发者ID:draios,项目名称:sysdig,代码行数:101,代码来源:scap_userlist.c


示例19: update_group


//.........这里部分代码省略.........
	}
	if (!gr_open (O_RDWR)) {
		fprintf (stderr, _("%s: error opening group file\n"),
			 Prog);
		SYSLOG ((LOG_ERR, "error opening group file"));
		gr_unlock ();
		return -1;
	}

	changed = 0;

	/*
	 * Scan through the entire group file looking for the groups that
	 * the user is a member of.
	 */
	while ((grp = gr_next ())) {

		/*
		 * See if the user specified this group as one of their
		 * concurrent groups.
		 */
		was_member = is_on_list (grp->gr_mem, user_name);
		is_member = Gflg && is_on_list (user_groups, grp->gr_name);

		if (!was_member && !is_member)
			continue;

		ngrp = __gr_dup (grp);
		if (!ngrp) {
			fprintf (stderr,
				 _("%s: out of memory in update_group\n"),
				 Prog);
			gr_unlock ();
			return -1;
		}

		if (was_member && (!Gflg || is_member)) {
			if (lflg) {
				ngrp->gr_mem = del_list (ngrp->gr_mem,
							 user_name);
				ngrp->gr_mem = add_list (ngrp->gr_mem,
							 user_newname);
				changed = 1;
				SYSLOG ((LOG_INFO,
					 "change `%s' to `%s' in group `%s'",
					 user_name, user_newname,
					 ngrp->gr_name));
			}
		} else if (was_member && Gflg && !is_member) {
			ngrp->gr_mem = del_list (ngrp->gr_mem, user_name);
			changed = 1;
			SYSLOG ((LOG_INFO, "delete `%s' from group `%s'",
				 user_name, ngrp->gr_name));
		} else if (!was_member && Gflg && is_member) {
			ngrp->gr_mem = add_list (ngrp->gr_mem,
						 lflg ? user_newname :
						 user_name);
			changed = 1;
			SYSLOG ((LOG_INFO, "add `%s' to group `%s'",
				 lflg ? user_newname : user_name,
				 ngrp->gr_name));
		}
		if (!changed)
			continue;

		changed = 0;
		if (!gr_update (ngrp)) {
			fprintf (stderr,
				 _("%s: error adding new group entry\n"),
				 Prog);
			SYSLOG ((LOG_ERR, "error adding group entry"));
			gr_unlock ();
			return -1;
		}
#ifdef	NDBM
		/*
		 * Update the DBM group file with the new entry as well.
		 */
		if (!gr_dbm_update (ngrp)) {
			fprintf (stderr,
				 _("%s: cannot add new dbm group entry\n"),
				 Prog);
			SYSLOG ((LOG_ERR, "error adding dbm group entry"));
			gr_unlock ();
			return -1;
		}
#endif				/* NDBM */
	}
#ifdef NDBM
	endgrent ();
#endif				/* NDBM */
	if (!gr_close ()) {
		fprintf (stderr, _("%s: cannot rewrite group file\n"),
			 Prog);
		gr_unlock ();
		return -1;
	}
	gr_unlock ();
	return 0;
}
开发者ID:daxxog,项目名称:shadow-utils-slitaz,代码行数:101,代码来源:usermod.c


示例20: findgroupbyname

static int
findgroupbyname(const char *name, struct group *grp, char *buf, size_t buflen, struct group **result)
{
    int rc;
# if defined(WITH_PAM_USER_LOOKUP) || \
     ( defined(WITH_FILE_USER_LOOKUP) && \
       !( defined(HAVE_FGETGRENT_R) && defined(HAVE_FGETPWENT_R) ) )
    rc = pthread_mutex_lock( &pw_gr_serializer );
    if( rc != 0 )
        return ENOENT;
# endif

# if defined(WITH_PAM_USER_LOOKUP)
    setgrent();
#  if defined(HAVE_GETGRGID_R)
    rc = getgrnam_r( name, grp, buf, buflen, result );
#  elif defined(HAVE_GETGRGID)
#   error non-reentrant function support using getgrgid() currently not implemented
#  else
#   error neither getgrgid_r() nor getgrgid() available
#  endif
    endgrent();
# elif defined(WITH_FILE_USER_LOOKUP)
    if( name == 0 )
    {
        if( result )
            *result = 0;

        rc = ENOENT;
    }
    else
    {
        FILE *fp = fopen( "/etc/group", "r" );
        if( 0 == fp )
        {
            rc = errno;
        }
        else
        {
#  if defined(HAVE_FGETGRENT_R)
            while( 0 == ( rc = fgetgrent_r( fp, grp, buf, buflen, result ) ) )
            {
                if( (grp->gr_name != 0) && strcmp( name, grp->gr_name ) == 0 )
                    break;
            }

            if( ( rc != 0 ) && ( result != 0 ) )
                *result = 0;

#  elif defined(HAVE_FGETGRENT)
#   error non-reentrant function support using fgetgrent() currently not implemented
#  else
#   error neither fgetgrent_r() nor fgetgrent() available
#  endif
            fclose( fp );
        }
    }
# endif

# if defined(WITH_PAM_USER_LOOKUP) || \
     ( defined(WITH_FILE_USER_LOOKUP) && \
       !( defined(HAVE_FGETGRENT_R) && defined(HAVE_FGETPWENT_R) ) )
    pthread_mutex_unlock( &pw_gr_serializer );
# endif

    re 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ endingSelection函数代码示例发布时间:2022-05-30
下一篇:
C++ endacq函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap