Test whether requested resource is a file or directory

This commit is contained in:
Camden Dixie O'Brien 2022-10-14 10:20:38 +01:00
parent a3cdde2c34
commit 543858d01d

61
main.c
View File

@ -157,7 +157,6 @@ int main(int argc, char *argv[])
socklen_t paddr_size = sizeof(paddr);
int cfd;
ssize_t n, slen;
DIR *rdir;
while (!exit_requested) {
/*
* Accept incoming connection.
@ -236,22 +235,40 @@ int main(int argc, char *argv[])
goto close_client_socket;
ppos += n;
// UNSAFE!
pbuf[ppos] = '\0';
printf("Requested path: %s\n", pbuf);
/*
* Determine the resource's type.
* Determine whether the resource is a file or a directory.
*
* The path passed to stat() has to be null-terminated, which
* pbuf is not, so a trailing null byte must first be added
* there.
*/
/*
* Open the resource.
*/
if (srvroot_len + 1 > PBUF_SIZE) {
if (ppos + 1 > PBUF_SIZE) {
fprintf(stderr, "Path buffer is too small\n");
goto close_client_socket;
}
pbuf[srvroot_len] = '\0';
pbuf[ppos] = '\0';
struct stat rstat;
if (stat(pbuf, &rstat) == -1) {
fprintf(stderr, "Failed to stat() path \"%s\"\n", pbuf);
goto close_client_socket;
}
if (S_ISREG(rstat.st_mode)) {
/*
* Send hard-coded response for files for now.
*/
const char *resp = "Files don't work yet\r\n.\r\n";
if (retrying_write(cfd, resp, strlen(resp)) == -1) {
fprintf(stderr, "Couldn't write to client socket\n");
goto close_client_socket;
}
} else if (S_ISDIR(rstat.st_mode)) {
/*
* Open the directory.
*
* The path is already null-terminated from the earlier call
* to stat().
*/
DIR *rdir;
do {
errno = 0;
rdir = opendir(pbuf);
@ -265,10 +282,13 @@ int main(int argc, char *argv[])
* Write a line for each entry in the directory to the client.
*/
struct dirent *ent;
struct stat rstat;
unsigned namelen;
while ((ent = readdir(rdir)) != NULL) {
if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0)
/*
* Skip . and .. entries.
*/
if (strcmp(ent->d_name, ".") == 0
|| strcmp(ent->d_name, "..") == 0)
continue;
/*
@ -291,7 +311,8 @@ int main(int argc, char *argv[])
*/
if (stat(pbuf, &rstat) == -1) {
fprintf(stderr,
"Failed to stat() path \"%s\", skipping entry\n", pbuf);
"Failed to stat() path \"%s\", skipping entry\n",
pbuf);
continue;
}
enum etype type;
@ -318,7 +339,8 @@ int main(int argc, char *argv[])
}
}
if (retrying_write(cfd, ".\r\n", 3) != 3) {
fprintf(stderr, "Error sending response terminator to client\n");
fprintf(stderr,
"Error sending response terminator to client\n");
goto close_client_socket;
}
@ -326,6 +348,13 @@ int main(int argc, char *argv[])
* Close the resource.
*/
closedir(rdir);
} else {
fprintf(stderr,
"Requested resource \"%s\" was not a directory or a "
"regular file\n",
pbuf);
goto close_client_socket;
}
close_client_socket:
close(cfd);