Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
setuid to another user and give group members write permissionto files with certain extensions. No idea why I ever needed this.
// perm.c - setuid to another user and give group members write permission
// to files with certain extensions.
// Emil Hernvall, 2008-04-14
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>
// The extensions to modify
const char *extensions[] = { "jpg", "jpeg", "png", "gif" };
int main(int argc, char **argv)
{
if (argc != 2) {
printf("usage: perm [dir]\n");
return;
}
// Make sure the directory requested exists.
struct stat probe_res;
if (stat(argv[1], &probe_res)) {
perror("stat");
return 1;
}
// Change working directory out of pure laziness
printf("Changing cwd to %s\n", argv[1]);
if (chdir(argv[1])) {
perror("chdir");
return 1;
}
// Change user id to gain the ability to modify the permissions
if (setuid(geteuid())) {
perror("setuid");
return 1;
}
// Change the permissions of the directory
if (chmod(argv[1], S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP)) {
printf("Failed to change permission for %s: %s\n", argv[1], strerror(errno));
return 1;
} else {
printf("Changed permission for %s\n", argv[1]);
}
// Open the directory
DIR* dirh = opendir(".");
if (dirh == NULL) {
perror("opendir");
return 1;
}
struct dirent* current;
int i;
while ((current = readdir(dirh)) != NULL) {
// Retrieve the extension of the current file
char *ext = strchr(current->d_name, '.');
if (ext == NULL) {
continue;
}
// Check for a valid extension
for (i = 0; i < sizeof(extensions)/sizeof(const char*); i++) {
if (strcasecmp(extensions[i], ext+1) != 0) {
continue;
}
// Change the permissions.
if (chmod(current->d_name, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)) {
printf("Failed to change permission for %s: %s\n", current->d_name, strerror(errno));
} else {
printf("Changed permission for %s\n", current->d_name);
}
// our work here is done.
break;
}
}
// Close the directory.
closedir(dirh);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment