misc.cpp 31 KB

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