res_hconf.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /* Copyright (C) 1993-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by David Mosberger (davidm@azstarnet.com).
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. /* This file provides a Linux /etc/host.conf compatible front end to
  16. the various name resolvers (/etc/hosts, named, NIS server, etc.).
  17. Though mostly compatibly, the following differences exist compared
  18. to the original implementation:
  19. - line comments can appear anywhere (not just at the beginning of
  20. a line)
  21. */
  22. #include <assert.h>
  23. #include <errno.h>
  24. #include <ctype.h>
  25. #include <libintl.h>
  26. #include <memory.h>
  27. #include <stdio.h>
  28. #include <stdio_ext.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #include <net/if.h>
  32. #include <sys/ioctl.h>
  33. #include <unistd.h>
  34. #include <netinet/in.h>
  35. #include <libc-lock.h>
  36. #include "ifreq.h"
  37. #include "res_hconf.h"
  38. #include <wchar.h>
  39. #include <atomic.h>
  40. #if IS_IN (libc)
  41. # define fgets_unlocked __fgets_unlocked
  42. #endif
  43. #define _PATH_HOSTCONF "/etc/host.conf"
  44. /* Environment vars that all user to override default behavior: */
  45. #define ENV_HOSTCONF "RESOLV_HOST_CONF"
  46. #define ENV_TRIM_OVERR "RESOLV_OVERRIDE_TRIM_DOMAINS"
  47. #define ENV_TRIM_ADD "RESOLV_ADD_TRIM_DOMAINS"
  48. #define ENV_MULTI "RESOLV_MULTI"
  49. #define ENV_REORDER "RESOLV_REORDER"
  50. enum parse_cbs
  51. {
  52. CB_none,
  53. CB_arg_trimdomain_list,
  54. CB_arg_bool
  55. };
  56. static const struct cmd
  57. {
  58. const char name[11];
  59. uint8_t cb;
  60. unsigned int arg;
  61. } cmd[] =
  62. {
  63. {"order", CB_none, 0},
  64. {"trim", CB_arg_trimdomain_list, 0},
  65. {"multi", CB_arg_bool, HCONF_FLAG_MULTI},
  66. {"reorder", CB_arg_bool, HCONF_FLAG_REORDER}
  67. };
  68. /* Structure containing the state. */
  69. struct hconf _res_hconf;
  70. /* Skip white space. */
  71. static const char *
  72. skip_ws (const char *str)
  73. {
  74. while (isspace (*str)) ++str;
  75. return str;
  76. }
  77. /* Skip until whitespace, comma, end of line, or comment character. */
  78. static const char *
  79. skip_string (const char *str)
  80. {
  81. while (*str && !isspace (*str) && *str != '#' && *str != ',')
  82. ++str;
  83. return str;
  84. }
  85. static const char *
  86. arg_trimdomain_list (const char *fname, int line_num, const char *args)
  87. {
  88. const char * start;
  89. size_t len;
  90. do
  91. {
  92. start = args;
  93. args = skip_string (args);
  94. len = args - start;
  95. if (_res_hconf.num_trimdomains >= TRIMDOMAINS_MAX)
  96. {
  97. char *buf;
  98. if (__asprintf (&buf, _("\
  99. %s: line %d: cannot specify more than %d trim domains"),
  100. fname, line_num, TRIMDOMAINS_MAX) < 0)
  101. return 0;
  102. __fxprintf (NULL, "%s", buf);
  103. free (buf);
  104. return 0;
  105. }
  106. _res_hconf.trimdomain[_res_hconf.num_trimdomains++] =
  107. __strndup (start, len);
  108. args = skip_ws (args);
  109. switch (*args)
  110. {
  111. case ',': case ';': case ':':
  112. args = skip_ws (++args);
  113. if (!*args || *args == '#')
  114. {
  115. char *buf;
  116. if (__asprintf (&buf, _("\
  117. %s: line %d: list delimiter not followed by domain"),
  118. fname, line_num) < 0)
  119. return 0;
  120. __fxprintf (NULL, "%s", buf);
  121. free (buf);
  122. return 0;
  123. }
  124. default:
  125. break;
  126. }
  127. }
  128. while (*args && *args != '#');
  129. return args;
  130. }
  131. static const char *
  132. arg_bool (const char *fname, int line_num, const char *args, unsigned flag)
  133. {
  134. if (__strncasecmp (args, "on", 2) == 0)
  135. {
  136. args += 2;
  137. _res_hconf.flags |= flag;
  138. }
  139. else if (__strncasecmp (args, "off", 3) == 0)
  140. {
  141. args += 3;
  142. _res_hconf.flags &= ~flag;
  143. }
  144. else
  145. {
  146. char *buf;
  147. if (__asprintf (&buf,
  148. _("%s: line %d: expected `on' or `off', found `%s'\n"),
  149. fname, line_num, args) < 0)
  150. return 0;
  151. __fxprintf (NULL, "%s", buf);
  152. free (buf);
  153. return 0;
  154. }
  155. return args;
  156. }
  157. static void
  158. parse_line (const char *fname, int line_num, const char *str)
  159. {
  160. const char *start;
  161. const struct cmd *c = 0;
  162. size_t len;
  163. size_t i;
  164. str = skip_ws (str);
  165. /* skip line comment and empty lines: */
  166. if (*str == '\0' || *str == '#') return;
  167. start = str;
  168. str = skip_string (str);
  169. len = str - start;
  170. for (i = 0; i < sizeof (cmd) / sizeof (cmd[0]); ++i)
  171. {
  172. if (__strncasecmp (start, cmd[i].name, len) == 0
  173. && strlen (cmd[i].name) == len)
  174. {
  175. c = &cmd[i];
  176. break;
  177. }
  178. }
  179. if (c == NULL)
  180. {
  181. char *buf;
  182. if (__asprintf (&buf, _("%s: line %d: bad command `%s'\n"),
  183. fname, line_num, start) < 0)
  184. return;
  185. __fxprintf (NULL, "%s", buf);
  186. free (buf);
  187. return;
  188. }
  189. /* process args: */
  190. str = skip_ws (str);
  191. if (c->cb == CB_arg_trimdomain_list)
  192. str = arg_trimdomain_list (fname, line_num, str);
  193. else if (c->cb == CB_arg_bool)
  194. str = arg_bool (fname, line_num, str, c->arg);
  195. else
  196. /* Ignore the line. */
  197. return;
  198. if (!str)
  199. return;
  200. /* rest of line must contain white space or comment only: */
  201. while (*str)
  202. {
  203. if (!isspace (*str)) {
  204. if (*str != '#')
  205. {
  206. char *buf;
  207. if (__asprintf (&buf,
  208. _("%s: line %d: ignoring trailing garbage `%s'\n"),
  209. fname, line_num, str) < 0)
  210. break;
  211. __fxprintf (NULL, "%s", buf);
  212. free (buf);
  213. }
  214. break;
  215. }
  216. ++str;
  217. }
  218. }
  219. static void
  220. do_init (void)
  221. {
  222. const char *hconf_name;
  223. int line_num = 0;
  224. char buf[256], *envval;
  225. FILE *fp;
  226. memset (&_res_hconf, '\0', sizeof (_res_hconf));
  227. hconf_name = getenv (ENV_HOSTCONF);
  228. if (hconf_name == NULL)
  229. hconf_name = _PATH_HOSTCONF;
  230. fp = fopen (hconf_name, "rce");
  231. if (fp)
  232. {
  233. /* No threads using this stream. */
  234. __fsetlocking (fp, FSETLOCKING_BYCALLER);
  235. while (fgets_unlocked (buf, sizeof (buf), fp))
  236. {
  237. ++line_num;
  238. *__strchrnul (buf, '\n') = '\0';
  239. parse_line (hconf_name, line_num, buf);
  240. }
  241. fclose (fp);
  242. }
  243. envval = getenv (ENV_MULTI);
  244. if (envval)
  245. arg_bool (ENV_MULTI, 1, envval, HCONF_FLAG_MULTI);
  246. envval = getenv (ENV_REORDER);
  247. if (envval)
  248. arg_bool (ENV_REORDER, 1, envval, HCONF_FLAG_REORDER);
  249. envval = getenv (ENV_TRIM_ADD);
  250. if (envval)
  251. arg_trimdomain_list (ENV_TRIM_ADD, 1, envval);
  252. envval = getenv (ENV_TRIM_OVERR);
  253. if (envval)
  254. {
  255. _res_hconf.num_trimdomains = 0;
  256. arg_trimdomain_list (ENV_TRIM_OVERR, 1, envval);
  257. }
  258. /* See comments on the declaration of _res_hconf. */
  259. atomic_store_release (&_res_hconf.initialized, 1);
  260. }
  261. /* Initialize hconf datastructure by reading host.conf file and
  262. environment variables. */
  263. void
  264. _res_hconf_init (void)
  265. {
  266. __libc_once_define (static, once);
  267. __libc_once (once, do_init);
  268. }
  269. #if IS_IN (libc)
  270. # if defined SIOCGIFCONF && defined SIOCGIFNETMASK
  271. /* List of known interfaces. */
  272. libc_freeres_ptr (
  273. static struct netaddr
  274. {
  275. int addrtype;
  276. union
  277. {
  278. struct
  279. {
  280. uint32_t addr;
  281. uint32_t mask;
  282. } ipv4;
  283. } u;
  284. } *ifaddrs);
  285. # endif
  286. /* Reorder addresses returned in a hostent such that the first address
  287. is an address on the local subnet, if there is such an address.
  288. Otherwise, nothing is changed.
  289. Note that this function currently only handles IPv4 addresses. */
  290. void
  291. _res_hconf_reorder_addrs (struct hostent *hp)
  292. {
  293. #if defined SIOCGIFCONF && defined SIOCGIFNETMASK
  294. int i, j;
  295. /* Number of interfaces. Also serves as a flag for the
  296. double-checked locking idiom. */
  297. static int num_ifs = -1;
  298. /* Local copy of num_ifs, for non-atomic access. */
  299. int num_ifs_local;
  300. /* We need to protect the dynamic buffer handling. The lock is only
  301. acquired during initialization. Afterwards, a positive num_ifs
  302. value indicates completed initialization. */
  303. __libc_lock_define_initialized (static, lock);
  304. /* Only reorder if we're supposed to. */
  305. if ((_res_hconf.flags & HCONF_FLAG_REORDER) == 0)
  306. return;
  307. /* Can't deal with anything but IPv4 for now... */
  308. if (hp->h_addrtype != AF_INET)
  309. return;
  310. /* This load synchronizes with the release MO store in the
  311. initialization block below. */
  312. num_ifs_local = atomic_load_acquire (&num_ifs);
  313. if (num_ifs_local <= 0)
  314. {
  315. struct ifreq *ifr, *cur_ifr;
  316. int sd, num, i;
  317. /* Save errno. */
  318. int save = errno;
  319. /* Initialize interface table. */
  320. /* The SIOCGIFNETMASK ioctl will only work on an AF_INET socket. */
  321. sd = __socket (AF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
  322. if (sd < 0)
  323. return;
  324. /* Get lock. */
  325. __libc_lock_lock (lock);
  326. /* Recheck, somebody else might have done the work by now. No
  327. ordering is required for the load because we have the lock,
  328. and num_ifs is only updated under the lock. Also see (3) in
  329. the analysis below. */
  330. num_ifs_local = atomic_load_relaxed (&num_ifs);
  331. if (num_ifs_local <= 0)
  332. {
  333. /* This is the only block which writes to num_ifs. It can
  334. be executed several times (sequentially) if
  335. initialization does not yield any interfaces, and num_ifs
  336. remains zero. However, once we stored a positive value
  337. in num_ifs below, this block cannot be entered again due
  338. to the condition above. */
  339. int new_num_ifs = 0;
  340. /* Get a list of interfaces. */
  341. __ifreq (&ifr, &num, sd);
  342. if (!ifr)
  343. goto cleanup;
  344. ifaddrs = malloc (num * sizeof (ifaddrs[0]));
  345. if (!ifaddrs)
  346. goto cleanup1;
  347. /* Copy usable interfaces in ifaddrs structure. */
  348. for (cur_ifr = ifr, i = 0; i < num;
  349. cur_ifr = __if_nextreq (cur_ifr), ++i)
  350. {
  351. union
  352. {
  353. struct sockaddr sa;
  354. struct sockaddr_in sin;
  355. } ss;
  356. if (cur_ifr->ifr_addr.sa_family != AF_INET)
  357. continue;
  358. ifaddrs[new_num_ifs].addrtype = AF_INET;
  359. ss.sa = cur_ifr->ifr_addr;
  360. ifaddrs[new_num_ifs].u.ipv4.addr = ss.sin.sin_addr.s_addr;
  361. if (__ioctl (sd, SIOCGIFNETMASK, cur_ifr) < 0)
  362. continue;
  363. ss.sa = cur_ifr->ifr_netmask;
  364. ifaddrs[new_num_ifs].u.ipv4.mask = ss.sin.sin_addr.s_addr;
  365. /* Now we're committed to this entry. */
  366. ++new_num_ifs;
  367. }
  368. /* Just keep enough memory to hold all the interfaces we want. */
  369. ifaddrs = realloc (ifaddrs, new_num_ifs * sizeof (ifaddrs[0]));
  370. assert (ifaddrs != NULL);
  371. cleanup1:
  372. __if_freereq (ifr, num);
  373. cleanup:
  374. /* Release lock, preserve error value, and close socket. */
  375. errno = save;
  376. /* Advertise successful initialization if new_num_ifs is
  377. positive (and no updates to ifaddrs are permitted after
  378. that). Otherwise, num_ifs remains unchanged, at zero.
  379. This store synchronizes with the initial acquire MO
  380. load. */
  381. atomic_store_release (&num_ifs, new_num_ifs);
  382. /* Keep the local copy current, to save another load. */
  383. num_ifs_local = new_num_ifs;
  384. }
  385. __libc_lock_unlock (lock);
  386. __close (sd);
  387. }
  388. /* num_ifs_local cannot be negative because the if statement above
  389. covered this case. It can still be zero if we just performed
  390. initialization, but could not find any interfaces. */
  391. if (num_ifs_local == 0)
  392. return;
  393. /* The code below accesses ifaddrs, so we need to ensure that the
  394. initialization happens-before this point.
  395. The actual initialization is sequenced-before the release store
  396. to num_ifs, and sequenced-before the end of the critical section.
  397. This means there are three possible executions:
  398. (1) The thread that initialized the data also uses it, so
  399. sequenced-before is sufficient to ensure happens-before.
  400. (2) The release MO store of num_ifs synchronizes-with the acquire
  401. MO load, and the acquire MO load is sequenced before the use
  402. of the initialized data below.
  403. (3) We enter the critical section, and the relaxed MO load of
  404. num_ifs yields a positive value. The write to ifaddrs is
  405. sequenced-before leaving the critical section. Leaving the
  406. critical section happens-before we entered the critical
  407. section ourselves, which means that the write to ifaddrs
  408. happens-before this point.
  409. Consequently, all potential writes to ifaddrs (and the data it
  410. points to) happens-before this point. */
  411. /* Find an address for which we have a direct connection. */
  412. for (i = 0; hp->h_addr_list[i]; ++i)
  413. {
  414. struct in_addr *haddr = (struct in_addr *) hp->h_addr_list[i];
  415. for (j = 0; j < num_ifs_local; ++j)
  416. {
  417. uint32_t if_addr = ifaddrs[j].u.ipv4.addr;
  418. uint32_t if_netmask = ifaddrs[j].u.ipv4.mask;
  419. if (((haddr->s_addr ^ if_addr) & if_netmask) == 0)
  420. {
  421. void *tmp;
  422. tmp = hp->h_addr_list[i];
  423. hp->h_addr_list[i] = hp->h_addr_list[0];
  424. hp->h_addr_list[0] = tmp;
  425. return;
  426. }
  427. }
  428. }
  429. #endif /* defined(SIOCGIFCONF) && ... */
  430. }
  431. /* If HOSTNAME has a postfix matching any of the trimdomains, trim away
  432. that postfix. Notice that HOSTNAME is modified inplace. Also, the
  433. original code applied all trimdomains in order, meaning that the
  434. same domainname could be trimmed multiple times. I believe this
  435. was unintentional. */
  436. void
  437. _res_hconf_trim_domain (char *hostname)
  438. {
  439. size_t hostname_len, trim_len;
  440. int i;
  441. hostname_len = strlen (hostname);
  442. for (i = 0; i < _res_hconf.num_trimdomains; ++i)
  443. {
  444. const char *trim = _res_hconf.trimdomain[i];
  445. trim_len = strlen (trim);
  446. if (hostname_len > trim_len
  447. && __strcasecmp (&hostname[hostname_len - trim_len], trim) == 0)
  448. {
  449. hostname[hostname_len - trim_len] = '\0';
  450. break;
  451. }
  452. }
  453. }
  454. /* Trim all hostnames/aliases in HP according to the trimdomain list.
  455. Notice that HP is modified inplace! */
  456. void
  457. _res_hconf_trim_domains (struct hostent *hp)
  458. {
  459. int i;
  460. if (_res_hconf.num_trimdomains == 0)
  461. return;
  462. _res_hconf_trim_domain (hp->h_name);
  463. for (i = 0; hp->h_aliases[i]; ++i)
  464. _res_hconf_trim_domain (hp->h_aliases[i]);
  465. }
  466. #endif