; Writing an OpenBSD Daemon
; openbsd go tech *nix
; Mon Nov 16 10:02:57 AM CET 2026

# Writing an OpenBSD Daemon

I recently{^At least it was recently when I started writing this!} migrated my server to OpenBSD, and decided to put some polish on my Twitch RSS generator [tweed](/repos/tweed/). It's a fairly simple Go program that makes some HTTP requests and serves RSS files via HTTP. The old version ran out of its working directory, reading its config and storing its data there. With the new update my goal was to have the program follow a more standard Unix daemon layout, keep its files in the conventional places, and run as a daemon user. Lastly, I wanted to do some OpenBSD-specific hardening using pledge and unveil.

## Logging

Traditionally, Unix daemons log using syslog. Syslog has been the standard on Unixes for over 40 years, and got standardised in 2009 by [RFC 5424](https://www.rfc-editor.org/rfc/rfc5424.txt). Using it in Go is simple: just import '''log/syslog''', call '''syslog.New''' to create your syslog writer, and start logging.

In my program, I open syslog with the daemon facility. Log calls go through a helper function that falls back to stderr when syslog isn't opened (more on that later).

'''
func initSyslog() error {
	w, err := syslog.New(syslog.LOG_DAEMON|syslog.LOG_INFO, "tweed")
	if err != nil {
		return err
	}
	sysLog = w
	return nil
}

func logAt(pri syslog.Priority, format string, args ...any) {
	msg := fmt.Sprintf(format, args...)
	if sysLog == nil {
		fmt.Fprintln(os.Stderr, msg)
		return
	}
	switch pri {
	case syslog.LOG_ERR:
		sysLog.Err(msg)
	case syslog.LOG_WARNING:
		sysLog.Warning(msg)
	default:
		sysLog.Info(msg)
	}
}
'''

What happens to these messages depends on how your syslog daemon is configured. On OpenBSD they mostly end up in '''/var/log/''', and are rotated using [newsyslog](https://man.openbsd.org/newsyslog.8). On systemd systems they are stored as binary files, and viewed using journalctl.

Lastly, I added a flag to log directly to the terminal instead. This is done by simply not calling '''initSyslog''', making it fall back to stderr. It's a useful debugging feature I have seen on several OpenBSD daemons like [httpd](https://man.openbsd.org/httpd.8) and [sshd](https://man.openbsd.org/sshd.8), and it made setting up the daemon a nicer experience.

'''
if !*debug {
	if err := initSyslog(); err != nil {
		fatal("syslog: %v", err)
	}
}
'''

## Config

The standard place for configuration files on most Unix-like systems is '''/etc/'''. NetBSD and FreeBSD both store non-base configuration files in the '''/usr/''' directory (in different places, of course), so I made the program search for its configuration files in multiple places.{^I only look for '''/etc/tweed/''' and '''/usr/local/etc/tweed/''', but might add more if I ever feel like it, or if someone else feels like it!} Importantly, I decided to not have my daemon create any directories on its own. I see this step as a part of the install process, which the user should do deliberately.

'''
var defaultConfigDirs = []string{
	"/etc/tweed",
	"/usr/local/etc/tweed",
}

func findConfigDir(given string) (string, error) {
	if given != "" {
		return given, nil
	}
	for _, d := range defaultConfigDirs {
		if _, err := os.Stat(filepath.Join(d, "config.ini")); !errors.Is(err, os.ErrNotExist) {
			return d, nil
		}
	}
	return "", fmt.Errorf("no config.ini found (looked in %s)",
		strings.Join(defaultConfigDirs, ", "))
}
'''

The config file is a plain key-value file with INI syntax.

'''
# /etc/tweed/config.ini
appId = ...
appSecret = ...
channels = foo, bar
port = 8081
dataDir = /var/www/tweed/
'''

I also decided to add a config flag to the program, allowing the user to set a custom config directory at runtime (this is the '''given''' argument to '''findConfigDir'''). This gives at least basic support for systems that keep configuration somewhere else.

## Data

The other place our program touches the filesystem is its data directory. It creates a feed directory inside of the data directory, and writes and serves RSS files in it. Again, where data belongs depends on the OS and what type of data it is. Persistent state, like our RSS files, is usually stored somewhere in '''/var/'''. On OpenBSD I believe '''/var/db/''' is preferred, while on Linux '''/var/lib/''' seems to be a common choice. I also made a configuration option to set a custom data directory (see above example config).

The code is quite similar to the config handling.

'''
var defaultDataDirs = []string{
	"/var/db/tweed",
	"/var/lib/tweed",
}

func findDataDir() (string, error) {
	for _, d := range defaultDataDirs {
		fi, err := os.Stat(d)
		if errors.Is(err, fs.ErrNotExist) {
			continue
		}
		if err != nil {
			return "", fmt.Errorf("data dir %s: %w", d, err)
		}
		if !fi.IsDir() {
			return "", fmt.Errorf("data dir %s: not a directory", d)
		}
		return d, nil
	}
	return "", fmt.Errorf("no data directory found (looked for %s)",
		strings.Join(defaultDataDirs, ", "))
}
'''

## Protection Against Multiple Instances

I wanted to make sure the program never leaves the data directory in an invalid state, since the RSS feeds are naïvely served directly from the filesystem. My first mitigation was to write each feed to a temporary file, then rename it into its final position. Since a rename within the same filesystem is atomic, anyone reading the feed sees either the complete old file or the complete new one, never a half-written file.

That doesn’t help, however, if a second instance is writing to the same data directory. The two could end up writing to the same temporary file at once, leaving a corrupted feed behind. The flock syscall solves exactly this issue. Calling a non-blocking exclusive flock on a file will fail if another process has already called flock on it, and that process is still running.

'''
if err := syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB); err != nil {
	f.Close()
	if errors.Is(err, syscall.EWOULDBLOCK) {
		return nil, fmt.Errorf("another tweed instance is using data dir %s", dir)
	}
	return nil, fmt.Errorf("data dir %s: locking %s: %w", dir, path, err)
}
'''

We do this check at the start of the program, and exit the program with an error if another instance is using the same data directory.

## Proper Signal Handling

In order for a daemon to be easily managed by a service control utility, like [rcctl](https://man.openbsd.org/rcctl.8) on OpenBSD or systemctl under systemd, it should shut down gracefully on SIGTERM. For tweed, this means letting in-flight HTTP requests finish and leaving all RSS files in a valid state.

For the implementation, SIGINT / SIGTERM cancel '''ctx''', and the goroutine that monitors Twitch channels checks '''ctx''' between making calls and while sleeping. '''main''' blocks until the context is cancelled, gives in-flight requests up to 5 seconds to finish, then waits for the monitor to return.

'''
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()

go func() {
	defer close(monitorDone)
	monitor(ctx, &cfg)
}()

<-ctx.Done()

shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx)
<-monitorDone
'''

Inside the monitor loop the sleep is a select, so a signal cuts it short.

'''
select {
case <-ctx.Done():
	return
case <-time.After(time.Duration(cfg.RefreshMinutes) * time.Minute):
}
'''

I decided against handling SIGHUP (reload), since restarting the program has the same effect, and the startup time is instantaneous. This means that a SIGHUP will terminate the program though, so don't send it SIGHUP expecting a reload.

## Pledge and Unveil

I first encountered OpenBSD's security function [pledge](https://man.openbsd.org/pledge.2) while hacking on my dwm build. I was rewriting the core event loop to use poll, but my changes made the program brutally crash on my OpenBSD laptop. I remember being quite puzzled at the time, but after looking at the stack trace and some man pages I eventually learned all about how pledge (and [unveil](https://man.openbsd.org/unveil.2)) worked.

Pledge lets a program limit itself to named groups of system calls (like '''stdio''' or '''inet'''), making anything it hasn't promised forbidden. Unveil works much the same way, just for the filesystem. Basically, once the program has read its configuration file and is ready to enter its main lifecycle loop, we restrict its capabilities to the bare minimum required for operating. If any of our promises are broken, like accessing a file outside of those unveiled, or making a call to a non-pledged subsystem, the program is immediately killed. This is a simple yet effective security measure to prevent programs from going haywire if something unexpected occurs, or they become compromised.

Calling pledge and unveil from Go is fairly simple with the [sys/unix](https://pkg.go.dev/golang.org/x/sys/unix) package. Since we only want to include these calls when compiling for OpenBSD, we have to use Go's build constraints. We start by creating a file '''sandbox_openbsd.go''', which Go only compiles when targeting OpenBSD (because of its '''_openbsd''' suffix).

'''
package main

import "golang.org/x/sys/unix"

func unveil(path, perms string) error { return unix.Unveil(path, perms) }
func unveilBlock() error { return unix.UnveilBlock() }
func pledge(promises string) error { return unix.PledgePromises(promises) }
'''

Next comes '''sandbox_other.go''', whose '''//go:build !openbsd''' line includes it on every other target. The functions are just defined as stubs in this case.{^I have to say that I find all of this less elegant than a simple '''#ifdef __OpenBSD__''', but I can see the pros of not having macros, even if I prefer having them.}

'''
//go:build !openbsd

package main

func unveil(string, string) error { return nil }
func unveilBlock() error { return nil }
func pledge(string) error { return nil }
'''

With our functions defined for every target, we can call them from our sandbox function.

'''
func sandbox(cfg *Config) error {
	_ = time.Local.String()

	paths := []struct{ path, perms string }{
		{filepath.Join(cfg.DataDir, "feeds"), "rwc"},
		{"/etc/ssl/cert.pem", "r"},
		{"/etc/resolv.conf", "r"},
		{"/etc/hosts", "r"},
		{"/dev/log", "rw"},
	}
	for _, p := range paths {
		if err := unveil(p.path, p.perms); err != nil {
			return fmt.Errorf("unveil %s: %w", p.path, err)
		}
	}
	if err := unveilBlock(); err != nil {
		return fmt.Errorf("unveil block: %w", err)
	}
	if err := pledge("stdio rpath wpath cpath fattr inet dns unix"); err != nil {
		return fmt.Errorf("pledge: %w", err)
	}
	return nil
}
'''

We start by unveiling the paths that we need in order to run, with the needed file permissions. We need to be able to read, write and create files in our feeds directory, read the given files in '''/etc/''' for networking purposes, and read and write to '''/dev/log''' for syslog. Note that since we call '''sandbox''' after reading our configuration files, we don't need to access them anymore. Then, we call '''unveilBlock''', blocking all further attempts to unveil any paths.

Our pledge call includes all of the needed subsystems that we need to access. '''stdio''' for stdio (I know, shocking), '''rpath''', '''wpath''' and '''cpath''' for reading, writing, creating and removing files. '''fattr''' for chmod, '''inet''' and '''dns''' for network stuff, and lastly '''unix''' for syslog's socket. That's a fairly broad set of promises, so here unveil probably does most of the protection.

## To Double Fork or not to Double Fork

Traditionally, Unix daemons do a thing called double forking. They do this to escape the launching shell's session and controlling terminal, and to avoid being a session leader. I won't go into why,{^I would probably explain it worse than any other online resource, since I have literally never done it!} since the advantages of doing it on modern systems are slim to none. It's also my understanding that most modern service managers advise against doing it, since they can / want to handle detaching themselves.

Unsurprisingly, given its heritage, the practice is closely tied to C programming and doesn't easily translate to Go. Go's runtime is multithreaded from startup, so in order to reproduce the same result you would have to re-execute the binary as a detached child, I believe. This is not very pretty, and since double forking in the year of our lord 2026 is dubious to begin with, I decided to not double fork.

## Setting Up the Daemon

The last thing to do is to actually run the thing. I built the program for OpenBSD by
specifying the target OS (and architecture for my server).

'''
GOOS=openbsd GOARCH=amd64 go build -o tweed
'''

Then I copied it to the server with [scp](https://man.openbsd.org/scp.1), and installed it to its final location.

'''
install -o root -g bin -m 755 tweed /usr/local/sbin/tweed
'''

It's good practice to run a daemon, especially a network-facing one, as its own user.

'''
useradd -L daemon -g =uid -d /var/empty -s /sbin/nologin -c "tweed daemon" _tweed
'''

This creates a user with login class '''daemon''', a group of the same name and id, an empty home directory and no login shell.

Next, I create the configuration directory and the config file. The permissions let only root edit the files, while members of the '''_tweed''' group can read them. Other users should not be allowed to read the files, since the config contains secrets.

'''
install -d -o root -g _tweed -m 750 /etc/tweed
install -o root -g _tweed -m 640 config.ini /etc/tweed/
'''

While setting up the daemon I had a realisation that I probably should have had a long time ago: httpd can serve the RSS files. On my old server I had tweed serve them on its own, but that's a whole other thing to set up and have fail. With this realisation I made a configuration option for serving feeds, set the data dir to be in '''/var/www/''', and made httpd serve the files.

'''
appId = ...
appSecret = ...

refreshMinutes = 5
ttlMinutes = 5

serveFeeds = false
dataDir = /var/www/tweed/
...
'''

Finally, I wrote an rcctl service file for the daemon. It sets the daemon user, runs tweed in the background, and disables reload (since we don't handle SIGHUP).

'''
#!/bin/ksh

daemon="/usr/local/sbin/tweed"
daemon_user="_tweed"

. /etc/rc.d/rc.subr

rc_bg=YES
rc_reload=NO

rc_cmd $1
'''

## Takeaways

As always, I greatly underestimated how much work the polishing would take. I fell right into the [ninety-ninety rule](https://en.wikipedia.org/wiki/Ninety%E2%80%93ninety_rule): the first 90% of the code takes the first 90% of the time, and the last 10% takes the other 90%. This sort of made me question whether it was even worth it. After all, the program had been running on my old server for about a year without any problems. I definitely learned a lot about writing daemons through this process though, and hopefully I can take that with me to future projects.
