util.c 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985
  1. /*************************************************************************
  2. *
  3. * Copyright (C) 2018-2023 Ruilin Peng (Nick) <[email protected]>.
  4. *
  5. * smartdns is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * smartdns is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #ifndef _GNU_SOURCE
  19. #define _GNU_SOURCE
  20. #include <stdio.h>
  21. #endif
  22. #include "dns_conf.h"
  23. #include "tlog.h"
  24. #include "util.h"
  25. #include <arpa/inet.h>
  26. #include <ctype.h>
  27. #include <dirent.h>
  28. #include <dlfcn.h>
  29. #include <errno.h>
  30. #include <fcntl.h>
  31. #include <inttypes.h>
  32. #include <libgen.h>
  33. #include <linux/capability.h>
  34. #include <linux/limits.h>
  35. #include <linux/netlink.h>
  36. #include <linux/rtnetlink.h>
  37. #include <netinet/tcp.h>
  38. #include <openssl/crypto.h>
  39. #include <openssl/ssl.h>
  40. #include <openssl/x509v3.h>
  41. #include <poll.h>
  42. #include <pthread.h>
  43. #include <signal.h>
  44. #include <stdlib.h>
  45. #include <string.h>
  46. #include <sys/prctl.h>
  47. #include <sys/resource.h>
  48. #include <sys/stat.h>
  49. #include <sys/statvfs.h>
  50. #include <sys/sysinfo.h>
  51. #include <sys/time.h>
  52. #include <sys/types.h>
  53. #include <time.h>
  54. #include <unistd.h>
  55. #include <unwind.h>
  56. #define TMP_BUFF_LEN_32 32
  57. #define NFNL_SUBSYS_IPSET 6
  58. #define IPSET_ATTR_DATA 7
  59. #define IPSET_ATTR_IP 1
  60. #define IPSET_ATTR_IPADDR_IPV4 1
  61. #define IPSET_ATTR_IPADDR_IPV6 2
  62. #define IPSET_ATTR_PROTOCOL 1
  63. #define IPSET_ATTR_SETNAME 2
  64. #define IPSET_ATTR_TIMEOUT 6
  65. #define IPSET_ADD 9
  66. #define IPSET_DEL 10
  67. #define IPSET_MAXNAMELEN 32
  68. #define IPSET_PROTOCOL 6
  69. #define IPV6_ADDR_LEN 16
  70. #define IPV4_ADDR_LEN 4
  71. #ifndef NFNETLINK_V0
  72. #define NFNETLINK_V0 0
  73. #endif
  74. #ifndef NLA_F_NESTED
  75. #define NLA_F_NESTED (1 << 15)
  76. #endif
  77. #ifndef NLA_F_NET_BYTEORDER
  78. #define NLA_F_NET_BYTEORDER (1 << 14)
  79. #endif
  80. #define NETLINK_ALIGN(len) (((len) + 3) & ~(3))
  81. #define BUFF_SZ 1024
  82. #define PACKET_BUF_SIZE 8192
  83. #define PACKET_MAGIC 0X11040918
  84. struct ipset_netlink_attr {
  85. unsigned short len;
  86. unsigned short type;
  87. };
  88. struct ipset_netlink_msg {
  89. unsigned char family;
  90. unsigned char version;
  91. __be16 res_id;
  92. };
  93. static int ipset_fd;
  94. static int pidfile_fd;
  95. unsigned long get_tick_count(void)
  96. {
  97. struct timespec ts;
  98. clock_gettime(CLOCK_MONOTONIC, &ts);
  99. return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000);
  100. }
  101. char *dir_name(char *path)
  102. {
  103. if (strstr(path, "/") == NULL) {
  104. safe_strncpy(path, "./", PATH_MAX);
  105. return path;
  106. }
  107. return dirname(path);
  108. }
  109. char *get_host_by_addr(char *host, int maxsize, struct sockaddr *addr)
  110. {
  111. struct sockaddr_storage *addr_store = (struct sockaddr_storage *)addr;
  112. host[0] = 0;
  113. switch (addr_store->ss_family) {
  114. case AF_INET: {
  115. struct sockaddr_in *addr_in = NULL;
  116. addr_in = (struct sockaddr_in *)addr;
  117. inet_ntop(AF_INET, &addr_in->sin_addr, host, maxsize);
  118. } break;
  119. case AF_INET6: {
  120. struct sockaddr_in6 *addr_in6 = NULL;
  121. addr_in6 = (struct sockaddr_in6 *)addr;
  122. if (IN6_IS_ADDR_V4MAPPED(&addr_in6->sin6_addr)) {
  123. struct sockaddr_in addr_in4;
  124. memset(&addr_in4, 0, sizeof(addr_in4));
  125. memcpy(&addr_in4.sin_addr.s_addr, addr_in6->sin6_addr.s6_addr + 12, sizeof(addr_in4.sin_addr.s_addr));
  126. inet_ntop(AF_INET, &addr_in4.sin_addr, host, maxsize);
  127. } else {
  128. inet_ntop(AF_INET6, &addr_in6->sin6_addr, host, maxsize);
  129. }
  130. } break;
  131. default:
  132. goto errout;
  133. break;
  134. }
  135. return host;
  136. errout:
  137. return NULL;
  138. }
  139. int generate_random_addr(unsigned char *addr, int addr_len, int mask)
  140. {
  141. if (mask / 8 > addr_len) {
  142. return -1;
  143. }
  144. int offset = mask / 8;
  145. int bit = 0;
  146. for (int i = offset; i < addr_len; i++) {
  147. bit = 0xFF;
  148. if (i == offset) {
  149. bit = ~(0xFF << (8 - mask % 8)) & 0xFF;
  150. }
  151. addr[i] = jhash(&addr[i], 1, 0) & bit;
  152. }
  153. return 0;
  154. }
  155. int generate_addr_map(unsigned char *addr_from, unsigned char *addr_to, unsigned char *addr_out, int addr_len, int mask)
  156. {
  157. if ((mask / 8) >= addr_len) {
  158. if (mask % 8 != 0) {
  159. return -1;
  160. }
  161. }
  162. int offset = mask / 8;
  163. int bit = mask % 8;
  164. for (int i = 0; i < offset; i++) {
  165. addr_out[i] = addr_to[i];
  166. }
  167. if (bit != 0) {
  168. int mask1 = 0xFF >> bit;
  169. int mask2 = (0xFF << (8 - bit)) & 0xFF;
  170. addr_out[offset] = addr_from[offset] & mask1;
  171. addr_out[offset] |= addr_to[offset] & mask2;
  172. offset = offset + 1;
  173. }
  174. for (int i = offset; i < addr_len; i++) {
  175. addr_out[i] = addr_from[i];
  176. }
  177. return 0;
  178. }
  179. int getaddr_by_host(const char *host, struct sockaddr *addr, socklen_t *addr_len)
  180. {
  181. struct addrinfo hints;
  182. struct addrinfo *result = NULL;
  183. int ret = 0;
  184. memset(&hints, 0, sizeof(hints));
  185. hints.ai_family = AF_UNSPEC;
  186. hints.ai_socktype = SOCK_STREAM;
  187. ret = getaddrinfo(host, "53", &hints, &result);
  188. if (ret != 0) {
  189. goto errout;
  190. }
  191. if (result->ai_addrlen > *addr_len) {
  192. result->ai_addrlen = *addr_len;
  193. }
  194. addr->sa_family = result->ai_family;
  195. memcpy(addr, result->ai_addr, result->ai_addrlen);
  196. *addr_len = result->ai_addrlen;
  197. freeaddrinfo(result);
  198. return 0;
  199. errout:
  200. if (result) {
  201. freeaddrinfo(result);
  202. }
  203. return -1;
  204. }
  205. int getsocket_inet(int fd, struct sockaddr *addr, socklen_t *addr_len)
  206. {
  207. struct sockaddr_storage addr_store;
  208. socklen_t addr_store_len = sizeof(addr_store);
  209. if (getsockname(fd, (struct sockaddr *)&addr_store, &addr_store_len) != 0) {
  210. goto errout;
  211. }
  212. switch (addr_store.ss_family) {
  213. case AF_INET: {
  214. struct sockaddr_in *addr_in = NULL;
  215. addr_in = (struct sockaddr_in *)addr;
  216. addr_in->sin_family = AF_INET;
  217. *addr_len = sizeof(struct sockaddr_in);
  218. memcpy(addr, addr_in, sizeof(struct sockaddr_in));
  219. } break;
  220. case AF_INET6: {
  221. struct sockaddr_in6 *addr_in6 = NULL;
  222. addr_in6 = (struct sockaddr_in6 *)addr;
  223. if (IN6_IS_ADDR_V4MAPPED(&addr_in6->sin6_addr)) {
  224. struct sockaddr_in addr_in4;
  225. memset(&addr_in4, 0, sizeof(addr_in4));
  226. memcpy(&addr_in4.sin_addr.s_addr, addr_in6->sin6_addr.s6_addr + 12, sizeof(addr_in4.sin_addr.s_addr));
  227. addr_in4.sin_family = AF_INET;
  228. addr_in4.sin_port = 0;
  229. *addr_len = sizeof(struct sockaddr_in);
  230. memcpy(addr, &addr_in4, sizeof(struct sockaddr_in));
  231. } else {
  232. addr_in6->sin6_family = AF_INET6;
  233. *addr_len = sizeof(struct sockaddr_in6);
  234. memcpy(addr, addr_in6, sizeof(struct sockaddr_in6));
  235. }
  236. } break;
  237. default:
  238. goto errout;
  239. break;
  240. }
  241. return 0;
  242. errout:
  243. return -1;
  244. }
  245. int fill_sockaddr_by_ip(unsigned char *ip, int ip_len, int port, struct sockaddr *addr, socklen_t *addr_len)
  246. {
  247. if (ip == NULL || addr == NULL || addr_len == NULL) {
  248. return -1;
  249. }
  250. if (ip_len == IPV4_ADDR_LEN) {
  251. struct sockaddr_in *addr_in = NULL;
  252. addr->sa_family = AF_INET;
  253. addr_in = (struct sockaddr_in *)addr;
  254. addr_in->sin_port = htons(port);
  255. addr_in->sin_family = AF_INET;
  256. memcpy(&addr_in->sin_addr.s_addr, ip, ip_len);
  257. *addr_len = 16;
  258. } else if (ip_len == IPV6_ADDR_LEN) {
  259. struct sockaddr_in6 *addr_in6 = NULL;
  260. addr->sa_family = AF_INET6;
  261. addr_in6 = (struct sockaddr_in6 *)addr;
  262. addr_in6->sin6_port = htons(port);
  263. addr_in6->sin6_family = AF_INET6;
  264. memcpy(addr_in6->sin6_addr.s6_addr, ip, ip_len);
  265. *addr_len = 28;
  266. }
  267. return -1;
  268. }
  269. int parse_ip(const char *value, char *ip, int *port)
  270. {
  271. int offset = 0;
  272. char *colon = NULL;
  273. colon = strstr(value, ":");
  274. if (strstr(value, "[")) {
  275. /* ipv6 with port */
  276. char *bracket_end = strstr(value, "]");
  277. if (bracket_end == NULL) {
  278. return -1;
  279. }
  280. offset = bracket_end - value - 1;
  281. memcpy(ip, value + 1, offset);
  282. ip[offset] = 0;
  283. colon = strstr(bracket_end, ":");
  284. if (colon) {
  285. colon++;
  286. }
  287. } else if (colon && strstr(colon + 1, ":")) {
  288. /* ipv6 without port */
  289. strncpy(ip, value, MAX_IP_LEN);
  290. colon = NULL;
  291. } else {
  292. /* ipv4 */
  293. colon = strstr(value, ":");
  294. if (colon == NULL) {
  295. /* without port */
  296. strncpy(ip, value, MAX_IP_LEN);
  297. } else {
  298. /* with port */
  299. offset = colon - value;
  300. colon++;
  301. memcpy(ip, value, offset);
  302. ip[offset] = 0;
  303. }
  304. }
  305. if (colon) {
  306. /* get port num */
  307. *port = atoi(colon);
  308. } else {
  309. *port = PORT_NOT_DEFINED;
  310. }
  311. if (ip[0] == 0) {
  312. return -1;
  313. }
  314. return 0;
  315. }
  316. int check_is_ipv4(const char *ip)
  317. {
  318. const char *ptr = ip;
  319. char c = 0;
  320. int dot_num = 0;
  321. int dig_num = 0;
  322. while ((c = *ptr++) != '\0') {
  323. if (c == '.') {
  324. dot_num++;
  325. dig_num = 0;
  326. continue;
  327. }
  328. /* check number count of one field */
  329. if (dig_num >= 4) {
  330. return -1;
  331. }
  332. if (c >= '0' && c <= '9') {
  333. dig_num++;
  334. continue;
  335. }
  336. return -1;
  337. }
  338. /* check field number */
  339. if (dot_num != 3) {
  340. return -1;
  341. }
  342. return 0;
  343. }
  344. int check_is_ipv6(const char *ip)
  345. {
  346. const char *ptr = ip;
  347. char c = 0;
  348. int colon_num = 0;
  349. int dig_num = 0;
  350. while ((c = *ptr++) != '\0') {
  351. if (c == '[' || c == ']') {
  352. continue;
  353. }
  354. if (c == ':') {
  355. colon_num++;
  356. dig_num = 0;
  357. continue;
  358. }
  359. /* check number count of one field */
  360. if (dig_num >= 5) {
  361. return -1;
  362. }
  363. dig_num++;
  364. if (c >= '0' && c <= '9') {
  365. continue;
  366. }
  367. if (c >= 'a' && c <= 'f') {
  368. continue;
  369. }
  370. if (c >= 'A' && c <= 'F') {
  371. continue;
  372. }
  373. return -1;
  374. }
  375. /* check field number */
  376. if (colon_num > 7) {
  377. return -1;
  378. }
  379. return 0;
  380. }
  381. int check_is_ipaddr(const char *ip)
  382. {
  383. if (strstr(ip, ".")) {
  384. /* IPV4 */
  385. return check_is_ipv4(ip);
  386. } else if (strstr(ip, ":")) {
  387. /* IPV6 */
  388. return check_is_ipv6(ip);
  389. }
  390. return -1;
  391. }
  392. int parse_uri(const char *value, char *scheme, char *host, int *port, char *path)
  393. {
  394. return parse_uri_ext(value, scheme, NULL, NULL, host, port, path);
  395. }
  396. void urldecode(char *dst, const char *src)
  397. {
  398. char a, b;
  399. while (*src) {
  400. if ((*src == '%') && ((a = src[1]) && (b = src[2])) && (isxdigit(a) && isxdigit(b))) {
  401. if (a >= 'a') {
  402. a -= 'a' - 'A';
  403. }
  404. if (a >= 'A') {
  405. a -= ('A' - 10);
  406. } else {
  407. a -= '0';
  408. }
  409. if (b >= 'a') {
  410. b -= 'a' - 'A';
  411. }
  412. if (b >= 'A') {
  413. b -= ('A' - 10);
  414. } else {
  415. b -= '0';
  416. }
  417. *dst++ = 16 * a + b;
  418. src += 3;
  419. } else if (*src == '+') {
  420. *dst++ = ' ';
  421. src++;
  422. } else {
  423. *dst++ = *src++;
  424. }
  425. }
  426. *dst++ = '\0';
  427. }
  428. int parse_uri_ext(const char *value, char *scheme, char *user, char *password, char *host, int *port, char *path)
  429. {
  430. char *scheme_end = NULL;
  431. int field_len = 0;
  432. const char *process_ptr = value;
  433. char user_pass_host_part[PATH_MAX];
  434. char *user_password = NULL;
  435. char *host_part = NULL;
  436. const char *host_end = NULL;
  437. scheme_end = strstr(value, "://");
  438. if (scheme_end) {
  439. field_len = scheme_end - value;
  440. if (scheme) {
  441. memcpy(scheme, value, field_len);
  442. scheme[field_len] = 0;
  443. }
  444. process_ptr += field_len + 3;
  445. } else {
  446. if (scheme) {
  447. scheme[0] = '\0';
  448. }
  449. }
  450. host_end = strstr(process_ptr, "/");
  451. if (host_end == NULL) {
  452. host_end = process_ptr + strlen(process_ptr);
  453. };
  454. field_len = host_end - process_ptr;
  455. if (field_len >= (int)sizeof(user_pass_host_part)) {
  456. return -1;
  457. }
  458. memcpy(user_pass_host_part, process_ptr, field_len);
  459. user_pass_host_part[field_len] = 0;
  460. host_part = strstr(user_pass_host_part, "@");
  461. if (host_part != NULL) {
  462. *host_part = '\0';
  463. host_part = host_part + 1;
  464. user_password = user_pass_host_part;
  465. char *sep = strstr(user_password, ":");
  466. if (sep != NULL) {
  467. *sep = '\0';
  468. sep = sep + 1;
  469. if (password) {
  470. urldecode(password, sep);
  471. }
  472. }
  473. if (user) {
  474. urldecode(user, user_password);
  475. }
  476. } else {
  477. host_part = user_pass_host_part;
  478. }
  479. if (host != NULL && parse_ip(host_part, host, port) != 0) {
  480. return -1;
  481. }
  482. process_ptr += field_len;
  483. if (path) {
  484. strcpy(path, process_ptr);
  485. }
  486. return 0;
  487. }
  488. int set_fd_nonblock(int fd, int nonblock)
  489. {
  490. int ret = 0;
  491. int flags = fcntl(fd, F_GETFL);
  492. if (flags == -1) {
  493. return -1;
  494. }
  495. flags = (nonblock) ? (flags | O_NONBLOCK) : (flags & ~O_NONBLOCK);
  496. ret = fcntl(fd, F_SETFL, flags);
  497. if (ret == -1) {
  498. return -1;
  499. }
  500. return 0;
  501. }
  502. char *reverse_string(char *output, const char *input, int len, int to_lower_case)
  503. {
  504. char *begin = output;
  505. if (len <= 0) {
  506. *output = 0;
  507. return output;
  508. }
  509. len--;
  510. while (len >= 0) {
  511. *output = *(input + len);
  512. if (to_lower_case) {
  513. if (*output >= 'A' && *output <= 'Z') {
  514. /* To lower case */
  515. *output = *output + 32;
  516. }
  517. }
  518. output++;
  519. len--;
  520. }
  521. *output = 0;
  522. return begin;
  523. }
  524. char *to_lower_case(char *output, const char *input, int len)
  525. {
  526. char *begin = output;
  527. int i = 0;
  528. if (len <= 0) {
  529. *output = 0;
  530. return output;
  531. }
  532. len--;
  533. while (i < len && *(input + i) != '\0') {
  534. *output = *(input + i);
  535. if (*output >= 'A' && *output <= 'Z') {
  536. /* To lower case */
  537. *output = *output + 32;
  538. }
  539. output++;
  540. i++;
  541. }
  542. *output = 0;
  543. return begin;
  544. }
  545. static inline void _ipset_add_attr(struct nlmsghdr *netlink_head, uint16_t type, size_t len, const void *data)
  546. {
  547. struct ipset_netlink_attr *attr = (void *)netlink_head + NETLINK_ALIGN(netlink_head->nlmsg_len);
  548. uint16_t payload_len = NETLINK_ALIGN(sizeof(struct ipset_netlink_attr)) + len;
  549. attr->type = type;
  550. attr->len = payload_len;
  551. memcpy((void *)attr + NETLINK_ALIGN(sizeof(struct ipset_netlink_attr)), data, len);
  552. netlink_head->nlmsg_len += NETLINK_ALIGN(payload_len);
  553. }
  554. static int _ipset_socket_init(void)
  555. {
  556. if (ipset_fd > 0) {
  557. return 0;
  558. }
  559. ipset_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_NETFILTER);
  560. if (ipset_fd < 0) {
  561. return -1;
  562. }
  563. return 0;
  564. }
  565. static int _ipset_support_timeout(void)
  566. {
  567. if (dns_conf_ipset_timeout_enable) {
  568. return 0;
  569. }
  570. return -1;
  571. }
  572. static int _ipset_operate(const char *ipset_name, const unsigned char addr[], int addr_len, unsigned long timeout,
  573. int operate)
  574. {
  575. struct nlmsghdr *netlink_head = NULL;
  576. struct ipset_netlink_msg *netlink_msg = NULL;
  577. struct ipset_netlink_attr *nested[3];
  578. char buffer[BUFF_SZ];
  579. uint8_t proto = 0;
  580. ssize_t rc = 0;
  581. int af = 0;
  582. static const struct sockaddr_nl snl = {.nl_family = AF_NETLINK};
  583. uint32_t expire = 0;
  584. if (addr_len != IPV4_ADDR_LEN && addr_len != IPV6_ADDR_LEN) {
  585. errno = EINVAL;
  586. return -1;
  587. }
  588. if (addr_len == IPV4_ADDR_LEN) {
  589. af = AF_INET;
  590. } else if (addr_len == IPV6_ADDR_LEN) {
  591. af = AF_INET6;
  592. } else {
  593. errno = EINVAL;
  594. return -1;
  595. }
  596. if (_ipset_socket_init() != 0) {
  597. return -1;
  598. }
  599. if (strlen(ipset_name) >= IPSET_MAXNAMELEN) {
  600. errno = ENAMETOOLONG;
  601. return -1;
  602. }
  603. memset(buffer, 0, BUFF_SZ);
  604. netlink_head = (struct nlmsghdr *)buffer;
  605. netlink_head->nlmsg_len = NETLINK_ALIGN(sizeof(struct nlmsghdr));
  606. netlink_head->nlmsg_type = operate | (NFNL_SUBSYS_IPSET << 8);
  607. netlink_head->nlmsg_flags = NLM_F_REQUEST | NLM_F_REPLACE;
  608. netlink_msg = (struct ipset_netlink_msg *)(buffer + netlink_head->nlmsg_len);
  609. netlink_head->nlmsg_len += NETLINK_ALIGN(sizeof(struct ipset_netlink_msg));
  610. netlink_msg->family = af;
  611. netlink_msg->version = NFNETLINK_V0;
  612. netlink_msg->res_id = htons(0);
  613. proto = IPSET_PROTOCOL;
  614. _ipset_add_attr(netlink_head, IPSET_ATTR_PROTOCOL, sizeof(proto), &proto);
  615. _ipset_add_attr(netlink_head, IPSET_ATTR_SETNAME, strlen(ipset_name) + 1, ipset_name);
  616. nested[0] = (struct ipset_netlink_attr *)(buffer + NETLINK_ALIGN(netlink_head->nlmsg_len));
  617. netlink_head->nlmsg_len += NETLINK_ALIGN(sizeof(struct ipset_netlink_attr));
  618. nested[0]->type = NLA_F_NESTED | IPSET_ATTR_DATA;
  619. nested[1] = (struct ipset_netlink_attr *)(buffer + NETLINK_ALIGN(netlink_head->nlmsg_len));
  620. netlink_head->nlmsg_len += NETLINK_ALIGN(sizeof(struct ipset_netlink_attr));
  621. nested[1]->type = NLA_F_NESTED | IPSET_ATTR_IP;
  622. _ipset_add_attr(netlink_head,
  623. (af == AF_INET ? IPSET_ATTR_IPADDR_IPV4 : IPSET_ATTR_IPADDR_IPV6) | NLA_F_NET_BYTEORDER, addr_len,
  624. addr);
  625. nested[1]->len = (void *)buffer + NETLINK_ALIGN(netlink_head->nlmsg_len) - (void *)nested[1];
  626. if (timeout > 0 && _ipset_support_timeout() == 0) {
  627. expire = htonl(timeout);
  628. _ipset_add_attr(netlink_head, IPSET_ATTR_TIMEOUT | NLA_F_NET_BYTEORDER, sizeof(expire), &expire);
  629. }
  630. nested[0]->len = (void *)buffer + NETLINK_ALIGN(netlink_head->nlmsg_len) - (void *)nested[0];
  631. for (;;) {
  632. rc = sendto(ipset_fd, buffer, netlink_head->nlmsg_len, 0, (const struct sockaddr *)&snl, sizeof(snl));
  633. if (rc >= 0) {
  634. break;
  635. }
  636. if (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR) {
  637. struct timespec waiter;
  638. waiter.tv_sec = 0;
  639. waiter.tv_nsec = 10000;
  640. nanosleep(&waiter, NULL);
  641. continue;
  642. }
  643. }
  644. return rc;
  645. }
  646. int ipset_add(const char *ipset_name, const unsigned char addr[], int addr_len, unsigned long timeout)
  647. {
  648. return _ipset_operate(ipset_name, addr, addr_len, timeout, IPSET_ADD);
  649. }
  650. int ipset_del(const char *ipset_name, const unsigned char addr[], int addr_len)
  651. {
  652. return _ipset_operate(ipset_name, addr, addr_len, 0, IPSET_DEL);
  653. }
  654. unsigned char *SSL_SHA256(const unsigned char *d, size_t n, unsigned char *md)
  655. {
  656. static unsigned char m[SHA256_DIGEST_LENGTH];
  657. if (md == NULL) {
  658. md = m;
  659. }
  660. EVP_MD_CTX *ctx = EVP_MD_CTX_create();
  661. if (ctx == NULL) {
  662. return NULL;
  663. }
  664. EVP_MD_CTX_init(ctx);
  665. EVP_DigestInit_ex(ctx, EVP_sha256(), NULL);
  666. EVP_DigestUpdate(ctx, d, n);
  667. EVP_DigestFinal_ex(ctx, m, NULL);
  668. EVP_MD_CTX_destroy(ctx);
  669. return (md);
  670. }
  671. int SSL_base64_decode(const char *in, unsigned char *out)
  672. {
  673. size_t inlen = strlen(in);
  674. int outlen = 0;
  675. if (inlen == 0) {
  676. return 0;
  677. }
  678. outlen = EVP_DecodeBlock(out, (unsigned char *)in, inlen);
  679. if (outlen < 0) {
  680. goto errout;
  681. }
  682. /* Subtract padding bytes from |outlen| */
  683. while (in[--inlen] == '=') {
  684. --outlen;
  685. }
  686. return outlen;
  687. errout:
  688. return -1;
  689. }
  690. int SSL_base64_encode(const void *in, int in_len, char *out)
  691. {
  692. int outlen = 0;
  693. if (in_len == 0) {
  694. return 0;
  695. }
  696. outlen = EVP_EncodeBlock((unsigned char *)out, in, in_len);
  697. if (outlen < 0) {
  698. goto errout;
  699. }
  700. return outlen;
  701. errout:
  702. return -1;
  703. }
  704. int create_pid_file(const char *pid_file)
  705. {
  706. int fd = 0;
  707. int flags = 0;
  708. char buff[TMP_BUFF_LEN_32];
  709. /* create pid file, and lock this file */
  710. fd = open(pid_file, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);
  711. if (fd == -1) {
  712. fprintf(stderr, "create pid file %s failed, %s\n", pid_file, strerror(errno));
  713. return -1;
  714. }
  715. flags = fcntl(fd, F_GETFD);
  716. if (flags < 0) {
  717. fprintf(stderr, "Could not get flags for PID file %s\n", pid_file);
  718. goto errout;
  719. }
  720. flags |= FD_CLOEXEC;
  721. if (fcntl(fd, F_SETFD, flags) == -1) {
  722. fprintf(stderr, "Could not set flags for PID file %s\n", pid_file);
  723. goto errout;
  724. }
  725. if (lockf(fd, F_TLOCK, 0) < 0) {
  726. memset(buff, 0, TMP_BUFF_LEN_32);
  727. if (read(fd, buff, TMP_BUFF_LEN_32) <= 0) {
  728. buff[0] = '\0';
  729. }
  730. fprintf(stderr, "Server is already running, pid is %s", buff);
  731. goto errout;
  732. }
  733. snprintf(buff, TMP_BUFF_LEN_32, "%d\n", getpid());
  734. if (write(fd, buff, strnlen(buff, TMP_BUFF_LEN_32)) < 0) {
  735. fprintf(stderr, "write pid to file failed, %s.\n", strerror(errno));
  736. goto errout;
  737. }
  738. if (pidfile_fd > 0) {
  739. close(pidfile_fd);
  740. }
  741. pidfile_fd = fd;
  742. return 0;
  743. errout:
  744. if (fd > 0) {
  745. close(fd);
  746. }
  747. return -1;
  748. }
  749. int full_path(char *normalized_path, int normalized_path_len, const char *path)
  750. {
  751. const char *p = path;
  752. if (path == NULL || normalized_path == NULL) {
  753. return -1;
  754. }
  755. while (*p == ' ') {
  756. p++;
  757. }
  758. if (*p == '\0' || *p == '/') {
  759. return -1;
  760. }
  761. char buf[PATH_MAX];
  762. snprintf(normalized_path, normalized_path_len, "%s/%s", getcwd(buf, sizeof(buf)), path);
  763. return 0;
  764. }
  765. int generate_cert_key(const char *key_path, const char *cert_path, const char *san, int days)
  766. {
  767. int ret = -1;
  768. #if (OPENSSL_VERSION_NUMBER <= 0x30000000L)
  769. RSA *rsa = NULL;
  770. BIGNUM *bn = NULL;
  771. #endif
  772. X509_EXTENSION *cert_ext = NULL;
  773. BIO *cert_file = NULL;
  774. BIO *key_file = NULL;
  775. X509 *cert = NULL;
  776. EVP_PKEY *pkey = NULL;
  777. const int RSA_KEY_LENGTH = 2048;
  778. if (key_path == NULL || cert_path == NULL) {
  779. return ret;
  780. }
  781. key_file = BIO_new_file(key_path, "wb");
  782. cert_file = BIO_new_file(cert_path, "wb");
  783. cert = X509_new();
  784. #if (OPENSSL_VERSION_NUMBER >= 0x30000000L)
  785. pkey = EVP_RSA_gen(RSA_KEY_LENGTH);
  786. #else
  787. bn = BN_new();
  788. rsa = RSA_new();
  789. pkey = EVP_PKEY_new();
  790. if (rsa == NULL || pkey == NULL || bn == NULL) {
  791. goto out;
  792. }
  793. EVP_PKEY_assign(pkey, EVP_PKEY_RSA, rsa);
  794. BN_set_word(bn, RSA_F4);
  795. if (RSA_generate_key_ex(rsa, RSA_KEY_LENGTH, bn, NULL) != 1) {
  796. goto out;
  797. }
  798. #endif
  799. if (key_file == NULL || cert_file == NULL || cert == NULL || pkey == NULL) {
  800. goto out;
  801. }
  802. ASN1_INTEGER_set(X509_get_serialNumber(cert), 1); // serial number
  803. X509_gmtime_adj(X509_get_notBefore(cert), 0); // now
  804. X509_gmtime_adj(X509_get_notAfter(cert), days * 24 * 3600); // accepts secs
  805. X509_set_pubkey(cert, pkey);
  806. X509_NAME *name = X509_get_subject_name(cert);
  807. const unsigned char *country = (unsigned char *)"smartdns";
  808. const unsigned char *company = (unsigned char *)"smartdns";
  809. const unsigned char *common_name = (unsigned char *)"smartdns";
  810. X509_NAME_add_entry_by_txt(name, "C", MBSTRING_ASC, country, -1, -1, 0);
  811. X509_NAME_add_entry_by_txt(name, "O", MBSTRING_ASC, company, -1, -1, 0);
  812. X509_NAME_add_entry_by_txt(name, "CN", MBSTRING_ASC, common_name, -1, -1, 0);
  813. if (san != NULL) {
  814. cert_ext = X509V3_EXT_conf_nid(NULL, NULL, NID_subject_alt_name, san);
  815. if (cert_ext == NULL) {
  816. goto out;
  817. }
  818. X509_add_ext(cert, cert_ext, -1);
  819. }
  820. X509_set_issuer_name(cert, name);
  821. X509_sign(cert, pkey, EVP_sha256());
  822. ret = PEM_write_bio_PrivateKey(key_file, pkey, NULL, NULL, 0, NULL, NULL);
  823. if (ret != 1) {
  824. goto out;
  825. }
  826. ret = PEM_write_bio_X509(cert_file, cert);
  827. if (ret != 1) {
  828. goto out;
  829. }
  830. chmod(key_path, S_IRUSR);
  831. chmod(cert_path, S_IRUSR);
  832. ret = 0;
  833. out:
  834. if (cert_ext) {
  835. X509_EXTENSION_free(cert_ext);
  836. }
  837. if (pkey) {
  838. EVP_PKEY_free(pkey);
  839. }
  840. #if (OPENSSL_VERSION_NUMBER <= 0x30000000L)
  841. if (rsa && pkey == NULL) {
  842. RSA_free(rsa);
  843. }
  844. if (bn) {
  845. BN_free(bn);
  846. }
  847. #endif
  848. if (cert_file) {
  849. BIO_free_all(cert_file);
  850. }
  851. if (key_file) {
  852. BIO_free_all(key_file);
  853. }
  854. if (cert) {
  855. X509_free(cert);
  856. }
  857. return ret;
  858. }
  859. #if OPENSSL_API_COMPAT < 0x10100000
  860. #define THREAD_STACK_SIZE (16 * 1024)
  861. static pthread_mutex_t *lock_cs;
  862. static long *lock_count;
  863. static __attribute__((unused)) void _pthreads_locking_callback(int mode, int type, const char *file, int line)
  864. {
  865. if (mode & CRYPTO_LOCK) {
  866. pthread_mutex_lock(&(lock_cs[type]));
  867. lock_count[type]++;
  868. } else {
  869. pthread_mutex_unlock(&(lock_cs[type]));
  870. }
  871. }
  872. static __attribute__((unused)) unsigned long _pthreads_thread_id(void)
  873. {
  874. unsigned long ret = 0;
  875. ret = (unsigned long)pthread_self();
  876. return (ret);
  877. }
  878. void SSL_CRYPTO_thread_setup(void)
  879. {
  880. int i = 0;
  881. lock_cs = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
  882. lock_count = OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long));
  883. if (!lock_cs || !lock_count) {
  884. /* Nothing we can do about this...void function! */
  885. if (lock_cs) {
  886. OPENSSL_free(lock_cs);
  887. }
  888. if (lock_count) {
  889. OPENSSL_free(lock_count);
  890. }
  891. return;
  892. }
  893. for (i = 0; i < CRYPTO_num_locks(); i++) {
  894. lock_count[i] = 0;
  895. pthread_mutex_init(&(lock_cs[i]), NULL);
  896. }
  897. #if OPENSSL_API_COMPAT < 0x10000000
  898. CRYPTO_set_id_callback(_pthreads_thread_id);
  899. #else
  900. CRYPTO_THREADID_set_callback(_pthreads_thread_id);
  901. #endif
  902. CRYPTO_set_locking_callback(_pthreads_locking_callback);
  903. }
  904. void SSL_CRYPTO_thread_cleanup(void)
  905. {
  906. int i = 0;
  907. CRYPTO_set_locking_callback(NULL);
  908. for (i = 0; i < CRYPTO_num_locks(); i++) {
  909. pthread_mutex_destroy(&(lock_cs[i]));
  910. }
  911. OPENSSL_free(lock_cs);
  912. OPENSSL_free(lock_count);
  913. }
  914. #endif
  915. #define SERVER_NAME_LEN 256
  916. #define TLS_HEADER_LEN 5
  917. #define TLS_HANDSHAKE_CONTENT_TYPE 0x16
  918. #define TLS_HANDSHAKE_TYPE_CLIENT_HELLO 0x01
  919. #ifndef MIN
  920. #define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
  921. #endif
  922. static int parse_extensions(const char *, size_t, char *, const char **);
  923. static int parse_server_name_extension(const char *, size_t, char *, const char **);
  924. /* Parse a TLS packet for the Server Name Indication extension in the client
  925. * hello handshake, returning the first server name found (pointer to static
  926. * array)
  927. *
  928. * Returns:
  929. * >=0 - length of the hostname and updates *hostname
  930. * caller is responsible for freeing *hostname
  931. * -1 - Incomplete request
  932. * -2 - No Host header included in this request
  933. * -3 - Invalid hostname pointer
  934. * -4 - malloc failure
  935. * < -4 - Invalid TLS client hello
  936. */
  937. int parse_tls_header(const char *data, size_t data_len, char *hostname, const char **hostname_ptr)
  938. {
  939. char tls_content_type = 0;
  940. char tls_version_major = 0;
  941. char tls_version_minor = 0;
  942. size_t pos = TLS_HEADER_LEN;
  943. size_t len = 0;
  944. if (hostname == NULL) {
  945. return -3;
  946. }
  947. /* Check that our TCP payload is at least large enough for a TLS header */
  948. if (data_len < TLS_HEADER_LEN) {
  949. return -1;
  950. }
  951. /* SSL 2.0 compatible Client Hello
  952. *
  953. * High bit of first byte (length) and content type is Client Hello
  954. *
  955. * See RFC5246 Appendix E.2
  956. */
  957. if (data[0] & 0x80 && data[2] == 1) {
  958. return -2;
  959. }
  960. tls_content_type = data[0];
  961. if (tls_content_type != TLS_HANDSHAKE_CONTENT_TYPE) {
  962. return -5;
  963. }
  964. tls_version_major = data[1];
  965. tls_version_minor = data[2];
  966. if (tls_version_major < 3) {
  967. return -2;
  968. }
  969. /* TLS record length */
  970. len = ((unsigned char)data[3] << 8) + (unsigned char)data[4] + TLS_HEADER_LEN;
  971. data_len = MIN(data_len, len);
  972. /* Check we received entire TLS record length */
  973. if (data_len < len) {
  974. return -1;
  975. }
  976. /*
  977. * Handshake
  978. */
  979. if (pos + 1 > data_len) {
  980. return -5;
  981. }
  982. if (data[pos] != TLS_HANDSHAKE_TYPE_CLIENT_HELLO) {
  983. return -5;
  984. }
  985. /* Skip past fixed length records:
  986. * 1 Handshake Type
  987. * 3 Length
  988. * 2 Version (again)
  989. * 32 Random
  990. * to Session ID Length
  991. */
  992. pos += 38;
  993. /* Session ID */
  994. if (pos + 1 > data_len) {
  995. return -5;
  996. }
  997. len = (unsigned char)data[pos];
  998. pos += 1 + len;
  999. /* Cipher Suites */
  1000. if (pos + 2 > data_len) {
  1001. return -5;
  1002. }
  1003. len = ((unsigned char)data[pos] << 8) + (unsigned char)data[pos + 1];
  1004. pos += 2 + len;
  1005. /* Compression Methods */
  1006. if (pos + 1 > data_len) {
  1007. return -5;
  1008. }
  1009. len = (unsigned char)data[pos];
  1010. pos += 1 + len;
  1011. if (pos == data_len && tls_version_major == 3 && tls_version_minor == 0) {
  1012. return -2;
  1013. }
  1014. /* Extensions */
  1015. if (pos + 2 > data_len) {
  1016. return -5;
  1017. }
  1018. len = ((unsigned char)data[pos] << 8) + (unsigned char)data[pos + 1];
  1019. pos += 2;
  1020. if (pos + len > data_len) {
  1021. return -5;
  1022. }
  1023. return parse_extensions(data + pos, len, hostname, hostname_ptr);
  1024. }
  1025. static int parse_extensions(const char *data, size_t data_len, char *hostname, const char **hostname_ptr)
  1026. {
  1027. size_t pos = 0;
  1028. size_t len = 0;
  1029. /* Parse each 4 bytes for the extension header */
  1030. while (pos + 4 <= data_len) {
  1031. /* Extension Length */
  1032. len = ((unsigned char)data[pos + 2] << 8) + (unsigned char)data[pos + 3];
  1033. /* Check if it's a server name extension */
  1034. if (data[pos] == 0x00 && data[pos + 1] == 0x00) {
  1035. /* There can be only one extension of each type, so we break
  1036. * our state and move p to beginning of the extension here */
  1037. if (pos + 4 + len > data_len) {
  1038. return -5;
  1039. }
  1040. return parse_server_name_extension(data + pos + 4, len, hostname, hostname_ptr);
  1041. }
  1042. pos += 4 + len; /* Advance to the next extension header */
  1043. }
  1044. /* Check we ended where we expected to */
  1045. if (pos != data_len) {
  1046. return -5;
  1047. }
  1048. return -2;
  1049. }
  1050. static int parse_server_name_extension(const char *data, size_t data_len, char *hostname, const char **hostname_ptr)
  1051. {
  1052. size_t pos = 2; /* skip server name list length */
  1053. size_t len = 0;
  1054. while (pos + 3 < data_len) {
  1055. len = ((unsigned char)data[pos + 1] << 8) + (unsigned char)data[pos + 2];
  1056. if (pos + 3 + len > data_len) {
  1057. return -5;
  1058. }
  1059. switch (data[pos]) { /* name type */
  1060. case 0x00: /* host_name */
  1061. strncpy(hostname, data + pos + 3, len);
  1062. if (hostname_ptr) {
  1063. *hostname_ptr = data + pos + 3;
  1064. }
  1065. hostname[len] = '\0';
  1066. return len;
  1067. default:
  1068. break;
  1069. }
  1070. pos += 3 + len;
  1071. }
  1072. /* Check we ended where we expected to */
  1073. if (pos != data_len) {
  1074. return -5;
  1075. }
  1076. return -2;
  1077. }
  1078. void get_compiled_time(struct tm *tm)
  1079. {
  1080. char s_month[5];
  1081. int month = 0;
  1082. int day = 0;
  1083. int year = 0;
  1084. int hour = 0;
  1085. int min = 0;
  1086. int sec = 0;
  1087. static const char *month_names = "JanFebMarAprMayJunJulAugSepOctNovDec";
  1088. sscanf(__DATE__, "%4s %d %d", s_month, &day, &year);
  1089. month = (strstr(month_names, s_month) - month_names) / 3;
  1090. sscanf(__TIME__, "%d:%d:%d", &hour, &min, &sec);
  1091. tm->tm_year = year - 1900;
  1092. tm->tm_mon = month;
  1093. tm->tm_mday = day;
  1094. tm->tm_isdst = -1;
  1095. tm->tm_hour = hour;
  1096. tm->tm_min = min;
  1097. tm->tm_sec = sec;
  1098. }
  1099. unsigned long get_system_mem_size(void)
  1100. {
  1101. struct sysinfo memInfo;
  1102. sysinfo(&memInfo);
  1103. long long totalMem = memInfo.totalram;
  1104. totalMem *= memInfo.mem_unit;
  1105. return totalMem;
  1106. }
  1107. int is_numeric(const char *str)
  1108. {
  1109. while (*str != '\0') {
  1110. if (*str < '0' || *str > '9') {
  1111. return -1;
  1112. }
  1113. str++;
  1114. }
  1115. return 0;
  1116. }
  1117. int has_network_raw_cap(void)
  1118. {
  1119. int fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
  1120. if (fd < 0) {
  1121. return 0;
  1122. }
  1123. close(fd);
  1124. return 1;
  1125. }
  1126. int has_unprivileged_ping(void)
  1127. {
  1128. int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_ICMP);
  1129. if (fd < 0) {
  1130. return 0;
  1131. }
  1132. close(fd);
  1133. fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_ICMPV6);
  1134. if (fd < 0) {
  1135. return 0;
  1136. }
  1137. close(fd);
  1138. return 1;
  1139. }
  1140. int set_sock_keepalive(int fd, int keepidle, int keepinterval, int keepcnt)
  1141. {
  1142. const int yes = 1;
  1143. if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes)) != 0) {
  1144. return -1;
  1145. }
  1146. setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
  1147. setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepinterval, sizeof(keepinterval));
  1148. setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepcnt, sizeof(keepcnt));
  1149. return 0;
  1150. }
  1151. int set_sock_lingertime(int fd, int time)
  1152. {
  1153. struct linger l;
  1154. l.l_onoff = 1;
  1155. l.l_linger = 0;
  1156. if (setsockopt(fd, SOL_SOCKET, SO_LINGER, (const char *)&l, sizeof(l)) != 0) {
  1157. return -1;
  1158. }
  1159. return 0;
  1160. }
  1161. uint64_t get_free_space(const char *path)
  1162. {
  1163. uint64_t size = 0;
  1164. struct statvfs buf;
  1165. if (statvfs(path, &buf) != 0) {
  1166. return 0;
  1167. }
  1168. size = (uint64_t)buf.f_frsize * buf.f_bavail;
  1169. return size;
  1170. }
  1171. struct backtrace_state {
  1172. void **current;
  1173. void **end;
  1174. };
  1175. static _Unwind_Reason_Code unwind_callback(struct _Unwind_Context *context, void *arg)
  1176. {
  1177. struct backtrace_state *state = (struct backtrace_state *)(arg);
  1178. uintptr_t pc = _Unwind_GetIP(context);
  1179. if (pc) {
  1180. if (state->current == state->end) {
  1181. return _URC_END_OF_STACK;
  1182. }
  1183. *state->current++ = (void *)(pc);
  1184. }
  1185. return _URC_NO_REASON;
  1186. }
  1187. void print_stack(void)
  1188. {
  1189. const size_t max_buffer = 30;
  1190. void *buffer[max_buffer];
  1191. int idx = 0;
  1192. struct backtrace_state state = {buffer, buffer + max_buffer};
  1193. _Unwind_Backtrace(unwind_callback, &state);
  1194. int frame_num = state.current - buffer;
  1195. if (frame_num == 0) {
  1196. return;
  1197. }
  1198. tlog(TLOG_FATAL, "Stack:");
  1199. for (idx = 0; idx < frame_num; ++idx) {
  1200. const void *addr = buffer[idx];
  1201. const char *symbol = "";
  1202. Dl_info info;
  1203. memset(&info, 0, sizeof(info));
  1204. if (dladdr(addr, &info) && info.dli_sname) {
  1205. symbol = info.dli_sname;
  1206. }
  1207. void *offset = (void *)((char *)(addr) - (char *)(info.dli_fbase));
  1208. tlog(TLOG_FATAL, "#%.2d: %p %s() from %s+%p", idx + 1, addr, symbol, info.dli_fname, offset);
  1209. }
  1210. }
  1211. void bug_ext(const char *file, int line, const char *func, const char *errfmt, ...)
  1212. {
  1213. va_list ap;
  1214. va_start(ap, errfmt);
  1215. tlog_vext(TLOG_FATAL, file, line, func, NULL, errfmt, ap);
  1216. va_end(ap);
  1217. print_stack();
  1218. /* trigger BUG */
  1219. sleep(1);
  1220. raise(SIGSEGV);
  1221. while (true) {
  1222. sleep(1);
  1223. };
  1224. }
  1225. int write_file(const char *filename, void *data, int data_len)
  1226. {
  1227. int fd = open(filename, O_WRONLY | O_CREAT, 0644);
  1228. if (fd < 0) {
  1229. return -1;
  1230. }
  1231. int len = write(fd, data, data_len);
  1232. if (len < 0) {
  1233. goto errout;
  1234. }
  1235. close(fd);
  1236. return 0;
  1237. errout:
  1238. if (fd > 0) {
  1239. close(fd);
  1240. }
  1241. return -1;
  1242. }
  1243. int dns_packet_save(const char *dir, const char *type, const char *from, const void *packet, int packet_len)
  1244. {
  1245. char *data = NULL;
  1246. int data_len = 0;
  1247. char filename[BUFF_SZ];
  1248. char time_s[BUFF_SZ];
  1249. int ret = -1;
  1250. struct tm *ptm;
  1251. struct tm tm;
  1252. struct timeval tm_val;
  1253. struct stat sb;
  1254. if (stat(dir, &sb) != 0) {
  1255. mkdir(dir, 0750);
  1256. }
  1257. if (gettimeofday(&tm_val, NULL) != 0) {
  1258. return -1;
  1259. }
  1260. ptm = localtime_r(&tm_val.tv_sec, &tm);
  1261. if (ptm == NULL) {
  1262. return -1;
  1263. }
  1264. snprintf(time_s, sizeof(time_s) - 1, "%.4d-%.2d-%.2d %.2d:%.2d:%.2d.%.3d", ptm->tm_year + 1900, ptm->tm_mon + 1,
  1265. ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, (int)(tm_val.tv_usec / 1000));
  1266. snprintf(filename, sizeof(filename) - 1, "%s/%s-%.4d%.2d%.2d-%.2d%.2d%.2d%.1d.packet", dir, type,
  1267. ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec,
  1268. (int)(tm_val.tv_usec / 100000));
  1269. data = malloc(PACKET_BUF_SIZE);
  1270. if (data == NULL) {
  1271. return -1;
  1272. }
  1273. data_len = snprintf(data, PACKET_BUF_SIZE,
  1274. "type: %s\n"
  1275. "from: %s\n"
  1276. "time: %s\n"
  1277. "packet-len: %d\n",
  1278. type, from, time_s, packet_len);
  1279. if (data_len <= 0 || data_len >= PACKET_BUF_SIZE) {
  1280. goto out;
  1281. }
  1282. data[data_len] = 0;
  1283. data_len++;
  1284. uint32_t magic = htonl(PACKET_MAGIC);
  1285. memcpy(data + data_len, &magic, sizeof(magic));
  1286. data_len += sizeof(magic);
  1287. int len_in_h = htonl(packet_len);
  1288. memcpy(data + data_len, &len_in_h, sizeof(len_in_h));
  1289. data_len += 4;
  1290. memcpy(data + data_len, packet, packet_len);
  1291. data_len += packet_len;
  1292. ret = write_file(filename, data, data_len);
  1293. if (ret != 0) {
  1294. goto out;
  1295. }
  1296. ret = 0;
  1297. out:
  1298. if (data) {
  1299. free(data);
  1300. }
  1301. return ret;
  1302. }
  1303. static void _close_all_fd_by_res(void)
  1304. {
  1305. struct rlimit lim;
  1306. int maxfd = 0;
  1307. int i = 0;
  1308. getrlimit(RLIMIT_NOFILE, &lim);
  1309. maxfd = lim.rlim_cur;
  1310. if (maxfd > 4096) {
  1311. maxfd = 4096;
  1312. }
  1313. for (i = 3; i < maxfd; i++) {
  1314. close(i);
  1315. }
  1316. }
  1317. void close_all_fd(int keepfd)
  1318. {
  1319. DIR *dirp;
  1320. int dir_fd = -1;
  1321. struct dirent *dentp;
  1322. dirp = opendir("/proc/self/fd");
  1323. if (dirp == NULL) {
  1324. goto errout;
  1325. }
  1326. dir_fd = dirfd(dirp);
  1327. while ((dentp = readdir(dirp)) != NULL) {
  1328. int fd = atol(dentp->d_name);
  1329. if (fd < 0) {
  1330. continue;
  1331. }
  1332. if (fd == dir_fd || fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO || fd == keepfd) {
  1333. continue;
  1334. }
  1335. close(fd);
  1336. }
  1337. closedir(dirp);
  1338. return;
  1339. errout:
  1340. if (dirp) {
  1341. closedir(dirp);
  1342. }
  1343. _close_all_fd_by_res();
  1344. return;
  1345. }
  1346. int daemon_kickoff(int fd, int status, int no_close)
  1347. {
  1348. if (fd <= 0) {
  1349. return -1;
  1350. }
  1351. int ret = write(fd, &status, sizeof(status));
  1352. if (ret != sizeof(status)) {
  1353. return -1;
  1354. }
  1355. if (no_close == 0) {
  1356. int fd_null = open("/dev/null", O_RDWR);
  1357. if (fd_null < 0) {
  1358. fprintf(stderr, "open /dev/null failed, %s\n", strerror(errno));
  1359. return -1;
  1360. }
  1361. dup2(fd_null, STDIN_FILENO);
  1362. dup2(fd_null, STDOUT_FILENO);
  1363. dup2(fd_null, STDERR_FILENO);
  1364. if (fd_null > 2) {
  1365. close(fd_null);
  1366. }
  1367. }
  1368. close(fd);
  1369. return 0;
  1370. }
  1371. int run_daemon()
  1372. {
  1373. pid_t pid = 0;
  1374. int fds[2] = {0};
  1375. if (pipe(fds) != 0) {
  1376. fprintf(stderr, "run daemon process failed, pipe failed, %s\n", strerror(errno));
  1377. return -1;
  1378. }
  1379. pid = fork();
  1380. if (pid < 0) {
  1381. fprintf(stderr, "run daemon process failed, fork failed, %s\n", strerror(errno));
  1382. close(fds[0]);
  1383. close(fds[1]);
  1384. return -1;
  1385. } else if (pid > 0) {
  1386. struct pollfd pfd;
  1387. int ret = 0;
  1388. int status = 0;
  1389. close(fds[1]);
  1390. pfd.fd = fds[0];
  1391. pfd.events = POLLIN;
  1392. pfd.revents = 0;
  1393. ret = poll(&pfd, 1, 1000);
  1394. if (ret <= 0) {
  1395. fprintf(stderr, "run daemon process failed, wait child timeout\n");
  1396. goto errout;
  1397. }
  1398. if (!(pfd.revents & POLLIN)) {
  1399. goto errout;
  1400. }
  1401. ret = read(fds[0], &status, sizeof(status));
  1402. if (ret != sizeof(status)) {
  1403. goto errout;
  1404. }
  1405. return status;
  1406. }
  1407. setsid();
  1408. pid = fork();
  1409. if (pid < 0) {
  1410. fprintf(stderr, "double fork failed, %s\n", strerror(errno));
  1411. _exit(1);
  1412. } else if (pid > 0) {
  1413. _exit(0);
  1414. }
  1415. umask(0);
  1416. if (chdir("/") != 0) {
  1417. goto errout;
  1418. }
  1419. close(fds[0]);
  1420. return fds[1];
  1421. errout:
  1422. kill(pid, SIGKILL);
  1423. return -1;
  1424. }
  1425. #ifdef DEBUG
  1426. struct _dns_read_packet_info {
  1427. int data_len;
  1428. int message_len;
  1429. char *message;
  1430. int packet_len;
  1431. uint8_t *packet;
  1432. uint8_t data[0];
  1433. };
  1434. static struct _dns_read_packet_info *_dns_read_packet_file(const char *packet_file)
  1435. {
  1436. struct _dns_read_packet_info *info = NULL;
  1437. int fd = 0;
  1438. int len = 0;
  1439. int message_len = 0;
  1440. uint8_t *ptr = NULL;
  1441. info = malloc(sizeof(struct _dns_read_packet_info) + PACKET_BUF_SIZE);
  1442. fd = open(packet_file, O_RDONLY);
  1443. if (fd < 0) {
  1444. printf("open file %s failed, %s\n", packet_file, strerror(errno));
  1445. goto errout;
  1446. }
  1447. len = read(fd, info->data, PACKET_BUF_SIZE);
  1448. if (len < 0) {
  1449. printf("read file %s failed, %s\n", packet_file, strerror(errno));
  1450. goto errout;
  1451. }
  1452. message_len = strnlen((char *)info->data, PACKET_BUF_SIZE);
  1453. if (message_len >= 512 || message_len >= len) {
  1454. printf("invalid packet file, bad message len\n");
  1455. goto errout;
  1456. }
  1457. info->message_len = message_len;
  1458. info->message = (char *)info->data;
  1459. ptr = info->data + message_len + 1;
  1460. uint32_t magic = 0;
  1461. if (ptr - (uint8_t *)info + sizeof(magic) >= (size_t)len) {
  1462. printf("invalid packet file, magic length is invalid.\n");
  1463. goto errout;
  1464. }
  1465. memcpy(&magic, ptr, sizeof(magic));
  1466. if (magic != htonl(PACKET_MAGIC)) {
  1467. printf("invalid packet file, bad magic\n");
  1468. goto errout;
  1469. }
  1470. ptr += sizeof(magic);
  1471. uint32_t packet_len = 0;
  1472. if (ptr - info->data + sizeof(packet_len) >= (size_t)len) {
  1473. printf("invalid packet file, packet length is invalid.\n");
  1474. goto errout;
  1475. }
  1476. memcpy(&packet_len, ptr, sizeof(packet_len));
  1477. packet_len = ntohl(packet_len);
  1478. ptr += sizeof(packet_len);
  1479. if (packet_len != (size_t)len - (ptr - info->data)) {
  1480. printf("invalid packet file, packet length is invalid\n");
  1481. goto errout;
  1482. }
  1483. info->packet_len = packet_len;
  1484. info->packet = ptr;
  1485. close(fd);
  1486. return info;
  1487. errout:
  1488. if (fd > 0) {
  1489. close(fd);
  1490. }
  1491. if (info) {
  1492. free(info);
  1493. }
  1494. return NULL;
  1495. }
  1496. static int _dns_debug_display(struct dns_packet *packet)
  1497. {
  1498. int i = 0;
  1499. int j = 0;
  1500. int ttl = 0;
  1501. struct dns_rrs *rrs = NULL;
  1502. int rr_count = 0;
  1503. char req_host[MAX_IP_LEN];
  1504. for (j = 1; j < DNS_RRS_END; j++) {
  1505. rrs = dns_get_rrs_start(packet, j, &rr_count);
  1506. printf("section: %d\n", j);
  1507. for (i = 0; i < rr_count && rrs; i++, rrs = dns_get_rrs_next(packet, rrs)) {
  1508. switch (rrs->type) {
  1509. case DNS_T_A: {
  1510. unsigned char addr[4];
  1511. char name[DNS_MAX_CNAME_LEN] = {0};
  1512. /* get A result */
  1513. dns_get_A(rrs, name, DNS_MAX_CNAME_LEN, &ttl, addr);
  1514. req_host[0] = '\0';
  1515. inet_ntop(AF_INET, addr, req_host, sizeof(req_host));
  1516. printf("domain: %s A: %s TTL: %d\n", name, req_host, ttl);
  1517. } break;
  1518. case DNS_T_AAAA: {
  1519. unsigned char addr[16];
  1520. char name[DNS_MAX_CNAME_LEN] = {0};
  1521. dns_get_AAAA(rrs, name, DNS_MAX_CNAME_LEN, &ttl, addr);
  1522. req_host[0] = '\0';
  1523. inet_ntop(AF_INET6, addr, req_host, sizeof(req_host));
  1524. printf("domain: %s AAAA: %s TTL:%d\n", name, req_host, ttl);
  1525. } break;
  1526. case DNS_T_HTTPS: {
  1527. char name[DNS_MAX_CNAME_LEN] = {0};
  1528. char target[DNS_MAX_CNAME_LEN] = {0};
  1529. struct dns_https_param *p = NULL;
  1530. int priority = 0;
  1531. int ret = 0;
  1532. ret = dns_get_HTTPS_svcparm_start(rrs, &p, name, DNS_MAX_CNAME_LEN, &ttl, &priority, target,
  1533. DNS_MAX_CNAME_LEN);
  1534. if (ret != 0) {
  1535. printf("get HTTPS svcparm failed\n");
  1536. break;
  1537. }
  1538. printf("domain: %s HTTPS: %s TTL: %d priority: %d\n", name, target, ttl, priority);
  1539. for (; p; p = dns_get_HTTPS_svcparm_next(rrs, p)) {
  1540. switch (p->key) {
  1541. case DNS_HTTPS_T_MANDATORY: {
  1542. printf(" HTTPS: mandatory: %s\n", p->value);
  1543. } break;
  1544. case DNS_HTTPS_T_ALPN: {
  1545. char alph[64] = {0};
  1546. int total_alph_len = 0;
  1547. char *ptr = (char *)p->value;
  1548. do {
  1549. int alphlen = *ptr;
  1550. memcpy(alph + total_alph_len, ptr + 1, alphlen);
  1551. total_alph_len += alphlen;
  1552. ptr += alphlen + 1;
  1553. alph[total_alph_len] = ',';
  1554. total_alph_len++;
  1555. alph[total_alph_len] = ' ';
  1556. total_alph_len++;
  1557. } while (ptr - (char *)p->value < p->len);
  1558. if (total_alph_len > 2) {
  1559. alph[total_alph_len - 2] = '\0';
  1560. }
  1561. printf(" HTTPS: alpn: %s\n", alph);
  1562. } break;
  1563. case DNS_HTTPS_T_NO_DEFAULT_ALPN: {
  1564. printf(" HTTPS: no_default_alpn: %s\n", p->value);
  1565. } break;
  1566. case DNS_HTTPS_T_PORT: {
  1567. int port = *(unsigned short *)(p->value);
  1568. printf(" HTTPS: port: %d\n", port);
  1569. } break;
  1570. case DNS_HTTPS_T_IPV4HINT: {
  1571. printf(" HTTPS: ipv4hint: %d\n", p->len / 4);
  1572. for (int k = 0; k < p->len / 4; k++) {
  1573. char ip[16] = {0};
  1574. inet_ntop(AF_INET, p->value + k * 4, ip, sizeof(ip));
  1575. printf(" ipv4: %s\n", ip);
  1576. }
  1577. } break;
  1578. case DNS_HTTPS_T_ECH: {
  1579. printf(" HTTPS: ech: ");
  1580. for (int k = 0; k < p->len; k++) {
  1581. printf("%02x ", p->value[k]);
  1582. }
  1583. printf("\n");
  1584. } break;
  1585. case DNS_HTTPS_T_IPV6HINT: {
  1586. printf(" HTTPS: ipv6hint: %d\n", p->len / 16);
  1587. for (int k = 0; k < p->len / 16; k++) {
  1588. char ip[64] = {0};
  1589. inet_ntop(AF_INET6, p->value + k * 16, ip, sizeof(ip));
  1590. printf(" ipv6: %s\n", ip);
  1591. }
  1592. } break;
  1593. }
  1594. }
  1595. } break;
  1596. case DNS_T_NS: {
  1597. char cname[DNS_MAX_CNAME_LEN];
  1598. char name[DNS_MAX_CNAME_LEN] = {0};
  1599. dns_get_CNAME(rrs, name, DNS_MAX_CNAME_LEN, &ttl, cname, DNS_MAX_CNAME_LEN);
  1600. printf("domain: %s TTL: %d NS: %s\n", name, ttl, cname);
  1601. } break;
  1602. case DNS_T_CNAME: {
  1603. char cname[DNS_MAX_CNAME_LEN];
  1604. char name[DNS_MAX_CNAME_LEN] = {0};
  1605. if (dns_conf_force_no_cname) {
  1606. continue;
  1607. }
  1608. dns_get_CNAME(rrs, name, DNS_MAX_CNAME_LEN, &ttl, cname, DNS_MAX_CNAME_LEN);
  1609. printf("domain: %s TTL: %d CNAME: %s\n", name, ttl, cname);
  1610. } break;
  1611. case DNS_T_SOA: {
  1612. char name[DNS_MAX_CNAME_LEN] = {0};
  1613. struct dns_soa soa;
  1614. dns_get_SOA(rrs, name, 128, &ttl, &soa);
  1615. printf("domain: %s SOA: mname: %s, rname: %s, serial: %d, refresh: %d, retry: %d, expire: "
  1616. "%d, minimum: %d",
  1617. name, soa.mname, soa.rname, soa.serial, soa.refresh, soa.retry, soa.expire, soa.minimum);
  1618. } break;
  1619. default:
  1620. break;
  1621. }
  1622. }
  1623. printf("\n");
  1624. }
  1625. return 0;
  1626. }
  1627. int dns_packet_debug(const char *packet_file)
  1628. {
  1629. struct _dns_read_packet_info *info = NULL;
  1630. char buff[DNS_PACKSIZE];
  1631. tlog_set_maxlog_count(0);
  1632. tlog_setlogscreen(1);
  1633. tlog_setlevel(TLOG_DEBUG);
  1634. info = _dns_read_packet_file(packet_file);
  1635. if (info == NULL) {
  1636. goto errout;
  1637. }
  1638. const char *send_env = getenv("SMARTDNS_DEBUG_SEND");
  1639. if (send_env != NULL) {
  1640. char ip[32];
  1641. int port = 53;
  1642. if (parse_ip(send_env, ip, &port) == 0) {
  1643. int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
  1644. if (sockfd > 0) {
  1645. struct sockaddr_in server;
  1646. server.sin_family = AF_INET;
  1647. server.sin_port = htons(port);
  1648. server.sin_addr.s_addr = inet_addr(ip);
  1649. sendto(sockfd, info->packet, info->packet_len, 0, (struct sockaddr *)&server, sizeof(server));
  1650. close(sockfd);
  1651. }
  1652. }
  1653. }
  1654. struct dns_packet *packet = (struct dns_packet *)buff;
  1655. if (dns_decode(packet, DNS_PACKSIZE, info->packet, info->packet_len) != 0) {
  1656. printf("decode failed.\n");
  1657. goto errout;
  1658. }
  1659. _dns_debug_display(packet);
  1660. free(info);
  1661. return 0;
  1662. errout:
  1663. if (info) {
  1664. free(info);
  1665. }
  1666. return -1;
  1667. }
  1668. #endif