5

I have a service that runs as root:

[Unit]
Description=my service
After=docker.service network-online.target
Requires=docker.service network-online.target

[Service]
TimeoutStartSec=0
RestartSec=60
Restart=always
User=root
Group=root

ExecStart=/usr/bin/myservice

[Install]
WantedBy=multi-user.target

I am getting some unexpected behavior with this:

The environment variable $HOME is set to /root when I look at the environment variable that myservice is getting which is causing it to fail.

However, as the root user I am getting:

$ echo $HOME
/home/root

This is in line with what I see in /etc/passwd

root:x:0:0:root:/home/root:/bin/sh

When I run myservice manually, it gets the correct $HOME env variable and it works.

I would like $HOME to be /home/root, not /root. So...

  1. Where is systemd getting /root from, and why is $HOME getting overwritten?
  2. How do I prevent systemd from doing this globally, aside from explicitly setting the $HOME environment variable in the service file? <-- upon reviewing the source code this doesn't seem like it'll make a difference
2
  • 2
    What Unix are you on where the root home directory is placed under /home?
    – Kusalananda
    Commented Mar 21, 2023 at 21:46
  • 1
    Yocto, which by default places root's home directory under /home. We can change this or even symlink /root to /home/root but I am still curious about how systemd handles cases where root has a non standard home directory
    – Alex
    Commented Mar 21, 2023 at 21:54

1 Answer 1

5

After examining the source code, I found out systemd actually hardcodes the home directory for root users. I have not found any documentation on configs that can change this so it's just something to be aware of for Yocto projects using the default home directory.

I confirmed this by modifying the hard coded /root values to /home/root in https://github.com/systemd/systemd/blob/main/src/basic/user-util.c and observed the modified systemd was spawning services with the correct $HOME variable.

As of now, symlinking /root with /home/root is a good workaround. Switching the default ROOT_HOME to /root may not be a bad idea to be consistent with the rest of the linux world.

2
  • They also appear to have a reason for it stated in the source code comments: "/* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode their user record data. */" That seems to make some sense, esp. considering that some services might need to be up for the NSS lookups to work, etc...
    – ilkkachu
    Commented Mar 22, 2023 at 18:41
  • Kudos for the fault finding - and for sharing the outcome here. You should be posting a bug to YoctoProject.
    – symcbean
    Commented Mar 23, 2023 at 0:34

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .