util.c 41 KB

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