1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
|
static int update_fsize(int objectif, int fsize, int fd)
{
--fsize;
while (++fsize <= objectif)
{
write(fd, " ", 1);
}
return (fsize);
}
static int init_file(char **av, void *file, int fsize, int fd)
{
t_users_index idx;
t_user user;
int objectif;
strcpy(idx.magic, MAGIC);
idx.nbr_users = 1;
idx.st_user_size = sizeof(t_user);
strcpy(user.login, av[1]);
strcpy(user.password, av[2]);
strcpy(user.root, USER_DIR);
strcat(user.root, av[1]);
objectif = sizeof(t_users_index);
fsize = update_fsize(objectif, fsize, fd);
memcpy(file, (void*)&idx, sizeof(t_users_index));
file = (void*)((int)file + sizeof(t_users_index));
objectif += sizeof(t_user);
fsize = update_fsize(objectif, fsize, fd);
memcpy(file, (void*)&user, sizeof(t_user));
file = (void*)((int)file + sizeof(t_user));
return (sizeof(t_user) + sizeof(t_users_index));
}
static int insert_file(char **av, void *file, int fsize, int fd)
{
t_users_index *idx;
t_user *user;
idx = (t_users_index*)file;
if (strcmp(idx->magic, MAGIC) != 0)
{
printf("Corrupted Memory\n");
exit(EXIT_FAILURE);
}
fsize = update_fsize(((idx->nbr_users + 1) * sizeof(t_user)), fsize, fd);
user = (t_user*)((int)file + sizeof(t_users_index) +
(idx->nbr_users * sizeof(t_user)));
idx->nbr_users++;
strcpy(user->login, av[1]);
strcpy(user->password, av[2]);
strcpy(user->root, USER_DIR);
strcat(user->root, av[1]);
return (fsize);
}
int add_user(char **av, void *file, int fsize, int fd)
{
printf("NEW user\nLogin : %s\nPassword : %s\n", av[1], av[2]);
if (fsize < 8)
{
fsize = init_file(av, file, fsize, fd);
return (fsize);
}
fsize = insert_file(av, file, fsize, fd);
return (fsize);
}
static void dump_memory(void* file)
{
t_users_index *idx;
t_user *user;
int i;
idx = (t_users_index*)file;
if (strcmp(idx->magic, MAGIC) != 0)
{
printf("Corrupted Memory\n");
exit(EXIT_FAILURE);
}
i = -1;
printf("idx : %d\n", idx->nbr_users);
user = (t_user*)((int)file + sizeof(t_users_index));
while (++i != idx->nbr_users)
{
printf("Login : %s\nPassword : %s\nRoot : %s\n"
, user->login, user->password, user->root);
user = (t_user*)((int)user + idx->st_user_size);
}
}
int main(int ac, char **av)
{
int fd;
int fsize;
void *file;
if (-1 == (fd = open(FNAME, O_CREAT | O_RDWR, 0755)))
{
printf("open failed\n");
return (EXIT_FAILURE);
}
fsize = lseek(fd, 0, SEEK_END);
file = mmap(NULL, fsize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (file == MAP_FAILED)
{
printf("mmap failed %d\n", fsize);
return (EXIT_FAILURE);
}
if (ac == 3)
fsize = add_user(av, file, fsize, fd) + 1;
else
dump_memory(file);
if (-1 == munmap(file, fsize))
printf("mmap failed\n");
return (EXIT_SUCCESS);
} |
Partager