Ejemplo n.º 1
0
const char *group_name(gid_t gid)
{
	const char *retval;
	
	if (!gid_hash)
		gid_hash = g_hash_table_new(NULL, NULL);

	retval = g_hash_table_lookup(gid_hash, GINT_TO_POINTER(gid));

	if (!retval)
	{
		struct group *group;

		group = getgrgid(gid);
		retval = group ? g_strdup(group->gr_name)
			       : g_strdup_printf("[%d]", (int) gid);
		g_hash_table_insert(gid_hash, GINT_TO_POINTER(gid),
				(gchar *) retval);
	}

	return retval;
}
Ejemplo n.º 2
0
/* recoded such that the uid may be passed in *p */
static void passwd_study(struct passwd *p)
{
	int max = UINT_MAX;

	if (getpwnam(p->pw_name)) {
		bb_error_msg_and_die("%s '%s' in use", "user", p->pw_name);
		/* this format string is reused in adduser and addgroup */
	}

	if (!(option_mask32 & OPT_UID)) {
		if (option_mask32 & OPT_SYSTEM_ACCOUNT) {
			p->pw_uid = CONFIG_FIRST_SYSTEM_ID;
			max = CONFIG_LAST_SYSTEM_ID;
		} else {
			p->pw_uid = CONFIG_LAST_SYSTEM_ID + 1;
			max = 64999;
		}
	}
	/* check for a free uid (and maybe gid) */
	while (getpwuid(p->pw_uid) || (p->pw_gid == (gid_t)-1 && getgrgid(p->pw_uid))) {
		if (option_mask32 & OPT_UID) {
			/* -u N, cannot pick uid other than N: error */
			bb_error_msg_and_die("%s '%s' in use", "uid", itoa(p->pw_uid));
			/* this format string is reused in adduser and addgroup */
		}
		if (p->pw_uid == max) {
			bb_error_msg_and_die("no %cids left", 'u');
		}
		p->pw_uid++;
	}

	if (p->pw_gid == (gid_t)-1) {
		p->pw_gid = p->pw_uid; /* new gid = uid */
		if (getgrnam(p->pw_name)) {
			bb_error_msg_and_die("%s '%s' in use", "group", p->pw_name);
			/* this format string is reused in adduser and addgroup */
		}
	}
}
Ejemplo n.º 3
0
static void
group(struct passwd *pw, int nflag)
{
	struct group *gr;
	int cnt, id, lastid, ngroups;
	long ngroups_max;
	gid_t *groups;
	const char *fmt;

	ngroups_max = sysconf(_SC_NGROUPS_MAX) + 1;
	if ((groups = malloc(sizeof(gid_t) * (ngroups_max))) == NULL)
		err(1, "malloc");

	if (pw) {
		ngroups = ngroups_max;
		(void) getgrouplist(pw->pw_name, pw->pw_gid, groups, &ngroups);
	} else {
		ngroups = getgroups(ngroups_max, groups);
	}
	fmt = nflag ? "%s" : "%u";
	for (lastid = -1, cnt = 0; cnt < ngroups; ++cnt) {
		if (lastid == (id = groups[cnt]))
			continue;
		if (nflag) {
			if ((gr = getgrgid(id)))
				(void)printf(fmt, gr->gr_name);
			else
				(void)printf(*fmt == ' ' ? " %u" : "%u",
				    id);
			fmt = " %s";
		} else {
			(void)printf(fmt, id);
			fmt = " %u";
		}
		lastid = id;
	}
	(void)printf("\n");
	free(groups);
}
Ejemplo n.º 4
0
t_file	*ft_putinfo(t_file *file, char *filename, char *dirname, int isln)
{
	ssize_t		i;
	t_stat	filestats;
	char	*path;
	
	path = ft_strjoin(dirname, "/");
	path = ft_strjoin(path, filename);
	if ((lstat(path, &filestats)) == -1)
		lstat(filename, &filestats);
	file->type = ft_gettype(filestats);
	file->rights = ft_getrights(filestats);
	file->links = (int)(filestats.st_nlink);
	file->uname = (getpwuid(filestats.st_uid))->pw_name;
	file->gname = (getgrgid(filestats.st_gid))->gr_name;
	if (file->type != 'b' && file->type != 'c')
		file->size = filestats.st_size;
	file->lnpath = malloc(sizeof(char ) * ft_strlen(filename) + 1);
	file->laccess = filestats.st_atimespec;
	file->blocks = filestats.st_blocks;
	file->ldatamod = filestats.st_mtimespec;
	file->lstatch = filestats.st_ctimespec;
	file->birthtime = filestats.st_birthtimespec;
	file->dname = ft_strdup(filename);
	//printf("%c\n", file->type);
	if (file->type == 'l')
	{
		if ((i = readlink(filename, file->lnpath, file->size)) != -1)
			file->lnpath[i] = '\0';
	}
		//else
		//	return ;
	if (file->type == 'c' || file->type == 'b')
	{
		file->major = (int)major(filestats.st_rdev);
		file->minor = (int)minor(filestats.st_rdev);
	}
	return(file);
}
Ejemplo n.º 5
0
Archivo: id.c Proyecto: 2asoft/freebsd
static void
pretty(struct passwd *pw)
{
	struct group *gr;
	u_int eid, rid;
	char *login;

	if (pw) {
		(void)printf("uid\t%s\n", pw->pw_name);
		(void)printf("groups\t");
		group(pw, 1);
	} else {
		if ((login = getlogin()) == NULL)
			err(1, "getlogin");

		pw = getpwuid(rid = getuid());
		if (pw == NULL || strcmp(login, pw->pw_name))
			(void)printf("login\t%s\n", login);
		if (pw)
			(void)printf("uid\t%s\n", pw->pw_name);
		else
			(void)printf("uid\t%u\n", rid);

		if ((eid = geteuid()) != rid) {
			if ((pw = getpwuid(eid)))
				(void)printf("euid\t%s\n", pw->pw_name);
			else
				(void)printf("euid\t%u\n", eid);
		}
		if ((rid = getgid()) != (eid = getegid())) {
			if ((gr = getgrgid(rid)))
				(void)printf("rgid\t%s\n", gr->gr_name);
			else
				(void)printf("rgid\t%u\n", rid);
		}
		(void)printf("groups\t");
		group(NULL, 1);
	}
}
Ejemplo n.º 6
0
/**
 * Write file statics in a line using the buffer from stat(...) primitive
 */
static bool get_file_info_stat(const char *file_name, char *line,struct stat *s_buff){
	char date[16];
	char mode[11]	= "----------";
	line[0]='\0';
	struct passwd * pass_info = getpwuid(s_buff->st_uid);
	if(pass_info!=NULL) {
		struct group * group_info = getgrgid(s_buff->st_gid);
		if(group_info!=NULL) {
			int b_mask = s_buff->st_mode & S_IFMT;
			if(b_mask == S_IFDIR) {
				mode[0]='d';
			} else if(b_mask == S_IFREG){
				mode[0]='-';
			} else {
				return FALSE;
			}
			mode[1] = (s_buff->st_mode & S_IRUSR)?'r':'-';
			mode[2] = (s_buff->st_mode & S_IWUSR)?'w':'-';
			mode[3] = (s_buff->st_mode & S_IXUSR)?'x':'-';
			mode[4] = (s_buff->st_mode & S_IRGRP)?'r':'-';
			mode[5] = (s_buff->st_mode & S_IWGRP)?'w':'-';
			mode[6] = (s_buff->st_mode & S_IXGRP)?'x':'-';
			mode[7] = (s_buff->st_mode & S_IROTH)?'r':'-';
			mode[8] = (s_buff->st_mode & S_IWOTH)?'w':'-';
			mode[9] = (s_buff->st_mode & S_IXOTH)?'x':'-';
			strftime(date,13,"%b %d %H:%M",localtime(&(s_buff->st_mtime)));

			write_file(
				line,mode,s_buff->st_nlink,
				pass_info->pw_name,
				group_info->gr_name,
				s_buff->st_size,date,
				file_name
			);
			return TRUE;
		}
	}
	return FALSE;
}
Ejemplo n.º 7
0
int make_dir(char *path, mode_t mode, uid_t uid, gid_t gid)
{
	struct passwd *pwd;
	struct group *grp;

	if (opt_dry_run) {
		pwd = getpwuid(uid);
		grp = getgrgid(gid);
		printf("if [ ! -e %s ]\n", path);
		printf("then\n");
		printf(" mkdir %s\n", path);
		printf(" chown %s:%s %s\n", pwd->pw_name, grp->gr_name, path);
		printf(" chmod %o %s\n", mode, path);
		printf("fi\n");
		return 0;
	}

	if (mkdir(path, mode)) {
		if (errno != EEXIST) {
			ERROR("Unable to create dir %s, error: %s\n",
				path, strerror(errno));
			return 1;
		}
	} else {
		if (chown(path, uid, gid)) {
			ERROR("Unable to change ownership of %s, error: %s\n",
				path, strerror(errno));
			return 1;
		}

		if (chmod(path, mode)) {
			ERROR("Unable to change permission on %s, error: %s\n",
				path, strerror(errno));
			return 1;
		}
	}

	return 0;
}
Ejemplo n.º 8
0
/* Returns information about the group with specified integer group id (gid),
 * as found in /etc/group.
 *
 * The information is returned as a Struct::Group; see getgrent above for
 * details.
 *
 * e.g.  Etc.getgrgid(100) -> #<struct Struct::Group name="users", passwd="x",
 * gid=100, mem=["meta", "root"]>
 *
 */
