misc.cpp 31 KB

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