commit 7d38e2bf78859a4df9223f76542b6bb25762277e Author: jaketothepast Date: Sat Feb 23 13:08:32 2019 -0500 First commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fb87d32 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +hb \ No newline at end of file diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..777849c --- /dev/null +++ b/Makefile @@ -0,0 +1,8 @@ +CC=gcc +CFLAGS=-I. + +hello: main.c + $(CC) -o hb main.c + +install: hello + install -m 744 hb /usr/local/bin \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..2795784 --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# HB + +The Host Blocker command. + +This is a system utility written in C that allows one to quickly black hole hosts in the /etc/hosts file, keeping one from resolving any DNS for those hosts and permanently blocking them on the system. + +# Motivations + +I would like to get better with C, and will be using C much more in the near future. In addition, I have issues with browsing to sites that hurt my productivity and am always on the command line. + +# TODO + +1. Get delete working for my /etc/hosts editor. +2. Daemonize this program to be started up by systemd. + - As part of daemonization, remember and remove added hosts on teardown. +3. Log dns requests that look at the hosts file -- To see how many go where \ No newline at end of file diff --git a/main.c b/main.c new file mode 100644 index 0000000..07df040 --- /dev/null +++ b/main.c @@ -0,0 +1,65 @@ +#include +#include +#include +#include +#include + +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); +} + +/** + * Entrypoint. + */ +int main(int argc, char **argv) +{ + FILE *hostsFile = NULL; + + if (getuid() != 0) + { + 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], "delete") == 0) + { + fprintf(stdout, "Soon to be implemented!\n"); + } + } + + if (hostsFile != NULL) + fclose(hostsFile); +} \ No newline at end of file