/contrib/bind9/bin/named/unix/os.c

https://bitbucket.org/freebsd/freebsd-head/ · C · 965 lines · 684 code · 116 blank · 165 comment · 184 complexity · 4d74f95bd40cf152049d8b76ae8b66ed MD5 · raw file

  1. /*
  2. * Copyright (C) 2004-2011 Internet Systems Consortium, Inc. ("ISC")
  3. * Copyright (C) 1999-2002 Internet Software Consortium.
  4. *
  5. * Permission to use, copy, modify, and/or distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  10. * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  11. * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  12. * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  13. * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  14. * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  15. * PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. /* $Id: os.c,v 1.104.38.3 2011/03/02 00:04:01 marka Exp $ */
  18. /*! \file */
  19. #include <config.h>
  20. #include <stdarg.h>
  21. #include <sys/types.h> /* dev_t FreeBSD 2.1 */
  22. #include <sys/stat.h>
  23. #include <ctype.h>
  24. #include <errno.h>
  25. #include <fcntl.h>
  26. #include <grp.h> /* Required for initgroups() on IRIX. */
  27. #include <pwd.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <signal.h>
  31. #include <syslog.h>
  32. #ifdef HAVE_TZSET
  33. #include <time.h>
  34. #endif
  35. #include <unistd.h>
  36. #include <isc/buffer.h>
  37. #include <isc/file.h>
  38. #include <isc/print.h>
  39. #include <isc/resource.h>
  40. #include <isc/result.h>
  41. #include <isc/strerror.h>
  42. #include <isc/string.h>
  43. #include <named/main.h>
  44. #include <named/os.h>
  45. #ifdef HAVE_LIBSCF
  46. #include <named/ns_smf_globals.h>
  47. #endif
  48. static char *pidfile = NULL;
  49. static int devnullfd = -1;
  50. #ifndef ISC_FACILITY
  51. #define ISC_FACILITY LOG_DAEMON
  52. #endif
  53. /*
  54. * If there's no <linux/capability.h>, we don't care about <sys/prctl.h>
  55. */
  56. #ifndef HAVE_LINUX_CAPABILITY_H
  57. #undef HAVE_SYS_PRCTL_H
  58. #endif
  59. /*
  60. * Linux defines:
  61. * (T) HAVE_LINUXTHREADS
  62. * (C) HAVE_SYS_CAPABILITY_H (or HAVE_LINUX_CAPABILITY_H)
  63. * (P) HAVE_SYS_PRCTL_H
  64. * The possible cases are:
  65. * none: setuid() normally
  66. * T: no setuid()
  67. * C: setuid() normally, drop caps (keep CAP_SETUID)
  68. * T+C: no setuid(), drop caps (don't keep CAP_SETUID)
  69. * T+C+P: setuid() early, drop caps (keep CAP_SETUID)
  70. * C+P: setuid() normally, drop caps (keep CAP_SETUID)
  71. * P: not possible
  72. * T+P: not possible
  73. *
  74. * if (C)
  75. * caps = BIND_SERVICE + CHROOT + SETGID
  76. * if ((T && C && P) || !T)
  77. * caps += SETUID
  78. * endif
  79. * capset(caps)
  80. * endif
  81. * if (T && C && P && -u)
  82. * setuid()
  83. * else if (T && -u)
  84. * fail
  85. * --> start threads
  86. * if (!T && -u)
  87. * setuid()
  88. * if (C && (P || !-u))
  89. * caps = BIND_SERVICE
  90. * capset(caps)
  91. * endif
  92. *
  93. * It will be nice when Linux threads work properly with setuid().
  94. */
  95. #ifdef HAVE_LINUXTHREADS
  96. static pid_t mainpid = 0;
  97. #endif
  98. static struct passwd *runas_pw = NULL;
  99. static isc_boolean_t done_setuid = ISC_FALSE;
  100. static int dfd[2] = { -1, -1 };
  101. #ifdef HAVE_LINUX_CAPABILITY_H
  102. static isc_boolean_t non_root = ISC_FALSE;
  103. static isc_boolean_t non_root_caps = ISC_FALSE;
  104. #ifdef HAVE_SYS_CAPABILITY_H
  105. #include <sys/capability.h>
  106. #else
  107. /*%
  108. * We define _LINUX_FS_H to prevent it from being included. We don't need
  109. * anything from it, and the files it includes cause warnings with 2.2
  110. * kernels, and compilation failures (due to conflicts between <linux/string.h>
  111. * and <string.h>) on 2.3 kernels.
  112. */
  113. #define _LINUX_FS_H
  114. #include <linux/capability.h>
  115. #include <syscall.h>
  116. #ifndef SYS_capset
  117. #ifndef __NR_capset
  118. #include <asm/unistd.h> /* Slackware 4.0 needs this. */
  119. #endif /* __NR_capset */
  120. #define SYS_capset __NR_capset
  121. #endif /* SYS_capset */
  122. #endif /* HAVE_SYS_CAPABILITY_H */
  123. #ifdef HAVE_SYS_PRCTL_H
  124. #include <sys/prctl.h> /* Required for prctl(). */
  125. /*
  126. * If the value of PR_SET_KEEPCAPS is not in <sys/prctl.h>, define it
  127. * here. This allows setuid() to work on systems running a new enough
  128. * kernel but with /usr/include/linux pointing to "standard" kernel
  129. * headers.
  130. */
  131. #ifndef PR_SET_KEEPCAPS
  132. #define PR_SET_KEEPCAPS 8
  133. #endif
  134. #endif /* HAVE_SYS_PRCTL_H */
  135. #ifdef HAVE_LIBCAP
  136. #define SETCAPS_FUNC "cap_set_proc "
  137. #else
  138. typedef unsigned int cap_t;
  139. #define SETCAPS_FUNC "syscall(capset) "
  140. #endif /* HAVE_LIBCAP */
  141. static void
  142. linux_setcaps(cap_t caps) {
  143. #ifndef HAVE_LIBCAP
  144. struct __user_cap_header_struct caphead;
  145. struct __user_cap_data_struct cap;
  146. #endif
  147. char strbuf[ISC_STRERRORSIZE];
  148. if ((getuid() != 0 && !non_root_caps) || non_root)
  149. return;
  150. #ifndef HAVE_LIBCAP
  151. memset(&caphead, 0, sizeof(caphead));
  152. caphead.version = _LINUX_CAPABILITY_VERSION;
  153. caphead.pid = 0;
  154. memset(&cap, 0, sizeof(cap));
  155. cap.effective = caps;
  156. cap.permitted = caps;
  157. cap.inheritable = 0;
  158. #endif
  159. #ifdef HAVE_LIBCAP
  160. if (cap_set_proc(caps) < 0) {
  161. #else
  162. if (syscall(SYS_capset, &caphead, &cap) < 0) {
  163. #endif
  164. isc__strerror(errno, strbuf, sizeof(strbuf));
  165. ns_main_earlyfatal(SETCAPS_FUNC "failed: %s:"
  166. " please ensure that the capset kernel"
  167. " module is loaded. see insmod(8)",
  168. strbuf);
  169. }
  170. }
  171. #ifdef HAVE_LIBCAP
  172. #define SET_CAP(flag) \
  173. do { \
  174. capval = (flag); \
  175. cap_flag_value_t curval; \
  176. err = cap_get_flag(curcaps, capval, CAP_PERMITTED, &curval); \
  177. if (err != -1 && curval) { \
  178. err = cap_set_flag(caps, CAP_EFFECTIVE, 1, &capval, CAP_SET); \
  179. if (err == -1) { \
  180. isc__strerror(errno, strbuf, sizeof(strbuf)); \
  181. ns_main_earlyfatal("cap_set_proc failed: %s", strbuf); \
  182. } \
  183. \
  184. err = cap_set_flag(caps, CAP_PERMITTED, 1, &capval, CAP_SET); \
  185. if (err == -1) { \
  186. isc__strerror(errno, strbuf, sizeof(strbuf)); \
  187. ns_main_earlyfatal("cap_set_proc failed: %s", strbuf); \
  188. } \
  189. } \
  190. } while (0)
  191. #define INIT_CAP \
  192. do { \
  193. caps = cap_init(); \
  194. if (caps == NULL) { \
  195. isc__strerror(errno, strbuf, sizeof(strbuf)); \
  196. ns_main_earlyfatal("cap_init failed: %s", strbuf); \
  197. } \
  198. curcaps = cap_get_proc(); \
  199. if (curcaps == NULL) { \
  200. isc__strerror(errno, strbuf, sizeof(strbuf)); \
  201. ns_main_earlyfatal("cap_get_proc failed: %s", strbuf); \
  202. } \
  203. } while (0)
  204. #define FREE_CAP \
  205. { \
  206. cap_free(caps); \
  207. cap_free(curcaps); \
  208. } while (0)
  209. #else
  210. #define SET_CAP(flag) do { caps |= (1 << (flag)); } while (0)
  211. #define INIT_CAP do { caps = 0; } while (0)
  212. #endif /* HAVE_LIBCAP */
  213. static void
  214. linux_initialprivs(void) {
  215. cap_t caps;
  216. #ifdef HAVE_LIBCAP
  217. cap_t curcaps;
  218. cap_value_t capval;
  219. char strbuf[ISC_STRERRORSIZE];
  220. int err;
  221. #endif
  222. /*%
  223. * We don't need most privileges, so we drop them right away.
  224. * Later on linux_minprivs() will be called, which will drop our
  225. * capabilities to the minimum needed to run the server.
  226. */
  227. INIT_CAP;
  228. /*
  229. * We need to be able to bind() to privileged ports, notably port 53!
  230. */
  231. SET_CAP(CAP_NET_BIND_SERVICE);
  232. /*
  233. * We need chroot() initially too.
  234. */
  235. SET_CAP(CAP_SYS_CHROOT);
  236. #if defined(HAVE_SYS_PRCTL_H) || !defined(HAVE_LINUXTHREADS)
  237. /*
  238. * We can setuid() only if either the kernel supports keeping
  239. * capabilities after setuid() (which we don't know until we've
  240. * tried) or we're not using threads. If either of these is
  241. * true, we want the setuid capability.
  242. */
  243. SET_CAP(CAP_SETUID);
  244. #endif
  245. /*
  246. * Since we call initgroups, we need this.
  247. */
  248. SET_CAP(CAP_SETGID);
  249. /*
  250. * Without this, we run into problems reading a configuration file
  251. * owned by a non-root user and non-world-readable on startup.
  252. */
  253. SET_CAP(CAP_DAC_READ_SEARCH);
  254. /*
  255. * XXX We might want to add CAP_SYS_RESOURCE, though it's not
  256. * clear it would work right given the way linuxthreads work.
  257. * XXXDCL But since we need to be able to set the maximum number
  258. * of files, the stack size, data size, and core dump size to
  259. * support named.conf options, this is now being added to test.
  260. */
  261. SET_CAP(CAP_SYS_RESOURCE);
  262. /*
  263. * We need to be able to set the ownership of the containing
  264. * directory of the pid file when we create it.
  265. */
  266. SET_CAP(CAP_CHOWN);
  267. linux_setcaps(caps);
  268. #ifdef HAVE_LIBCAP
  269. FREE_CAP;
  270. #endif
  271. }
  272. static void
  273. linux_minprivs(void) {
  274. cap_t caps;
  275. #ifdef HAVE_LIBCAP
  276. cap_t curcaps;
  277. cap_value_t capval;
  278. char strbuf[ISC_STRERRORSIZE];
  279. int err;
  280. #endif
  281. INIT_CAP;
  282. /*%
  283. * Drop all privileges except the ability to bind() to privileged
  284. * ports.
  285. *
  286. * It's important that we drop CAP_SYS_CHROOT. If we didn't, it
  287. * chroot() could be used to escape from the chrooted area.
  288. */
  289. SET_CAP(CAP_NET_BIND_SERVICE);
  290. /*
  291. * XXX We might want to add CAP_SYS_RESOURCE, though it's not
  292. * clear it would work right given the way linuxthreads work.
  293. * XXXDCL But since we need to be able to set the maximum number
  294. * of files, the stack size, data size, and core dump size to
  295. * support named.conf options, this is now being added to test.
  296. */
  297. SET_CAP(CAP_SYS_RESOURCE);
  298. linux_setcaps(caps);
  299. #ifdef HAVE_LIBCAP
  300. FREE_CAP;
  301. #endif
  302. }
  303. #ifdef HAVE_SYS_PRCTL_H
  304. static void
  305. linux_keepcaps(void) {
  306. char strbuf[ISC_STRERRORSIZE];
  307. /*%
  308. * Ask the kernel to allow us to keep our capabilities after we
  309. * setuid().
  310. */
  311. if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) < 0) {
  312. if (errno != EINVAL) {
  313. isc__strerror(errno, strbuf, sizeof(strbuf));
  314. ns_main_earlyfatal("prctl() failed: %s", strbuf);
  315. }
  316. } else {
  317. non_root_caps = ISC_TRUE;
  318. if (getuid() != 0)
  319. non_root = ISC_TRUE;
  320. }
  321. }
  322. #endif
  323. #endif /* HAVE_LINUX_CAPABILITY_H */
  324. static void
  325. setup_syslog(const char *progname) {
  326. int options;
  327. options = LOG_PID;
  328. #ifdef LOG_NDELAY
  329. options |= LOG_NDELAY;
  330. #endif
  331. openlog(isc_file_basename(progname), options, ISC_FACILITY);
  332. }
  333. void
  334. ns_os_init(const char *progname) {
  335. setup_syslog(progname);
  336. #ifdef HAVE_LINUX_CAPABILITY_H
  337. linux_initialprivs();
  338. #endif
  339. #ifdef HAVE_LINUXTHREADS
  340. mainpid = getpid();
  341. #endif
  342. #ifdef SIGXFSZ
  343. signal(SIGXFSZ, SIG_IGN);
  344. #endif
  345. }
  346. void
  347. ns_os_daemonize(void) {
  348. pid_t pid;
  349. char strbuf[ISC_STRERRORSIZE];
  350. if (pipe(dfd) == -1) {
  351. isc__strerror(errno, strbuf, sizeof(strbuf));
  352. ns_main_earlyfatal("pipe(): %s", strbuf);
  353. }
  354. pid = fork();
  355. if (pid == -1) {
  356. isc__strerror(errno, strbuf, sizeof(strbuf));
  357. ns_main_earlyfatal("fork(): %s", strbuf);
  358. }
  359. if (pid != 0) {
  360. int n;
  361. /*
  362. * Wait for the child to finish loading for the first time.
  363. * This would be so much simpler if fork() worked once we
  364. * were multi-threaded.
  365. */
  366. (void)close(dfd[1]);
  367. do {
  368. char buf;
  369. n = read(dfd[0], &buf, 1);
  370. if (n == 1)
  371. _exit(0);
  372. } while (n == -1 && errno == EINTR);
  373. _exit(1);
  374. }
  375. (void)close(dfd[0]);
  376. /*
  377. * We're the child.
  378. */
  379. #ifdef HAVE_LINUXTHREADS
  380. mainpid = getpid();
  381. #endif
  382. if (setsid() == -1) {
  383. isc__strerror(errno, strbuf, sizeof(strbuf));
  384. ns_main_earlyfatal("setsid(): %s", strbuf);
  385. }
  386. /*
  387. * Try to set stdin, stdout, and stderr to /dev/null, but press
  388. * on even if it fails.
  389. *
  390. * XXXMLG The close() calls here are unneeded on all but NetBSD, but
  391. * are harmless to include everywhere. dup2() is supposed to close
  392. * the FD if it is in use, but unproven-pthreads-0.16 is broken
  393. * and will end up closing the wrong FD. This will be fixed eventually,
  394. * and these calls will be removed.
  395. */
  396. if (devnullfd != -1) {
  397. if (devnullfd != STDIN_FILENO) {
  398. (void)close(STDIN_FILENO);
  399. (void)dup2(devnullfd, STDIN_FILENO);
  400. }
  401. if (devnullfd != STDOUT_FILENO) {
  402. (void)close(STDOUT_FILENO);
  403. (void)dup2(devnullfd, STDOUT_FILENO);
  404. }
  405. if (devnullfd != STDERR_FILENO) {
  406. (void)close(STDERR_FILENO);
  407. (void)dup2(devnullfd, STDERR_FILENO);
  408. }
  409. }
  410. }
  411. void
  412. ns_os_started(void) {
  413. char buf = 0;
  414. /*
  415. * Signal to the parent that we started successfully.
  416. */
  417. if (dfd[0] != -1 && dfd[1] != -1) {
  418. if (write(dfd[1], &buf, 1) != 1)
  419. ns_main_earlyfatal("unable to signal parent that we "
  420. "otherwise started successfully.");
  421. close(dfd[1]);
  422. dfd[0] = dfd[1] = -1;
  423. }
  424. }
  425. void
  426. ns_os_opendevnull(void) {
  427. devnullfd = open("/dev/null", O_RDWR, 0);
  428. }
  429. void
  430. ns_os_closedevnull(void) {
  431. if (devnullfd != STDIN_FILENO &&
  432. devnullfd != STDOUT_FILENO &&
  433. devnullfd != STDERR_FILENO) {
  434. close(devnullfd);
  435. devnullfd = -1;
  436. }
  437. }
  438. static isc_boolean_t
  439. all_digits(const char *s) {
  440. if (*s == '\0')
  441. return (ISC_FALSE);
  442. while (*s != '\0') {
  443. if (!isdigit((*s)&0xff))
  444. return (ISC_FALSE);
  445. s++;
  446. }
  447. return (ISC_TRUE);
  448. }
  449. void
  450. ns_os_chroot(const char *root) {
  451. char strbuf[ISC_STRERRORSIZE];
  452. #ifdef HAVE_LIBSCF
  453. ns_smf_chroot = 0;
  454. #endif
  455. if (root != NULL) {
  456. #ifdef HAVE_CHROOT
  457. if (chroot(root) < 0) {
  458. isc__strerror(errno, strbuf, sizeof(strbuf));
  459. ns_main_earlyfatal("chroot(): %s", strbuf);
  460. }
  461. #else
  462. ns_main_earlyfatal("chroot(): disabled");
  463. #endif
  464. if (chdir("/") < 0) {
  465. isc__strerror(errno, strbuf, sizeof(strbuf));
  466. ns_main_earlyfatal("chdir(/): %s", strbuf);
  467. }
  468. #ifdef HAVE_LIBSCF
  469. /* Set ns_smf_chroot flag on successful chroot. */
  470. ns_smf_chroot = 1;
  471. #endif
  472. }
  473. }
  474. void
  475. ns_os_inituserinfo(const char *username) {
  476. char strbuf[ISC_STRERRORSIZE];
  477. if (username == NULL)
  478. return;
  479. if (all_digits(username))
  480. runas_pw = getpwuid((uid_t)atoi(username));
  481. else
  482. runas_pw = getpwnam(username);
  483. endpwent();
  484. if (runas_pw == NULL)
  485. ns_main_earlyfatal("user '%s' unknown", username);
  486. if (getuid() == 0) {
  487. if (initgroups(runas_pw->pw_name, runas_pw->pw_gid) < 0) {
  488. isc__strerror(errno, strbuf, sizeof(strbuf));
  489. ns_main_earlyfatal("initgroups(): %s", strbuf);
  490. }
  491. }
  492. }
  493. void
  494. ns_os_changeuser(void) {
  495. char strbuf[ISC_STRERRORSIZE];
  496. if (runas_pw == NULL || done_setuid)
  497. return;
  498. done_setuid = ISC_TRUE;
  499. #ifdef HAVE_LINUXTHREADS
  500. #ifdef HAVE_LINUX_CAPABILITY_H
  501. if (!non_root_caps)
  502. ns_main_earlyfatal("-u with Linux threads not supported: "
  503. "requires kernel support for "
  504. "prctl(PR_SET_KEEPCAPS)");
  505. #else
  506. ns_main_earlyfatal("-u with Linux threads not supported: "
  507. "no capabilities support or capabilities "
  508. "disabled at build time");
  509. #endif
  510. #endif
  511. if (setgid(runas_pw->pw_gid) < 0) {
  512. isc__strerror(errno, strbuf, sizeof(strbuf));
  513. ns_main_earlyfatal("setgid(): %s", strbuf);
  514. }
  515. if (setuid(runas_pw->pw_uid) < 0) {
  516. isc__strerror(errno, strbuf, sizeof(strbuf));
  517. ns_main_earlyfatal("setuid(): %s", strbuf);
  518. }
  519. #if defined(HAVE_SYS_PRCTL_H) && defined(PR_SET_DUMPABLE)
  520. /*
  521. * Restore the ability of named to drop core after the setuid()
  522. * call has disabled it.
  523. */
  524. if (prctl(PR_SET_DUMPABLE,1,0,0,0) < 0) {
  525. isc__strerror(errno, strbuf, sizeof(strbuf));
  526. ns_main_earlywarning("prctl(PR_SET_DUMPABLE) failed: %s",
  527. strbuf);
  528. }
  529. #endif
  530. #if defined(HAVE_LINUX_CAPABILITY_H) && !defined(HAVE_LINUXTHREADS)
  531. linux_minprivs();
  532. #endif
  533. }
  534. void
  535. ns_os_adjustnofile() {
  536. #ifdef HAVE_LINUXTHREADS
  537. isc_result_t result;
  538. isc_resourcevalue_t newvalue;
  539. /*
  540. * Linux: max number of open files specified by one thread doesn't seem
  541. * to apply to other threads on Linux.
  542. */
  543. newvalue = ISC_RESOURCE_UNLIMITED;
  544. result = isc_resource_setlimit(isc_resource_openfiles, newvalue);
  545. if (result != ISC_R_SUCCESS)
  546. ns_main_earlywarning("couldn't adjust limit on open files");
  547. #endif
  548. }
  549. void
  550. ns_os_minprivs(void) {
  551. #ifdef HAVE_SYS_PRCTL_H
  552. linux_keepcaps();
  553. #endif
  554. #ifdef HAVE_LINUXTHREADS
  555. ns_os_changeuser(); /* Call setuid() before threads are started */
  556. #endif
  557. #if defined(HAVE_LINUX_CAPABILITY_H) && defined(HAVE_LINUXTHREADS)
  558. linux_minprivs();
  559. #endif
  560. }
  561. static int
  562. safe_open(const char *filename, mode_t mode, isc_boolean_t append) {
  563. int fd;
  564. struct stat sb;
  565. if (stat(filename, &sb) == -1) {
  566. if (errno != ENOENT)
  567. return (-1);
  568. } else if ((sb.st_mode & S_IFREG) == 0) {
  569. errno = EOPNOTSUPP;
  570. return (-1);
  571. }
  572. if (append)
  573. fd = open(filename, O_WRONLY|O_CREAT|O_APPEND, mode);
  574. else {
  575. if (unlink(filename) < 0 && errno != ENOENT)
  576. return (-1);
  577. fd = open(filename, O_WRONLY|O_CREAT|O_EXCL, mode);
  578. }
  579. return (fd);
  580. }
  581. static void
  582. cleanup_pidfile(void) {
  583. int n;
  584. if (pidfile != NULL) {
  585. n = unlink(pidfile);
  586. if (n == -1 && errno != ENOENT)
  587. ns_main_earlywarning("unlink '%s': failed", pidfile);
  588. free(pidfile);
  589. }
  590. pidfile = NULL;
  591. }
  592. static int
  593. mkdirpath(char *filename, void (*report)(const char *, ...)) {
  594. char *slash = strrchr(filename, '/');
  595. char strbuf[ISC_STRERRORSIZE];
  596. unsigned int mode;
  597. if (slash != NULL && slash != filename) {
  598. struct stat sb;
  599. *slash = '\0';
  600. if (stat(filename, &sb) == -1) {
  601. if (errno != ENOENT) {
  602. isc__strerror(errno, strbuf, sizeof(strbuf));
  603. (*report)("couldn't stat '%s': %s", filename,
  604. strbuf);
  605. goto error;
  606. }
  607. if (mkdirpath(filename, report) == -1)
  608. goto error;
  609. /*
  610. * Handle "//", "/./" and "/../" in path.
  611. */
  612. if (!strcmp(slash + 1, "") ||
  613. !strcmp(slash + 1, ".") ||
  614. !strcmp(slash + 1, "..")) {
  615. *slash = '/';
  616. return (0);
  617. }
  618. mode = S_IRUSR | S_IWUSR | S_IXUSR; /* u=rwx */
  619. mode |= S_IRGRP | S_IXGRP; /* g=rx */
  620. mode |= S_IROTH | S_IXOTH; /* o=rx */
  621. if (mkdir(filename, mode) == -1) {
  622. isc__strerror(errno, strbuf, sizeof(strbuf));
  623. (*report)("couldn't mkdir '%s': %s", filename,
  624. strbuf);
  625. goto error;
  626. }
  627. if (runas_pw != NULL &&
  628. chown(filename, runas_pw->pw_uid,
  629. runas_pw->pw_gid) == -1) {
  630. isc__strerror(errno, strbuf, sizeof(strbuf));
  631. (*report)("couldn't chown '%s': %s", filename,
  632. strbuf);
  633. }
  634. }
  635. *slash = '/';
  636. }
  637. return (0);
  638. error:
  639. *slash = '/';
  640. return (-1);
  641. }
  642. static void
  643. setperms(uid_t uid, gid_t gid) {
  644. char strbuf[ISC_STRERRORSIZE];
  645. #if !defined(HAVE_SETEGID) && defined(HAVE_SETRESGID)
  646. gid_t oldgid, tmpg;
  647. #endif
  648. #if !defined(HAVE_SETEUID) && defined(HAVE_SETRESUID)
  649. uid_t olduid, tmpu;
  650. #endif
  651. #if defined(HAVE_SETEGID)
  652. if (getegid() != gid && setegid(gid) == -1) {
  653. isc__strerror(errno, strbuf, sizeof(strbuf));
  654. ns_main_earlywarning("unable to set effective gid to %ld: %s",
  655. (long)gid, strbuf);
  656. }
  657. #elif defined(HAVE_SETRESGID)
  658. if (getresgid(&tmpg, &oldgid, &tmpg) == -1 || oldgid != gid) {
  659. if (setresgid(-1, gid, -1) == -1) {
  660. isc__strerror(errno, strbuf, sizeof(strbuf));
  661. ns_main_earlywarning("unable to set effective "
  662. "gid to %d: %s", gid, strbuf);
  663. }
  664. }
  665. #endif
  666. #if defined(HAVE_SETEUID)
  667. if (geteuid() != uid && seteuid(uid) == -1) {
  668. isc__strerror(errno, strbuf, sizeof(strbuf));
  669. ns_main_earlywarning("unable to set effective uid to %ld: %s",
  670. (long)uid, strbuf);
  671. }
  672. #elif defined(HAVE_SETRESUID)
  673. if (getresuid(&tmpu, &olduid, &tmpu) == -1 || olduid != uid) {
  674. if (setresuid(-1, uid, -1) == -1) {
  675. isc__strerror(errno, strbuf, sizeof(strbuf));
  676. ns_main_earlywarning("unable to set effective "
  677. "uid to %d: %s", uid, strbuf);
  678. }
  679. }
  680. #endif
  681. }
  682. FILE *
  683. ns_os_openfile(const char *filename, mode_t mode, isc_boolean_t switch_user) {
  684. char strbuf[ISC_STRERRORSIZE], *f;
  685. FILE *fp;
  686. int fd;
  687. /*
  688. * Make the containing directory if it doesn't exist.
  689. */
  690. f = strdup(filename);
  691. if (f == NULL) {
  692. isc__strerror(errno, strbuf, sizeof(strbuf));
  693. ns_main_earlywarning("couldn't strdup() '%s': %s",
  694. filename, strbuf);
  695. return (NULL);
  696. }
  697. if (mkdirpath(f, ns_main_earlywarning) == -1) {
  698. free(f);
  699. return (NULL);
  700. }
  701. free(f);
  702. if (switch_user && runas_pw != NULL) {
  703. #ifndef HAVE_LINUXTHREADS
  704. gid_t oldgid = getgid();
  705. #endif
  706. /* Set UID/GID to the one we'll be running with eventually */
  707. setperms(runas_pw->pw_uid, runas_pw->pw_gid);
  708. fd = safe_open(filename, mode, ISC_FALSE);
  709. #ifndef HAVE_LINUXTHREADS
  710. /* Restore UID/GID to root */
  711. setperms(0, oldgid);
  712. #endif /* HAVE_LINUXTHREADS */
  713. if (fd == -1) {
  714. #ifndef HAVE_LINUXTHREADS
  715. fd = safe_open(filename, mode, ISC_FALSE);
  716. if (fd != -1) {
  717. ns_main_earlywarning("Required root "
  718. "permissions to open "
  719. "'%s'.", filename);
  720. } else {
  721. ns_main_earlywarning("Could not open "
  722. "'%s'.", filename);
  723. }
  724. ns_main_earlywarning("Please check file and "
  725. "directory permissions "
  726. "or reconfigure the filename.");
  727. #else /* HAVE_LINUXTHREADS */
  728. ns_main_earlywarning("Could not open "
  729. "'%s'.", filename);
  730. ns_main_earlywarning("Please check file and "
  731. "directory permissions "
  732. "or reconfigure the filename.");
  733. #endif /* HAVE_LINUXTHREADS */
  734. }
  735. } else {
  736. fd = safe_open(filename, mode, ISC_FALSE);
  737. }
  738. if (fd < 0) {
  739. isc__strerror(errno, strbuf, sizeof(strbuf));
  740. ns_main_earlywarning("could not open file '%s': %s",
  741. filename, strbuf);
  742. return (NULL);
  743. }
  744. fp = fdopen(fd, "w");
  745. if (fp == NULL) {
  746. isc__strerror(errno, strbuf, sizeof(strbuf));
  747. ns_main_earlywarning("could not fdopen() file '%s': %s",
  748. filename, strbuf);
  749. }
  750. return (fp);
  751. }
  752. void
  753. ns_os_writepidfile(const char *filename, isc_boolean_t first_time) {
  754. FILE *lockfile;
  755. pid_t pid;
  756. char strbuf[ISC_STRERRORSIZE];
  757. void (*report)(const char *, ...);
  758. /*
  759. * The caller must ensure any required synchronization.
  760. */
  761. report = first_time ? ns_main_earlyfatal : ns_main_earlywarning;
  762. cleanup_pidfile();
  763. if (filename == NULL)
  764. return;
  765. pidfile = strdup(filename);
  766. if (pidfile == NULL) {
  767. isc__strerror(errno, strbuf, sizeof(strbuf));
  768. (*report)("couldn't strdup() '%s': %s", filename, strbuf);
  769. return;
  770. }
  771. lockfile = ns_os_openfile(filename, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH,
  772. first_time);
  773. if (lockfile == NULL) {
  774. cleanup_pidfile();
  775. return;
  776. }
  777. #ifdef HAVE_LINUXTHREADS
  778. pid = mainpid;
  779. #else
  780. pid = getpid();
  781. #endif
  782. if (fprintf(lockfile, "%ld\n", (long)pid) < 0) {
  783. (*report)("fprintf() to pid file '%s' failed", filename);
  784. (void)fclose(lockfile);
  785. cleanup_pidfile();
  786. return;
  787. }
  788. if (fflush(lockfile) == EOF) {
  789. (*report)("fflush() to pid file '%s' failed", filename);
  790. (void)fclose(lockfile);
  791. cleanup_pidfile();
  792. return;
  793. }
  794. (void)fclose(lockfile);
  795. }
  796. void
  797. ns_os_shutdown(void) {
  798. closelog();
  799. cleanup_pidfile();
  800. }
  801. isc_result_t
  802. ns_os_gethostname(char *buf, size_t len) {
  803. int n;
  804. n = gethostname(buf, len);
  805. return ((n == 0) ? ISC_R_SUCCESS : ISC_R_FAILURE);
  806. }
  807. static char *
  808. next_token(char **stringp, const char *delim) {
  809. char *res;
  810. do {
  811. res = strsep(stringp, delim);
  812. if (res == NULL)
  813. break;
  814. } while (*res == '\0');
  815. return (res);
  816. }
  817. void
  818. ns_os_shutdownmsg(char *command, isc_buffer_t *text) {
  819. char *input, *ptr;
  820. unsigned int n;
  821. pid_t pid;
  822. input = command;
  823. /* Skip the command name. */
  824. ptr = next_token(&input, " \t");
  825. if (ptr == NULL)
  826. return;
  827. ptr = next_token(&input, " \t");
  828. if (ptr == NULL)
  829. return;
  830. if (strcmp(ptr, "-p") != 0)
  831. return;
  832. #ifdef HAVE_LINUXTHREADS
  833. pid = mainpid;
  834. #else
  835. pid = getpid();
  836. #endif
  837. n = snprintf((char *)isc_buffer_used(text),
  838. isc_buffer_availablelength(text),
  839. "pid: %ld", (long)pid);
  840. /* Only send a message if it is complete. */
  841. if (n > 0 && n < isc_buffer_availablelength(text))
  842. isc_buffer_add(text, n);
  843. }
  844. void
  845. ns_os_tzset(void) {
  846. #ifdef HAVE_TZSET
  847. tzset();
  848. #endif
  849. }