Tor always overwrites onion service hostname file, but should leave it alone if it shouldn't change
If you start your Tor with an onion service, it will make the appropriate files in your onion service directory, e.g.
$ ls -la hidden_service
total 32
drwx------ 3 arma arma 4096 Jul 24 05:14 .
drwxrwxrwt 21 root root 12288 Jul 24 05:11 ..
drwx------ 2 arma arma 4096 Jul 24 05:11 authorized_clients
-rw------- 1 arma arma 63 Jul 24 05:14 hostname
-rw------- 1 arma arma 64 Jul 16 00:11 hs_ed25519_public_key
-rw------- 1 arma arma 96 Jul 16 00:11 hs_ed25519_secret_key
but if you then set the directory to read-only, Tor will fail to start, complaining
Jul 24 05:16:38.104 [warn] Couldn't open "/tmp/hidden_service//hostname.tmp" (/tmp/hidden_service//hostname) for writing: Permission denied
Jul 24 05:16:38.104 [warn] Could not write onion address to hostname file "/tmp/hidden_service//hostname"
Jul 24 05:16:38.104 [warn] Error loading rendezvous service keys
Jul 24 05:16:38.104 [err] set_options(): Bug: Acting on config options left us in a broken state. Dying. (on Tor 0.4.5.0-alpha-dev 5336ac26693cdba4)
Back in the day, I added some logic where it would first read the hostname file, and decide if it already has the correct content in it, and if it does, it would leave it alone (i.e. not try to write). It looks like either I misremembered doing that, or we lost that feature somewhere along the way.
If we resume doing that behavior, then people can set their onion service keys directory to be read-only, which will let them improve their opsec.
Bug reported by Jeff Moss on his Defcon onion.