misc.cpp 44 KB

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