static VALUE
etc_getgrgid(int argc, VALUE *argv, VALUE obj)
{
#ifdef HAVE_GETGRENT
    VALUE id;
    gid_t gid;
    struct group *grp;

    rb_secure(4);
    if (rb_scan_args(argc, argv, "01", &id) == 1) {
        gid = NUM2GIDT(id);
    }
    else {
        gid = getgid();
    }
    grp = getgrgid(gid);
    if (grp == 0) rb_raise(rb_eArgError, "can't find group for %d", (int)gid);
    return setup_group(grp);
#else
    return Qnil;
#endif
}
static JBoolean
jGetGroupInfo
	(
	const gid_t	gid,
	jGIDInfo*	info
	)
{
	if (groupInfoMap.IsEmpty())
		{
		groupInfoMap.SetCompareFunction(jCompareGIDs);
		groupInfoMap.SetSortOrder(JOrderedSetT::kSortAscending);
		}

	const jGIDInfo target = { gid, NULL };
	JIndex i;
	if (groupInfoMap.SearchSorted(target, JOrderedSetT::kAnyMatch, &i))
		{
		*info = groupInfoMap.GetElement(i);
		}
	else
		{
		group* grpbuf = getgrgid(gid);
		if (grpbuf != NULL)
			{
			info->groupName = new JString(grpbuf->gr_name);
			assert( info->groupName != NULL );

			info->id = gid;
			const JBoolean inserted = groupInfoMap.InsertSorted(*info, kJFalse);
			assert( inserted );
			}
		else
			{
			info->groupName = NULL;
			}
		}

	return JI2B( info->groupName != NULL );
}
Ejemplo n.º 10
0
gid_t Utils::getGroupId(const char *groupName)
{
    static bool init=false;
    static gid_t gid=0;

    if (init) {
        return gid;
    }

    init=true;

    // First of all see if current group is actually 'groupName'!!!
    gid_t egid=getegid();
    struct group *group=getgrgid(egid);

    if (group && 0==strcmp(group->gr_name, groupName)) {
        gid=egid;
        return gid;
    }

    // Now see if user is a member of 'groupName'
    struct passwd *pw=getpwuid(geteuid());

    if (!pw) {
        return gid;
    }

    group=getgrnam(groupName);

    if (group) {
        for (int i=0; group->gr_mem[i]; ++i) {
            if (0==strcmp(group->gr_mem[i], pw->pw_name)) {
                gid=group->gr_gid;
                return gid;
            }
        }
    }
    return gid;
}
/* Get a list of group names, filtered to only the ones
 * that contain the given username. If the username is
 * NULL, returns a list of all group names.
 */
