-
Notifications
You must be signed in to change notification settings - Fork 1
/
gx.c
143 lines (123 loc) · 2.28 KB
/
gx.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
#include <utf.h>
#include <fmt.h>
#include <regexp9.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include "config.h"
struct match {
char *re;
Reprog *prog;
};
#define X(s) {s, 0},
#define Y(s) {0, 0},
struct match matches[] = {
TABLE
{(char *)-1, (Reprog *)-1},
};
#undef X
#undef Y
#define X(s)
#define Y(s) s,
char *commands[] = {
TABLE
0,
};
#undef X
#undef Y
char buf[1024] = {0};
char *in;
Resub results[8];
char run[4096] = {0};
uint8_t VERBOSE = 0;
uint8_t MESSAGE = 0;
void fill() {
int devnull = open("/dev/null", O_RDONLY);
fread(buf, 1, 1024, stdin);
dup2(devnull, fileno(stdin));
dup2(devnull, fileno(stdout));
VERBOSE ? 0 : dup2(devnull, fileno(stderr));
close(devnull);
}
void init() {
for(struct match *i = matches; i->re != (char *)-1; i++) {
if(i->re == 0) {
continue;
}
i->prog = regcomp(i->re);
}
}
void doplumb() {
uint8_t found = 1;
uint16_t j = 0;
for(struct match *i = matches; i->re != (char *)-1; i++) {
if(!found && i->re == 0) {
found = 1;
j++;
continue;
}
if(!found) {
continue;
}
if(i->re == 0) {
regsub(commands[j], run, 4096, results, 8);
VERBOSE ? fprintf(stderr, "running: %s\n", run) : 0;
if(fork() == 0) {
execl("/bin/sh", "sh", "-c", run, NULL);
}
exit(0);
}
VERBOSE ? fprintf(stderr, "checking %s against %s for %s\n", in, i->re, commands[j]) : 0;
results->s.sp = 0;
results->e.ep = 0;
found = regexec(i->prog, in, results, 8) == 1;
if(found) {
VERBOSE ? fprintf(stderr, "found for %s\n", commands[j]) : 0;
found = results->s.sp == in && !*(results->e.ep);
}
}
}
uint8_t streq(char *s, char *t) {
while(*s && *s == *t) {
s++;
t++;
}
return *s == *t;
}
char *trim(char *s) {
while(*s && isspace(*s)) s++;
if(!*s) return s;
char *e = s;
while(*e) e++;
e--;
while(isspace(*e)) *(e--) = 0;
return s;
}
int main(int argc, char ** argv) {
for(int i = 1; i < argc; i++) {
if(streq(argv[i], "-h")) {
printf("Usage: gx [--verbose] [-m \"message\"]\n");
exit(0);
}
if(streq(argv[i], "--verbose")) {
VERBOSE=1;
}
if(streq(argv[i], "-m")) {
MESSAGE=1;
i++;
in = argv[i];
}
}
if(!MESSAGE) {
fill();
in = buf;
}
in = trim(in);
init();
doplumb();
exit(1);
}