main.cpp 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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. using namespace std;
  35. char local_address[100], remote_address[100],source_address[100];
  36. int local_port = -1, remote_port = -1;
  37. int epollfd ;
  38. uint32_t session_id=0;
  39. uint32_t received_session_id=0;
  40. const int buf_len = 20480;
  41. const int server_mode=2;
  42. const int client_mode=1;
  43. int prog_mode=0; //0 unset; 1client 2server
  44. const int RETRY_TIME=3;
  45. const int debug_mode=0;
  46. int bind_fd;
  47. void handler(int num) {
  48. int status;
  49. int pid;
  50. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  51. if (WIFEXITED(status)) {
  52. //printf("The child exit with code %d",WEXITSTATUS(status));
  53. }
  54. }
  55. }
  56. void setnonblocking(int sock) {
  57. int opts;
  58. opts = fcntl(sock, F_GETFL);
  59. if (opts < 0) {
  60. perror("fcntl(sock,GETFL)");
  61. exit(1);
  62. }
  63. opts = opts | O_NONBLOCK;
  64. if (fcntl(sock, F_SETFL, opts) < 0) {
  65. perror("fcntl(sock,SETFL,opts)");
  66. exit(1);
  67. }
  68. }
  69. int udp_fd=-1;
  70. int raw_recv_fd;
  71. int raw_send_fd;
  72. int init_raw_socket()
  73. {
  74. raw_send_fd = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
  75. if(raw_send_fd == -1) {
  76. perror("Failed to create raw_send_fd");
  77. exit(1);
  78. }
  79. //raw_fd = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));
  80. raw_recv_fd= socket(PF_PACKET, SOCK_RAW, htons(ETH_P_IP));
  81. //raw_fd=socket(AF_PACKET , SOCK_RAW , htons(ETH_P_IP));
  82. // packet_recv_sd = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
  83. if(raw_recv_fd == -1) {
  84. //socket creation failed, may be because of non-root privileges
  85. perror("Failed to create raw_recv_fd");
  86. exit(1);
  87. }
  88. //IP_HDRINCL to tell the kernel that headers are included in the packet
  89. int one = 1;
  90. const int *val = &one;
  91. if (setsockopt (raw_send_fd, IPPROTO_IP, IP_HDRINCL, val, sizeof (one)) < 0) {
  92. perror("Error setting IP_HDRINCL");
  93. exit(2);
  94. }
  95. return 0;
  96. }
  97. char buf[buf_len];
  98. char buf2[buf_len];
  99. char raw_send_buf[buf_len];
  100. char raw_send_buf2[buf_len];
  101. struct sock_filter code[] = {
  102. { 0x28, 0, 0, 0x0000000c },//0
  103. { 0x15, 0, 10, 0x00000800 },//1
  104. { 0x30, 0, 0, 0x00000017 },//2
  105. { 0x15, 0, 8, 0x00000006 },//3
  106. { 0x28, 0, 0, 0x00000014 },//4
  107. { 0x45, 6, 0, 0x00001fff },//5
  108. { 0xb1, 0, 0, 0x0000000e },//6
  109. { 0x48, 0, 0, 0x0000000e },//7
  110. { 0x15, 2, 0, 0x0000ef32 },//8
  111. { 0x48, 0, 0, 0x00000010 },//9
  112. { 0x15, 0, 1, 0x0000ef32 },//10
  113. { 0x6, 0, 0, 0x0000ffff },//11
  114. { 0x6, 0, 0, 0x00000000 },//12
  115. };
  116. sock_fprog bpf;
  117. long long get_current_time()
  118. {
  119. timespec tmp_time;
  120. clock_gettime(CLOCK_MONOTONIC, &tmp_time);
  121. return tmp_time.tv_sec*1000+tmp_time.tv_nsec/(1000*1000ll);
  122. }
  123. void init_filter(int port)
  124. {
  125. code[8].k=code[10].k=port;
  126. bpf.len = sizeof(code)/sizeof(code[0]);
  127. bpf.filter = code;
  128. //printf("<%d>\n",bpf.len);
  129. int dummy;
  130. int ret=setsockopt(raw_recv_fd, SOL_SOCKET, SO_DETACH_FILTER, &dummy, sizeof(int));
  131. if (ret != 0)
  132. {
  133. printf("error remove fiter\n");
  134. perror("filter");
  135. //exit(-1);
  136. }
  137. ret = setsockopt(raw_recv_fd, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
  138. //memset(code,0,sizeof(code));
  139. if (ret != 0)
  140. {
  141. printf("error set fiter\n");
  142. perror("filter");
  143. exit(-1);
  144. }
  145. }
  146. void process_arg(int argc, char *argv[])
  147. {
  148. int i,j,k,opt;
  149. static struct option long_options[] =
  150. {
  151. /* These options set a flag. */
  152. {"source-ip", required_argument, 0, 1},
  153. };
  154. int option_index = 0;
  155. printf("argc=%d ", argc);
  156. for (i = 0; i < argc; i++)
  157. printf("%s ", argv[i]);
  158. printf("\n");
  159. if (argc == 1)
  160. {
  161. printf(
  162. "proc -l [adress:]port -r [adress:]port [-a passwd] [-b passwd]\n");
  163. exit(-1);
  164. }
  165. int no_l = 1, no_r = 1;
  166. while ((opt = getopt_long(argc, argv, "l:r:sch",long_options,&option_index)) != -1) {
  167. //string opt_key;
  168. //opt_key+=opt;
  169. switch (opt) {
  170. case 'l':
  171. no_l = 0;
  172. if (strchr(optarg, ':') != 0) {
  173. sscanf(optarg, "%[^:]:%d", local_address, &local_port);
  174. } else {
  175. strcpy(local_address, "127.0.0.1");
  176. sscanf(optarg, "%d", &local_port);
  177. }
  178. break;
  179. case 'r':
  180. no_r = 0;
  181. if (strchr(optarg, ':') != 0) {
  182. sscanf(optarg, "%[^:]:%d", remote_address, &remote_port);
  183. } else {
  184. strcpy(remote_address, "127.0.0.1");
  185. sscanf(optarg, "%d", &remote_port);
  186. }
  187. break;
  188. case 's':
  189. if(prog_mode==0)
  190. {
  191. prog_mode=server_mode;
  192. }
  193. else
  194. {
  195. printf("-s /-c has already been set,-s option conflict");
  196. exit(-1);
  197. }
  198. break;
  199. case 'c':
  200. if(prog_mode==0)
  201. {
  202. prog_mode=client_mode;
  203. }
  204. else
  205. {
  206. printf("-s /-c has already been set,-c option conflict");
  207. exit(-1);
  208. }
  209. break;
  210. case 'h':
  211. break;
  212. case 1:
  213. //if (strchr(optarg, ':') != 0) {
  214. sscanf(optarg, "%s", source_address);
  215. printf("source: %s",source_address);
  216. //} else {
  217. //printf("format --source-ip :adress");
  218. //exit(-1);
  219. //}
  220. break;
  221. default:
  222. printf("ignore unknown <%s>", optopt);
  223. }
  224. }
  225. if (no_l)
  226. printf("error: -i not found\n");
  227. if (no_r)
  228. printf("error: -o not found\n");
  229. if(prog_mode==0)
  230. printf("error: -s /-r hasnt been set\n");
  231. if (no_l || no_r||prog_mode==0)
  232. {
  233. exit(-1);
  234. }
  235. }
  236. struct packet_info_t
  237. {
  238. //ip_part:
  239. uint32_t src_ip;
  240. uint16_t src_port;
  241. uint32_t dst_ip;
  242. uint16_t dst_port;
  243. //tcp_part:
  244. bool syn,ack,psh;
  245. uint32_t seq,ack_seq;
  246. }g_packet_info;
  247. struct pseudo_header {
  248. u_int32_t source_address;
  249. u_int32_t dest_address;
  250. u_int8_t placeholder;
  251. u_int8_t protocol;
  252. u_int16_t tcp_length;
  253. };
  254. /*
  255. Generic checksum calculation function
  256. */
  257. unsigned short csum(unsigned short *ptr,int nbytes) {
  258. register long sum;
  259. unsigned short oddbyte;
  260. register short answer;
  261. sum=0;
  262. while(nbytes>1) {
  263. sum+=*ptr++;
  264. nbytes-=2;
  265. }
  266. if(nbytes==1) {
  267. oddbyte=0;
  268. *((u_char*)&oddbyte)=*(u_char*)ptr;
  269. sum+=oddbyte;
  270. }
  271. sum = (sum>>16)+(sum & 0xffff);
  272. sum = sum + (sum>>16);
  273. answer=(short)~sum;
  274. return(answer);
  275. }
  276. int send_raw(packet_info_t &info,char * payload,int payloadlen)
  277. {
  278. if(prog_mode==client_mode&& payloadlen!=9 ||prog_mode==server_mode&& payloadlen!=5)
  279. printf("send raw from to %d %d %d %d\n",info.src_ip,info.src_port,info.dst_ip,info.dst_port);
  280. char *data;
  281. memset(raw_send_buf,0,payloadlen+100);
  282. struct iphdr *iph = (struct iphdr *) raw_send_buf;
  283. //TCP header
  284. struct tcphdr *tcph = (struct tcphdr *) (raw_send_buf + sizeof (struct ip));
  285. struct sockaddr_in sin;
  286. struct pseudo_header psh;
  287. //Data part
  288. data = raw_send_buf + sizeof(struct iphdr) + sizeof(struct tcphdr);
  289. memcpy(data , payload, payloadlen);
  290. //some address resolution
  291. sin.sin_family = AF_INET;
  292. sin.sin_port = htons(info.dst_port);
  293. sin.sin_addr.s_addr = info.dst_ip;
  294. //Fill in the IP Header
  295. iph->ihl = 5;
  296. iph->version = 4;
  297. iph->tos = 0;
  298. iph->tot_len = sizeof (struct iphdr) + sizeof (struct tcphdr) + payloadlen;
  299. iph->id = htonl (54321); //Id of this packet
  300. iph->frag_off = 0;
  301. iph->ttl = 255;
  302. iph->protocol = IPPROTO_TCP;
  303. iph->check = 0; //Set to 0 before calculating checksum
  304. iph->saddr = info.src_ip; //Spoof the source ip address
  305. iph->daddr = info.dst_ip;
  306. //TCP Header
  307. tcph->source = htons(info.src_port);
  308. tcph->dest = htons(info.dst_port);
  309. tcph->seq =htonl(info.seq);
  310. tcph->ack_seq = htonl(info.ack_seq);
  311. tcph->doff = 5; //tcp header size
  312. tcph->fin=0;
  313. tcph->syn=info.syn;
  314. tcph->rst=0;
  315. tcph->psh=info.psh;
  316. tcph->ack=info.ack;
  317. tcph->urg=0;
  318. tcph->window = htons((uint16_t)129600);
  319. tcph->check = 0; //leave checksum 0 now, filled later by pseudo header
  320. tcph->urg_ptr = 0;
  321. psh.source_address = info.src_ip;
  322. psh.dest_address = sin.sin_addr.s_addr;
  323. psh.placeholder = 0;
  324. psh.protocol = IPPROTO_TCP;
  325. psh.tcp_length = htons(sizeof(struct tcphdr) + payloadlen );
  326. int psize = sizeof(struct pseudo_header) + sizeof(struct tcphdr) + payloadlen;
  327. memcpy(raw_send_buf2 , (char*) &psh , sizeof (struct pseudo_header));
  328. memcpy(raw_send_buf2 + sizeof(struct pseudo_header) , tcph , sizeof(struct tcphdr) + payloadlen);
  329. tcph->check = csum( (unsigned short*) raw_send_buf2, psize);
  330. //Ip checksum
  331. iph->check = csum ((unsigned short *) raw_send_buf, iph->tot_len);
  332. if(prog_mode==client_mode&& payloadlen!=9 ||prog_mode==server_mode&& payloadlen!=5)
  333. printf("sent seq ack_seq len<%u %u %d>\n",g_packet_info.seq,g_packet_info.ack_seq,payloadlen);
  334. int ret = sendto(raw_send_fd, raw_send_buf, iph->tot_len , 0, (struct sockaddr *) &sin, sizeof (sin));
  335. if(g_packet_info.syn==0&&g_packet_info.ack==1&&payloadlen!=0)
  336. {
  337. g_packet_info.seq+=payloadlen;
  338. }
  339. if(debug_mode) printf("<ret:%d>\n",ret);
  340. if(ret<0)
  341. {
  342. perror("raw send error");
  343. //printf("send error\n");
  344. }
  345. return 0;
  346. }
  347. char send_data_buf[buf_len];
  348. int send_data(packet_info_t &info,char* data,int len,uint32_t id1,uint32_t id2 )
  349. {
  350. int new_len=1+sizeof(session_id)*2+len;
  351. send_data_buf[0]='d';
  352. uint32_t tmp;
  353. tmp=htonl(id1);
  354. memcpy(send_data_buf+1,&tmp,sizeof(session_id));
  355. tmp=htonl(id2);
  356. memcpy(send_data_buf+1+sizeof(session_id),&tmp,sizeof(session_id));
  357. memcpy(send_data_buf+1+sizeof(session_id)*2,data,len);
  358. send_raw(info,send_data_buf,new_len);
  359. return 0;
  360. }
  361. int send_sync()
  362. {
  363. //g_packet_info.seq=3;
  364. g_packet_info.ack=0;
  365. g_packet_info.syn=1;
  366. //g_packet_info.ack_seq=5;
  367. g_packet_info.psh=0;
  368. send_raw(g_packet_info,0,0);
  369. return 0;
  370. }
  371. const int client_nothing=0;
  372. const int client_syn_sent=1;
  373. const int client_ack_sent=2;
  374. const int client_ready=3;
  375. int client_current_state=client_nothing;
  376. int retry_counter;
  377. long long last_state_time;
  378. uint32_t get_true_random_number()
  379. {
  380. uint32_t ret;
  381. int fd=open("/dev/urandom",O_RDONLY);
  382. read(fd,&ret,sizeof(ret));
  383. return htonl(ret);
  384. }
  385. const int server_nothing=0;
  386. const int server_syn_ack_sent=1;
  387. const int server_heartbeat_sent=2;
  388. const int server_ready=3;
  389. int server_current_state=server_nothing;
  390. long long last_hb_recv_time;
  391. long long last_udp_recv_time=0;
  392. int try_to_list_and_bind(int port)
  393. {
  394. int old_bind_fd=bind_fd;
  395. bind_fd=socket(AF_INET,SOCK_STREAM,0);
  396. if(old_bind_fd!=-1)
  397. {
  398. close(old_bind_fd);
  399. }
  400. struct sockaddr_in temp_bind_addr;
  401. bzero(&temp_bind_addr, sizeof(temp_bind_addr));
  402. temp_bind_addr.sin_family = AF_INET;
  403. temp_bind_addr.sin_port = htons(local_port);
  404. temp_bind_addr.sin_addr.s_addr = inet_addr(local_address);
  405. if (bind(bind_fd, (struct sockaddr*)&temp_bind_addr, sizeof(temp_bind_addr)) !=0)
  406. {
  407. printf("bind fail\n");
  408. return -1;
  409. }
  410. if(listen(bind_fd, SOMAXCONN) != 0 )
  411. {
  412. printf("listen fail\n");
  413. return -1;
  414. }
  415. return 0;
  416. }
  417. int client_bind_to_a_new_port()
  418. {
  419. int raw_send_port=10000+get_true_random_number()%(65535-10000);
  420. for(int i=0;i<1000;i++)
  421. {
  422. if (try_to_list_and_bind(raw_send_port)==0)
  423. {
  424. return raw_send_port;
  425. }
  426. }
  427. printf("bind port fail\n");
  428. fflush(stdout);
  429. exit(-1);
  430. return -1;////for compiler check
  431. }
  432. int fake_tcp_keep_connection_client() //for client
  433. {
  434. //printf("timer!");
  435. //fflush(stdout);
  436. begin:
  437. if(client_current_state==client_nothing)
  438. {
  439. client_current_state=client_syn_sent;
  440. last_state_time=get_current_time();
  441. printf("state changed from nothing to syn_sent\n");
  442. retry_counter=5;
  443. g_packet_info.src_port=client_bind_to_a_new_port();
  444. printf("using port %d\n",g_packet_info.src_port);
  445. g_packet_info.src_ip=inet_addr(source_address);
  446. init_filter(g_packet_info.src_port);
  447. g_packet_info.seq=get_true_random_number();
  448. g_packet_info.ack_seq=get_true_random_number();
  449. send_sync(/*sync*/);//send sync
  450. }
  451. if(client_current_state==client_syn_sent &&get_current_time()-last_state_time>1000ll)
  452. {
  453. if(retry_counter==0)
  454. {
  455. client_current_state=client_nothing;
  456. printf("state back to nothing\n");
  457. goto begin;
  458. }
  459. else
  460. {
  461. retry_counter--;
  462. printf("retry send sync\n");
  463. send_sync(/*sync*/);//send sync again
  464. last_state_time=get_current_time();
  465. }
  466. }
  467. if(client_current_state==client_ack_sent &&get_current_time()-last_state_time>1000)
  468. {
  469. printf("!!!!!\n");
  470. fflush(stdout);
  471. if(retry_counter==0)
  472. {
  473. client_current_state=client_nothing;
  474. printf("state back to nothing\n");
  475. goto begin;
  476. }
  477. else
  478. {
  479. retry_counter--;
  480. send_raw(g_packet_info,0,0);
  481. last_state_time=get_current_time();
  482. printf("retry send ack counter left:%d\n",retry_counter);
  483. fflush(stdout);
  484. }
  485. }
  486. if(client_current_state==client_ready)
  487. {
  488. if(debug_mode)printf("time %lld %lld\n",get_current_time(),last_state_time);
  489. if(get_current_time()-last_hb_recv_time>5*1000ll)
  490. {
  491. client_current_state=client_nothing;
  492. printf("state back to nothing\n");
  493. return 0;
  494. }
  495. g_packet_info.syn=0;
  496. g_packet_info.ack=1;
  497. if(debug_mode)printf("heartbeat sent <%x,%x>\n",received_session_id,session_id);
  498. buf[0]='h';
  499. uint32_t tmp;
  500. tmp=htonl(received_session_id);
  501. memcpy(buf+1+sizeof(session_id),&tmp,sizeof(session_id));
  502. tmp=htonl(session_id);
  503. memcpy(buf+1,&tmp,sizeof(session_id));
  504. send_raw(g_packet_info,buf,sizeof(session_id)*2+1);
  505. //last_time=get_current_time();
  506. }
  507. }
  508. int fake_tcp_keep_connection_server()
  509. {
  510. //begin:
  511. if(debug_mode) printf("timerxxxx!\n");
  512. if(server_current_state==server_nothing)
  513. {
  514. return 0;
  515. }
  516. if(server_current_state==server_syn_ack_sent &&get_current_time()-last_state_time>1000ll )
  517. {
  518. if(retry_counter==0)
  519. {
  520. server_current_state=server_nothing;
  521. printf("state back to nothing\n");
  522. //send_raw(g_packet_info,0,0);
  523. }
  524. else
  525. {
  526. retry_counter--;
  527. send_raw(g_packet_info,0,0);
  528. last_state_time=get_current_time();
  529. printf("resend syn ack\n");
  530. }
  531. //send_raw(/*syn ack*/);
  532. }
  533. if(server_current_state==server_heartbeat_sent||server_current_state==server_ready)
  534. {
  535. if(get_current_time()-last_hb_recv_time>5*1000ll)
  536. {
  537. printf("%lld %lld",get_current_time(),last_state_time);
  538. server_current_state=server_nothing;
  539. printf("state back to nothing\n");
  540. printf("changed state to server_nothing111\n");
  541. return 0;
  542. }
  543. g_packet_info.syn=0;
  544. g_packet_info.ack=1;
  545. //g_packet_info.psh=1;
  546. buf[0]='h';
  547. uint32_t tmp;
  548. tmp=htonl(session_id);
  549. memcpy(buf+1,&tmp,sizeof(session_id));
  550. send_raw(g_packet_info,buf,sizeof(session_id)+1);
  551. //last_time=get_current_time();
  552. if(debug_mode) printf("heart beat sent<%x>\n",session_id);
  553. fflush(stdout);
  554. }
  555. }
  556. struct sockaddr_in udp_old_addr_in;
  557. int set_timer(int epollfd,int &timer_fd)
  558. {
  559. int ret;
  560. epoll_event ev;
  561. itimerspec its;
  562. memset(&its,0,sizeof(its));
  563. if((timer_fd=timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK)) < 0)
  564. {
  565. printf("timer_fd create error");
  566. exit(1);
  567. }
  568. its.it_interval.tv_sec=1;
  569. its.it_value.tv_sec=1;
  570. timerfd_settime(timer_fd,0,&its,0);
  571. ev.events = EPOLLIN;
  572. ev.data.fd = timer_fd;
  573. epoll_ctl(epollfd, EPOLL_CTL_ADD, timer_fd, &ev);
  574. if (ret < 0) {
  575. printf("epoll_ctl return %d\n", ret);
  576. exit(-1);
  577. }
  578. }
  579. const int MTU=1440;
  580. int client_raw_recv(iphdr * iph,tcphdr *tcph,char * data,int data_len)
  581. {
  582. if(client_current_state==client_syn_sent )
  583. {
  584. if (!(tcph->syn==1&&tcph->ack==1&&data_len==0)) return 0;
  585. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  586. {
  587. printf("unexpected adress %d %d %d %d\n",iph->saddr,g_packet_info.dst_ip,ntohl(tcph->source),g_packet_info.dst_port);
  588. return 0;
  589. }
  590. g_packet_info.ack_seq=ntohl(tcph->seq)+1;
  591. g_packet_info.psh=0;
  592. g_packet_info.syn=0;
  593. g_packet_info.ack=1;
  594. g_packet_info.seq+=1;
  595. printf("sent ack back\n");
  596. fflush(stdout);
  597. send_raw(g_packet_info,0,0);
  598. client_current_state=client_ack_sent;
  599. printf("changed state to client_ack_sent\n");
  600. last_state_time=get_current_time();
  601. retry_counter=RETRY_TIME;
  602. }
  603. if(client_current_state==client_ack_sent )
  604. {
  605. //printf(" i m here\n");
  606. //fflush(stdout);
  607. if( tcph->syn==1||tcph->ack!=1 ||data_len==0)
  608. {
  609. printf("unexpected syn ack");
  610. return 0;
  611. }
  612. if(data_len!=sizeof(session_id)+1||data[0]!='h')
  613. {
  614. return 0;
  615. }
  616. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  617. {
  618. printf("unexpected adress\n");
  619. return 0;
  620. }
  621. received_session_id= ntohl(* ((uint32_t *)&data[1]));
  622. printf("====first hb received %x\n==",received_session_id);
  623. client_current_state=client_ready;
  624. printf("changed state to client_ready\n");
  625. //send_raw(g_packet_info,"hb",strlen("hb"));
  626. }
  627. if(client_current_state==client_ready )
  628. {
  629. if( tcph->syn==1||tcph->ack!=1 ||data_len==0)
  630. {
  631. printf("unexpected syn ack");
  632. return 0;
  633. }
  634. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  635. {
  636. printf("unexpected adress\n");
  637. return 0;
  638. }
  639. if(data_len==sizeof(session_id)+1&&data[0]=='h')
  640. {
  641. if(debug_mode)printf("heart beat received\n");
  642. last_hb_recv_time=get_current_time();
  643. return 0;
  644. }
  645. else if(data_len>=sizeof(session_id)*2+1&&data[0]=='d')
  646. {
  647. printf("received a data from fake tcp,len:%d\n",data_len);
  648. uint32_t tmp_session_id= ntohl(* ((uint32_t *)&data[1]));
  649. if(tmp_session_id!=session_id)
  650. {
  651. printf("client session id mismatch%x %x,ignore\n",tmp_session_id,session_id);
  652. return 0;
  653. }
  654. int ret=sendto(udp_fd,data+1+sizeof(session_id)*2,data_len -(1+sizeof(session_id)*2),0,(struct sockaddr *)&udp_old_addr_in,sizeof(udp_old_addr_in));
  655. if(ret<0)perror("ret<0");
  656. printf("%d byte sent\n",ret);
  657. }
  658. return 0;
  659. }
  660. }
  661. #include <set>
  662. using namespace std;
  663. set<uint32_t> died_session_id;
  664. int server_raw_recv(iphdr * iph,tcphdr *tcph,char * data,int data_len)
  665. {
  666. if(server_current_state==server_nothing)
  667. {
  668. if(!( tcph->syn==1&&tcph->ack==0 &&data_len==0)) return 0;
  669. g_packet_info.dst_port=ntohs(tcph->source);
  670. g_packet_info.dst_ip=iph->saddr;
  671. g_packet_info.ack_seq=ntohl(tcph->seq)+1;
  672. g_packet_info.psh=0;
  673. g_packet_info.syn=1;
  674. g_packet_info.ack=1;
  675. g_packet_info.seq;//dont need to set
  676. printf("sent syn ack\n");
  677. fflush(stdout);
  678. send_raw(g_packet_info,0,0);
  679. server_current_state=server_syn_ack_sent;
  680. printf("changed state to server_syn_ack_sent\n");
  681. retry_counter=RETRY_TIME;
  682. last_state_time=get_current_time();
  683. }
  684. else if(server_current_state==server_syn_ack_sent)
  685. {
  686. if(!( tcph->syn==0&&tcph->ack==1 &&data_len==0)) return 0;
  687. server_current_state=server_heartbeat_sent;
  688. g_packet_info.syn=0;
  689. g_packet_info.ack=1;
  690. g_packet_info.seq+=1;////////is this right?
  691. //send_raw(g_packet_info,"hb",strlen("hb"));
  692. printf("changed state to server_heartbeat_sent\n");
  693. last_hb_recv_time=get_current_time(); //this ack is counted as hearbeat
  694. last_state_time=get_current_time();
  695. session_id=get_true_random_number();
  696. }
  697. else if(server_current_state==server_heartbeat_sent)//heart beat received
  698. {
  699. if( tcph->syn==1||tcph->ack!=1 ||data_len==0) return 0;
  700. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  701. {
  702. printf("unexpected adress\n");
  703. return 0;
  704. }
  705. if(data_len!=sizeof(session_id)*2+1||data[0]!='h')
  706. {
  707. return 0;
  708. }
  709. int tmp_received_session_id= ntohl(* ((uint32_t *)&data[1+sizeof(session_id)]));
  710. if(tmp_received_session_id!=received_session_id)
  711. {
  712. struct epoll_event ev;
  713. if(udp_fd!=-1)
  714. {
  715. ev.events = EPOLLIN;
  716. ev.data.fd = udp_fd;
  717. int ret = epoll_ctl(epollfd, EPOLL_CTL_DEL, udp_fd, &ev);
  718. //close(udp_fd);
  719. udp_fd=-1;
  720. }
  721. received_session_id=session_id;
  722. }
  723. uint32_t tmp= ntohl(* ((uint32_t *)&data[1+sizeof(session_id)]));
  724. printf("received hb %x %x\n",received_session_id,tmp);
  725. if(received_session_id!=session_id)
  726. {
  727. printf("auth fail!!\n");
  728. return 0;
  729. }
  730. //session_id=get_true_random_number();
  731. server_current_state=server_ready;
  732. last_state_time=get_current_time();
  733. last_hb_recv_time=get_current_time();
  734. printf("changed state to server_ready\n");
  735. }
  736. else if(server_current_state==server_ready)
  737. {
  738. if( tcph->syn==1||tcph->ack!=1 ||data_len==0) return 0;
  739. if(iph->saddr!=g_packet_info.dst_ip||ntohs(tcph->source)!=g_packet_info.dst_port)
  740. {
  741. printf("unexpected adress\n");
  742. return 0;
  743. }
  744. if(data[0]=='h'&&data_len==sizeof(session_id)*2+1)
  745. {
  746. uint32_t tmp= ntohl(* ((uint32_t *)&data[1+sizeof(uint32_t)]));
  747. if(debug_mode)printf("received hb <%x,%x>\n",received_session_id,tmp);
  748. last_hb_recv_time=get_current_time();
  749. }
  750. else if(data[0]=='d'&&data_len>=sizeof(session_id)*2+1)
  751. {
  752. uint32_t tmp_received_session_id=ntohl(* ((uint32_t *)&data[1]));
  753. uint32_t tmp_session_id=ntohl(* ((uint32_t *)&data[1+sizeof(session_id)]));
  754. if(tmp_session_id!=session_id)
  755. {
  756. printf("server session id mismatch,ignore\n");
  757. return 0;
  758. }
  759. if(tmp_received_session_id!=received_session_id)
  760. {
  761. if(died_session_id.find(tmp_received_session_id)!=died_session_id.end())
  762. {
  763. printf("packet from an old died session id\n");
  764. return 0;
  765. }
  766. died_session_id.insert(received_session_id);
  767. }
  768. if(udp_fd==-1||tmp_received_session_id!=received_session_id)// this is first send or client changed session
  769. {
  770. int old_fd=udp_fd;
  771. struct sockaddr_in remote_addr_in;
  772. socklen_t slen = sizeof(sockaddr_in);
  773. memset(&remote_addr_in, 0, sizeof(remote_addr_in));
  774. remote_addr_in.sin_family = AF_INET;
  775. remote_addr_in.sin_port = htons(remote_port);
  776. remote_addr_in.sin_addr.s_addr = inet_addr(remote_address);
  777. udp_fd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  778. printf("created new udp_fd");
  779. int ret = connect(udp_fd, (struct sockaddr *) &remote_addr_in, slen);
  780. if(ret!=0)
  781. {
  782. printf("udp fd connect fail\n");
  783. }
  784. struct epoll_event ev;
  785. ev.events = EPOLLIN;
  786. ev.data.fd = udp_fd;
  787. ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, udp_fd, &ev);
  788. if (ret!= 0) {
  789. printf("add udp_fd error\n");
  790. exit(-1);
  791. }
  792. if(old_fd!=-1)
  793. {
  794. ev.events = EPOLLIN;
  795. ev.data.fd = old_fd;
  796. ret = epoll_ctl(epollfd, EPOLL_CTL_DEL, old_fd, &ev);
  797. //close(old_fd);
  798. }
  799. }
  800. if(tmp_received_session_id!=received_session_id)
  801. {
  802. received_session_id=tmp_received_session_id;
  803. printf("created new udp_fd");
  804. }
  805. printf("received a data from fake tcp,len:%d\n",data_len);
  806. int ret=send(udp_fd,data+1+sizeof(session_id)*2,data_len -(1+sizeof(session_id)*2),0);
  807. printf("%d byte sent\n",ret);
  808. }
  809. }
  810. }
  811. char raw_recv_buf[buf_len];
  812. char raw_recv_buf2[buf_len];
  813. int on_raw_recv()
  814. {
  815. int size;
  816. struct sockaddr saddr;
  817. socklen_t saddr_size;
  818. saddr_size = sizeof(saddr);
  819. if(debug_mode)printf("raw!\n");
  820. size = recvfrom(raw_recv_fd, buf, buf_len, 0 ,&saddr , &saddr_size);
  821. if(buf[12]!=8||buf[13]!=0)
  822. {
  823. printf("not an ipv4 packet!\n");
  824. fflush(stdout);
  825. return 0;
  826. }
  827. char *ip_data=buf+14;
  828. struct iphdr *iph = (struct iphdr *) (ip_data);
  829. if (!(iph->ihl > 0 && iph->ihl <=60)) {
  830. if(debug_mode) printf("iph ihl error");
  831. return 0;
  832. }
  833. if (iph->protocol != IPPROTO_TCP) {
  834. if(debug_mode)printf("iph protocal != tcp\n");
  835. return 0;
  836. }
  837. int ip_len=ntohs(iph->tot_len);
  838. unsigned short iphdrlen =iph->ihl*4;
  839. struct tcphdr *tcph=(struct tcphdr*)(ip_data+ iphdrlen);
  840. unsigned short tcphdrlen = tcph->doff*4;
  841. if (!(tcph->doff > 0 && tcph->doff <=60)) {
  842. if(debug_mode) printf("tcph error");
  843. return 0;
  844. }
  845. /////ip
  846. uint32_t ip_chk=csum ((unsigned short *) ip_data, iphdrlen);
  847. int psize = sizeof(struct pseudo_header) + ip_len-iphdrlen;
  848. /////ip end
  849. ///tcp
  850. struct pseudo_header psh;
  851. psh.source_address = iph->saddr;
  852. psh.dest_address = iph->daddr;
  853. psh.placeholder = 0;
  854. psh.protocol = IPPROTO_TCP;
  855. psh.tcp_length = htons(ip_len-iphdrlen);
  856. memcpy(raw_recv_buf2 , (char*) &psh , sizeof (struct pseudo_header));
  857. memcpy(raw_recv_buf2 + sizeof(struct pseudo_header) , ip_data+ iphdrlen , ip_len-iphdrlen);
  858. uint16_t tcp_chk = csum( (unsigned short*) raw_recv_buf2, psize);
  859. if(ip_chk!=0)
  860. {
  861. printf("ip header error %d\n",ip_chk);
  862. return 0;
  863. }
  864. if(tcp_chk!=0)
  865. {
  866. printf("tcp_chk:%x\n",tcp_chk);
  867. printf("tcp header error\n");
  868. return 0;
  869. }
  870. ////tcp end
  871. // char pseudo_tcp_buffer[MTU];
  872. int data_len = ip_len-tcphdrlen-iphdrlen;
  873. char *data=ip_data+tcphdrlen+iphdrlen;
  874. if(prog_mode==client_mode&& data_len!=5 ||prog_mode==server_mode&& data_len!=9)
  875. {
  876. printf("recvd <%u %u %d>\n",ntohl(tcph->seq ),ntohl(tcph->ack_seq), data_len);
  877. }
  878. if(data_len>0&&tcph->syn==0&&tcph->ack==1)
  879. {
  880. g_packet_info.ack_seq=ntohl(tcph->seq)+(uint32_t)data_len;
  881. }
  882. //printf("%d\n",ip_len);
  883. /*
  884. for(int i=0;i<size;i++)
  885. {
  886. printf("<%x>",(unsigned char)buf[i]);
  887. }
  888. printf("\n");
  889. for(int i=0;i<data_len;i++)
  890. {
  891. printf("<%x>",(unsigned char)data[i]);
  892. }*/
  893. if(debug_mode)
  894. {
  895. printf("\n");
  896. printf("<%u,%u,%u,%u,%d>\n",(unsigned int)iphdrlen,(unsigned int)tcphdrlen,(unsigned int)tcph->syn,(unsigned int)tcph->ack,data_len);
  897. //fflush(stdout);
  898. }
  899. if(prog_mode==server_mode)
  900. {
  901. server_raw_recv(iph,tcph,data,data_len);
  902. }
  903. else
  904. {
  905. client_raw_recv(iph,tcph,data,data_len);
  906. }
  907. return 0;
  908. }
  909. int client()
  910. {
  911. int i, j, k;int ret;
  912. init_raw_socket();
  913. session_id=get_true_random_number();
  914. //init_filter(source_port);
  915. g_packet_info.dst_ip=inet_addr(remote_address);
  916. g_packet_info.dst_port=remote_port;
  917. //g_packet_info.src_ip=inet_addr(source_address);
  918. //g_packet_info.src_port=source_port;
  919. udp_fd=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  920. int yes = 1;
  921. //setsockopt(udp_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  922. struct sockaddr_in local_me;
  923. socklen_t slen = sizeof(sockaddr_in);
  924. memset(&local_me, 0, sizeof(local_me));
  925. local_me.sin_family = AF_INET;
  926. local_me.sin_port = htons(local_port);
  927. local_me.sin_addr.s_addr = inet_addr(local_address);
  928. if (bind(udp_fd, (struct sockaddr*) &local_me, slen) == -1) {
  929. perror("socket bind error");
  930. exit(1);
  931. }
  932. setnonblocking(udp_fd);
  933. int epollfd = epoll_create1(0);
  934. const int max_events = 4096;
  935. struct epoll_event ev, events[max_events];
  936. if (epollfd < 0) {
  937. printf("epoll return %d\n", epollfd);
  938. exit(-1);
  939. }
  940. ev.events = EPOLLIN;
  941. ev.data.fd = udp_fd;
  942. ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, udp_fd, &ev);
  943. if (ret!=0) {
  944. printf("add udp_listen_fd error\n");
  945. exit(-1);
  946. }
  947. ev.events = EPOLLIN;
  948. ev.data.fd = raw_recv_fd;
  949. ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, raw_recv_fd, &ev);
  950. if (ret!= 0) {
  951. printf("add raw_fd error\n");
  952. exit(-1);
  953. }
  954. ////add_timer for fake_tcp_keep_connection_client
  955. //sleep(10);
  956. memset(&udp_old_addr_in,0,sizeof(sockaddr_in));
  957. int unbind=1;
  958. int timer_fd;
  959. set_timer(epollfd,timer_fd);
  960. while(1)////////////////////////
  961. {
  962. int nfds = epoll_wait(epollfd, events, max_events, 180 * 1000);
  963. if (nfds < 0) { //allow zero
  964. printf("epoll_wait return %d\n", nfds);
  965. exit(-1);
  966. }
  967. int n;
  968. for (n = 0; n < nfds; ++n) {
  969. if (events[n].data.fd == raw_recv_fd)
  970. {
  971. on_raw_recv();
  972. /*if(is_sync_ack)
  973. {
  974. }
  975. else if(is heart_beat)
  976. {
  977. }
  978. else if(is_data)
  979. {
  980. sendto();
  981. }*/
  982. }
  983. if(events[n].data.fd ==timer_fd)
  984. {
  985. //printf("timer!\n");
  986. //fflush(stdout);
  987. uint64_t value;
  988. read(timer_fd, &value, 8);
  989. fake_tcp_keep_connection_client();
  990. }
  991. if (events[n].data.fd == udp_fd)
  992. {
  993. socklen_t recv_len;
  994. struct sockaddr_in udp_new_addr_in;
  995. if ((recv_len = recvfrom(udp_fd, buf, buf_len, 0,
  996. (struct sockaddr *) &udp_new_addr_in, &slen)) == -1) {
  997. printf("recv_from error");
  998. exit(1);
  999. };
  1000. printf("Received packet from %s:%d,len: %d\n", inet_ntoa(udp_new_addr_in.sin_addr),
  1001. ntohs(udp_new_addr_in.sin_port),recv_len);
  1002. if(udp_old_addr_in.sin_addr.s_addr==0&&udp_old_addr_in.sin_port==0)
  1003. {
  1004. memcpy(&udp_old_addr_in,&udp_new_addr_in,sizeof(udp_new_addr_in));
  1005. }
  1006. else if(udp_new_addr_in.sin_addr.s_addr!=udp_old_addr_in.sin_addr.s_addr
  1007. ||udp_new_addr_in.sin_port!=udp_old_addr_in.sin_port)
  1008. {
  1009. if(get_current_time()- last_udp_recv_time <3*1000)
  1010. {
  1011. printf("new <ip,port> connected in,ignored,bc last connection is still active\n");
  1012. continue;
  1013. }
  1014. else
  1015. {
  1016. printf("new <ip,port> connected in,accpeted\n");
  1017. memcpy(&udp_old_addr_in,&udp_new_addr_in,sizeof(udp_new_addr_in));
  1018. session_id=get_true_random_number();
  1019. }
  1020. }
  1021. last_udp_recv_time=get_current_time();
  1022. if(client_current_state=client_ready)
  1023. {
  1024. send_data(g_packet_info,buf,recv_len,session_id,received_session_id);
  1025. }
  1026. ////send_data_raw(buf,recv_len);
  1027. }
  1028. }
  1029. }
  1030. return 0;
  1031. }
  1032. int server()
  1033. {
  1034. int i, j, k;int ret;
  1035. g_packet_info.src_ip=inet_addr(local_address);
  1036. g_packet_info.src_port=local_port;
  1037. bind_fd=socket(AF_INET,SOCK_STREAM,0);
  1038. struct sockaddr_in temp_bind_addr;
  1039. bzero(&temp_bind_addr, sizeof(temp_bind_addr));
  1040. temp_bind_addr.sin_family = AF_INET;
  1041. temp_bind_addr.sin_port = htons(local_port);
  1042. temp_bind_addr.sin_addr.s_addr = inet_addr(local_address);
  1043. if (bind(bind_fd, (struct sockaddr*)&temp_bind_addr, sizeof(temp_bind_addr)) !=0)
  1044. {
  1045. printf("bind fail\n");
  1046. exit(-1);
  1047. }
  1048. if(listen(bind_fd, SOMAXCONN) != 0 )
  1049. {
  1050. printf("listen fail\n");
  1051. exit(-1);
  1052. }
  1053. init_raw_socket();
  1054. init_filter(local_port);
  1055. epollfd = epoll_create1(0);
  1056. const int max_events = 4096;
  1057. struct epoll_event ev, events[max_events];
  1058. if (epollfd < 0) {
  1059. printf("epoll return %d\n", epollfd);
  1060. exit(-1);
  1061. }
  1062. ev.events = EPOLLIN;
  1063. ev.data.fd = raw_recv_fd;
  1064. ret = epoll_ctl(epollfd, EPOLL_CTL_ADD, raw_recv_fd, &ev);
  1065. if (ret!= 0) {
  1066. printf("add raw_fd error\n");
  1067. exit(-1);
  1068. }
  1069. int timer_fd;
  1070. set_timer(epollfd,timer_fd);
  1071. while(1)////////////////////////
  1072. {
  1073. int nfds = epoll_wait(epollfd, events, max_events, 180 * 1000);
  1074. if (nfds < 0) { //allow zero
  1075. printf("epoll_wait return %d\n", nfds);
  1076. exit(-1);
  1077. }
  1078. int n;
  1079. const int MTU=1440;
  1080. for (n = 0; n < nfds; ++n)
  1081. {
  1082. if (events[n].data.fd == udp_fd)
  1083. {
  1084. int recv_len=recv(udp_fd,buf,buf_len,0);
  1085. printf("received a packet from udp_fd,len:%d\n",recv_len);
  1086. perror("wtf?");
  1087. if(recv_len<0)
  1088. {
  1089. printf("continue\n");
  1090. continue;
  1091. //return 0;
  1092. }
  1093. send_data(g_packet_info,buf,recv_len,received_session_id,session_id);
  1094. }
  1095. //printf("%d %d %d %d\n",timer_fd,raw_recv_fd,raw_send_fd,n);
  1096. if (events[n].data.fd == timer_fd)
  1097. {
  1098. uint64_t value;
  1099. read(timer_fd, &value, 8);
  1100. fake_tcp_keep_connection_server();
  1101. }
  1102. if (events[n].data.fd == raw_recv_fd)
  1103. {
  1104. on_raw_recv();
  1105. }
  1106. }
  1107. }
  1108. return 0;
  1109. }
  1110. int main(int argc, char *argv[])
  1111. {
  1112. g_packet_info.ack_seq=get_true_random_number();
  1113. g_packet_info.seq=get_true_random_number();
  1114. int i, j, k;
  1115. signal(SIGCHLD, handler);
  1116. process_arg(argc,argv);
  1117. if(prog_mode==client_mode)
  1118. {
  1119. client();
  1120. }
  1121. else
  1122. {
  1123. server();
  1124. }
  1125. return 0;
  1126. }