Obtaining the user's home directory for a daemon application running as root in linux

49 views Asked by At

help me find the optimal solution.

I have a compiled application (written in Go if it matters). The application should run as a daemon in Linux and write logs to the user's home directory. The problem is that the daemon will be launched as root, and the home directory will be that of root.

I tried to add the following line to the postinst script of the deb package:

sed -i "s:%homedir%:${HOME}:g" /lib/systemd/system/mydemon.service

(My application has a CLI parameter that accepts the directory for log writing.)

But if the installation is done with sudo, then we'll get the wrong directory.

I also tried getting the user's home directory in the program itself using os.UserHomeDir(), but it returns the root directory if the application runs under root.

Perhaps there's a way to obtain the home directory based on the session. For example, in Windows, my service also runs under the "SYSTEM" account, but I get the current user's directory through the session (using WinAPI, getting the UserToken, then GetUserProfileDirectory).

Is there something similar that can be done in Linux?

1

There are 1 answers

0
Artem On

I answer my question, if you refine the postinst script, then everything works (it seems)

if [ -n "$SUDO_USER" ]; then
    user_home=$(getent passwd $SUDO_USER | cut -d: -f6)
else
    user_home=$HOME
fi

sed -i "s:%homedir%:$user_home:g" /lib/systemd/system/mydemon.service