misc.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379
  1. /*
  2. * misc.cpp
  3. *
  4. * Created on: Sep 23, 2017
  5. * Author: root
  6. */
  7. #include "git_version.h"
  8. #include "common.h"
  9. #include "encrypt.h"
  10. #include "misc.h"
  11. #include "network.h"
  12. #include "connection.h"
  13. #include "fd_manager.h"
  14. int hb_mode=1;
  15. int hb_len=1200;
  16. char hb_buf[buf_len];
  17. int mtu_warn=1375;//if a packet larger than mtu warn is receviced,there will be a warning
  18. int max_rst_to_show=15;
  19. int max_rst_allowed=-1;
  20. int enable_dns_resolve=0;
  21. int ttl_value=64;
  22. fd_manager_t fd_manager;
  23. //char remote_address[max_address_len]="";
  24. //char local_ip[100]="0.0.0.0", remote_ip[100]="255.255.255.255",source_ip[100]="0.0.0.0";//local_ip is for -l option,remote_ip for -r option,source for --source-ip
  25. //u32_t local_ip_uint32,remote_ip_uint32,source_ip_uint32;//convert from last line.
  26. //int local_port = -1, remote_port=-1,source_port=0;//similiar to local_ip remote_ip,buf for port.source_port=0 indicates --source-port is not enabled
  27. address_t local_addr,remote_addr,source_addr;
  28. my_ip_t bind_addr;
  29. int source_port=-1;
  30. int bind_addr_used=0;
  31. int force_source_ip=0; //if --source-ip is enabled
  32. int force_source_port=0;
  33. my_id_t const_id=0;//an id used for connection recovery,its generated randomly,it never change since its generated
  34. int udp_fd=-1; //for client only. client use this fd to listen and handle udp connection
  35. int bind_fd=-1; //bind only,never send or recv. its just a dummy fd for bind,so that other program wont occupy the same port
  36. int epollfd=-1; //fd for epoll
  37. int timer_fd=-1; //the general timer fd for client and server.for server this is not the only timer find,every connection has a timer fd.
  38. int fail_time_counter=0;//determine if the max_fail_time is reached
  39. int epoll_trigger_counter=0;//for debug only
  40. int debug_flag=0;//for debug only
  41. int simple_rule=0; //deprecated.
  42. int keep_rule=0; //whether to monitor the iptables rule periodly,re-add if losted
  43. int auto_add_iptables_rule=0;//if -a is set
  44. int generate_iptables_rule=0;//if -g is set
  45. int generate_iptables_rule_add=0;// if --gen-add is set
  46. int retry_on_error=0;
  47. int debug_resend=0; // debug only
  48. char key_string[1000]= "secret key";// -k option
  49. char fifo_file[1000]="";
  50. int clear_iptables=0;
  51. int wait_xtables_lock=0;
  52. string iptables_command0="iptables/ip6tables ";
  53. string iptables_command="";
  54. string iptables_pattern="";
  55. int iptables_rule_added=0;
  56. int iptables_rule_keeped=0;
  57. int iptables_rule_keep_index=0;
  58. program_mode_t program_mode=unset_mode;//0 unset; 1client 2server
  59. raw_mode_t raw_mode=mode_faketcp;
  60. u32_t raw_ip_version=(u32_t)-1;
  61. unordered_map<int, const char*> raw_mode_tostring = {{mode_faketcp, "faketcp"}, {mode_udp, "udp"}, {mode_icmp, "icmp"}};
  62. int about_to_exit=0;
  63. int socket_buf_size=1024*1024;
  64. //int force_socket_buf=0;
  65. //char lower_level_arg[1000];
  66. int process_lower_level_arg()//handle --lower-level option
  67. {
  68. lower_level=1;
  69. if(strcmp(optarg,"auto")==0)
  70. {
  71. return 0;
  72. }
  73. lower_level_manual=1;
  74. if (strchr(optarg, '#') == 0) {
  75. mylog(log_fatal,
  76. "lower-level parameter invaild,check help page for format\n");
  77. myexit(-1);
  78. }
  79. lower_level = 1;
  80. u32_t hw[6];
  81. memset(hw, 0, sizeof(hw));
  82. sscanf(optarg, "%[^#]#%x:%x:%x:%x:%x:%x", if_name, &hw[0], &hw[1], &hw[2],
  83. &hw[3], &hw[4], &hw[5]);
  84. mylog(log_warn,
  85. "make sure this is correct: if_name=<%s> dest_mac_adress=<%02x:%02x:%02x:%02x:%02x:%02x> \n",
  86. if_name, hw[0], hw[1], hw[2], hw[3], hw[4], hw[5]);
  87. for (int i = 0; i < 6; i++) {
  88. dest_hw_addr[i] = uint8_t(hw[i]);
  89. }
  90. return 0;
  91. }
  92. void print_help()
  93. {
  94. char git_version_buf[100]={0};
  95. strncpy(git_version_buf,gitversion,10);
  96. printf("udp2raw-tunnel\n");
  97. printf("git version:%s ",git_version_buf);
  98. printf("build date:%s %s\n",__DATE__,__TIME__);
  99. printf("repository: https://github.com/wangyu-/udp2raw-tunnel\n");
  100. printf("\n");
  101. printf("usage:\n");
  102. printf(" run as client : ./this_program -c -l local_listen_ip:local_port -r server_address:server_port [options]\n");
  103. printf(" run as server : ./this_program -s -l server_listen_ip:server_port -r remote_address:remote_port [options]\n");
  104. printf("\n");
  105. printf("common options,these options must be same on both side:\n");
  106. printf(" --raw-mode <string> avaliable values:faketcp(default),udp,icmp\n");
  107. printf(" -k,--key <string> password to gen symetric key,default:\"secret key\"\n");
  108. printf(" --cipher-mode <string> avaliable values:aes128cfb,aes128cbc(default),xor,none\n");
  109. printf(" --auth-mode <string> avaliable values:hmac_sha1,md5(default),crc32,simple,none\n");
  110. printf(" -a,--auto-rule auto add (and delete) iptables rule\n");
  111. printf(" -g,--gen-rule generate iptables rule then exit,so that you can copy and\n");
  112. printf(" add it manually.overrides -a\n");
  113. printf(" --disable-anti-replay disable anti-replay,not suggested\n");
  114. //printf("\n");
  115. printf("client options:\n");
  116. printf(" --source-ip <ip> force source-ip for raw socket\n");
  117. printf(" --source-port <port> force source-port for raw socket,tcp/udp only\n");
  118. printf(" this option disables port changing while re-connecting\n");
  119. // printf(" \n");
  120. printf("other options:\n");
  121. printf(" --conf-file <string> read options from a configuration file instead of command line.\n");
  122. printf(" check example.conf in repo for format\n");
  123. printf(" --fifo <string> use a fifo(named pipe) for sending commands to the running program,\n");
  124. printf(" check readme.md in repository for supported commands.\n");
  125. printf(" --log-level <number> 0:never 1:fatal 2:error 3:warn \n");
  126. printf(" 4:info (default) 5:debug 6:trace\n");
  127. // printf("\n");
  128. printf(" --log-position enable file name,function name,line number in log\n");
  129. printf(" --disable-color disable log color\n");
  130. printf(" --disable-bpf disable the kernel space filter,most time its not necessary\n");
  131. printf(" unless you suspect there is a bug\n");
  132. // printf("\n");
  133. printf(" --dev <string> bind raw socket to a device, not necessary but improves performance\n");
  134. printf(" --sock-buf <number> buf size for socket,>=10 and <=10240,unit:kbyte,default:1024\n");
  135. printf(" --force-sock-buf bypass system limitation while setting sock-buf\n");
  136. printf(" --seq-mode <number> seq increase mode for faketcp:\n");
  137. printf(" 0:static header,do not increase seq and ack_seq\n");
  138. printf(" 1:increase seq for every packet,simply ack last seq\n");
  139. printf(" 2:increase seq randomly, about every 3 packets,simply ack last seq\n");
  140. printf(" 3:simulate an almost real seq/ack procedure(default)\n");
  141. printf(" 4:similiar to 3,but do not consider TCP Option Window_Scale,\n");
  142. printf(" maybe useful when firewall doesnt support TCP Option \n");
  143. // printf("\n");
  144. printf(" --lower-level <string> send packets at OSI level 2, format:'if_name#dest_mac_adress'\n");
  145. printf(" ie:'eth0#00:23:45:67:89:b9'.or try '--lower-level auto' to obtain\n");
  146. printf(" the parameter automatically,specify it manually if 'auto' failed\n");
  147. printf(" --wait-lock wait for xtables lock while invoking iptables, need iptables v1.4.20+\n");
  148. printf(" --gen-add generate iptables rule and add it permanently,then exit.overrides -g\n");
  149. printf(" --keep-rule monitor iptables and auto re-add if necessary.implys -a\n");
  150. printf(" --hb-len <number> length of heart-beat packet, >=0 and <=1500\n");
  151. printf(" --mtu-warn <number> mtu warning threshold, unit:byte, default:1375\n");
  152. printf(" --clear clear any iptables rules added by this program.overrides everything\n");
  153. printf(" --retry-on-error retry on error, allow to start udp2raw before network is initialized\n");
  154. printf(" -h,--help print this help message\n");
  155. //printf("common options,these options must be same on both side\n");
  156. }
  157. int load_config(char *file_name, int &argc, vector<string> &argv) //load conf file and append to argv
  158. {
  159. // Load configurations from config_file instead of the command line.
  160. // See config.example for example configurations
  161. std::ifstream conf_file(file_name);
  162. std::string line;
  163. if(conf_file.fail())
  164. {
  165. mylog(log_fatal,"conf_file %s open failed,reason :%s\n",file_name,get_sock_error());
  166. myexit(-1);
  167. }
  168. while(std::getline(conf_file,line))
  169. {
  170. auto res=parse_conf_line(line);
  171. argc+=res.size();
  172. for(int i=0;i<(int)res.size();i++)
  173. {
  174. argv.push_back(res[i]);
  175. }
  176. }
  177. conf_file.close();
  178. return 0;
  179. }
  180. int process_log_level(int argc,char *argv[])//process --log-level and --disable-cloer --log-postion options
  181. {
  182. int i,j,k;
  183. for (i = 0; i < argc; i++)
  184. {
  185. if(strcmp(argv[i],"--log-level")==0)
  186. {
  187. if(i<argc -1)
  188. {
  189. sscanf(argv[i+1],"%d",&log_level);
  190. if(0<=log_level&&log_level<log_end)
  191. {
  192. }
  193. else
  194. {
  195. log_bare(log_fatal,"invalid log_level\n");
  196. myexit(-1);
  197. }
  198. }
  199. }
  200. if(strcmp(argv[i],"--enable-color")==0)
  201. {
  202. enable_log_color=1;
  203. }
  204. if(strcmp(argv[i],"--disable-color")==0)
  205. {
  206. enable_log_color=0;
  207. }
  208. if(strcmp(argv[i],"--log-position")==0)
  209. {
  210. enable_log_position=1;
  211. }
  212. }
  213. return 0;
  214. }
  215. void process_arg(int argc, char *argv[]) //process all options
  216. {
  217. int i,j,k,opt;
  218. int option_index = 0;
  219. char options[]="l:r:schk:ag";
  220. static struct option long_options[] =
  221. {
  222. /* These options set a flag. */
  223. {"source-ip", required_argument, 0, 1},
  224. {"source-port", required_argument, 0, 1},
  225. {"log-level", required_argument, 0, 1},
  226. {"key", required_argument, 0, 'k'},
  227. {"auth-mode", required_argument, 0, 1},
  228. {"cipher-mode", required_argument, 0, 1},
  229. {"raw-mode", required_argument, 0, 1},
  230. {"disable-color", no_argument, 0, 1},
  231. {"enable-color", no_argument, 0, 1},
  232. {"log-position", no_argument, 0, 1},
  233. {"disable-bpf", no_argument, 0, 1},
  234. {"disable-anti-replay", no_argument, 0, 1},
  235. {"auto-rule", no_argument, 0, 'a'},
  236. {"gen-rule", no_argument, 0, 'g'},
  237. {"gen-add", no_argument, 0, 1},
  238. {"debug", no_argument, 0, 1},
  239. {"retry-on-error", no_argument, 0, 1},
  240. {"clear", no_argument, 0, 1},
  241. {"simple-rule", no_argument, 0, 1},
  242. {"keep-rule", no_argument, 0, 1},
  243. {"lower-level", required_argument, 0, 1},
  244. {"sock-buf", required_argument, 0, 1},
  245. {"seq-mode", required_argument, 0, 1},
  246. {"conf-file", required_argument, 0, 1},
  247. {"force-sock-buf", no_argument, 0, 1},
  248. {"wait-lock", no_argument, 0, 1},
  249. {"random-drop", required_argument, 0, 1},
  250. {"fifo", required_argument, 0, 1},
  251. {"hb-mode", required_argument, 0, 1},
  252. {"hb-len", required_argument, 0, 1},
  253. {"mtu-warn", required_argument, 0, 1},
  254. {"max-rst-to-show", required_argument, 0, 1},
  255. {"max-rst-allowed", required_argument, 0, 1},
  256. {"set-ttl", required_argument, 0, 1},
  257. {"dev", required_argument, 0, 1},
  258. {"dns-resolve", no_argument, 0, 1},
  259. {"easy-tcp", no_argument, 0, 1},
  260. {"fix-gro", no_argument, 0, 1},
  261. {NULL, 0, 0, 0}
  262. };
  263. process_log_level(argc,argv);
  264. set<string> all_options;
  265. map<string,string> shortcut_map;
  266. all_options.insert("--help");
  267. all_options.insert("-h");
  268. string dummy="";
  269. for(i=0;i<(int)strlen(options);i++)
  270. {
  271. char val=options[i];
  272. if( ( val>='0'&&val<='9') ||( val>='a'&&val<='z')||(val>='A'&&val<='Z'))
  273. {
  274. all_options.insert(dummy+'-'+val);
  275. }
  276. }
  277. for(i=0;i<int( sizeof(long_options)/sizeof(long_options[0]) );i++)
  278. {
  279. if(long_options[i].name==NULL) break;
  280. int val=long_options[i].val;
  281. if( ( val>='0'&&val<='9') ||( val>='a'&&val<='z')||(val>='A'&&val<='Z'))
  282. {
  283. shortcut_map[dummy+"--"+long_options[i].name]= dummy+"-"+ char(val);
  284. }
  285. all_options.insert(dummy+"--"+long_options[i].name);
  286. }
  287. for (i = 0; i < argc; i++)
  288. {
  289. int len=strlen(argv[i]);
  290. if(len==0)
  291. {
  292. mylog(log_fatal,"found an empty string in options\n");
  293. myexit(-1);
  294. }
  295. if(len==1&&argv[i][0]=='-' )
  296. {
  297. mylog(log_fatal,"invaild option '-' in argv\n");
  298. myexit(-1);
  299. }
  300. if(len==2&&argv[i][0]=='-'&&argv[i][1]=='-' )
  301. {
  302. mylog(log_fatal,"invaild option '--' in argv\n");
  303. myexit(-1);
  304. }
  305. }
  306. mylog(log_info,"argc=%d ", argc);
  307. for (i = 0; i < argc; i++) {
  308. log_bare(log_info, "%s ", argv[i]);
  309. }
  310. log_bare(log_info, "\n");
  311. //string dummy="";
  312. for(i=+1;i<argc;i++)
  313. {
  314. if(argv[i][0]!='-') continue;
  315. string a=argv[i];
  316. if(a[0]=='-'&&a[1]!='-')
  317. a=dummy+a[0]+a[1];
  318. if(all_options.find(a.c_str())==all_options.end())
  319. {
  320. mylog(log_fatal,"invaild option %s\n",a.c_str());
  321. myexit(-1);
  322. }
  323. for(j=i+1;j<argc;j++)
  324. {
  325. if(argv[j][0]!='-') continue;
  326. string b=argv[j];
  327. if(b[0]=='-'&&b[1]!='-')
  328. b=dummy+b[0]+b[1];
  329. if(shortcut_map.find(a)!=shortcut_map.end())
  330. a=shortcut_map[a];
  331. if(shortcut_map.find(b)!=shortcut_map.end())
  332. b=shortcut_map[b];
  333. if(a==b)
  334. {
  335. mylog(log_fatal,"%s duplicates with %s\n",argv[i],argv[j]);
  336. myexit(-1);
  337. }
  338. }
  339. }
  340. int no_l = 1, no_r = 1;
  341. while ((opt = getopt_long(argc, argv,options,long_options,&option_index)) != -1) {
  342. //string opt_key;
  343. //opt_key+=opt;
  344. switch (opt) {
  345. case 'l':
  346. no_l = 0;
  347. local_addr.from_str(optarg);
  348. if(local_addr.get_port()==22)
  349. {
  350. mylog(log_fatal,"port 22 not allowed\n");
  351. myexit(-1);
  352. }
  353. /*
  354. if (strchr(optarg, ':') != 0) {
  355. sscanf(optarg, "%[^:]:%d", local_ip, &local_port);
  356. if(local_port==22)
  357. {
  358. mylog(log_fatal,"port 22 not allowed\n");
  359. myexit(-1);
  360. }
  361. } else {
  362. mylog(log_fatal,"invalid parameter for -l ,%s,should be ip:port\n",optarg);
  363. myexit(-1);
  364. }*/
  365. break;
  366. case 'r':
  367. no_r = 0;
  368. remote_addr.from_str(optarg);
  369. if(remote_addr.get_port()==22)
  370. {
  371. mylog(log_fatal,"port 22 not allowed\n");
  372. myexit(-1);
  373. }
  374. /*
  375. if (strchr(optarg, ':') != 0) {
  376. sscanf(optarg, "%[^:]:%d", remote_address, &remote_port);
  377. if(remote_port==22)
  378. {
  379. mylog(log_fatal,"port 22 not allowed\n");
  380. myexit(-1);
  381. }
  382. } else {
  383. mylog(log_fatal,"invalid parameter for -r ,%s,should be ip:port\n",optarg);
  384. myexit(-1);
  385. }*/
  386. break;
  387. case 's':
  388. if(program_mode==0)
  389. {
  390. program_mode=server_mode;
  391. }
  392. else
  393. {
  394. mylog(log_fatal,"-s /-c has already been set,conflict\n");
  395. myexit(-1);
  396. }
  397. break;
  398. case 'c':
  399. if(program_mode==0)
  400. {
  401. program_mode=client_mode;
  402. }
  403. else
  404. {
  405. mylog(log_fatal,"-s /-c has already been set,conflict\n");
  406. myexit(-1);
  407. }
  408. break;
  409. case 'h':
  410. break;
  411. case 'a':
  412. auto_add_iptables_rule=1;
  413. break;
  414. case 'g':
  415. generate_iptables_rule=1;
  416. break;
  417. case 'k':
  418. mylog(log_debug,"parsing key option\n");
  419. sscanf(optarg,"%s",key_string);
  420. break;
  421. case 1:
  422. mylog(log_debug,"option_index: %d\n",option_index);
  423. if(strcmp(long_options[option_index].name,"clear")==0)
  424. {
  425. clear_iptables=1;
  426. }
  427. else if(strcmp(long_options[option_index].name,"source-ip")==0)
  428. {
  429. mylog(log_debug,"parsing long option :source-ip\n");
  430. //sscanf(optarg, "%s", source_ip);
  431. source_addr.from_str_ip_only(optarg);
  432. mylog(log_debug,"source: %s\n",source_addr.get_ip());
  433. force_source_ip=1;
  434. }
  435. else if(strcmp(long_options[option_index].name,"source-port")==0)
  436. {
  437. mylog(log_debug,"parsing long option :source-port\n");
  438. sscanf(optarg, "%d", &source_port);
  439. mylog(log_info,"source: %d\n",source_port);
  440. force_source_port=1;
  441. }
  442. else if(strcmp(long_options[option_index].name,"raw-mode")==0)
  443. {
  444. /*
  445. for(i=0;i<mode_end;i++)
  446. {
  447. if(strcmp(optarg,raw_mode_tostring[i])==0)
  448. {
  449. //printf("%d i\n",i);
  450. //printf("%s",raw_mode_tostring[i]);
  451. raw_mode=(raw_mode_t)i;
  452. break;
  453. }
  454. }
  455. if(i==mode_end)
  456. {
  457. mylog(log_fatal,"no such raw_mode %s\n",optarg);
  458. myexit(-1);
  459. }
  460. */
  461. if(strcmp(optarg,"easyfaketcp")==0||strcmp(optarg,"easy_faketcp")==0||strcmp(optarg,"easy-faketcp")==0)
  462. {
  463. raw_mode=mode_faketcp;
  464. use_tcp_dummy_socket=1;
  465. }
  466. else
  467. {
  468. for(i=0;i<mode_end;i++)
  469. {
  470. if(strcmp(optarg,raw_mode_tostring[i])==0)
  471. {
  472. //printf("%d i\n",i);
  473. //printf("%s",raw_mode_tostring[i]);
  474. raw_mode=(raw_mode_t)i;
  475. break;
  476. }
  477. }
  478. if(i==mode_end)
  479. {
  480. mylog(log_fatal,"no such raw_mode %s\n",optarg);
  481. myexit(-1);
  482. }
  483. }
  484. }
  485. else if(strcmp(long_options[option_index].name,"auth-mode")==0)
  486. {
  487. for(i=0;i<auth_end;i++)
  488. {
  489. if(strcmp(optarg,auth_mode_tostring[i])==0)
  490. {
  491. auth_mode=(auth_mode_t)i;
  492. if(auth_mode==auth_none)
  493. {
  494. disable_anti_replay=1;
  495. }
  496. break;
  497. }
  498. }
  499. if(i==auth_end)
  500. {
  501. mylog(log_fatal,"no such auth_mode %s\n",optarg);
  502. myexit(-1);
  503. }
  504. }
  505. else if(strcmp(long_options[option_index].name,"cipher-mode")==0)
  506. {
  507. for(i=0;i<cipher_end;i++)
  508. {
  509. if(strcmp(optarg,cipher_mode_tostring[i])==0)
  510. {
  511. cipher_mode=(cipher_mode_t)i;
  512. break;
  513. }
  514. }
  515. if(i==cipher_end)
  516. {
  517. mylog(log_fatal,"no such cipher_mode %s\n",optarg);
  518. myexit(-1);
  519. }
  520. }
  521. else if(strcmp(long_options[option_index].name,"log-level")==0)
  522. {
  523. }
  524. else if(strcmp(long_options[option_index].name,"lower-level")==0)
  525. {
  526. process_lower_level_arg();
  527. //lower_level=1;
  528. //strcpy(lower_level_arg,optarg);
  529. }
  530. else if(strcmp(long_options[option_index].name,"simple-rule")==0)
  531. {
  532. simple_rule=1;
  533. }
  534. else if(strcmp(long_options[option_index].name,"keep-rule")==0)
  535. {
  536. keep_rule=1;
  537. }
  538. else if(strcmp(long_options[option_index].name,"gen-add")==0)
  539. {
  540. generate_iptables_rule_add=1;
  541. }
  542. else if(strcmp(long_options[option_index].name,"disable-color")==0)
  543. {
  544. //enable_log_color=0;
  545. }
  546. else if(strcmp(long_options[option_index].name,"enable-color")==0)
  547. {
  548. //enable_log_color=0;
  549. }
  550. else if(strcmp(long_options[option_index].name,"debug")==0)
  551. {
  552. debug_flag=1;
  553. //enable_log_color=0;
  554. }
  555. else if(strcmp(long_options[option_index].name,"dev")==0)
  556. {
  557. sscanf(optarg,"%s",dev);
  558. //enable_log_color=0;
  559. mylog(log_info,"dev=[%s]\n",dev);
  560. }
  561. else if(strcmp(long_options[option_index].name,"debug-resend")==0)
  562. {
  563. //debug_resend=1;
  564. //enable_log_color=0;
  565. }
  566. else if(strcmp(long_options[option_index].name,"log-position")==0)
  567. {
  568. //enable_log_position=1;
  569. }
  570. else if(strcmp(long_options[option_index].name,"force-sock-buf")==0)
  571. {
  572. force_socket_buf=1;
  573. }
  574. else if(strcmp(long_options[option_index].name,"retry-on-error")==0)
  575. {
  576. retry_on_error=1;
  577. }
  578. else if(strcmp(long_options[option_index].name,"wait-lock")==0)
  579. {
  580. wait_xtables_lock=1;
  581. }
  582. else if(strcmp(long_options[option_index].name,"disable-bpf")==0)
  583. {
  584. disable_bpf_filter=1;
  585. }
  586. else if(strcmp(long_options[option_index].name,"disable-anti-replay")==0)
  587. {
  588. disable_anti_replay=1;
  589. }
  590. else if(strcmp(long_options[option_index].name,"sock-buf")==0)
  591. {
  592. int tmp=-1;
  593. sscanf(optarg,"%d",&tmp);
  594. if(10<=tmp&&tmp<=10*1024)
  595. {
  596. socket_buf_size=tmp*1024;
  597. }
  598. else
  599. {
  600. mylog(log_fatal,"sock-buf value must be between 1 and 10240 (kbyte) \n");
  601. myexit(-1);
  602. }
  603. }
  604. else if(strcmp(long_options[option_index].name,"seq-mode")==0)
  605. {
  606. sscanf(optarg,"%d",&seq_mode);
  607. if(0<=seq_mode&&seq_mode<=max_seq_mode)
  608. {
  609. }
  610. else
  611. {
  612. mylog(log_fatal,"seq_mode value must be 0,1,or 2 \n");
  613. myexit(-1);
  614. }
  615. }
  616. else if(strcmp(long_options[option_index].name,"random-drop")==0)
  617. {
  618. sscanf(optarg,"%d",&random_drop);
  619. if(random_drop<0||random_drop>10000)
  620. {
  621. mylog(log_fatal,"random_drop must be between 0 10000 \n");
  622. myexit(-1);
  623. }
  624. mylog(log_info,"random_drop =%d \n",random_drop);
  625. }
  626. else if(strcmp(long_options[option_index].name,"fifo")==0)
  627. {
  628. sscanf(optarg,"%s",fifo_file);
  629. mylog(log_info,"fifo_file =%s \n",fifo_file);
  630. }
  631. else if(strcmp(long_options[option_index].name,"conf-file")==0)
  632. {
  633. mylog(log_info,"configuration loaded from %s\n",optarg);
  634. }
  635. else if(strcmp(long_options[option_index].name,"hb-mode")==0)
  636. {
  637. sscanf(optarg,"%d",&hb_mode);
  638. assert(hb_mode==0||hb_mode==1);
  639. mylog(log_info,"hb_mode =%d \n",hb_mode);
  640. }
  641. else if(strcmp(long_options[option_index].name,"hb-len")==0)
  642. {
  643. sscanf(optarg,"%d",&hb_len);
  644. assert(hb_len>=0&&hb_len<=1500);
  645. mylog(log_info,"hb_len =%d \n",hb_len);
  646. }
  647. else if(strcmp(long_options[option_index].name,"mtu-warn")==0)
  648. {
  649. sscanf(optarg,"%d",&mtu_warn);
  650. assert(mtu_warn>0);
  651. mylog(log_info,"mtu_warn=%d \n",mtu_warn);
  652. }
  653. else if(strcmp(long_options[option_index].name,"max-rst-to-show")==0)
  654. {
  655. sscanf(optarg,"%d",&max_rst_to_show);
  656. assert(max_rst_to_show>=-1);
  657. mylog(log_info,"max_rst_to_show=%d \n",max_rst_to_show);
  658. }
  659. else if(strcmp(long_options[option_index].name,"max-rst-allowed")==0)
  660. {
  661. sscanf(optarg,"%d",&max_rst_allowed);
  662. assert(max_rst_allowed>=-1);
  663. mylog(log_info,"max_rst_allowed=%d \n",max_rst_allowed);
  664. }
  665. else if(strcmp(long_options[option_index].name,"set-ttl")==0)
  666. {
  667. sscanf(optarg,"%d",&ttl_value);
  668. assert(ttl_value>=0&&ttl_value<=255);
  669. mylog(log_info,"ttl_value=%d\n",ttl_value);
  670. }
  671. else if(strcmp(long_options[option_index].name,"dns-resolve")==0) // currently not used
  672. {
  673. enable_dns_resolve=1;
  674. mylog(log_info,"dns-resolve enabled\n");
  675. }
  676. else if(strcmp(long_options[option_index].name,"easy-tcp")==0)
  677. {
  678. use_tcp_dummy_socket=1;
  679. mylog(log_info,"--easy-tcp enabled, now a dummy tcp socket will be created for handshake and block rst\n");
  680. }
  681. else if(strcmp(long_options[option_index].name,"fix-gro")==0)
  682. {
  683. mylog(log_info,"--fix-gro enabled\n");
  684. g_fix_gro=1;
  685. }
  686. else
  687. {
  688. mylog(log_warn,"ignored unknown long option ,option_index:%d code:<%x>\n",option_index, optopt);
  689. }
  690. break;
  691. default:
  692. mylog(log_fatal,"unknown option ,code:<%c>,<%x>\n",optopt, optopt);
  693. myexit(-1);
  694. }
  695. }
  696. if (no_l)
  697. mylog(log_fatal,"error: -l not found\n");
  698. if (no_r)
  699. mylog(log_fatal,"error: -r not found\n");
  700. if(program_mode==0)
  701. mylog(log_fatal,"error: -c /-s hasnt been set\n");
  702. if (no_l || no_r||program_mode==0)
  703. {
  704. print_help();
  705. myexit(-1);
  706. }
  707. if(program_mode==client_mode)
  708. {
  709. raw_ip_version=remote_addr.get_type();
  710. }
  711. else
  712. {
  713. raw_ip_version=local_addr.get_type();
  714. }
  715. if(auto_add_iptables_rule&& use_tcp_dummy_socket)
  716. {
  717. mylog(log_error,"-a,--auto-rule is not supposed to be used with easyfaketcp mode, you are likely making a mistake, but we can try to continue\n");
  718. }
  719. if(keep_rule&& use_tcp_dummy_socket)
  720. {
  721. mylog(log_error,"--keep-rule is not supposed to be used with easyfaketcp mode, you are likely making a mistake, but we can try to continue\n");
  722. }
  723. mylog(log_info,"important variables: ");
  724. log_bare(log_info,"log_level=%d:%s ",log_level,log_text[log_level]);
  725. log_bare(log_info,"raw_mode=%s ",raw_mode_tostring[raw_mode]);
  726. log_bare(log_info,"cipher_mode=%s ",cipher_mode_tostring[cipher_mode]);
  727. log_bare(log_info,"auth_mode=%s ",auth_mode_tostring[auth_mode]);
  728. log_bare(log_info,"key=%s ",key_string);
  729. log_bare(log_info,"local_addr=%s ",local_addr.get_str());
  730. log_bare(log_info,"remote_addr=%s ",remote_addr.get_str());
  731. if(force_source_ip)
  732. log_bare(log_info,"source_addr=%s ",source_addr.get_ip());
  733. if(force_source_port)
  734. log_bare(log_info,"source_port=%d ",source_port);
  735. log_bare(log_info,"socket_buf_size=%d ",socket_buf_size);
  736. log_bare(log_info,"\n");
  737. }
  738. void pre_process_arg(int argc, char *argv[])//mainly for load conf file
  739. {
  740. int i,j,k;
  741. for (i = 0; i < argc; i++)
  742. {
  743. if(strcmp(argv[i],"--unit-test")==0)
  744. {
  745. unit_test();
  746. myexit(0);
  747. }
  748. }
  749. for (i = 0; i < argc; i++)
  750. {
  751. if(strcmp(argv[i],"-h")==0||strcmp(argv[i],"--help")==0)
  752. {
  753. print_help();
  754. myexit(0);
  755. }
  756. }
  757. if (argc == 1)
  758. {
  759. print_help();
  760. myexit(-1);
  761. }
  762. process_log_level(argc,argv);
  763. int new_argc=0;
  764. vector<string> new_argv;
  765. int count=0;
  766. int pos=-1;
  767. for (i = 0; i < argc; i++)
  768. {
  769. if(strcmp(argv[i],"--conf-file")==0)
  770. {
  771. count++;
  772. pos=i;
  773. if(i==argc)
  774. {
  775. mylog(log_fatal,"--conf-file need a parameter\n");
  776. myexit(-1);
  777. }
  778. if(argv[i+1][0]=='-')
  779. {
  780. mylog(log_fatal,"--conf-file need a parameter\n");
  781. myexit(-1);
  782. }
  783. i++;
  784. }
  785. else
  786. {
  787. //printf("<%s>",argv[i]);
  788. new_argc++;
  789. new_argv.push_back(argv[i]);
  790. }
  791. }
  792. if(count>1)
  793. {
  794. mylog(log_fatal,"duplicated --conf-file option\n");
  795. myexit(-1);
  796. }
  797. if(count>0)
  798. {
  799. load_config(argv[pos+1],new_argc,new_argv);
  800. }
  801. char* new_argv_char[new_argv.size()];
  802. new_argc=0;
  803. for(i=0;i<(int)new_argv.size();i++)
  804. {
  805. if(strcmp(new_argv[i].c_str(),"--conf-file")==0)
  806. {
  807. mylog(log_fatal,"cant have --conf-file in a config file\n");
  808. myexit(-1);
  809. }
  810. new_argv_char[new_argc++]=(char *)new_argv[i].c_str();
  811. }
  812. process_arg(new_argc,new_argv_char);
  813. }
  814. void *run_keep(void *none) //called in a new thread for --keep-rule option
  815. {
  816. while(1)
  817. {
  818. sleep(iptables_rule_keep_interval);
  819. keep_iptables_rule();
  820. if(about_to_exit) //just incase it runs forever if there is some bug,not necessary
  821. {
  822. sleep(10);
  823. keep_thread_running=0; //not thread safe ,but wont cause problem
  824. break;
  825. }
  826. }
  827. return NULL;
  828. }
  829. void iptables_rule() // handles -a -g --gen-add --keep-rule --clear --wait-lock
  830. {
  831. assert(raw_ip_version==AF_INET||raw_ip_version==AF_INET6);
  832. if(raw_ip_version==AF_INET)
  833. {
  834. iptables_command0="iptables ";
  835. }
  836. else
  837. iptables_command0="ip6tables ";
  838. if(!wait_xtables_lock)
  839. {
  840. iptables_command=iptables_command0;
  841. }
  842. else
  843. {
  844. iptables_command=iptables_command0+"-w ";
  845. }
  846. if(clear_iptables)
  847. {
  848. char *output;
  849. //int ret =system("iptables-save |grep udp2raw_dWRwMnJhdw|sed -n 's/^-A/iptables -D/p'|sh");
  850. int ret =run_command(iptables_command+"-S|sed -n '/udp2rawDwrW/p'|sed -n 's/^-A/"+iptables_command+"-D/p'|sh",output);
  851. int ret2 =run_command(iptables_command+"-S|sed -n '/udp2rawDwrW/p'|sed -n 's/^-N/"+iptables_command+"-X/p'|sh",output);
  852. //system("iptables-save |grep udp2raw_dWRwMnJhdw|sed 's/^-A/iptables -D/'|sh");
  853. //system("iptables-save|grep -v udp2raw_dWRwMnJhdw|iptables-restore");
  854. mylog(log_info,"tried to clear all iptables rule created previously,return value %d %d\n",ret,ret2);
  855. myexit(-1);
  856. }
  857. if(auto_add_iptables_rule&&generate_iptables_rule)
  858. {
  859. mylog(log_warn," -g overrides -a\n");
  860. auto_add_iptables_rule=0;
  861. //myexit(-1);
  862. }
  863. if(generate_iptables_rule_add&&generate_iptables_rule)
  864. {
  865. mylog(log_warn," --gen-add overrides -g\n");
  866. generate_iptables_rule=0;
  867. //myexit(-1);
  868. }
  869. if(keep_rule&&auto_add_iptables_rule==0)
  870. {
  871. auto_add_iptables_rule=1;
  872. mylog(log_warn," --keep_rule implys -a\n");
  873. generate_iptables_rule=0;
  874. //myexit(-1);
  875. }
  876. char tmp_pattern[200];
  877. string pattern="";
  878. if(program_mode==client_mode)
  879. {
  880. tmp_pattern[0]=0;
  881. if(raw_mode==mode_faketcp)
  882. {
  883. sprintf(tmp_pattern,"-s %s -p tcp -m tcp --sport %d",remote_addr.get_ip(),remote_addr.get_port());
  884. }
  885. if(raw_mode==mode_udp)
  886. {
  887. sprintf(tmp_pattern,"-s %s -p udp -m udp --sport %d",remote_addr.get_ip(),remote_addr.get_port());
  888. }
  889. if(raw_mode==mode_icmp)
  890. {
  891. if(raw_ip_version==AF_INET)
  892. sprintf(tmp_pattern,"-s %s -p icmp --icmp-type 0",remote_addr.get_ip());
  893. else
  894. sprintf(tmp_pattern,"-s %s -p icmpv6 --icmpv6-type 129",remote_addr.get_ip());
  895. }
  896. pattern+=tmp_pattern;
  897. }
  898. if(program_mode==server_mode)
  899. {
  900. tmp_pattern[0]=0;
  901. if(raw_ip_version==AF_INET)
  902. {
  903. if(local_addr.inner.ipv4.sin_addr.s_addr!=0)
  904. {
  905. sprintf(tmp_pattern,"-d %s ",local_addr.get_ip());
  906. }
  907. }
  908. else
  909. {
  910. char zero_arr[16]={0};
  911. if(memcmp(&local_addr.inner.ipv6.sin6_addr,zero_arr,16)!=0)
  912. {
  913. sprintf(tmp_pattern,"-d %s ",local_addr.get_ip());
  914. }
  915. }
  916. pattern+=tmp_pattern;
  917. tmp_pattern[0]=0;
  918. if(raw_mode==mode_faketcp)
  919. {
  920. sprintf(tmp_pattern,"-p tcp -m tcp --dport %d",local_addr.get_port());
  921. }
  922. if(raw_mode==mode_udp)
  923. {
  924. sprintf(tmp_pattern,"-p udp -m udp --dport %d",local_addr.get_port());
  925. }
  926. if(raw_mode==mode_icmp)
  927. {
  928. if(raw_ip_version==AF_INET)
  929. sprintf(tmp_pattern,"-p icmp --icmp-type 8");
  930. else
  931. sprintf(tmp_pattern,"-p icmpv6 --icmpv6-type 128");
  932. }
  933. pattern+=tmp_pattern;
  934. }
  935. /*
  936. if(!simple_rule)
  937. {
  938. pattern += " -m comment --comment udp2rawDwrW_";
  939. char const_id_str[100];
  940. sprintf(const_id_str, "%x_", const_id);
  941. pattern += const_id_str;
  942. time_t timer;
  943. char buffer[26];
  944. struct tm* tm_info;
  945. time(&timer);
  946. tm_info = localtime(&timer);
  947. strftime(buffer, 26, "%Y-%m-%d-%H:%M:%S", tm_info);
  948. pattern += buffer;
  949. }*/
  950. if(generate_iptables_rule)
  951. {
  952. string rule=iptables_command+"-I INPUT ";
  953. rule+=pattern;
  954. rule+=" -j DROP";
  955. printf("generated iptables rule:\n");
  956. printf("%s\n",rule.c_str());
  957. myexit(0);
  958. }
  959. if(generate_iptables_rule_add)
  960. {
  961. iptables_gen_add(pattern.c_str(),const_id);
  962. myexit(0);
  963. }
  964. if(auto_add_iptables_rule)
  965. {
  966. iptables_rule_init(pattern.c_str(),const_id,keep_rule);
  967. if(keep_rule)
  968. {
  969. if(pthread_create(&keep_thread, NULL, run_keep, 0)) {
  970. mylog(log_fatal, "Error creating thread\n");
  971. myexit(-1);
  972. }
  973. keep_thread_running=1;
  974. }
  975. }
  976. else
  977. {
  978. mylog(log_warn," -a has not been set, make sure you have added the needed iptables rules manually\n");
  979. }
  980. }
  981. int unit_test()
  982. {
  983. printf("running unit test\n");
  984. vector<string> conf_lines= {"---aaa","--aaa bbb","-a bbb"," \t \t \t-a\t \t \t bbbbb\t \t \t "};
  985. for(int i=0;i<int(conf_lines.size());i++)
  986. {
  987. printf("orign:%s\n",conf_lines[i].c_str());
  988. auto res=parse_conf_line(conf_lines[i]);
  989. printf("pasrse_result: size %d",int(res.size()));
  990. for(int j=0;j<int(res.size());j++)
  991. {
  992. printf("<%s>",res[j].c_str());
  993. }
  994. printf("\n");
  995. }
  996. char s1[]={1,2,3,4,5};
  997. char s2[]={1};
  998. short c1=csum((unsigned short*)s1,5);
  999. short c2=csum((unsigned short*)s2,1);
  1000. //c2=0;
  1001. printf("%x %x\n",(int)c1,(int)c2);
  1002. const char buf[]={1,2,3,4,5,6,7,8,9,10,11,2,13,14,15,16};
  1003. char key[100]={0};
  1004. char buf2[100]={0};
  1005. char buf3[100]={0};
  1006. char buf4[100]={0};
  1007. int len=16;
  1008. for(int i=0;i<len;i++)
  1009. {
  1010. printf("<%d>",buf[i]);
  1011. }
  1012. printf("\n");
  1013. cipher_encrypt(buf,buf2,len,key);
  1014. for(int i=0;i<len;i++)
  1015. {
  1016. printf("<%d>",buf2[i]);
  1017. }
  1018. printf("\n");
  1019. int temp_len=len;
  1020. cipher_decrypt(buf2,buf3,len,key);
  1021. for(int i=0;i<len;i++)
  1022. {
  1023. printf("<%d>",buf3[i]);
  1024. }
  1025. printf("\n");
  1026. cipher_encrypt(buf2,buf4,temp_len,key);
  1027. for(int i=0;i<temp_len;i++)
  1028. {
  1029. printf("<%d>",buf4[i]);
  1030. }
  1031. return 0;
  1032. }
  1033. int set_timer(int epollfd,int &timer_fd)//put a timer_fd into epoll,general function,used both in client and server
  1034. {
  1035. int ret;
  1036. epoll_event ev;
  1037. itimerspec its;
  1038. memset(&its,0,sizeof(its));
  1039. if((timer_fd=timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK)) < 0)
  1040. {
  1041. mylog(log_fatal,"timer_fd create error\n");
  1042. myexit(1);
  1043. }
  1044. its.it_interval.tv_sec=(timer_interval/1000);
  1045. its.it_interval.tv_nsec=(timer_interval%1000)*1000ll*1000ll;
  1046. its.it_value.tv_nsec=1; //imidiately
  1047. timerfd_settime(timer_fd,0,&its,0);
  1048. ev.events = EPOLLIN;
  1049. ev.data.u64 = timer_fd;
  1050. ret=epoll_ctl(epollfd, EPOLL_CTL_ADD, timer_fd, &ev);
  1051. if (ret < 0) {
  1052. mylog(log_fatal,"epoll_ctl return %d\n", ret);
  1053. myexit(-1);
  1054. }
  1055. return 0;
  1056. }
  1057. int set_timer_server(int epollfd,int &timer_fd,fd64_t &fd64)//only for server
  1058. {
  1059. int ret;
  1060. epoll_event ev;
  1061. itimerspec its;
  1062. memset(&its,0,sizeof(its));
  1063. if((timer_fd=timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK)) < 0)
  1064. {
  1065. mylog(log_fatal,"timer_fd create error\n");
  1066. myexit(1);
  1067. }
  1068. its.it_interval.tv_sec=(timer_interval/1000);
  1069. its.it_interval.tv_nsec=(timer_interval%1000)*1000ll*1000ll;
  1070. its.it_value.tv_nsec=1; //imidiately
  1071. timerfd_settime(timer_fd,0,&its,0);
  1072. fd64=fd_manager.create(timer_fd);
  1073. ev.events = EPOLLIN;
  1074. ev.data.u64 = fd64;////difference
  1075. ret=epoll_ctl(epollfd, EPOLL_CTL_ADD, timer_fd, &ev);
  1076. if (ret < 0) {
  1077. mylog(log_fatal,"epoll_ctl return %d\n", ret);
  1078. myexit(-1);
  1079. }
  1080. return 0;
  1081. }
  1082. int handle_lower_level(raw_info_t &raw_info)//fill lower_level info,when --lower-level is enabled,only for server
  1083. {
  1084. packet_info_t &send_info=raw_info.send_info;
  1085. packet_info_t &recv_info=raw_info.recv_info;
  1086. if(lower_level_manual)
  1087. {
  1088. memset(&send_info.addr_ll,0,sizeof(send_info.addr_ll));
  1089. send_info.addr_ll.sll_family=AF_PACKET;
  1090. send_info.addr_ll.sll_ifindex=ifindex;
  1091. send_info.addr_ll.sll_halen=ETHER_ADDR_LEN;
  1092. send_info.addr_ll.sll_protocol=htons(ETH_P_IP);
  1093. memcpy(&send_info.addr_ll.sll_addr,dest_hw_addr,ETHER_ADDR_LEN);
  1094. mylog(log_debug,"[manual]lower level info %x %x\n ",send_info.addr_ll.sll_halen,send_info.addr_ll.sll_protocol);
  1095. }
  1096. else
  1097. {
  1098. memset(&send_info.addr_ll,0,sizeof(send_info.addr_ll));
  1099. send_info.addr_ll.sll_family=recv_info.addr_ll.sll_family;
  1100. send_info.addr_ll.sll_ifindex=recv_info.addr_ll.sll_ifindex;
  1101. send_info.addr_ll.sll_protocol=recv_info.addr_ll.sll_protocol;
  1102. send_info.addr_ll.sll_halen=recv_info.addr_ll.sll_halen;
  1103. memcpy(send_info.addr_ll.sll_addr,recv_info.addr_ll.sll_addr,sizeof(send_info.addr_ll.sll_addr));
  1104. //other bytes should be kept zero.
  1105. mylog(log_debug,"[auto]lower level info %x %x\n ",send_info.addr_ll.sll_halen,send_info.addr_ll.sll_protocol);
  1106. }
  1107. return 0;
  1108. }
  1109. string chain[2];
  1110. string rule_keep[2];
  1111. string rule_keep_add[2];
  1112. string rule_keep_del[2];
  1113. u64_t keep_rule_last_time=0;
  1114. pthread_t keep_thread;
  1115. int keep_thread_running=0;
  1116. int iptables_gen_add(const char * s,u32_t const_id)
  1117. {
  1118. string dummy="";
  1119. iptables_pattern=s;
  1120. chain[0] =dummy+ "udp2rawDwrW_C";
  1121. rule_keep[0]=dummy+ iptables_pattern+" -j " +chain[0];
  1122. rule_keep_add[0]=iptables_command+"-I INPUT "+rule_keep[0];
  1123. char *output;
  1124. run_command(iptables_command+"-N "+chain[0],output,show_none);
  1125. run_command(iptables_command+"-F "+chain[0],output);
  1126. run_command(iptables_command+"-I "+chain[0] + " -j DROP",output);
  1127. rule_keep_del[0]=iptables_command+"-D INPUT "+rule_keep[0];
  1128. run_command(rule_keep_del[0],output,show_none);
  1129. run_command(rule_keep_del[0],output,show_none);
  1130. if(run_command(rule_keep_add[0],output)!=0)
  1131. {
  1132. mylog(log_fatal,"auto added iptables failed by: %s\n",rule_keep_add[0].c_str());
  1133. myexit(-1);
  1134. }
  1135. return 0;
  1136. }
  1137. int iptables_rule_init(const char * s,u32_t const_id,int keep)
  1138. {
  1139. iptables_pattern=s;
  1140. iptables_rule_added=1;
  1141. iptables_rule_keeped=keep;
  1142. string dummy="";
  1143. char const_id_str[100];
  1144. sprintf(const_id_str, "%x", const_id);
  1145. chain[0] =dummy+ "udp2rawDwrW_"+const_id_str+"_C0";
  1146. chain[1] =dummy+ "udp2rawDwrW_"+const_id_str+"_C1";
  1147. rule_keep[0]=dummy+ iptables_pattern+" -j " +chain[0];
  1148. rule_keep[1]=dummy+ iptables_pattern+" -j " +chain[1];
  1149. rule_keep_add[0]=iptables_command+"-I INPUT "+rule_keep[0];
  1150. rule_keep_add[1]=iptables_command+"-I INPUT "+rule_keep[1];
  1151. rule_keep_del[0]=iptables_command+"-D INPUT "+rule_keep[0];
  1152. rule_keep_del[1]=iptables_command+"-D INPUT "+rule_keep[1];
  1153. keep_rule_last_time=get_current_time();
  1154. char *output;
  1155. for(int i=0;i<=iptables_rule_keeped;i++)
  1156. {
  1157. run_command(iptables_command+"-N "+chain[i],output);
  1158. run_command(iptables_command+"-F "+chain[i],output);
  1159. run_command(iptables_command+"-I "+chain[i] + " -j DROP",output);
  1160. if(run_command(rule_keep_add[i],output)!=0)
  1161. {
  1162. mylog(log_fatal,"auto added iptables failed by: %s\n",rule_keep_add[i].c_str());
  1163. myexit(-1);
  1164. }
  1165. }
  1166. mylog(log_warn,"auto added iptables rules\n");
  1167. return 0;
  1168. }
  1169. int keep_iptables_rule() //magic to work on a machine without grep/iptables --check/-m commment
  1170. {
  1171. /*
  1172. if(iptables_rule_keeped==0) return 0;
  1173. uint64_t tmp_current_time=get_current_time();
  1174. if(tmp_current_time-keep_rule_last_time<=iptables_rule_keep_interval)
  1175. {
  1176. return 0;
  1177. }
  1178. else
  1179. {
  1180. keep_rule_last_time=tmp_current_time;
  1181. }*/
  1182. mylog(log_debug,"keep_iptables_rule begin %llu\n",get_current_time());
  1183. iptables_rule_keep_index+=1;
  1184. iptables_rule_keep_index%=2;
  1185. string dummy="";
  1186. char *output;
  1187. int i=iptables_rule_keep_index;
  1188. run_command(iptables_command + "-N " + chain[i], output,show_none);
  1189. if (run_command(iptables_command + "-F " + chain[i], output,show_none) != 0)
  1190. mylog(log_warn, "iptables -F failed %d\n",i);
  1191. if (run_command(iptables_command + "-I " + chain[i] + " -j DROP",output,show_none) != 0)
  1192. mylog(log_warn, "iptables -I failed %d\n",i);
  1193. if (run_command(rule_keep_del[i], output,show_none) != 0)
  1194. mylog(log_warn, "rule_keep_del failed %d\n",i);
  1195. run_command(rule_keep_del[i], output,show_none); //do it twice,incase it fails for unknown random reason
  1196. if(run_command(rule_keep_add[i], output,show_log)!=0)
  1197. mylog(log_warn, "rule_keep_del failed %d\n",i);
  1198. mylog(log_debug,"keep_iptables_rule end %llu\n",get_current_time());
  1199. return 0;
  1200. }
  1201. int clear_iptables_rule()
  1202. {
  1203. char *output;
  1204. string dummy="";
  1205. if(!iptables_rule_added) return 0;
  1206. for(int i=0;i<=iptables_rule_keeped;i++ )
  1207. {
  1208. run_command(rule_keep_del[i],output);
  1209. run_command(iptables_command+"-F "+chain[i],output);
  1210. run_command(iptables_command+"-X "+chain[i],output);
  1211. }
  1212. return 0;
  1213. }
  1214. void signal_handler(int sig)
  1215. {
  1216. about_to_exit=1;
  1217. // myexit(0);
  1218. }