-
Notifications
You must be signed in to change notification settings - Fork 11
/
hostsblock.c
146 lines (133 loc) · 2.32 KB
/
hostsblock.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#include <ctype.h>
#include <stdio.h>
#include <string.h>
/* Length limit for domain names is 253 characters */
#define MAX_DOMAIN_LENGTH 254
#define MAX_DOMAIN_RULE_LENGTH MAX_DOMAIN_LENGTH + 3
enum state {
INIT,
FIRST_BAR,
SECOND_BAR,
DOMAIN_ALNUM,
DOMAIN_HYPHEN,
DOMAIN_PERIOD,
DELIM
};
int get_domain(char *rule, char *domain)
{
enum state state = INIT;
int i = 0;
do {
switch (state) {
case INIT:
if (*rule == '|') {
state = FIRST_BAR;
} else {
return 1;
}
break;
case FIRST_BAR:
if (*rule == '|') {
state = SECOND_BAR;
} else {
return 1;
}
break;
case SECOND_BAR:
if (isalnum(*rule)) {
domain[i] = *rule;
++i;
state = DOMAIN_ALNUM;
} else {
return 1;
}
break;
case DOMAIN_ALNUM:
if (isalnum(*rule)) {
domain[i] = *rule;
i++;
state = DOMAIN_ALNUM;
break;
}
switch (*rule) {
case '-':
domain[i] = *rule;
i++;
state = DOMAIN_HYPHEN;
break;
case '.':
domain[i] = *rule;
i++;
state = DOMAIN_PERIOD;
break;
case '|':
case '^':
state = DELIM;
break;
default:
return 1;
}
break;
case DOMAIN_HYPHEN:
if (isalnum(*rule)) {
domain[i] = *rule;
++i;
state = DOMAIN_ALNUM;
break;
}
if (*rule == '-') {
domain[i] = *rule;
i++;
state = DOMAIN_HYPHEN;
} else {
return 1;
}
break;
case DOMAIN_PERIOD:
if (isalnum(*rule)) {
domain[i] = *rule;
i++;
state = DOMAIN_ALNUM;
} else {
return 1;
}
break;
case DELIM:
if (*rule == '\n') {
domain[i] = '\0';
return 0;
} else {
return 1;
}
}
} while (++rule && i < MAX_DOMAIN_LENGTH);
return 1;
}
int main(int argc, char **argv)
{
FILE *list;
char rule[MAX_DOMAIN_RULE_LENGTH];
char domain[MAX_DOMAIN_LENGTH] = { 0 };
if (argc > 2) {
fputs("usage: hostsblock file\n", stderr);
return 1;
}
if (argc < 2 || !strncmp(argv[1], "-", 2)) list = stdin;
else list = fopen(argv[1], "r");
if (list == NULL) {
perror("error opening filter list");
return 1;
}
while (1) {
char *c = fgets(rule, MAX_DOMAIN_RULE_LENGTH, list);
if (c == NULL || feof(list) || ferror(list)) break;
if (!get_domain(rule, domain)) {
printf("0\t%s\n", domain);
}
}
if (ferror(list)) {
perror("error reading filter list");
return 1;
}
return 0;
}