dont buffer output
[roguegraph.git] / rg.c
1 // Copyright (C) Jann Horn (2013)
2 // You can redistribute this code under the terms of the GPLv2 or GPLv3.
3 // THIS PROGRAM IS FOR EDUCATIONAL PURPOSES ONLY!
4 // I AM NOT RESPONSIBLE FOR WHAT YOU DO WITH THIS PROGRAM OR THE IMPACT THIS
5 // PROGRAM MIGHT HAVE ON YOUR SYSTEMS! YOU HAVE BEEN WARNED!
6
7 #include <stdlib.h>
8 #include <stdio.h>
9 #include <time.h>
10 #include <unistd.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <fcntl.h>
15
16 char *target;
17
18 void run(void) {
19   int pipefds[2];
20   if (pipe(pipefds)) perror("can't create pipe"), exit(1);
21   int parent_fd = pipefds[0];
22   int child_fd = pipefds[1];
23
24   pid_t pid = fork();
25   if (pid < 0) perror("can't fork"), exit(1);
26
27   if (pid == 0) {
28     int nullfd = open("/dev/null", O_RDWR);
29     dup2(nullfd, 0);
30     dup2(nullfd, 2);
31     close(nullfd);
32     close(parent_fd);
33     dup2(child_fd, 1);
34     close(child_fd);
35     execlp("hping3", "hping3", "-c", "20", "-p", "80", "-i", "u100000", "--syn", target, NULL);
36     perror("can't exec"), exit(1);
37   }
38   close(child_fd);
39
40   char indata[4096];
41   int indata_written = 0;
42   int rres;
43   while ((rres=read(parent_fd, indata+indata_written, 4095-indata_written)) > 0) {
44     indata_written += rres;
45     if (indata_written >= 4095) fputs("too much information", stderr), exit(1);
46   }
47   if (rres < 0) perror("failure reading from child"), exit(1);
48   indata[indata_written] = '\0';
49   close(parent_fd);
50
51   char *s = indata;
52   int last_id = -1;
53   int sum = 0;
54   while ((s=strstr(s, " id=")) != NULL) {
55     s += 4;
56     int id = atoi(s);
57     if (last_id != -1) {
58       int diff = id - last_id;
59       if (diff < 0) diff += (256*256);
60       sum += diff;
61     }
62     last_id = id;
63   }
64
65   printf("%i %i\n", (int)time(NULL), sum);
66 }
67
68 int main(int argc, char **argv) {
69   if (argc != 2) fputs("bad invocation\n", stderr), exit(1);
70   target = argv[1];
71
72   setbuf(stdout, NULL);
73
74   while (1) {
75     run();
76     sleep(300);
77   }
78 }