/* * HOSTMAN * Is a hosts file manager for entries in /etc/hosts. * Downloads remote blocklists and manages * ads; tracking; blacklist; etc. entries. Must be run as root. * * USAGE * $ hostman -a Add a remote list * $ hostman -r Remove a list * $ hostman -m Move entry to position * $ hostman -u Update all or specific lists * $ hostman -e Edit a local list * $ hostman -h Show help * * INSTALL * $ make install -> /usr/bin/hostman * * AUTHOR * Written by 'hostman' contributors. */ #define _POSIX_C_SOURCE 200809L #include #include #include #include #include #include #include #include #include #include #include #define MAX_ENTRIES 100 #define MAX_LINE_LEN 256 #define MAX_HEADER_LEN 256 #define MAX_NAME_LEN 220 #define HFM_VERSION "0.1" #define HOSTS_FILE_PATH "/etc/hosts" typedef struct Host { char *name; struct Host *next; } Host; typedef struct Domain { char *url; Host *hosts; } Domain; /* globals */ int entrycount = 0; int updatecount[MAX_ENTRIES]; int domaincount[MAX_ENTRIES]; int selected[MAX_ENTRIES] = {0}; Domain domains[MAX_ENTRIES]; char *entries[MAX_ENTRIES]; char urlspath[256]; char countspath[256]; long remotesize[MAX_ENTRIES]; const char *hostpath = "/etc/hosts"; /* ---- config paths ---- */ const char * configpath(const char *filename, char *buffer, size_t size) { const char *home = NULL; if(geteuid() == 0) { const char *sudouser = getenv("SUDO_USER"); if(sudouser && strlen(sudouser) > 0) { struct passwd *pw = getpwnam(sudouser); if(pw && pw->pw_dir) { home = pw->pw_dir; } } } if(!home || strlen(home) == 0) { home = getenv("HOME"); } if(!home || strlen(home) == 0) { fprintf(stderr, "[FATAL] No HOME directory found!\n"); return NULL; } const char *xdgconfighome = getenv("XDG_CONFIG_HOME"); const char *xdgstatehome = getenv("XDG_STATE_HOME"); if(strcmp(filename, "counts") == 0) { if(xdgstatehome && strlen(xdgstatehome) > 0) { snprintf(buffer, size, "%s/hfc/%s", xdgstatehome, filename); } else { snprintf(buffer, size, "%s/.local/state/hfc/%s", home, filename); } } else { if(xdgconfighome && strlen(xdgconfighome) > 0) { snprintf(buffer, size, "%s/hfc/%s", xdgconfighome, filename); } else { snprintf(buffer, size, "%s/.config/hfc/%s", home, filename); } } return buffer; } /* ---- download (curl) ---- */ typedef struct MemoryStruct MemoryStruct; struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize; char *ptr; MemoryStruct *mem; realsize = size * nmemb; mem = (MemoryStruct *)userp; ptr = realloc(mem->memory, mem->size + realsize + 1); if(!ptr) return 0; mem->memory = ptr; memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = '\0'; return realsize; } char * fetchurl(const char *url, char *errmsg, size_t errsz) { CURL *curlh; CURLcode res; MemoryStruct chunk; chunk.memory = malloc(1); chunk.size = 0; curlh = curl_easy_init(); if(!curlh) { snprintf(errmsg, errsz, "Could not initialize CURL"); free(chunk.memory); return NULL; } char useragent[64]; snprintf(useragent, sizeof(useragent), "hfc/%s", HFM_VERSION); curl_easy_setopt(curlh, CURLOPT_URL, url); curl_easy_setopt(curlh, CURLOPT_WRITEFUNCTION, WriteMemoryCallback); curl_easy_setopt(curlh, CURLOPT_WRITEDATA, (void *)&chunk); curl_easy_setopt(curlh, CURLOPT_USERAGENT, useragent); curl_easy_setopt(curlh, CURLOPT_ERRORBUFFER, errmsg); curl_easy_setopt(curlh, CURLOPT_VERBOSE, 0L); res = curl_easy_perform(curlh); if(res != CURLE_OK) { free(chunk.memory); chunk.memory = NULL; } else { errmsg[0] = '\0'; } curl_easy_cleanup(curlh); return chunk.memory; } long remotelen(const char *url) { CURL *curl; CURLcode res; curl_off_t clength = -1; curl = curl_easy_init(); if(!curl) return -1; char useragent[64]; snprintf(useragent, sizeof(useragent), "hfc/%s", HFM_VERSION); curl_easy_setopt(curl, CURLOPT_USERAGENT, useragent); curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10L); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L); res = curl_easy_perform(curl); if(res == CURLE_OK) { if(curl_easy_getinfo(curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &clength) != CURLE_OK) clength = -1; } curl_easy_cleanup(curl); return (clength >= 0) ? (long)clength : -1; } int hashostentry(const char *content) { const char *line, *nextline; size_t len; char *cr; char buffer[512]; if(!content) return 0; line = content; while(*line) { nextline = strchr(line, '\n'); len = nextline ? (size_t)(nextline - line) : strlen(line); if(len >= sizeof(buffer)) len = sizeof(buffer) - 1; if(len > 0) { memcpy(buffer, line, len); buffer[len] = '\0'; cr = strchr(buffer, '\r'); if(cr) *cr = '\0'; while(*buffer == ' ' || *buffer == '\t') memmove(buffer, buffer + 1, strlen(buffer)); if(strncmp(buffer, "0.0.0.0 ", 8) == 0 || strncmp(buffer, "127.0.0.1 ", 10) == 0) return 1; } if(!nextline) break; line = nextline + 1; } return 0; } int savehosts(const char *content, const char *url, int number) { FILE *fp; const char *line, *nextline; size_t len; char *cr; char buffer[512], ip[16], domain[256]; if(!content) return 0; fp = fopen(HOSTS_FILE_PATH, "a"); if(!fp) return 0; fprintf(fp, "# %d. %s\n", number, url); line = content; while(*line) { nextline = strchr(line, '\n'); len = nextline ? (size_t)(nextline - line) : strlen(line); if(len >= sizeof(buffer)) len = sizeof(buffer) - 1; if(len > 0) { memcpy(buffer, line, len); buffer[len] = '\0'; cr = strchr(buffer, '\r'); if(cr) *cr = '\0'; while(*buffer == ' ' || *buffer == '\t') memmove(buffer, buffer + 1, strlen(buffer)); if(sscanf(buffer, "%15s %255s", ip, domain) == 2) { if(strcmp(ip, "127.0.0.1") == 0 || strcmp(ip, "0.0.0.0") == 0) fprintf(fp, "0.0.0.0 %s\n", domain); } } if(!nextline) break; line = nextline + 1; } fclose(fp); return 1; } /* ---- counting ---- */ int counthosts(const char *content) { const char *line, *next; size_t len; int count = 0; char buffer[512], *cr; if(!content) return 0; line = content; while(*line) { next = strchr(line, '\n'); len = next ? (size_t)(next - line) : strlen(line); if(len >= sizeof(buffer)) len = sizeof(buffer) - 1; memcpy(buffer, line, len); buffer[len] = '\0'; cr = strchr(buffer, '\r'); if(cr) *cr = '\0'; while(*buffer == ' ' || *buffer == '\t') memmove(buffer, buffer + 1, strlen(buffer)); if(strncmp(buffer, "0.0.0.0 ", 8) == 0 || strncmp(buffer, "127.0.0.1 ", 10) == 0) count++; if(!next) break; line = next + 1; } return count; } /* ---- core ---- */ static int islocal(const char *entry) { if(!entry) return 0; return !(strstr(entry, "http://") || strstr(entry, "https://")); } /* 01.00 */ static int checkwritehosts(bool silent) { if(access(hostpath, W_OK) != 0) { if(!silent) fprintf(stderr, "Error: Can't open hosts for writing: permission denied.\n"); return 0; } return 1; } /* 02.00 */ static void loadentries(void) { FILE *fp; char line[MAX_LINE_LEN]; char sectionhdr[64]; int sectionidx = 0; entrycount = 0; fp = fopen(hostpath, "r"); if(!fp) return; while(fgets(line, sizeof(line), fp) && entrycount < MAX_ENTRIES) { line[strcspn(line, "\n")] = '\0'; if(strncmp(line, "# ", 2) == 0) { snprintf(sectionhdr, sizeof(sectionhdr), "# %d.", sectionidx + 1); if(strncmp(line, sectionhdr, strlen(sectionhdr)) == 0) { char *namestart = line + strlen(sectionhdr) + 1; while(*namestart == ' ') namestart++; if(*namestart) { entries[entrycount] = strdup(namestart); domains[entrycount].url = strdup(namestart); domains[entrycount].hosts = NULL; entrycount++; } } sectionidx++; } } fclose(fp); } /* 10.00 */ static void savecounts(void) { FILE *f; int i; f = fopen(countspath, "w"); if(!f) return; for(i = 0; i < entrycount; i++) fprintf(f, "%d %ld\n", updatecount[i], remotesize[i]); fclose(f); } /* 16.00 */ static void saveentries(void) { FILE *fp = fopen(urlspath, "w"); if(!fp) return; for(int i = 0; i < entrycount; i++) { if(entries[i] && strlen(entries[i]) > 0) { fprintf(fp, "%s\n", entries[i]); } } fclose(fp); } /* 15.00 */ static int countsection(int sectionidx) { FILE *fp; char line[512]; char sectionhdr[256]; int cursection = -1; int count = 0; fp = fopen(hostpath, "r"); if(!fp) return 0; snprintf(sectionhdr, sizeof(sectionhdr), "# %d.", sectionidx + 1); while(fgets(line, sizeof(line), fp)) { line[strcspn(line, "\n")] = '\0'; if(strncmp(line, "# ", 2) == 0) { if(strncmp(line, sectionhdr, strlen(sectionhdr)) == 0) { cursection = sectionidx; count = 0; } else if(cursection == sectionidx) { break; } else { cursection = -1; } } else if(cursection == sectionidx) { if(strlen(line) > 0) { char *first = line; while(*first == ' ' || *first == '\t') first++; if(strlen(first) > 0 && !(*first == '#')) { count++; } } } } fclose(fp); return count; } /* 11.00 */ static void loadcounts(void) { for(int i = 0; i < entrycount; i++) { domaincount[i] = countsection(i); if(islocal(entries[i])) { updatecount[i] = 0; remotesize[i] = 0; } else { updatecount[i] = domaincount[i]; remotesize[i] = 0; } } } /* 14.00 */ static void updatedomain(int index) { long newsize; char errmsg[256]; char *content; if(index < 0 || index >= entrycount || !entries[index]) { updatecount[index] = 0; return; } newsize = remotelen(entries[index]); if(newsize <= 0) return; if(newsize != remotesize[index]) { content = fetchurl(entries[index], errmsg, sizeof(errmsg)); if(!content) return; int count = counthosts(content); updatecount[index] = count; domaincount[index] = count; remotesize[index] = newsize; free(content); savecounts(); } } /* 03.00 */ static void reorderentry(int from, int to) { if(from == to || from < 0 || to < 0 || from >= entrycount || to >= entrycount) return; if(!checkwritehosts(true)) { return; } /* read hosts file into blocks */ FILE *fp = fopen(hostpath, "r"); if(!fp) return; char **blocks = calloc(entrycount, sizeof(char *)); size_t *blocksizes = calloc(entrycount, sizeof(size_t)); int current = -1; size_t bufsize = 0; char *blockbuf = NULL; char line[MAX_LINE_LEN]; while(fgets(line, sizeof(line), fp)) { if(strncmp(line, "# ", 2) == 0) { if(current >= 0) { blocks[current] = blockbuf; blocksizes[current] = bufsize; } current++; blockbuf = NULL; bufsize = 0; } size_t len = strlen(line); blockbuf = realloc(blockbuf, bufsize + len + 1); memcpy(blockbuf + bufsize, line, len); bufsize += len; blockbuf[bufsize] = '\0'; } if(current >= 0) { blocks[current] = blockbuf; blocksizes[current] = bufsize; } fclose(fp); /* back up metadata */ char *entrytmp = entries[from]; int domaincnttmp = domaincount[from]; int updatetmp = updatecount[from]; long sizetmp = remotesize[from]; int seltmp = selected[from]; Domain domainval = domains[from]; char *blocktmp = blocks[from]; size_t blocksztmp = blocksizes[from]; /* move arrays */ if(from < to) { for(int i = from; i < to; i++) { entries[i] = entries[i + 1]; domaincount[i] = domaincount[i + 1]; updatecount[i] = updatecount[i + 1]; remotesize[i] = remotesize[i + 1]; selected[i] = selected[i + 1]; domains[i] = domains[i + 1]; blocks[i] = blocks[i + 1]; blocksizes[i] = blocksizes[i + 1]; } } else { for(int i = from; i > to; i--) { entries[i] = entries[i - 1]; domaincount[i] = domaincount[i - 1]; updatecount[i] = updatecount[i - 1]; remotesize[i] = remotesize[i - 1]; selected[i] = selected[i - 1]; domains[i] = domains[i - 1]; blocks[i] = blocks[i - 1]; blocksizes[i] = blocksizes[i - 1]; } } /* use secured position */ entries[to] = entrytmp; domaincount[to] = domaincnttmp; updatecount[to] = updatetmp; remotesize[to] = sizetmp; selected[to] = seltmp; domains[to] = domainval; blocks[to] = blocktmp; blocksizes[to] = blocksztmp; /* rewrite hosts file with new numbers */ FILE *out = fopen(hostpath, "w"); if(out) { for(int i = 0; i < entrycount; i++) { fprintf(out, "# %d. %s\n", i + 1, entries[i]); char *blockcontent = strstr(blocks[i], "\n"); if(blockcontent) { fputs(blockcontent + 1, out); } } fclose(out); } for(int i = 0; i < entrycount; i++) { free(blocks[i]); } free(blocks); free(blocksizes); saveentries(); savecounts(); } /* 18.01 */ static void listentries(void) { int termwidth = 80; struct winsize w; if(ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) == 0 && w.ws_col > 0) { termwidth = w.ws_col; } int pad = 1; int widid = 3; int widentries = 7; int widlist = termwidth - pad - 1 - widid - 1 - widentries - 1 - pad; printf("%*s %-*s %-*s %*s\n", pad, " ", widid, "ID", widlist, "LIST", widentries, "ENTRYS"); printf("%*s %-*s %-*s %*s\n", pad, " ", widid, "---", widlist, "-----", widentries, "------"); for(int i = 0; i < entrycount; i++) { const char *name = entries[i] ? entries[i] : ""; int local = domaincount[i]; int remote = updatecount[i]; int needupdate = !islocal(name) && local != remote && local > 0 && remote > 0; char linesbuf[32]; snprintf(linesbuf, sizeof(linesbuf), "%d%s", local, needupdate ? "*" : ""); if((int)strlen(name) > widlist - 3) { printf("%*s %-*d %-.*s... %*s %s\n", pad, " ", widid, i + 1, widlist - 3, name, widentries, linesbuf, " "); } else { printf("%*s %-*d %-*s %*s %s\n", pad, " ", widid, i + 1, widlist, name, widentries, linesbuf, " "); } } } /* 27.00 */ static void rebuildheaders(void) { FILE *in = fopen(hostpath, "r"); FILE *out = fopen("/tmp/hosts_reindexed", "w"); char line[MAX_LINE_LEN]; int entryidx = 0; int inblock = 0; if(!in || !out) { if(in) fclose(in); if(out) fclose(out); return; } while(fgets(line, sizeof(line), in)) { if(strncmp(line, "# ", 2) == 0) { if(entryidx < entrycount) { fprintf(out, "# %d. %s\n", entryidx + 1, entries[entryidx]); inblock = 1; entryidx++; } else { inblock = 0; } continue; } if(inblock || line[0] == '\n') { fputs(line, out); } } fclose(in); fclose(out); rename("/tmp/hosts_reindexed", hostpath); } /* 25.00 */ static void removeentry(int index) { if(index < 0 || index >= entrycount || !entries[index]) return; if(!checkwritehosts(true)) return; const char *targeturl = entries[index]; FILE *in = fopen(hostpath, "r"); FILE *out = fopen("/tmp/hosts_temp", "w"); if(!in || !out) { if(in) fclose(in); if(out) fclose(out); return; } char line[MAX_LINE_LEN]; int skipblock = 0; while(fgets(line, sizeof(line), in)) { if(strncmp(line, "# ", 2) == 0) { /* is that a block with the url? */ if(strstr(line, targeturl)) { skipblock = 1; continue; } else { skipblock = 0; } } if(!skipblock) fputs(line, out); } fclose(in); fclose(out); rename("/tmp/hosts_temp", hostpath); /* move array entries */ free(entries[index]); for(int i = index; i < entrycount - 1; i++) { entries[i] = entries[i + 1]; updatecount[i] = updatecount[i + 1]; domaincount[i] = domaincount[i + 1]; remotesize[i] = remotesize[i + 1]; selected[i] = selected[i + 1]; } entries[entrycount - 1] = NULL; updatecount[entrycount - 1] = 0; domaincount[entrycount - 1] = 0; remotesize[entrycount - 1] = 0; selected[entrycount - 1] = 0; entrycount--; saveentries(); savecounts(); rebuildheaders(); } /* 32.00 */ static int netup(void) { struct addrinfo hints = {0}, *res = NULL; int result; hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; /* try resolving google.com */ result = getaddrinfo("google.com", NULL, &hints, &res); if(res) freeaddrinfo(res); return result == 0; } /* 33.00 */ int main(int argc, char *argv[]) { const char *editor = getenv("EDITOR"); configpath("counts", countspath, sizeof(countspath)); configpath("urls", urlspath, sizeof(urlspath)); setlocale(LC_ALL, ""); curl_global_init(CURL_GLOBAL_DEFAULT); loadentries(); loadcounts(); if(argc == 1 || (argc == 2 && (strcmp(argv[1], "-l") == 0 || strcmp(argv[1], "--list") == 0))) { listentries(); return 0; } if(argc == 2 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0)) { printf("Usage: hfm [OPTION]\n\n"); printf("Options:\n"); printf(" -h, --help Show usage information.\n"); printf(" -l, --list List all entries (default).\n"); printf(" -a, --add Add a remote URL or custom list.\n"); printf(" -r, --remove Remove a remote URL or custom list.\n"); printf(" -e, --edit Edit a local entry section with $EDITOR\n"); printf(" -U, --update_all Update all remote sources.\n"); printf(" -m, --move Move entry to position .\n"); printf("\nReport bugs via mail or xmpp to hi@marlonivo.com.\n"); return 0; } if(argc == 2 && ( strcmp(argv[1], "-a") == 0 || strcmp(argv[1], "--add") == 0 || strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--remove") == 0 || strcmp(argv[1], "-e") == 0 || strcmp(argv[1], "--edit") == 0 )) { fprintf(stderr, "hosts file manager\n" "usage: hfm '%s' \n" "\n" "Use -h to get help or, even better, run 'man hfm'\n", argv[1]); return 1; } if(argc == 3 && (strcmp(argv[1], "-a") == 0 || strcmp(argv[1], "--add") == 0)) { char *url = argv[2]; if(!netup()) { fprintf(stderr, "Error: No network connection.\n"); return 1; } char errmsg[CURL_ERROR_SIZE] = {0}; char *content = fetchurl(url, errmsg, sizeof(errmsg)); if(!content) { fprintf(stderr, "Download failed: %s\n", errmsg); return 1; } if(!hashostentry(content)) { fprintf(stderr, "Error: No valid hosts entries found.\n"); free(content); return 1; } if(entrycount >= MAX_ENTRIES) { fprintf(stderr, "Error: Maximum number of entries reached.\n"); free(content); return 1; } if(!checkwritehosts(true)) { free(content); return 1; } entries[entrycount] = strdup(url); entrycount++; saveentries(); if(!savehosts(content, url, entrycount)) { fprintf(stderr, "Error: Could not write to hosts.\n"); free(content); return 1; } int localcnt = countsection(entrycount - 1); domaincount[entrycount - 1] = localcnt; updatedomain(entrycount - 1); savecounts(); free(content); printf("Entry added successfully: %s\n", url); return 0; } if(argc == 3 && (strcmp(argv[1], "-r") == 0 || strcmp(argv[1], "--remove") == 0)) { char *url = argv[2]; int found = -1; for(int i = 0; i < entrycount; i++) { if(strcmp(entries[i], url) == 0) { found = i; break; } } if(found == -1) { fprintf(stderr, "Entry not found: %s\n", url); return 1; } if(!checkwritehosts(true)) { return 1; } removeentry(found); printf("Entry removed successfully: %s\n", url); return 0; } if(argc == 2 && (strcmp(argv[1], "-U") == 0 || strcmp(argv[1], "--update_all") == 0)) { if(!netup()) { fprintf(stderr, "Error: No network connection.\n"); return 1; } int total = 0; for(int i = 0; i < entrycount; i++) { if(!islocal(entries[i])) total++; } int current = 0; for(int i = 0; i < entrycount; i++) { if(islocal(entries[i])) continue; current++; printf("(%d/%d) updating %s\n", current, total, entries[i]); fflush(stdout); updatedomain(i); } savecounts(); printf("All sources updated.\n"); return 0; } if(argc == 3 && (strcmp(argv[1], "-e") == 0 || strcmp(argv[1], "--edit") == 0)) { char *url = argv[2]; int found = -1; for(int i = 0; i < entrycount; i++) { if(strcmp(entries[i], url) == 0) { found = i; break; } } if(found == -1) { fprintf(stderr, "Entry not found: %s\n", url); return 1; } FILE *fp = fopen(hostpath, "r"); if(!fp) { fprintf(stderr, "Error: Could not open hosts\n"); return 1; } char line[1024]; int lineno = 0; int targetline = -1; char searchtag[256]; snprintf(searchtag, sizeof(searchtag), "# %d. %s", found + 1, entries[found]); while(fgets(line, sizeof(line), fp)) { lineno++; if(strstr(line, searchtag)) { targetline = lineno; break; } } fclose(fp); if(targetline == -1) { fprintf(stderr, "Error: Entry header not found in hosts\n"); return 1; } if(!checkwritehosts(true)) { return 1; } char cmd[1024]; snprintf(cmd, sizeof(cmd), "%s +%d %s", editor, targetline, hostpath); int ret = system(cmd); return ret; } if(argc == 4 && (strcmp(argv[1], "-m") == 0 || strcmp(argv[1], "--move") == 0)) { char *fromarg = argv[2]; char *toarg = argv[3]; int from = atoi(fromarg) - 1; int to = atoi(toarg) - 1; if(from < 0 || from >= entrycount) { fprintf(stderr, "Error: Invalid entry ID '%s' (must be 1-%d).\n", fromarg, entrycount); return 1; } if(to < 0 || to >= entrycount) { fprintf(stderr, "Error: Invalid position '%s' (must be 1-%d).\n", toarg, entrycount); return 1; } if(from == to) { return 0; } reorderentry(from, to); printf("Entry moved from position %d to %d.\n", from + 1, to + 1); return 0; } fprintf(stderr, "Unknown option. Use -h for help.\n"); return 1; }