1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
|
/*
* ntpd.c - main program for the fixed point NTP daemon
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include "ntp_machine.h"
#include "ntpd.h"
#include "ntp_io.h"
#include "ntp_stdlib.h"
#include <ntp_random.h>
#include "ntp_config.h"
#include "ntp_syslog.h"
#include "ntp_assert.h"
#include "isc/error.h"
#include "isc/strerror.h"
#include "isc/formatcheck.h"
#include "iosignal.h"
#ifdef SIM
# include "ntpsim.h"
#endif
#include "ntp_libopts.h"
#include "ntpd-opts.h"
/* there's a short treatise below what the thread stuff is for.
* [Bug 2954] enable the threading warm-up only for Linux.
*/
#if defined(HAVE_PTHREADS) && HAVE_PTHREADS && !defined(NO_THREADS)
# ifdef HAVE_PTHREAD_H
# include <pthread.h>
# endif
# if defined(linux)
# define NEED_PTHREAD_WARMUP
# endif
#endif
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#include <stdio.h>
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#ifdef HAVE_SYS_SIGNAL_H
# include <sys/signal.h>
#else
# include <signal.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif /* HAVE_SYS_IOCTL_H */
#if defined(HAVE_RTPRIO)
# ifdef HAVE_SYS_LOCK_H
# include <sys/lock.h>
# endif
# include <sys/rtprio.h>
#else
# ifdef HAVE_PLOCK
# ifdef HAVE_SYS_LOCK_H
# include <sys/lock.h>
# endif
# endif
#endif
#if defined(HAVE_SCHED_SETSCHEDULER)
# ifdef HAVE_SCHED_H
# include <sched.h>
# else
# ifdef HAVE_SYS_SCHED_H
# include <sys/sched.h>
# endif
# endif
#endif
#if defined(HAVE_SYS_MMAN_H)
# include <sys/mman.h>
#endif
#ifdef HAVE_SYSEXITS_H
# include <sysexits.h>
#endif
#ifdef HAVE_TERMIOS_H
# include <termios.h>
#endif
#ifdef SYS_DOMAINOS
# include <apollo/base.h>
#endif /* SYS_DOMAINOS */
#include "recvbuff.h"
#include "ntp_cmdargs.h"
#if 0 /* HMS: I don't think we need this. 961223 */
#ifdef LOCK_PROCESS
# ifdef SYS_SOLARIS
# include <sys/mman.h>
# else
# include <sys/lock.h>
# endif
#endif
#endif
#ifdef SYS_WINNT
# include "ntservice.h"
#endif
#ifdef _AIX
# include <ulimit.h>
#endif /* _AIX */
#ifdef SCO5_CLOCK
# include <sys/ci/ciioctl.h>
#endif
#ifdef HAVE_DROPROOT
# include <ctype.h>
# include <grp.h>
# include <pwd.h>
#ifdef HAVE_LINUX_CAPABILITIES
# include <sys/capability.h>
# include <sys/prctl.h>
#endif /* HAVE_LINUX_CAPABILITIES */
#if defined(HAVE_PRIV_H) && defined(HAVE_SOLARIS_PRIVS)
# include <priv.h>
#endif /* HAVE_PRIV_H */
#if defined(HAVE_TRUSTEDBSD_MAC)
# include <sys/mac.h>
#endif /* HAVE_TRUSTEDBSD_MAC */
#endif /* HAVE_DROPROOT */
#if defined (LIBSECCOMP) && (KERN_SECCOMP)
/* # include <sys/types.h> */
# include <sys/resource.h>
# include <seccomp.h>
#endif /* LIBSECCOMP and KERN_SECCOMP */
#ifdef __FreeBSD__
#include <sys/procctl.h>
#ifndef PROC_STACKGAP_CTL
/*
* Even if we compile on an older system we can still run on a newer one.
*/
#define PROC_STACKGAP_CTL 17
#define PROC_STACKGAP_DISABLE 0x0002
#endif
#endif
#ifdef HAVE_DNSREGISTRATION
# include <dns_sd.h>
DNSServiceRef mdns;
#endif
/* In case 'sysexits.h' is unavailable, define some exit codes here: */
#ifndef EX_SOFTWARE
# define EX_SOFTWARE 70
#endif
#ifndef EX_OSERR
# define EX_OSERR 71
#endif
#ifndef EX_IOERR
# define EX_IOERR 74
#endif
#ifndef EX_PROTOCOL
#define EX_PROTOCOL 76
#endif
#ifdef HAVE_SETPGRP_0
# define ntp_setpgrp(x, y) setpgrp()
#else
# define ntp_setpgrp(x, y) setpgrp(x, y)
#endif
#ifdef HAVE_SOLARIS_PRIVS
# define LOWPRIVS "basic,sys_time,net_privaddr,proc_setid,!proc_info,!proc_session,!proc_exec"
static priv_set_t *lowprivs = NULL;
static priv_set_t *highprivs = NULL;
#endif /* HAVE_SOLARIS_PRIVS */
/*
* Scheduling priority we run at
*/
#define NTPD_PRIO (-12)
int priority_done = 2; /* 0 - Set priority */
/* 1 - priority is OK where it is */
/* 2 - Don't set priority */
/* 1 and 2 are pretty much the same */
int listen_to_virtual_ips = TRUE;
/*
* No-fork flag. If set, we do not become a background daemon.
*/
int nofork; /* Fork by default */
#ifdef HAVE_DNSREGISTRATION
/*
* mDNS registration flag. If set, we attempt to register with the mDNS system, but only
* after we have synched the first time. If the attempt fails, then try again once per
* minute for up to 5 times. After all, we may be starting before mDNS.
*/
int mdnsreg = FALSE;
int mdnstries = 5;
#endif /* HAVE_DNSREGISTRATION */
#ifdef HAVE_LINUX_CAPABILITIES
int have_caps; /* runtime check whether capabilities work */
#endif /* HAVE_LINUX_CAPABILITIES */
#ifdef HAVE_DROPROOT
int droproot;
int root_dropped;
char *user; /* User to switch to */
char *group; /* group to switch to */
const char *chrootdir; /* directory to chroot to */
uid_t sw_uid;
gid_t sw_gid;
struct group *gr;
struct passwd *pw;
#endif /* HAVE_DROPROOT */
#ifdef HAVE_WORKING_FORK
int daemon_pipe[2] = { -1, -1 };
#endif
/*
* Version declaration
*/
extern const char *Version;
char const *progname;
int was_alarmed;
#ifdef DECL_SYSCALL
/*
* We put this here, since the argument profile is syscall-specific
*/
extern int syscall (int, ...);
#endif /* DECL_SYSCALL */
#if !defined(SIM) && defined(SIGDIE1)
static volatile int signalled = 0;
static volatile int signo = 0;
/* In an ideal world, 'finish_safe()' would declared as noreturn... */
static void finish_safe (int);
static RETSIGTYPE finish (int);
#endif
#if !defined(SIM) && defined(HAVE_WORKING_FORK)
static int wait_child_sync_if (int, unsigned long);
static int wait_child_exit_if (pid_t, int);
#endif
#if !defined(SIM) && !defined(SYS_WINNT)
# ifdef DEBUG
static RETSIGTYPE moredebug (int);
static RETSIGTYPE lessdebug (int);
# else /* !DEBUG follows */
static RETSIGTYPE no_debug (int);
# endif /* !DEBUG */
#endif /* !SIM && !SYS_WINNT */
#ifndef WORK_FORK
int saved_argc;
char ** saved_argv;
#endif
#ifndef SIM
int ntpdmain (int, char **);
static void set_process_priority (void);
static void assertion_failed (const char *, int,
isc_assertiontype_t,
const char *)
__attribute__ ((__noreturn__));
static void library_fatal_error (const char *, int,
const char *, va_list)
ISC_FORMAT_PRINTF(3, 0);
static void library_unexpected_error(const char *, int,
const char *, va_list)
ISC_FORMAT_PRINTF(3, 0);
#endif /* !SIM */
/* Bug2332 unearthed a problem in the interaction of reduced user
* privileges, the limits on memory usage and some versions of the
* pthread library on Linux systems. The 'pthread_cancel()' function and
* likely some others need to track the stack of the thread involved,
* and uses a function that comes from GCC (--> libgcc_s.so) to do
* this. Unfortunately the developers of glibc decided to load the
* library on demand, which speeds up program start but can cause
* trouble here: Due to all the things NTPD does to limit its resource
* usage, this deferred load of libgcc_s does not always work once the
* restrictions are in effect.
*
* One way out of this was attempting a forced link against libgcc_s
* when possible because it makes the library available immediately
* without deferred load. (The symbol resolution would still be dynamic
* and on demand, but the code would already be in the process image.)
*
* This is a tricky thing to do, since it's not necessary everywhere,
* not possible everywhere, has shown to break the build of other
* programs in the NTP suite and is now generally frowned upon.
*
* So we take a different approach here: We creat a worker thread that does
* actually nothing except waiting for cancellation and cancel it. If
* this is done before all the limitations are put in place, the
* machinery is pre-heated and all the runtime stuff should be in place
* and useable when needed.
*
* This uses only the standard pthread API and should work with all
* implementations of pthreads. It is not necessary everywhere, but it's
* cheap enough to go on nearly unnoticed.
*
* Addendum: Bug 2954 showed that the assumption that this should work
* with all OS is wrong -- at least FreeBSD bombs heavily.
*/
#ifdef NEED_PTHREAD_WARMUP
/* simple thread function: sleep until cancelled, just to exercise
* thread cancellation.
*/
static void*
my_pthread_warmup_worker(
void *thread_args)
{
(void)thread_args;
for (;;)
sleep(10);
return NULL;
}
/* pre-heat threading: create a thread and cancel it, just to exercise
* thread cancellation.
*/
static void
my_pthread_warmup(void)
{
pthread_t thread;
pthread_attr_t thr_attr;
int rc;
pthread_attr_init(&thr_attr);
#if defined(HAVE_PTHREAD_ATTR_GETSTACKSIZE) && \
defined(HAVE_PTHREAD_ATTR_SETSTACKSIZE) && \
defined(PTHREAD_STACK_MIN)
{
size_t ssmin = 32*1024; /* 32kB should be minimum */
if (ssmin < PTHREAD_STACK_MIN)
ssmin = PTHREAD_STACK_MIN;
rc = pthread_attr_setstacksize(&thr_attr, ssmin);
if (0 != rc)
msyslog(LOG_ERR,
"my_pthread_warmup: pthread_attr_setstacksize() -> %s",
strerror(rc));
}
#endif
rc = pthread_create(
&thread, &thr_attr, my_pthread_warmup_worker, NULL);
pthread_attr_destroy(&thr_attr);
if (0 != rc) {
msyslog(LOG_ERR,
"my_pthread_warmup: pthread_create() -> %s",
strerror(rc));
} else {
pthread_cancel(thread);
pthread_join(thread, NULL);
}
}
#endif /*defined(NEED_PTHREAD_WARMUP)*/
#ifdef NEED_EARLY_FORK
static void
dummy_callback(void) { return; }
static void
fork_nonchroot_worker(void) {
getaddrinfo_sometime("localhost", "ntp", NULL, INITIAL_DNS_RETRY,
(gai_sometime_callback)&dummy_callback, NULL);
}
#endif /* NEED_EARLY_FORK */
void
parse_cmdline_opts(
int * pargc,
char ***pargv
)
{
static int parsed;
static int optct;
if (!parsed)
optct = ntpOptionProcess(&ntpdOptions, *pargc, *pargv);
parsed = 1;
*pargc -= optct;
*pargv += optct;
}
#ifdef SIM
int
main(
int argc,
char *argv[]
)
{
progname = argv[0];
parse_cmdline_opts(&argc, &argv);
#ifdef DEBUG
debug = OPT_VALUE_SET_DEBUG_LEVEL;
DPRINTF(1, ("%s\n", Version));
#endif
return ntpsim(argc, argv);
}
#elif defined(NO_MAIN_ALLOWED)
CALL(ntpd,"ntpd",ntpdmain);
#elif !defined(SYS_WINNT)
int
main(
int argc,
char *argv[]
)
{
# ifdef __FreeBSD__
{
/*
* We Must disable ASLR stack gap on FreeBSD to avoid a
* segfault. See PR/241421 and PR/241960.
*/
int aslr_var = PROC_STACKGAP_DISABLE;
pid_t my_pid = getpid();
procctl(P_PID, my_pid, PROC_STACKGAP_CTL, &aslr_var);
}
# endif
return ntpdmain(argc, argv);
}
#endif /* !SYS_WINNT */
#ifdef _AIX
/*
* OK. AIX is different than solaris in how it implements plock().
* If you do NOT adjust the stack limit, you will get the MAXIMUM
* stack size allocated and PINNED with you program. To check the
* value, use ulimit -a.
*
* To fix this, we create an automatic variable and set our stack limit
* to that PLUS 32KB of extra space (we need some headroom).
*
* This subroutine gets the stack address.
*
* Grover Davidson and Matt Ladendorf
*
*/
static char *
get_aix_stack(void)
{
char ch;
return (&ch);
}
/*
* Signal handler for SIGDANGER.
*/
static void
catch_danger(int signo)
{
msyslog(LOG_INFO, "ntpd: setpgid(): %m");
/* Make the system believe we'll free something, but don't do it! */
return;
}
#endif /* _AIX */
/*
* Set the process priority
*/
#ifndef SIM
static void
set_process_priority(void)
{
# ifdef DEBUG
if (debug > 1)
msyslog(LOG_DEBUG, "set_process_priority: %s: priority_done is <%d>",
((priority_done)
? "Leave priority alone"
: "Attempt to set priority"
),
priority_done);
# endif /* DEBUG */
# if defined(HAVE_SCHED_SETSCHEDULER)
if (!priority_done) {
extern int config_priority_override, config_priority;
int pmax, pmin;
struct sched_param sched;
pmax = sched_get_priority_max(SCHED_FIFO);
sched.sched_priority = pmax;
if ( config_priority_override ) {
pmin = sched_get_priority_min(SCHED_FIFO);
if ( config_priority > pmax )
sched.sched_priority = pmax;
else if ( config_priority < pmin )
sched.sched_priority = pmin;
else
sched.sched_priority = config_priority;
}
if ( sched_setscheduler(0, SCHED_FIFO, &sched) == -1 )
msyslog(LOG_ERR, "sched_setscheduler(): %m");
else
++priority_done;
}
# endif /* HAVE_SCHED_SETSCHEDULER */
# ifdef HAVE_RTPRIO
# ifdef RTP_SET
if (!priority_done) {
struct rtprio srtp;
srtp.type = RTP_PRIO_REALTIME; /* was: RTP_PRIO_NORMAL */
srtp.prio = 0; /* 0 (hi) -> RTP_PRIO_MAX (31,lo) */
if (rtprio(RTP_SET, getpid(), &srtp) < 0)
msyslog(LOG_ERR, "rtprio() error: %m");
else
++priority_done;
}
# else /* !RTP_SET follows */
if (!priority_done) {
if (rtprio(0, 120) < 0)
msyslog(LOG_ERR, "rtprio() error: %m");
else
++priority_done;
}
# endif /* !RTP_SET */
# endif /* HAVE_RTPRIO */
# if defined(NTPD_PRIO) && NTPD_PRIO != 0
# ifdef HAVE_ATT_NICE
if (!priority_done) {
errno = 0;
if (-1 == nice (NTPD_PRIO) && errno != 0)
msyslog(LOG_ERR, "nice() error: %m");
else
++priority_done;
}
# endif /* HAVE_ATT_NICE */
# ifdef HAVE_BSD_NICE
if (!priority_done) {
if (-1 == setpriority(PRIO_PROCESS, 0, NTPD_PRIO))
msyslog(LOG_ERR, "setpriority() error: %m");
else
++priority_done;
}
# endif /* HAVE_BSD_NICE */
# endif /* NTPD_PRIO && NTPD_PRIO != 0 */
if (!priority_done)
msyslog(LOG_ERR, "set_process_priority: No way found to improve our priority");
}
#endif /* !SIM */
#if !defined(SIM) && !defined(SYS_WINNT)
/*
* Detach from terminal (much like daemon())
* Nothe that this function calls exit()
*/
# ifdef HAVE_WORKING_FORK
static void
detach_from_terminal(
int pipe[2],
long wait_sync,
const char *logfilename
)
{
pid_t cpid;
int exit_code;
# if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
int fid;
# endif
# ifdef _AIX
struct sigaction sa;
# endif
cpid = fork();
if (0 != cpid) {
/* parent */
if (-1 == cpid) {
msyslog(LOG_ERR, "fork: %m");
exit_code = EX_OSERR;
} else {
close(pipe[1]);
pipe[1] = -1;
exit_code = wait_child_sync_if(
pipe[0], wait_sync);
DPRINTF(1, ("sync_if: rc=%d\n", exit_code));
if (exit_code <= 0) {
/* probe daemon exit code -- wait for
* child process if we have an unexpected
* EOF on the monitor pipe.
*/
exit_code = wait_child_exit_if(
cpid, (exit_code < 0));
DPRINTF(1, ("exit_if: rc=%d\n", exit_code));
}
}
exit(exit_code);
}
/*
* child/daemon
* close all open files excepting waitsync_fd_to_close.
* msyslog() unreliable until after init_logging().
*/
closelog();
if (syslog_file != NULL) {
fclose(syslog_file);
syslog_file = NULL;
syslogit = TRUE;
}
close_all_except(pipe[1]);
pipe[0] = -1;
INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
&& 2 == dup2(0, 2));
init_logging(progname, 0, TRUE);
/* we lost our logfile (if any) daemonizing */
setup_logfile(logfilename);
# ifdef SYS_DOMAINOS
{
uid_$t puid;
status_$t st;
proc2_$who_am_i(&puid);
proc2_$make_server(&puid, &st);
}
# endif /* SYS_DOMAINOS */
# ifdef HAVE_SETSID
if (setsid() == (pid_t)-1)
msyslog(LOG_ERR, "setsid(): %m");
# elif defined(HAVE_SETPGID)
if (setpgid(0, 0) == -1)
msyslog(LOG_ERR, "setpgid(): %m");
# else /* !HAVE_SETSID && !HAVE_SETPGID follows */
# ifdef TIOCNOTTY
fid = open("/dev/tty", 2);
if (fid >= 0) {
ioctl(fid, (u_long)TIOCNOTTY, NULL);
close(fid);
}
# endif /* TIOCNOTTY */
ntp_setpgrp(0, getpid());
# endif /* !HAVE_SETSID && !HAVE_SETPGID */
# ifdef _AIX
/* Don't get killed by low-on-memory signal. */
sa.sa_handler = catch_danger;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART;
sigaction(SIGDANGER, &sa, NULL);
# endif /* _AIX */
return;
}
# endif /* HAVE_WORKING_FORK */
#ifdef HAVE_DROPROOT
/*
* Map user name/number to user ID
*/
static int
map_user(
)
{
char *endp;
if (isdigit((unsigned char)*user)) {
sw_uid = (uid_t)strtoul(user, &endp, 0);
if (*endp != '\0')
goto getuser;
if ((pw = getpwuid(sw_uid)) != NULL) {
free(user);
user = estrdup(pw->pw_name);
sw_gid = pw->pw_gid;
} else {
errno = 0;
msyslog(LOG_ERR, "Cannot find user ID %s", user);
return 0;
}
} else {
getuser:
errno = 0;
if ((pw = getpwnam(user)) != NULL) {
sw_uid = pw->pw_uid;
sw_gid = pw->pw_gid;
} else {
if (errno)
msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
else
msyslog(LOG_ERR, "Cannot find user `%s'", user);
return 0;
}
}
return 1;
}
/*
* Map group name/number to group ID
*/
static int
map_group(void)
{
char *endp;
if (isdigit((unsigned char)*group)) {
sw_gid = (gid_t)strtoul(group, &endp, 0);
if (*endp != '\0')
goto getgroup;
} else {
getgroup:
if ((gr = getgrnam(group)) != NULL) {
sw_gid = gr->gr_gid;
} else {
errno = 0;
msyslog(LOG_ERR, "Cannot find group `%s'", group);
return 0;
}
}
return 1;
}
static int
set_group_ids(void)
{
if (user && initgroups(user, sw_gid)) {
msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
return 0;
}
if (group && setgid(sw_gid)) {
msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
return 0;
}
if (group && setegid(sw_gid)) {
msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
return 0;
}
if (group) {
if (0 != setgroups(1, &sw_gid)) {
msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
return 0;
}
}
else if (pw)
if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
return 0;
}
return 1;
}
static int
set_user_ids(void)
{
if (user && setuid(sw_uid)) {
msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
return 0;
}
if (user && seteuid(sw_uid)) {
msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
return 0;
}
return 1;
}
/*
* Change (effective) user and group IDs, also initialize the supplementary group access list
*/
int set_user_group_ids(void);
int
set_user_group_ids(void)
{
/* If the the user was already mapped, no need to map it again */
if ((NULL != user) && (0 == sw_uid)) {
if (0 == map_user())
exit (-1);
}
/* same applies for the group */
if ((NULL != group) && (0 == sw_gid)) {
if (0 == map_group())
exit (-1);
}
if (getegid() != sw_gid && 0 == set_group_ids())
return 0;
if (geteuid() != sw_uid && 0 == set_user_ids())
return 0;
return 1;
}
#endif /* HAVE_DROPROOT */
#endif /* !SIM */
/*
* Main program. Initialize us, disconnect us from the tty if necessary,
* and loop waiting for I/O and/or timer expiries.
*/
#ifndef SIM
int
ntpdmain(
int argc,
char *argv[]
)
{
l_fp now;
struct recvbuf *rbuf;
const char * logfilename;
# ifdef HAVE_UMASK
mode_t uv;
# endif
# if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
uid_t uid;
# endif
# if defined(HAVE_WORKING_FORK)
long wait_sync = 0;
# endif /* HAVE_WORKING_FORK*/
# ifdef SCO5_CLOCK
int fd;
int zero;
# endif
# ifdef NEED_PTHREAD_WARMUP
my_pthread_warmup();
# endif
# ifdef HAVE_UMASK
uv = umask(0);
if (uv)
umask(uv);
else
umask(022);
# endif
saved_argc = argc;
saved_argv = argv;
progname = argv[0];
initializing = TRUE; /* mark that we are initializing */
parse_cmdline_opts(&argc, &argv);
# ifdef DEBUG
debug = OPT_VALUE_SET_DEBUG_LEVEL;
# ifdef HAVE_SETLINEBUF
setlinebuf(stdout);
# endif
# endif
if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
# ifdef DEBUG
|| debug
# endif
|| HAVE_OPT(SAVECONFIGQUIT))
nofork = TRUE;
init_logging(progname, NLOG_SYNCMASK, TRUE);
/* honor -l/--logfile option to log to a file */
if (HAVE_OPT(LOGFILE)) {
logfilename = OPT_ARG(LOGFILE);
syslogit = FALSE;
change_logfile(logfilename, FALSE);
} else {
logfilename = NULL;
if (nofork)
msyslog_term = TRUE;
if (HAVE_OPT(SAVECONFIGQUIT))
syslogit = FALSE;
}
msyslog(LOG_NOTICE, "%s: Starting", Version);
{
int i;
char buf[1024]; /* Secret knowledge of msyslog buf length */
char *cp = buf;
/* Note that every arg has an initial space character */
snprintf(cp, sizeof(buf), "Command line:");
cp += strlen(cp);
for (i = 0; i < saved_argc ; ++i) {
snprintf(cp, sizeof(buf) - (cp - buf),
" %s", saved_argv[i]);
cp += strlen(cp);
}
msyslog(LOG_NOTICE, "%s", buf);
}
msyslog(LOG_NOTICE, "----------------------------------------------------");
msyslog(LOG_NOTICE, "ntp-4 is maintained by Network Time Foundation,");
msyslog(LOG_NOTICE, "Inc. (NTF), a non-profit 501(c)(3) public-benefit");
msyslog(LOG_NOTICE, "corporation. Support and training for ntp-4 are");
msyslog(LOG_NOTICE, "available at https://www.nwtime.org/support");
msyslog(LOG_NOTICE, "----------------------------------------------------");
/*
* Install trap handlers to log errors and assertion failures.
* Default handlers print to stderr which doesn't work if detached.
*/
isc_assertion_setcallback(assertion_failed);
isc_error_setfatal(library_fatal_error);
isc_error_setunexpected(library_unexpected_error);
/* MPE lacks the concept of root */
# if defined(HAVE_GETUID) && !defined(MPE)
uid = getuid();
if (uid && !HAVE_OPT( SAVECONFIGQUIT )
# if defined(HAVE_TRUSTEDBSD_MAC)
/* We can run as non-root if the mac_ntpd policy is enabled. */
&& mac_is_present("ntpd") != 1
# endif
) {
msyslog_term = TRUE;
msyslog(LOG_ERR,
"must be run as root, not uid %ld", (long)uid);
exit(1);
}
# endif
/*
* Enable the Multi-Media Timer for Windows?
*/
# ifdef SYS_WINNT
if (HAVE_OPT( MODIFYMMTIMER ))
set_mm_timer(MM_TIMER_HIRES);
# endif
#ifdef HAVE_DNSREGISTRATION
/*
* Enable mDNS registrations?
*/
if (HAVE_OPT( MDNS )) {
mdnsreg = TRUE;
}
#endif /* HAVE_DNSREGISTRATION */
if (HAVE_OPT( NOVIRTUALIPS ))
listen_to_virtual_ips = 0;
/*
* --interface, listen on specified interfaces
*/
if (HAVE_OPT( INTERFACE )) {
int ifacect = STACKCT_OPT( INTERFACE );
const char** ifaces = STACKLST_OPT( INTERFACE );
sockaddr_u addr;
while (ifacect-- > 0) {
add_nic_rule(
is_ip_address(*ifaces, AF_UNSPEC, &addr)
? MATCH_IFADDR
: MATCH_IFNAME,
*ifaces, -1, ACTION_LISTEN);
ifaces++;
}
}
if (HAVE_OPT( NICE ))
priority_done = 0;
# ifdef HAVE_SCHED_SETSCHEDULER
if (HAVE_OPT( PRIORITY )) {
config_priority = OPT_VALUE_PRIORITY;
config_priority_override = 1;
priority_done = 0;
}
# endif
# ifdef HAVE_WORKING_FORK
/* make sure the FDs are initialised
*
* note: if WAIT_SYNC is requested, we *have* to fork. This will
* overide any '-n' (nofork) or '-d' (debug) option presented on
* the command line!
*/
if (HAVE_OPT(WAIT_SYNC)) {
wait_sync = OPT_VALUE_WAIT_SYNC;
if (wait_sync <= 0)
wait_sync = 0;
else
nofork = FALSE;
}
if ( !nofork && pipe(daemon_pipe)) {
msyslog(LOG_ERR,
"Pipe creation failed for --wait-sync/daemon: %m");
exit(EX_OSERR);
}
# endif /* HAVE_WORKING_FORK */
init_lib();
# ifdef SYS_WINNT
/*
* Make sure the service is initialized before we do anything else
*/
ntservice_init();
/*
* Start interpolation thread, must occur before first
* get_systime()
*/
init_winnt_time();
# endif
/*
* Initialize random generator and public key pair
*/
get_systime(&now);
ntp_srandom((int)(now.l_i * now.l_uf));
/*
* Detach us from the terminal. May need an #ifndef GIZMO.
*/
# ifdef HAVE_WORKING_FORK
if (!nofork) {
detach_from_terminal(daemon_pipe, wait_sync, logfilename);
}
# endif /* HAVE_WORKING_FORK */
# ifdef SCO5_CLOCK
/*
* SCO OpenServer's system clock offers much more precise timekeeping
* on the base CPU than the other CPUs (for multiprocessor systems),
* so we must lock to the base CPU.
*/
fd = open("/dev/at1", O_RDONLY);
if (fd >= 0) {
zero = 0;
if (ioctl(fd, ACPU_LOCK, &zero) < 0)
msyslog(LOG_ERR, "cannot lock to base CPU: %m");
close(fd);
}
# endif
/* Setup stack size in preparation for locking pages in memory. */
# if defined(HAVE_MLOCKALL)
# ifdef HAVE_SETRLIMIT
ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
# ifdef RLIMIT_MEMLOCK
/*
* The default RLIMIT_MEMLOCK is very low on Linux systems.
* Unless we increase this limit malloc calls are likely to
* fail if we drop root privilege. To be useful the value
* has to be larger than the largest ntpd resident set size.
*/
ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
# endif /* RLIMIT_MEMLOCK */
# endif /* HAVE_SETRLIMIT */
# else /* !HAVE_MLOCKALL follows */
# ifdef HAVE_PLOCK
# ifdef PROCLOCK
# ifdef _AIX
/*
* set the stack limit for AIX for plock().
* see get_aix_stack() for more info.
*/
if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
msyslog(LOG_ERR,
"Cannot adjust stack limit for plock: %m");
# endif /* _AIX */
# endif /* PROCLOCK */
# endif /* HAVE_PLOCK */
# endif /* !HAVE_MLOCKALL */
/*
* Set up signals we pay attention to locally.
*/
# ifdef SIGDIE1
signal_no_reset(SIGDIE1, finish);
signal_no_reset(SIGDIE2, finish);
signal_no_reset(SIGDIE3, finish);
signal_no_reset(SIGDIE4, finish);
# endif
# ifdef SIGBUS
signal_no_reset(SIGBUS, finish);
# endif
# if !defined(SYS_WINNT) && !defined(VMS)
# ifdef DEBUG
(void) signal_no_reset(MOREDEBUGSIG, moredebug);
(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
# else
(void) signal_no_reset(MOREDEBUGSIG, no_debug);
(void) signal_no_reset(LESSDEBUGSIG, no_debug);
# endif /* DEBUG */
# endif /* !SYS_WINNT && !VMS */
/*
* Set up signals we should never pay attention to.
*/
# ifdef SIGPIPE
signal_no_reset(SIGPIPE, SIG_IGN);
# endif
/*
* Call the init_ routines to initialize the data structures.
*
* Exactly what command-line options are we expecting here?
*/
INIT_SSL();
init_auth();
init_util();
init_restrict();
init_mon();
init_timer();
init_request();
init_control();
init_peer();
# ifdef REFCLOCK
init_refclock();
# endif
set_process_priority();
init_proto(); /* Call at high priority */
init_io();
init_loopfilter();
mon_start(MON_ON); /* monitor on by default now */
/* turn off in config if unwanted */
/*
* Get the configuration. This is done in a separate module
* since this will definitely be different for the gizmo board.
*/
getconfig(argc, argv);
if (-1 == cur_memlock) {
# if defined(HAVE_MLOCKALL)
/*
* lock the process into memory
*/
if ( !HAVE_OPT(SAVECONFIGQUIT)
# ifdef RLIMIT_MEMLOCK
&& -1 != DFLT_RLIMIT_MEMLOCK
# endif
&& 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
msyslog(LOG_ERR, "mlockall(): %m");
# else /* !HAVE_MLOCKALL follows */
# ifdef HAVE_PLOCK
# ifdef PROCLOCK
/*
* lock the process into memory
*/
if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
msyslog(LOG_ERR, "plock(PROCLOCK): %m");
# else /* !PROCLOCK follows */
# ifdef TXTLOCK
/*
* Lock text into ram
*/
if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
# else /* !TXTLOCK follows */
msyslog(LOG_ERR, "plock() - don't know what to lock!");
# endif /* !TXTLOCK */
# endif /* !PROCLOCK */
# endif /* HAVE_PLOCK */
# endif /* !HAVE_MLOCKALL */
}
loop_config(LOOP_DRIFTINIT, 0);
report_event(EVNT_SYSRESTART, NULL, NULL);
initializing = FALSE;
# ifdef HAVE_LINUX_CAPABILITIES
{
/* Check that setting capabilities actually works; we might be
* run on a kernel with disabled capabilities. We must not
* drop privileges in this case.
*/
cap_t caps;
caps = cap_from_text("cap_sys_time,cap_setuid,cap_setgid,cap_sys_chroot,cap_net_bind_service=pe");
if ( ! caps) {
msyslog( LOG_ERR, "cap_from_text() failed: %m" );
exit(-1);
}
have_caps = (cap_set_proc(caps) == 0);
cap_free(caps); /* caps not NULL here! */
}
# endif /* HAVE_LINUX_CAPABILITIES */
# ifdef HAVE_DROPROOT
# ifdef HAVE_LINUX_CAPABILITIES
if (droproot && have_caps) {
# else
if (droproot) {
# endif /*HAVE_LINUX_CAPABILITIES*/
# ifdef NEED_EARLY_FORK
fork_nonchroot_worker();
# endif
/* Drop super-user privileges and chroot now if the OS supports this */
# ifdef HAVE_LINUX_CAPABILITIES
/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
exit(-1);
}
# elif HAVE_SOLARIS_PRIVS
/* Nothing to do here */
# else
/* we need a user to switch to */
if (user == NULL) {
msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
exit(-1);
}
# endif /* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */
if (user != NULL) {
if (0 == map_user())
exit (-1);
}
if (group != NULL) {
if (0 == map_group())
exit (-1);
}
if (chrootdir ) {
/* make sure cwd is inside the jail: */
if (chdir(chrootdir)) {
msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
exit (-1);
}
if (chroot(chrootdir)) {
msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
exit (-1);
}
if (chdir("/")) {
msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
exit (-1);
}
}
# ifdef HAVE_SOLARIS_PRIVS
if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
exit(-1);
}
if ((highprivs = priv_allocset()) == NULL) {
msyslog(LOG_ERR, "priv_allocset() failed:%m");
exit(-1);
}
(void) getppriv(PRIV_PERMITTED, highprivs);
(void) priv_intersect(highprivs, lowprivs);
if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
msyslog(LOG_ERR, "setppriv() failed:%m");
exit(-1);
}
# endif /* HAVE_SOLARIS_PRIVS */
if (0 == set_user_group_ids())
exit(-1);
# if defined(HAVE_TRUSTEDBSD_MAC)
/*
* To manipulate system time and (re-)bind to NTP_PORT as needed
* following interface changes, we must either run as uid 0 or
* the mac_ntpd policy module must be enabled.
*/
if (sw_uid != 0 && mac_is_present("ntpd") != 1) {
msyslog(LOG_ERR, "Need MAC 'ntpd' policy enabled to drop root privileges");
exit (-1);
}
# elif !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
/*
* for now assume that the privilege to bind to privileged ports
* is associated with running with uid 0 - should be refined on
* ports that allow binding to NTP_PORT with uid != 0
*/
disable_dynamic_updates |= (sw_uid != 0); /* also notifies routing message listener */
# endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */
if (disable_dynamic_updates && interface_interval) {
interface_interval = 0;
msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
}
# ifdef HAVE_LINUX_CAPABILITIES
{
/*
* We may be running under non-root uid now, but we still hold full root privileges!
* We drop all of them, except for the crucial one or two: cap_sys_time and
* cap_net_bind_service if doing dynamic interface tracking.
*/
cap_t caps;
char *captext;
captext = (0 != interface_interval)
? "cap_sys_time,cap_net_bind_service=pe"
: "cap_sys_time=pe";
caps = cap_from_text(captext);
if (!caps) {
msyslog(LOG_ERR,
"cap_from_text(%s) failed: %m",
captext);
exit(-1);
}
if (-1 == cap_set_proc(caps)) {
msyslog(LOG_ERR,
"cap_set_proc() failed to drop root privs: %m");
exit(-1);
}
cap_free(caps);
}
# endif /* HAVE_LINUX_CAPABILITIES */
# ifdef HAVE_SOLARIS_PRIVS
if (priv_delset(lowprivs, "proc_setid") == -1) {
msyslog(LOG_ERR, "priv_delset() failed:%m");
exit(-1);
}
if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
msyslog(LOG_ERR, "setppriv() failed:%m");
exit(-1);
}
priv_freeset(lowprivs);
priv_freeset(highprivs);
# endif /* HAVE_SOLARIS_PRIVS */
root_dropped = TRUE;
fork_deferred_worker();
} /* if (droproot) */
# endif /* HAVE_DROPROOT */
/* libssecomp sandboxing */
#if defined (LIBSECCOMP) && (KERN_SECCOMP)
scmp_filter_ctx ctx;
if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
else {
msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
}
#ifdef __x86_64__
int scmp_sc[] = {
SCMP_SYS(adjtimex),
SCMP_SYS(bind),
SCMP_SYS(brk),
SCMP_SYS(chdir),
SCMP_SYS(clock_gettime),
SCMP_SYS(clock_settime),
SCMP_SYS(close),
SCMP_SYS(connect),
SCMP_SYS(exit_group),
SCMP_SYS(fstat),
SCMP_SYS(fsync),
SCMP_SYS(futex),
SCMP_SYS(getitimer),
SCMP_SYS(getsockname),
SCMP_SYS(ioctl),
SCMP_SYS(lseek),
SCMP_SYS(madvise),
SCMP_SYS(mmap),
SCMP_SYS(munmap),
SCMP_SYS(open),
SCMP_SYS(poll),
SCMP_SYS(read),
SCMP_SYS(recvmsg),
SCMP_SYS(rename),
SCMP_SYS(rt_sigaction),
SCMP_SYS(rt_sigprocmask),
SCMP_SYS(rt_sigreturn),
SCMP_SYS(select),
SCMP_SYS(sendto),
SCMP_SYS(setitimer),
SCMP_SYS(setsid),
SCMP_SYS(socket),
SCMP_SYS(stat),
SCMP_SYS(time),
SCMP_SYS(write),
};
#endif
#ifdef __i386__
int scmp_sc[] = {
SCMP_SYS(_newselect),
SCMP_SYS(adjtimex),
SCMP_SYS(brk),
SCMP_SYS(chdir),
SCMP_SYS(clock_gettime),
SCMP_SYS(clock_settime),
SCMP_SYS(close),
SCMP_SYS(exit_group),
SCMP_SYS(fsync),
SCMP_SYS(futex),
SCMP_SYS(getitimer),
SCMP_SYS(madvise),
SCMP_SYS(mmap),
SCMP_SYS(mmap2),
SCMP_SYS(munmap),
SCMP_SYS(open),
SCMP_SYS(poll),
SCMP_SYS(read),
SCMP_SYS(rename),
SCMP_SYS(rt_sigaction),
SCMP_SYS(rt_sigprocmask),
SCMP_SYS(select),
SCMP_SYS(setitimer),
SCMP_SYS(setsid),
SCMP_SYS(sigprocmask),
SCMP_SYS(sigreturn),
SCMP_SYS(socketcall),
SCMP_SYS(stat64),
SCMP_SYS(time),
SCMP_SYS(write),
};
#endif
{
int i;
for (i = 0; i < COUNTOF(scmp_sc); i++) {
if (seccomp_rule_add(ctx,
SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
msyslog(LOG_ERR,
"%s: seccomp_rule_add() failed: %m",
__func__);
}
}
}
if (seccomp_load(ctx) < 0)
msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
__func__);
else {
msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
}
#endif /* LIBSECCOMP and KERN_SECCOMP */
#if defined(SYS_WINNT)
ntservice_isup();
#elif defined(HAVE_WORKING_FORK)
if (daemon_pipe[1] != -1) {
write(daemon_pipe[1], "R\n", 2);
}
#endif /* HAVE_WORKING_FORK */
# ifndef HAVE_IO_COMPLETION_PORT
BLOCK_IO_AND_ALARM();
was_alarmed = FALSE;
# endif
for (;;) {
#if !defined(SIM) && defined(SIGDIE1)
if (signalled)
finish_safe(signo);
#endif
# ifdef HAVE_IO_COMPLETION_PORT
GetReceivedBuffers();
# else /* normal I/O */
if (alarm_flag) { /* alarmed? */
was_alarmed = TRUE;
alarm_flag = FALSE;
}
/* collect async name/addr results */
if (!was_alarmed)
harvest_blocking_responses();
if (!was_alarmed && !has_full_recv_buffer()) {
/*
* Nothing to do. Wait for something.
*/
io_handler();
}
if (alarm_flag) { /* alarmed? */
was_alarmed = TRUE;
alarm_flag = FALSE;
}
if (was_alarmed) {
UNBLOCK_IO_AND_ALARM();
/*
* Out here, signals are unblocked. Call timer routine
* to process expiry.
*/
timer();
was_alarmed = FALSE;
BLOCK_IO_AND_ALARM();
}
# endif /* !HAVE_IO_COMPLETION_PORT */
# ifdef DEBUG_TIMING
{
l_fp pts;
l_fp tsa, tsb;
int bufcount = 0;
get_systime(&pts);
tsa = pts;
# endif
rbuf = get_full_recv_buffer();
while (rbuf != NULL) {
if (alarm_flag) {
was_alarmed = TRUE;
alarm_flag = FALSE;
}
UNBLOCK_IO_AND_ALARM();
if (was_alarmed) {
/* avoid timer starvation during lengthy I/O handling */
timer();
was_alarmed = FALSE;
}
/*
* Call the data procedure to handle each received
* packet.
*/
if (rbuf->receiver != NULL) {
# ifdef DEBUG_TIMING
l_fp dts = pts;
L_SUB(&dts, &rbuf->recv_time);
DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
collect_timing(rbuf, "buffer processing delay", 1, &dts);
bufcount++;
# endif
(*rbuf->receiver)(rbuf);
} else {
msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
abort();
}
BLOCK_IO_AND_ALARM();
freerecvbuf(rbuf);
rbuf = get_full_recv_buffer();
}
# ifdef DEBUG_TIMING
get_systime(&tsb);
L_SUB(&tsb, &tsa);
if (bufcount) {
collect_timing(NULL, "processing", bufcount, &tsb);
DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
}
}
# endif
/*
* Go around again
*/
# ifdef HAVE_DNSREGISTRATION
if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
mdnsreg = current_time;
msyslog(LOG_INFO, "Attempting to register mDNS");
if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL,
htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
if (!--mdnstries) {
msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
} else {
msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
}
} else {
msyslog(LOG_INFO, "mDNS service registered.");
mdnsreg = FALSE;
}
}
# endif /* HAVE_DNSREGISTRATION */
}
UNBLOCK_IO_AND_ALARM();
return 1;
}
#endif /* !SIM */
#if !defined(SIM) && defined(SIGDIE1)
/*
* finish - exit gracefully
*/
static void
finish_safe(
int sig
)
{
const char *sig_desc;
sig_desc = NULL;
#ifdef HAVE_STRSIGNAL
sig_desc = strsignal(sig);
#endif
if (sig_desc == NULL)
sig_desc = "";
msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
sig, sig_desc);
/* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
# ifdef HAVE_DNSREGISTRATION
if (mdns != NULL)
DNSServiceRefDeallocate(mdns);
# endif
peer_cleanup();
exit(0);
}
static RETSIGTYPE
finish(
int sig
)
{
signalled = 1;
signo = sig;
}
#endif /* !SIM && SIGDIE1 */
#ifndef SIM
/*
* wait_child_sync_if - implements parent side of -w/--wait-sync
*/
# ifdef HAVE_WORKING_FORK
static int
wait_child_sync_if(
int pipe_read_fd,
unsigned long wait_sync
)
{
int rc;
char ch;
time_t wait_end_time;
time_t cur_time;
time_t wait_rem;
fd_set readset;
struct timeval wtimeout;
/* we wait a bit for the child in *any* case, because on failure
* of the child we have to get and inspect the exit code!
*/
wait_end_time = time(NULL);
if (wait_sync)
wait_end_time += wait_sync;
else
wait_end_time += 30;
do {
cur_time = time(NULL);
wait_rem = (wait_end_time > cur_time)
? (wait_end_time - cur_time)
: 0;
wtimeout.tv_sec = wait_rem;
wtimeout.tv_usec = 0;
FD_ZERO(&readset);
FD_SET(pipe_read_fd, &readset);
rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
&wtimeout);
if (-1 == rc) {
if (EINTR == errno)
continue;
msyslog(LOG_ERR,
"daemon startup: select failed: %m");
return EX_IOERR;
}
if (0 == rc) {
/*
* select() indicated a timeout, but in case
* its timeouts are affected by a step of the
* system clock, select() again with a zero
* timeout to confirm.
*/
FD_ZERO(&readset);
FD_SET(pipe_read_fd, &readset);
wtimeout.tv_sec = 0;
wtimeout.tv_usec = 0;
rc = select(pipe_read_fd + 1, &readset, NULL,
NULL, &wtimeout);
if (0 == rc) /* select() timeout */
break;
}
rc = read(pipe_read_fd, &ch, 1);
if (rc == 0) {
DPRINTF(2, ("daemon control: got EOF\n"));
return -1; /* unexpected EOF, check daemon */
} else if (rc == 1) {
DPRINTF(2, ("daemon control: got '%c'\n",
(ch >= ' ' ? ch : '.')));
if (ch == 'R' && !wait_sync)
return 0;
if (ch == 'S' && wait_sync)
return 0;
} else {
DPRINTF(2, ("daemon control: read 1 char failed: %s\n",
strerror(errno)));
return EX_IOERR;
}
} while (wait_rem > 0);
if (wait_sync) {
fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
progname, wait_sync);
return EX_PROTOCOL;
} else {
fprintf(stderr, "%s: daemon startup monitoring timed out.\n",
progname);
return 0;
}
}
static int
wait_child_exit_if(
pid_t cpid,
int blocking
)
{
# ifdef HAVE_WAITPID
int rc = 0;
int wstatus;
if (cpid == waitpid(cpid, &wstatus, (blocking ? 0 : WNOHANG))) {
DPRINTF(1, ("child (pid=%d) dead now\n", cpid));
if (WIFEXITED(wstatus)) {
rc = WEXITSTATUS(wstatus);
msyslog(LOG_ERR, "daemon child exited with code %d",
rc);
} else if (WIFSIGNALED(wstatus)) {
rc = EX_SOFTWARE;
msyslog(LOG_ERR, "daemon child died with signal %d",
WTERMSIG(wstatus));
} else {
rc = EX_SOFTWARE;
msyslog(LOG_ERR, "daemon child died with unknown cause");
}
} else {
DPRINTF(1, ("child (pid=%d) still alive\n", cpid));
}
return rc;
# else
UNUSED_ARG(cpid);
return 0;
# endif
}
# endif /* HAVE_WORKING_FORK */
/*
* assertion_failed - Redirect assertion failures to msyslog().
*/
static void
assertion_failed(
const char *file,
int line,
isc_assertiontype_t type,
const char *cond
)
{
isc_assertion_setcallback(NULL); /* Avoid recursion */
msyslog(LOG_ERR, "%s:%d: %s(%s) failed",
file, line, isc_assertion_typetotext(type), cond);
msyslog(LOG_ERR, "exiting (due to assertion failure)");
#if defined(DEBUG) && defined(SYS_WINNT)
if (debug)
DebugBreak();
#endif
abort();
}
/*
* library_fatal_error - Handle fatal errors from our libraries.
*/
static void
library_fatal_error(
const char *file,
int line,
const char *format,
va_list args
)
{
char errbuf[256];
isc_error_setfatal(NULL); /* Avoid recursion */
msyslog(LOG_ERR, "%s:%d: fatal error:", file, line);
vsnprintf(errbuf, sizeof(errbuf), format, args);
msyslog(LOG_ERR, "%s", errbuf);
msyslog(LOG_ERR, "exiting (due to fatal error in library)");
#if defined(DEBUG) && defined(SYS_WINNT)
if (debug)
DebugBreak();
#endif
abort();
}
/*
* library_unexpected_error - Handle non fatal errors from our libraries.
*/
# define MAX_UNEXPECTED_ERRORS 100
int unexpected_error_cnt = 0;
static void
library_unexpected_error(
const char *file,
int line,
const char *format,
va_list args
)
{
char errbuf[256];
if (unexpected_error_cnt >= MAX_UNEXPECTED_ERRORS)
return; /* avoid clutter in log */
msyslog(LOG_ERR, "%s:%d: unexpected error:", file, line);
vsnprintf(errbuf, sizeof(errbuf), format, args);
msyslog(LOG_ERR, "%s", errbuf);
if (++unexpected_error_cnt == MAX_UNEXPECTED_ERRORS)
msyslog(LOG_ERR, "Too many errors. Shutting up.");
}
#endif /* !SIM */
#if !defined(SIM) && !defined(SYS_WINNT)
# ifdef DEBUG
/*
* moredebug - increase debugging verbosity
*/
static RETSIGTYPE
moredebug(
int sig
)
{
int saved_errno = errno;
if (debug < 255)
{
debug++;
msyslog(LOG_DEBUG, "debug raised to %d", debug);
}
errno = saved_errno;
}
/*
* lessdebug - decrease debugging verbosity
*/
static RETSIGTYPE
lessdebug(
int sig
)
{
int saved_errno = errno;
if (debug > 0)
{
debug--;
msyslog(LOG_DEBUG, "debug lowered to %d", debug);
}
errno = saved_errno;
}
# else /* !DEBUG follows */
/*
* no_debug - We don't do the debug here.
*/
static RETSIGTYPE
no_debug(
int sig
)
{
int saved_errno = errno;
msyslog(LOG_DEBUG, "ntpd not compiled for debugging (signal %d)", sig);
errno = saved_errno;
}
# endif /* !DEBUG */
#endif /* !SIM && !SYS_WINNT */
|