mirror of
https://github.com/bol-van/zapret.git
synced 2025-05-24 22:32:58 +03:00
first commit
This commit is contained in:
14
tpws/Makefile
Normal file
14
tpws/Makefile
Normal file
@@ -0,0 +1,14 @@
|
||||
CC = gcc
|
||||
CFLAGS =
|
||||
LIBS =
|
||||
SRC_FILES = *.c
|
||||
|
||||
all: tpws
|
||||
|
||||
tpws: $(SRC_FILES)
|
||||
$(CC) $(CFLAGS) -o $@ $^ $(LIBS)
|
||||
|
||||
clean:
|
||||
rm -f tpws *.o
|
||||
|
||||
.PHONY: clean
|
597
tpws/tpws.c
Normal file
597
tpws/tpws.c
Normal file
@@ -0,0 +1,597 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/ip.h>
|
||||
#include <netdb.h>
|
||||
#include <unistd.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <sys/select.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/queue.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <signal.h>
|
||||
#include <errno.h>
|
||||
#include <stdbool.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <getopt.h>
|
||||
#include <pwd.h>
|
||||
|
||||
#include "tpws.h"
|
||||
#include "tpws_conn.h"
|
||||
|
||||
enum splithttpreq {split_none=0,split_method,split_host};
|
||||
|
||||
struct params_s
|
||||
{
|
||||
char bindaddr[64];
|
||||
uid_t uid;
|
||||
gid_t gid;
|
||||
uint16_t port;
|
||||
bool daemon;
|
||||
bool hostcase,methodcase;
|
||||
enum splithttpreq split_http_req;
|
||||
int maxconn;
|
||||
};
|
||||
|
||||
struct params_s params;
|
||||
|
||||
unsigned char *find_bin(void *data,ssize_t len,const void *blk,ssize_t blk_len)
|
||||
{
|
||||
while (len>=blk_len)
|
||||
{
|
||||
if (!memcmp(data,blk,blk_len))
|
||||
return data;
|
||||
data=(char*)data+1;
|
||||
len--;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
ssize_t send_with_flush(int sockfd, const void *buf, size_t len, int flags)
|
||||
{
|
||||
int flag,err;
|
||||
ssize_t wr;
|
||||
|
||||
flag=1;
|
||||
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
|
||||
wr=send(sockfd,buf,len,flags);
|
||||
err=errno;
|
||||
flag=0;
|
||||
setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *) &flag, sizeof(int));
|
||||
errno=err;
|
||||
return wr;
|
||||
}
|
||||
|
||||
void close_tcp_conn(tproxy_conn_t *conn, struct tailhead *conn_list,
|
||||
struct tailhead *close_list){
|
||||
conn->state = CONN_CLOSED;
|
||||
TAILQ_REMOVE(conn_list, conn, conn_ptrs);
|
||||
TAILQ_INSERT_TAIL(close_list, conn, conn_ptrs);
|
||||
}
|
||||
|
||||
static const char *http_split_methods[]={"GET /","POST /","HEAD /","OPTIONS /",NULL};
|
||||
static const char *http_split_host[]={"\r\nHost: ",NULL};
|
||||
|
||||
bool handle_epollin(tproxy_conn_t *conn,int *data_transferred){
|
||||
int numbytes;
|
||||
int fd_in, fd_out;
|
||||
bool bOutgoing;
|
||||
ssize_t rd=0,wr=0;
|
||||
|
||||
//Easy way to determin which socket is ready for reading
|
||||
//TODO: Optimize. This one allows me quick lookup for conn, but
|
||||
//I need to make a system call to determin which socket
|
||||
numbytes=0;
|
||||
if(ioctl(conn->local_fd, FIONREAD, &numbytes) != -1
|
||||
&& numbytes > 0){
|
||||
fd_in = conn->local_fd;
|
||||
fd_out = conn->remote_fd;
|
||||
bOutgoing = true;
|
||||
} else {
|
||||
fd_in = conn->remote_fd;
|
||||
fd_out = conn->local_fd;
|
||||
numbytes=0;
|
||||
ioctl(fd_in, FIONREAD, &numbytes);
|
||||
bOutgoing = false;
|
||||
}
|
||||
|
||||
if (numbytes)
|
||||
{
|
||||
if (bOutgoing)
|
||||
{
|
||||
char buf[8192],*p;
|
||||
ssize_t l,split_pos=0;
|
||||
const char **split_array,**split_item;
|
||||
|
||||
rd = recv(fd_in,buf,sizeof(buf),MSG_DONTWAIT);
|
||||
if (rd>0)
|
||||
{
|
||||
switch (params.split_http_req)
|
||||
{
|
||||
case split_method:
|
||||
split_array = http_split_methods;
|
||||
break;
|
||||
case split_host:
|
||||
split_array = http_split_host;
|
||||
break;
|
||||
default:
|
||||
split_array = NULL;
|
||||
}
|
||||
if (split_array)
|
||||
{
|
||||
for(split_item=split_array;*split_item;split_item++)
|
||||
{
|
||||
l = strlen(*split_item);
|
||||
if (p=find_bin(buf,rd,*split_item,l))
|
||||
{
|
||||
split_pos = p-buf;
|
||||
printf("Found split item '%s' at pos %d\n",*split_item,split_pos);
|
||||
split_pos += l-1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (params.hostcase)
|
||||
{
|
||||
if (p=find_bin(buf,rd,"\r\nHost: ",8))
|
||||
{
|
||||
printf("Changing 'Host:' => 'host:' at pos %d\n",p-buf);
|
||||
p[2]='h';
|
||||
}
|
||||
}
|
||||
if (params.methodcase)
|
||||
{
|
||||
for(split_item=http_split_methods;*split_item;split_item++)
|
||||
{
|
||||
l = strlen(*split_item);
|
||||
if (p=find_bin(buf,rd,*split_item,l))
|
||||
{
|
||||
printf("Changing '%s' case\n",*split_item);
|
||||
*p += 'a'-'A';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (split_pos)
|
||||
{
|
||||
wr=send_with_flush(fd_out,buf,split_pos,0);
|
||||
if (wr>=0)
|
||||
wr=send(fd_out,buf+split_pos,rd-split_pos,0);
|
||||
}
|
||||
else
|
||||
{
|
||||
wr=send(fd_out,buf,rd,0);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// *** we are not interested in incoming traffic
|
||||
// splice it without processing
|
||||
|
||||
//printf("splicing numbytes=%d\n",numbytes);
|
||||
rd = numbytes = splice(fd_in, NULL, conn->splice_pipe[1], NULL,
|
||||
SPLICE_LEN, SPLICE_F_MOVE | SPLICE_F_NONBLOCK);
|
||||
//printf("spliced rd=%d\n",rd);
|
||||
if (rd>0)
|
||||
{
|
||||
wr = splice(conn->splice_pipe[0], NULL, fd_out, NULL,
|
||||
rd, SPLICE_F_MOVE);
|
||||
}
|
||||
//printf("splice rd=%d wr=%d\n",rd,wr);
|
||||
}
|
||||
}
|
||||
if (data_transferred) *data_transferred = rd<0 ? 0 : rd;
|
||||
return rd!=-1 && wr!=-1;
|
||||
}
|
||||
|
||||
void remove_closed_connections(struct tailhead *close_list){
|
||||
tproxy_conn_t *conn = NULL;
|
||||
|
||||
while(close_list->tqh_first != NULL){
|
||||
conn = (tproxy_conn_t*) close_list->tqh_first;
|
||||
TAILQ_REMOVE(close_list, close_list->tqh_first, conn_ptrs);
|
||||
|
||||
int rd=0;
|
||||
while(handle_epollin(conn,&rd) && rd);
|
||||
|
||||
printf("Socket %d and %d closed, connection removed\n",
|
||||
conn->local_fd, conn->remote_fd);
|
||||
free_conn(conn);
|
||||
}
|
||||
}
|
||||
|
||||
int event_loop(int listen_fd){
|
||||
int retval = 0, num_events = 0;
|
||||
int tmp_fd = 0; //Used to temporarily hold the accepted file descriptor
|
||||
tproxy_conn_t *conn = NULL;
|
||||
int efd, i;
|
||||
struct epoll_event ev, events[MAX_EPOLL_EVENTS];
|
||||
struct tailhead conn_list, close_list;
|
||||
uint8_t check_close = 0;
|
||||
int conncount = 0;
|
||||
|
||||
//Initialize queue (remember that TAILQ_HEAD just defines the struct)
|
||||
TAILQ_INIT(&conn_list);
|
||||
TAILQ_INIT(&close_list);
|
||||
|
||||
if((efd = epoll_create(1)) == -1){
|
||||
perror("epoll_create");
|
||||
return -1;
|
||||
}
|
||||
|
||||
//Start monitoring listen socket
|
||||
memset(&ev, 0, sizeof(ev));
|
||||
ev.events = EPOLLIN;
|
||||
//There is only one listen socket, and I want to use ptr in order to have
|
||||
//easy access to the connections. So if ptr is NULL that means an event on
|
||||
//listen socket.
|
||||
ev.data.ptr = NULL;
|
||||
if(epoll_ctl(efd, EPOLL_CTL_ADD, listen_fd, &ev) == -1){
|
||||
perror("epoll_ctl (listen socket)");
|
||||
return -1;
|
||||
}
|
||||
|
||||
while(1){
|
||||
if((num_events = epoll_wait(efd, events, MAX_EPOLL_EVENTS, -1)) == -1){
|
||||
perror("epoll_wait");
|
||||
retval = -1;
|
||||
break;
|
||||
}
|
||||
|
||||
for(i=0; i<num_events; i++){
|
||||
if(events[i].data.ptr == NULL){
|
||||
//Accept new connection
|
||||
tmp_fd = accept(listen_fd, NULL, 0);
|
||||
if (tmp_fd<0)
|
||||
{
|
||||
fprintf(stderr, "Failed to accept connection\n");
|
||||
}
|
||||
else if (conncount>=params.maxconn)
|
||||
{
|
||||
close(tmp_fd);
|
||||
fprintf(stderr, "Too much connections : %d\n",conncount);
|
||||
}
|
||||
else if((conn = add_tcp_connection(efd, &conn_list, tmp_fd, params.port)) == NULL)
|
||||
{
|
||||
close(tmp_fd);
|
||||
fprintf(stderr, "Failed to add connection\n");
|
||||
}
|
||||
else
|
||||
{
|
||||
conncount++;
|
||||
printf("Connections : %d\n",conncount);
|
||||
}
|
||||
} else {
|
||||
conn = (tproxy_conn_t*) events[i].data.ptr;
|
||||
|
||||
//Only applies to remote_fd, connection attempt has
|
||||
//succeeded/failed
|
||||
if(events[i].events & EPOLLOUT){
|
||||
if(check_connection_attempt(conn, efd) == -1){
|
||||
fprintf(stderr, "Connection attempt failed for %d\n",
|
||||
conn->remote_fd);
|
||||
check_close = 1;
|
||||
close_tcp_conn(conn, &conn_list, &close_list);
|
||||
conncount--;
|
||||
}
|
||||
continue;
|
||||
} else if(conn->state != CONN_CLOSED &&
|
||||
(events[i].events & EPOLLRDHUP ||
|
||||
events[i].events & EPOLLHUP ||
|
||||
events[i].events & EPOLLERR)){
|
||||
check_close = 1;
|
||||
close_tcp_conn(conn, &conn_list, &close_list);
|
||||
conncount--;
|
||||
continue;
|
||||
}
|
||||
|
||||
//Since I use an event cache, earlier events might cause for
|
||||
//example this connection to be closed. No need to process fd if
|
||||
//that is the case
|
||||
if(conn->state == CONN_CLOSED){
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!handle_epollin(conn,NULL)){
|
||||
close_tcp_conn(conn, &conn_list, &close_list);
|
||||
conncount--;
|
||||
check_close = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Remove connections
|
||||
if(check_close)
|
||||
remove_closed_connections(&close_list);
|
||||
|
||||
check_close = 0;
|
||||
}
|
||||
|
||||
//Add cleanup
|
||||
return retval;
|
||||
}
|
||||
|
||||
int8_t block_sigpipe(){
|
||||
sigset_t sigset;
|
||||
memset(&sigset, 0, sizeof(sigset));
|
||||
|
||||
//Get the old sigset, add SIGPIPE and update sigset
|
||||
if(sigprocmask(SIG_BLOCK, NULL, &sigset) == -1){
|
||||
perror("sigprocmask (get)");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if(sigaddset(&sigset, SIGPIPE) == -1){
|
||||
perror("sigaddset");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if(sigprocmask(SIG_BLOCK, &sigset, NULL) == -1){
|
||||
perror("sigprocmask (set)");
|
||||
return -1;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
void exithelp()
|
||||
{
|
||||
printf(" --bind-addr=<ipv4_addr>|<ipv6_addr>\n --port=<port>\n --maxconn=<max_connections>\n --split-http-req=method|host\n --hostcase\t\t; change Host: => host:\n --methodcase\t\t; change GET => gET, POST=>pOST, ...\n --daemon\t\t; daemonize\n --user=<username>\t; drop root privs\n");
|
||||
exit(1);
|
||||
}
|
||||
|
||||
void parse_params(int argc, char *argv[])
|
||||
{
|
||||
int option_index=0;
|
||||
int v,i;
|
||||
|
||||
memset(¶ms,0,sizeof(params));
|
||||
params.maxconn = DEFAULT_MAX_CONN;
|
||||
|
||||
const struct option long_options[] = {
|
||||
{"help",no_argument,0,0},// optidx=0
|
||||
{"h",no_argument,0,0},// optidx=1
|
||||
{"bind-addr",required_argument,0,0},// optidx=2
|
||||
{"port",required_argument,0,0},// optidx=3
|
||||
{"daemon",no_argument,0,0},// optidx=4
|
||||
{"user",required_argument,0,0},// optidx=5
|
||||
{"maxconn",required_argument,0,0},// optidx=6
|
||||
{"hostcase",no_argument,0,0},// optidx=7
|
||||
{"methodcase",no_argument,0,0},// optidx=8
|
||||
{"split-http-req",required_argument,0,0},// optidx=9
|
||||
{NULL,0,NULL,0}
|
||||
};
|
||||
while ((v=getopt_long_only(argc,argv,"",long_options,&option_index))!=-1)
|
||||
{
|
||||
if (v) exithelp();
|
||||
switch(option_index)
|
||||
{
|
||||
case 0:
|
||||
case 1:
|
||||
exithelp();
|
||||
break;
|
||||
case 2: /* bind-addr */
|
||||
strncpy(params.bindaddr,optarg,sizeof(params.bindaddr));
|
||||
params.bindaddr[sizeof(params.bindaddr)-1] = 0;
|
||||
break;
|
||||
case 3: /* qnum */
|
||||
i=atoi(optarg);
|
||||
if (i<=0 || i>65535)
|
||||
{
|
||||
fprintf(stderr,"bad port number\n");
|
||||
exit(1);
|
||||
}
|
||||
params.port=(uint16_t)i;
|
||||
break;
|
||||
case 4: /* daemon */
|
||||
params.daemon = true;
|
||||
break;
|
||||
case 5: /* user */
|
||||
{
|
||||
struct passwd *pwd = getpwnam(optarg);
|
||||
if (!pwd)
|
||||
{
|
||||
fprintf(stderr,"non-existent username supplied\n");
|
||||
exit(1);
|
||||
}
|
||||
params.uid = pwd->pw_uid;
|
||||
params.gid = pwd->pw_gid;
|
||||
break;
|
||||
}
|
||||
case 6: /* maxconn */
|
||||
params.maxconn=atoi(optarg);
|
||||
if (params.maxconn<=0)
|
||||
{
|
||||
fprintf(stderr,"bad maxconn\n");
|
||||
exit(1);
|
||||
}
|
||||
break;
|
||||
case 7: /* hostcase */
|
||||
params.hostcase = true;
|
||||
break;
|
||||
case 8: /* methodcase */
|
||||
params.methodcase = true;
|
||||
break;
|
||||
case 9: /* split-http-req */
|
||||
if (!strcmp(optarg,"method"))
|
||||
params.split_http_req = split_method;
|
||||
else if (!strcmp(optarg,"host"))
|
||||
params.split_http_req = split_host;
|
||||
else
|
||||
{
|
||||
fprintf(stderr,"Invalid argument for split-http-req\n");
|
||||
exit(1);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!params.port)
|
||||
{
|
||||
fprintf(stderr,"Need port number\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
void daemonize()
|
||||
{
|
||||
int pid;
|
||||
|
||||
pid = fork();
|
||||
if (pid == -1)
|
||||
{
|
||||
perror("fork: ");
|
||||
exit(2);
|
||||
}
|
||||
else if (pid != 0)
|
||||
exit(0);
|
||||
|
||||
if (setsid() == -1)
|
||||
exit(2);
|
||||
if (chdir ("/") == -1)
|
||||
exit(2);
|
||||
close(STDIN_FILENO);
|
||||
close(STDOUT_FILENO);
|
||||
close(STDERR_FILENO);
|
||||
/* redirect fd's 0,1,2 to /dev/null */
|
||||
open ("/dev/null", O_RDWR);
|
||||
/* stdin */
|
||||
dup(0);
|
||||
/* stdout */
|
||||
dup(0);
|
||||
/* stderror */
|
||||
}
|
||||
|
||||
bool droproot()
|
||||
{
|
||||
if (params.uid)
|
||||
{
|
||||
if (setgid(params.gid))
|
||||
{
|
||||
perror("setgid: ");
|
||||
return false;
|
||||
}
|
||||
if (setuid(params.uid))
|
||||
{
|
||||
perror("setuid: ");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]){
|
||||
int listen_fd = 0;
|
||||
int yes = 1, retval = 0;
|
||||
int r;
|
||||
struct sockaddr_storage salisten;
|
||||
socklen_t salisten_len;
|
||||
int ipv6_only;
|
||||
|
||||
parse_params(argc,argv);
|
||||
|
||||
memset(&salisten,0,sizeof(salisten));
|
||||
if (*params.bindaddr)
|
||||
{
|
||||
if (inet_pton(AF_INET,params.bindaddr, &((struct sockaddr_in*)&salisten)->sin_addr))
|
||||
{
|
||||
salisten.ss_family = AF_INET;
|
||||
((struct sockaddr_in*)&salisten)->sin_port = htons(params.port);
|
||||
salisten_len = sizeof(struct sockaddr_in);
|
||||
}
|
||||
else if (inet_pton(AF_INET6,params.bindaddr, &((struct sockaddr_in6*)&salisten)->sin6_addr))
|
||||
{
|
||||
salisten.ss_family = AF_INET6;
|
||||
((struct sockaddr_in6*)&salisten)->sin6_port = htons(params.port);
|
||||
salisten_len = sizeof(struct sockaddr_in6);
|
||||
ipv6_only=1;
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("bad bind addr\n");
|
||||
exit(1);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
salisten.ss_family = AF_INET6;
|
||||
((struct sockaddr_in6*)&salisten)->sin6_port = htons(params.port);
|
||||
salisten_len = sizeof(struct sockaddr_in6);
|
||||
ipv6_only=0;
|
||||
// leave sin6_addr zero
|
||||
}
|
||||
|
||||
if (params.daemon) daemonize();
|
||||
|
||||
if((listen_fd = socket(salisten.ss_family, SOCK_STREAM, 0)) == -1){
|
||||
perror("socket: ");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if ((salisten.ss_family==AF_INET6) && setsockopt(listen_fd, IPPROTO_IPV6, IPV6_V6ONLY, &ipv6_only, sizeof(ipv6_only)) == -1)
|
||||
{
|
||||
perror("setsockopt (IPV6_ONLY): ");
|
||||
close(listen_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if(setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) == -1)
|
||||
{
|
||||
perror("setsockopt (SO_REUSEADDR): ");
|
||||
close(listen_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
//Mark that this socket can be used for transparent proxying
|
||||
//This allows the socket to accept connections for non-local IPs
|
||||
if(setsockopt(listen_fd, SOL_IP, IP_TRANSPARENT, &yes, sizeof(yes)) == -1)
|
||||
{
|
||||
perror("setsockopt (IP_TRANSPARENT): ");
|
||||
close(listen_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if (!droproot())
|
||||
{
|
||||
close(listen_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if(bind(listen_fd, (struct sockaddr *)&salisten, salisten_len) == -1){
|
||||
perror("bind: ");
|
||||
close(listen_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if(listen(listen_fd, BACKLOG) == -1){
|
||||
perror("listen: ");
|
||||
close(listen_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
//splice() causes the process to receive the SIGPIPE-signal if one part (for
|
||||
//example a socket) is closed during splice(). I would rather have splice()
|
||||
//fail and return -1, so blocking SIGPIPE.
|
||||
if(block_sigpipe() == -1){
|
||||
fprintf(stderr, "Could not block SIGPIPE signal\n");
|
||||
close(listen_fd);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
fprintf(stderr, "Will listen to port %d\n", params.port);
|
||||
|
||||
retval = event_loop(listen_fd);
|
||||
close(listen_fd);
|
||||
|
||||
fprintf(stderr, "Will exit\n");
|
||||
|
||||
if(retval < 0)
|
||||
exit(EXIT_FAILURE);
|
||||
else
|
||||
exit(EXIT_SUCCESS);
|
||||
|
||||
}
|
37
tpws/tpws.h
Normal file
37
tpws/tpws.h
Normal file
@@ -0,0 +1,37 @@
|
||||
#ifndef TPROXY_EXAMPLE_H
|
||||
#define TPROXY_EXAMPLE_H
|
||||
|
||||
#include <stdint.h>
|
||||
#include <sys/queue.h>
|
||||
|
||||
#define BACKLOG 10
|
||||
#define MAX_EPOLL_EVENTS BACKLOG
|
||||
#define IP_TRANSPARENT 19 //So that application compiles on OpenWRT
|
||||
#define SPLICE_LEN 65536
|
||||
#define DEFAULT_MAX_CONN 512
|
||||
|
||||
//Three different states of a connection
|
||||
enum{
|
||||
CONN_AVAILABLE=0,
|
||||
CONN_CLOSED,
|
||||
};
|
||||
typedef uint8_t conn_state_t;
|
||||
|
||||
struct tproxy_conn{
|
||||
int local_fd; //Connection to host on local network
|
||||
int remote_fd; //Connection to remote host
|
||||
int splice_pipe[2]; //Have pipes per connection for now. Multiplexing
|
||||
//different connections onto pipes is tricky, for
|
||||
//example when flushing pipe after one connection has
|
||||
//failed.
|
||||
conn_state_t state;
|
||||
|
||||
//Create the struct which contains ptrs to next/prev element
|
||||
TAILQ_ENTRY(tproxy_conn) conn_ptrs;
|
||||
};
|
||||
typedef struct tproxy_conn tproxy_conn_t;
|
||||
|
||||
//Define the struct tailhead (code in sys/queue.h is quite intuitive)
|
||||
//Use tail queue for efficient delete
|
||||
TAILQ_HEAD(tailhead, tproxy_conn);
|
||||
#endif
|
285
tpws/tpws_conn.c
Normal file
285
tpws/tpws_conn.c
Normal file
@@ -0,0 +1,285 @@
|
||||
#include <stdio.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/ip.h>
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <sys/epoll.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdlib.h>
|
||||
#include "linux/netfilter_ipv4.h"
|
||||
#include <ifaddrs.h>
|
||||
|
||||
#include "tpws_conn.h"
|
||||
|
||||
#ifndef IP6T_SO_ORIGINAL_DST
|
||||
#define IP6T_SO_ORIGINAL_DST 80
|
||||
#endif
|
||||
|
||||
int linger(int sock_fd)
|
||||
{
|
||||
struct linger ling={1,5};
|
||||
return setsockopt(sock_fd,SOL_SOCKET,SO_LINGER,&ling,sizeof(ling));
|
||||
}
|
||||
|
||||
bool ismapped(const struct sockaddr_in6 *sa)
|
||||
{
|
||||
// ::ffff:1.2.3.4
|
||||
return !memcmp(sa->sin6_addr.s6_addr,"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff",12);
|
||||
}
|
||||
bool mappedcmp(const struct sockaddr_in *sa1,const struct sockaddr_in6 *sa2)
|
||||
{
|
||||
return ismapped(sa2) && !memcmp(sa2->sin6_addr.s6_addr+12,&sa1->sin_addr.s_addr,4);
|
||||
}
|
||||
bool sacmp(const struct sockaddr *sa1,const struct sockaddr *sa2)
|
||||
{
|
||||
return sa1->sa_family==AF_INET && sa2->sa_family==AF_INET && !memcmp(&((struct sockaddr_in*)sa1)->sin_addr,&((struct sockaddr_in*)sa2)->sin_addr,sizeof(struct in_addr)) ||
|
||||
sa1->sa_family==AF_INET6 && sa2->sa_family==AF_INET6 && !memcmp(&((struct sockaddr_in6*)sa1)->sin6_addr,&((struct sockaddr_in6*)sa2)->sin6_addr,sizeof(struct in6_addr)) ||
|
||||
sa1->sa_family==AF_INET && sa2->sa_family==AF_INET6 && mappedcmp((struct sockaddr_in*)sa1,(struct sockaddr_in6*)sa2) ||
|
||||
sa1->sa_family==AF_INET6 && sa2->sa_family==AF_INET && mappedcmp((struct sockaddr_in*)sa2,(struct sockaddr_in6*)sa1);
|
||||
}
|
||||
uint16_t saport(const struct sockaddr *sa)
|
||||
{
|
||||
return htons(sa->sa_family==AF_INET ? ((struct sockaddr_in*)sa)->sin_port :
|
||||
sa->sa_family==AF_INET6 ? ((struct sockaddr_in6*)sa)->sin6_port : 0);
|
||||
}
|
||||
// -1 = error, 0 = not local, 1 = local
|
||||
int check_local_ip(const struct sockaddr *saddr)
|
||||
{
|
||||
struct ifaddrs *addrs,*a;
|
||||
|
||||
if (getifaddrs(&addrs)<0) return -1;
|
||||
a = addrs;
|
||||
|
||||
while (a)
|
||||
{
|
||||
if (a->ifa_addr && sacmp(a->ifa_addr,saddr))
|
||||
{
|
||||
freeifaddrs(addrs);
|
||||
return 1;
|
||||
}
|
||||
a = a->ifa_next;
|
||||
}
|
||||
|
||||
freeifaddrs(addrs);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//Createas a socket and initiates the connection to the host specified by
|
||||
//remote_addr.
|
||||
//Returns 0 if something fails, >0 on success (socket fd).
|
||||
static int connect_remote(struct sockaddr_storage *remote_addr){
|
||||
int remote_fd = 0, yes = 1;
|
||||
|
||||
//Use NONBLOCK to avoid slow connects affecting the performance of other
|
||||
//connections
|
||||
if((remote_fd = socket(remote_addr->ss_family, SOCK_STREAM |
|
||||
SOCK_NONBLOCK, 0)) < 0){
|
||||
perror("socket (connect_remote): ");
|
||||
return 0;
|
||||
}
|
||||
|
||||
if(setsockopt(remote_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)) < 0){
|
||||
perror("setsockopt (SO_REUSEADDR, connect_remote): ");
|
||||
close(remote_fd);
|
||||
return 0;
|
||||
}
|
||||
|
||||
if(connect(remote_fd, (struct sockaddr*) remote_addr,
|
||||
remote_addr->ss_family == AF_INET ? sizeof(struct sockaddr_in) :
|
||||
sizeof(struct sockaddr_in6)) < 0){
|
||||
if(errno != EINPROGRESS){
|
||||
perror("connect (connect_remote): ");
|
||||
close(remote_fd);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return remote_fd;
|
||||
}
|
||||
|
||||
//Store the original destination address in remote_addr
|
||||
//Return 0 on success, <0 on failure
|
||||
static int get_org_dstaddr(int sockfd, struct sockaddr_storage *orig_dst){
|
||||
char orig_dst_str[INET6_ADDRSTRLEN];
|
||||
socklen_t addrlen = sizeof(*orig_dst);
|
||||
int r;
|
||||
|
||||
memset(orig_dst, 0, addrlen);
|
||||
|
||||
//For UDP transparent proxying:
|
||||
//Set IP_RECVORIGDSTADDR socket option for getting the original
|
||||
//destination of a datagram
|
||||
|
||||
// DNAT
|
||||
r=getsockopt(sockfd, SOL_IP, SO_ORIGINAL_DST, (struct sockaddr*) orig_dst, &addrlen);
|
||||
if (r<0)
|
||||
r = getsockopt(sockfd, SOL_IPV6, IP6T_SO_ORIGINAL_DST, (struct sockaddr*) orig_dst, &addrlen);
|
||||
if (r<0)
|
||||
{
|
||||
fprintf(stderr,"both SO_ORIGINAL_DST and IP6T_SO_ORIGINAL_DST failed !\n");
|
||||
// TPROXY : socket is bound to original destination
|
||||
r=getsockname(sockfd, (struct sockaddr*) orig_dst, &addrlen);
|
||||
if (r<0)
|
||||
{
|
||||
perror("getsockname: ");
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if(orig_dst->ss_family == AF_INET){
|
||||
inet_ntop(AF_INET,
|
||||
&(((struct sockaddr_in*) orig_dst)->sin_addr),
|
||||
orig_dst_str, INET_ADDRSTRLEN);
|
||||
fprintf(stderr, "Original destination for socket %d : %s:%d\n", sockfd,orig_dst_str, htons(((struct sockaddr_in*) orig_dst)->sin_port));
|
||||
} else if(orig_dst->ss_family == AF_INET6){
|
||||
inet_ntop(AF_INET6,
|
||||
&(((struct sockaddr_in6*) orig_dst)->sin6_addr),
|
||||
orig_dst_str, INET6_ADDRSTRLEN);
|
||||
fprintf(stderr, "Original destination for socket %d : [%s]:%d\n", sockfd,orig_dst_str, htons(((struct sockaddr_in6*) orig_dst)->sin6_port));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
//Acquires information, initiates a connect and initialises a new connection
|
||||
//object. Return NULL if anything fails, pointer to object otherwise
|
||||
tproxy_conn_t* add_tcp_connection(int efd, struct tailhead *conn_list,
|
||||
int local_fd, uint16_t listen_port)
|
||||
{
|
||||
struct sockaddr_storage orig_dst;
|
||||
tproxy_conn_t *conn;
|
||||
int remote_fd;
|
||||
struct epoll_event ev;
|
||||
|
||||
if(get_org_dstaddr(local_fd, &orig_dst)){
|
||||
fprintf(stderr, "Could not get local address\n");
|
||||
close(local_fd);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (check_local_ip((struct sockaddr*)&orig_dst)==1 && saport((struct sockaddr*)&orig_dst)==listen_port)
|
||||
{
|
||||
fprintf(stderr, "Dropping connection to local address to the same port to avoid loop\n");
|
||||
close(local_fd);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
if((remote_fd = connect_remote(&orig_dst)) == 0){
|
||||
fprintf(stderr, "Failed to connect\n");
|
||||
close(remote_fd);
|
||||
close(local_fd);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
//Create connection object and fill in information
|
||||
if((conn = (tproxy_conn_t*) malloc(sizeof(tproxy_conn_t))) == NULL){
|
||||
fprintf(stderr, "Could not allocate memory for connection\n");
|
||||
close(remote_fd);
|
||||
close(local_fd);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
memset(conn, 0, sizeof(tproxy_conn_t));
|
||||
conn->state = CONN_AVAILABLE;
|
||||
conn->remote_fd = remote_fd;
|
||||
conn->local_fd = local_fd;
|
||||
|
||||
if(pipe(conn->splice_pipe) != 0){
|
||||
fprintf(stderr, "Could not create the required pipe\n");
|
||||
free_conn(conn);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
|
||||
//remote_fd is connecting. Non-blocking connects are signaled as done by
|
||||
//socket being marked as ready for writing
|
||||
memset(&ev, 0, sizeof(ev));
|
||||
ev.events = EPOLLIN | EPOLLOUT;
|
||||
ev.data.ptr = (void*) conn;
|
||||
|
||||
if(epoll_ctl(efd, EPOLL_CTL_ADD, remote_fd, &ev) == -1){
|
||||
perror("epoll_ctl (remote_fd)");
|
||||
free_conn(conn);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
//Local socket can be closed while waiting for connection attempt. I need
|
||||
//to detect this when waiting for connect() to complete. However, I dont
|
||||
//want to get EPOLLIN-events, as I dont want to receive any data before
|
||||
//remote connection is established
|
||||
ev.events = EPOLLRDHUP;
|
||||
|
||||
if(epoll_ctl(efd, EPOLL_CTL_ADD, local_fd, &ev) == -1){
|
||||
perror("epoll_ctl (local_fd)");
|
||||
free_conn(conn);
|
||||
return NULL;
|
||||
} else
|
||||
{
|
||||
TAILQ_INSERT_HEAD(conn_list, conn, conn_ptrs);
|
||||
return conn;
|
||||
}
|
||||
}
|
||||
|
||||
//Free resources occupied by this connection
|
||||
void free_conn(tproxy_conn_t *conn){
|
||||
|
||||
close(conn->remote_fd);
|
||||
close(conn->local_fd);
|
||||
|
||||
if(conn->splice_pipe[0] != 0){
|
||||
close(conn->splice_pipe[0]);
|
||||
close(conn->splice_pipe[1]);
|
||||
}
|
||||
|
||||
free(conn);
|
||||
}
|
||||
|
||||
//Checks if a connection attempt was successful or not
|
||||
//Returns 0 if successfull, -1 if not
|
||||
int8_t check_connection_attempt(tproxy_conn_t *conn, int efd){
|
||||
struct epoll_event ev;
|
||||
int conn_success = 0;
|
||||
int fd_flags = 0;
|
||||
socklen_t optlen = sizeof(conn_success);
|
||||
|
||||
//If the connection was sucessfull or not is contained in SO_ERROR
|
||||
if(getsockopt(conn->remote_fd, SOL_SOCKET, SO_ERROR, &conn_success,
|
||||
&optlen) == -1){
|
||||
perror("getsockopt (SO_ERROR)");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if(conn_success == 0){
|
||||
fprintf(stderr, "Socket %d connected\n", conn->remote_fd);
|
||||
|
||||
//Set socket as blocking now, for ease of processing
|
||||
//TODO: Non-blocking
|
||||
if((fd_flags = fcntl(conn->remote_fd, F_GETFL)) == -1){
|
||||
perror("fcntl (F_GETFL)");
|
||||
return -1;
|
||||
}
|
||||
|
||||
if(fcntl(conn->remote_fd, F_SETFL, fd_flags & ~O_NONBLOCK) == -1){
|
||||
perror("fcntl (F_SETFL)");
|
||||
return -1;
|
||||
}
|
||||
|
||||
//Update both file descriptors. I am interested in EPOLLIN (if there is
|
||||
//any data) and EPOLLRDHUP (remote peer closed socket). As this is just
|
||||
//an example, EPOLLOUT is ignored and it is OK for send() to block
|
||||
memset(&ev, 0, sizeof(ev));
|
||||
ev.events = EPOLLIN | EPOLLRDHUP;
|
||||
ev.data.ptr = (void*) conn;
|
||||
|
||||
if(epoll_ctl(efd, EPOLL_CTL_MOD, conn->remote_fd, &ev) == -1 ||
|
||||
epoll_ctl(efd, EPOLL_CTL_MOD, conn->local_fd, &ev) == -1){
|
||||
perror("epoll_ctl (check_connection_attempt)");
|
||||
return -1;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
13
tpws/tpws_conn.h
Normal file
13
tpws/tpws_conn.h
Normal file
@@ -0,0 +1,13 @@
|
||||
#ifndef TPROXY_TEST_CONN_H
|
||||
#define TPROXY_TEST_CONN_H
|
||||
|
||||
#include "tpws.h"
|
||||
#include <stdbool.h>
|
||||
|
||||
int check_local_ip(const struct sockaddr *saddr);
|
||||
uint16_t saport(const struct sockaddr *sa);
|
||||
tproxy_conn_t* add_tcp_connection(int efd, struct tailhead *conn_list,
|
||||
int local_fd, uint16_t listen_port);
|
||||
void free_conn(tproxy_conn_t *conn);
|
||||
int8_t check_connection_attempt(tproxy_conn_t *conn, int efd);
|
||||
#endif
|
Reference in New Issue
Block a user