main.cpp 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901
  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<sys/socket.h>
  4. #include<arpa/inet.h>
  5. #include<stdlib.h>
  6. #include<getopt.h>
  7. #include <unistd.h>
  8. #include<errno.h>
  9. #include <fcntl.h>
  10. //#include"aes.h"
  11. #include <sys/epoll.h>
  12. #include <sys/wait.h>
  13. #include<map>
  14. #include<string>
  15. #include<vector>
  16. #include <sys/socket.h> //for socket ofcourse
  17. #include <sys/types.h>
  18. #include <stdlib.h> //for exit(0);
  19. #include <errno.h> //For errno - the error number
  20. #include <netinet/tcp.h> //Provides declarations for tcp header
  21. #include <netinet/ip.h> //Provides declarations for ip header
  22. #include <netinet/if_ether.h>
  23. #include <arpa/inet.h>
  24. #include <fcntl.h>
  25. #include <byteswap.h>
  26. #include <sys/socket.h>
  27. #include <sys/types.h>
  28. #include <arpa/inet.h>
  29. #include <linux/if_ether.h>
  30. #include <linux/filter.h>
  31. #include <sys/time.h>
  32. #include <time.h>
  33. #include <sys/timerfd.h>
  34. #include <set>
  35. #include <encrypt.h>
  36. #include <inttypes.h>
  37. using namespace std;
  38. char local_address[100], remote_address[100],source_address[100];
  39. int local_port = -1, remote_port = -1;
  40. int epollfd ;
  41. uint32_t const_id=0;
  42. uint32_t oppsite_const_id;
  43. uint32_t my_id=0;
  44. uint32_t oppsite_id=0;
  45. uint32_t conv_id=0;
  46. uint32_t oppsite_const_id=0;
  47. const int handshake_timeout=2000;
  48. const int heartbeat_timeout=10000;
  49. const int udp_timeout=3000;
  50. const int heartbeat_interval=1000;
  51. const int timer_interval=500;
  52. const int RETRY_TIME=3;
  53. //const uint16_t tcp_window=50000;
  54. const int buf_len = 65535+100;
  55. const int server_mode=2;
  56. const int client_mode=1;
  57. int prog_mode=0; //0 unset; 1client 2server
  58. const int debug_mode=0;
  59. int bind_fd;
  60. int first_data_packet=0;
  61. const int seq_mode=2; //0 dont increase /1 increase //increase randomly,about every 5 packet
  62. const uint64_t epoll_timer_fd_sn=1;
  63. const uint64_t epoll_raw_recv_fd_sn=2;
  64. uint64_t epoll_udp_fd_sn=256; //udp_fd_sn =256,512,768......the lower 8 bit is not used,to avoid confliction
  65. const int server_nothing=0;
  66. const int server_syn_ack_sent=1;
  67. const int server_heartbeat_sent=2;
  68. const int server_ready=3;
  69. int server_current_state=server_nothing;
  70. long long last_hb_recv_time;
  71. long long last_udp_recv_time=0;
  72. int socket_buf_size=1024*1024*4;
  73. int udp_fd=-1;
  74. int raw_recv_fd;
  75. int raw_send_fd;
  76. const int client_nothing=0;
  77. const int client_syn_sent=1;
  78. const int client_ack_sent=2;
  79. const int client_heartbeat_sent=3;
  80. const int client_ready=4;
  81. int client_current_state=client_nothing;
  82. int retry_counter;
  83. long long last_state_time=0;
  84. long long last_hb_sent_time=0;
  85. char buf[buf_len];
  86. char buf2[buf_len];
  87. char raw_send_buf[buf_len];
  88. char raw_send_buf2[buf_len];
  89. char raw_recv_buf[buf_len];
  90. char raw_recv_buf2[buf_len];
  91. char raw_recv_buf3[buf_len];
  92. char replay_buf[buf_len];
  93. char send_data_buf[buf_len]; //buf for send data and send hb
  94. struct sock_filter code[] = {
  95. { 0x28, 0, 0, 0x0000000c },//0
  96. { 0x15, 0, 10, 0x00000800 },//1
  97. { 0x30, 0, 0, 0x00000017 },//2
  98. { 0x15, 0, 8, 0x00000006 },//3
  99. { 0x28, 0, 0, 0x00000014 },//4
  100. { 0x45, 6, 0, 0x00001fff },//5
  101. { 0xb1, 0, 0, 0x0000000e },//6
  102. { 0x48, 0, 0, 0x0000000e },//7
  103. { 0x15, 2, 0, 0x0000ef32 },//8
  104. { 0x48, 0, 0, 0x00000010 },//9
  105. { 0x15, 0, 1, 0x0000ef32 },//10
  106. { 0x6, 0, 0, 0x0000ffff },//11
  107. { 0x6, 0, 0, 0x00000000 },//12
  108. };
  109. sock_fprog bpf;
  110. uint16_t ip_id=1;
  111. //const int MTU=1440;
  112. struct sockaddr_in udp_old_addr_in;
  113. uint64_t seq=0;
  114. uint8_t key[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16, 0,0,0,0};
  115. const int window_size=2000;
  116. uint32_t get_true_random_number()
  117. {
  118. uint32_t ret;
  119. int fd=open("/dev/urandom",O_RDONLY);
  120. read(fd,&ret,sizeof(ret));
  121. return htonl(ret);
  122. }
  123. struct anti_replay_t
  124. {
  125. uint64_t max_packet_received;
  126. char window[window_size];
  127. char disabled;
  128. anti_replay_t()
  129. {
  130. disabled=0;
  131. max_packet_received=0;
  132. //memset(window,0,sizeof(window)); //not necessary
  133. }
  134. void re_init()
  135. {
  136. disabled=0;
  137. max_packet_received=0;
  138. //memset(window,0,sizeof(window));
  139. }
  140. void disable()
  141. {
  142. disabled=1;
  143. }
  144. void enable()
  145. {
  146. disabled=0;
  147. }
  148. int is_vaild(uint64_t seq)
  149. {
  150. //if(disabled) return 0;
  151. if(seq==max_packet_received) return 0||disabled;
  152. else if(seq>max_packet_received)
  153. {
  154. if(seq-max_packet_received>=window_size)
  155. {
  156. memset(window,0,sizeof(window));
  157. window[seq%window_size]=1;
  158. }
  159. else
  160. {
  161. for (int i=max_packet_received+1;i<seq;i++)
  162. window[i%window_size]=0;
  163. window[seq%window_size]=1;
  164. }
  165. max_packet_received=seq;
  166. return 1;
  167. }
  168. else if(seq<max_packet_received)
  169. {
  170. if(max_packet_received-seq>=window_size) return 0||disabled;
  171. else
  172. {
  173. if (window[seq%window_size]==1) return 0||disabled;
  174. else
  175. {
  176. window[seq%window_size]=1;
  177. return 1;
  178. }
  179. }
  180. }
  181. }
  182. }anti_replay;
  183. int pre_send(char * data, int &data_len)
  184. {
  185. //return 0;
  186. if(data_len<0) return -3;
  187. seq++;
  188. uint32_t seq_high= htonl(seq>>32u);
  189. uint32_t seq_low= htonl((seq<<32u)>>32u);
  190. memcpy(replay_buf,&seq_high,sizeof(uint32_t));
  191. memcpy(replay_buf+sizeof(uint32_t),&seq_low,sizeof(uint32_t));
  192. memcpy(replay_buf+sizeof(uint32_t)*2,data,data_len);
  193. data_len+=sizeof(uint32_t)*2;
  194. //memcpy(data,replay_buf,data_len);
  195. if(my_encrypt((unsigned char*)replay_buf,(unsigned char*)data,data_len,key) <0)
  196. {
  197. printf("encrypt fail\n");
  198. return -1;
  199. }
  200. return 0;
  201. }
  202. int pre_recv(char * data, int &data_len)
  203. {
  204. //return 0;
  205. if(data_len<0) return -1;
  206. //if(data_len<8+16) return -3;
  207. if(my_decrypt((uint8_t*)data,(uint8_t*)replay_buf,data_len,key) <0)
  208. {
  209. printf("decrypt fail\n");
  210. return -1;
  211. }
  212. data_len-=sizeof(uint32_t)*2;
  213. if(data_len<0)
  214. {
  215. printf("data_len<=0\n");
  216. return -2;
  217. }
  218. uint64_t seq_high= ntohl(*((uint32_t*)(replay_buf) ) );
  219. uint32_t seq_low= ntohl(*((uint32_t*)(replay_buf+sizeof(uint32_t)) ) );
  220. uint64_t recv_seq =(seq_high<<32u )+seq_low;
  221. if(anti_replay.is_vaild(recv_seq)!=1)
  222. {
  223. printf("dropped replay packet\n");
  224. return -1;
  225. }
  226. printf("<<<<<%ld,%d,%ld>>>>\n",seq_high,seq_low,recv_seq);
  227. memcpy(data,replay_buf+sizeof(uint32_t)*2,data_len);
  228. return 0;
  229. }
  230. void handler(int num) {
  231. int status;
  232. int pid;
  233. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  234. if (WIFEXITED(status)) {
  235. //printf("The child exit with code %d",WEXITSTATUS(status));
  236. }
  237. }
  238. }
  239. void setnonblocking(int sock) {
  240. int opts;
  241. opts = fcntl(sock, F_GETFL);
  242. if (opts < 0) {
  243. perror("fcntl(sock,GETFL)");
  244. exit(1);
  245. }
  246. opts = opts | O_NONBLOCK;
  247. if (fcntl(sock, F_SETFL, opts) < 0) {
  248. perror("fcntl(sock,SETFL,opts)");
  249. exit(1);
  250. }
  251. }
  252. int set_udp_buf_size(int fd)
  253. {
  254. if(setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &socket_buf_size, sizeof(socket_buf_size))<0)
  255. {
  256. printf("SO_SNDBUFFORCE fail\n");
  257. exit(1);
  258. }
  259. if(setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &socket_buf_size, sizeof(socket_buf_size))<0)
  260. {
  261. printf("SO_RCVBUFFORCE fail\n");
  262. exit(1);
  263. }
  264. return 0;
  265. }
  266. int init_raw_socket()
  267. {
  268. raw_send_fd = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
  269. if(raw_send_fd == -1) {
  270. perror("Failed to create raw_send_fd");
  271. exit(1);
  272. }
  273. if(setsockopt(raw_send_fd, SOL_SOCKET, SO_SNDBUFFORCE, &socket_buf_size, sizeof(socket_buf_size))<0)
  274. {
  275. printf("SO_SNDBUFFORCE fail\n");
  276. exit(1);
  277. }
  278. //raw_fd = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
  279. raw_recv_fd= socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP));
  280. if(setsockopt(raw_recv_fd, SOL_SOCKET, SO_RCVBUFFORCE, &socket_buf_size, sizeof(socket_buf_size))<0)
  281. {
  282. printf("SO_RCVBUFFORCE fail\n");
  283. exit(1);
  284. }
  285. //raw_fd=socket(AF_PACKET , SOCK_RAW , htons(ETH_P_IP));
  286. // packet_recv_sd = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
  287. if(raw_recv_fd == -1) {
  288. //socket creation failed, may be because of non-root privileges
  289. perror("Failed to create raw_recv_fd");
  290. exit(1);
  291. }
  292. //IP_HDRINCL to tell the kernel that headers are included in the packet
  293. int one = 1;
  294. const int *val = &one;
  295. if (setsockopt (raw_send_fd, IPPROTO_IP, IP_HDRINCL, val, sizeof (one)) < 0) {
  296. perror("Error setting IP_HDRINCL");
  297. exit(2);
  298. }
  299. return 0;
  300. }
  301. long long get_current_time()
  302. {
  303. timespec tmp_time;
  304. clock_gettime(CLOCK_MONOTONIC, &tmp_time);
  305. return tmp_time.tv_sec*1000+tmp_time.tv_nsec/(1000*1000ll);
  306. }
  307. const int conv_timeout=60000; //60 second
  308. const int conv_clear_ratio=10;
  309. struct conv_manager
  310. {
  311. map<uint64_t,uint32_t> u64_to_conv; //conv and u64 are both supposed to be uniq
  312. map<uint32_t,uint64_t> conv_to_u64;
  313. map<uint32_t,uint64_t> conv_last_active_time;
  314. map<uint32_t,uint64_t>::iterator clear_it;
  315. conv_manager()
  316. {
  317. clear_it=conv_last_active_time.begin();
  318. }
  319. uint32_t get_new_conv()
  320. {
  321. uint32_t conv=get_true_random_number();
  322. while(conv_to_u64.find(conv)!=conv_to_u64.end())
  323. {
  324. conv=get_true_random_number();
  325. }
  326. return conv;
  327. }
  328. int is_conv_used(uint32_t conv)
  329. {
  330. return conv_to_u64.find(conv)!=conv_to_u64.end();
  331. }
  332. int is_u64_used(uint64_t u64)
  333. {
  334. return u64_to_conv.find(u64)!=u64_to_conv.end();
  335. }
  336. int find_conv_by_u64(uint64_t u64)
  337. {
  338. return u64_to_conv[u64];
  339. }
  340. int find_u64_by_conv(uint32_t conv)
  341. {
  342. return conv_to_u64[conv];
  343. }
  344. int update_active_time(uint32_t conv)
  345. {
  346. return conv_last_active_time[conv]=get_current_time();
  347. }
  348. int insert_conv(uint32_t conv,uint64_t u64)
  349. {
  350. u64_to_conv[u64]=conv;
  351. conv_to_u64[conv]=u64;
  352. conv_last_active_time[conv]=get_current_time();
  353. return 0;
  354. }
  355. int erase_conv(uint32_t conv)
  356. {
  357. uint64_t u64=conv_to_u64[conv];
  358. conv_to_u64.erase(conv);
  359. u64_to_conv.erase(u64);
  360. conv_last_active_time.erase(conv);
  361. return 0;
  362. }
  363. int clean_inactive()
  364. {
  365. map<uint32_t,uint64_t>::iterator old_it;
  366. map<uint32_t,uint64_t>::iterator it;
  367. int cnt=0;
  368. it=clear_it;
  369. int size=conv_last_active_time.size();
  370. int num_to_clean=size/conv_clear_ratio; //clear 1/10 each time,to avoid latency glitch
  371. uint64_t current_time=get_current_time();
  372. for(;;)
  373. {
  374. if(cnt>=num_to_clean) break;
  375. if(conv_last_active_time.begin()==conv_last_active_time.end()) break;
  376. if(it==conv_last_active_time.end())
  377. {
  378. it=conv_last_active_time.begin();
  379. }
  380. if( current_time -it->second >conv_timeout )
  381. {
  382. old_it=it;
  383. it++;
  384. erase_conv(old_it->first);
  385. }
  386. else
  387. {
  388. it++;
  389. }
  390. cnt++;
  391. }
  392. return 0;
  393. }
  394. };
  395. void init_filter(int port)
  396. {
  397. code[8].k=code[10].k=port;
  398. bpf.len = sizeof(code)/sizeof(code[0]);
  399. bpf.filter = code;
  400. //printf("<%d>\n",bpf.len);
  401. int dummy;
  402. int ret=setsockopt(raw_recv_fd, SOL_SOCKET, SO_DETACH_FILTER, &dummy, sizeof(dummy));
  403. if (ret != 0)
  404. {
  405. printf("error remove fiter\n");
  406. perror("filter");
  407. //exit(-1);
  408. }
  409. ret = setsockopt(raw_recv_fd, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
  410. //memset(code,0,sizeof(code));
  411. if (ret != 0)
  412. {
  413. printf("error set fiter\n");
  414. perror("filter");
  415. exit(-1);
  416. }
  417. }
  418. void process_arg(int argc, char *argv[])
  419. {
  420. int i,j,k,opt;
  421. static struct option long_options[] =
  422. {
  423. /* These options set a flag. */
  424. {"source-ip", required_argument, 0, 1},
  425. };
  426. int option_index = 0;
  427. printf("argc=%d ", argc);
  428. for (i = 0; i < argc; i++)
  429. printf("%s ", argv[i]);
  430. printf("\n");
  431. if (argc == 1)
  432. {
  433. printf(
  434. "proc -l [adress:]port -r [adress:]port [-a passwd] [-b passwd]\n");
  435. exit(-1);
  436. }
  437. int no_l = 1, no_r = 1;
  438. while ((opt = getopt_long(argc, argv, "l:r:sch",long_options,&option_index)) != -1) {
  439. //string opt_key;
  440. //opt_key+=opt;
  441. switch (opt) {
  442. case 'l':
  443. no_l = 0;
  444. if (strchr(optarg, ':') != 0) {
  445. sscanf(optarg, "%[^:]:%d", local_address, &local_port);
  446. } else {
  447. strcpy(local_address, "127.0.0.1");
  448. sscanf(optarg, "%d", &local_port);
  449. }
  450. break;
  451. case 'r':
  452. no_r = 0;
  453. if (strchr(optarg, ':') != 0) {
  454. sscanf(optarg, "%[^:]:%d", remote_address, &remote_port);
  455. } else {
  456. strcpy(remote_address, "127.0.0.1");
  457. sscanf(optarg, "%d", &remote_port);
  458. }
  459. break;
  460. case 's':
  461. if(prog_mode==0)
  462. {
  463. prog_mode=server_mode;
  464. }
  465. else
  466. {
  467. printf("-s /-c has already been set,-s option conflict");
  468. exit(-1);
  469. }
  470. break;
  471. case 'c':
  472. if(prog_mode==0)
  473. {
  474. prog_mode=client_mode;
  475. }
  476. else
  477. {
  478. printf("-s /-c has already been set,-c option conflict");
  479. exit(-1);
  480. }
  481. break;
  482. case 'h':
  483. break;
  484. case 1:
  485. //if (strchr(optarg, ':') != 0) {
  486. sscanf(optarg, "%s", source_address);
  487. printf("source: %s",source_address);
  488. //} else {
  489. //printf("format --source-ip :adress");
  490. //exit(-1);
  491. //}
  492. break;
  493. default:
  494. printf("ignore unknown <%s>", optopt);
  495. }
  496. }
  497. if (no_l)
  498. printf("error: -i not found\n");
  499. if (no_r)
  500. printf("error: -o not found\n");
  501. if(prog_mode==0)
  502. printf("error: -s /-r hasnt been set\n");
  503. if (no_l || no_r||prog_mode==0)
  504. {
  505. exit(-1);
  506. }
  507. }
  508. struct packet_info_t
  509. {
  510. //ip_part:
  511. uint32_t src_ip;
  512. uint16_t src_port;
  513. uint32_t dst_ip;
  514. uint16_t dst_port;
  515. //tcp_part:
  516. bool syn,ack,psh;
  517. uint32_t seq,ack_seq;
  518. uint32_t ts,ts_ack;
  519. }g_packet_info;
  520. struct pseudo_header {
  521. u_int32_t source_address;
  522. u_int32_t dest_address;
  523. u_int8_t placeholder;
  524. u_int8_t protocol;
  525. u_int16_t tcp_length;
  526. };
  527. /*
  528. Generic checksum calculation function
  529. */
  530. unsigned short csum(unsigned short *ptr,int nbytes) {
  531. register long sum;
  532. unsigned short oddbyte;
  533. register short answer;
  534. sum=0;
  535. while(nbytes>1) {
  536. sum+=*ptr++;
  537. nbytes-=2;
  538. }
  539. if(nbytes==1) {
  540. oddbyte=0;
  541. *((u_char*)&oddbyte)=*(u_char*)ptr;
  542. sum+=oddbyte;
  543. }
  544. sum = (sum>>16)+(sum & 0xffff);
  545. sum = sum + (sum>>16);
  546. answer=(short)~sum;
  547. return(answer);
  548. }
  549. int send_raw(packet_info_t &info,char * payload,int payloadlen)
  550. {
  551. if(prog_mode==client_mode&& payloadlen!=9 ||prog_mode==server_mode&& payloadlen!=5)
  552. printf("send raw from to %d %d %d %d\n",info.src_ip,info.src_port,info.dst_ip,info.dst_port);
  553. char *data;
  554. memset(raw_send_buf,0,payloadlen+100);
  555. struct iphdr *iph = (struct iphdr *) raw_send_buf;
  556. //TCP header
  557. struct tcphdr *tcph = (struct tcphdr *) (raw_send_buf + sizeof (struct ip));
  558. struct sockaddr_in sin;
  559. struct pseudo_header psh;
  560. //some address resolution
  561. sin.sin_family = AF_INET;
  562. sin.sin_port = htons(info.dst_port);
  563. sin.sin_addr.s_addr = info.dst_ip;
  564. //Fill in the IP Header
  565. iph->ihl = 5;
  566. iph->version = 4;
  567. iph->tos = 0;
  568. iph->id = htonl (ip_id++); //Id of this packet
  569. iph->frag_off = htons(0x4000); //DF set,others are zero
  570. iph->ttl = 64;
  571. iph->protocol = IPPROTO_TCP;
  572. iph->check = 0; //Set to 0 before calculating checksum
  573. iph->saddr = info.src_ip; //Spoof the source ip address
  574. iph->daddr = info.dst_ip;
  575. //TCP Header
  576. tcph->source = htons(info.src_port);
  577. tcph->dest = htons(info.dst_port);
  578. tcph->seq =htonl(info.seq);
  579. tcph->ack_seq = htonl(info.ack_seq);
  580. tcph->fin=0;
  581. tcph->syn=info.syn;
  582. tcph->rst=0;
  583. tcph->psh=info.psh;
  584. tcph->ack=info.ack;
  585. if(tcph->syn==1)
  586. {
  587. tcph->doff = 10; //tcp header size
  588. int i=sizeof (struct iphdr)+20;
  589. raw_send_buf[i++]=0x02;//mss
  590. raw_send_buf[i++]=0x04;
  591. raw_send_buf[i++]=0x05;
  592. raw_send_buf[i++]=0xb4;
  593. //raw_send_buf[i++]=0x01;
  594. //raw_send_buf[i++]=0x01;
  595. raw_send_buf[i++]=0x04; //sack ok
  596. raw_send_buf[i++]=0x02; //sack ok
  597. raw_send_buf[i++]=0x08; //i=6;
  598. raw_send_buf[i++]=0x0a;
  599. *(uint32_t*)(& raw_send_buf[i])=htonl((uint32_t)get_current_time());
  600. i+=4;
  601. *(uint32_t*)(& raw_send_buf[i])=htonl(info.ts_ack);
  602. i+=4;
  603. raw_send_buf[i++]=0x01;
  604. raw_send_buf[i++]=0x03;
  605. raw_send_buf[i++]=0x03;
  606. raw_send_buf[i++]=0x05;
  607. }
  608. else
  609. {
  610. tcph->doff=8;
  611. int i=sizeof (struct iphdr)+20;
  612. raw_send_buf[i++]=0x01;
  613. raw_send_buf[i++]=0x01;
  614. raw_send_buf[i++]=0x08; //i=0;
  615. raw_send_buf[i++]=0x0a;
  616. *(uint32_t*)(& raw_send_buf[i])=htonl((uint32_t)get_current_time());
  617. i+=4;
  618. *(uint32_t*)(& raw_send_buf[i])=htonl(info.ts_ack);
  619. i+=4;
  620. }
  621. tcph->urg=0;
  622. //tcph->window = htons((uint16_t)(1024));
  623. tcph->window = htons((uint16_t)(10240+random()%100));
  624. tcph->check = 0; //leave checksum 0 now, filled later by pseudo header
  625. tcph->urg_ptr = 0;
  626. //Data part
  627. data = raw_send_buf + sizeof(struct iphdr) + tcph->doff*4;
  628. iph->tot_len = sizeof (struct iphdr) + tcph->doff*4 + payloadlen;
  629. memcpy(data , payload, payloadlen);
  630. psh.source_address = info.src_ip;
  631. psh.dest_address = sin.sin_addr.s_addr;
  632. psh.placeholder = 0;
  633. psh.protocol = IPPROTO_TCP;
  634. psh.tcp_length = htons(tcph->doff*4 + payloadlen );
  635. int psize = sizeof(struct pseudo_header) + tcph->doff*4 + payloadlen;
  636. memcpy(raw_send_buf2 , (char*) &psh , sizeof (struct pseudo_header));
  637. memcpy(raw_send_buf2 + sizeof(struct pseudo_header) , tcph , tcph->doff*4 + payloadlen);
  638. tcph->check = csum( (unsigned short*) raw_send_buf2, psize);
  639. //Ip checksum
  640. iph->check = csum ((unsigned short *) raw_send_buf, iph->tot_len);
  641. if(prog_mode==client_mode&& payloadlen!=9 ||prog_mode==server_mode&& payloadlen!=5)
  642. printf("sent seq ack_seq len<%u %u %d>\n",g_packet_info.seq,g_packet_info.ack_seq,payloadlen);
  643. int ret = sendto(raw_send_fd, raw_send_buf, iph->tot_len , 0, (struct sockaddr *) &sin, sizeof (sin));
  644. if(g_packet_info.syn==0&&g_packet_info.ack==1&&payloadlen!=0)
  645. {
  646. if(seq_mode==0)
  647. {
  648. }
  649. else if(seq_mode==1)
  650. {
  651. g_packet_info.seq+=payloadlen;
  652. }
  653. else if(seq_mode==2)
  654. {
  655. if(random()% 5==3 )
  656. g_packet_info.seq+=payloadlen;
  657. }
  658. }
  659. if(debug_mode) printf("<ret:%d>\n",ret);
  660. if(ret<0)
  661. {
  662. perror("raw send error");
  663. //printf("send error\n");
  664. }
  665. return 0;
  666. }
  667. int send_data(packet_info_t &info,char* data,int len,uint32_t id1,uint32_t id2,uint32_t conv_id)
  668. {
  669. int new_len=1+sizeof(my_id)*3+len;
  670. send_data_buf[0]='d';
  671. uint32_t tmp;
  672. tmp=htonl(id1);
  673. memcpy(send_data_buf+1,&tmp,sizeof(my_id));
  674. tmp=htonl(id2);
  675. memcpy(send_data_buf+1+sizeof(my_id),&tmp,sizeof(my_id));
  676. tmp=htonl(conv_id);
  677. memcpy(send_data_buf+1+sizeof(my_id)*2,&tmp,sizeof(my_id));
  678. memcpy(send_data_buf+1+sizeof(my_id)*3,data,len);
  679. if(pre_send(send_data_buf,new_len)<0)
  680. {
  681. return -1;
  682. }
  683. send_raw(info,send_data_buf,new_len);
  684. return 0;
  685. }
  686. const int hb_length=1+3*sizeof(uint32_t);
  687. int send_hb(packet_info_t &info,uint32_t id1,uint32_t id2 ,uint32_t id3)
  688. {
  689. int new_len=1+sizeof(my_id)*3;
  690. send_data_buf[0]='h';
  691. uint32_t tmp;
  692. tmp=htonl(id1);
  693. memcpy(send_data_buf+1,&tmp,sizeof(my_id));
  694. tmp=htonl(id2);
  695. memcpy(send_data_buf+1+sizeof(my_id),&tmp,sizeof(my_id));
  696. tmp=htonl(id3);
  697. memcpy(send_data_buf+1+sizeof(my_id)*2,&tmp,sizeof(my_id));
  698. if(pre_send(send_data_buf,new_len)<0)
  699. {
  700. return -1;
  701. }
  702. send_raw(info,send_data_buf,new_len);
  703. return 0;
  704. }
  705. /*int send_sync()
  706. {
  707. //g_packet_info.seq=3;
  708. g_packet_info.ack=0;
  709. g_packet_info.syn=1;
  710. //g_packet_info.ack_seq=5;
  711. g_packet_info.psh=0;
  712. send_raw(g_packet_info,0,0);
  713. return 0;
  714. }*/
  715. int try_to_list_and_bind(int port)
  716. {
  717. int old_bind_fd=bind_fd;
  718. bind_fd=socket(AF_INET,SOCK_STREAM,0);
  719. if(old_bind_fd!=-1)
  720. {
  721. close(old_bind_fd);
  722. }
  723. struct sockaddr_in temp_bind_addr;
  724. bzero(&temp_bind_addr, sizeof(temp_bind_addr));
  725. temp_bind_addr.sin_family = AF_INET;
  726. temp_bind_addr.sin_port = htons(port);
  727. temp_bind_addr.sin_addr.s_addr = inet_addr(local_address);
  728. if (bind(bind_fd, (struct sockaddr*)&temp_bind_addr, sizeof(temp_bind_addr)) !=0)
  729. {
  730. printf("bind fail\n");
  731. return -1;
  732. }
  733. if(listen(bind_fd, SOMAXCONN) != 0 )
  734. {
  735. printf("listen fail\n");
  736. return -1;
  737. }
  738. return 0;
  739. }
  740. int client_bind_to_a_new_port()
  741. {
  742. int raw_send_port=10000+get_true_random_number()%(65535-10000);
  743. for(int i=0;i<1000;i++)//try 1000 times at max,this should be enough
  744. {
  745. if (try_to_list_and_bind(raw_send_port)==0)
  746. {
  747. return raw_send_port;
  748. }
  749. }
  750. printf("bind port fail\n");
  751. fflush(stdout);
  752. exit(-1);
  753. return -1;////for compiler check
  754. }
  755. int fake_tcp_keep_connection_client() //for client
  756. {
  757. if(debug_mode)printf("timer!\n");
  758. //fflush(stdout);
  759. begin:
  760. if(client_current_state==client_nothing)
  761. {
  762. anti_replay.re_init(); // this is not safe
  763. client_current_state=client_syn_sent;
  764. last_state_time=get_current_time();
  765. printf("state changed from nothing to syn_sent\n");
  766. retry_counter=5;
  767. g_packet_info.src_port=client_bind_to_a_new_port();
  768. printf("using port %d\n",g_packet_info.src_port);
  769. g_packet_info.src_ip=inet_addr(source_address);
  770. init_filter(g_packet_info.src_port);
  771. g_packet_info.seq=get_true_random_number();
  772. g_packet_info.ack_seq=0;//get_true_random_number();
  773. g_packet_info.ts_ack=0;
  774. g_packet_info.ack=0;
  775. g_packet_info.syn=1;
  776. g_packet_info.psh=0;
  777. send_raw(g_packet_info,0,0);
  778. }
  779. if(client_current_state==client_syn_sent &&get_current_time()-last_state_time>handshake_timeout)
  780. {
  781. if(retry_counter==0)
  782. {
  783. client_current_state=client_nothing;
  784. printf("state back to nothing\n");
  785. return 0;
  786. //goto begin;
  787. }
  788. else
  789. {
  790. retry_counter--;
  791. printf("retry send sync\n");
  792. send_raw(g_packet_info,0,0);
  793. last_state_time=get_current_time();
  794. }
  795. }
  796. if(client_current_state==client_ack_sent &&get_current_time()-last_state_time>handshake_timeout)
  797. {
  798. if(retry_counter==0)
  799. {
  800. client_current_state=client_nothing;
  801. printf("state back to nothing\n");
  802. return 0;
  803. //goto begin;
  804. }
  805. else
  806. {
  807. retry_counter--;
  808. send_raw(g_packet_info,0,0);
  809. last_state_time=get_current_time();
  810. printf("retry send ack counter left:%d\n",retry_counter);
  811. }
  812. }
  813. if(client_current_state==client_heartbeat_sent&&get_current_time()-last_state_time>handshake_timeout)
  814. {
  815. if(retry_counter==0)
  816. {
  817. client_current_state=client_nothing;
  818. printf("state back to nothing\n");
  819. return 0;
  820. //goto begin;
  821. }
  822. else
  823. {
  824. retry_counter--;
  825. send_hb(g_packet_info,my_id,oppsite_id,const_id);
  826. last_state_time=get_current_time();
  827. printf("retry send heart_beat counter left:%d\n",retry_counter);
  828. printf("heartbeat sent <%x,%x>\n",oppsite_id,my_id);
  829. }
  830. }
  831. if(client_current_state==client_ready)
  832. {
  833. if(debug_mode)printf("time %lld %lld\n",get_current_time(),last_state_time);
  834. if(get_current_time()-last_hb_recv_time>heartbeat_timeout)
  835. {
  836. client_current_state=client_nothing;
  837. my_id=get_true_random_number();
  838. printf("state back to nothing\n");
  839. return 0;
  840. }
  841. if(get_current_time()-last_hb_sent_time<heartbeat_interval)
  842. {
  843. return 0;
  844. }
  845. if(debug_mode)printf("heartbeat sent <%x,%x>\n",oppsite_id,my_id);
  846. send_hb(g_packet_info,my_id,oppsite_id,const_id);
  847. last_hb_sent_time=get_current_time();
  848. }
  849. }
  850. int fake_tcp_keep_connection_server()
  851. {
  852. //begin:
  853. if(debug_mode) printf("timer!\n");
  854. if(server_current_state==server_nothing)
  855. {
  856. return 0;
  857. }
  858. if(server_current_state==server_syn_ack_sent &&get_current_time()-last_state_time>handshake_timeout )
  859. {
  860. if(retry_counter==0)
  861. {
  862. server_current_state=server_nothing;
  863. printf("state back to nothing\n");
  864. }
  865. else
  866. {
  867. retry_counter--;
  868. send_raw(g_packet_info,0,0);
  869. last_state_time=get_current_time();
  870. printf("resend syn ack\n");
  871. }
  872. }
  873. if(server_current_state==server_heartbeat_sent &&get_current_time()-last_state_time>handshake_timeout)
  874. {
  875. if(retry_counter==0)
  876. {
  877. server_current_state=server_nothing;
  878. printf("state back to nothing\n");
  879. }
  880. else
  881. {
  882. retry_counter--;
  883. send_hb(g_packet_info,my_id,0,const_id);
  884. last_state_time=get_current_time();
  885. printf("half heart beat sent<%x>\n",my_id);
  886. }
  887. }
  888. if(server_current_state==server_ready)
  889. {
  890. if( get_current_time()-last_hb_recv_time>heartbeat_timeout )
  891. {
  892. printf("%lld %lld",get_current_time(),last_state_time);
  893. server_current_state=server_nothing;
  894. printf("changed session id\n");
  895. my_id=get_true_random_number();
  896. printf("state back to nothing\n");
  897. printf("changed state to server_nothing111\n");
  898. return 0;
  899. }
  900. if(get_current_time()-last_hb_sent_time<heartbeat_interval)
  901. {
  902. return 0;
  903. }
  904. send_hb(g_packet_info,my_id,oppsite_id,const_id);
  905. last_hb_sent_time=get_current_time();
  906. if(debug_mode) printf("heart beat sent<%x>\n",my_id);
  907. }
  908. }
  909. int set_timer(int epollfd,int &timer_fd)
  910. {
  911. int ret;
  912. epoll_event ev;
  913. itimerspec its;
  914. memset(&its,0,sizeof(its));
  915. if((timer_fd=timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK)) < 0)
  916. {
  917. printf("timer_fd create error");
  918. exit(1);
  919. }
  920. its.it_interval.tv_nsec=timer_interval*1000ll*1000ll;
  921. its.it_value.tv_nsec=1; //imidiately
  922. timerfd_settime(timer_fd,0,&its,0);
  923. ev.events = EPOLLIN;
  924. ev.data.u64 = epoll_timer_fd_sn;
  925. epoll_ctl(epollfd, EPOLL_CTL_ADD, timer_fd, &ev);
  926. if (ret < 0) {
  927. printf("epoll_ctl return %d\n", ret);
  928. exit(-1);
  929. }
  930. }
  931. int client_raw_recv(iphdr *iph,tcphdr *tcph,char * data,int data_len)
  932. {
  933. if(client_current_state==client_syn_sent )
  934. {
  935. if (!(tcph->syn==1&&tcph->ack==1&&data_len==0)) return 0;
  936. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  937. {
  938. printf("unexpected adress %d %d %d %d\n",iph->saddr,g_packet_info.dst_ip,ntohl(tcph->source),g_packet_info.dst_port);
  939. return 0;
  940. }
  941. g_packet_info.ack_seq=ntohl(tcph->seq)+1;
  942. g_packet_info.psh=0;
  943. g_packet_info.syn=0;
  944. g_packet_info.ack=1;
  945. g_packet_info.seq+=1;
  946. printf("sent ack back\n");
  947. send_raw(g_packet_info,0,0);
  948. client_current_state=client_ack_sent;
  949. last_state_time=get_current_time();
  950. retry_counter=RETRY_TIME;
  951. printf("changed state to client_ack_sent\n");
  952. }
  953. if(client_current_state==client_ack_sent )
  954. {
  955. if( tcph->syn==1||tcph->ack!=1 ||data_len==0)
  956. {
  957. printf("unexpected syn ack or other zero lenght packet\n");
  958. return 0;
  959. }
  960. if(data_len<hb_length||data[0]!='h')
  961. {
  962. printf("not a heartbeat\n");
  963. return 0;
  964. }
  965. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  966. {
  967. printf("unexpected adress\n");
  968. return 0;
  969. }
  970. oppsite_id= ntohl(* ((uint32_t *)&data[1]));
  971. printf("====first hb received %x\n==",oppsite_id);
  972. printf("changed state to client_heartbeat_sent\n");
  973. send_hb(g_packet_info,my_id,oppsite_id,const_id);
  974. client_current_state=client_heartbeat_sent;
  975. last_state_time=get_current_time();
  976. retry_counter=RETRY_TIME;
  977. }
  978. if(client_current_state==client_heartbeat_sent)
  979. {
  980. if( tcph->syn==1||tcph->ack!=1 ||data_len==0)
  981. {
  982. printf("unexpected syn ack or other zero lenght packet\n");
  983. return 0;
  984. }
  985. if(data_len<hb_length||data[0]!='h')
  986. {
  987. printf("not a heartbeat\n");
  988. return 0;
  989. }
  990. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  991. {
  992. printf("unexpected adress\n");
  993. return 0;
  994. }
  995. uint32_t tmp_my_id= ntohl(* ((uint32_t *)&data[1+sizeof(my_id)]));
  996. if(tmp_my_id!=my_id)
  997. {
  998. printf("auth fail\n");
  999. return 0;
  1000. }
  1001. uint32_t tmp_oppsite_session_id=ntohl(* ((uint32_t *)&data[1]));
  1002. if(tmp_oppsite_session_id!=oppsite_id)
  1003. {
  1004. printf("oppsite id mismatch%x %x,ignore\n",tmp_oppsite_session_id,my_id);
  1005. return 0;
  1006. }
  1007. printf("changed state to client_ready\n");
  1008. client_current_state=client_ready;
  1009. last_state_time=get_current_time();
  1010. last_hb_recv_time=get_current_time();
  1011. }
  1012. if(client_current_state==client_ready )
  1013. {
  1014. if( tcph->syn==1||tcph->ack!=1 ||data_len==0)
  1015. {
  1016. printf("unexpected syn ack");
  1017. return 0;
  1018. }
  1019. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  1020. {
  1021. printf("unexpected adress\n");
  1022. return 0;
  1023. }
  1024. if(data_len<hb_length&&data[0]=='h')
  1025. {
  1026. if(debug_mode)printf("heart beat received\n");
  1027. last_hb_recv_time=get_current_time();
  1028. return 0;
  1029. }
  1030. else if(data_len>=sizeof(my_id)*3+1&&data[0]=='d')
  1031. {
  1032. printf("received a data from fake tcp,len:%d\n",data_len);
  1033. uint32_t tmp_session_id= ntohl(* ((uint32_t *)&data[1+sizeof(my_id)]));
  1034. if(tmp_session_id!=my_id)
  1035. {
  1036. printf("client session id mismatch%x %x,ignore\n",tmp_session_id,my_id);
  1037. return 0;
  1038. }
  1039. uint32_t tmp_oppsite_session_id=ntohl(* ((uint32_t *)&data[1]));
  1040. if(tmp_oppsite_session_id!=oppsite_id)
  1041. {
  1042. printf("server session id mismatch%x %x,ignore\n",tmp_oppsite_session_id,my_id);
  1043. return 0;
  1044. }
  1045. uint32_t tmp_conv_id= ntohl(* ((uint32_t *)&data[1+sizeof(my_id)*2]));
  1046. if(tmp_conv_id!=conv_id)
  1047. {
  1048. printf("conv id mismatch%x %x,ignore\n",tmp_oppsite_session_id,my_id);
  1049. return 0;
  1050. }
  1051. last_hb_recv_time=get_current_time();
  1052. int ret=sendto(udp_fd,data+1+sizeof(my_id)*3,data_len -(1+sizeof(my_id)*3),0,(struct sockaddr *)&udp_old_addr_in,sizeof(udp_old_addr_in));
  1053. if(ret<0)perror("ret<0");
  1054. printf("%d byte sent\n",ret);
  1055. }
  1056. return 0;
  1057. }
  1058. }
  1059. int server_raw_recv(iphdr * iph,tcphdr *tcph,char * data,int data_len)
  1060. {
  1061. if(server_current_state==server_nothing)
  1062. {
  1063. anti_replay.re_init();
  1064. if(!( tcph->syn==1&&tcph->ack==0 &&data_len==0)) return 0;
  1065. g_packet_info.dst_port=ntohs(tcph->source);
  1066. g_packet_info.dst_ip=iph->saddr;
  1067. g_packet_info.ack_seq=ntohl(tcph->seq)+1;
  1068. g_packet_info.psh=0;
  1069. g_packet_info.syn=1;
  1070. g_packet_info.ack=1;
  1071. g_packet_info.seq=get_true_random_number();//not necessary to set
  1072. printf("sent syn ack\n");
  1073. send_raw(g_packet_info,0,0);
  1074. printf("changed state to server_syn_ack_sent\n");
  1075. server_current_state=server_syn_ack_sent;
  1076. retry_counter=RETRY_TIME;
  1077. last_state_time=get_current_time();
  1078. }
  1079. else if(server_current_state==server_syn_ack_sent)
  1080. {
  1081. if(!( tcph->syn==0&&tcph->ack==1 &&data_len==0)) return 0;
  1082. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  1083. {
  1084. printf("unexpected adress\n");
  1085. return 0;
  1086. }
  1087. g_packet_info.syn=0;
  1088. g_packet_info.ack=1;
  1089. g_packet_info.seq+=1;////////is this right?
  1090. send_hb(g_packet_info,my_id,0,const_id); // send a hb immidately
  1091. printf("changed state to server_heartbeat_sent\n");
  1092. server_current_state=server_heartbeat_sent;
  1093. last_state_time=get_current_time();
  1094. retry_counter=RETRY_TIME;
  1095. }
  1096. else if(server_current_state==server_heartbeat_sent)//heart beat received
  1097. {
  1098. if( tcph->syn==1||tcph->ack!=1 ||data_len==0) return 0;
  1099. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  1100. {
  1101. printf("unexpected adress\n");
  1102. return 0;
  1103. }
  1104. if(data_len<hb_length||data[0]!='h')
  1105. {
  1106. return 0;
  1107. }
  1108. uint32_t tmp_session_id= ntohl(* ((uint32_t *)&data[1+sizeof(my_id)]));
  1109. printf("received hb %x %x\n",oppsite_id,tmp_session_id);
  1110. if(tmp_session_id!=my_id)
  1111. {
  1112. printf("auth fail!!\n");
  1113. return 0;
  1114. }
  1115. int tmp_oppsite_session_id= ntohl(* ((uint32_t *)&data[1]));
  1116. oppsite_id=tmp_oppsite_session_id;
  1117. send_hb(g_packet_info,my_id,oppsite_id,const_id);
  1118. server_current_state=server_ready;
  1119. last_state_time=get_current_time();
  1120. last_hb_recv_time=get_current_time();
  1121. first_data_packet=1;
  1122. printf("changed state to server_ready\n");
  1123. }
  1124. else if(server_current_state==server_ready)
  1125. {
  1126. if( tcph->syn==1||tcph->ack!=1 ||data_len==0) return 0;
  1127. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  1128. {
  1129. printf("unexpected adress\n");
  1130. return 0;
  1131. }
  1132. if(data[0]=='h'&&data_len>=hb_length)
  1133. {
  1134. uint32_t tmp= ntohl(* ((uint32_t *)&data[1+sizeof(uint32_t)]));
  1135. if(debug_mode)printf("received hb <%x,%x>\n",oppsite_id,tmp);
  1136. last_hb_recv_time=get_current_time();
  1137. }
  1138. else if(data[0]=='d'&&data_len>=sizeof(my_id)*3+1)
  1139. {
  1140. uint32_t tmp_oppsite_session_id=ntohl(* ((uint32_t *)&data[1]));
  1141. uint32_t tmp_session_id=ntohl(* ((uint32_t *)&data[1+sizeof(my_id)]));
  1142. uint32_t tmp_conv_id=ntohl(* ((uint32_t *)&data[1+sizeof(my_id)*2]));
  1143. if(tmp_session_id!=my_id)
  1144. {
  1145. printf("my id mismatch,ignore\n");
  1146. return 0;
  1147. }
  1148. if(tmp_oppsite_session_id!=oppsite_id)
  1149. {
  1150. printf("oppsite id mismatch,ignore\n");
  1151. return 0;
  1152. }
  1153. if(first_data_packet==0&& tmp_conv_id!=conv_id) //magic to find out which one is actually larger
  1154. //consider 0xffffffff+1= 0x0 ,in this case 0x0 is "actually" larger
  1155. {
  1156. uint32_t smaller,bigger;
  1157. smaller=min(conv_id,tmp_conv_id);//smaller in normal sense
  1158. bigger=max(conv_id,tmp_conv_id);
  1159. uint32_t distance=min(bigger-smaller,smaller+(0xffffffff-bigger+1));
  1160. if(distance==bigger-smaller)
  1161. {
  1162. if(bigger==conv_id) //received_session_id is acutally bigger
  1163. {
  1164. printf("old_session_id ,ingored1\n");
  1165. return 0;
  1166. }
  1167. }
  1168. else
  1169. {
  1170. if(smaller==conv_id) //received_session_id is acutally bigger
  1171. {
  1172. printf("old_session_id ,ingored2\n");
  1173. return 0;
  1174. }
  1175. }
  1176. }
  1177. first_data_packet=0;
  1178. if(udp_fd==-1||tmp_conv_id!=conv_id)// this is first send or client changed session
  1179. {
  1180. int old_fd=udp_fd;
  1181. struct sockaddr_in remote_addr_in;
  1182. socklen_t slen = sizeof(sockaddr_in);
  1183. memset(&remote_addr_in, 0, sizeof(remote_addr_in));
  1184. remote_addr_in.sin_family = AF_INET;
  1185. remote_addr_in.sin_port = htons(remote_port);
  1186. remote_addr_in.sin_addr.s_addr = inet_addr(remote_address);
  1187. udp_fd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  1188. set_udp_buf_size(udp_fd);
  1189. printf("created new udp_fd");
  1190. int ret = connect(udp_fd, (struct sockaddr *) &remote_addr_in, slen);
  1191. if(ret!=0)
  1192. {
  1193. printf("udp fd connect fail\n");
  1194. }
  1195. struct epoll_event ev;
  1196. ev.events = EPOLLIN;
  1197. epoll_udp_fd_sn+=256;
  1198. ev.data.u64 = epoll_udp_fd_sn;
  1199. ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, udp_fd, &ev);
  1200. if (ret!= 0) {
  1201. printf("add udp_fd error\n");
  1202. exit(-1);
  1203. }
  1204. if(old_fd!=-1)
  1205. {
  1206. epoll_ctl(epollfd, EPOLL_CTL_DEL, old_fd, 0);
  1207. close(old_fd);
  1208. }
  1209. }
  1210. if(tmp_conv_id!=conv_id)
  1211. {
  1212. conv_id=tmp_conv_id;
  1213. }
  1214. printf("received a data from fake tcp,len:%d\n",data_len);
  1215. last_hb_recv_time=get_current_time();
  1216. int ret=send(udp_fd,data+1+sizeof(my_id)*3,data_len -(1+sizeof(my_id)*3),0);
  1217. printf("%d byte sent\n",ret);
  1218. }
  1219. }
  1220. }
  1221. int on_raw_recv(iphdr * & iph,tcphdr * &tcph,char * &data,int &data_len)
  1222. {
  1223. int size;
  1224. struct sockaddr saddr;
  1225. socklen_t saddr_size;
  1226. saddr_size = sizeof(saddr);
  1227. if(debug_mode)printf("raw!\n");
  1228. size = recvfrom(raw_recv_fd, buf, buf_len, 0 ,&saddr , &saddr_size);
  1229. if(buf[12]!=8||buf[13]!=0)
  1230. {
  1231. printf("not an ipv4 packet!\n");
  1232. fflush(stdout);
  1233. return 0;
  1234. }
  1235. char *ip_begin=buf+14;
  1236. iph = (struct iphdr *) (ip_begin);
  1237. if (!(iph->ihl > 0 && iph->ihl <=60)) {
  1238. if(debug_mode) printf("iph ihl error");
  1239. return 0;
  1240. }
  1241. if (iph->protocol != IPPROTO_TCP) {
  1242. if(debug_mode)printf("iph protocal != tcp\n");
  1243. return 0;
  1244. }
  1245. int ip_len=ntohs(iph->tot_len);
  1246. unsigned short iphdrlen =iph->ihl*4;
  1247. tcph=(struct tcphdr*)(ip_begin+ iphdrlen);
  1248. unsigned short tcphdrlen = tcph->doff*4;
  1249. if (!(tcph->doff > 0 && tcph->doff <=60)) {
  1250. if(debug_mode) printf("tcph error");
  1251. return 0;
  1252. }
  1253. /////ip
  1254. uint32_t ip_chk=csum ((unsigned short *) ip_begin, iphdrlen);
  1255. int psize = sizeof(struct pseudo_header) + ip_len-iphdrlen;
  1256. /////ip end
  1257. ///tcp
  1258. struct pseudo_header psh;
  1259. psh.source_address = iph->saddr;
  1260. psh.dest_address = iph->daddr;
  1261. psh.placeholder = 0;
  1262. psh.protocol = IPPROTO_TCP;
  1263. psh.tcp_length = htons(ip_len-iphdrlen);
  1264. memcpy(raw_recv_buf2 , (char*) &psh , sizeof (struct pseudo_header));
  1265. memcpy(raw_recv_buf2 + sizeof(struct pseudo_header) , ip_begin+ iphdrlen , ip_len-iphdrlen);
  1266. uint16_t tcp_chk = csum( (unsigned short*) raw_recv_buf2, psize);
  1267. if(ip_chk!=0)
  1268. {
  1269. printf("ip header error %d\n",ip_chk);
  1270. return 0;
  1271. }
  1272. if(tcp_chk!=0)
  1273. {
  1274. printf("tcp_chk:%x\n",tcp_chk);
  1275. printf("tcp header error\n");
  1276. return 0;
  1277. }
  1278. char *tcp_begin=raw_recv_buf2+sizeof(struct pseudo_header); //data
  1279. char *tcp_option=raw_recv_buf2+sizeof(struct pseudo_header)+sizeof(tcphdr);
  1280. if(tcph->doff==10)
  1281. {
  1282. if(tcp_option[6]==0x08 &&tcp_option[7]==0x0a)
  1283. {
  1284. g_packet_info.ts_ack= ntohl(*(uint32_t*)(&tcp_option[8]));
  1285. }
  1286. }
  1287. if(tcph->doff==8)
  1288. {
  1289. if(tcp_option[3]==0x08 &&tcp_option[4]==0x0a)
  1290. {
  1291. g_packet_info.ts_ack= ntohl(*(uint32_t*)(&tcp_option[0]));
  1292. }
  1293. }
  1294. if(tcph->rst==1)
  1295. {
  1296. printf("%%%%%%%%%%rst==1%%%%%%%%%%%%%\n");
  1297. }
  1298. ////tcp end
  1299. // char pseudo_tcp_buffer[MTU];
  1300. data_len = ip_len-tcphdrlen-iphdrlen;
  1301. data=ip_begin+tcphdrlen+iphdrlen;
  1302. if(data_len>0&&data[0]=='h')
  1303. {
  1304. printf("recvd <%u %u %d>\n",ntohl(tcph->seq ),ntohl(tcph->ack_seq), data_len);
  1305. }
  1306. if(data_len>0&&tcph->syn==0&&tcph->ack==1)
  1307. {
  1308. //if(seq_increse)
  1309. g_packet_info.ack_seq=ntohl(tcph->seq)+(uint32_t)data_len;
  1310. }
  1311. //printf("%d\n",ip_len);
  1312. /*
  1313. for(int i=0;i<size;i++)
  1314. {
  1315. printf("<%x>",(unsigned char)buf[i]);
  1316. }
  1317. printf("\n");
  1318. for(int i=0;i<data_len;i++)
  1319. {
  1320. printf("<%x>",(unsigned char)data[i]);
  1321. }*/
  1322. if(debug_mode)
  1323. {
  1324. printf("\n");
  1325. printf("<%u,%u,%u,%u,%d>\n",(unsigned int)iphdrlen,(unsigned int)tcphdrlen,(unsigned int)tcph->syn,(unsigned int)tcph->ack,data_len);
  1326. //fflush(stdout);
  1327. }
  1328. return 0;
  1329. }
  1330. int client()
  1331. {
  1332. int i, j, k;int ret;
  1333. init_raw_socket();
  1334. my_id=get_true_random_number();
  1335. conv_id=get_true_random_number();
  1336. //init_filter(source_port);
  1337. g_packet_info.dst_ip=inet_addr(remote_address);
  1338. g_packet_info.dst_port=remote_port;
  1339. //g_packet_info.src_ip=inet_addr(source_address);
  1340. //g_packet_info.src_port=source_port;
  1341. udp_fd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  1342. set_udp_buf_size(udp_fd);
  1343. int yes = 1;
  1344. //setsockopt(udp_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  1345. struct sockaddr_in local_me;
  1346. socklen_t slen = sizeof(sockaddr_in);
  1347. memset(&local_me, 0, sizeof(local_me));
  1348. local_me.sin_family = AF_INET;
  1349. local_me.sin_port = htons(local_port);
  1350. local_me.sin_addr.s_addr = inet_addr(local_address);
  1351. if (bind(udp_fd, (struct sockaddr*) &local_me, slen) == -1) {
  1352. perror("socket bind error");
  1353. exit(1);
  1354. }
  1355. setnonblocking(udp_fd);
  1356. int epollfd = epoll_create1(0);
  1357. const int max_events = 4096;
  1358. struct epoll_event ev, events[max_events];
  1359. if (epollfd < 0) {
  1360. printf("epoll return %d\n", epollfd);
  1361. exit(-1);
  1362. }
  1363. ev.events = EPOLLIN;
  1364. ev.data.u64 = epoll_udp_fd_sn;
  1365. ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, udp_fd, &ev);
  1366. if (ret!=0) {
  1367. printf("add udp_listen_fd error\n");
  1368. exit(-1);
  1369. }
  1370. ev.events = EPOLLIN;
  1371. ev.data.u64 = epoll_raw_recv_fd_sn;
  1372. ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, raw_recv_fd, &ev);
  1373. if (ret!= 0) {
  1374. printf("add raw_fd error\n");
  1375. exit(-1);
  1376. }
  1377. ////add_timer for fake_tcp_keep_connection_client
  1378. //sleep(10);
  1379. memset(&udp_old_addr_in,0,sizeof(sockaddr_in));
  1380. int unbind=1;
  1381. int timer_fd;
  1382. set_timer(epollfd,timer_fd);
  1383. while(1)////////////////////////
  1384. {
  1385. int nfds = epoll_wait(epollfd, events, max_events, 180 * 1000);
  1386. if (nfds < 0) { //allow zero
  1387. printf("epoll_wait return %d\n", nfds);
  1388. exit(-1);
  1389. }
  1390. int n;
  1391. for (n = 0; n < nfds; ++n) {
  1392. if (events[n].data.u64 == epoll_raw_recv_fd_sn)
  1393. {
  1394. iphdr *iph;tcphdr *tcph;char* data;int data_len;
  1395. on_raw_recv(iph,tcph,data,data_len);
  1396. int new_len=data_len;
  1397. memcpy(raw_recv_buf3,data,new_len);
  1398. if(data_len!=0)
  1399. {
  1400. if(pre_recv(raw_recv_buf3,new_len)<0)
  1401. continue;
  1402. }
  1403. client_raw_recv(iph,tcph,raw_recv_buf3,new_len);
  1404. }
  1405. if(events[n].data.u64 ==epoll_timer_fd_sn)
  1406. {
  1407. //printf("timer!\n");
  1408. //fflush(stdout);
  1409. uint64_t value;
  1410. read(timer_fd, &value, 8);
  1411. fake_tcp_keep_connection_client();
  1412. }
  1413. if (events[n].data.u64 == epoll_udp_fd_sn)
  1414. {
  1415. socklen_t recv_len;
  1416. struct sockaddr_in udp_new_addr_in;
  1417. if ((recv_len = recvfrom(udp_fd, buf, buf_len, 0,
  1418. (struct sockaddr *) &udp_new_addr_in, &slen)) == -1) {
  1419. printf("recv_from error");
  1420. exit(1);
  1421. };
  1422. printf("Received packet from %s:%d,len: %d\n", inet_ntoa(udp_new_addr_in.sin_addr),
  1423. ntohs(udp_new_addr_in.sin_port),recv_len);
  1424. if(udp_old_addr_in.sin_addr.s_addr==0&&udp_old_addr_in.sin_port==0)
  1425. {
  1426. memcpy(&udp_old_addr_in,&udp_new_addr_in,sizeof(udp_new_addr_in));
  1427. }
  1428. else if(udp_new_addr_in.sin_addr.s_addr!=udp_old_addr_in.sin_addr.s_addr
  1429. ||udp_new_addr_in.sin_port!=udp_old_addr_in.sin_port)
  1430. {
  1431. if(get_current_time()- last_udp_recv_time <udp_timeout)
  1432. {
  1433. printf("new <ip,port> connected in,ignored,bc last connection is still active\n");
  1434. continue;
  1435. }
  1436. else
  1437. {
  1438. printf("new <ip,port> connected in,accpeted\n");
  1439. memcpy(&udp_old_addr_in,&udp_new_addr_in,sizeof(udp_new_addr_in));
  1440. conv_id++;
  1441. }
  1442. }
  1443. last_udp_recv_time=get_current_time();
  1444. if(client_current_state=client_ready)
  1445. {
  1446. send_data(g_packet_info,buf,recv_len,my_id,oppsite_id,conv_id);
  1447. }
  1448. ////send_data_raw(buf,recv_len);
  1449. }
  1450. }
  1451. }
  1452. return 0;
  1453. }
  1454. int server()
  1455. {
  1456. int i, j, k;int ret;
  1457. g_packet_info.src_ip=inet_addr(local_address);
  1458. g_packet_info.src_port=local_port;
  1459. bind_fd=socket(AF_INET,SOCK_STREAM,0);
  1460. struct sockaddr_in temp_bind_addr;
  1461. bzero(&temp_bind_addr, sizeof(temp_bind_addr));
  1462. temp_bind_addr.sin_family = AF_INET;
  1463. temp_bind_addr.sin_port = htons(local_port);
  1464. temp_bind_addr.sin_addr.s_addr = inet_addr(local_address);
  1465. if (bind(bind_fd, (struct sockaddr*)&temp_bind_addr, sizeof(temp_bind_addr)) !=0)
  1466. {
  1467. printf("bind fail\n");
  1468. exit(-1);
  1469. }
  1470. if(listen(bind_fd, SOMAXCONN) != 0 )
  1471. {
  1472. printf("listen fail\n");
  1473. exit(-1);
  1474. }
  1475. init_raw_socket();
  1476. init_filter(local_port);
  1477. epollfd = epoll_create1(0);
  1478. const int max_events = 4096;
  1479. struct epoll_event ev, events[max_events];
  1480. if (epollfd < 0) {
  1481. printf("epoll return %d\n", epollfd);
  1482. exit(-1);
  1483. }
  1484. ev.events = EPOLLIN;
  1485. ev.data.u64 = epoll_raw_recv_fd_sn;
  1486. ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, raw_recv_fd, &ev);
  1487. if (ret!= 0) {
  1488. printf("add raw_fd error\n");
  1489. exit(-1);
  1490. }
  1491. int timer_fd;
  1492. set_timer(epollfd,timer_fd);
  1493. while(1)////////////////////////
  1494. {
  1495. int nfds = epoll_wait(epollfd, events, max_events, 180 * 1000);
  1496. if (nfds < 0) { //allow zero
  1497. printf("epoll_wait return %d\n", nfds);
  1498. exit(-1);
  1499. }
  1500. int n;
  1501. const int MTU=1440;
  1502. for (n = 0; n < nfds; ++n)
  1503. {
  1504. if (events[n].data.u64 == epoll_udp_fd_sn)
  1505. {
  1506. int recv_len=recv(udp_fd,buf,buf_len,0);
  1507. printf("received a packet from udp_fd,len:%d\n",recv_len);
  1508. if(recv_len<0)
  1509. {
  1510. printf("continue\n");
  1511. perror("wtf?");
  1512. continue;
  1513. //return 0;
  1514. }
  1515. send_data(g_packet_info,buf,recv_len,my_id,oppsite_id,conv_id);
  1516. }
  1517. //printf("%d %d %d %d\n",timer_fd,raw_recv_fd,raw_send_fd,n);
  1518. if (events[n].data.u64 == epoll_timer_fd_sn)
  1519. {
  1520. uint64_t value;
  1521. read(timer_fd, &value, 8);
  1522. fake_tcp_keep_connection_server();
  1523. }
  1524. if (events[n].data.u64 == epoll_raw_recv_fd_sn)
  1525. {
  1526. iphdr *iph;tcphdr *tcph;char* data;int data_len;
  1527. on_raw_recv(iph,tcph,data,data_len);
  1528. int new_len=data_len;
  1529. memcpy(raw_recv_buf3,data,new_len);
  1530. if(data_len!=0)
  1531. {
  1532. if(pre_recv(raw_recv_buf3,new_len)<0)
  1533. continue;
  1534. }
  1535. server_raw_recv(iph,tcph,raw_recv_buf3,new_len);
  1536. }
  1537. }
  1538. }
  1539. return 0;
  1540. }
  1541. int main(int argc, char *argv[])
  1542. {
  1543. const_id=get_true_random_number();
  1544. g_packet_info.ack_seq=get_true_random_number();
  1545. g_packet_info.seq=get_true_random_number();
  1546. int i, j, k;
  1547. signal(SIGCHLD, handler);
  1548. process_arg(argc,argv);
  1549. if(prog_mode==client_mode)
  1550. {
  1551. client();
  1552. }
  1553. else
  1554. {
  1555. server();
  1556. }
  1557. return 0;
  1558. }