-
Notifications
You must be signed in to change notification settings - Fork 13
/
forge_ip_server.c
85 lines (76 loc) · 2.03 KB
/
forge_ip_server.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
#include <ev.h>
#include <assert.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include "utils.h"
#define SERVER_PORT 7899
struct forge_ip_server_ctx {
ev_io io;
int fd;
uint8_t buf[128];
};
static void forge_ip_read_cb(EV_P_ ev_io *w, int revents)
{
struct forge_ip_server_ctx *s = (typeof(s))w;
ssize_t len;
struct sockaddr_in from;
int fromlen = sizeof(from);
struct sockaddr_in real_source;
len = recvfrom(s->fd, s->buf, 127, 0,
(struct sockaddr *)&from, (socklen_t *)&fromlen);
if (len <= 0)
return;
s->buf[len] = '\0';
memset(&real_source, 0, sizeof(real_source));
real_source.sin_family = AF_INET;
real_source.sin_port = (s->buf[0] << 8) + s->buf[1];
if (inet_pton(AF_INET, (char *)&s->buf[2],
&real_source.sin_addr) <= 0) {
fprintf(stderr, "inet_pton() fail: %s\n", strerror(errno));
fprintf(stderr, "from: %s\n", inet_ntoa(from.sin_addr));
fprintf(stderr, "buf: %s\n", s->buf);
return;
}
fprintf(stderr, "========================================\n"
"real source port: %d ip: %s\n",
real_source.sin_port, &s->buf[2]);
len = sprintf((char *)s->buf, "forged source port: %d ip: %s\n",
ntohs(from.sin_port), inet_ntoa(from.sin_addr));
fprintf(stderr, "%s========================================\n\n",
s->buf);
sendto(s->fd, s->buf, len, 0,
(const struct sockaddr *)&real_source, sizeof(real_source));
}
int main(int argc, char **argv)
{
struct forge_ip_server_ctx s;
struct ev_loop *loop = EV_DEFAULT;
int opt;
FILE *logfp;
while ((opt = getopt(argc, argv, "b")) != -1) {
switch (opt) {
case 'b':
logfp = fopen("forge_ip_server.log", "a");
if (logfp == NULL) {
perror("fopen");
exit(1);
}
dup2(fileno(logfp), STDERR_FILENO);
fclose(logfp);
daemon(0, 1);
break;
default:
fprintf(stderr, "usage: %s [-b]\n", argv[0]);
exit(1);
}
}
s.fd = init_server_UDP_fd(SERVER_PORT, 0);
assert(s.fd > 0);
ev_io_init(&s.io, forge_ip_read_cb, s.fd, EV_READ);
ev_io_start(loop, &s.io);
ev_run(loop, 0);
return 0;
}