misc.cpp 32 KB

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