Darthfett Darthfett - 4 years ago 182
C Question

Writing my own HTTP Server - How to find relative path of a file

I'm currently writing an HTTP Server over UNIX Sockets in C, and I'm about to implement the part of the GET request that checks the requested file to make sure it has appropriate permissions.

Before I knew anything about HTTP servers, I set up an Apache server, and it is my understanding that there is a single directory which the HTTP server looks to find a requested file. I do not know if this is because the server somehow has no permissions outside of the directory, or if it actually validates the path to ensure it is inside the directory.

Now that I am about to implement this on my own, I'm not sure how to properly handle this. Is there a function in C that will allow me to determine if a path is inside a given directory (e.g. is

foo/bar/../../baz
inside
foo/
)?

In python, I would use
os.path.relpath
and check if the result starts with
..
, to ensure that the path is not outside the given directory.

For example, if the directory is
/foo/bar/htdocs
, and the given path is
index.html/../../passwords.txt
, I want
../passwords.txt
, so I can see from the leading
..
that the file is outside the
/foo/bar/htdocs
directory.

Answer Source

As a simple (but incomplete) solution, I just decided to write a bit of code to check the file path for any ...

int is_valid_fname(char *fname) {
    char *it = fname;
    while(TRUE) {
        if (strncmp(it, "..", 2) == 0) {
            return FALSE;
        }
        it = strchr(it, '/');
        if (it == NULL) break;
        it++;
    }
    return TRUE;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download