Skip to content

Commit

Permalink
kthd: resolve to absolute path in chdir()
Browse files Browse the repository at this point in the history
  • Loading branch information
jewelcodes committed Oct 4, 2024
1 parent 2fed36e commit 48139c6
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions kthd/src/chdir.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,58 @@

#include <liblux/liblux.h>
#include <sys/stat.h>
#include <string.h>
#include <errno.h>

/* clean(): helper function to clean up a path
* params: path - path to be cleaned, the string will be directly modified
* params: pointer to path
*/

static char *clean(char *path) {
if(strlen(path) == 1) return path; // root will never need to be cleaned

// first try to get rid of excessive slashes
for(int i = 0; i < strlen(path); i++) {
if((path[i] == '/') && (i < strlen(path)-1) && (path[i+1] == '/')) {
memmove(&path[i], &path[i+1], strlen(&path[i])+1);
continue;
}
}

// if the last character is a slash, remove it except for the root dir
if(strlen(path) == 1) return path;
while(path[strlen(path)-1] == '/') path[strlen(path)-1] = 0;

// parse '../' to reflect the parent directory
for(int i = 0; i < strlen(path); i++) {
if((path[i] == '.') && (path[i+1] == '.') && ((path[i+2] == '/') || (!path[i+2]))) {
// find the parent
int parent = i-2;
for(; parent > 0; parent--) {
if(path[parent] == '/') break;
}

parent++;
memmove(&path[parent], &path[i+3], strlen(&path[i+3])+1);
}
}

// remove './' because it refers to the self directory
for(int i = 0; i < strlen(path); i++) {
if((path[i] == '.') && ((path[i+1] == '/') || (!path[i+1]))) {
memmove(&path[i], &path[i+2], strlen(&path[i+2])+1);
continue;
}
}

// and finally remove any trailing slashes left while processing the string
if(strlen(path) == 1) return path;
while(path[strlen(path)-1] == '/') path[strlen(path)-1] = 0;

return path;
}

void kthdChdir(ChdirCommand *cmd) {
cmd->header.header.response = 1;
cmd->header.header.length = sizeof(ChdirCommand);
Expand Down Expand Up @@ -37,5 +87,7 @@ void kthdChdir(ChdirCommand *cmd) {
if(!(st.st_mode & S_IXOTH)) cmd->header.header.status = -EPERM;
}

// success, clean up the path
clean(cmd->path);
luxSendLumen(cmd);
}

0 comments on commit 48139c6

Please sign in to comment.