CMLAB-Docker-Builder/tool/setup_uid.c
2024-05-25 18:35:26 +08:00

87 lines
2.6 KiB
C

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
bool check_user(char *filename, char *username, unsigned long *new_start) {
/*
* Check whether the user exists in the uid file (subuid, subgid).
* Return exists or not, and set the new_start if need it.
*
* Args:
* filename (char *): means the uid file (subuid or subgid).
* username (char *): the user who run this excutable file.
* new_start (unsigned long *): it's a pointer, save the new start point.
* Return:
* exist (bool): exist or not
*/
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("[ERROR] Please contact Unix Manager.\n");
exit(1);
}
// read data from subuid, subgid
char line[100];
char user[30];
unsigned long start, size; // 0~2^32-1, equal to subuid
bool exist = false;
while (fgets(line, sizeof(line), fp)) {
sscanf(line, "%[^:]:%lu:%lu", user, &start, &size);
*new_start = start + size;
if (strcmp(username, user) == 0) exist = true;
}
fclose(fp);
return exist;
}
void insert_user(char *filename, char *username, unsigned long start) {
/*
* Insert the user into uid file
* It will setup the next start uid automatically
* == it will change /etc/subuid or /etc/subgid ==
*
* Args:
* filename (char *): means the uid file (subuid or subgid).
* username (char *): the user who run this excutable file.
* new_start (unsigned long ): it's a value, means the next start uid
* Return:
* No
*/
FILE *fp = fopen(filename, "a");
if (fp == NULL) {
printf("[ERROR] Please contact Unix Manager.\n");
exit(1);
}
char new_line[100];
sprintf(new_line, "%s:%lu:%d\n", username, start, 65535);
fputs(new_line, fp);
fclose(fp);
printf("[SUCCESS] %s has been inserted in %s\n", username, filename);
}
int main() {
char *username = getlogin();
char filenames[2][20] = {
"/etc/subuid", "/etc/subgid"
};
bool exist;
unsigned long new_start; // 0~2^32-1, equal to subuid
for (int i=0; i<2; i++) {
new_start = 100000; // subuid, subgid default from 100000~165535
exist = check_user(filenames[i], username, &new_start);
if (exist) {
printf("[WARNING] %s has been in %s, no change\n", username, filenames[i]);
} else {
insert_user(filenames[i], username, new_start);
}
}
return 0;
}