GList *
eel_get_group_names_for_user (void)
{
	GList *list;
	struct group *group;
	int count, i;
	gid_t gid_list[NGROUPS_MAX + 1];
	

	list = NULL;

	count = getgroups (NGROUPS_MAX + 1, gid_list);
	for (i = 0; i < count; i++) {
		group = getgrgid (gid_list[i]);
		if (group == NULL)
			break;
		
		list = g_list_prepend (list, g_strdup (group->gr_name));
	}

	return eel_g_str_list_alphabetize (list);
}
Ejemplo n.º 12
0
char *strgid(gid_t id)
{
	struct name_cache *tail = groups;
	struct group *grent;
	char *name, buff[6];

	while (tail && tail->id != id)
		tail = tail->next;
	if (tail == 0 || tail->id != id) {
		if ((grent = getgrgid(id)) == 0)
			sprintf(name = buff, "%u", id);
		else
			name = grent->gr_name;
		if ((tail = malloc(sizeof *tail)) == 0)
			return name;
		tail->id = id;
		tail->name = strdup(name);
		tail->next = groups;
		groups = tail;
	}
	return tail->name;
}
Ejemplo n.º 13
0
int main()
{
     DIR *dir;
        if ((dir = opendir(".")) == NULL) 
        {
        	perror("couldn't open '.'");
                return;
        }
     /* Loop through directory entries */
     while ((dp = readdir(dir)) != NULL) {
         /* Get entry's information. */
         if (stat(dp->d_name, &statbuf) == -1)
         continue;

          /* Print out type, permissions, and number of links. */
          printf("%10.10s", sperm (statbuf.st_mode));
          printf("%4d", statbuf.st_nlink);

          /* Print out owners name if it is found using getpwuid(). */
          if ((pwd = getpwuid(statbuf.st_uid)) != NULL)
             printf(" %-8.8s", pwd->pw_name);
          else
             printf(" %-8d", statbuf.st_uid);

          /* Print out group name if it's found using getgrgid(). */
          if ((grp = getgrgid(statbuf.st_gid)) != NULL)
             printf(" %-8.8s", grp->gr_name);
          else
             printf(" %-8d", statbuf.st_gid);

          /* Print size of file. */
          printf(" %9jd", (intmax_t)statbuf.st_size);
          tm = localtime(&statbuf.st_mtime);

          /* Get localized date string. */
          strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm);
          printf(" %s %s\n", datestring, dp->d_name);
      }
}
Ejemplo n.º 14
0
void maGetUserGroup(MaAppweb *appweb)
{
#if BLD_UNIX_LIKE
    struct passwd   *pp;
    struct group    *gp;

    appweb->uid = getuid();
    if ((pp = getpwuid(appweb->uid)) == 0) {
        mprError("Can't read user credentials: %d. Check your /etc/passwd file.", appweb->uid);
    } else {
        appweb->user = sclone(pp->pw_name);
    }
    appweb->gid = getgid();
    if ((gp = getgrgid(appweb->gid)) == 0) {
        mprError("Can't read group credentials: %d. Check your /etc/group file", appweb->gid);
    } else {
        appweb->group = sclone(gp->gr_name);
    }
#else
    appweb->uid = appweb->gid = -1;
#endif
}
Ejemplo n.º 15
0
Archivo: ugid.c Proyecto: lb1a/avfs
char *av_findgname(struct ugidcache *cache, int gid, const char *deflt)
{
    if(gid == -1)
        return av_strdup(deflt);

    if(cache->gname == NULL || gid != cache->gid) {
        int res;
        struct group gr;
        struct group *grres;
        char *buf = NULL;
        size_t bufsize = 0;

#ifdef HAVE_GETGRGID_R
        do {
            bufsize += 256;
            buf = av_realloc(buf, bufsize);
            res = getgrgid_r(gid, &gr, buf, bufsize, &grres);
        } while(res == ERANGE);
#else
	grres = getgrgid(gid);
#endif

        av_free(cache->gname);
        if(grres == NULL)
            cache->gname = av_strdup("");
        else
            cache->gname = av_strdup(grres->gr_name);

        cache->gid = gid;
#ifdef HAVE_GETGRGID_R
        av_free(buf);
#endif
    }
    
    if(!cache->gname[0])
        return av_strdup(deflt);
    else
        return av_strdup(cache->gname);
}
Ejemplo n.º 16
0
static int
check_group_membership(const char* usr, const char* grp)
{
	int index = 0;
	struct passwd *pwd = NULL;
	struct group *group = NULL;
	
	CRM_CHECK(usr != NULL, return FALSE);
	CRM_CHECK(grp != NULL, return FALSE);

	pwd = getpwnam(usr);
	if (pwd == NULL) {
		crm_err("No user named '%s' exists!", usr);
		return FALSE;
	}

	group = getgrgid(pwd->pw_gid);
	if (group != NULL && crm_str_eq(grp, group->gr_name, TRUE)) {
		return TRUE;
	}
	
	group = getgrnam(grp);
	if (group == NULL) {
		crm_err("No group named '%s' exists!", grp);
		return FALSE;
	}

	while (TRUE) {
		char* member = group->gr_mem[index++];
		if(member == NULL) {
			break;

		} else if (crm_str_eq(usr, member, TRUE)) {
			return TRUE;
		}
	};

	return FALSE;
}
Ejemplo n.º 17
0
Archivo: lposix.c Proyecto: ktf/apt-rpm
static int Pgetgroup(lua_State *L)		/** getgroup(name or id) */
{
	struct group *g=NULL;
	if (lua_isnumber(L, 1))
		g = getgrgid((gid_t)lua_tonumber(L, 1));
	else if (lua_isstring(L, 1))
		g = getgrnam(lua_tostring(L, 1));
	else
		luaL_typerror(L, 1, "string or number");
	if (g==NULL)
		lua_pushnil(L);
	else
	{
		int i;
		lua_newtable(L);
		storestring(L, "name", g->gr_name);
		storenumber(L, "gid", g->gr_gid);
		for (i=0; g->gr_mem[i] != NULL; i++)
			storeindex(L, i+1, g->gr_mem[i]);
	}
	return 1;
}
Ejemplo n.º 18
0
void print_stat( const compiled_stats_t const * stats )
{
   if( !stats )
      return;

   struct passwd* user_info = getpwuid( stats->uid );
   struct group* group_info = getgrgid( stats->gid );
   printf( "   Relative Name ...... %s", stats->name );
      
      // add '/' if it is a dir
   if( S_ISDIR( stats->mode ) )
      printf( "/\n" );
   else
      printf( "\n" );

   printf( "   Inode Number ....... %ld\n", stats->inode );

      // add (self) if gid or uid is the currently 
      // running user/group
   if( stats->uid == getuid() )
      printf( "   Owner .............. %s (self)\n", user_info->pw_name );
   else
      printf( "   Owner .............. %s\n", user_info->pw_name );

   if( stats->gid == getgid() )
      printf( "   Group .............. %s (self)\n", group_info->gr_name );
   else
      printf( "   Group .............. %s\n", group_info->gr_name );

   printf( "   File Size (bytes) .. %ld\n", stats->size );
   printf( "   Last Modified ...... %s", ctime( &(stats->mtime) ) );
   
   char perm[12];
   strmode( stats->mode, perm );
   printf( "   Access Rights ...... %s\n", perm );
   printf( "\n" );

}
Ejemplo n.º 19
0
static char *
humanize_ids(char *rule)
{
	id_t id;
	struct passwd *pwd;
	struct group *grp;
	const char *subject, *textid, *rest;
	char *humanized;

	subject = strsep(&rule, ":");
	textid = strsep(&rule, ":");
	if (textid == NULL)
		errx(1, "rule passed from the kernel didn't contain subject");
	if (rule != NULL)
		rest = rule;
	else
		rest = "";

	/* Replace numerical user and group ids with names. */
	if (strcasecmp(subject, "user") == 0) {
		id = parse_user(textid);
		pwd = getpwuid(id);
		if (pwd != NULL)
			textid = pwd->pw_name;
	} else if (strcasecmp(subject, "group") == 0) {
		id = parse_group(textid);
		grp = getgrgid(id);
		if (grp != NULL)
			textid = grp->gr_name;
	}

	asprintf(&humanized, "%s:%s:%s", subject, textid, rest);

	if (humanized == NULL)
		err(1, "asprintf");

	return (humanized);
}
Ejemplo n.º 20
0
static PyObject *
grp_getgrgid_impl(PyModuleDef *module, PyObject *id)
/*[clinic end generated code: output=8a11f5fdeb8c78a0 input=15fa0e2ccf5cda25]*/
{
    PyObject *py_int_id;
    gid_t gid;
    struct group *p;

    if (!_Py_Gid_Converter(id, &gid)) {
        if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
            return NULL;
        }
        PyErr_Clear();
        if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
                             "group id must be int, not %.200",
                             id->ob_type->tp_name) < 0) {
            return NULL;
        }
        py_int_id = PyNumber_Long(id);
        if (!py_int_id)
            return NULL;
        if (!_Py_Gid_Converter(py_int_id, &gid)) {
            Py_DECREF(py_int_id);
            return NULL;
        }
        Py_DECREF(py_int_id);
    }

    if ((p = getgrgid(gid)) == NULL) {
        PyObject *gid_obj = _PyLong_FromGid(gid);
        if (gid_obj == NULL)
            return NULL;
        PyErr_Format(PyExc_KeyError, "getgrgid(): gid not found: %S", gid_obj);
        Py_DECREF(gid_obj);
        return NULL;
    }
    return mkgrent(p);
}
Ejemplo n.º 21
0
void fastproxy::parse_config(int argc, char* argv[])
{
    po::options_description desc("Allowed options");
    desc.add_options()
            ("help", "produce help message")
            ("ingoing-http", po::value<endpoint_vec>()->required(), "http listening addresses")
            ("ingoing-stat", po::value<std::string>()->required(), "statistics listening socket")
            ("outgoing-http", po::value<ip::tcp::endpoint>()->default_value(ip::tcp::endpoint()), "outgoing address for HTTP requests")
            ("outgoing-ns", po::value<ip::udp::endpoint>()->default_value(ip::udp::endpoint()), "outgoing address for NS lookup")
            ("log-level", po::value<int>()->default_value(2), "logging level")
            ("log-channel", po::value<string_vec>(), "logging channel")
            ("receive-timeout", po::value<time_duration::sec_type>()->default_value(3600), "timeout for receive operations (in seconds)")
            ("connect-timeout", po::value<time_duration::sec_type>()->default_value(3), "timeout for connect operation (in seconds)")
            ("resolve-timeout", po::value<time_duration::sec_type>()->default_value(3), "timeout for resolve operation (in seconds)")
            ("allow-header", po::value<string_vec>()->default_value(string_vec(), "any"), "allowed header for requests")
            ("stat-socket-user", po::value<std::string>()->default_value(getpwuid(getuid())->pw_name), "user for statistics socket")
            ("stat-socket-group", po::value<std::string>()->default_value(getgrgid(getgid())->gr_name), "group for statistics socket")
            ("stop-after-init", po::value<bool>()->default_value(false), "raise SIGSTOP after initialization (Upstart support)")
            ("error-page-dir", po::value<std::string>()->default_value("/etc/fastproxy/errors"), "directory where error pages are located");

    try
    {
        po::store(po::parse_command_line(argc, argv, desc), vm);

        if (vm.count("help"))
        {
            std::cout << desc << std::endl;
            exit(1);
        }

        po::notify(vm);
    }
    catch (const boost::program_options::required_option& exc)
    {
        std::cout << desc << std::endl;
        throw;
    }
}
Ejemplo n.º 22
0
int
dogetgr(const char **list)
{
	struct group *grp;
	int rc = EXC_SUCCESS;
	char *ptr;
	gid_t gid;

	if (list == NULL || *list == NULL) {
		while ((grp = getgrent()) != NULL)
			(void) putgrent(grp, stdout);
	} else {
		for (; *list != NULL; list++) {
			errno = 0;

			/*
			 * Here we assume that the argument passed is
			 * a gid, if it can be completely transformed
			 * to a long integer. So we check for gid in
			 * the database and if we fail then we check
			 * for the group name.
			 * If the argument passed is not numeric, then
			 * we take it as the group name and proceed.
			 */
			gid = strtoul(*list, &ptr, 10);
			if (!(*ptr == '\0' && errno == 0) ||
			    ((grp = getgrgid(gid)) == NULL)) {
				grp = getgrnam(*list);
			}
			if (grp == NULL)
				rc = EXC_NAME_NOT_FOUND;
			else
				(void) putgrent(grp, stdout);
		}
	}

	return (rc);
}
/*
 * drwxr-xr-x    5 markus   markus       1024 Jan 13 18:39 .ssh
 */
static char *
ls_file(char *name, struct stat *st)
{
	int ulen, glen, sz = 0;
	struct passwd *pw;
	struct group *gr;
	struct tm *ltime = localtime(&st->st_mtime);
	char *user, *group;
	char buf[1024], mode[11+1], tbuf[12+1], ubuf[11+1], gbuf[11+1];

	strmode(st->st_mode, mode);
	if ((pw = getpwuid(st->st_uid)) != NULL) {
		user = pw->pw_name;
	} else {
		snprintf(ubuf, sizeof ubuf, "%u", (u_int)st->st_uid);
		user = ubuf;
	}
	if ((gr = getgrgid(st->st_gid)) != NULL) {
		group = gr->gr_name;
	} else {
		snprintf(gbuf, sizeof gbuf, "%u", (u_int)st->st_gid);
		group = gbuf;
	}
	if (ltime != NULL) {
		if (time(NULL) - st->st_mtime < (365*24*60*60)/2)
			sz = strftime(tbuf, sizeof tbuf, "%b %e %H:%M", ltime);
		else
			sz = strftime(tbuf, sizeof tbuf, "%b %e  %Y", ltime);
	}
	if (sz == 0)
		tbuf[0] = '\0';
	ulen = MAX(strlen(user), 8);
	glen = MAX(strlen(group), 8);
	snprintf(buf, sizeof buf, "%s %3d %-*s %-*s %8llu %s %s", mode,
	    st->st_nlink, ulen, user, glen, group,
	    (u_int64_t)st->st_size, tbuf, name);
	return xstrdup(buf);
}
Ejemplo n.º 24
0
char *libfile_status (const char *address, char category) {
	if (address == NULL) return NULL;
	struct stat status; if (lstat (address, &status) == -1) return NULL;
	if (category == 't') {
		if (S_ISREG (status.st_mode)) return strdup ("Regular file");
		else if (S_ISDIR (status.st_mode)) return strdup ("Directory");
		else if (S_ISCHR (status.st_mode)) return strdup ("Character device");
		else if (S_ISBLK (status.st_mode)) return strdup ("Block device");
		else if (S_ISFIFO (status.st_mode)) return strdup ("FIFO");
		else if (S_ISLNK (status.st_mode)) return strdup ("Symbolic link");
		else if (S_ISSOCK (status.st_mode)) return strdup ("Socket");
		else return strdup ("Unknown type");
	}
	else if (category == 's') return libtext_number ((int) status.st_size);
	else if (category == 'o') {
		struct passwd *owner = getpwuid (status.st_uid); if (owner == NULL) return NULL;
		return strdup (owner->pw_name);
	}
	else if (category == 'g') {
		struct group *group = getgrgid (status.st_gid); if (group == NULL) return NULL;
		return strdup (group->gr_name);
	}
}
Ejemplo n.º 25
0
static void			nbr_space2(t_dnode *temp, t_space *space)
{
	int				group;
	int				user;
	int				min;
	struct group	*sgroup;
	struct passwd	*suser;

	sgroup = getgrgid(((t_value*)(temp->content))->sb->st_gid);
	suser = getpwuid(((t_value*)(temp->content))->sb->st_uid);
	if (sgroup)
		group = ft_strlen(sgroup->gr_name);
	else
		group = nbr_len(((t_value*)(temp->content))->sb->st_gid);
	if (suser)
		user = ft_strlen(suser->pw_name);
	else
		user = nbr_len(((t_value*)(temp->content))->sb->st_uid);
	min = nbr_len(minor(((t_value*)(temp->content))->sb->st_rdev));
	space->group = (space->group < group) ? group : space->group;
	space->user = (space->user < user) ? user : space->user;
	space->min = (space->min < min) ? min : space->min;
}
Ejemplo n.º 26
0
/* Print the name or value of group ID GID. */
extern bool
print_group (gid_t gid, bool use_name)
{
  struct group *grp = NULL;
  bool ok = true;

  if (use_name)
    {
      grp = getgrgid (gid);
      if (grp == NULL)
        {
          error (0, 0, _("cannot find name for group ID %lu"),
                 (unsigned long int) gid);
          ok = false;
        }
    }

  if (grp == NULL)
    printf ("%lu", (unsigned long int) gid);
  else
    printf ("%s", grp->gr_name);
  return ok;
}
Ejemplo n.º 27
0
int isUserOfGroup(char* username, char* groupname){
    int numgroups, iter, retCode;
    int numgroups_max = sysconf(_SC_NGROUPS_MAX) + 1;
    gid_t groupList[numgroups_max];
    retCode = initgroups(username, 0);

    if (retCode != 0){
        printf("Permissions issue : %d\n\n", retCode);
        return -1;
    }
    numgroups = getgroups(numgroups_max, groupList);
    for (iter=0; iter <= numgroups; iter++){
        if (iter != 0 &&  iter != numgroups ){
            struct group *g = getgrgid(groupList[iter]);
            if(g != NULL){
                if(strcmp(g->gr_name,groupname) == 0){
                    return 1;
                }
            }
        }
    }
    return 0;
}
Ejemplo n.º 28
0
static char *
decode_group(gid_t gid)
{
	struct group *gr;
	static gid_t sav_gid = -1;
	static char sav_gidstr[256];

	if (gid != sav_gid) {
#ifdef VIRTUAL_ID
		if (gid == 0)
			return ("root");
		sav_gid = gid;
		if (Cns_getgrpbygid (sav_gid, sav_gidstr) < 0)
#else
		sav_gid = gid;
		if (gr = getgrgid (sav_gid)) {
			strcpy (sav_gidstr, gr->gr_name);
		} else
#endif
			sprintf (sav_gidstr, "%d", sav_gid);
	}
	return (sav_gidstr);
}
Ejemplo n.º 29
0
wi_boolean_t _wi_settings_set_group(wi_settings_t *settings, wi_uinteger_t index, wi_string_t *name, wi_string_t *value) {
	struct group		*group;
	uint32_t			gid;
	
	group = getgrnam(wi_string_cstring(value));
	
	if(!group) {
		gid = wi_string_uint32(value);
		
		if(gid != 0 || wi_is_equal(value, WI_STR("0")))
			group = getgrgid(wi_string_uint32(value));
	}

	if(!group) {
		wi_error_set_libwired_error(WI_ERROR_SETTINGS_NOSUCHGROUP);

		return false;
	}

	*(gid_t *) settings->spec[index].setting = group->gr_gid;
	
	return true;
}
Ejemplo n.º 30
0
static void listGroupMembers(gid_t gid, uint maxCount, std::function<void(passwd *)> handleNextGroupUser)
{
    if (maxCount == 0) {
        return;
    }
    struct group *g = getgrgid(gid);
    if (!g) {
        return;
    }
    uint found = 0;
    QVarLengthArray<uid_t> addedUsers;
    struct passwd *p = 0;
    for (char **user = g->gr_mem; *user; user++) {
        if ((p = getpwnam(*user))) {
            addedUsers.append(p->pw_uid);
            handleNextGroupUser(p);
            found++;
            if (found >= maxCount) {
                break;
            }
        }
    }

    //gr_mem doesn't contain users where the primary group == gid -> we have to iterate over all users
    setpwent();
    while ((p = getpwent()) && found < maxCount) {
        if (p->pw_gid != gid) {
            continue; // only need primary gid since otherwise gr_mem already contains this user
        }
        // make sure we don't list a user twice
        if (std::find(addedUsers.cbegin(), addedUsers.cend(), p->pw_uid) == addedUsers.cend()) {
            handleNextGroupUser(p);
            found++;
        }
    }
    endpwent();
}