My indexes function recognizes some file's names (not all) and then continues to throw out garbarge data '\000' as file names. Here is the code I wrote for indexes:
char* indexes(const char* path)
{
// ensure path is readable and executable
if (access(path, R_OK | X_OK) == -1)
{
error(403);
return NULL;
}
// open directory
DIR* dir = malloc(sizeof(int));
dir = opendir(path);
if (dir == NULL)
{
return NULL;
}
bool php_file = false;
bool html_file = false;
// iterate over directory entries
struct dirent *dp = malloc (sizeof(int));
if (dp == NULL)
{
return NULL;
}
// declares variable count
int count = 0;
// read the next file in directory
while ((dir) && count = 0)
{
if ((dp = readdir(dir)) != NULL)
{
char *name = malloc (15);
name = dp->d_name;
if (strcmp(name, "index.php") == 0)
{
php_file = true;
closedir(dir);
count++;
}
else if (strcmp(name, "index.html") == 0)
{
html_file = true;
closedir(dir);
count++;
}
free(name);
}
else
{
closedir(dir);
count++;
}
}
if (php_file)
{
char php = malloc (11);
if (php == NULL)
{
return NULL;
}
php = "/index.php";
return strcat((char)path, php);
free (php);
}
else if (html_file)
{
char html = malloc (12);
if (html == NULL)
{
return NULL;
}
html = "/index.html";
return strcat((char) path, html);
free (html);
}
else
{
return NULL;
}
free (dir);
free (dp);
}
EDIT #1
I remade the function in an attempt to get it simpler, following a helpful comment but I am getting a segfault after entering into _if (access(path1), R_OK | X_OK) == -1)_ and after free(php) (which by the way is wrong because there is no index.php file in my public directory). Any clue would be very much appreciated!
char* indexes(const char* path)
{
// ensure path is readable and executable
if (access(path, R_OK | X_OK) == -1)
{
error(403);
return NULL;
}
// declare a string for php and html
char *php = malloc(11);
if (php == NULL)
{
return NULL;
}
php = "index.php";
char html = malloc(12);
if (html == NULL)
{
return NULL;
}
html = "index.html";
char path1 = malloc(sizeof(path) + 11);
if (path1 == NULL)
{
return NULL;
}
path1 = strcat((char*)path, php);
char* path2 = malloc(sizeof(path) + 12);
if (path2 == NULL)
{
return NULL;
}
path2 = strcat((char*)path, html);
// check if index.html or index.php exists and returns else returns NULL
if (access(path1, R_OK | X_OK) == -1)
{
free (php);
free (html);
free (path2);
return path1;
}
else if (access(path2, R_OK | X_OK) == -1)
{
free (php);
free (html);
free (path1);
return (path2);
}
else
{
free(php);
free(html);
free(path1);
free(path2);
return NULL;
}
}