2021-11-30 16:10:41 +01:00
|
|
|
# Copyright 2021 Mattia Giambirtone & All Contributors
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
# you may not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
2021-11-30 20:54:27 +01:00
|
|
|
import parseopt
|
2021-11-30 16:10:41 +01:00
|
|
|
import strformat
|
|
|
|
import posix
|
2022-03-12 17:22:40 +01:00
|
|
|
import net
|
2021-11-30 16:10:41 +01:00
|
|
|
import os
|
|
|
|
|
2021-11-30 23:56:38 +01:00
|
|
|
# NimD's own stuff
|
2022-01-09 22:46:25 +01:00
|
|
|
import util/[logging, constants, misc, config]
|
2021-12-04 13:47:06 +01:00
|
|
|
import core/[mainloop, fs, shutdown, services]
|
2021-11-30 16:10:41 +01:00
|
|
|
|
|
|
|
|
2021-12-05 20:53:44 +01:00
|
|
|
proc addStuff =
|
|
|
|
## Adds stuff to test NimD. This is
|
|
|
|
## a temporary procedure
|
|
|
|
|
2022-01-31 14:56:12 +01:00
|
|
|
## Note: Commented because the config file now does this work!
|
2021-12-05 20:53:44 +01:00
|
|
|
# Adds symlinks
|
2022-01-31 14:56:12 +01:00
|
|
|
# addSymlink(newSymlink(dest="/dev/fd", source="/proc/self/fd"))
|
|
|
|
# addSymlink(newSymlink(dest="/dev/fd/0", source="/proc/self/fd/0"))
|
|
|
|
# addSymlink(newSymlink(dest="/dev/fd/1", source="/proc/self/fd/1"))
|
|
|
|
# addSymlink(newSymlink(dest="/dev/fd/2", source="/proc/self/fd/2"))
|
|
|
|
# addSymlink(newSymlink(dest="/dev/std/in", source="/proc/self/fd/0"))
|
|
|
|
# addSymlink(newSymlink(dest="/dev/std/out", source="/proc/self/fd/1"))
|
|
|
|
# addSymlink(newSymlink(dest="/dev/std/err", source="/proc/self/fd/2"))
|
|
|
|
# # Tests here. Check logging output (debug) to see if
|
|
|
|
# # they work as intended
|
|
|
|
# addSymlink(newSymlink(dest="/dev/std/err", source="/")) # Should say link already exists and points to /proc/self/fd/2
|
|
|
|
# addSymlink(newSymlink(dest="/dev/std/in", source="/does/not/exist")) # Should say destination does not exist
|
|
|
|
# addSymlink(newSymlink(dest="/dev/std/in", source="/proc/self/fd/0")) # Should say link already exists
|
|
|
|
# addDirectory(newDirectory("test", 764)) # Should create a directory
|
|
|
|
# addDirectory(newDirectory("/dev/disk", 123)) # Should say directory already exists
|
2022-01-09 22:46:25 +01:00
|
|
|
|
2021-12-05 20:53:44 +01:00
|
|
|
# Adds test services
|
2021-12-16 11:24:00 +01:00
|
|
|
var echoer = newService(name="echoer", description="prints owo", exec="/bin/echo owoooooooooo",
|
2021-12-06 20:45:53 +01:00
|
|
|
runlevel=Boot, kind=Oneshot, workDir=getCurrentDir(),
|
|
|
|
supervised=false, restart=Never, restartDelay=0,
|
2022-01-14 08:30:18 +01:00
|
|
|
depends=(@[]), provides=(@[]), stdin="/dev/null", stderr="", stdout="")
|
2021-12-06 20:45:53 +01:00
|
|
|
var errorer = newService(name="errorer", description="la mamma di gavd",
|
2021-12-05 20:53:44 +01:00
|
|
|
exec="/bin/false", supervised=true, restart=OnFailure,
|
2021-12-06 20:45:53 +01:00
|
|
|
restartDelay=5, runlevel=Boot, workDir="/", kind=Simple,
|
2022-01-14 08:30:18 +01:00
|
|
|
depends=(@[newDependency(Other, echoer)]), provides=(@[]),
|
|
|
|
stdin="/dev/null", stderr="", stdout="")
|
2021-12-06 20:45:53 +01:00
|
|
|
var exiter = newService(name="exiter", description="la mamma di licenziat",
|
2021-12-05 20:53:44 +01:00
|
|
|
exec="/bin/true", supervised=true, restart=Always,
|
2021-12-06 20:45:53 +01:00
|
|
|
restartDelay=5, runlevel=Boot, workDir="/", kind=Simple,
|
2022-01-14 08:30:18 +01:00
|
|
|
depends=(@[newDependency(Other, errorer)]), provides=(@[]),
|
|
|
|
stdin="/dev/null", stderr="", stdout="")
|
2021-12-09 17:30:30 +01:00
|
|
|
var shell = newService(name="login", description="A simple login shell", kind=Simple,
|
2022-01-14 08:30:18 +01:00
|
|
|
workDir=getCurrentDir(), runlevel=Boot, exec="/bin/login -f root",
|
2021-12-16 11:24:00 +01:00
|
|
|
supervised=true, restart=Always, restartDelay=0, depends=(@[]), provides=(@[]),
|
2022-03-13 12:46:39 +01:00
|
|
|
useParentStreams=true, stdin="/dev/null", stderr="/proc/self/fd/2", stdout="/proc/self/fd/1"
|
2021-12-09 17:30:30 +01:00
|
|
|
)
|
2021-12-06 20:45:53 +01:00
|
|
|
addService(errorer)
|
|
|
|
addService(echoer)
|
|
|
|
addService(exiter)
|
2021-12-09 17:30:30 +01:00
|
|
|
addService(shell)
|
|
|
|
|
2021-12-05 20:53:44 +01:00
|
|
|
|
2022-03-12 17:22:40 +01:00
|
|
|
proc checkControlSocket(logger: Logger, config: NimDConfig): bool =
|
|
|
|
## Performs some startup checks on nim's control
|
|
|
|
## socket
|
|
|
|
result = true
|
|
|
|
var stat_result: Stat
|
|
|
|
if posix.stat(cstring(config.sock), stat_result) == -1:
|
|
|
|
logger.warning(&"Could not stat() {config.sock}, assuming NimD instance isn't running")
|
|
|
|
# I stole this from /usr/lib/python3.10/stat.py
|
|
|
|
elif (int(stat_result.st_mode) and 0o170000) != 0o140000:
|
|
|
|
logger.fatal(&"{config.sock} exists and is not a socket")
|
|
|
|
result = false
|
|
|
|
elif dirExists(config.sock):
|
|
|
|
logger.info("Control socket path is a directory, appending nimd.sock to it")
|
|
|
|
config.sock = config.sock.joinPath("nimd.sock")
|
|
|
|
else:
|
|
|
|
logger.debug("Trying to reach current NimD instance")
|
|
|
|
var sock = newSocket(Domain.AF_UNIX, SockType.SOCK_STREAM, Protocol.IPPROTO_IP)
|
|
|
|
try:
|
|
|
|
sock.connectUnix(config.sock)
|
|
|
|
logger.info("Control socket already exists, trying to reach current NimD instance")
|
|
|
|
except OSError:
|
|
|
|
logger.warning(&"Could not connect to control socket at {config.sock} ({getCurrentExceptionMsg()}), assuming NimD instance isn't running")
|
|
|
|
try:
|
|
|
|
removeFile(config.sock)
|
|
|
|
except OSError:
|
|
|
|
logger.warning(&"Could not delete dangling control socket at {config.sock} ({getCurrentExceptionMsg()})")
|
|
|
|
if sock.trySend("c"):
|
|
|
|
try:
|
|
|
|
if sock.recv(1, timeout=5) == "1":
|
|
|
|
logger.error("Another NimD instance is running! Exiting")
|
|
|
|
result = false
|
|
|
|
except OSError:
|
|
|
|
logger.warning(&"Could not read from control socket at {config.sock} ({getCurrentExceptionMsg()}), assuming NimD instance isn't running")
|
|
|
|
except TimeoutError:
|
|
|
|
logger.warning(&"Could not read from control socket at {config.sock} ({getCurrentExceptionMsg()}), assuming NimD instance isn't running")
|
|
|
|
else:
|
|
|
|
logger.fatal(&"Could not write on control socket at {config.sock}")
|
|
|
|
result = false
|
|
|
|
|
2021-12-05 20:53:44 +01:00
|
|
|
|
2022-01-09 22:46:25 +01:00
|
|
|
proc main(logger: Logger, config: NimDConfig) =
|
2021-12-04 13:47:06 +01:00
|
|
|
## NimD's entry point and setup
|
|
|
|
## function
|
2022-03-12 17:22:40 +01:00
|
|
|
if not checkControlSocket(logger, config):
|
|
|
|
return
|
2022-01-09 22:46:25 +01:00
|
|
|
logger.debug(&"Setting log file to '{config.logFile}'")
|
|
|
|
setLogFile(file=config.logFile)
|
2021-12-06 13:47:11 +01:00
|
|
|
logger.debug("Starting NimD: A minimal, self-contained, dependency-based Linux init system written in Nim")
|
2021-12-04 13:47:06 +01:00
|
|
|
logger.info(&"NimD version {NimdVersion.major}.{NimdVersion.minor}.{NimdVersion.patch} is starting up!")
|
2021-11-30 20:54:27 +01:00
|
|
|
logger.trace("Calling getCurrentProcessId()")
|
|
|
|
let pid = getCurrentProcessId()
|
|
|
|
logger.trace(&"getCurrentProcessId() returned {pid}")
|
|
|
|
if pid != 1:
|
2021-11-30 16:10:41 +01:00
|
|
|
logger.warning(&"Expecting to run as PID 1, but current process ID is {pid}")
|
2021-11-30 20:54:27 +01:00
|
|
|
logger.trace("Calling getuid()")
|
|
|
|
let uid = posix.getuid()
|
|
|
|
logger.trace(&"getuid() returned {uid}")
|
|
|
|
if uid != 0:
|
|
|
|
logger.fatal(&"NimD must run as root, but current user id is {uid}")
|
2021-12-06 13:47:11 +01:00
|
|
|
nimDExit(logger, EPERM, emerg=false) # EPERM - Operation not permitted
|
2021-12-04 13:47:06 +01:00
|
|
|
logger.trace("Setting up signal handlers")
|
2021-12-04 17:31:18 +01:00
|
|
|
onSignal(SIGABRT, SIGALRM, SIGHUP, SIGILL, SIGKILL, SIGQUIT, SIGSTOP, SIGSEGV, SIGTSTP,
|
2022-01-09 22:46:25 +01:00
|
|
|
SIGTRAP, SIGPIPE, SIGUSR1, SIGUSR2, 6, SIGFPE, SIGBUS, SIGURG, SIGTERM, SIGINT): # 6 is SIGIOT
|
2021-12-02 18:54:48 +01:00
|
|
|
# Can't capture local variables because this implicitly generates
|
2021-12-06 13:47:11 +01:00
|
|
|
# a noconv procedure, so we use getDefaultLogger() instead
|
2021-12-02 18:54:48 +01:00
|
|
|
getDefaultLogger().warning(&"Ignoring signal {sig} ({strsignal(sig)})") # Nim injects the variable "sig" into the scope. Gotta love those macros
|
2021-12-02 23:16:16 +01:00
|
|
|
onSignal(SIGCHLD):
|
2021-12-04 13:47:06 +01:00
|
|
|
# One of the key features of an init system is reaping child
|
|
|
|
# processes!
|
2021-12-02 23:16:16 +01:00
|
|
|
reapProcess(getDefaultLogger())
|
2022-01-09 22:46:25 +01:00
|
|
|
if config.autoUnmount:
|
|
|
|
logger.debug("Setting up shutdown handler for automatic disk unmounting")
|
|
|
|
# Shutdown handler to unmount disks
|
|
|
|
addShutdownHandler(newShutdownHandler(unmountAllDisks))
|
2021-12-05 20:53:44 +01:00
|
|
|
addStuff()
|
2021-12-04 13:47:06 +01:00
|
|
|
try:
|
2022-01-09 22:46:25 +01:00
|
|
|
if config.autoMount:
|
2021-12-04 13:47:06 +01:00
|
|
|
logger.info("Mounting filesystem")
|
2022-01-09 22:46:25 +01:00
|
|
|
mountDisks(logger, config.fstab)
|
2021-12-04 13:47:06 +01:00
|
|
|
else:
|
|
|
|
logger.info("Skipping disk mounting, assuming this has already been done")
|
2021-12-05 20:53:44 +01:00
|
|
|
logger.info("Creating symlinks")
|
|
|
|
createSymlinks(logger)
|
|
|
|
logger.info("Creating directories")
|
|
|
|
createDirectories(logger)
|
|
|
|
logger.info("Filesystem preparation complete")
|
|
|
|
logger.debug("Calling sync() just in case")
|
|
|
|
doSync(logger)
|
2021-12-04 13:47:06 +01:00
|
|
|
except:
|
|
|
|
logger.fatal(&"A fatal error has occurred while preparing filesystem, booting cannot continue. Error -> {getCurrentExceptionMsg()}")
|
|
|
|
nimDExit(logger, 131, emerg=false)
|
2022-01-09 22:46:25 +01:00
|
|
|
if config.setHostname:
|
2021-12-09 17:09:00 +01:00
|
|
|
logger.info("Setting hostname")
|
|
|
|
logger.debug(&"Hostname was set to '{misc.setHostname(logger)}'")
|
|
|
|
else:
|
|
|
|
logger.info("Skipping setting hostname")
|
2021-12-04 17:31:18 +01:00
|
|
|
logger.debug("Entering critical fork() section: blocking signals")
|
2021-12-05 20:53:44 +01:00
|
|
|
blockSignals(logger) # They are later unblocked in mainLoop
|
2021-12-04 13:47:06 +01:00
|
|
|
logger.info("Processing boot runlevel")
|
2022-01-09 22:46:25 +01:00
|
|
|
startServices(logger, workers=config.workers, level=Boot)
|
2021-12-04 13:47:06 +01:00
|
|
|
logger.debug("Starting main loop")
|
2022-01-09 22:46:25 +01:00
|
|
|
mainLoop(logger, config)
|
2021-11-30 20:54:27 +01:00
|
|
|
|
2021-11-30 16:10:41 +01:00
|
|
|
|
|
|
|
when isMainModule:
|
|
|
|
var logger = getDefaultLogger()
|
2021-11-30 20:54:27 +01:00
|
|
|
var optParser = initOptParser(commandLineParams())
|
|
|
|
for kind, key, value in optParser.getopt():
|
|
|
|
case kind:
|
|
|
|
of cmdArgument:
|
2021-12-05 20:53:44 +01:00
|
|
|
echo "Error: unexpected argument"
|
|
|
|
quit(EINVAL)
|
2021-11-30 20:54:27 +01:00
|
|
|
of cmdLongOption:
|
|
|
|
case key:
|
|
|
|
of "help":
|
|
|
|
echo helpMessage
|
|
|
|
quit(0)
|
|
|
|
of "version":
|
2021-11-30 23:56:38 +01:00
|
|
|
echo NimDVersionString
|
2021-11-30 20:54:27 +01:00
|
|
|
quit(0)
|
|
|
|
of "verbose":
|
|
|
|
logger.setLevel(LogLevel.Debug)
|
|
|
|
of "extra":
|
|
|
|
logger.setLevel(LogLevel.Trace)
|
|
|
|
else:
|
2021-12-05 20:53:44 +01:00
|
|
|
echo &"Unkown command-line long option '{key}'"
|
2021-11-30 20:54:27 +01:00
|
|
|
quit(EINVAL) # EINVAL - Invalid argument
|
|
|
|
of cmdShortOption:
|
|
|
|
case key:
|
|
|
|
of "h":
|
|
|
|
echo helpMessage
|
|
|
|
quit(0)
|
|
|
|
of "v":
|
2021-11-30 23:56:38 +01:00
|
|
|
echo NimDVersionString
|
2021-11-30 20:54:27 +01:00
|
|
|
quit(0)
|
|
|
|
of "V":
|
|
|
|
logger.setLevel(LogLevel.Debug)
|
|
|
|
of "X":
|
|
|
|
logger.setLevel(LogLevel.Trace)
|
|
|
|
else:
|
2021-12-05 20:53:44 +01:00
|
|
|
echo &"Unkown command-line short option '{key}'"
|
|
|
|
echo "Usage: nimd [options]"
|
|
|
|
echo "Try nimd --help for more info"
|
2021-11-30 20:54:27 +01:00
|
|
|
quit(EINVAL) # EINVAL - Invalid argument
|
|
|
|
else:
|
|
|
|
echo "Usage: nimd [options]"
|
2022-03-12 17:22:40 +01:00
|
|
|
quit(EINVAL) # EINVAL - Invalid argument
|
2022-01-09 22:46:25 +01:00
|
|
|
setStdIoUnbuffered() # Colors don't work otherwise!
|
2021-11-30 16:10:41 +01:00
|
|
|
try:
|
2022-01-09 22:46:25 +01:00
|
|
|
main(logger, parseConfig(logger, "/etc/nimd/nimd.conf"))
|
2021-11-30 16:10:41 +01:00
|
|
|
except:
|
2021-11-30 20:54:27 +01:00
|
|
|
logger.fatal(&"A fatal unrecoverable error has occurred during startup and NimD cannot continue: {getCurrentExceptionMsg()}")
|
2021-12-02 02:53:51 +01:00
|
|
|
nimDExit(logger, 131) # ENOTRECOVERABLE - State not recoverable
|
2021-11-30 16:10:41 +01:00
|
|
|
# This will almost certainly cause the kernel to crash with an error the likes of "Kernel not syncing, attempted to kill init!",
|
2021-12-05 20:53:44 +01:00
|
|
|
# but, after all, there isn't much we can do if we can't even initialize *ourselves* is there?
|