hb/main.c

133 lines
2.5 KiB
C
Raw Normal View History

2019-04-18 01:06:55 +00:00
#define _GNU_SOURCE
#include <string.h>
2019-02-23 18:08:32 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
2019-02-24 00:41:47 +00:00
#include <sys/wait.h>
2019-02-23 18:08:32 +00:00
/**
* TODO - daemonize, add in reading of config file,
* block sites within a certain time limit.
*/
2019-02-23 18:08:32 +00:00
const char *blockString = "0.0.0.0 ";
FILE *fopenHostsFile(int mode)
{
switch(mode)
{
case 0:
return fopen("/etc/hosts", "r");
case 1:
return fopen("/etc/hosts", "a");
}
}
/**
* Block a hosts using the hostsFile in FILE
*/
void blockHost(FILE *hostsFile, char *host)
{
// Buffer to hold our block rule.
char blockRule[256];
// Copy the blockstring and host to the blockrule.
strcpy(blockRule, blockString);
strcat(blockRule, host);
strcat(blockRule, "\n");
// Add a null terminator..
blockRule[strlen(blockRule)] = 0;
fputs(blockRule, hostsFile);
}
2019-02-24 00:33:54 +00:00
void usage()
{
fprintf(stdout, "Usage: ");
fprintf(stdout, "hb [add] <sitename>\n");
}
2019-02-24 00:41:47 +00:00
void showHosts()
{
pid_t child = fork();
int rc = 0;
char *const parmList[] = {"/bin/cat", "/etc/hosts", NULL};
2019-02-24 00:41:47 +00:00
if (child == 0)
{
execv("/bin/cat", parmList);
2019-02-24 00:41:47 +00:00
}
else
{
rc = wait(NULL);
}
}
void readToHost(char *host, FILE *hostsFile)
{
char buf[256];
2019-04-18 01:06:55 +00:00
char *ptr, *f;
2019-04-18 01:06:55 +00:00
while ((ptr = fgets(buf, 256, hostsFile)) != NULL)
{
2019-04-18 01:06:55 +00:00
/**
printf("%s\n", ptr);
printf("%s\n", host);
**/
f = strcasestr(host, ptr);
if (f != NULL) {
printf("FOUND IT\n");
2019-04-18 01:06:55 +00:00
break;
}
}
}
2019-02-23 18:08:32 +00:00
/**
* Entrypoint.
*/
int main(int argc, char **argv)
{
2019-04-18 01:06:55 +00:00
FILE *hostsFile = fopenHostsFile(0);
2019-04-18 01:06:55 +00:00
readToHost("reddit.com", hostsFile);
2019-04-18 01:06:55 +00:00
fclose(hostsFile);
hostsFile = NULL;
if (getuid() != 0)
2019-02-23 18:08:32 +00:00
{
fprintf(stderr, "hb: Must run as root using sudo!\n");
}
for (int i = 0; i < argc; i++)
{
if (strcmp(argv[i], "add") == 0)
{
hostsFile = fopenHostsFile(1);
blockHost(hostsFile, argv[i+1]);
}
else if (strcmp(argv[i], "edit") == 0)
{
readToHost(argv[i+1], hostsFile);
}
2019-02-23 18:08:32 +00:00
else if (strcmp(argv[i], "delete") == 0)
{
fprintf(stdout, "Soon to be implemented!\n");
}
2019-02-24 00:33:54 +00:00
else if (strcmp(argv[i], "-h") == 0)
{
usage();
exit(0);
}
else if (strcmp(argv[i], "show") == 0)
2019-02-24 00:41:47 +00:00
{
showHosts();
}
2019-02-23 18:08:32 +00:00
}
if (hostsFile != NULL)
fclose(hostsFile);
}