From 1601d86349c03678d08e66c9c53f70210369104a Mon Sep 17 00:00:00 2001 From: Ben Kurtovic Date: Wed, 18 Mar 2015 13:43:11 -0500 Subject: [PATCH] Guard against reading directories as ROM files. --- crater.c | 4 ++-- src/rom.c | 27 ++++++++++++++++++++++----- src/rom.h | 4 ++-- 3 files changed, 26 insertions(+), 9 deletions(-) diff --git a/crater.c b/crater.c index b262d28..c3787f1 100644 --- a/crater.c +++ b/crater.c @@ -150,7 +150,7 @@ int main(int argc, char *argv[]) if (rom_path[0] == '\0') FATAL("no image given") - if (!(rom = open_rom(rom_path))) { + if (!(rom = rom_open(rom_path))) { if (errno == ENOMEM) OUT_OF_MEMORY() else @@ -162,6 +162,6 @@ int main(int argc, char *argv[]) // TODO: start from here - close_rom(rom); + rom_close(rom); return 0; } diff --git a/src/rom.c b/src/rom.c index 0cd5dd3..d9f0d7f 100644 --- a/src/rom.c +++ b/src/rom.c @@ -1,34 +1,51 @@ /* Copyright (C) 2014-2015 Ben Kurtovic Released under the terms of the MIT License. See LICENSE for details. */ +#include #include #include #include +#include #include "rom.h" /* Create and return a ROM object located at the given path. Return NULL if there was an error; errno will be set appropriately. */ -rom_type* open_rom(const char *path) +rom_type* rom_open(const char *path) { rom_type *rom; FILE* fp; + struct stat s; if (!(fp = fopen(path, "r"))) return NULL; - if (!(rom = malloc(sizeof(rom_type)))) + + if (fstat(fileno(fp), &s)) { + fclose(fp); + return NULL; + } + if (!(s.st_mode & S_IFREG)) { + if (s.st_mode & S_IFDIR) + errno = EISDIR; + fclose(fp); + return NULL; + } + + if (!(rom = malloc(sizeof(rom_type)))) { + fclose(fp); return NULL; + } rom->name = malloc(sizeof(char) * (strlen(path) + 1)); strcpy(rom->name, path); - // load data from file into a buffer + // TODO: load data from file into a buffer fclose(fp); return rom; } -/* Free a ROM object previously created with open_rom(). */ -void close_rom(rom_type *rom) +/* Free a ROM object previously created with rom_open(). */ +void rom_close(rom_type *rom) { free(rom); } diff --git a/src/rom.h b/src/rom.h index b022ac0..7923d14 100644 --- a/src/rom.h +++ b/src/rom.h @@ -12,5 +12,5 @@ typedef struct { /* Functions */ -rom_type* open_rom(const char*); -void close_rom(rom_type*); +rom_type* rom_open(const char*); +void rom_close(rom_type*);