Search code examples
ctcphttp-headers

Stat function always returns -1 on valid paths


I'm trying to write a simple webserver using sockets in C. I want to check if the request url is just a directory or a file i.e. localhost:8080/docroot or localhost:8080/docroot/file.html.

That's why I wanted to use stat() and the ISDIR and ISREG macros. Unfortunately the stat function always returns -1. The request url itself is correct (in this example it is /docroot). I also tried adding a dot in front of it, but that didn't work either.

struct stat fileinfo;
char request_line[255];
char* request_method; // GET, POST etc.
char* request_path; // the url
strncpy(request_line, in, indexOf(in, '\n'));

request_method = strtok(request_line, " ");
request_path = strtok(NULL, " ");

// the actual thing
if (stat(request_path, &fileinfo) == -1) {
  printf("Invalid path: #%s#", request_path);
  throwError();
}
if (S_ISDIR(fileinfo.st_mode))
  renderDirectory(request_path, sockfd);
else if (S_ISREG(fileinfo.st_mode)) {
  transferFile(request_path, sockfd);
} 
else
  throwError("Fehler beim erkennen der Datei/des Pfades");

So as I said, the request_path returns the correct url which is /docroot. The directory exists inside of the cwd. Unfortunately the stat function returns -1 no matter what. Maybe it's just a stupid mistake of mine, but I can't seem to figure this out...

Edit: the output of the printf is:

#/docroot#

Solution

  • So I found the issue. All of you who said it was because the path isn't relative: you were wrong. I have no idea why, but apparently a threading issue in some part of the code which is being called much later, was the problem here. I removed that bit and now it works with and without a dot and/or slash.