Source code pulled from OpenBSD for OpenNTPD. The place to contribute to this code is via the OpenBSD CVS tree.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

632 lines
15 KiB

8 years ago
8 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. # $OpenBSD: rc,v 1.513 2017/07/18 19:31:20 zhuk Exp $
  2. # System startup script run by init on autoboot or after single-user.
  3. # Output and error are redirected to console by init, and the console is the
  4. # controlling terminal.
  5. # Turn off Strict Bourne shell.
  6. set +o sh
  7. # Subroutines (have to come first).
  8. # Strip in- and whole-line comments from a file.
  9. # Strip leading and trailing whitespace if IFS is set.
  10. # Usage: stripcom /path/to/file
  11. stripcom() {
  12. local _file=$1 _line
  13. [[ -s $_file ]] || return
  14. while read _line ; do
  15. _line=${_line%%#*}
  16. [[ -n $_line ]] && print -r -- "$_line"
  17. done <$_file
  18. }
  19. # Update resource limits based on login.conf settings.
  20. # Usage: update_limit -flag capability
  21. update_limit() {
  22. local _flag=$1 # ulimit flag
  23. local _cap=$2 _val # login.conf capability and its value
  24. local _suffix
  25. for _suffix in {,-max,-cur}; do
  26. _val=$(getcap -f /etc/login.conf -s ${_cap}${_suffix} daemon 2>/dev/null)
  27. [[ -n $_val ]] || continue
  28. [[ $_val == infinity ]] && _val=unlimited
  29. case $_suffix in
  30. -cur) ulimit -S $_flag $_val
  31. ;;
  32. -max) ulimit -H $_flag $_val
  33. ;;
  34. *) ulimit $_flag $_val
  35. return
  36. ;;
  37. esac
  38. done
  39. }
  40. # Apply sysctl.conf(5) settings.
  41. sysctl_conf() {
  42. stripcom /etc/sysctl.conf |
  43. while read _line; do
  44. sysctl "$_line"
  45. case $_line in
  46. kern.maxproc=*)
  47. update_limit -p maxproc;;
  48. kern.maxfiles=*)
  49. update_limit -n openfiles;;
  50. esac
  51. done
  52. }
  53. # Apply mixerctl.conf(5) settings.
  54. mixerctl_conf() {
  55. stripcom /etc/mixerctl.conf |
  56. while read _line; do
  57. mixerctl -q "$_line" 2>/dev/null
  58. done
  59. }
  60. # Apply wsconsctl.conf(5) settings.
  61. wsconsctl_conf() {
  62. [[ -x /sbin/wsconsctl ]] || return
  63. stripcom /etc/wsconsctl.conf |
  64. while read _line; do
  65. eval "wsconsctl $_line"
  66. done
  67. }
  68. # Push the old seed into the kernel, create a future seed and create a seed
  69. # file for the boot-loader.
  70. random_seed() {
  71. dd if=/var/db/host.random of=/dev/random bs=65536 count=1 status=none
  72. chmod 600 /var/db/host.random
  73. dd if=/dev/random of=/var/db/host.random bs=65536 count=1 status=none
  74. dd if=/dev/random of=/etc/random.seed bs=512 count=1 status=none
  75. chmod 600 /etc/random.seed
  76. }
  77. # Populate net.inet.(tcp|udp).baddynamic with the contents of /etc/services so
  78. # as to avoid randomly allocating source ports that correspond to well-known
  79. # services.
  80. # Usage: fill_baddynamic tcp|udp
  81. fill_baddynamic() {
  82. local _service=$1
  83. local _sysctl="net.inet.${_service}.baddynamic"
  84. stripcom /etc/services |
  85. {
  86. _ban=
  87. while IFS=" /" read _name _port _srv _junk; do
  88. [[ $_srv == $_service ]] || continue
  89. _ban="${_ban:+$_ban,}+$_port"
  90. # Flush before argv gets too long
  91. if ((${#_ban} > 1024)); then
  92. sysctl -q "$_sysctl=$_ban"
  93. _ban=
  94. fi
  95. done
  96. [[ -n $_ban ]] && sysctl -q "$_sysctl=$_ban"
  97. }
  98. }
  99. # Start daemon using the rc.d daemon control scripts.
  100. # Usage: start_daemon daemon1 daemon2 daemon3
  101. start_daemon() {
  102. local _daemon
  103. for _daemon; do
  104. eval "_do=\${${_daemon}_flags}"
  105. [[ $_do != NO ]] && /etc/rc.d/${_daemon} start
  106. done
  107. }
  108. # Generate keys for isakmpd, iked and sshd if they don't exist yet.
  109. make_keys() {
  110. local _isakmpd_key=/etc/isakmpd/private/local.key
  111. local _isakmpd_pub=/etc/isakmpd/local.pub
  112. local _iked_key=/etc/iked/private/local.key
  113. local _iked_pub=/etc/iked/local.pub
  114. if [[ ! -f $_isakmpd_key ]]; then
  115. echo -n "openssl: generating isakmpd/iked RSA keys... "
  116. if openssl genrsa -out $_isakmpd_key 2048 >/dev/null 2>&1 &&
  117. chmod 600 $_isakmpd_key &&
  118. openssl rsa -out $_isakmpd_pub -in $_isakmpd_key \
  119. -pubout >/dev/null 2>&1; then
  120. echo done.
  121. else
  122. echo failed.
  123. fi
  124. fi
  125. if [[ ! -f $_iked_key ]]; then
  126. # Just copy the generated isakmpd key
  127. cp $_isakmpd_key $_iked_key
  128. chmod 600 $_iked_key
  129. cp $_isakmpd_pub $_iked_pub
  130. fi
  131. ssh-keygen -A
  132. }
  133. # Re-link libraries, placing the objects in a random order.
  134. reorder_libs() {
  135. local _dkdev _liba _libas _mp _tmpdir _remount=false _error=false
  136. [[ $library_aslr == NO ]] && return
  137. _dkdev=$(df /usr/lib | sed '1d;s/ .*//')
  138. _mp=$(mount | grep "^$_dkdev")
  139. # Skip if /usr/lib is on a nfs mounted filesystem.
  140. [[ $_mp == *' type nfs '* ]] && return
  141. echo -n 'reordering libraries:'
  142. # Remount read-write, if /usr/lib is on a read-only ffs filesystem.
  143. if [[ $_mp == *' type ffs '*'read-only'* ]]; then
  144. if mount -u -w $_dkdev; then
  145. _remount=true
  146. else
  147. echo ' failed.'
  148. return
  149. fi
  150. fi
  151. # Only choose the latest version of the libraries.
  152. for _liba in /usr/lib/lib{c,crypto}; do
  153. _libas="$_libas $(ls $_liba.so.+([0-9.]).a | sort -rV | head -1)"
  154. done
  155. _libas=${_libas# }
  156. for _liba in $_libas; do
  157. _tmpdir=$(mktemp -dq /tmp/_librebuild.XXXXXXXXXXXX) && (
  158. set -o errexit
  159. _lib=${_liba#/usr/lib/}
  160. _lib=${_lib%.a}
  161. cd $_tmpdir
  162. ar x ${_liba}
  163. cc -shared -o $_lib $(ls *.so | sort -R) $(cat .ldadd)
  164. [[ -s $_lib ]] && file $_lib | fgrep -q 'shared object'
  165. LD_BIND_NOW=1 LD_LIBRARY_PATH=$_tmpdir awk 'BEGIN {exit 0}'
  166. LD_BIND_NOW=1 LD_LIBRARY_PATH=$_tmpdir openssl \
  167. x509 -in /etc/ssl/cert.pem -out /dev/null
  168. install -F -S -o root -g bin -m 0444 $_lib /usr/lib/$_lib
  169. ) || { _error=true; break; }
  170. done
  171. rm -rf /tmp/_librebuild.*
  172. # Restore previous mount state if it was changed.
  173. if $_remount; then
  174. mount -u -r $_dkdev || _error=true
  175. fi
  176. if $_error; then
  177. echo ' failed.'
  178. else
  179. echo ' done.'
  180. fi
  181. }
  182. # Re-link the kernel, placing the objects in a random order.
  183. # Replace current with relinked kernel and inform root about it.
  184. reorder_kernel() (
  185. local _dkdev=$(df /usr/share | sed '1d;s/ .*//')
  186. # Skip if /usr/share is on a nfs mounted filesystem.
  187. [[ $(mount | grep "^$_dkdev") == *" type nfs "* ]] && return
  188. _compile=/usr/share/compile
  189. _kernel=$(sysctl -n kern.osversion)
  190. _kernel=${_kernel%#*}
  191. _log=$_compile/$_kernel/relink.log
  192. _sha256=/var/db/kernel.SHA256
  193. mkdir -m 700 -p $_compile/$_kernel
  194. exec 1>$_log
  195. exec 2>&1
  196. trap 'trap - EXIT; logger -st /etc/rc \
  197. "kernel relinking failed; see $_log" >>/dev/console 2>&1' ERR
  198. trap 'logger -t /etc/rc "kernel relinking done"' EXIT
  199. set -e
  200. if [[ -f $_compile.tgz ]]; then
  201. rm -rf $_compile/$_kernel/*
  202. exec 1>$_log
  203. tar -C $_compile -xzf $_compile.tgz $_kernel
  204. rm -f $_compile.tgz
  205. fi
  206. sha256 -C $_sha256 /bsd
  207. cd $_compile/$_kernel
  208. make newbsd
  209. make newinstall
  210. echo "\nKernel has been relinked and is active on next reboot.\n"
  211. cat $_sha256
  212. )
  213. # Run rc.* script and email output to root.
  214. # Usage: run_upgrade_script firsttime|sysmerge
  215. run_upgrade_script() {
  216. local _suffix=$1
  217. [[ -n $_suffix ]] || return 1
  218. if [[ -f /etc/rc.$_suffix ]]; then
  219. mv /etc/rc.$_suffix /etc/rc.$_suffix.run
  220. . /etc/rc.$_suffix.run 2>&1 | tee /dev/tty |
  221. mail -Es "$(hostname) rc.$_suffix output" root >/dev/null
  222. fi
  223. rm -f /etc/rc.$_suffix.run
  224. }
  225. # Check filesystems, optionally by using a fsck(8) flag.
  226. # Usage: do_fsck [-flag]
  227. do_fsck() {
  228. fsck -p "$@"
  229. case $? in
  230. 0) ;;
  231. 2) exit 1
  232. ;;
  233. 4) echo "Rebooting..."
  234. reboot
  235. echo "Reboot failed; help!"
  236. exit 1
  237. ;;
  238. 8) echo "Automatic file system check failed; help!"
  239. exit 1
  240. ;;
  241. 12) echo "Boot interrupted."
  242. exit 1
  243. ;;
  244. 130) # Interrupt before catcher installed.
  245. exit 1
  246. ;;
  247. *) echo "Unknown error; help!"
  248. exit 1
  249. ;;
  250. esac
  251. }
  252. # End subroutines.
  253. stty status '^T'
  254. # Set shell to ignore SIGINT (2), but not children; shell catches SIGQUIT (3)
  255. # and returns to single user after fsck.
  256. trap : 2
  257. trap : 3 # Shouldn't be needed.
  258. export HOME=/
  259. export INRC=1
  260. export PATH=/sbin:/bin:/usr/sbin:/usr/bin
  261. # Must set the domainname before rc.conf, so YP startup choices can be made.
  262. if [[ -s /etc/defaultdomain ]]; then
  263. domainname "$(stripcom /etc/defaultdomain)"
  264. fi
  265. # Get local functions from rc.subr to load rc.conf into scope.
  266. FUNCS_ONLY=1 . /etc/rc.d/rc.subr
  267. _rc_parse_conf
  268. # If executed with the 'shutdown' parameter by the halt, reboot or shutdown:
  269. # - update seed files
  270. # - execute the rc.d scripts specified by $pkg_scripts in reverse order
  271. # - bring carp interfaces down gracefully
  272. if [[ $1 == shutdown ]]; then
  273. if echo 2>/dev/null >>/var/db/host.random || \
  274. echo 2>/dev/null >>/etc/random.seed; then
  275. random_seed
  276. else
  277. echo warning: cannot write random seed to disk
  278. fi
  279. # If we are in secure level 0, assume single user mode.
  280. if (($(sysctl -n kern.securelevel) == 0)); then
  281. echo 'single user: not running shutdown scripts'
  282. else
  283. pkg_scripts=${pkg_scripts%%*( )}
  284. if [[ -n $pkg_scripts ]]; then
  285. echo -n 'stopping package daemons:'
  286. while [[ -n $pkg_scripts ]]; do
  287. _d=${pkg_scripts##* }
  288. pkg_scripts=${pkg_scripts%%*( )$_d}
  289. [[ -x /etc/rc.d/$_d ]] && /etc/rc.d/$_d stop
  290. done
  291. echo '.'
  292. fi
  293. [[ -f /etc/rc.shutdown ]] && sh /etc/rc.shutdown
  294. fi
  295. ifconfig | while read _if _junk; do
  296. [[ $_if == carp+([0-9]): ]] && ifconfig ${_if%:} down
  297. done
  298. exit 0
  299. fi
  300. # Add swap block-devices.
  301. swapctl -A -t blk
  302. # Run filesystem check unless a /fastboot file exists.
  303. if [[ -e /fastboot ]]; then
  304. echo "Fast boot: skipping disk checks."
  305. elif [[ $1 == autoboot ]]; then
  306. echo "Automatic boot in progress: starting file system checks."
  307. do_fsck
  308. fi
  309. # From now on, allow user to interrupt (^C) the boot process.
  310. trap "echo 'Boot interrupted.'; exit 1" 3
  311. # Unmount all filesystems except root.
  312. umount -a >/dev/null 2>&1
  313. # Mount all filesystems except those of type NFS and VND.
  314. mount -a -t nonfs,vnd
  315. # Re-mount the root filesystem read/writeable. (root on nfs requires this,
  316. # others aren't hurt.)
  317. mount -uw /
  318. chmod og-rwx /bsd
  319. ln -fh /bsd /bsd.booted
  320. rm -f /fastboot
  321. # Set flags on ttys.
  322. echo 'setting tty flags'
  323. ttyflags -a
  324. # Set keyboard encoding.
  325. if [[ -x /sbin/kbd && -s /etc/kbdtype ]]; then
  326. kbd "$(cat /etc/kbdtype)"
  327. fi
  328. wsconsctl_conf
  329. # Set initial temporary pf rule set.
  330. if [[ $pf != NO ]]; then
  331. RULES="
  332. block all
  333. pass on lo0
  334. pass in proto tcp from any to any port ssh keep state
  335. pass out proto { tcp, udp } from any to any port domain keep state
  336. pass out inet proto icmp all icmp-type echoreq keep state
  337. pass out inet proto udp from any port bootpc to any port bootps
  338. pass in inet proto udp from any port bootps to any port bootpc"
  339. if ifconfig lo0 inet6 >/dev/null 2>&1; then
  340. RULES="$RULES
  341. pass out inet6 proto icmp6 all icmp6-type neighbrsol
  342. pass in inet6 proto icmp6 all icmp6-type neighbradv
  343. pass out inet6 proto icmp6 all icmp6-type routersol
  344. pass in inet6 proto icmp6 all icmp6-type routeradv
  345. pass out inet6 proto udp from any port dhcpv6-client to any port dhcpv6-server
  346. pass in inet6 proto udp from any port dhcpv6-server to any port dhcpv6-client"
  347. fi
  348. RULES="$RULES
  349. pass in proto carp keep state (no-sync)
  350. pass out proto carp !received-on any keep state (no-sync)"
  351. if (($(sysctl -n vfs.mounts.nfs 2>/dev/null) > 0)); then
  352. # Don't kill NFS.
  353. RULES="set reassemble yes no-df
  354. $RULES
  355. pass in proto { tcp, udp } from any port { sunrpc, nfsd } to any
  356. pass out proto { tcp, udp } from any to any port { sunrpc, nfsd } !received-on any"
  357. fi
  358. print -- "$RULES" | pfctl -f -
  359. pfctl -e
  360. fi
  361. fill_baddynamic udp
  362. fill_baddynamic tcp
  363. sysctl_conf
  364. start_daemon slaacd >/dev/null 2>&1
  365. echo 'starting network'
  366. # Set carp interlock by increasing the demotion counter.
  367. # Prevents carp from preempting until the system is booted.
  368. ifconfig -g carp carpdemote 128
  369. sh /etc/netstart
  370. # Any write triggers a rekey.
  371. dmesg >/dev/random
  372. # Load pf rules and bring up pfsync interface.
  373. if [[ $pf != NO ]]; then
  374. if [[ -f /etc/pf.conf ]]; then
  375. pfctl -f /etc/pf.conf
  376. fi
  377. if [[ -f /etc/hostname.pfsync0 ]]; then
  378. sh /etc/netstart pfsync0
  379. fi
  380. fi
  381. mount -s /usr >/dev/null 2>&1
  382. mount -s /var >/dev/null 2>&1
  383. random_seed
  384. reorder_libs
  385. # Clean up left-over files.
  386. rm -f /etc/nologin /var/spool/lock/LCK.*
  387. (cd /var/run && { rm -rf -- *; install -c -m 664 -g utmp /dev/null utmp; })
  388. (cd /var/authpf && rm -rf -- *)
  389. # Save a copy of the boot messages.
  390. dmesg >/var/run/dmesg.boot
  391. make_keys
  392. echo -n 'starting early daemons:'
  393. start_daemon syslogd ldattach pflogd nsd rebound unbound ntpd
  394. start_daemon iscsid isakmpd iked sasyncd ldapd npppd
  395. echo '.'
  396. # Load IPsec rules.
  397. if [[ $ipsec != NO && -f /etc/ipsec.conf ]]; then
  398. ipsecctl -f /etc/ipsec.conf
  399. fi
  400. echo -n 'starting RPC daemons:'
  401. start_daemon portmap ypldap
  402. rm -f /var/run/ypbind.lock
  403. if [[ -n $(domainname) ]]; then
  404. start_daemon ypserv ypbind
  405. fi
  406. start_daemon mountd nfsd lockd statd amd
  407. echo '.'
  408. # Check and mount remaining file systems and enable additional swap.
  409. mount -a
  410. swapctl -A -t noblk
  411. do_fsck -N
  412. mount -a -N
  413. # /var/crash should be a directory or a symbolic link to the crash directory
  414. # if core dumps are to be saved.
  415. if [[ -d /var/crash ]]; then
  416. savecore $savecore_flags /var/crash
  417. fi
  418. # Store ACPI tables in /var/db/acpi to be used by sendbug(1).
  419. if [[ -x /usr/sbin/acpidump ]]; then
  420. acpidump -o /var/db/acpi/
  421. fi
  422. if [[ $check_quotas == YES ]]; then
  423. echo -n 'checking quotas:'
  424. quotacheck -a
  425. echo ' done.'
  426. quotaon -a
  427. fi
  428. # Build kvm(3) and /dev databases.
  429. kvm_mkdb
  430. dev_mkdb
  431. # Set proper permission for the tty device files.
  432. chmod 666 /dev/tty[pqrstuvwxyzPQRST]*
  433. chown root:wheel /dev/tty[pqrstuvwxyzPQRST]*
  434. # Check for the password temp/lock file.
  435. if [[ -f /etc/ptmp ]]; then
  436. logger -s -p auth.err \
  437. 'password file may be incorrect -- /etc/ptmp exists'
  438. fi
  439. echo clearing /tmp
  440. # Prune quickly with one rm, then use find to clean up /tmp/[lqv]*
  441. # (not needed with mfs /tmp, but doesn't hurt there...).
  442. (cd /tmp && rm -rf [a-km-pr-uw-zA-Z]*)
  443. (cd /tmp &&
  444. find . -maxdepth 1 ! -name . ! -name lost+found ! -name quota.user \
  445. ! -name quota.group ! -name vi.recover -execdir rm -rf -- {} \;)
  446. # Create Unix sockets directories for X if needed and make sure they have
  447. # correct permissions.
  448. [[ -d /usr/X11R6/lib ]] && mkdir -m 1777 /tmp/.{X11,ICE}-unix
  449. [[ -f /etc/rc.securelevel ]] && sh /etc/rc.securelevel
  450. # rc.securelevel did not specifically set -1 or 2, so select the default: 1.
  451. (($(sysctl -n kern.securelevel) == 0)) && sysctl kern.securelevel=1
  452. # Patch /etc/motd.
  453. if [[ ! -f /etc/motd ]]; then
  454. install -c -o root -g wheel -m 664 /dev/null /etc/motd
  455. fi
  456. if T=$(mktemp /tmp/_motd.XXXXXXXXXX); then
  457. sysctl -n kern.version | sed 1q >$T
  458. sed -n '/^$/,$p' </etc/motd >>$T
  459. cmp -s $T /etc/motd || cp $T /etc/motd
  460. rm -f $T
  461. fi
  462. if [[ $accounting == YES ]]; then
  463. [[ ! -f /var/account/acct ]] && touch /var/account/acct
  464. echo 'turning on accounting'
  465. accton /var/account/acct
  466. fi
  467. if [[ -x /sbin/ldconfig ]]; then
  468. echo 'creating runtime link editor directory cache.'
  469. [[ -d /usr/local/lib ]] && shlib_dirs="/usr/local/lib $shlib_dirs"
  470. [[ -d /usr/X11R6/lib ]] && shlib_dirs="/usr/X11R6/lib $shlib_dirs"
  471. ldconfig $shlib_dirs
  472. fi
  473. echo 'preserving editor files.'; /usr/libexec/vi.recover
  474. # If rc.sysmerge exists, run it just once, and make sure it is deleted.
  475. run_upgrade_script sysmerge
  476. echo -n 'starting network daemons:'
  477. start_daemon ldomd sshd switchd snmpd ldpd ripd ospfd ospf6d bgpd ifstated
  478. start_daemon relayd dhcpd dhcrelay mrouted dvmrpd radiusd eigrpd
  479. if ifconfig lo0 inet6 >/dev/null 2>&1; then
  480. if (($(sysctl -n net.inet6.ip6.forwarding) == 1)); then
  481. start_daemon route6d rtadvd
  482. fi
  483. fi
  484. start_daemon hostapd lpd smtpd slowcgi httpd ftpd
  485. start_daemon ftpproxy ftpproxy6 tftpd tftpproxy identd inetd rarpd bootparamd
  486. start_daemon rbootd mopd vmd spamd spamlogd sndiod
  487. echo '.'
  488. # If rc.firsttime exists, run it just once, and make sure it is deleted.
  489. run_upgrade_script firsttime
  490. # Run rc.d(8) scripts from packages.
  491. if [[ -n $pkg_scripts ]]; then
  492. echo -n 'starting package daemons:'
  493. for _daemon in $pkg_scripts; do
  494. if [[ -x /etc/rc.d/$_daemon ]]; then
  495. start_daemon $_daemon
  496. else
  497. echo -n " ${_daemon}(absent)"
  498. fi
  499. done
  500. echo '.'
  501. fi
  502. [[ -f /etc/rc.local ]] && sh /etc/rc.local
  503. # Disable carp interlock.
  504. ifconfig -g carp -carpdemote 128
  505. mixerctl_conf
  506. echo -n 'starting local daemons:'
  507. start_daemon apmd sensorsd hotplugd watchdogd cron wsmoused xenodm
  508. echo '.'
  509. reorder_kernel &
  510. date
  511. exit 0