fix indent with clang-format

This commit is contained in:
yancey 2023-02-07 07:11:49 -05:00
parent 87b0db8862
commit 9217e0e9e6
21 changed files with 7584 additions and 8903 deletions

1638
client.cpp

File diff suppressed because it is too large Load Diff

1974
common.cpp

File diff suppressed because it is too large Load Diff

650
common.h
View File

@ -10,16 +10,16 @@
#define __STDC_FORMAT_MACROS 1
#include <inttypes.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<getopt.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <getopt.h>
#include<unistd.h>
#include<errno.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <stdlib.h> //for exit(0);
#include <errno.h> //For errno - the error number
#include <stdlib.h> //for exit(0);
#include <errno.h> //For errno - the error number
#include <fcntl.h>
#include <sys/time.h>
#include <time.h>
@ -32,7 +32,7 @@
#endif
#if defined(UDP2RAW_MP)
const int is_udp2raw_mp=1;
const int is_udp2raw_mp = 1;
#if !defined(__CYGWIN__) && !defined(__MINGW32__)
#include <pcap.h>
#else
@ -44,10 +44,9 @@ const int is_udp2raw_mp=1;
#include <libnet.h>
#endif
#else
#define UDP2RAW_LINUX
const int is_udp2raw_mp=0;
const int is_udp2raw_mp = 0;
//#include <linux/if_ether.h>
#include <linux/filter.h>
#include <linux/if_packet.h>
@ -80,51 +79,47 @@ typedef int socklen_t;
#include <netinet/in.h>
#endif
#include<unordered_map>
#include <unordered_map>
#include <fstream>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <list>
using namespace std;
using namespace std;
#if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN || \
#if defined(__BYTE_ORDER) && __BYTE_ORDER == __BIG_ENDIAN || \
defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ || \
defined(__BIG_ENDIAN__) || \
defined(__ARMEB__) || \
defined(__THUMBEB__) || \
defined(__AARCH64EB__) || \
defined(__BIG_ENDIAN__) || \
defined(__ARMEB__) || \
defined(__THUMBEB__) || \
defined(__AARCH64EB__) || \
defined(_MIBSEB) || defined(__MIBSEB) || defined(__MIBSEB__)
#define UDP2RAW_BIG_ENDIAN 1
#endif
#if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \
#if defined(__BYTE_ORDER) && __BYTE_ORDER == __LITTLE_ENDIAN || \
defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ || \
defined(__LITTLE_ENDIAN__) || \
defined(__ARMEL__) || \
defined(__THUMBEL__) || \
defined(__AARCH64EL__) || \
defined(__LITTLE_ENDIAN__) || \
defined(__ARMEL__) || \
defined(__THUMBEL__) || \
defined(__AARCH64EL__) || \
defined(_MIPSEL) || defined(__MIPSEL) || defined(__MIPSEL__)
#define UDP2RAW_LITTLE_ENDIAN 1
#endif
#if defined(UDP2RAW_BIG_ENDIAN) &&defined(UDP2RAW_LITTLE_ENDIAN)
#if defined(UDP2RAW_BIG_ENDIAN) && defined(UDP2RAW_LITTLE_ENDIAN)
#error "endian detection conflicts"
#endif
#if !defined(UDP2RAW_BIG_ENDIAN) && !defined(UDP2RAW_LITTLE_ENDIAN)
#error "endian detection failed"
#endif
#if defined(__MINGW32__)
int inet_pton(int af, const char *src, void *dst);
const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
#define setsockopt(a,b,c,d,e) setsockopt(a,b,c,(const char *)(d),e)
#define setsockopt(a, b, c, d, e) setsockopt(a, b, c, (const char *)(d), e)
#endif
char *get_sock_error();
@ -132,21 +127,18 @@ int get_sock_errno();
#if defined(__MINGW32__)
typedef SOCKET my_fd_t;
inline int sock_close(my_fd_t fd)
{
return closesocket(fd);
inline int sock_close(my_fd_t fd) {
return closesocket(fd);
}
#else
typedef int my_fd_t;
inline int sock_close(my_fd_t fd)
{
return close(fd);
inline int sock_close(my_fd_t fd) {
return close(fd);
}
#endif
typedef unsigned long long u64_t; //this works on most platform,avoid using the PRId64
typedef unsigned long long u64_t; // this works on most platform,avoid using the PRId64
typedef long long i64_t;
typedef unsigned int u32_t;
@ -165,7 +157,7 @@ typedef u64_t anti_replay_seq_t;
typedef u64_t my_time_t;
const int max_addr_len=100;
const int max_addr_len = 100;
extern int force_socket_buf;
@ -174,251 +166,224 @@ extern int g_fix_gro;
/*
struct ip_port_t
{
u32_t ip;
int port;
void from_u64(u64_t u64);
u64_t to_u64();
char * to_s();
u32_t ip;
int port;
void from_u64(u64_t u64);
u64_t to_u64();
char * to_s();
};*/
typedef u64_t fd64_t;
u32_t djb2(unsigned char *str,int len);
u32_t sdbm(unsigned char *str,int len);
u32_t djb2(unsigned char *str, int len);
u32_t sdbm(unsigned char *str, int len);
struct address_t //TODO scope id
struct address_t // TODO scope id
{
struct hash_function
{
u32_t operator()(const address_t &key) const
{
return sdbm((unsigned char*)&key.inner,sizeof(key.inner));
}
};
struct hash_function {
u32_t operator()(const address_t &key) const {
return sdbm((unsigned char *)&key.inner, sizeof(key.inner));
}
};
union storage_t //sockaddr_storage is too huge, we dont use it.
{
sockaddr_in ipv4;
sockaddr_in6 ipv6;
};
storage_t inner;
address_t()
{
clear();
}
void clear()
{
memset(&inner,0,sizeof(inner));
}
int from_ip_port(u32_t ip, int port)
{
clear();
inner.ipv4.sin_family=AF_INET;
inner.ipv4.sin_port=htons(port);
inner.ipv4.sin_addr.s_addr=ip;
return 0;
}
int from_ip_port_new(int type, void * ip, int port)
{
clear();
if(type==AF_INET)
{
inner.ipv4.sin_family=AF_INET;
inner.ipv4.sin_port=htons(port);
inner.ipv4.sin_addr.s_addr=*((u32_t *)ip);
}
else if(type==AF_INET6)
{
inner.ipv6.sin6_family=AF_INET6;
inner.ipv6.sin6_port=htons(port);
inner.ipv6.sin6_addr=*((in6_addr*)ip);
}
return 0;
}
int from_str(char * str);
int from_str_ip_only(char * str);
int from_sockaddr(sockaddr *,socklen_t);
char* get_str();
void to_str(char *);
inline u32_t get_type()
{
u32_t ret=((sockaddr*)&inner)->sa_family;
assert(ret==AF_INET||ret==AF_INET6);
return ret;
}
inline u32_t get_len()
{
u32_t type=get_type();
switch(type)
{
case AF_INET:
return sizeof(sockaddr_in);
case AF_INET6:
return sizeof(sockaddr_in6);
default:
assert(0==1);
}
return -1;
}
inline u32_t get_port()
{
u32_t type=get_type();
switch(type)
{
case AF_INET:
return ntohs(inner.ipv4.sin_port);
case AF_INET6:
return ntohs(inner.ipv6.sin6_port);
default:
assert(0==1);
}
return -1;
}
inline void set_port(int port)
{
u32_t type=get_type();
switch(type)
{
case AF_INET:
inner.ipv4.sin_port=htons(port);
break;
case AF_INET6:
inner.ipv6.sin6_port=htons(port);
break;
default:
assert(0==1);
}
return ;
}
bool operator == (const address_t &b) const
union storage_t // sockaddr_storage is too huge, we dont use it.
{
//return this->data==b.data;
return memcmp(&this->inner,&b.inner,sizeof(this->inner))==0;
sockaddr_in ipv4;
sockaddr_in6 ipv6;
};
storage_t inner;
address_t() {
clear();
}
void clear() {
memset(&inner, 0, sizeof(inner));
}
int from_ip_port(u32_t ip, int port) {
clear();
inner.ipv4.sin_family = AF_INET;
inner.ipv4.sin_port = htons(port);
inner.ipv4.sin_addr.s_addr = ip;
return 0;
}
int from_ip_port_new(int type, void *ip, int port) {
clear();
if (type == AF_INET) {
inner.ipv4.sin_family = AF_INET;
inner.ipv4.sin_port = htons(port);
inner.ipv4.sin_addr.s_addr = *((u32_t *)ip);
} else if (type == AF_INET6) {
inner.ipv6.sin6_family = AF_INET6;
inner.ipv6.sin6_port = htons(port);
inner.ipv6.sin6_addr = *((in6_addr *)ip);
}
return 0;
}
int from_str(char *str);
int from_str_ip_only(char *str);
int from_sockaddr(sockaddr *, socklen_t);
char *get_str();
void to_str(char *);
inline u32_t get_type() {
u32_t ret = ((sockaddr *)&inner)->sa_family;
assert(ret == AF_INET || ret == AF_INET6);
return ret;
}
inline u32_t get_len() {
u32_t type = get_type();
switch (type) {
case AF_INET:
return sizeof(sockaddr_in);
case AF_INET6:
return sizeof(sockaddr_in6);
default:
assert(0 == 1);
}
return -1;
}
inline u32_t get_port() {
u32_t type = get_type();
switch (type) {
case AF_INET:
return ntohs(inner.ipv4.sin_port);
case AF_INET6:
return ntohs(inner.ipv6.sin6_port);
default:
assert(0 == 1);
}
return -1;
}
inline void set_port(int port) {
u32_t type = get_type();
switch (type) {
case AF_INET:
inner.ipv4.sin_port = htons(port);
break;
case AF_INET6:
inner.ipv6.sin6_port = htons(port);
break;
default:
assert(0 == 1);
}
return;
}
bool operator==(const address_t &b) const {
// return this->data==b.data;
return memcmp(&this->inner, &b.inner, sizeof(this->inner)) == 0;
}
int new_connected_udp_fd();
char* get_ip();
char *get_ip();
};
namespace std {
template <>
struct hash<address_t>
{
std::size_t operator()(const address_t& key) const
{
struct hash<address_t> {
std::size_t operator()(const address_t &key) const {
// return address_t::hash_function(k);
return sdbm((unsigned char *)&key.inner, sizeof(key.inner));
}
};
} // namespace std
//return address_t::hash_function(k);
return sdbm((unsigned char*)&key.inner,sizeof(key.inner));
}
};
}
union my_ip_t //just a simple version of address_t,stores ip only
union my_ip_t // just a simple version of address_t,stores ip only
{
u32_t v4;
in6_addr v6;
u32_t v4;
in6_addr v6;
bool equal (const my_ip_t &b) const;
bool equal(const my_ip_t &b) const;
//int from_str(char * str);
char * get_str1() const;
char * get_str2() const;
// int from_str(char * str);
char *get_str1() const;
char *get_str2() const;
int from_address_t(address_t a);
};
struct not_copy_able_t
{
not_copy_able_t()
{
}
not_copy_able_t(const not_copy_able_t &other)
{
assert(0==1);
}
const not_copy_able_t & operator=(const not_copy_able_t &other)
{
assert(0==1);
return other;
}
struct not_copy_able_t {
not_copy_able_t() {
}
not_copy_able_t(const not_copy_able_t &other) {
assert(0 == 1);
}
const not_copy_able_t &operator=(const not_copy_able_t &other) {
assert(0 == 1);
return other;
}
};
const int huge_data_len=65535+100; //a packet with link level header might be larger than 65535
const int huge_buf_len=huge_data_len+100;
const int huge_data_len = 65535 + 100; // a packet with link level header might be larger than 65535
const int huge_buf_len = huge_data_len + 100;
const int max_data_len=1800;
const int buf_len=max_data_len+400;
const int max_data_len = 1800;
const int buf_len = max_data_len + 400;
//const int max_address_len=512;
// const int max_address_len=512;
#ifdef UDP2RAW_MP
const int queue_len=200;
const int queue_len = 200;
struct queue_t
{
char data[queue_len][huge_buf_len];
int data_len[queue_len];
struct queue_t {
char data[queue_len][huge_buf_len];
int data_len[queue_len];
int head=0;
int tail=0;
void clear()
{
head=tail=0;
}
int empty()
{
if(head==tail) return 1;
else return 0;
}
int full()
{
if( (tail+1)%queue_len==head ) return 1;
else return 0;
}
void peek_front(char * & p,int &len)
{
assert(!empty());
p=data[head];
len=data_len[head];
}
void pop_front()
{
assert(!empty());
head++;head%=queue_len;
}
void push_back(char * p,int len)
{
assert(!full());
memcpy(data[tail],p,len);
data_len[tail]=len;
tail++;tail%=queue_len;
}
int head = 0;
int tail = 0;
void clear() {
head = tail = 0;
}
int empty() {
if (head == tail)
return 1;
else
return 0;
}
int full() {
if ((tail + 1) % queue_len == head)
return 1;
else
return 0;
}
void peek_front(char *&p, int &len) {
assert(!empty());
p = data[head];
len = data_len[head];
}
void pop_front() {
assert(!empty());
head++;
head %= queue_len;
}
void push_back(char *p, int len) {
assert(!full());
memcpy(data[tail], p, len);
data_len[tail] = len;
tail++;
tail %= queue_len;
}
};
int init_ws();
#endif
u64_t get_current_time();
u64_t pack_u64(u32_t a,u32_t b);
u64_t pack_u64(u32_t a, u32_t b);
u32_t get_u64_h(u64_t a);
u32_t get_u64_l(u64_t a);
char * my_ntoa(u32_t ip);
char *my_ntoa(u32_t ip);
void init_random_number_fd();
u64_t get_true_random_number_64();
@ -427,138 +392,131 @@ u32_t get_true_random_number_nz();
u64_t ntoh64(u64_t a);
u64_t hton64(u64_t a);
void write_u16(char *,u16_t a);// network order
void write_u16(char *, u16_t a); // network order
u16_t read_u16(char *);
void write_u32(char *,u32_t a);// network order
void write_u32(char *, u32_t a); // network order
u32_t read_u32(char *);
void write_u64(char *,u64_t a);
void write_u64(char *, u64_t a);
u64_t read_u64(char *);
bool larger_than_u16(uint16_t a,uint16_t b);
bool larger_than_u32(u32_t a,u32_t b);
bool larger_than_u16(uint16_t a, uint16_t b);
bool larger_than_u32(u32_t a, u32_t b);
void setnonblocking(int sock);
int set_buf_size(int fd,int socket_buf_size);
int set_buf_size(int fd, int socket_buf_size);
void myexit(int a);
unsigned short csum(const unsigned short *ptr,int nbytes);
unsigned short csum_with_header(char* header,int hlen,const unsigned short *ptr,int nbytes);
unsigned short csum(const unsigned short *ptr, int nbytes);
unsigned short csum_with_header(char *header, int hlen, const unsigned short *ptr, int nbytes);
int numbers_to_char(my_id_t id1,my_id_t id2,my_id_t id3,char * &data,int &len);
int char_to_numbers(const char * data,int len,my_id_t &id1,my_id_t &id2,my_id_t &id3);
int numbers_to_char(my_id_t id1, my_id_t id2, my_id_t id3, char *&data, int &len);
int char_to_numbers(const char *data, int len, my_id_t &id1, my_id_t &id2, my_id_t &id3);
const int show_none=0;
const int show_command=0x1;
const int show_log=0x2;
const int show_all=show_command|show_log;
const int show_none = 0;
const int show_command = 0x1;
const int show_log = 0x2;
const int show_all = show_command | show_log;
int run_command(string command,char * &output,int flag=show_all);
//int run_command_no_log(string command,char * &output);
int read_file(const char * file,string &output);
int run_command(string command, char *&output, int flag = show_all);
// int run_command_no_log(string command,char * &output);
int read_file(const char *file, string &output);
vector<string> string_to_vec(const char * s,const char * sp);
vector< vector <string> > string_to_vec2(const char * s);
vector<string> string_to_vec(const char *s, const char *sp);
vector<vector<string> > string_to_vec2(const char *s);
string trim(const string& str, char c);
string trim(const string &str, char c);
string trim_conf_line(const string& str);
string trim_conf_line(const string &str);
vector<string> parse_conf_line(const string& s);
vector<string> parse_conf_line(const string &s);
int hex_to_u32_with_endian(const string & a,u32_t &output);
int hex_to_u32(const string & a,u32_t &output);
//extern string iptables_pattern;
int hex_to_u32_with_endian(const string &a, u32_t &output);
int hex_to_u32(const string &a, u32_t &output);
// extern string iptables_pattern;
int create_fifo(char * file);
int create_fifo(char *file);
void print_binary_chars(const char * a,int len);
void print_binary_chars(const char *a, int len);
template <class key_t>
struct lru_collector_t:not_copy_able_t
{
//typedef void* key_t;
//#define key_t void*
struct lru_pair_t
{
key_t key;
my_time_t ts;
};
struct lru_collector_t : not_copy_able_t {
// typedef void* key_t;
//#define key_t void*
struct lru_pair_t {
key_t key;
my_time_t ts;
};
unordered_map<key_t,typename list<lru_pair_t>::iterator> mp;
unordered_map<key_t, typename list<lru_pair_t>::iterator> mp;
list<lru_pair_t> q;
int update(key_t key)
{
assert(mp.find(key)!=mp.end());
auto it=mp[key];
q.erase(it);
list<lru_pair_t> q;
int update(key_t key) {
assert(mp.find(key) != mp.end());
auto it = mp[key];
q.erase(it);
my_time_t value=get_current_time();
if(!q.empty())
{
assert(value >=q.front().ts);
}
lru_pair_t tmp; tmp.key=key; tmp.ts=value;
q.push_front( tmp);
mp[key]=q.begin();
my_time_t value = get_current_time();
if (!q.empty()) {
assert(value >= q.front().ts);
}
lru_pair_t tmp;
tmp.key = key;
tmp.ts = value;
q.push_front(tmp);
mp[key] = q.begin();
return 0;
}
int new_key(key_t key)
{
assert(mp.find(key)==mp.end());
return 0;
}
int new_key(key_t key) {
assert(mp.find(key) == mp.end());
my_time_t value=get_current_time();
if(!q.empty())
{
assert(value >=q.front().ts);
}
lru_pair_t tmp; tmp.key=key; tmp.ts=value;
q.push_front( tmp);
mp[key]=q.begin();
my_time_t value = get_current_time();
if (!q.empty()) {
assert(value >= q.front().ts);
}
lru_pair_t tmp;
tmp.key = key;
tmp.ts = value;
q.push_front(tmp);
mp[key] = q.begin();
return 0;
}
int size()
{
return q.size();
}
int empty()
{
return q.empty();
}
void clear()
{
mp.clear(); q.clear();
}
my_time_t ts_of(key_t key)
{
assert(mp.find(key)!=mp.end());
return mp[key]->ts;
}
return 0;
}
int size() {
return q.size();
}
int empty() {
return q.empty();
}
void clear() {
mp.clear();
q.clear();
}
my_time_t ts_of(key_t key) {
assert(mp.find(key) != mp.end());
return mp[key]->ts;
}
my_time_t peek_back(key_t &key)
{
assert(!q.empty());
auto it=q.end(); it--;
key=it->key;
return it->ts;
}
void erase(key_t key)
{
assert(mp.find(key)!=mp.end());
q.erase(mp[key]);
mp.erase(key);
}
/*
void erase_back()
{
assert(!q.empty());
auto it=q.end(); it--;
key_t key=it->key;
erase(key);
}*/
my_time_t peek_back(key_t &key) {
assert(!q.empty());
auto it = q.end();
it--;
key = it->key;
return it->ts;
}
void erase(key_t key) {
assert(mp.find(key) != mp.end());
q.erase(mp[key]);
mp.erase(key);
}
/*
void erase_back()
{
assert(!q.empty());
auto it=q.end(); it--;
key_t key=it->key;
erase(key);
}*/
};
#endif /* COMMON_H_ */

File diff suppressed because it is too large Load Diff

View File

@ -16,336 +16,298 @@ extern int disable_anti_replay;
#include "network.h"
#include "misc.h"
const int disable_conv_clear=0;//a udp connection in the multiplexer is called conversation in this program,conv for short.
const int disable_conv_clear = 0; // a udp connection in the multiplexer is called conversation in this program,conv for short.
struct anti_replay_t //its for anti replay attack,similar to openvpn/ipsec 's anti replay window
struct anti_replay_t // its for anti replay attack,similar to openvpn/ipsec 's anti replay window
{
u64_t max_packet_received;
char window[anti_replay_window_size];
anti_replay_seq_t anti_replay_seq;
anti_replay_seq_t get_new_seq_for_send();
anti_replay_t();
void re_init();
u64_t max_packet_received;
char window[anti_replay_window_size];
anti_replay_seq_t anti_replay_seq;
anti_replay_seq_t get_new_seq_for_send();
anti_replay_t();
void re_init();
int is_vaild(u64_t seq);
};//anti_replay;
int is_vaild(u64_t seq);
}; // anti_replay;
void server_clear_function(u64_t u64);
#include <type_traits>
template <class T>
template <class T>
struct conv_manager_t // manage the udp connections
{
//typedef hash_map map;
unordered_map<T,u32_t> data_to_conv; //conv and u64 are both supposed to be uniq
unordered_map<u32_t,T> conv_to_data;
// typedef hash_map map;
unordered_map<T, u32_t> data_to_conv; // conv and u64 are both supposed to be uniq
unordered_map<u32_t, T> conv_to_data;
lru_collector_t<u32_t> lru;
//unordered_map<u32_t,u64_t> conv_last_active_time;
lru_collector_t<u32_t> lru;
// unordered_map<u32_t,u64_t> conv_last_active_time;
//unordered_map<u32_t,u64_t>::iterator clear_it;
// unordered_map<u32_t,u64_t>::iterator clear_it;
void (*additional_clear_function)(T data) =0;
void (*additional_clear_function)(T data) = 0;
long long last_clear_time;
long long last_clear_time;
conv_manager_t()
{
//clear_it=conv_last_active_time.begin();
long long last_clear_time=0;
additional_clear_function=0;
}
~conv_manager_t()
{
clear();
}
int get_size()
{
return conv_to_data.size();
}
void reserve()
{
data_to_conv.reserve(10007);
conv_to_data.reserve(10007);
//conv_last_active_time.reserve(10007);
conv_manager_t() {
// clear_it=conv_last_active_time.begin();
long long last_clear_time = 0;
additional_clear_function = 0;
}
~conv_manager_t() {
clear();
}
int get_size() {
return conv_to_data.size();
}
void reserve() {
data_to_conv.reserve(10007);
conv_to_data.reserve(10007);
// conv_last_active_time.reserve(10007);
lru.mp.reserve(10007);
}
void clear()
{
if(disable_conv_clear) return ;
lru.mp.reserve(10007);
}
void clear() {
if (disable_conv_clear) return;
if(additional_clear_function!=0)
{
for(auto it=conv_to_data.begin();it!=conv_to_data.end();it++)
{
//int fd=int((it->second<<32u)>>32u);
additional_clear_function( it->second);
}
}
data_to_conv.clear();
conv_to_data.clear();
if (additional_clear_function != 0) {
for (auto it = conv_to_data.begin(); it != conv_to_data.end(); it++) {
// int fd=int((it->second<<32u)>>32u);
additional_clear_function(it->second);
}
}
data_to_conv.clear();
conv_to_data.clear();
lru.clear();
//conv_last_active_time.clear();
lru.clear();
// conv_last_active_time.clear();
//clear_it=conv_last_active_time.begin();
// clear_it=conv_last_active_time.begin();
}
u32_t get_new_conv() {
u32_t conv = get_true_random_number_nz();
while (conv_to_data.find(conv) != conv_to_data.end()) {
conv = get_true_random_number_nz();
}
return conv;
}
int is_conv_used(u32_t conv) {
return conv_to_data.find(conv) != conv_to_data.end();
}
int is_data_used(T data) {
return data_to_conv.find(data) != data_to_conv.end();
}
u32_t find_conv_by_data(T data) {
return data_to_conv[data];
}
T find_data_by_conv(u32_t conv) {
return conv_to_data[conv];
}
int update_active_time(u32_t conv) {
// return conv_last_active_time[conv]=get_current_time();
lru.update(conv);
return 0;
}
int insert_conv(u32_t conv, T data) {
data_to_conv[data] = conv;
conv_to_data[conv] = data;
// conv_last_active_time[conv]=get_current_time();
lru.new_key(conv);
return 0;
}
int erase_conv(u32_t conv) {
if (disable_conv_clear) return 0;
T data = conv_to_data[conv];
if (additional_clear_function != 0) {
additional_clear_function(data);
}
conv_to_data.erase(conv);
data_to_conv.erase(data);
// conv_last_active_time.erase(conv);
lru.erase(conv);
return 0;
}
int clear_inactive(char *info = 0) {
if (get_current_time() - last_clear_time > conv_clear_interval) {
last_clear_time = get_current_time();
return clear_inactive0(info);
}
return 0;
}
int clear_inactive0(char *info) {
if (disable_conv_clear) return 0;
}
u32_t get_new_conv()
{
u32_t conv=get_true_random_number_nz();
while(conv_to_data.find(conv)!=conv_to_data.end())
{
conv=get_true_random_number_nz();
}
return conv;
}
int is_conv_used(u32_t conv)
{
return conv_to_data.find(conv)!=conv_to_data.end();
}
int is_data_used(T data)
{
return data_to_conv.find(data)!=data_to_conv.end();
}
u32_t find_conv_by_data(T data)
{
return data_to_conv[data];
}
T find_data_by_conv(u32_t conv)
{
return conv_to_data[conv];
}
int update_active_time(u32_t conv)
{
//return conv_last_active_time[conv]=get_current_time();
lru.update(conv);
return 0;
}
int insert_conv(u32_t conv,T data)
{
data_to_conv[data]=conv;
conv_to_data[conv]=data;
//conv_last_active_time[conv]=get_current_time();
lru.new_key(conv);
return 0;
}
int erase_conv(u32_t conv)
{
if(disable_conv_clear) return 0;
T data=conv_to_data[conv];
if(additional_clear_function!=0)
{
additional_clear_function(data);
}
conv_to_data.erase(conv);
data_to_conv.erase(data);
//conv_last_active_time.erase(conv);
lru.erase(conv);
return 0;
}
int clear_inactive(char * info=0)
{
if(get_current_time()-last_clear_time>conv_clear_interval)
{
last_clear_time=get_current_time();
return clear_inactive0(info);
}
return 0;
}
int clear_inactive0(char * info)
{
if(disable_conv_clear) return 0;
unordered_map<u32_t, u64_t>::iterator it;
unordered_map<u32_t, u64_t>::iterator old_it;
// map<uint32_t,uint64_t>::iterator it;
int cnt = 0;
// it=clear_it;
int size = lru.size();
int num_to_clean = size / conv_clear_ratio + conv_clear_min; // clear 1/10 each time,to avoid latency glitch
unordered_map<u32_t,u64_t>::iterator it;
unordered_map<u32_t,u64_t>::iterator old_it;
num_to_clean = min(num_to_clean, size);
//map<uint32_t,uint64_t>::iterator it;
int cnt=0;
//it=clear_it;
int size=lru.size();
int num_to_clean=size/conv_clear_ratio+conv_clear_min; //clear 1/10 each time,to avoid latency glitch
my_time_t current_time = get_current_time();
for (;;) {
if (cnt >= num_to_clean) break;
if (lru.empty()) break;
num_to_clean=min(num_to_clean,size);
u32_t conv;
my_time_t ts = lru.peek_back(conv);
my_time_t current_time=get_current_time();
for(;;)
{
if(cnt>=num_to_clean) break;
if(lru.empty()) break;
if (current_time - ts < conv_timeout) break;
u32_t conv;
my_time_t ts=lru.peek_back(conv);
erase_conv(conv);
if (info == 0) {
mylog(log_info, "conv %x cleared\n", conv);
} else {
mylog(log_info, "[%s]conv %x cleared\n", info, conv);
}
cnt++;
}
return 0;
}
if(current_time- ts < conv_timeout) break;
/*
conv_manager_t();
~conv_manager_t();
int get_size();
void reserve();
void clear();
u32_t get_new_conv();
int is_conv_used(u32_t conv);
int is_u64_used(T u64);
u32_t find_conv_by_u64(T u64);
T find_u64_by_conv(u32_t conv);
int update_active_time(u32_t conv);
int insert_conv(u32_t conv,T u64);
int erase_conv(u32_t conv);
int clear_inactive(char * ip_port=0);
int clear_inactive0(char * ip_port);*/
}; // g_conv_manager;
erase_conv(conv);
if(info==0)
{
mylog(log_info,"conv %x cleared\n",conv);
}
else
{
mylog(log_info,"[%s]conv %x cleared\n",info,conv);
}
cnt++;
}
return 0;
}
/*
conv_manager_t();
~conv_manager_t();
int get_size();
void reserve();
void clear();
u32_t get_new_conv();
int is_conv_used(u32_t conv);
int is_u64_used(T u64);
u32_t find_conv_by_u64(T u64);
T find_u64_by_conv(u32_t conv);
int update_active_time(u32_t conv);
int insert_conv(u32_t conv,T u64);
int erase_conv(u32_t conv);
int clear_inactive(char * ip_port=0);
int clear_inactive0(char * ip_port);*/
};//g_conv_manager;
struct blob_t:not_copy_able_t //used in conn_info_t.
struct blob_t : not_copy_able_t // used in conn_info_t.
{
union tmp_union_t//conv_manager_t is here to avoid copying when a connection is recovered
{
conv_manager_t<address_t> c;
conv_manager_t<u64_t> s;
//avoid templates here and there, avoid pointer and type cast
tmp_union_t()
{
if(program_mode==client_mode)
{
new( &c ) conv_manager_t<address_t>();
}
else
{
assert(program_mode==server_mode);
new( &s ) conv_manager_t<u64_t>();
}
}
~tmp_union_t()
{
if(program_mode==client_mode)
{
c.~conv_manager_t<address_t>();
}
else
{
assert(program_mode==server_mode);
s.~conv_manager_t<u64_t>();
}
}
}conv_manager;
union tmp_union_t // conv_manager_t is here to avoid copying when a connection is recovered
{
conv_manager_t<address_t> c;
conv_manager_t<u64_t> s;
// avoid templates here and there, avoid pointer and type cast
tmp_union_t() {
if (program_mode == client_mode) {
new (&c) conv_manager_t<address_t>();
} else {
assert(program_mode == server_mode);
new (&s) conv_manager_t<u64_t>();
}
}
~tmp_union_t() {
if (program_mode == client_mode) {
c.~conv_manager_t<address_t>();
} else {
assert(program_mode == server_mode);
s.~conv_manager_t<u64_t>();
}
}
} conv_manager;
anti_replay_t anti_replay;//anti_replay_t is here bc its huge,its allocation is delayed.
anti_replay_t anti_replay; // anti_replay_t is here bc its huge,its allocation is delayed.
};
struct conn_info_t //stores info for a raw connection.for client ,there is only one connection,for server there can be thousand of connection since server can
//handle multiple clients
struct conn_info_t // stores info for a raw connection.for client ,there is only one connection,for server there can be thousand of connection since server can
// handle multiple clients
{
current_state_t state;
current_state_t state;
raw_info_t raw_info;
u64_t last_state_time;
u64_t last_hb_sent_time; //client re-use this for retry
u64_t last_hb_recv_time;
//long long last_resent_time;
raw_info_t raw_info;
u64_t last_state_time;
u64_t last_hb_sent_time; // client re-use this for retry
u64_t last_hb_recv_time;
// long long last_resent_time;
my_id_t my_id;
my_id_t oppsite_id;
my_id_t my_id;
my_id_t oppsite_id;
fd64_t timer_fd64;
fd64_t udp_fd64;
fd64_t timer_fd64;
fd64_t udp_fd64;
my_id_t oppsite_const_id;
my_id_t oppsite_const_id;
blob_t *blob;
blob_t *blob;
uint8_t my_roller;
uint8_t oppsite_roller;
u64_t last_oppsite_roller_time;
uint8_t my_roller;
uint8_t oppsite_roller;
u64_t last_oppsite_roller_time;
// ip_port_t ip_port;
// ip_port_t ip_port;
/*
const uint32_t &ip=raw_info.recv_info.src_ip;
const uint16_t &port=raw_info.recv_info.src_port;
/*
const uint32_t &ip=raw_info.recv_info.src_ip;
const uint16_t &port=raw_info.recv_info.src_port;
*/
void recover(const conn_info_t &conn_info);
void re_init();
conn_info_t();
void prepare();
conn_info_t(const conn_info_t &b);
conn_info_t &operator=(const conn_info_t &b);
~conn_info_t();
}; // g_conn_info;
*/
void recover(const conn_info_t &conn_info);
void re_init();
conn_info_t();
void prepare();
conn_info_t(const conn_info_t&b);
conn_info_t& operator=(const conn_info_t& b);
~conn_info_t();
};//g_conn_info;
struct conn_manager_t //manager for connections. for client,we dont need conn_manager since there is only one connection.for server we use one conn_manager for all connections
struct conn_manager_t // manager for connections. for client,we dont need conn_manager since there is only one connection.for server we use one conn_manager for all connections
{
u32_t ready_num;
u32_t ready_num;
// unordered_map<int,conn_info_t *> udp_fd_mp; //a bit dirty to used pointer,but can void unordered_map search
// unordered_map<int,conn_info_t *> timer_fd_mp;//we can use pointer here since unordered_map.rehash() uses shallow copy
//unordered_map<int,conn_info_t *> udp_fd_mp; //a bit dirty to used pointer,but can void unordered_map search
//unordered_map<int,conn_info_t *> timer_fd_mp;//we can use pointer here since unordered_map.rehash() uses shallow copy
unordered_map<my_id_t, conn_info_t *> const_id_mp;
unordered_map<my_id_t,conn_info_t *> const_id_mp;
unordered_map<address_t, conn_info_t *> mp; // put it at end so that it de-consturcts first
unordered_map<address_t,conn_info_t*> mp; //put it at end so that it de-consturcts first
// lru_collector_t<address_t> lru;
//lru_collector_t<address_t> lru;
unordered_map<address_t, conn_info_t *>::iterator clear_it;
unordered_map<address_t,conn_info_t*>::iterator clear_it;
long long last_clear_time;
long long last_clear_time;
conn_manager_t();
int exist(address_t addr);
/*
int insert(uint32_t ip,uint16_t port)
{
uint64_t u64=0;
u64=ip;
u64<<=32u;
u64|=port;
mp[u64];
return 0;
}*/
conn_info_t *& find_insert_p(address_t addr); //be aware,the adress may change after rehash //not true?
conn_info_t & find_insert(address_t addr) ; //be aware,the adress may change after rehash
int erase(unordered_map<address_t,conn_info_t*>::iterator erase_it);
int clear_inactive();
int clear_inactive0();
conn_manager_t();
int exist(address_t addr);
/*
int insert(uint32_t ip,uint16_t port)
{
uint64_t u64=0;
u64=ip;
u64<<=32u;
u64|=port;
mp[u64];
return 0;
}*/
conn_info_t *&find_insert_p(address_t addr); // be aware,the adress may change after rehash //not true?
conn_info_t &find_insert(address_t addr); // be aware,the adress may change after rehash
int erase(unordered_map<address_t, conn_info_t *>::iterator erase_it);
int clear_inactive();
int clear_inactive0();
};
extern conn_manager_t conn_manager;
void server_clear_function(u64_t u64);
int send_bare(raw_info_t &raw_info,const char* data,int len);//send function with encryption but no anti replay,this is used when client and server verifys each other
//you have to design the protocol carefully, so that you wont be affect by relay attack
//int reserved_parse_bare(const char *input,int input_len,char* & data,int & len); // a sub function used in recv_bare
int recv_bare(raw_info_t &raw_info,char* & data,int & len);//recv function with encryption but no anti replay,this is used when client and server verifys each other
//you have to design the protocol carefully, so that you wont be affect by relay attack
int send_handshake(raw_info_t &raw_info,my_id_t id1,my_id_t id2,my_id_t id3);// a warp for send_bare for sending handshake(this is not tcp handshake) easily
int send_safer(conn_info_t &conn_info,char type,const char* data,int len); //safer transfer function with anti-replay,when mutually verification is done.
int send_data_safer(conn_info_t &conn_info,const char* data,int len,u32_t conv_num);//a wrap for send_safer for transfer data.
//int reserved_parse_safer(conn_info_t &conn_info,const char * input,int input_len,char &type,char* &data,int &len);//subfunction for recv_safer,allow overlap
int send_bare(raw_info_t &raw_info, const char *data, int len); // send function with encryption but no anti replay,this is used when client and server verifys each other
// you have to design the protocol carefully, so that you wont be affect by relay attack
// int reserved_parse_bare(const char *input,int input_len,char* & data,int & len); // a sub function used in recv_bare
int recv_bare(raw_info_t &raw_info, char *&data, int &len); // recv function with encryption but no anti replay,this is used when client and server verifys each other
// you have to design the protocol carefully, so that you wont be affect by relay attack
int send_handshake(raw_info_t &raw_info, my_id_t id1, my_id_t id2, my_id_t id3); // a warp for send_bare for sending handshake(this is not tcp handshake) easily
int send_safer(conn_info_t &conn_info, char type, const char *data, int len); // safer transfer function with anti-replay,when mutually verification is done.
int send_data_safer(conn_info_t &conn_info, const char *data, int len, u32_t conv_num); // a wrap for send_safer for transfer data.
// int reserved_parse_safer(conn_info_t &conn_info,const char * input,int input_len,char &type,char* &data,int &len);//subfunction for recv_safer,allow overlap
//int recv_safer(conn_info_t &conn_info,char &type,char* &data,int &len);///safer transfer function with anti-replay,when mutually verification is done.
// int recv_safer(conn_info_t &conn_info,char &type,char* &data,int &len);///safer transfer function with anti-replay,when mutually verification is done.
int recv_safer_multi(conn_info_t &conn_info,vector<char> &type_arr,vector<string> &data_arr);//new api for handle gro
#endif /* CONNECTION_H_ */
int recv_safer_multi(conn_info_t &conn_info, vector<char> &type_arr, vector<string> &data_arr); // new api for handle gro
#endif /* CONNECTION_H_ */

913
encrypt.cpp Executable file → Normal file

File diff suppressed because it is too large Load Diff

44
encrypt.h Executable file → Normal file
View File

@ -1,33 +1,35 @@
#ifndef UDP2RAW_ENCRYPTION_H_
#define UDP2RAW_ENCRYPTION_H_
//#include "aes.h"
//#include "md5.h"
#include "common.h"
// using namespace std;
// extern char key[16];
//using namespace std;
//extern char key[16];
const int aes_key_optimize=1; //if enabled,once you used a key for aes,you cant change it anymore
const int aes_key_optimize = 1; // if enabled,once you used a key for aes,you cant change it anymore
extern int aes128cfb_old;
int my_init_keys(const char *,int);
int my_init_keys(const char *, int);
int my_encrypt(const char *data,char *output,int &len);
int my_decrypt(const char *data,char *output,int &len);
int my_encrypt(const char *data, char *output, int &len);
int my_decrypt(const char *data, char *output, int &len);
unsigned short csum(const unsigned short *ptr, int nbytes);
unsigned short csum(const unsigned short *ptr,int nbytes) ;
enum auth_mode_t {auth_none=0,auth_md5,auth_crc32,auth_simple,auth_hmac_sha1,auth_end};
enum cipher_mode_t {cipher_none=0,cipher_aes128cbc,cipher_xor,cipher_aes128cfb,cipher_end};
enum auth_mode_t { auth_none = 0,
auth_md5,
auth_crc32,
auth_simple,
auth_hmac_sha1,
auth_end };
enum cipher_mode_t { cipher_none = 0,
cipher_aes128cbc,
cipher_xor,
cipher_aes128cfb,
cipher_end };
extern auth_mode_t auth_mode;
extern cipher_mode_t cipher_mode;
@ -35,13 +37,13 @@ extern cipher_mode_t cipher_mode;
extern unordered_map<int, const char *> auth_mode_tostring;
extern unordered_map<int, const char *> cipher_mode_tostring;
extern char gro_xor[256+100];
extern char gro_xor[256 + 100];
int cipher_decrypt(const char *data,char *output,int &len,char * key);//internal interface ,exposed for test only
int cipher_encrypt(const char *data,char *output,int &len,char * key);//internal interface ,exposed for test only
int cipher_decrypt(const char *data, char *output, int &len, char *key); // internal interface ,exposed for test only
int cipher_encrypt(const char *data, char *output, int &len, char *key); // internal interface ,exposed for test only
void aes_ecb_encrypt(const char *data,char *output);
void aes_ecb_decrypt(const char *data,char *output);
void aes_ecb_encrypt(const char *data, char *output);
void aes_ecb_decrypt(const char *data, char *output);
void aes_ecb_encrypt1(char *data);
void aes_ecb_decrypt1(char *data);

View File

@ -5,60 +5,49 @@
* Author: root
*/
#include "fd_manager.h"
int fd_manager_t::fd_exist(int fd)
{
return fd_to_fd64_mp.find(fd)!=fd_to_fd64_mp.end();
int fd_manager_t::fd_exist(int fd) {
return fd_to_fd64_mp.find(fd) != fd_to_fd64_mp.end();
}
int fd_manager_t::exist(fd64_t fd64)
{
return fd64_to_fd_mp.find(fd64)!=fd64_to_fd_mp.end();
int fd_manager_t::exist(fd64_t fd64) {
return fd64_to_fd_mp.find(fd64) != fd64_to_fd_mp.end();
}
int fd_manager_t::to_fd(fd64_t fd64)
{
assert(exist(fd64));
return fd64_to_fd_mp[fd64];
int fd_manager_t::to_fd(fd64_t fd64) {
assert(exist(fd64));
return fd64_to_fd_mp[fd64];
}
void fd_manager_t::fd64_close(fd64_t fd64)
{
assert(exist(fd64));
int fd=fd64_to_fd_mp[fd64];
fd64_to_fd_mp.erase(fd64);
fd_to_fd64_mp.erase(fd);
if(exist_info(fd64))
{
fd_info_mp.erase(fd64);
}
//assert(close(fd)==0);
sock_close(fd);
void fd_manager_t::fd64_close(fd64_t fd64) {
assert(exist(fd64));
int fd = fd64_to_fd_mp[fd64];
fd64_to_fd_mp.erase(fd64);
fd_to_fd64_mp.erase(fd);
if (exist_info(fd64)) {
fd_info_mp.erase(fd64);
}
// assert(close(fd)==0);
sock_close(fd);
}
void fd_manager_t::reserve(int n)
{
fd_to_fd64_mp.reserve(n);
fd64_to_fd_mp.reserve(n);
fd_info_mp.reserve(n);
void fd_manager_t::reserve(int n) {
fd_to_fd64_mp.reserve(n);
fd64_to_fd_mp.reserve(n);
fd_info_mp.reserve(n);
}
u64_t fd_manager_t::create(int fd)
{
assert(!fd_exist(fd));
fd64_t fd64=counter++;
fd_to_fd64_mp[fd]=fd64;
fd64_to_fd_mp[fd64]=fd;
return fd64;
u64_t fd_manager_t::create(int fd) {
assert(!fd_exist(fd));
fd64_t fd64 = counter++;
fd_to_fd64_mp[fd] = fd64;
fd64_to_fd_mp[fd64] = fd;
return fd64;
}
fd_manager_t::fd_manager_t()
{
counter=u32_t(-1);
counter+=100;
reserve(10007);
fd_manager_t::fd_manager_t() {
counter = u32_t(-1);
counter += 100;
reserve(10007);
}
fd_info_t & fd_manager_t::get_info(fd64_t fd64)
{
assert(exist(fd64));
return fd_info_mp[fd64];
fd_info_t& fd_manager_t::get_info(fd64_t fd64) {
assert(exist(fd64));
return fd_info_mp[fd64];
}
int fd_manager_t::exist_info(fd64_t fd64)
{
return fd_info_mp.find(fd64)!=fd_info_mp.end();
int fd_manager_t::exist_info(fd64_t fd64) {
return fd_info_mp.find(fd64) != fd_info_mp.end();
}

View File

@ -12,31 +12,31 @@
//#include "packet.h"
#include "connection.h"
struct fd_info_t
{
//ip_port_t ip_port;
conn_info_t *p_conn_info;
struct fd_info_t {
// ip_port_t ip_port;
conn_info_t *p_conn_info;
};
struct fd_manager_t //conver fd to a uniq 64bit number,avoid fd value conflict caused by close and re-create
//this class is not strictly necessary,it just makes epoll fd handling easier
struct fd_manager_t // conver fd to a uniq 64bit number,avoid fd value conflict caused by close and re-create
// this class is not strictly necessary,it just makes epoll fd handling easier
{
fd_info_t & get_info(fd64_t fd64);
int exist_info(fd64_t);
int exist(fd64_t fd64);
int to_fd(fd64_t);
void fd64_close(fd64_t fd64);
void reserve(int n);
u64_t create(int fd);
fd_manager_t();
private:
u64_t counter;
unordered_map<int,fd64_t> fd_to_fd64_mp;
unordered_map<fd64_t,int> fd64_to_fd_mp;
unordered_map<fd64_t,fd_info_t> fd_info_mp;
int fd_exist(int fd);
//void remove_fd(int fd);
//fd64_t fd_to_fd64(int fd);
fd_info_t &get_info(fd64_t fd64);
int exist_info(fd64_t);
int exist(fd64_t fd64);
int to_fd(fd64_t);
void fd64_close(fd64_t fd64);
void reserve(int n);
u64_t create(int fd);
fd_manager_t();
private:
u64_t counter;
unordered_map<int, fd64_t> fd_to_fd64_mp;
unordered_map<fd64_t, int> fd64_to_fd_mp;
unordered_map<fd64_t, fd_info_t> fd_info_mp;
int fd_exist(int fd);
// void remove_fd(int fd);
// fd64_t fd_to_fd64(int fd);
};
extern fd_manager_t fd_manager;

87
log.cpp Executable file → Normal file
View File

@ -1,62 +1,57 @@
#include "log.h"
#include "misc.h"
int log_level=log_info;
int log_level = log_info;
int enable_log_position=0;
int enable_log_color=1;
int enable_log_position = 0;
int enable_log_color = 1;
void log0(const char * file,const char * function,int line,int level,const char* str, ...) {
void log0(const char* file, const char* function, int line, int level, const char* str, ...) {
if (level > log_level) return;
if (level > log_trace || level < 0) return;
if(level>log_level) return ;
if(level>log_trace||level<0) return ;
time_t timer;
char buffer[100];
struct tm* tm_info;
time(&timer);
tm_info = localtime(&timer);
time_t timer;
char buffer[100];
struct tm* tm_info;
if (enable_log_color)
printf("%s", log_color[level]);
time(&timer);
tm_info = localtime(&timer);
strftime(buffer, 100, "%Y-%m-%d %H:%M:%S", tm_info);
printf("[%s][%s]", buffer, log_text[level]);
if(enable_log_color)
printf("%s",log_color[level]);
if (enable_log_position) printf("[%s,func:%s,line:%d]", file, function, line);
strftime(buffer, 100, "%Y-%m-%d %H:%M:%S", tm_info);
printf("[%s][%s]",buffer,log_text[level]);
va_list vlist;
va_start(vlist, str);
vfprintf(stdout, str, vlist);
va_end(vlist);
if (enable_log_color)
printf("%s", RESET);
if(enable_log_position)printf("[%s,func:%s,line:%d]",file,function,line);
// printf("\n");
// if(enable_log_color)
// printf(log_color[level]);
fflush(stdout);
va_list vlist;
va_start(vlist, str);
vfprintf(stdout, str, vlist);
va_end(vlist);
if(enable_log_color)
printf("%s",RESET);
//printf("\n");
//if(enable_log_color)
//printf(log_color[level]);
fflush(stdout);
if(log_level==log_fatal)
{
about_to_exit=1;
}
if (log_level == log_fatal) {
about_to_exit = 1;
}
}
void log_bare(int level,const char* str, ...)
{
if(level>log_level) return ;
if(level>log_trace||level<0) return ;
if(enable_log_color)
printf("%s",log_color[level]);
va_list vlist;
va_start(vlist, str);
vfprintf(stdout, str, vlist);
va_end(vlist);
if(enable_log_color)
printf("%s",RESET);
fflush(stdout);
void log_bare(int level, const char* str, ...) {
if (level > log_level) return;
if (level > log_trace || level < 0) return;
if (enable_log_color)
printf("%s", log_color[level]);
va_list vlist;
va_start(vlist, str);
vfprintf(stdout, str, vlist);
va_end(vlist);
if (enable_log_color)
printf("%s", RESET);
fflush(stdout);
}

49
log.h Executable file → Normal file
View File

@ -2,53 +2,46 @@
#ifndef UDP2RAW_LOG_MYLOG_H_
#define UDP2RAW_LOG_MYLOG_H_
#include "common.h"
using namespace std;
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RED "\x1B[31m"
#define GRN "\x1B[32m"
#define YEL "\x1B[33m"
#define BLU "\x1B[34m"
#define MAG "\x1B[35m"
#define CYN "\x1B[36m"
#define WHT "\x1B[37m"
#define RESET "\x1B[0m"
const int log_never = 0;
const int log_fatal = 1;
const int log_error = 2;
const int log_warn = 3;
const int log_info = 4;
const int log_debug = 5;
const int log_trace = 6;
const int log_end = 7;
const int log_never=0;
const int log_fatal=1;
const int log_error=2;
const int log_warn=3;
const int log_info=4;
const int log_debug=5;
const int log_trace=6;
const int log_end=7;
const char log_text[][20]={"NEVER","FATAL","ERROR","WARN","INFO","DEBUG","TRACE",""};
const char log_color[][20]={RED,RED,RED,YEL,GRN,MAG,""};
const char log_text[][20] = {"NEVER", "FATAL", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", ""};
const char log_color[][20] = {RED, RED, RED, YEL, GRN, MAG, ""};
extern int log_level;
extern int enable_log_position;
extern int enable_log_color;
#ifdef MY_DEBUG
#define mylog(__first_argu__dummy_abcde__,...) printf(__VA_ARGS__)
#define mylog(__first_argu__dummy_abcde__, ...) printf(__VA_ARGS__)
#else
#define mylog(...) log0(__FILE__,__FUNCTION__,__LINE__,__VA_ARGS__)
#define mylog(...) log0(__FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#endif
//#define mylog(__first_argu__dummy_abcde__,...) {;}
void log0(const char * file,const char * function,int line,int level,const char* str, ...);
void log_bare(int level,const char* str, ...);
void log0(const char* file, const char* function, int line, int level, const char* str, ...);
void log_bare(int level, const char* str, ...);
#endif

130
main.cpp Executable file → Normal file
View File

@ -7,114 +7,100 @@
#include "encrypt.h"
#include "fd_manager.h"
void sigpipe_cb(struct ev_loop *l, ev_signal *w, int revents)
{
mylog(log_info, "got sigpipe, ignored");
void sigpipe_cb(struct ev_loop *l, ev_signal *w, int revents) {
mylog(log_info, "got sigpipe, ignored");
}
void sigterm_cb(struct ev_loop *l, ev_signal *w, int revents)
{
mylog(log_info, "got sigterm, exit");
myexit(0);
void sigterm_cb(struct ev_loop *l, ev_signal *w, int revents) {
mylog(log_info, "got sigterm, exit");
myexit(0);
}
void sigint_cb(struct ev_loop *l, ev_signal *w, int revents)
{
mylog(log_info, "got sigint, exit");
myexit(0);
void sigint_cb(struct ev_loop *l, ev_signal *w, int revents) {
mylog(log_info, "got sigint, exit");
myexit(0);
}
int client_event_loop();
int server_event_loop();
int main(int argc, char *argv[])
{
assert(sizeof(unsigned short)==2);
assert(sizeof(unsigned int)==4);
assert(sizeof(unsigned long long)==8);
int main(int argc, char *argv[]) {
assert(sizeof(unsigned short) == 2);
assert(sizeof(unsigned int) == 4);
assert(sizeof(unsigned long long) == 8);
#ifdef UDP2RAW_MP
init_ws();
init_ws();
#endif
dup2(1, 2);//redirect stderr to stdout
dup2(1, 2); // redirect stderr to stdout
#if defined(__MINGW32__)
enable_log_color=0;
enable_log_color = 0;
#endif
pre_process_arg(argc,argv);
pre_process_arg(argc, argv);
if(program_mode==client_mode)
{
struct ev_loop* loop=ev_default_loop(0);
if (program_mode == client_mode) {
struct ev_loop *loop = ev_default_loop(0);
#if !defined(__MINGW32__)
ev_signal signal_watcher_sigpipe;
ev_signal_init(&signal_watcher_sigpipe, sigpipe_cb, SIGPIPE);
ev_signal_start(loop, &signal_watcher_sigpipe);
ev_signal signal_watcher_sigpipe;
ev_signal_init(&signal_watcher_sigpipe, sigpipe_cb, SIGPIPE);
ev_signal_start(loop, &signal_watcher_sigpipe);
#endif
ev_signal signal_watcher_sigterm;
ev_signal_init(&signal_watcher_sigterm, sigterm_cb, SIGTERM);
ev_signal_start(loop, &signal_watcher_sigterm);
ev_signal signal_watcher_sigterm;
ev_signal_init(&signal_watcher_sigterm, sigterm_cb, SIGTERM);
ev_signal_start(loop, &signal_watcher_sigterm);
ev_signal signal_watcher_sigint;
ev_signal_init(&signal_watcher_sigint, sigint_cb, SIGINT);
ev_signal_start(loop, &signal_watcher_sigint);
}
else
{
ev_signal signal_watcher_sigint;
ev_signal_init(&signal_watcher_sigint, sigint_cb, SIGINT);
ev_signal_start(loop, &signal_watcher_sigint);
} else {
#ifdef UDP2RAW_LINUX
signal(SIGINT, signal_handler);
signal(SIGHUP, signal_handler);
signal(SIGKILL, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGQUIT, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGHUP, signal_handler);
signal(SIGKILL, signal_handler);
signal(SIGTERM, signal_handler);
signal(SIGQUIT, signal_handler);
#else
mylog(log_fatal,"server mode not supported in multi-platform version\n");
myexit(-1);
mylog(log_fatal, "server mode not supported in multi-platform version\n");
myexit(-1);
#endif
}
}
#if !defined(__MINGW32__)
if(geteuid() != 0)
{
mylog(log_warn,"root check failed, it seems like you are using a non-root account. we can try to continue, but it may fail. If you want to run udp2raw as non-root, you have to add iptables rule manually, and grant udp2raw CAP_NET_RAW capability, check README.md in repo for more info.\n");
}
else
{
mylog(log_warn,"you can run udp2raw with non-root account for better security. check README.md in repo for more info.\n");
}
if (geteuid() != 0) {
mylog(log_warn, "root check failed, it seems like you are using a non-root account. we can try to continue, but it may fail. If you want to run udp2raw as non-root, you have to add iptables rule manually, and grant udp2raw CAP_NET_RAW capability, check README.md in repo for more info.\n");
} else {
mylog(log_warn, "you can run udp2raw with non-root account for better security. check README.md in repo for more info.\n");
}
#endif
mylog(log_info,"remote_ip=[%s], make sure this is a vaild IP address\n",remote_addr.get_ip());
mylog(log_info, "remote_ip=[%s], make sure this is a vaild IP address\n", remote_addr.get_ip());
//init_random_number_fd();
srand(get_true_random_number_nz());
const_id=get_true_random_number_nz();
// init_random_number_fd();
srand(get_true_random_number_nz());
const_id = get_true_random_number_nz();
mylog(log_info,"const_id:%x\n",const_id);
mylog(log_info, "const_id:%x\n", const_id);
my_init_keys(key_string,program_mode==client_mode?1:0);
my_init_keys(key_string, program_mode == client_mode ? 1 : 0);
iptables_rule();
iptables_rule();
#ifdef UDP2RAW_LINUX
init_raw_socket();
init_raw_socket();
#endif
if(program_mode==client_mode)
{
client_event_loop();
}
else
{
if (program_mode == client_mode) {
client_event_loop();
} else {
#ifdef UDP2RAW_LINUX
server_event_loop();
server_event_loop();
#else
mylog(log_fatal,"server mode not supported in multi-platform version\n");
myexit(-1);
mylog(log_fatal, "server mode not supported in multi-platform version\n");
myexit(-1);
#endif
}
}
return 0;
return 0;
}

2503
misc.cpp

File diff suppressed because it is too large Load Diff

140
misc.h
View File

@ -8,7 +8,6 @@
#ifndef MISC_H_
#define MISC_H_
#include "common.h"
#include "log.h"
#include "network.h"
@ -26,128 +25,131 @@ extern int enable_dns_resolve;
extern int ttl_value;
const u32_t max_handshake_conn_num = 10000;
const u32_t max_ready_conn_num = 1000;
const u32_t anti_replay_window_size = 4000;
const int max_conv_num = 10000;
const u32_t max_handshake_conn_num=10000;
const u32_t max_ready_conn_num=1000;
const u32_t anti_replay_window_size=4000;
const int max_conv_num=10000;
const u32_t client_handshake_timeout = 5000; // unit ms
const u32_t client_retry_interval = 1000; // ms
const u32_t client_handshake_timeout=5000;//unit ms
const u32_t client_retry_interval=1000;//ms
const u32_t server_handshake_timeout = client_handshake_timeout + 5000; // this should be longer than clients. client retry initially ,server retry passtively
const u32_t server_handshake_timeout=client_handshake_timeout+5000;// this should be longer than clients. client retry initially ,server retry passtively
const int conv_clear_ratio = 30; // conv grabage collecter check 1/30 of all conv one time
const int conn_clear_ratio = 50;
const int conv_clear_min = 1;
const int conn_clear_min = 1;
const int conv_clear_ratio=30; //conv grabage collecter check 1/30 of all conv one time
const int conn_clear_ratio=50;
const int conv_clear_min=1;
const int conn_clear_min=1;
const u32_t conv_clear_interval = 1000; // ms
const u32_t conn_clear_interval = 1000; // ms
const u32_t conv_clear_interval=1000;//ms
const u32_t conn_clear_interval=1000;//ms
const i32_t max_fail_time = 0; // disable
const u32_t heartbeat_interval = 600; // ms
const i32_t max_fail_time=0;//disable
const u32_t timer_interval = 400; // ms. this should be smaller than heartbeat_interval and retry interval;
const u32_t heartbeat_interval=600;//ms
const uint32_t conv_timeout = 180000; // ms. 120 second
// const u32_t conv_timeout=30000; //for test
const u32_t timer_interval=400;//ms. this should be smaller than heartbeat_interval and retry interval;
const u32_t client_conn_timeout = 10000; // ms.
const u32_t client_conn_uplink_timeout = client_conn_timeout + 2000; // ms
const uint32_t conv_timeout=180000; //ms. 120 second
//const u32_t conv_timeout=30000; //for test
const uint32_t server_conn_timeout = conv_timeout + 60000; // ms. this should be 60s+ longer than conv_timeout,so that conv_manager can destruct convs gradually,to avoid latency glicth
// const u32_t server_conn_timeout=conv_timeout+10000;//for test
const u32_t client_conn_timeout=10000;//ms.
const u32_t client_conn_uplink_timeout=client_conn_timeout+2000;//ms
const u32_t iptables_rule_keep_interval = 20; // unit: second;
const uint32_t server_conn_timeout=conv_timeout+60000;//ms. this should be 60s+ longer than conv_timeout,so that conv_manager can destruct convs gradually,to avoid latency glicth
//const u32_t server_conn_timeout=conv_timeout+10000;//for test
enum server_current_state_t { server_idle = 0,
server_handshake1,
server_ready }; // server state machine
enum client_current_state_t { client_idle = 0,
client_tcp_handshake,
client_handshake1,
client_handshake2,
client_ready,
client_tcp_handshake_dummy }; // client state machine
const u32_t iptables_rule_keep_interval=20;//unit: second;
enum raw_mode_t { mode_faketcp = 0,
mode_udp,
mode_icmp,
mode_end };
enum program_mode_t { unset_mode = 0,
client_mode,
server_mode };
enum server_current_state_t {server_idle=0,server_handshake1,server_ready}; //server state machine
enum client_current_state_t {client_idle=0,client_tcp_handshake,client_handshake1,client_handshake2,client_ready,client_tcp_handshake_dummy};//client state machine
enum raw_mode_t{mode_faketcp=0,mode_udp,mode_icmp,mode_end};
enum program_mode_t {unset_mode=0,client_mode,server_mode};
union current_state_t
{
server_current_state_t server_current_state;
client_current_state_t client_current_state;
union current_state_t {
server_current_state_t server_current_state;
client_current_state_t client_current_state;
};
//extern char remote_address[max_address_len];
//extern char local_ip[100], remote_ip[100],source_ip[100];//local_ip is for -l option,remote_ip for -r option,source for --source-ip
//extern u32_t local_ip_uint32,remote_ip_uint32,source_ip_uint32;//convert from last line.
//extern int local_port , remote_port,source_port;//similiar to local_ip remote_ip,buf for port.source_port=0 indicates --source-port is not enabled
// extern char remote_address[max_address_len];
// extern char local_ip[100], remote_ip[100],source_ip[100];//local_ip is for -l option,remote_ip for -r option,source for --source-ip
// extern u32_t local_ip_uint32,remote_ip_uint32,source_ip_uint32;//convert from last line.
// extern int local_port , remote_port,source_port;//similiar to local_ip remote_ip,buf for port.source_port=0 indicates --source-port is not enabled
extern address_t local_addr,remote_addr,source_addr;
extern address_t local_addr, remote_addr, source_addr;
extern my_ip_t bind_addr;
extern int bind_addr_used;
extern int force_source_ip; //if --source-ip is enabled
extern int force_source_ip; // if --source-ip is enabled
extern int force_source_port;
extern int source_port;
extern my_id_t const_id;//an id used for connection recovery,its generated randomly,it never change since its generated
extern my_id_t const_id; // an id used for connection recovery,its generated randomly,it never change since its generated
extern int udp_fd; //for client only. client use this fd to listen and handle udp connection
extern int bind_fd; //bind only,never send or recv. its just a dummy fd for bind,so that other program wont occupy the same port
extern int epollfd; //fd for epoll
extern int timer_fd; //the general timer fd for client and server.for server this is not the only timer find,every connection has a timer fd.
extern int fail_time_counter;//determine if the max_fail_time is reached
extern int epoll_trigger_counter;//for debug only
extern int debug_flag;//for debug only
extern int udp_fd; // for client only. client use this fd to listen and handle udp connection
extern int bind_fd; // bind only,never send or recv. its just a dummy fd for bind,so that other program wont occupy the same port
extern int epollfd; // fd for epoll
extern int timer_fd; // the general timer fd for client and server.for server this is not the only timer find,every connection has a timer fd.
extern int fail_time_counter; // determine if the max_fail_time is reached
extern int epoll_trigger_counter; // for debug only
extern int debug_flag; // for debug only
extern int simple_rule; //deprecated.
extern int keep_rule; //whether to monitor the iptables rule periodly,re-add if losted
extern int auto_add_iptables_rule;//if -a is set
extern int generate_iptables_rule;//if -g is set
extern int generate_iptables_rule_add;// if --gen-add is set
extern int simple_rule; // deprecated.
extern int keep_rule; // whether to monitor the iptables rule periodly,re-add if losted
extern int auto_add_iptables_rule; // if -a is set
extern int generate_iptables_rule; // if -g is set
extern int generate_iptables_rule_add; // if --gen-add is set
extern int retry_on_error;
const int retry_on_error_interval=10;
const int retry_on_error_interval = 10;
extern int debug_resend; // debug only
extern int debug_resend; // debug only
extern char key_string[1000];// -k option
extern char key_string[1000]; // -k option
extern char fifo_file[1000];
extern raw_mode_t raw_mode;
extern u32_t raw_ip_version;
extern program_mode_t program_mode;
extern unordered_map<int, const char*> raw_mode_tostring ;
extern unordered_map<int, const char *> raw_mode_tostring;
extern int about_to_exit;
extern int socket_buf_size;
extern pthread_t keep_thread;
extern int keep_thread_running;
int process_lower_level_arg();
void print_help();
void iptables_rule();
void pre_process_arg(int argc, char *argv[]);//mainly for load conf file;
void pre_process_arg(int argc, char *argv[]); // mainly for load conf file;
int unit_test();
int set_timer(int epollfd,int &timer_fd);
int set_timer_server(int epollfd,int &timer_fd,fd64_t &fd64);
int set_timer(int epollfd, int &timer_fd);
int set_timer_server(int epollfd, int &timer_fd, fd64_t &fd64);
int handle_lower_level(raw_info_t &raw_info);
int add_iptables_rule(const char *);
int clear_iptables_rule();
int iptables_gen_add(const char * s,u32_t const_id);
int iptables_rule_init(const char * s,u32_t const_id,int keep);
int iptables_gen_add(const char *s, u32_t const_id);
int iptables_rule_init(const char *s, u32_t const_id, int keep);
int keep_iptables_rule();
void signal_handler(int sig);
void signal_handler(int sig);
#endif /* MISC_H_ */

View File

@ -2,4 +2,3 @@
#include "my_ev_common.h"
#include "ev.h"

View File

@ -1,6 +1,8 @@
#define EV_STANDALONE 1
#define EV_COMMON void *data; unsigned long long u64;
#define EV_COMMON \
void *data; \
unsigned long long u64;
#define EV_COMPAT3 0
//#include <wepoll.h>
@ -8,11 +10,10 @@
//#define EV_USE_SELECT 1
//#define EV_SELECT_IS_WINSOCKET 1
# define EV_FD_TO_WIN32_HANDLE(fd) (fd)
# define EV_WIN32_HANDLE_TO_FD(handle) (handle)
# define EV_WIN32_CLOSE_FD(fd) closesocket (fd)
# define FD_SETSIZE 4096
#define EV_FD_TO_WIN32_HANDLE(fd) (fd)
#define EV_WIN32_HANDLE_TO_FD(handle) (handle)
#define EV_WIN32_CLOSE_FD(fd) closesocket(fd)
#define FD_SETSIZE 4096
#endif
//#define EV_VERIFY 2

File diff suppressed because it is too large Load Diff

325
network.h
View File

@ -14,7 +14,7 @@ extern int use_tcp_dummy_socket;
extern int seq_mode;
extern int max_seq_mode;
extern int filter_port;
//extern u32_t bind_address_uint32;
// extern u32_t bind_address_uint32;
extern int disable_bpf_filter;
extern int lower_level;
@ -34,7 +34,7 @@ extern int g_packet_buf_cnt;
extern queue_t my_queue;
extern ev_async async_watcher;
extern struct ev_loop* g_default_loop;
extern struct ev_loop *g_default_loop;
extern pthread_mutex_t queue_mutex;
extern int use_pcap_mutex;
@ -47,24 +47,22 @@ extern int send_with_pcap;
extern int pcap_header_captured;
extern int pcap_header_buf[buf_len];
struct icmphdr
{
uint8_t type;
uint8_t code;
uint16_t check_sum;
uint16_t id;
uint16_t seq;
struct icmphdr {
uint8_t type;
uint8_t code;
uint16_t check_sum;
uint16_t id;
uint16_t seq;
};
#endif
struct my_iphdr
{
struct my_iphdr {
#ifdef UDP2RAW_LITTLE_ENDIAN
unsigned char ihl:4;
unsigned char version:4;
unsigned char ihl : 4;
unsigned char version : 4;
#else
unsigned char version:4;
unsigned char ihl:4;
unsigned char version : 4;
unsigned char ihl : 4;
#endif
u_int8_t tos;
u_int16_t tot_len;
@ -76,105 +74,98 @@ struct my_iphdr
u_int32_t saddr;
u_int32_t daddr;
/*The options start here. */
};
struct my_udphdr
{
/*__extension__*/ union
{
struct
{
u_int16_t uh_sport; /* source port */
u_int16_t uh_dport; /* destination port */
u_int16_t uh_ulen; /* udp length */
u_int16_t uh_sum; /* udp checksum */
};
struct
{
u_int16_t source;
u_int16_t dest;
u_int16_t len;
u_int16_t check;
};
};
};
struct my_tcphdr
{
/*__extension__*/ union
{
struct
{
u_int16_t th_sport; /* source port */
u_int16_t th_dport; /* destination port */
u_int32_t th_seq; /* sequence number */
u_int32_t th_ack; /* acknowledgement number */
# ifdef UDP2RAW_LITTLE_ENDIAN
u_int8_t th_x2:4; /* (unused) */
u_int8_t tc_off:4; /* data offset */
# else
u_int8_t th_off:4; /* data offset */
u_int8_t th_x2:4; /* (unused) */
# endif
u_int8_t th_flags;
# define TH_FIN 0x01
# define TH_SYN 0x02
# define TH_RST 0x04
# define TH_PUSH 0x08
# define TH_ACK 0x10
# define TH_URG 0x20
u_int16_t th_win; /* window */
u_int16_t th_sum; /* checksum */
u_int16_t th_urp; /* urgent pointer */
};
struct
{
u_int16_t source;
u_int16_t dest;
u_int32_t seq;
u_int32_t ack_seq;
# ifdef UDP2RAW_LITTLE_ENDIAN
u_int16_t res1:4;
u_int16_t doff:4;
u_int16_t fin:1;
u_int16_t syn:1;
u_int16_t rst:1;
u_int16_t psh:1;
u_int16_t ack:1;
u_int16_t urg:1;
u_int16_t res2:2;
# else
u_int16_t doff:4;
u_int16_t res1:4;
u_int16_t res2:2;
u_int16_t urg:1;
u_int16_t ack:1;
u_int16_t psh:1;
u_int16_t rst:1;
u_int16_t syn:1;
u_int16_t fin:1;
# endif
u_int16_t window;
u_int16_t check;
u_int16_t urg_ptr;
};
struct my_udphdr {
/*__extension__*/ union {
struct
{
u_int16_t uh_sport; /* source port */
u_int16_t uh_dport; /* destination port */
u_int16_t uh_ulen; /* udp length */
u_int16_t uh_sum; /* udp checksum */
};
struct
{
u_int16_t source;
u_int16_t dest;
u_int16_t len;
u_int16_t check;
};
};
};
struct my_ip6hdr
{
# ifdef UDP2RAW_LITTLE_ENDIAN
uint8_t traffic_class_high:4;
uint8_t version:4;
uint8_t flow_label_high:4;
uint8_t traffic_class_low:4;
struct my_tcphdr {
/*__extension__*/ union {
struct
{
u_int16_t th_sport; /* source port */
u_int16_t th_dport; /* destination port */
u_int32_t th_seq; /* sequence number */
u_int32_t th_ack; /* acknowledgement number */
#ifdef UDP2RAW_LITTLE_ENDIAN
u_int8_t th_x2 : 4; /* (unused) */
u_int8_t tc_off : 4; /* data offset */
#else
uint8_t version:4;
uint8_t traffic_class_high:4;
uint8_t traffic_class_low:4;
uint8_t flow_label_high:4;
u_int8_t th_off : 4; /* data offset */
u_int8_t th_x2 : 4; /* (unused) */
#endif
u_int8_t th_flags;
#define TH_FIN 0x01
#define TH_SYN 0x02
#define TH_RST 0x04
#define TH_PUSH 0x08
#define TH_ACK 0x10
#define TH_URG 0x20
u_int16_t th_win; /* window */
u_int16_t th_sum; /* checksum */
u_int16_t th_urp; /* urgent pointer */
};
struct
{
u_int16_t source;
u_int16_t dest;
u_int32_t seq;
u_int32_t ack_seq;
#ifdef UDP2RAW_LITTLE_ENDIAN
u_int16_t res1 : 4;
u_int16_t doff : 4;
u_int16_t fin : 1;
u_int16_t syn : 1;
u_int16_t rst : 1;
u_int16_t psh : 1;
u_int16_t ack : 1;
u_int16_t urg : 1;
u_int16_t res2 : 2;
#else
u_int16_t doff : 4;
u_int16_t res1 : 4;
u_int16_t res2 : 2;
u_int16_t urg : 1;
u_int16_t ack : 1;
u_int16_t psh : 1;
u_int16_t rst : 1;
u_int16_t syn : 1;
u_int16_t fin : 1;
#endif
u_int16_t window;
u_int16_t check;
u_int16_t urg_ptr;
};
};
};
struct my_ip6hdr {
#ifdef UDP2RAW_LITTLE_ENDIAN
uint8_t traffic_class_high : 4;
uint8_t version : 4;
uint8_t flow_label_high : 4;
uint8_t traffic_class_low : 4;
#else
uint8_t version : 4;
uint8_t traffic_class_high : 4;
uint8_t traffic_class_low : 4;
uint8_t flow_label_high : 4;
#endif
u_int16_t flow_label_low;
u_int16_t payload_len;
@ -183,15 +174,14 @@ struct my_ip6hdr
struct in6_addr src;
struct in6_addr dst;
};
};
struct my_icmphdr
{
uint8_t type;
uint8_t code;
uint16_t check_sum;
uint16_t id;
uint16_t seq;
struct my_icmphdr {
uint8_t type;
uint8_t code;
uint16_t check_sum;
uint16_t id;
uint16_t seq;
};
struct pseudo_header {
@ -211,57 +201,53 @@ struct pseudo_header6 {
u_int8_t next_header;
};
struct packet_info_t //todo change this to union
struct packet_info_t // todo change this to union
{
uint8_t protocol;
uint8_t protocol;
// u32_t src_ip;
// u32_t dst_ip;
my_ip_t new_src_ip;
my_ip_t new_dst_ip;
//u32_t src_ip;
//u32_t dst_ip;
my_ip_t new_src_ip;
my_ip_t new_dst_ip;
uint16_t src_port;
uint16_t dst_port;
uint16_t src_port;
uint16_t dst_port;
// tcp_part:
bool syn, ack, psh, rst;
//tcp_part:
bool syn,ack,psh,rst;
u32_t seq, ack_seq;
u32_t seq,ack_seq;
u32_t ack_seq_counter;
u32_t ack_seq_counter;
u32_t ts, ts_ack;
u32_t ts,ts_ack;
uint16_t my_icmp_seq;
uint16_t my_icmp_seq;
bool has_ts;
bool has_ts;
#ifdef UDP2RAW_LINUX
sockaddr_ll addr_ll;
sockaddr_ll addr_ll;
#endif
i32_t data_len;
i32_t data_len;
packet_info_t();
packet_info_t();
};
struct raw_info_t
{
packet_info_t send_info;
packet_info_t recv_info;
//int last_send_len;
//int last_recv_len;
bool peek=0;
//bool csum=1;
u32_t reserved_send_seq;
//uint32_t first_seq,first_ack_seq;
int rst_received=0;
bool disabled=0;
};//g_raw_info;
struct raw_info_t {
packet_info_t send_info;
packet_info_t recv_info;
// int last_send_len;
// int last_recv_len;
bool peek = 0;
// bool csum=1;
u32_t reserved_send_seq;
// uint32_t first_seq,first_ack_seq;
int rst_received = 0;
bool disabled = 0;
}; // g_raw_info;
int init_raw_socket();
@ -270,56 +256,55 @@ void init_filter(int port);
void remove_filter();
#ifdef UDP2RAW_LINUX
int init_ifindex(const char * if_name,int fd,int &index);
int init_ifindex(const char *if_name, int fd, int &index);
#endif
#ifdef UDP2RAW_MP
int init_ifindex(const char * if_name,int &index);
int init_ifindex(const char *if_name, int &index);
#endif
int find_lower_level_info(u32_t ip,u32_t &dest_ip,string &if_name,string &hw);
int find_lower_level_info(u32_t ip, u32_t &dest_ip, string &if_name, string &hw);
int get_src_adress(u32_t &ip,u32_t remote_ip_uint32,int remote_port); //a trick to get src adress for a dest adress,so that we can use the src address in raw socket as source ip
int get_src_adress2(address_t &output_addr,address_t remote_addr);
int get_src_adress(u32_t &ip, u32_t remote_ip_uint32, int remote_port); // a trick to get src adress for a dest adress,so that we can use the src address in raw socket as source ip
int get_src_adress2(address_t &output_addr, address_t remote_addr);
int try_to_list_and_bind(int & bind_fd,u32_t local_ip_uint32,int port); //try to bind to a port,may fail.
int try_to_list_and_bind2(int &fd,address_t address);
int try_to_list_and_bind(int &bind_fd, u32_t local_ip_uint32, int port); // try to bind to a port,may fail.
int try_to_list_and_bind2(int &fd, address_t address);
int client_bind_to_a_new_port(int & bind_fd,u32_t local_ip_uint32);//find a free port and bind to it.
int client_bind_to_a_new_port2(int &fd,const address_t& address);
int client_bind_to_a_new_port(int &bind_fd, u32_t local_ip_uint32); // find a free port and bind to it.
int client_bind_to_a_new_port2(int &fd, const address_t &address);
int discard_raw_packet();
int pre_recv_raw_packet();
int send_raw_ip(raw_info_t &raw_info,const char * payload,int payloadlen);
int send_raw_ip(raw_info_t &raw_info, const char *payload, int payloadlen);
int peek_raw(raw_info_t &peek_info);
int recv_raw_ip(raw_info_t &raw_info,char * &payload,int &payloadlen);
int recv_raw_ip(raw_info_t &raw_info, char *&payload, int &payloadlen);
int send_raw_icmp(raw_info_t &raw_info, const char * payload, int payloadlen);
int send_raw_icmp(raw_info_t &raw_info, const char *payload, int payloadlen);
int send_raw_udp(raw_info_t &raw_info, const char * payload, int payloadlen);
int send_raw_udp(raw_info_t &raw_info, const char *payload, int payloadlen);
int send_raw_tcp(raw_info_t &raw_info,const char * payload, int payloadlen);
int send_raw_tcp(raw_info_t &raw_info, const char *payload, int payloadlen);
int recv_raw_icmp(raw_info_t &raw_info, char *&payload, int &payloadlen);
int recv_raw_udp(raw_info_t &raw_info, char *&payload, int &payloadlen);
int recv_raw_tcp(raw_info_t &raw_info,char * &payload,int &payloadlen);
int recv_raw_tcp(raw_info_t &raw_info, char *&payload, int &payloadlen);
//int send_raw(raw_info_t &raw_info,const char * payload,int payloadlen);
// int send_raw(raw_info_t &raw_info,const char * payload,int payloadlen);
//int recv_raw(raw_info_t &raw_info,char * &payload,int &payloadlen);
// int recv_raw(raw_info_t &raw_info,char * &payload,int &payloadlen);
int send_raw0(raw_info_t &raw_info,const char * payload,int payloadlen);
int send_raw0(raw_info_t &raw_info, const char *payload, int payloadlen);
int recv_raw0(raw_info_t &raw_info,char * &payload,int &payloadlen);
int recv_raw0(raw_info_t &raw_info, char *&payload, int &payloadlen);
int after_send_raw0(raw_info_t &raw_info);
int after_recv_raw0(raw_info_t &raw_info);
#endif /* NETWORK_H_ */

View File

@ -2,124 +2,118 @@
#include <pcap_wrapper.h>
#include <assert.h>
#include <stdio.h>
int (*pcap_loop )(pcap_t *, int, pcap_handler, u_char *);
int (*pcap_breakloop )(pcap_t *);
int (*pcap_loop)(pcap_t *, int, pcap_handler, u_char *);
int (*pcap_breakloop)(pcap_t *);
pcap_t* (*pcap_create)(const char *, char *);
pcap_t *(*pcap_create)(const char *, char *);
int (*pcap_set_snaplen) (pcap_t *, int)=0;
int (*pcap_set_promisc) (pcap_t *, int)=0;
int (*pcap_can_set_rfmon) (pcap_t *)=0;
int (*pcap_set_rfmon )(pcap_t *, int)=0;
int (*pcap_set_timeout)(pcap_t *, int)=0;
int (*pcap_set_buffer_size)(pcap_t *, int)=0;
int (*pcap_activate)(pcap_t *)=0;
int (*pcap_set_snaplen)(pcap_t *, int) = 0;
int (*pcap_set_promisc)(pcap_t *, int) = 0;
int (*pcap_can_set_rfmon)(pcap_t *) = 0;
int (*pcap_set_rfmon)(pcap_t *, int) = 0;
int (*pcap_set_timeout)(pcap_t *, int) = 0;
int (*pcap_set_buffer_size)(pcap_t *, int) = 0;
int (*pcap_activate)(pcap_t *) = 0;
int (*pcap_setfilter)(pcap_t *, struct bpf_program *)=0;
int (*pcap_setdirection)(pcap_t *, pcap_direction_t)=0;
int (*pcap_setfilter)(pcap_t *, struct bpf_program *) = 0;
int (*pcap_setdirection)(pcap_t *, pcap_direction_t) = 0;
int (*pcap_datalink)(pcap_t *)=0;
int (*pcap_datalink)(pcap_t *) = 0;
void (*pcap_freecode)(struct bpf_program *)=0;
void (*pcap_freecode)(struct bpf_program *) = 0;
int (*pcap_compile)(pcap_t *, struct bpf_program *, const char *, int,
bpf_u_int32)=0;
int (*pcap_compile)(pcap_t *, struct bpf_program *, const char *, int,
bpf_u_int32) = 0;
char* (*pcap_geterr)(pcap_t *)=0;
int (*pcap_sendpacket)(pcap_t *, const u_char *, int)=0;
char *(*pcap_geterr)(pcap_t *) = 0;
int (*pcap_sendpacket)(pcap_t *, const u_char *, int) = 0;
char* (*pcap_lookupdev)(char *)=0;
char *(*pcap_lookupdev)(char *) = 0;
int (*pcap_findalldevs)(pcap_if_t **, char *)=0;
int (*pcap_findalldevs)(pcap_if_t **, char *) = 0;
struct init_pcap_t
{
init_pcap_t()
{
init_pcap();
}
}do_it;
struct init_pcap_t {
init_pcap_t() {
init_pcap();
}
static void init_npcap_dll_path()
{
BOOL(WINAPI *SetDllDirectory)(LPCTSTR);
char sysdir_name[512];
int len;
} do_it;
SetDllDirectory = (BOOL(WINAPI *)(LPCTSTR)) GetProcAddress(GetModuleHandle("kernel32.dll"), "SetDllDirectoryA");
if (SetDllDirectory == NULL) {
printf("Error in SetDllDirectory\n");
}
else {
len = GetSystemDirectory(sysdir_name, 480); // be safe
if (!len)
printf("Error in GetSystemDirectory (%d)\n", (int)GetLastError());
strcat(sysdir_name, "\\Npcap");
if (SetDllDirectory(sysdir_name) == 0)
printf("Error in SetDllDirectory(\"System32\\Npcap\")\n");
}
static void init_npcap_dll_path() {
BOOL(WINAPI * SetDllDirectory)
(LPCTSTR);
char sysdir_name[512];
int len;
SetDllDirectory = (BOOL(WINAPI *)(LPCTSTR))GetProcAddress(GetModuleHandle("kernel32.dll"), "SetDllDirectoryA");
if (SetDllDirectory == NULL) {
printf("Error in SetDllDirectory\n");
} else {
len = GetSystemDirectory(sysdir_name, 480); // be safe
if (!len)
printf("Error in GetSystemDirectory (%d)\n", (int)GetLastError());
strcat(sysdir_name, "\\Npcap");
if (SetDllDirectory(sysdir_name) == 0)
printf("Error in SetDllDirectory(\"System32\\Npcap\")\n");
}
}
#define EXPORT_FUN(XXX) do{ XXX= (__typeof__(XXX)) GetProcAddress(wpcap, #XXX); }while(0)
int init_pcap()
{
HMODULE wpcap=LoadLibrary("wpcap.dll");
if(wpcap!=0)
{
printf("using system32/wpcap.dll\n");
}
else
{
init_npcap_dll_path();
//SetDllDirectory("C:\\Windows\\System32\\Npcap\\");
wpcap=LoadLibrary("wpcap.dll");
if(wpcap!=0)
printf("using system32/npcap/wpcap.dll\n");
}
if(wpcap==0)
{
printf("cant not open wpcap.dll, make sure winpcap/npcap is installed\n");
exit(-1);
}
assert(wpcap!=0);
EXPORT_FUN(pcap_loop);
EXPORT_FUN(pcap_breakloop);
EXPORT_FUN(pcap_create);
EXPORT_FUN(pcap_set_snaplen);
EXPORT_FUN(pcap_set_promisc);
EXPORT_FUN(pcap_set_timeout);
EXPORT_FUN(pcap_activate);
EXPORT_FUN(pcap_setfilter);
EXPORT_FUN(pcap_setdirection);
EXPORT_FUN(pcap_datalink);
EXPORT_FUN(pcap_freecode);
EXPORT_FUN(pcap_compile);
EXPORT_FUN(pcap_geterr);
EXPORT_FUN(pcap_sendpacket);
EXPORT_FUN(pcap_lookupdev);
EXPORT_FUN(pcap_findalldevs);
/*
pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
pcap_create = (__typeof__(pcap_create))GetProcAddress(wpcap, "pcap_create");
pcap_set_snaplen = (__typeof__(pcap_set_snaplen))GetProcAddress(wpcap, "pcap_set_snaplen");
pcap_set_promisc = (__typeof__(pcap_set_promisc))GetProcAddress(wpcap, "pcap_set_promisc");
pcap_set_timeout = (__typeof__(pcap_set_timeout))GetProcAddress(wpcap, "pcap_set_timeout");
pcap_activate = (__typeof__(pcap_activate))GetProcAddress(wpcap, "pcap_activate");
pcap_setfilter = (__typeof__(pcap_setfilter))GetProcAddress(wpcap, "pcap_setfilter");
pcap_setdirection = (__typeof__(pcap_setdirection))GetProcAddress(wpcap, "pcap_setdirection");
pcap_datalink = (__typeof__(pcap_datalink))GetProcAddress(wpcap, "pcap_datalink");
pcap_freecode = (__typeof__(pcap_freecode))GetProcAddress(wpcap, "pcap_freecode");
pcap_compile = (__typeof__(pcap_compile))GetProcAddress(wpcap, "pcap_compile");
pcap_geterr = (__typeof__(pcap_geterr))GetProcAddress(wpcap, "pcap_geterr");
pcap_sendpacket = (__typeof__(pcap_sendpacket))GetProcAddress(wpcap, "pcap_sendpacket");
pcap_lookupdev = (__typeof__(pcap_lookupdev))GetProcAddress(wpcap, "pcap_lookupdev");
pcap_findalldevs = (__typeof__(pcap_findalldevs))GetProcAddress(wpcap, "pcap_findalldevs");
//pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
//pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
//pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
*/
return 0;
#define EXPORT_FUN(XXX) \
do { \
XXX = (__typeof__(XXX))GetProcAddress(wpcap, #XXX); \
} while (0)
int init_pcap() {
HMODULE wpcap = LoadLibrary("wpcap.dll");
if (wpcap != 0) {
printf("using system32/wpcap.dll\n");
} else {
init_npcap_dll_path();
// SetDllDirectory("C:\\Windows\\System32\\Npcap\\");
wpcap = LoadLibrary("wpcap.dll");
if (wpcap != 0)
printf("using system32/npcap/wpcap.dll\n");
}
if (wpcap == 0) {
printf("cant not open wpcap.dll, make sure winpcap/npcap is installed\n");
exit(-1);
}
assert(wpcap != 0);
EXPORT_FUN(pcap_loop);
EXPORT_FUN(pcap_breakloop);
EXPORT_FUN(pcap_create);
EXPORT_FUN(pcap_set_snaplen);
EXPORT_FUN(pcap_set_promisc);
EXPORT_FUN(pcap_set_timeout);
EXPORT_FUN(pcap_activate);
EXPORT_FUN(pcap_setfilter);
EXPORT_FUN(pcap_setdirection);
EXPORT_FUN(pcap_datalink);
EXPORT_FUN(pcap_freecode);
EXPORT_FUN(pcap_compile);
EXPORT_FUN(pcap_geterr);
EXPORT_FUN(pcap_sendpacket);
EXPORT_FUN(pcap_lookupdev);
EXPORT_FUN(pcap_findalldevs);
/*
pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
pcap_create = (__typeof__(pcap_create))GetProcAddress(wpcap, "pcap_create");
pcap_set_snaplen = (__typeof__(pcap_set_snaplen))GetProcAddress(wpcap, "pcap_set_snaplen");
pcap_set_promisc = (__typeof__(pcap_set_promisc))GetProcAddress(wpcap, "pcap_set_promisc");
pcap_set_timeout = (__typeof__(pcap_set_timeout))GetProcAddress(wpcap, "pcap_set_timeout");
pcap_activate = (__typeof__(pcap_activate))GetProcAddress(wpcap, "pcap_activate");
pcap_setfilter = (__typeof__(pcap_setfilter))GetProcAddress(wpcap, "pcap_setfilter");
pcap_setdirection = (__typeof__(pcap_setdirection))GetProcAddress(wpcap, "pcap_setdirection");
pcap_datalink = (__typeof__(pcap_datalink))GetProcAddress(wpcap, "pcap_datalink");
pcap_freecode = (__typeof__(pcap_freecode))GetProcAddress(wpcap, "pcap_freecode");
pcap_compile = (__typeof__(pcap_compile))GetProcAddress(wpcap, "pcap_compile");
pcap_geterr = (__typeof__(pcap_geterr))GetProcAddress(wpcap, "pcap_geterr");
pcap_sendpacket = (__typeof__(pcap_sendpacket))GetProcAddress(wpcap, "pcap_sendpacket");
pcap_lookupdev = (__typeof__(pcap_lookupdev))GetProcAddress(wpcap, "pcap_lookupdev");
pcap_findalldevs = (__typeof__(pcap_findalldevs))GetProcAddress(wpcap, "pcap_findalldevs");
//pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
//pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
//pcap_loop = (__typeof__(pcap_loop))GetProcAddress(wpcap, "pcap_loop");
*/
return 0;
}

View File

@ -1,127 +1,117 @@
#pragma once
//#ifdef __cplusplus
//extern "C" {
// extern "C" {
//#endif
//#include <sys/time.h>
//#include <stdint.h>
struct bpf_program
{
char a[4096];
struct bpf_program {
char a[4096];
};
struct pcap_t
{
char a[4096];
struct pcap_t {
char a[4096];
};
typedef unsigned int bpf_u_int32;
typedef struct my_timeval {
int tv_sec;
int tv_usec;
int tv_sec;
int tv_usec;
} my_timeval;
struct pcap_pkthdr {
struct my_timeval ts; /* time stamp */
bpf_u_int32 caplen; /* length of portion present */
bpf_u_int32 len; /* length this packet (off wire) */
struct my_timeval ts; /* time stamp */
bpf_u_int32 caplen; /* length of portion present */
bpf_u_int32 len; /* length this packet (off wire) */
};
typedef enum {
PCAP_D_INOUT = 0,
PCAP_D_IN,
PCAP_D_OUT
PCAP_D_INOUT = 0,
PCAP_D_IN,
PCAP_D_OUT
} pcap_direction_t;
struct pcap_addr {
struct pcap_addr *next;
struct sockaddr *addr; /* address */
struct sockaddr *netmask; /* netmask for that address */
struct sockaddr *broadaddr; /* broadcast address for that address */
struct sockaddr *dstaddr; /* P2P destination address for that address */
struct pcap_addr *next;
struct sockaddr *addr; /* address */
struct sockaddr *netmask; /* netmask for that address */
struct sockaddr *broadaddr; /* broadcast address for that address */
struct sockaddr *dstaddr; /* P2P destination address for that address */
};
struct pcap_if {
struct pcap_if *next;
char *name; /* name to hand to "pcap_open_live()" */
char *description; /* textual description of interface, or NULL */
struct pcap_addr *addresses;
bpf_u_int32 flags; /* PCAP_IF_ interface flags */
struct pcap_if *next;
char *name; /* name to hand to "pcap_open_live()" */
char *description; /* textual description of interface, or NULL */
struct pcap_addr *addresses;
bpf_u_int32 flags; /* PCAP_IF_ interface flags */
};
typedef struct pcap_if pcap_if_t;
typedef struct pcap_addr pcap_addr_t;
typedef unsigned char u_char;
#define PCAP_ERRBUF_SIZE 256
#define DLT_NULL 0 /* BSD loopback encapsulation */
#define DLT_EN10MB 1 /* Ethernet (10Mb) */
#define DLT_EN3MB 2 /* Experimental Ethernet (3Mb) */
#define DLT_AX25 3 /* Amateur Radio AX.25 */
#define DLT_PRONET 4 /* Proteon ProNET Token Ring */
#define DLT_CHAOS 5 /* Chaos */
#define DLT_IEEE802 6 /* 802.5 Token Ring */
#define DLT_ARCNET 7 /* ARCNET, with BSD-style header */
#define DLT_SLIP 8 /* Serial Line IP */
#define DLT_PPP 9 /* Point-to-point Protocol */
#define DLT_FDDI 10 /* FDDI */
#define DLT_LINUX_SLL 113
#define DLT_NULL 0 /* BSD loopback encapsulation */
#define DLT_EN10MB 1 /* Ethernet (10Mb) */
#define DLT_EN3MB 2 /* Experimental Ethernet (3Mb) */
#define DLT_AX25 3 /* Amateur Radio AX.25 */
#define DLT_PRONET 4 /* Proteon ProNET Token Ring */
#define DLT_CHAOS 5 /* Chaos */
#define DLT_IEEE802 6 /* 802.5 Token Ring */
#define DLT_ARCNET 7 /* ARCNET, with BSD-style header */
#define DLT_SLIP 8 /* Serial Line IP */
#define DLT_PPP 9 /* Point-to-point Protocol */
#define DLT_FDDI 10 /* FDDI */
#define DLT_LINUX_SLL 113
#define PCAP_NETMASK_UNKNOWN 0xffffffff
#define PCAP_NETMASK_UNKNOWN 0xffffffff
typedef void (*pcap_handler)(u_char *, const struct pcap_pkthdr *,
const u_char *);
const u_char *);
extern int (*pcap_loop )(pcap_t *, int, pcap_handler, u_char *);
extern int (*pcap_loop)(pcap_t *, int, pcap_handler, u_char *);
extern int (*pcap_breakloop )(pcap_t *);
extern int (*pcap_breakloop)(pcap_t *);
extern pcap_t* (*pcap_create)(const char *, char *);
extern pcap_t *(*pcap_create)(const char *, char *);
extern int (*pcap_set_snaplen) (pcap_t *, int);
extern int (*pcap_set_promisc) (pcap_t *, int);
extern int (*pcap_can_set_rfmon) (pcap_t *);
extern int (*pcap_set_rfmon )(pcap_t *, int);
extern int (*pcap_set_timeout)(pcap_t *, int);
extern int (*pcap_set_buffer_size)(pcap_t *, int);
extern int (*pcap_activate)(pcap_t *);
extern int (*pcap_set_snaplen)(pcap_t *, int);
extern int (*pcap_set_promisc)(pcap_t *, int);
extern int (*pcap_can_set_rfmon)(pcap_t *);
extern int (*pcap_set_rfmon)(pcap_t *, int);
extern int (*pcap_set_timeout)(pcap_t *, int);
extern int (*pcap_set_buffer_size)(pcap_t *, int);
extern int (*pcap_activate)(pcap_t *);
extern int (*pcap_setfilter)(pcap_t *, struct bpf_program *);
extern int (*pcap_setdirection)(pcap_t *, pcap_direction_t);
extern int (*pcap_setfilter)(pcap_t *, struct bpf_program *);
extern int (*pcap_setdirection)(pcap_t *, pcap_direction_t);
extern int (*pcap_datalink)(pcap_t *);
extern int (*pcap_datalink)(pcap_t *);
extern void (*pcap_freecode)(struct bpf_program *);
extern void (*pcap_freecode)(struct bpf_program *);
extern int (*pcap_compile)(pcap_t *, struct bpf_program *, const char *, int,
bpf_u_int32);
extern int (*pcap_compile)(pcap_t *, struct bpf_program *, const char *, int,
bpf_u_int32);
extern char* (*pcap_geterr)(pcap_t *);
extern int (*pcap_sendpacket)(pcap_t *, const u_char *, int);
extern char *(*pcap_geterr)(pcap_t *);
extern int (*pcap_sendpacket)(pcap_t *, const u_char *, int);
extern char* (*pcap_lookupdev)(char *);
extern char *(*pcap_lookupdev)(char *);
extern int (*pcap_findalldevs)(pcap_if_t **, char *);
extern int (*pcap_findalldevs)(pcap_if_t **, char *);
inline int pcap_set_immediate_mode(pcap_t *,int)
{
return 0;
inline int pcap_set_immediate_mode(pcap_t *, int) {
return 0;
}
//#ifdef __cplusplus
//}
//#endif
int init_pcap();

1537
server.cpp

File diff suppressed because it is too large Load Diff